1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
134 /// removeFromWorkList - remove all instances of N from the worklist.
136 void removeFromWorkList(SDNode *N) {
137 WorkListContents.erase(N);
140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144 return CombineTo(N, &Res, 1, AddTo);
147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
149 SDValue To[] = { Res0, Res1 };
150 return CombineTo(N, To, 2, AddTo);
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
157 /// SimplifyDemandedBits - Check the specified integer node value to see if
158 /// it can be simplified or if things it uses can be simplified by bit
159 /// propagation. If so, return true.
160 bool SimplifyDemandedBits(SDValue Op) {
161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
163 return SimplifyDemandedBits(Op, Demanded);
166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
170 bool SliceUpLoad(SDNode *N);
172 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
175 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
176 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
177 /// \param EltNo index of the vector element to load.
178 /// \param OriginalLoad load that EVE came from to be replaced.
179 /// \returns EVE on success SDValue() on failure.
180 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
181 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
186 SDValue PromoteIntBinOp(SDValue Op);
187 SDValue PromoteIntShiftOp(SDValue Op);
188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
193 ISD::NodeType ExtType);
195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
198 SDValue combine(SDNode *N);
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
212 SDValue visitSUBC(SDNode *N);
213 SDValue visitADDE(SDNode *N);
214 SDValue visitSUBE(SDNode *N);
215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
232 SDValue SimplifyVUnaryOp(SDNode *N);
233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
236 SDValue visitRotate(SDNode *N);
237 SDValue visitCTLZ(SDNode *N);
238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
239 SDValue visitCTTZ(SDNode *N);
240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
243 SDValue visitVSELECT(SDNode *N);
244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
251 SDValue visitBITCAST(SDNode *N);
252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
256 SDValue visitFMA(SDNode *N);
257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
284 SDValue XformToShuffleWithZero(SDNode *N);
285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
293 SDValue N3, ISD::CondCode CC,
294 bool NotExtCompare = false);
295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
296 SDLoc DL, bool foldBooleans = true);
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
300 bool isOneUseSetCC(SDValue N) const;
302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
306 SDValue BuildSDIV(SDNode *N);
307 SDValue BuildUDIV(SDNode *N);
308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309 bool DemandHighBits = true);
310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312 SDValue InnerPos, SDValue InnerNeg,
313 unsigned PosOpcode, unsigned NegOpcode,
315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
316 SDValue ReduceLoadWidth(SDNode *N);
317 SDValue ReduceLoadOpStoreWidth(SDNode *N);
318 SDValue TransformFPLoadStorePair(SDNode *N);
319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
322 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for aliasing nodes and adding them to the Aliases vector.
326 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
327 SmallVectorImpl<SDValue> &Aliases);
329 /// isAlias - Return true if there is any possibility that the two addresses
331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
334 /// looking for a better chain (aliasing node.)
335 SDValue FindBetterChain(SDNode *N, SDValue Chain);
337 /// Merge consecutive store operations into a wide store.
338 /// This optimization uses wide integers or vectors when possible.
339 /// \return True if some memory operations were changed.
340 bool MergeConsecutiveStores(StoreSDNode *N);
342 /// \brief Try to transform a truncation where C is a constant:
343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
345 /// \p N needs to be a truncation and its first operand an AND. Other
346 /// requirements are checked by the function (e.g. that trunc is
347 /// single-use) and if missed an empty SDValue is returned.
348 SDValue distributeTruncateThroughAnd(SDNode *N);
351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
362 /// Run - runs the dag combiner on all nodes in the work list
363 void Run(CombineLevel AtLevel);
365 SelectionDAG &getDAG() const { return DAG; }
367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
369 EVT getShiftAmountTy(EVT LHSTy) {
370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395 /// nodes from the worklist.
396 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
399 explicit WorkListRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
402 void NodeDeleted(SDNode *N, SDNode *E) override {
403 DC.removeFromWorkList(N);
408 //===----------------------------------------------------------------------===//
409 // TargetLowering::DAGCombinerInfo implementation
410 //===----------------------------------------------------------------------===//
412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorkList(N);
416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorkList(N);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
425 SDValue TargetLowering::DAGCombinerInfo::
426 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
431 SDValue TargetLowering::DAGCombinerInfo::
432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
436 void TargetLowering::DAGCombinerInfo::
437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
446 /// specified expression for the same cost as the expression itself, or 2 if we
447 /// can compute the negated form more cheaply than the expression itself.
448 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
449 const TargetLowering &TLI,
450 const TargetOptions *Options,
451 unsigned Depth = 0) {
452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
466 return LegalOperations ? 0 : 1;
468 // FIXME: determine better conditions for this xform.
469 if (!Options->UnsafeFPMath) return 0;
471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 // We can't turn -(A-B) into B-A when we honor signed zeros.
485 if (!Options->UnsafeFPMath) return 0;
487 // fold (fneg (fsub A, B)) -> (fsub B, A)
492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
511 /// returns the newly negated expression.
512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
513 bool LegalOperations, unsigned Depth = 0) {
514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
521 switch (Op.getOpcode()) {
522 default: llvm_unreachable("Unknown code");
523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 return DAG.getConstantFP(V, Op.getValueType());
529 // FIXME: determine better conditions for this xform.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
534 DAG.getTargetLoweringInfo(),
535 &DAG.getTarget().Options, Depth+1))
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(0), DAG,
538 LegalOperations, Depth+1),
540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
542 GetNegatedExpression(Op.getOperand(1), DAG,
543 LegalOperations, Depth+1),
546 // We can't turn -(A-B) into B-A when we honor signed zeros.
547 assert(DAG.getTarget().Options.UnsafeFPMath);
549 // fold (fneg (fsub 0, B)) -> B
550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
551 if (N0CFP->getValueAPF().isZero())
552 return Op.getOperand(1);
554 // fold (fneg (fsub A, B)) -> (fsub B, A)
555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556 Op.getOperand(1), Op.getOperand(0));
560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
564 DAG.getTargetLoweringInfo(),
565 &DAG.getTarget().Options, Depth+1))
566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1));
579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
580 GetNegatedExpression(Op.getOperand(0), DAG,
581 LegalOperations, Depth+1));
583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(0), DAG,
585 LegalOperations, Depth+1),
590 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
591 // that selects between the target values used for true and false, making it
592 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593 // the appropriate nodes based on the type of node we are checking. This
594 // simplifies life a bit for the callers.
595 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
597 if (N.getOpcode() == ISD::SETCC) {
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(2);
604 if (N.getOpcode() != ISD::SELECT_CC ||
605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
615 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616 // one use. If this is true, it allows the users to invert the operation for
617 // free when it is profitable to do so.
618 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
625 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626 /// elements are all the same constant or undefined.
627 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
633 unsigned SplatBitSize;
635 EVT EltVT = N->getValueType(0).getVectorElementType();
636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
638 EltVT.getSizeInBits() >= SplatBitSize);
641 // \brief Returns the SDNode if it is a constant BuildVector or constant.
642 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643 if (isa<ConstantSDNode>(N))
645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646 if(BV && BV->isConstant())
651 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
653 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
658 BitVector UndefElements;
659 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
661 // BuildVectors can truncate their operands. Ignore that case here.
662 // FIXME: We blindly ignore splats which include undef which is overly
664 if (CN && UndefElements.none() &&
665 CN->getValueType(0) == N.getValueType().getScalarType())
672 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
673 SDValue N0, SDValue N1) {
674 EVT VT = N0.getValueType();
675 if (N0.getOpcode() == Opc) {
676 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
677 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
678 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
679 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
680 if (!OpNode.getNode())
682 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
684 if (N0.hasOneUse()) {
685 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
687 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
688 if (!OpNode.getNode())
690 AddToWorkList(OpNode.getNode());
691 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
696 if (N1.getOpcode() == Opc) {
697 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
698 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
699 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
700 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
701 if (!OpNode.getNode())
703 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
705 if (N1.hasOneUse()) {
706 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
708 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
709 if (!OpNode.getNode())
711 AddToWorkList(OpNode.getNode());
712 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
720 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
722 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
724 DEBUG(dbgs() << "\nReplacing.1 ";
726 dbgs() << "\nWith: ";
727 To[0].getNode()->dump(&DAG);
728 dbgs() << " and " << NumTo-1 << " other values\n";
729 for (unsigned i = 0, e = NumTo; i != e; ++i)
730 assert((!To[i].getNode() ||
731 N->getValueType(i) == To[i].getValueType()) &&
732 "Cannot combine value to value of different type!"));
733 WorkListRemover DeadNodes(*this);
734 DAG.ReplaceAllUsesWith(N, To);
736 // Push the new nodes and any users onto the worklist
737 for (unsigned i = 0, e = NumTo; i != e; ++i) {
738 if (To[i].getNode()) {
739 AddToWorkList(To[i].getNode());
740 AddUsersToWorkList(To[i].getNode());
745 // Finally, if the node is now dead, remove it from the graph. The node
746 // may not be dead if the replacement process recursively simplified to
747 // something else needing this node.
748 if (N->use_empty()) {
749 // Nodes can be reintroduced into the worklist. Make sure we do not
750 // process a node that has been replaced.
751 removeFromWorkList(N);
753 // Finally, since the node is now dead, remove it from the graph.
756 return SDValue(N, 0);
760 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
761 // Replace all uses. If any nodes become isomorphic to other nodes and
762 // are deleted, make sure to remove them from our worklist.
763 WorkListRemover DeadNodes(*this);
764 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
766 // Push the new node and any (possibly new) users onto the worklist.
767 AddToWorkList(TLO.New.getNode());
768 AddUsersToWorkList(TLO.New.getNode());
770 // Finally, if the node is now dead, remove it from the graph. The node
771 // may not be dead if the replacement process recursively simplified to
772 // something else needing this node.
773 if (TLO.Old.getNode()->use_empty()) {
774 removeFromWorkList(TLO.Old.getNode());
776 // If the operands of this node are only used by the node, they will now
777 // be dead. Make sure to visit them first to delete dead nodes early.
778 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
779 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
780 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
782 DAG.DeleteNode(TLO.Old.getNode());
786 /// SimplifyDemandedBits - Check the specified integer node value to see if
787 /// it can be simplified or if things it uses can be simplified by bit
788 /// propagation. If so, return true.
789 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
790 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
791 APInt KnownZero, KnownOne;
792 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
796 AddToWorkList(Op.getNode());
798 // Replace the old value with the new one.
800 DEBUG(dbgs() << "\nReplacing.2 ";
801 TLO.Old.getNode()->dump(&DAG);
802 dbgs() << "\nWith: ";
803 TLO.New.getNode()->dump(&DAG);
806 CommitTargetLoweringOpt(TLO);
810 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
812 EVT VT = Load->getValueType(0);
813 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
815 DEBUG(dbgs() << "\nReplacing.9 ";
817 dbgs() << "\nWith: ";
818 Trunc.getNode()->dump(&DAG);
820 WorkListRemover DeadNodes(*this);
821 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
822 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
823 removeFromWorkList(Load);
824 DAG.DeleteNode(Load);
825 AddToWorkList(Trunc.getNode());
828 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
832 EVT MemVT = LD->getMemoryVT();
833 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
834 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
836 : LD->getExtensionType();
838 return DAG.getExtLoad(ExtType, dl, PVT,
839 LD->getChain(), LD->getBasePtr(),
840 MemVT, LD->getMemOperand());
843 unsigned Opc = Op.getOpcode();
846 case ISD::AssertSext:
847 return DAG.getNode(ISD::AssertSext, dl, PVT,
848 SExtPromoteOperand(Op.getOperand(0), PVT),
850 case ISD::AssertZext:
851 return DAG.getNode(ISD::AssertZext, dl, PVT,
852 ZExtPromoteOperand(Op.getOperand(0), PVT),
854 case ISD::Constant: {
856 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
857 return DAG.getNode(ExtOpc, dl, PVT, Op);
861 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
863 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
866 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
867 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
869 EVT OldVT = Op.getValueType();
871 bool Replace = false;
872 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
873 if (!NewOp.getNode())
875 AddToWorkList(NewOp.getNode());
878 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
880 DAG.getValueType(OldVT));
883 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
884 EVT OldVT = Op.getValueType();
886 bool Replace = false;
887 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
888 if (!NewOp.getNode())
890 AddToWorkList(NewOp.getNode());
893 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
894 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
897 /// PromoteIntBinOp - Promote the specified integer binary operation if the
898 /// target indicates it is beneficial. e.g. On x86, it's usually better to
899 /// promote i16 operations to i32 since i16 instructions are longer.
900 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
901 if (!LegalOperations)
904 EVT VT = Op.getValueType();
905 if (VT.isVector() || !VT.isInteger())
908 // If operation type is 'undesirable', e.g. i16 on x86, consider
910 unsigned Opc = Op.getOpcode();
911 if (TLI.isTypeDesirableForOp(Opc, VT))
915 // Consult target whether it is a good idea to promote this operation and
916 // what's the right type to promote it to.
917 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
918 assert(PVT != VT && "Don't know what type to promote to!");
920 bool Replace0 = false;
921 SDValue N0 = Op.getOperand(0);
922 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926 bool Replace1 = false;
927 SDValue N1 = Op.getOperand(1);
932 NN1 = PromoteOperand(N1, PVT, Replace1);
937 AddToWorkList(NN0.getNode());
939 AddToWorkList(NN1.getNode());
942 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
944 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
946 DEBUG(dbgs() << "\nPromoting ";
947 Op.getNode()->dump(&DAG));
949 return DAG.getNode(ISD::TRUNCATE, dl, VT,
950 DAG.getNode(Opc, dl, PVT, NN0, NN1));
955 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
956 /// target indicates it is beneficial. e.g. On x86, it's usually better to
957 /// promote i16 operations to i32 since i16 instructions are longer.
958 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
959 if (!LegalOperations)
962 EVT VT = Op.getValueType();
963 if (VT.isVector() || !VT.isInteger())
966 // If operation type is 'undesirable', e.g. i16 on x86, consider
968 unsigned Opc = Op.getOpcode();
969 if (TLI.isTypeDesirableForOp(Opc, VT))
973 // Consult target whether it is a good idea to promote this operation and
974 // what's the right type to promote it to.
975 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
976 assert(PVT != VT && "Don't know what type to promote to!");
978 bool Replace = false;
979 SDValue N0 = Op.getOperand(0);
981 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
982 else if (Opc == ISD::SRL)
983 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
985 N0 = PromoteOperand(N0, PVT, Replace);
989 AddToWorkList(N0.getNode());
991 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
993 DEBUG(dbgs() << "\nPromoting ";
994 Op.getNode()->dump(&DAG));
996 return DAG.getNode(ISD::TRUNCATE, dl, VT,
997 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1002 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1003 if (!LegalOperations)
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector() || !VT.isInteger())
1010 // If operation type is 'undesirable', e.g. i16 on x86, consider
1012 unsigned Opc = Op.getOpcode();
1013 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 // Consult target whether it is a good idea to promote this operation and
1018 // what's the right type to promote it to.
1019 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020 assert(PVT != VT && "Don't know what type to promote to!");
1021 // fold (aext (aext x)) -> (aext x)
1022 // fold (aext (zext x)) -> (zext x)
1023 // fold (aext (sext x)) -> (sext x)
1024 DEBUG(dbgs() << "\nPromoting ";
1025 Op.getNode()->dump(&DAG));
1026 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1031 bool DAGCombiner::PromoteLoad(SDValue Op) {
1032 if (!LegalOperations)
1035 EVT VT = Op.getValueType();
1036 if (VT.isVector() || !VT.isInteger())
1039 // If operation type is 'undesirable', e.g. i16 on x86, consider
1041 unsigned Opc = Op.getOpcode();
1042 if (TLI.isTypeDesirableForOp(Opc, VT))
1046 // Consult target whether it is a good idea to promote this operation and
1047 // what's the right type to promote it to.
1048 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1049 assert(PVT != VT && "Don't know what type to promote to!");
1052 SDNode *N = Op.getNode();
1053 LoadSDNode *LD = cast<LoadSDNode>(N);
1054 EVT MemVT = LD->getMemoryVT();
1055 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1056 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1058 : LD->getExtensionType();
1059 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1060 LD->getChain(), LD->getBasePtr(),
1061 MemVT, LD->getMemOperand());
1062 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1064 DEBUG(dbgs() << "\nPromoting ";
1067 Result.getNode()->dump(&DAG);
1069 WorkListRemover DeadNodes(*this);
1070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1072 removeFromWorkList(N);
1074 AddToWorkList(Result.getNode());
1081 //===----------------------------------------------------------------------===//
1082 // Main DAG Combiner implementation
1083 //===----------------------------------------------------------------------===//
1085 void DAGCombiner::Run(CombineLevel AtLevel) {
1086 // set the instance variables, so that the various visit routines may use it.
1088 LegalOperations = Level >= AfterLegalizeVectorOps;
1089 LegalTypes = Level >= AfterLegalizeTypes;
1091 // Add all the dag nodes to the worklist.
1092 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1093 E = DAG.allnodes_end(); I != E; ++I)
1096 // Create a dummy node (which is not added to allnodes), that adds a reference
1097 // to the root node, preventing it from being deleted, and tracking any
1098 // changes of the root.
1099 HandleSDNode Dummy(DAG.getRoot());
1101 // The root of the dag may dangle to deleted nodes until the dag combiner is
1102 // done. Set it to null to avoid confusion.
1103 DAG.setRoot(SDValue());
1105 // while the worklist isn't empty, find a node and
1106 // try and combine it.
1107 while (!WorkListContents.empty()) {
1109 // The WorkListOrder holds the SDNodes in order, but it may contain
1111 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1112 // worklist *should* contain, and check the node we want to visit is should
1113 // actually be visited.
1115 N = WorkListOrder.pop_back_val();
1116 } while (!WorkListContents.erase(N));
1118 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1119 // N is deleted from the DAG, since they too may now be dead or may have a
1120 // reduced number of uses, allowing other xforms.
1121 if (N->use_empty() && N != &Dummy) {
1122 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1123 AddToWorkList(N->getOperand(i).getNode());
1129 SDValue RV = combine(N);
1136 // If we get back the same node we passed in, rather than a new node or
1137 // zero, we know that the node must have defined multiple values and
1138 // CombineTo was used. Since CombineTo takes care of the worklist
1139 // mechanics for us, we have no work to do in this case.
1140 if (RV.getNode() == N)
1143 assert(N->getOpcode() != ISD::DELETED_NODE &&
1144 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1145 "Node was deleted but visit returned new node!");
1147 DEBUG(dbgs() << "\nReplacing.3 ";
1149 dbgs() << "\nWith: ";
1150 RV.getNode()->dump(&DAG);
1153 // Transfer debug value.
1154 DAG.TransferDbgValues(SDValue(N, 0), RV);
1155 WorkListRemover DeadNodes(*this);
1156 if (N->getNumValues() == RV.getNode()->getNumValues())
1157 DAG.ReplaceAllUsesWith(N, RV.getNode());
1159 assert(N->getValueType(0) == RV.getValueType() &&
1160 N->getNumValues() == 1 && "Type mismatch");
1162 DAG.ReplaceAllUsesWith(N, &OpV);
1165 // Push the new node and any users onto the worklist
1166 AddToWorkList(RV.getNode());
1167 AddUsersToWorkList(RV.getNode());
1169 // Add any uses of the old node to the worklist in case this node is the
1170 // last one that uses them. They may become dead after this node is
1172 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1173 AddToWorkList(N->getOperand(i).getNode());
1175 // Finally, if the node is now dead, remove it from the graph. The node
1176 // may not be dead if the replacement process recursively simplified to
1177 // something else needing this node.
1178 if (N->use_empty()) {
1179 // Nodes can be reintroduced into the worklist. Make sure we do not
1180 // process a node that has been replaced.
1181 removeFromWorkList(N);
1183 // Finally, since the node is now dead, remove it from the graph.
1188 // If the root changed (e.g. it was a dead load, update the root).
1189 DAG.setRoot(Dummy.getValue());
1190 DAG.RemoveDeadNodes();
1193 SDValue DAGCombiner::visit(SDNode *N) {
1194 switch (N->getOpcode()) {
1196 case ISD::TokenFactor: return visitTokenFactor(N);
1197 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1198 case ISD::ADD: return visitADD(N);
1199 case ISD::SUB: return visitSUB(N);
1200 case ISD::ADDC: return visitADDC(N);
1201 case ISD::SUBC: return visitSUBC(N);
1202 case ISD::ADDE: return visitADDE(N);
1203 case ISD::SUBE: return visitSUBE(N);
1204 case ISD::MUL: return visitMUL(N);
1205 case ISD::SDIV: return visitSDIV(N);
1206 case ISD::UDIV: return visitUDIV(N);
1207 case ISD::SREM: return visitSREM(N);
1208 case ISD::UREM: return visitUREM(N);
1209 case ISD::MULHU: return visitMULHU(N);
1210 case ISD::MULHS: return visitMULHS(N);
1211 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1212 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1213 case ISD::SMULO: return visitSMULO(N);
1214 case ISD::UMULO: return visitUMULO(N);
1215 case ISD::SDIVREM: return visitSDIVREM(N);
1216 case ISD::UDIVREM: return visitUDIVREM(N);
1217 case ISD::AND: return visitAND(N);
1218 case ISD::OR: return visitOR(N);
1219 case ISD::XOR: return visitXOR(N);
1220 case ISD::SHL: return visitSHL(N);
1221 case ISD::SRA: return visitSRA(N);
1222 case ISD::SRL: return visitSRL(N);
1224 case ISD::ROTL: return visitRotate(N);
1225 case ISD::CTLZ: return visitCTLZ(N);
1226 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1227 case ISD::CTTZ: return visitCTTZ(N);
1228 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1229 case ISD::CTPOP: return visitCTPOP(N);
1230 case ISD::SELECT: return visitSELECT(N);
1231 case ISD::VSELECT: return visitVSELECT(N);
1232 case ISD::SELECT_CC: return visitSELECT_CC(N);
1233 case ISD::SETCC: return visitSETCC(N);
1234 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1235 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1236 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1237 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1238 case ISD::TRUNCATE: return visitTRUNCATE(N);
1239 case ISD::BITCAST: return visitBITCAST(N);
1240 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1241 case ISD::FADD: return visitFADD(N);
1242 case ISD::FSUB: return visitFSUB(N);
1243 case ISD::FMUL: return visitFMUL(N);
1244 case ISD::FMA: return visitFMA(N);
1245 case ISD::FDIV: return visitFDIV(N);
1246 case ISD::FREM: return visitFREM(N);
1247 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1248 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1249 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1250 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1251 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1252 case ISD::FP_ROUND: return visitFP_ROUND(N);
1253 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1254 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1255 case ISD::FNEG: return visitFNEG(N);
1256 case ISD::FABS: return visitFABS(N);
1257 case ISD::FFLOOR: return visitFFLOOR(N);
1258 case ISD::FCEIL: return visitFCEIL(N);
1259 case ISD::FTRUNC: return visitFTRUNC(N);
1260 case ISD::BRCOND: return visitBRCOND(N);
1261 case ISD::BR_CC: return visitBR_CC(N);
1262 case ISD::LOAD: return visitLOAD(N);
1263 case ISD::STORE: return visitSTORE(N);
1264 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1265 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1266 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1267 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1268 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1269 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1270 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1275 SDValue DAGCombiner::combine(SDNode *N) {
1276 SDValue RV = visit(N);
1278 // If nothing happened, try a target-specific DAG combine.
1279 if (!RV.getNode()) {
1280 assert(N->getOpcode() != ISD::DELETED_NODE &&
1281 "Node was deleted but visit returned NULL!");
1283 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1284 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1286 // Expose the DAG combiner to the target combiner impls.
1287 TargetLowering::DAGCombinerInfo
1288 DagCombineInfo(DAG, Level, false, this);
1290 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1294 // If nothing happened still, try promoting the operation.
1295 if (!RV.getNode()) {
1296 switch (N->getOpcode()) {
1304 RV = PromoteIntBinOp(SDValue(N, 0));
1309 RV = PromoteIntShiftOp(SDValue(N, 0));
1311 case ISD::SIGN_EXTEND:
1312 case ISD::ZERO_EXTEND:
1313 case ISD::ANY_EXTEND:
1314 RV = PromoteExtend(SDValue(N, 0));
1317 if (PromoteLoad(SDValue(N, 0)))
1323 // If N is a commutative binary node, try commuting it to enable more
1325 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1326 N->getNumValues() == 1) {
1327 SDValue N0 = N->getOperand(0);
1328 SDValue N1 = N->getOperand(1);
1330 // Constant operands are canonicalized to RHS.
1331 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1332 SDValue Ops[] = {N1, N0};
1334 if (const BinaryWithFlagsSDNode *BinNode =
1335 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1336 CSENode = DAG.getNodeIfExists(
1337 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1338 BinNode->hasNoSignedWrap(), BinNode->isExact());
1340 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1343 return SDValue(CSENode, 0);
1350 /// getInputChainForNode - Given a node, return its input chain if it has one,
1351 /// otherwise return a null sd operand.
1352 static SDValue getInputChainForNode(SDNode *N) {
1353 if (unsigned NumOps = N->getNumOperands()) {
1354 if (N->getOperand(0).getValueType() == MVT::Other)
1355 return N->getOperand(0);
1356 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1357 return N->getOperand(NumOps-1);
1358 for (unsigned i = 1; i < NumOps-1; ++i)
1359 if (N->getOperand(i).getValueType() == MVT::Other)
1360 return N->getOperand(i);
1365 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1366 // If N has two operands, where one has an input chain equal to the other,
1367 // the 'other' chain is redundant.
1368 if (N->getNumOperands() == 2) {
1369 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1370 return N->getOperand(0);
1371 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1372 return N->getOperand(1);
1375 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1376 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1377 SmallPtrSet<SDNode*, 16> SeenOps;
1378 bool Changed = false; // If we should replace this token factor.
1380 // Start out with this token factor.
1383 // Iterate through token factors. The TFs grows when new token factors are
1385 for (unsigned i = 0; i < TFs.size(); ++i) {
1386 SDNode *TF = TFs[i];
1388 // Check each of the operands.
1389 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1390 SDValue Op = TF->getOperand(i);
1392 switch (Op.getOpcode()) {
1393 case ISD::EntryToken:
1394 // Entry tokens don't need to be added to the list. They are
1399 case ISD::TokenFactor:
1400 if (Op.hasOneUse() &&
1401 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1402 // Queue up for processing.
1403 TFs.push_back(Op.getNode());
1404 // Clean up in case the token factor is removed.
1405 AddToWorkList(Op.getNode());
1412 // Only add if it isn't already in the list.
1413 if (SeenOps.insert(Op.getNode()))
1424 // If we've change things around then replace token factor.
1427 // The entry token is the only possible outcome.
1428 Result = DAG.getEntryNode();
1430 // New and improved token factor.
1431 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1434 // Don't add users to work list.
1435 return CombineTo(N, Result, false);
1441 /// MERGE_VALUES can always be eliminated.
1442 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1443 WorkListRemover DeadNodes(*this);
1444 // Replacing results may cause a different MERGE_VALUES to suddenly
1445 // be CSE'd with N, and carry its uses with it. Iterate until no
1446 // uses remain, to ensure that the node can be safely deleted.
1447 // First add the users of this node to the work list so that they
1448 // can be tried again once they have new operands.
1449 AddUsersToWorkList(N);
1451 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1453 } while (!N->use_empty());
1454 removeFromWorkList(N);
1456 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1460 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1461 SelectionDAG &DAG) {
1462 EVT VT = N0.getValueType();
1463 SDValue N00 = N0.getOperand(0);
1464 SDValue N01 = N0.getOperand(1);
1465 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1467 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1468 isa<ConstantSDNode>(N00.getOperand(1))) {
1469 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1470 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1471 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1472 N00.getOperand(0), N01),
1473 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1474 N00.getOperand(1), N01));
1475 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1481 SDValue DAGCombiner::visitADD(SDNode *N) {
1482 SDValue N0 = N->getOperand(0);
1483 SDValue N1 = N->getOperand(1);
1484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486 EVT VT = N0.getValueType();
1489 if (VT.isVector()) {
1490 SDValue FoldedVOp = SimplifyVBinOp(N);
1491 if (FoldedVOp.getNode()) return FoldedVOp;
1493 // fold (add x, 0) -> x, vector edition
1494 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1496 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1500 // fold (add x, undef) -> undef
1501 if (N0.getOpcode() == ISD::UNDEF)
1503 if (N1.getOpcode() == ISD::UNDEF)
1505 // fold (add c1, c2) -> c1+c2
1507 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1508 // canonicalize constant to RHS
1510 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1511 // fold (add x, 0) -> x
1512 if (N1C && N1C->isNullValue())
1514 // fold (add Sym, c) -> Sym+c
1515 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1516 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1517 GA->getOpcode() == ISD::GlobalAddress)
1518 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1520 (uint64_t)N1C->getSExtValue());
1521 // fold ((c1-A)+c2) -> (c1+c2)-A
1522 if (N1C && N0.getOpcode() == ISD::SUB)
1523 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1524 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1525 DAG.getConstant(N1C->getAPIntValue()+
1526 N0C->getAPIntValue(), VT),
1529 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1532 // fold ((0-A) + B) -> B-A
1533 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1534 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1536 // fold (A + (0-B)) -> A-B
1537 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1538 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1539 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1540 // fold (A+(B-A)) -> B
1541 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1542 return N1.getOperand(0);
1543 // fold ((B-A)+A) -> B
1544 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1545 return N0.getOperand(0);
1546 // fold (A+(B-(A+C))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548 N0 == N1.getOperand(1).getOperand(0))
1549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550 N1.getOperand(1).getOperand(1));
1551 // fold (A+(B-(C+A))) to (B-C)
1552 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1553 N0 == N1.getOperand(1).getOperand(1))
1554 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1555 N1.getOperand(1).getOperand(0));
1556 // fold (A+((B-A)+or-C)) to (B+or-C)
1557 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1558 N1.getOperand(0).getOpcode() == ISD::SUB &&
1559 N0 == N1.getOperand(0).getOperand(1))
1560 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1561 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1563 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1564 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1565 SDValue N00 = N0.getOperand(0);
1566 SDValue N01 = N0.getOperand(1);
1567 SDValue N10 = N1.getOperand(0);
1568 SDValue N11 = N1.getOperand(1);
1570 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1571 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1572 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1573 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1576 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1577 return SDValue(N, 0);
1579 // fold (a+b) -> (a|b) iff a and b share no bits.
1580 if (VT.isInteger() && !VT.isVector()) {
1581 APInt LHSZero, LHSOne;
1582 APInt RHSZero, RHSOne;
1583 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1585 if (LHSZero.getBoolValue()) {
1586 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1588 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1589 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1590 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1591 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1592 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1597 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1598 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1599 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1600 if (Result.getNode()) return Result;
1602 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1603 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1604 if (Result.getNode()) return Result;
1607 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1608 if (N1.getOpcode() == ISD::SHL &&
1609 N1.getOperand(0).getOpcode() == ISD::SUB)
1610 if (ConstantSDNode *C =
1611 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1612 if (C->getAPIntValue() == 0)
1613 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1614 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1615 N1.getOperand(0).getOperand(1),
1617 if (N0.getOpcode() == ISD::SHL &&
1618 N0.getOperand(0).getOpcode() == ISD::SUB)
1619 if (ConstantSDNode *C =
1620 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1621 if (C->getAPIntValue() == 0)
1622 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1623 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1624 N0.getOperand(0).getOperand(1),
1627 if (N1.getOpcode() == ISD::AND) {
1628 SDValue AndOp0 = N1.getOperand(0);
1629 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1630 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1631 unsigned DestBits = VT.getScalarType().getSizeInBits();
1633 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1634 // and similar xforms where the inner op is either ~0 or 0.
1635 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1637 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1641 // add (sext i1), X -> sub X, (zext i1)
1642 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1643 N0.getOperand(0).getValueType() == MVT::i1 &&
1644 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1646 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1647 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1653 SDValue DAGCombiner::visitADDC(SDNode *N) {
1654 SDValue N0 = N->getOperand(0);
1655 SDValue N1 = N->getOperand(1);
1656 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1657 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1658 EVT VT = N0.getValueType();
1660 // If the flag result is dead, turn this into an ADD.
1661 if (!N->hasAnyUseOfValue(1))
1662 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1663 DAG.getNode(ISD::CARRY_FALSE,
1664 SDLoc(N), MVT::Glue));
1666 // canonicalize constant to RHS.
1668 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1670 // fold (addc x, 0) -> x + no carry out
1671 if (N1C && N1C->isNullValue())
1672 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1673 SDLoc(N), MVT::Glue));
1675 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1676 APInt LHSZero, LHSOne;
1677 APInt RHSZero, RHSOne;
1678 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1680 if (LHSZero.getBoolValue()) {
1681 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1683 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1684 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1685 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1686 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1687 DAG.getNode(ISD::CARRY_FALSE,
1688 SDLoc(N), MVT::Glue));
1694 SDValue DAGCombiner::visitADDE(SDNode *N) {
1695 SDValue N0 = N->getOperand(0);
1696 SDValue N1 = N->getOperand(1);
1697 SDValue CarryIn = N->getOperand(2);
1698 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1701 // canonicalize constant to RHS
1703 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1706 // fold (adde x, y, false) -> (addc x, y)
1707 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1708 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1713 // Since it may not be valid to emit a fold to zero for vector initializers
1714 // check if we can before folding.
1715 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1717 bool LegalOperations, bool LegalTypes) {
1719 return DAG.getConstant(0, VT);
1720 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1721 return DAG.getConstant(0, VT);
1725 SDValue DAGCombiner::visitSUB(SDNode *N) {
1726 SDValue N0 = N->getOperand(0);
1727 SDValue N1 = N->getOperand(1);
1728 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1729 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1730 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1731 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1732 EVT VT = N0.getValueType();
1735 if (VT.isVector()) {
1736 SDValue FoldedVOp = SimplifyVBinOp(N);
1737 if (FoldedVOp.getNode()) return FoldedVOp;
1739 // fold (sub x, 0) -> x, vector edition
1740 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1744 // fold (sub x, x) -> 0
1745 // FIXME: Refactor this and xor and other similar operations together.
1747 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1748 // fold (sub c1, c2) -> c1-c2
1750 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1751 // fold (sub x, c) -> (add x, -c)
1753 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1754 DAG.getConstant(-N1C->getAPIntValue(), VT));
1755 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1756 if (N0C && N0C->isAllOnesValue())
1757 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1758 // fold A-(A-B) -> B
1759 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1760 return N1.getOperand(1);
1761 // fold (A+B)-A -> B
1762 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1763 return N0.getOperand(1);
1764 // fold (A+B)-B -> A
1765 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1766 return N0.getOperand(0);
1767 // fold C2-(A+C1) -> (C2-C1)-A
1768 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1769 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1771 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1774 // fold ((A+(B+or-C))-B) -> A+or-C
1775 if (N0.getOpcode() == ISD::ADD &&
1776 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1777 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1778 N0.getOperand(1).getOperand(0) == N1)
1779 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1780 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1781 // fold ((A+(C+B))-B) -> A+C
1782 if (N0.getOpcode() == ISD::ADD &&
1783 N0.getOperand(1).getOpcode() == ISD::ADD &&
1784 N0.getOperand(1).getOperand(1) == N1)
1785 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1786 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1787 // fold ((A-(B-C))-C) -> A-B
1788 if (N0.getOpcode() == ISD::SUB &&
1789 N0.getOperand(1).getOpcode() == ISD::SUB &&
1790 N0.getOperand(1).getOperand(1) == N1)
1791 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1792 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1794 // If either operand of a sub is undef, the result is undef
1795 if (N0.getOpcode() == ISD::UNDEF)
1797 if (N1.getOpcode() == ISD::UNDEF)
1800 // If the relocation model supports it, consider symbol offsets.
1801 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1802 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1803 // fold (sub Sym, c) -> Sym-c
1804 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1805 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1807 (uint64_t)N1C->getSExtValue());
1808 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1809 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1810 if (GA->getGlobal() == GB->getGlobal())
1811 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1818 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1822 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823 EVT VT = N0.getValueType();
1825 // If the flag result is dead, turn this into an SUB.
1826 if (!N->hasAnyUseOfValue(1))
1827 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1828 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1831 // fold (subc x, x) -> 0 + no borrow
1833 return CombineTo(N, DAG.getConstant(0, VT),
1834 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1837 // fold (subc x, 0) -> x + no borrow
1838 if (N1C && N1C->isNullValue())
1839 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1842 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1843 if (N0C && N0C->isAllOnesValue())
1844 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1845 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1851 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1852 SDValue N0 = N->getOperand(0);
1853 SDValue N1 = N->getOperand(1);
1854 SDValue CarryIn = N->getOperand(2);
1856 // fold (sube x, y, false) -> (subc x, y)
1857 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1863 SDValue DAGCombiner::visitMUL(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
1866 EVT VT = N0.getValueType();
1868 // fold (mul x, undef) -> 0
1869 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1870 return DAG.getConstant(0, VT);
1872 bool N0IsConst = false;
1873 bool N1IsConst = false;
1874 APInt ConstValue0, ConstValue1;
1876 if (VT.isVector()) {
1877 SDValue FoldedVOp = SimplifyVBinOp(N);
1878 if (FoldedVOp.getNode()) return FoldedVOp;
1880 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1881 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1883 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1884 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1886 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1887 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1891 // fold (mul c1, c2) -> c1*c2
1892 if (N0IsConst && N1IsConst)
1893 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1895 // canonicalize constant to RHS
1896 if (N0IsConst && !N1IsConst)
1897 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1898 // fold (mul x, 0) -> 0
1899 if (N1IsConst && ConstValue1 == 0)
1901 // We require a splat of the entire scalar bit width for non-contiguous
1904 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1905 // fold (mul x, 1) -> x
1906 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1908 // fold (mul x, -1) -> 0-x
1909 if (N1IsConst && ConstValue1.isAllOnesValue())
1910 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1911 DAG.getConstant(0, VT), N0);
1912 // fold (mul x, (1 << c)) -> x << c
1913 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1914 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1915 DAG.getConstant(ConstValue1.logBase2(),
1916 getShiftAmountTy(N0.getValueType())));
1917 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1918 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1919 unsigned Log2Val = (-ConstValue1).logBase2();
1920 // FIXME: If the input is something that is easily negated (e.g. a
1921 // single-use add), we should put the negate there.
1922 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1923 DAG.getConstant(0, VT),
1924 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1925 DAG.getConstant(Log2Val,
1926 getShiftAmountTy(N0.getValueType()))));
1930 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1931 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1932 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1933 isa<ConstantSDNode>(N0.getOperand(1)))) {
1934 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935 N1, N0.getOperand(1));
1936 AddToWorkList(C3.getNode());
1937 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1938 N0.getOperand(0), C3);
1941 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1944 SDValue Sh(nullptr,0), Y(nullptr,0);
1945 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1946 if (N0.getOpcode() == ISD::SHL &&
1947 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1948 isa<ConstantSDNode>(N0.getOperand(1))) &&
1949 N0.getNode()->hasOneUse()) {
1951 } else if (N1.getOpcode() == ISD::SHL &&
1952 isa<ConstantSDNode>(N1.getOperand(1)) &&
1953 N1.getNode()->hasOneUse()) {
1958 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1959 Sh.getOperand(0), Y);
1960 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1961 Mul, Sh.getOperand(1));
1965 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1966 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1967 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968 isa<ConstantSDNode>(N0.getOperand(1))))
1969 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1970 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1971 N0.getOperand(0), N1),
1972 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1973 N0.getOperand(1), N1));
1976 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1983 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1984 SDValue N0 = N->getOperand(0);
1985 SDValue N1 = N->getOperand(1);
1986 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1987 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1988 EVT VT = N->getValueType(0);
1991 if (VT.isVector()) {
1992 SDValue FoldedVOp = SimplifyVBinOp(N);
1993 if (FoldedVOp.getNode()) return FoldedVOp;
1996 // fold (sdiv c1, c2) -> c1/c2
1997 if (N0C && N1C && !N1C->isNullValue())
1998 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1999 // fold (sdiv X, 1) -> X
2000 if (N1C && N1C->getAPIntValue() == 1LL)
2002 // fold (sdiv X, -1) -> 0-X
2003 if (N1C && N1C->isAllOnesValue())
2004 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2005 DAG.getConstant(0, VT), N0);
2006 // If we know the sign bits of both operands are zero, strength reduce to a
2007 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2008 if (!VT.isVector()) {
2009 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2010 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2014 // fold (sdiv X, pow2) -> simple ops after legalize
2015 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2016 (-N1C->getAPIntValue()).isPowerOf2())) {
2017 // If dividing by powers of two is cheap, then don't perform the following
2019 if (TLI.isPow2DivCheap())
2022 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2024 // Splat the sign bit into the register
2026 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2027 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2028 getShiftAmountTy(N0.getValueType())));
2029 AddToWorkList(SGN.getNode());
2031 // Add (N0 < 0) ? abs2 - 1 : 0;
2033 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2034 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2035 getShiftAmountTy(SGN.getValueType())));
2036 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2037 AddToWorkList(SRL.getNode());
2038 AddToWorkList(ADD.getNode()); // Divide by pow2
2039 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2040 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2042 // If we're dividing by a positive value, we're done. Otherwise, we must
2043 // negate the result.
2044 if (N1C->getAPIntValue().isNonNegative())
2047 AddToWorkList(SRA.getNode());
2048 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2051 // if integer divide is expensive and we satisfy the requirements, emit an
2052 // alternate sequence.
2053 if (N1C && !TLI.isIntDivCheap()) {
2054 SDValue Op = BuildSDIV(N);
2055 if (Op.getNode()) return Op;
2059 if (N0.getOpcode() == ISD::UNDEF)
2060 return DAG.getConstant(0, VT);
2061 // X / undef -> undef
2062 if (N1.getOpcode() == ISD::UNDEF)
2068 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2069 SDValue N0 = N->getOperand(0);
2070 SDValue N1 = N->getOperand(1);
2071 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2072 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2073 EVT VT = N->getValueType(0);
2076 if (VT.isVector()) {
2077 SDValue FoldedVOp = SimplifyVBinOp(N);
2078 if (FoldedVOp.getNode()) return FoldedVOp;
2081 // fold (udiv c1, c2) -> c1/c2
2082 if (N0C && N1C && !N1C->isNullValue())
2083 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2084 // fold (udiv x, (1 << c)) -> x >>u c
2085 if (N1C && N1C->getAPIntValue().isPowerOf2())
2086 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2087 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2088 getShiftAmountTy(N0.getValueType())));
2089 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2090 if (N1.getOpcode() == ISD::SHL) {
2091 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2092 if (SHC->getAPIntValue().isPowerOf2()) {
2093 EVT ADDVT = N1.getOperand(1).getValueType();
2094 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2096 DAG.getConstant(SHC->getAPIntValue()
2099 AddToWorkList(Add.getNode());
2100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2104 // fold (udiv x, c) -> alternate
2105 if (N1C && !TLI.isIntDivCheap()) {
2106 SDValue Op = BuildUDIV(N);
2107 if (Op.getNode()) return Op;
2111 if (N0.getOpcode() == ISD::UNDEF)
2112 return DAG.getConstant(0, VT);
2113 // X / undef -> undef
2114 if (N1.getOpcode() == ISD::UNDEF)
2120 SDValue DAGCombiner::visitSREM(SDNode *N) {
2121 SDValue N0 = N->getOperand(0);
2122 SDValue N1 = N->getOperand(1);
2123 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2124 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2125 EVT VT = N->getValueType(0);
2127 // fold (srem c1, c2) -> c1%c2
2128 if (N0C && N1C && !N1C->isNullValue())
2129 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2130 // If we know the sign bits of both operands are zero, strength reduce to a
2131 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2132 if (!VT.isVector()) {
2133 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2137 // If X/C can be simplified by the division-by-constant logic, lower
2138 // X%C to the equivalent of X-X/C*C.
2139 if (N1C && !N1C->isNullValue()) {
2140 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2141 AddToWorkList(Div.getNode());
2142 SDValue OptimizedDiv = combine(Div.getNode());
2143 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2144 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2146 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2147 AddToWorkList(Mul.getNode());
2153 if (N0.getOpcode() == ISD::UNDEF)
2154 return DAG.getConstant(0, VT);
2155 // X % undef -> undef
2156 if (N1.getOpcode() == ISD::UNDEF)
2162 SDValue DAGCombiner::visitUREM(SDNode *N) {
2163 SDValue N0 = N->getOperand(0);
2164 SDValue N1 = N->getOperand(1);
2165 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2166 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2167 EVT VT = N->getValueType(0);
2169 // fold (urem c1, c2) -> c1%c2
2170 if (N0C && N1C && !N1C->isNullValue())
2171 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2172 // fold (urem x, pow2) -> (and x, pow2-1)
2173 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2174 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2175 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2176 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2177 if (N1.getOpcode() == ISD::SHL) {
2178 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2179 if (SHC->getAPIntValue().isPowerOf2()) {
2181 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2182 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2184 AddToWorkList(Add.getNode());
2185 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2190 // If X/C can be simplified by the division-by-constant logic, lower
2191 // X%C to the equivalent of X-X/C*C.
2192 if (N1C && !N1C->isNullValue()) {
2193 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2194 AddToWorkList(Div.getNode());
2195 SDValue OptimizedDiv = combine(Div.getNode());
2196 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2197 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2199 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2200 AddToWorkList(Mul.getNode());
2206 if (N0.getOpcode() == ISD::UNDEF)
2207 return DAG.getConstant(0, VT);
2208 // X % undef -> undef
2209 if (N1.getOpcode() == ISD::UNDEF)
2215 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2216 SDValue N0 = N->getOperand(0);
2217 SDValue N1 = N->getOperand(1);
2218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2219 EVT VT = N->getValueType(0);
2222 // fold (mulhs x, 0) -> 0
2223 if (N1C && N1C->isNullValue())
2225 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2226 if (N1C && N1C->getAPIntValue() == 1)
2227 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2228 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2229 getShiftAmountTy(N0.getValueType())));
2230 // fold (mulhs x, undef) -> 0
2231 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2232 return DAG.getConstant(0, VT);
2234 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2236 if (VT.isSimple() && !VT.isVector()) {
2237 MVT Simple = VT.getSimpleVT();
2238 unsigned SimpleSize = Simple.getSizeInBits();
2239 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2240 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2241 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2242 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2243 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2244 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2245 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2246 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2253 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
2256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2257 EVT VT = N->getValueType(0);
2260 // fold (mulhu x, 0) -> 0
2261 if (N1C && N1C->isNullValue())
2263 // fold (mulhu x, 1) -> 0
2264 if (N1C && N1C->getAPIntValue() == 1)
2265 return DAG.getConstant(0, N0.getValueType());
2266 // fold (mulhu x, undef) -> 0
2267 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2268 return DAG.getConstant(0, VT);
2270 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2272 if (VT.isSimple() && !VT.isVector()) {
2273 MVT Simple = VT.getSimpleVT();
2274 unsigned SimpleSize = Simple.getSizeInBits();
2275 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2278 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2279 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2281 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2282 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2289 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2290 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2291 /// that are being performed. Return true if a simplification was made.
2293 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2295 // If the high half is not needed, just compute the low half.
2296 bool HiExists = N->hasAnyUseOfValue(1);
2298 (!LegalOperations ||
2299 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2300 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2301 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2302 return CombineTo(N, Res, Res);
2305 // If the low half is not needed, just compute the high half.
2306 bool LoExists = N->hasAnyUseOfValue(0);
2308 (!LegalOperations ||
2309 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2310 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2311 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2312 return CombineTo(N, Res, Res);
2315 // If both halves are used, return as it is.
2316 if (LoExists && HiExists)
2319 // If the two computed results can be simplified separately, separate them.
2321 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2322 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2323 AddToWorkList(Lo.getNode());
2324 SDValue LoOpt = combine(Lo.getNode());
2325 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2326 (!LegalOperations ||
2327 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2328 return CombineTo(N, LoOpt, LoOpt);
2332 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2333 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2334 AddToWorkList(Hi.getNode());
2335 SDValue HiOpt = combine(Hi.getNode());
2336 if (HiOpt.getNode() && HiOpt != Hi &&
2337 (!LegalOperations ||
2338 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2339 return CombineTo(N, HiOpt, HiOpt);
2345 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2347 if (Res.getNode()) return Res;
2349 EVT VT = N->getValueType(0);
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2360 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362 // Compute the high part as N1.
2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366 // Compute the low part as N0.
2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368 return CombineTo(N, Lo, Hi);
2375 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2377 if (Res.getNode()) return Res;
2379 EVT VT = N->getValueType(0);
2382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2390 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2391 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2392 // Compute the high part as N1.
2393 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2394 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2395 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2396 // Compute the low part as N0.
2397 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2398 return CombineTo(N, Lo, Hi);
2405 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2406 // (smulo x, 2) -> (saddo x, x)
2407 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408 if (C2->getAPIntValue() == 2)
2409 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2410 N->getOperand(0), N->getOperand(0));
2415 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2416 // (umulo x, 2) -> (uaddo x, x)
2417 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2418 if (C2->getAPIntValue() == 2)
2419 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2420 N->getOperand(0), N->getOperand(0));
2425 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2427 if (Res.getNode()) return Res;
2432 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2433 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2434 if (Res.getNode()) return Res;
2439 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2440 /// two operands of the same opcode, try to simplify it.
2441 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2442 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2443 EVT VT = N0.getValueType();
2444 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2446 // Bail early if none of these transforms apply.
2447 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2449 // For each of OP in AND/OR/XOR:
2450 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2451 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2452 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2453 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2455 // do not sink logical op inside of a vector extend, since it may combine
2457 EVT Op0VT = N0.getOperand(0).getValueType();
2458 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2459 N0.getOpcode() == ISD::SIGN_EXTEND ||
2460 // Avoid infinite looping with PromoteIntBinOp.
2461 (N0.getOpcode() == ISD::ANY_EXTEND &&
2462 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2463 (N0.getOpcode() == ISD::TRUNCATE &&
2464 (!TLI.isZExtFree(VT, Op0VT) ||
2465 !TLI.isTruncateFree(Op0VT, VT)) &&
2466 TLI.isTypeLegal(Op0VT))) &&
2468 Op0VT == N1.getOperand(0).getValueType() &&
2469 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2470 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2471 N0.getOperand(0).getValueType(),
2472 N0.getOperand(0), N1.getOperand(0));
2473 AddToWorkList(ORNode.getNode());
2474 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2477 // For each of OP in SHL/SRL/SRA/AND...
2478 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2479 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2480 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2481 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2482 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2483 N0.getOperand(1) == N1.getOperand(1)) {
2484 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2485 N0.getOperand(0).getValueType(),
2486 N0.getOperand(0), N1.getOperand(0));
2487 AddToWorkList(ORNode.getNode());
2488 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2489 ORNode, N0.getOperand(1));
2492 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2493 // Only perform this optimization after type legalization and before
2494 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2495 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2496 // we don't want to undo this promotion.
2497 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2499 if ((N0.getOpcode() == ISD::BITCAST ||
2500 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2501 Level == AfterLegalizeTypes) {
2502 SDValue In0 = N0.getOperand(0);
2503 SDValue In1 = N1.getOperand(0);
2504 EVT In0Ty = In0.getValueType();
2505 EVT In1Ty = In1.getValueType();
2507 // If both incoming values are integers, and the original types are the
2509 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2510 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2511 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2512 AddToWorkList(Op.getNode());
2517 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2518 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2519 // If both shuffles use the same mask, and both shuffle within a single
2520 // vector, then it is worthwhile to move the swizzle after the operation.
2521 // The type-legalizer generates this pattern when loading illegal
2522 // vector types from memory. In many cases this allows additional shuffle
2524 // There are other cases where moving the shuffle after the xor/and/or
2525 // is profitable even if shuffles don't perform a swizzle.
2526 // If both shuffles use the same mask, and both shuffles have the same first
2527 // or second operand, then it might still be profitable to move the shuffle
2528 // after the xor/and/or operation.
2529 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2533 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2534 "Inputs to shuffles are not the same type");
2536 // Check that both shuffles use the same mask. The masks are known to be of
2537 // the same length because the result vector type is the same.
2538 // Check also that shuffles have only one use to avoid introducing extra
2540 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2541 SVN0->getMask().equals(SVN1->getMask())) {
2542 SDValue ShOp = N0->getOperand(1);
2544 // Don't try to fold this node if it requires introducing a
2545 // build vector of all zeros that might be illegal at this stage.
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2548 ShOp = DAG.getConstant(0, VT);
2553 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2554 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2555 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2556 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(0), N1->getOperand(0));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2561 &SVN0->getMask()[0]);
2564 // Don't try to fold this node if it requires introducing a
2565 // build vector of all zeros that might be illegal at this stage.
2566 ShOp = N0->getOperand(0);
2567 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2569 ShOp = DAG.getConstant(0, VT);
2574 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2575 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2576 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2577 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2578 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2579 N0->getOperand(1), N1->getOperand(1));
2580 AddToWorkList(NewNode.getNode());
2581 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2582 &SVN0->getMask()[0]);
2590 SDValue DAGCombiner::visitAND(SDNode *N) {
2591 SDValue N0 = N->getOperand(0);
2592 SDValue N1 = N->getOperand(1);
2593 SDValue LL, LR, RL, RR, CC0, CC1;
2594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2596 EVT VT = N1.getValueType();
2597 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2600 if (VT.isVector()) {
2601 SDValue FoldedVOp = SimplifyVBinOp(N);
2602 if (FoldedVOp.getNode()) return FoldedVOp;
2604 // fold (and x, 0) -> 0, vector edition
2605 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2607 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2610 // fold (and x, -1) -> x, vector edition
2611 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2613 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2617 // fold (and x, undef) -> 0
2618 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2619 return DAG.getConstant(0, VT);
2620 // fold (and c1, c2) -> c1&c2
2622 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2623 // canonicalize constant to RHS
2625 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2626 // fold (and x, -1) -> x
2627 if (N1C && N1C->isAllOnesValue())
2629 // if (and x, c) is known to be zero, return 0
2630 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2631 APInt::getAllOnesValue(BitWidth)))
2632 return DAG.getConstant(0, VT);
2634 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2637 // fold (and (or x, C), D) -> D if (C & D) == D
2638 if (N1C && N0.getOpcode() == ISD::OR)
2639 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2640 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2642 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2643 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2644 SDValue N0Op0 = N0.getOperand(0);
2645 APInt Mask = ~N1C->getAPIntValue();
2646 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2647 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2648 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2649 N0.getValueType(), N0Op0);
2651 // Replace uses of the AND with uses of the Zero extend node.
2654 // We actually want to replace all uses of the any_extend with the
2655 // zero_extend, to avoid duplicating things. This will later cause this
2656 // AND to be folded.
2657 CombineTo(N0.getNode(), Zext);
2658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2661 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2662 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2663 // already be zero by virtue of the width of the base type of the load.
2665 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2667 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2668 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2669 N0.getOpcode() == ISD::LOAD) {
2670 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2671 N0 : N0.getOperand(0) );
2673 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2674 // This can be a pure constant or a vector splat, in which case we treat the
2675 // vector as a scalar and use the splat value.
2676 APInt Constant = APInt::getNullValue(1);
2677 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2678 Constant = C->getAPIntValue();
2679 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2680 APInt SplatValue, SplatUndef;
2681 unsigned SplatBitSize;
2683 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2684 SplatBitSize, HasAnyUndefs);
2686 // Undef bits can contribute to a possible optimisation if set, so
2688 SplatValue |= SplatUndef;
2690 // The splat value may be something like "0x00FFFFFF", which means 0 for
2691 // the first vector value and FF for the rest, repeating. We need a mask
2692 // that will apply equally to all members of the vector, so AND all the
2693 // lanes of the constant together.
2694 EVT VT = Vector->getValueType(0);
2695 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2697 // If the splat value has been compressed to a bitlength lower
2698 // than the size of the vector lane, we need to re-expand it to
2700 if (BitWidth > SplatBitSize)
2701 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2702 SplatBitSize < BitWidth;
2703 SplatBitSize = SplatBitSize * 2)
2704 SplatValue |= SplatValue.shl(SplatBitSize);
2706 Constant = APInt::getAllOnesValue(BitWidth);
2707 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2708 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2712 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2713 // actually legal and isn't going to get expanded, else this is a false
2715 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2716 Load->getMemoryVT());
2718 // Resize the constant to the same size as the original memory access before
2719 // extension. If it is still the AllOnesValue then this AND is completely
2722 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2725 switch (Load->getExtensionType()) {
2726 default: B = false; break;
2727 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2729 case ISD::NON_EXTLOAD: B = true; break;
2732 if (B && Constant.isAllOnesValue()) {
2733 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2734 // preserve semantics once we get rid of the AND.
2735 SDValue NewLoad(Load, 0);
2736 if (Load->getExtensionType() == ISD::EXTLOAD) {
2737 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2738 Load->getValueType(0), SDLoc(Load),
2739 Load->getChain(), Load->getBasePtr(),
2740 Load->getOffset(), Load->getMemoryVT(),
2741 Load->getMemOperand());
2742 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2743 if (Load->getNumValues() == 3) {
2744 // PRE/POST_INC loads have 3 values.
2745 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2746 NewLoad.getValue(2) };
2747 CombineTo(Load, To, 3, true);
2749 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2753 // Fold the AND away, taking care not to fold to the old load node if we
2755 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2760 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2761 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2762 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2763 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2765 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2766 LL.getValueType().isInteger()) {
2767 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2768 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770 LR.getValueType(), LL, RL);
2771 AddToWorkList(ORNode.getNode());
2772 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2774 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2775 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2776 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2777 LR.getValueType(), LL, RL);
2778 AddToWorkList(ANDNode.getNode());
2779 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2781 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2782 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2783 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2784 LR.getValueType(), LL, RL);
2785 AddToWorkList(ORNode.getNode());
2786 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2789 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2790 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2791 Op0 == Op1 && LL.getValueType().isInteger() &&
2792 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2793 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2794 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2795 cast<ConstantSDNode>(RR)->isNullValue()))) {
2796 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2797 LL, DAG.getConstant(1, LL.getValueType()));
2798 AddToWorkList(ADDNode.getNode());
2799 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2800 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2802 // canonicalize equivalent to ll == rl
2803 if (LL == RR && LR == RL) {
2804 Op1 = ISD::getSetCCSwappedOperands(Op1);
2807 if (LL == RL && LR == RR) {
2808 bool isInteger = LL.getValueType().isInteger();
2809 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2810 if (Result != ISD::SETCC_INVALID &&
2811 (!LegalOperations ||
2812 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2813 TLI.isOperationLegal(ISD::SETCC,
2814 getSetCCResultType(N0.getSimpleValueType())))))
2815 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2820 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2821 if (N0.getOpcode() == N1.getOpcode()) {
2822 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2823 if (Tmp.getNode()) return Tmp;
2826 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2827 // fold (and (sra)) -> (and (srl)) when possible.
2828 if (!VT.isVector() &&
2829 SimplifyDemandedBits(SDValue(N, 0)))
2830 return SDValue(N, 0);
2832 // fold (zext_inreg (extload x)) -> (zextload x)
2833 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2835 EVT MemVT = LN0->getMemoryVT();
2836 // If we zero all the possible extended bits, then we can turn this into
2837 // a zextload if we are running before legalize or the operation is legal.
2838 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2839 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2840 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2841 ((!LegalOperations && !LN0->isVolatile()) ||
2842 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2843 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2844 LN0->getChain(), LN0->getBasePtr(),
2845 MemVT, LN0->getMemOperand());
2847 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2851 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2852 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2855 EVT MemVT = LN0->getMemoryVT();
2856 // If we zero all the possible extended bits, then we can turn this into
2857 // a zextload if we are running before legalize or the operation is legal.
2858 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2859 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2860 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2861 ((!LegalOperations && !LN0->isVolatile()) ||
2862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2863 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2864 LN0->getChain(), LN0->getBasePtr(),
2865 MemVT, LN0->getMemOperand());
2867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2872 // fold (and (load x), 255) -> (zextload x, i8)
2873 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2874 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2875 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2876 (N0.getOpcode() == ISD::ANY_EXTEND &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2878 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2879 LoadSDNode *LN0 = HasAnyExt
2880 ? cast<LoadSDNode>(N0.getOperand(0))
2881 : cast<LoadSDNode>(N0);
2882 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2883 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2884 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2885 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2886 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2887 EVT LoadedVT = LN0->getMemoryVT();
2889 if (ExtVT == LoadedVT &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2895 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2896 LN0->getMemOperand());
2898 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2902 // Do not change the width of a volatile load.
2903 // Do not generate loads of non-round integer types since these can
2904 // be expensive (and would be wrong if the type is not byte sized).
2905 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2906 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2907 EVT PtrType = LN0->getOperand(1).getValueType();
2909 unsigned Alignment = LN0->getAlignment();
2910 SDValue NewPtr = LN0->getBasePtr();
2912 // For big endian targets, we need to add an offset to the pointer
2913 // to load the correct bytes. For little endian systems, we merely
2914 // need to read fewer bytes from the same pointer.
2915 if (TLI.isBigEndian()) {
2916 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2917 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2918 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2919 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2920 NewPtr, DAG.getConstant(PtrOff, PtrType));
2921 Alignment = MinAlign(Alignment, PtrOff);
2924 AddToWorkList(NewPtr.getNode());
2926 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2928 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2929 LN0->getChain(), NewPtr,
2930 LN0->getPointerInfo(),
2931 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2932 Alignment, LN0->getTBAAInfo());
2934 CombineTo(LN0, Load, Load.getValue(1));
2935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2941 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2942 VT.getSizeInBits() <= 64) {
2943 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2944 APInt ADDC = ADDI->getAPIntValue();
2945 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2947 // immediate for an add, but it is legal if its top c2 bits are set,
2948 // transform the ADD so the immediate doesn't need to be materialized
2950 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2951 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2952 SRLI->getZExtValue());
2953 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2955 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2957 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2958 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2959 CombineTo(N0.getNode(), NewAdd);
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2968 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2969 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2970 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2971 N0.getOperand(1), false);
2972 if (BSwap.getNode())
2979 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2981 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2982 bool DemandHighBits) {
2983 if (!LegalOperations)
2986 EVT VT = N->getValueType(0);
2987 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2989 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2992 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2993 bool LookPassAnd0 = false;
2994 bool LookPassAnd1 = false;
2995 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2997 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2999 if (N0.getOpcode() == ISD::AND) {
3000 if (!N0.getNode()->hasOneUse())
3002 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3003 if (!N01C || N01C->getZExtValue() != 0xFF00)
3005 N0 = N0.getOperand(0);
3006 LookPassAnd0 = true;
3009 if (N1.getOpcode() == ISD::AND) {
3010 if (!N1.getNode()->hasOneUse())
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013 if (!N11C || N11C->getZExtValue() != 0xFF)
3015 N1 = N1.getOperand(0);
3016 LookPassAnd1 = true;
3019 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3021 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3023 if (!N0.getNode()->hasOneUse() ||
3024 !N1.getNode()->hasOneUse())
3027 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3031 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3034 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3035 SDValue N00 = N0->getOperand(0);
3036 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3037 if (!N00.getNode()->hasOneUse())
3039 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3040 if (!N001C || N001C->getZExtValue() != 0xFF)
3042 N00 = N00.getOperand(0);
3043 LookPassAnd0 = true;
3046 SDValue N10 = N1->getOperand(0);
3047 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3048 if (!N10.getNode()->hasOneUse())
3050 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3051 if (!N101C || N101C->getZExtValue() != 0xFF00)
3053 N10 = N10.getOperand(0);
3054 LookPassAnd1 = true;
3060 // Make sure everything beyond the low halfword gets set to zero since the SRL
3061 // 16 will clear the top bits.
3062 unsigned OpSizeInBits = VT.getSizeInBits();
3063 if (DemandHighBits && OpSizeInBits > 16) {
3064 // If the left-shift isn't masked out then the only way this is a bswap is
3065 // if all bits beyond the low 8 are 0. In that case the entire pattern
3066 // reduces to a left shift anyway: leave it for other parts of the combiner.
3070 // However, if the right shift isn't masked out then it might be because
3071 // it's not needed. See if we can spot that too.
3072 if (!LookPassAnd1 &&
3073 !DAG.MaskedValueIsZero(
3074 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3078 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3079 if (OpSizeInBits > 16)
3080 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3081 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3085 /// isBSwapHWordElement - Return true if the specified node is an element
3086 /// that makes up a 32-bit packed halfword byteswap. i.e.
3087 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3088 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3089 if (!N.getNode()->hasOneUse())
3092 unsigned Opc = N.getOpcode();
3093 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3101 switch (N1C->getZExtValue()) {
3104 case 0xFF: Num = 0; break;
3105 case 0xFF00: Num = 1; break;
3106 case 0xFF0000: Num = 2; break;
3107 case 0xFF000000: Num = 3; break;
3110 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3111 SDValue N0 = N.getOperand(0);
3112 if (Opc == ISD::AND) {
3113 if (Num == 0 || Num == 2) {
3115 // (x >> 8) & 0xff0000
3116 if (N0.getOpcode() != ISD::SRL)
3118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119 if (!C || C->getZExtValue() != 8)
3122 // (x << 8) & 0xff00
3123 // (x << 8) & 0xff000000
3124 if (N0.getOpcode() != ISD::SHL)
3126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127 if (!C || C->getZExtValue() != 8)
3130 } else if (Opc == ISD::SHL) {
3132 // (x & 0xff0000) << 8
3133 if (Num != 0 && Num != 2)
3135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136 if (!C || C->getZExtValue() != 8)
3138 } else { // Opc == ISD::SRL
3139 // (x & 0xff00) >> 8
3140 // (x & 0xff000000) >> 8
3141 if (Num != 1 && Num != 3)
3143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3144 if (!C || C->getZExtValue() != 8)
3151 Parts[Num] = N0.getOperand(0).getNode();
3155 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3156 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3157 /// => (rotl (bswap x), 16)
3158 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3159 if (!LegalOperations)
3162 EVT VT = N->getValueType(0);
3165 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3168 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3170 // (or (or (and), (and)), (or (and), (and)))
3171 // (or (or (or (and), (and)), (and)), (and))
3172 if (N0.getOpcode() != ISD::OR)
3174 SDValue N00 = N0.getOperand(0);
3175 SDValue N01 = N0.getOperand(1);
3177 if (N1.getOpcode() == ISD::OR &&
3178 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3179 // (or (or (and), (and)), (or (and), (and)))
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3184 SDValue N001 = N00.getOperand(1);
3185 if (!isBSwapHWordElement(N001, Parts))
3187 SDValue N010 = N01.getOperand(0);
3188 if (!isBSwapHWordElement(N010, Parts))
3190 SDValue N011 = N01.getOperand(1);
3191 if (!isBSwapHWordElement(N011, Parts))
3194 // (or (or (or (and), (and)), (and)), (and))
3195 if (!isBSwapHWordElement(N1, Parts))
3197 if (!isBSwapHWordElement(N01, Parts))
3199 if (N00.getOpcode() != ISD::OR)
3201 SDValue N000 = N00.getOperand(0);
3202 if (!isBSwapHWordElement(N000, Parts))
3204 SDValue N001 = N00.getOperand(1);
3205 if (!isBSwapHWordElement(N001, Parts))
3209 // Make sure the parts are all coming from the same node.
3210 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3213 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3214 SDValue(Parts[0],0));
3216 // Result of the bswap should be rotated by 16. If it's not legal, then
3217 // do (x << 16) | (x >> 16).
3218 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3219 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3220 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3221 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3222 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3223 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3224 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3225 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3228 SDValue DAGCombiner::visitOR(SDNode *N) {
3229 SDValue N0 = N->getOperand(0);
3230 SDValue N1 = N->getOperand(1);
3231 SDValue LL, LR, RL, RR, CC0, CC1;
3232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3234 EVT VT = N1.getValueType();
3237 if (VT.isVector()) {
3238 SDValue FoldedVOp = SimplifyVBinOp(N);
3239 if (FoldedVOp.getNode()) return FoldedVOp;
3241 // fold (or x, 0) -> x, vector edition
3242 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3244 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3247 // fold (or x, -1) -> -1, vector edition
3248 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3250 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3253 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3254 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3255 // Do this only if the resulting shuffle is legal.
3256 if (isa<ShuffleVectorSDNode>(N0) &&
3257 isa<ShuffleVectorSDNode>(N1) &&
3258 N0->getOperand(1) == N1->getOperand(1) &&
3259 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3260 bool CanFold = true;
3261 unsigned NumElts = VT.getVectorNumElements();
3262 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3263 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3264 // We construct two shuffle masks:
3265 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3266 // and N1 as the second operand.
3267 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3268 // and N0 as the second operand.
3269 // We do this because OR is commutable and therefore there might be
3270 // two ways to fold this node into a shuffle.
3271 SmallVector<int,4> Mask1;
3272 SmallVector<int,4> Mask2;
3274 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3275 int M0 = SV0->getMaskElt(i);
3276 int M1 = SV1->getMaskElt(i);
3278 // Both shuffle indexes are undef. Propagate Undef.
3279 if (M0 < 0 && M1 < 0) {
3280 Mask1.push_back(M0);
3281 Mask2.push_back(M0);
3285 if (M0 < 0 || M1 < 0 ||
3286 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3287 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3292 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3293 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3297 // Fold this sequence only if the resulting shuffle is 'legal'.
3298 if (TLI.isShuffleMaskLegal(Mask1, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3300 N1->getOperand(0), &Mask1[0]);
3301 if (TLI.isShuffleMaskLegal(Mask2, VT))
3302 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3303 N0->getOperand(0), &Mask2[0]);
3308 // fold (or x, undef) -> -1
3309 if (!LegalOperations &&
3310 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3311 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3312 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3314 // fold (or c1, c2) -> c1|c2
3316 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3317 // canonicalize constant to RHS
3319 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3320 // fold (or x, 0) -> x
3321 if (N1C && N1C->isNullValue())
3323 // fold (or x, -1) -> -1
3324 if (N1C && N1C->isAllOnesValue())
3326 // fold (or x, c) -> c iff (x & ~c) == 0
3327 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3330 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3331 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3332 if (BSwap.getNode())
3334 BSwap = MatchBSwapHWordLow(N, N0, N1);
3335 if (BSwap.getNode())
3339 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3342 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3343 // iff (c1 & c2) == 0.
3344 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3345 isa<ConstantSDNode>(N0.getOperand(1))) {
3346 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3347 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3348 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3352 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3353 N0.getOperand(0), N1), COR);
3356 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3357 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3358 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3359 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3361 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3362 LL.getValueType().isInteger()) {
3363 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3364 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3365 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3366 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3367 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3368 LR.getValueType(), LL, RL);
3369 AddToWorkList(ORNode.getNode());
3370 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3372 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3373 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3374 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3375 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3376 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3377 LR.getValueType(), LL, RL);
3378 AddToWorkList(ANDNode.getNode());
3379 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3382 // canonicalize equivalent to ll == rl
3383 if (LL == RR && LR == RL) {
3384 Op1 = ISD::getSetCCSwappedOperands(Op1);
3387 if (LL == RL && LR == RR) {
3388 bool isInteger = LL.getValueType().isInteger();
3389 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3390 if (Result != ISD::SETCC_INVALID &&
3391 (!LegalOperations ||
3392 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3393 TLI.isOperationLegal(ISD::SETCC,
3394 getSetCCResultType(N0.getValueType())))))
3395 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3400 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3401 if (N0.getOpcode() == N1.getOpcode()) {
3402 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3403 if (Tmp.getNode()) return Tmp;
3406 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3407 if (N0.getOpcode() == ISD::AND &&
3408 N1.getOpcode() == ISD::AND &&
3409 N0.getOperand(1).getOpcode() == ISD::Constant &&
3410 N1.getOperand(1).getOpcode() == ISD::Constant &&
3411 // Don't increase # computations.
3412 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3413 // We can only do this xform if we know that bits from X that are set in C2
3414 // but not in C1 are already zero. Likewise for Y.
3415 const APInt &LHSMask =
3416 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3417 const APInt &RHSMask =
3418 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3420 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3421 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3422 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3423 N0.getOperand(0), N1.getOperand(0));
3424 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3425 DAG.getConstant(LHSMask | RHSMask, VT));
3429 // See if this is some rotate idiom.
3430 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3431 return SDValue(Rot, 0);
3433 // Simplify the operands using demanded-bits information.
3434 if (!VT.isVector() &&
3435 SimplifyDemandedBits(SDValue(N, 0)))
3436 return SDValue(N, 0);
3441 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3442 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3443 if (Op.getOpcode() == ISD::AND) {
3444 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3445 Mask = Op.getOperand(1);
3446 Op = Op.getOperand(0);
3452 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3460 // Return true if we can prove that, whenever Neg and Pos are both in the
3461 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3462 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3464 // (or (shift1 X, Neg), (shift2 X, Pos))
3466 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3467 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3468 // to consider shift amounts with defined behavior.
3469 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3470 // If OpSize is a power of 2 then:
3472 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3473 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3475 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3476 // for the stronger condition:
3478 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3480 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3481 // we can just replace Neg with Neg' for the rest of the function.
3483 // In other cases we check for the even stronger condition:
3485 // Neg == OpSize - Pos [B]
3487 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3488 // behavior if Pos == 0 (and consequently Neg == OpSize).
3490 // We could actually use [A] whenever OpSize is a power of 2, but the
3491 // only extra cases that it would match are those uninteresting ones
3492 // where Neg and Pos are never in range at the same time. E.g. for
3493 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3494 // as well as (sub 32, Pos), but:
3496 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3498 // always invokes undefined behavior for 32-bit X.
3500 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3501 unsigned MaskLoBits = 0;
3502 if (Neg.getOpcode() == ISD::AND &&
3503 isPowerOf2_64(OpSize) &&
3504 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3505 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3506 Neg = Neg.getOperand(0);
3507 MaskLoBits = Log2_64(OpSize);
3510 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3511 if (Neg.getOpcode() != ISD::SUB)
3513 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3516 SDValue NegOp1 = Neg.getOperand(1);
3518 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3519 // Pos'. The truncation is redundant for the purpose of the equality.
3521 Pos.getOpcode() == ISD::AND &&
3522 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3523 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3524 Pos = Pos.getOperand(0);
3526 // The condition we need is now:
3528 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3530 // If NegOp1 == Pos then we need:
3532 // OpSize & Mask == NegC & Mask
3534 // (because "x & Mask" is a truncation and distributes through subtraction).
3537 Width = NegC->getAPIntValue();
3538 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3539 // Then the condition we want to prove becomes:
3541 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3543 // which, again because "x & Mask" is a truncation, becomes:
3545 // NegC & Mask == (OpSize - PosC) & Mask
3546 // OpSize & Mask == (NegC + PosC) & Mask
3547 else if (Pos.getOpcode() == ISD::ADD &&
3548 Pos.getOperand(0) == NegOp1 &&
3549 Pos.getOperand(1).getOpcode() == ISD::Constant)
3550 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3551 NegC->getAPIntValue());
3555 // Now we just need to check that OpSize & Mask == Width & Mask.
3557 // Opsize & Mask is 0 since Mask is Opsize - 1.
3558 return Width.getLoBits(MaskLoBits) == 0;
3559 return Width == OpSize;
3562 // A subroutine of MatchRotate used once we have found an OR of two opposite
3563 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3564 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3565 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3566 // Neg with outer conversions stripped away.
3567 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3568 SDValue Neg, SDValue InnerPos,
3569 SDValue InnerNeg, unsigned PosOpcode,
3570 unsigned NegOpcode, SDLoc DL) {
3571 // fold (or (shl x, (*ext y)),
3572 // (srl x, (*ext (sub 32, y)))) ->
3573 // (rotl x, y) or (rotr x, (sub 32, y))
3575 // fold (or (shl x, (*ext (sub 32, y))),
3576 // (srl x, (*ext y))) ->
3577 // (rotr x, y) or (rotl x, (sub 32, y))
3578 EVT VT = Shifted.getValueType();
3579 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3580 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3581 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3582 HasPos ? Pos : Neg).getNode();
3588 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3589 // idioms for rotate, and if the target supports rotation instructions, generate
3591 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3592 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3593 EVT VT = LHS.getValueType();
3594 if (!TLI.isTypeLegal(VT)) return nullptr;
3596 // The target must have at least one rotate flavor.
3597 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3598 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3599 if (!HasROTL && !HasROTR) return nullptr;
3601 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3602 SDValue LHSShift; // The shift.
3603 SDValue LHSMask; // AND value if any.
3604 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3605 return nullptr; // Not part of a rotate.
3607 SDValue RHSShift; // The shift.
3608 SDValue RHSMask; // AND value if any.
3609 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3610 return nullptr; // Not part of a rotate.
3612 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3613 return nullptr; // Not shifting the same value.
3615 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3616 return nullptr; // Shifts must disagree.
3618 // Canonicalize shl to left side in a shl/srl pair.
3619 if (RHSShift.getOpcode() == ISD::SHL) {
3620 std::swap(LHS, RHS);
3621 std::swap(LHSShift, RHSShift);
3622 std::swap(LHSMask , RHSMask );
3625 unsigned OpSizeInBits = VT.getSizeInBits();
3626 SDValue LHSShiftArg = LHSShift.getOperand(0);
3627 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3628 SDValue RHSShiftArg = RHSShift.getOperand(0);
3629 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3631 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3632 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3633 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3634 RHSShiftAmt.getOpcode() == ISD::Constant) {
3635 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3636 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3637 if ((LShVal + RShVal) != OpSizeInBits)
3640 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3641 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3643 // If there is an AND of either shifted operand, apply it to the result.
3644 if (LHSMask.getNode() || RHSMask.getNode()) {
3645 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3647 if (LHSMask.getNode()) {
3648 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3649 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3651 if (RHSMask.getNode()) {
3652 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3653 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3656 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3659 return Rot.getNode();
3662 // If there is a mask here, and we have a variable shift, we can't be sure
3663 // that we're masking out the right stuff.
3664 if (LHSMask.getNode() || RHSMask.getNode())
3667 // If the shift amount is sign/zext/any-extended just peel it off.
3668 SDValue LExtOp0 = LHSShiftAmt;
3669 SDValue RExtOp0 = RHSShiftAmt;
3670 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3671 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3672 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3673 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3674 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3675 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3676 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3677 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3678 LExtOp0 = LHSShiftAmt.getOperand(0);
3679 RExtOp0 = RHSShiftAmt.getOperand(0);
3682 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3683 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3687 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3688 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3695 SDValue DAGCombiner::visitXOR(SDNode *N) {
3696 SDValue N0 = N->getOperand(0);
3697 SDValue N1 = N->getOperand(1);
3698 SDValue LHS, RHS, CC;
3699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3701 EVT VT = N0.getValueType();
3704 if (VT.isVector()) {
3705 SDValue FoldedVOp = SimplifyVBinOp(N);
3706 if (FoldedVOp.getNode()) return FoldedVOp;
3708 // fold (xor x, 0) -> x, vector edition
3709 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3711 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3715 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3716 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3717 return DAG.getConstant(0, VT);
3718 // fold (xor x, undef) -> undef
3719 if (N0.getOpcode() == ISD::UNDEF)
3721 if (N1.getOpcode() == ISD::UNDEF)
3723 // fold (xor c1, c2) -> c1^c2
3725 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3726 // canonicalize constant to RHS
3728 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3729 // fold (xor x, 0) -> x
3730 if (N1C && N1C->isNullValue())
3733 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3737 // fold !(x cc y) -> (x !cc y)
3738 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3739 bool isInt = LHS.getValueType().isInteger();
3740 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3743 if (!LegalOperations ||
3744 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3745 switch (N0.getOpcode()) {
3747 llvm_unreachable("Unhandled SetCC Equivalent!");
3749 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3750 case ISD::SELECT_CC:
3751 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3752 N0.getOperand(3), NotCC);
3757 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3758 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3759 N0.getNode()->hasOneUse() &&
3760 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3761 SDValue V = N0.getOperand(0);
3762 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3763 DAG.getConstant(1, V.getValueType()));
3764 AddToWorkList(V.getNode());
3765 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3768 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3769 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3770 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3771 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3772 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3773 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3774 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3775 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3776 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3777 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3780 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3781 if (N1C && N1C->isAllOnesValue() &&
3782 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3783 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3784 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3785 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3786 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3787 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3788 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3789 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3792 // fold (xor (and x, y), y) -> (and (not x), y)
3793 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3794 N0->getOperand(1) == N1) {
3795 SDValue X = N0->getOperand(0);
3796 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3797 AddToWorkList(NotX.getNode());
3798 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3800 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3801 if (N1C && N0.getOpcode() == ISD::XOR) {
3802 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3803 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3805 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3806 DAG.getConstant(N1C->getAPIntValue() ^
3807 N00C->getAPIntValue(), VT));
3809 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3810 DAG.getConstant(N1C->getAPIntValue() ^
3811 N01C->getAPIntValue(), VT));
3813 // fold (xor x, x) -> 0
3815 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3817 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3818 if (N0.getOpcode() == N1.getOpcode()) {
3819 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3820 if (Tmp.getNode()) return Tmp;
3823 // Simplify the expression using non-local knowledge.
3824 if (!VT.isVector() &&
3825 SimplifyDemandedBits(SDValue(N, 0)))
3826 return SDValue(N, 0);
3831 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3832 /// the shift amount is a constant.
3833 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3834 // We can't and shouldn't fold opaque constants.
3835 if (Amt->isOpaque())
3838 SDNode *LHS = N->getOperand(0).getNode();
3839 if (!LHS->hasOneUse()) return SDValue();
3841 // We want to pull some binops through shifts, so that we have (and (shift))
3842 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3843 // thing happens with address calculations, so it's important to canonicalize
3845 bool HighBitSet = false; // Can we transform this if the high bit is set?
3847 switch (LHS->getOpcode()) {
3848 default: return SDValue();
3851 HighBitSet = false; // We can only transform sra if the high bit is clear.
3854 HighBitSet = true; // We can only transform sra if the high bit is set.
3857 if (N->getOpcode() != ISD::SHL)
3858 return SDValue(); // only shl(add) not sr[al](add).
3859 HighBitSet = false; // We can only transform sra if the high bit is clear.
3863 // We require the RHS of the binop to be a constant and not opaque as well.
3864 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3865 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3867 // FIXME: disable this unless the input to the binop is a shift by a constant.
3868 // If it is not a shift, it pessimizes some common cases like:
3870 // void foo(int *X, int i) { X[i & 1235] = 1; }
3871 // int bar(int *X, int i) { return X[i & 255]; }
3872 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3873 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3874 BinOpLHSVal->getOpcode() != ISD::SRA &&
3875 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3876 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3879 EVT VT = N->getValueType(0);
3881 // If this is a signed shift right, and the high bit is modified by the
3882 // logical operation, do not perform the transformation. The highBitSet
3883 // boolean indicates the value of the high bit of the constant which would
3884 // cause it to be modified for this operation.
3885 if (N->getOpcode() == ISD::SRA) {
3886 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3887 if (BinOpRHSSignSet != HighBitSet)
3891 if (!TLI.isDesirableToCommuteWithShift(LHS))
3894 // Fold the constants, shifting the binop RHS by the shift amount.
3895 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3897 LHS->getOperand(1), N->getOperand(1));
3898 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3900 // Create the new shift.
3901 SDValue NewShift = DAG.getNode(N->getOpcode(),
3902 SDLoc(LHS->getOperand(0)),
3903 VT, LHS->getOperand(0), N->getOperand(1));
3905 // Create the new binop.
3906 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3909 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3910 assert(N->getOpcode() == ISD::TRUNCATE);
3911 assert(N->getOperand(0).getOpcode() == ISD::AND);
3913 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3914 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3915 SDValue N01 = N->getOperand(0).getOperand(1);
3917 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3918 EVT TruncVT = N->getValueType(0);
3919 SDValue N00 = N->getOperand(0).getOperand(0);
3920 APInt TruncC = N01C->getAPIntValue();
3921 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3923 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3924 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3925 DAG.getConstant(TruncC, TruncVT));
3932 SDValue DAGCombiner::visitRotate(SDNode *N) {
3933 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3934 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3935 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3936 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3937 if (NewOp1.getNode())
3938 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3939 N->getOperand(0), NewOp1);
3944 SDValue DAGCombiner::visitSHL(SDNode *N) {
3945 SDValue N0 = N->getOperand(0);
3946 SDValue N1 = N->getOperand(1);
3947 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3948 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3949 EVT VT = N0.getValueType();
3950 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3953 if (VT.isVector()) {
3954 SDValue FoldedVOp = SimplifyVBinOp(N);
3955 if (FoldedVOp.getNode()) return FoldedVOp;
3957 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3958 // If setcc produces all-one true value then:
3959 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3960 if (N1CV && N1CV->isConstant()) {
3961 if (N0.getOpcode() == ISD::AND) {
3962 SDValue N00 = N0->getOperand(0);
3963 SDValue N01 = N0->getOperand(1);
3964 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3966 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3967 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3968 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3969 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3971 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3974 N1C = isConstOrConstSplat(N1);
3979 // fold (shl c1, c2) -> c1<<c2
3981 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3982 // fold (shl 0, x) -> 0
3983 if (N0C && N0C->isNullValue())
3985 // fold (shl x, c >= size(x)) -> undef
3986 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3987 return DAG.getUNDEF(VT);
3988 // fold (shl x, 0) -> x
3989 if (N1C && N1C->isNullValue())
3991 // fold (shl undef, x) -> 0
3992 if (N0.getOpcode() == ISD::UNDEF)
3993 return DAG.getConstant(0, VT);
3994 // if (shl x, c) is known to be zero, return 0
3995 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3996 APInt::getAllOnesValue(OpSizeInBits)))
3997 return DAG.getConstant(0, VT);
3998 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3999 if (N1.getOpcode() == ISD::TRUNCATE &&
4000 N1.getOperand(0).getOpcode() == ISD::AND) {
4001 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4002 if (NewOp1.getNode())
4003 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4006 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4007 return SDValue(N, 0);
4009 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4010 if (N1C && N0.getOpcode() == ISD::SHL) {
4011 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4012 uint64_t c1 = N0C1->getZExtValue();
4013 uint64_t c2 = N1C->getZExtValue();
4014 if (c1 + c2 >= OpSizeInBits)
4015 return DAG.getConstant(0, VT);
4016 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4017 DAG.getConstant(c1 + c2, N1.getValueType()));
4021 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4022 // For this to be valid, the second form must not preserve any of the bits
4023 // that are shifted out by the inner shift in the first form. This means
4024 // the outer shift size must be >= the number of bits added by the ext.
4025 // As a corollary, we don't care what kind of ext it is.
4026 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4027 N0.getOpcode() == ISD::ANY_EXTEND ||
4028 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4029 N0.getOperand(0).getOpcode() == ISD::SHL) {
4030 SDValue N0Op0 = N0.getOperand(0);
4031 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4032 uint64_t c1 = N0Op0C1->getZExtValue();
4033 uint64_t c2 = N1C->getZExtValue();
4034 EVT InnerShiftVT = N0Op0.getValueType();
4035 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4036 if (c2 >= OpSizeInBits - InnerShiftSize) {
4037 if (c1 + c2 >= OpSizeInBits)
4038 return DAG.getConstant(0, VT);
4039 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4040 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4041 N0Op0->getOperand(0)),
4042 DAG.getConstant(c1 + c2, N1.getValueType()));
4047 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4048 // Only fold this if the inner zext has no other uses to avoid increasing
4049 // the total number of instructions.
4050 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4051 N0.getOperand(0).getOpcode() == ISD::SRL) {
4052 SDValue N0Op0 = N0.getOperand(0);
4053 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4054 uint64_t c1 = N0Op0C1->getZExtValue();
4055 if (c1 < VT.getScalarSizeInBits()) {
4056 uint64_t c2 = N1C->getZExtValue();
4058 SDValue NewOp0 = N0.getOperand(0);
4059 EVT CountVT = NewOp0.getOperand(1).getValueType();
4060 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4061 NewOp0, DAG.getConstant(c2, CountVT));
4062 AddToWorkList(NewSHL.getNode());
4063 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4069 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4070 // (and (srl x, (sub c1, c2), MASK)
4071 // Only fold this if the inner shift has no other uses -- if it does, folding
4072 // this will increase the total number of instructions.
4073 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4074 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4075 uint64_t c1 = N0C1->getZExtValue();
4076 if (c1 < OpSizeInBits) {
4077 uint64_t c2 = N1C->getZExtValue();
4078 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4081 Mask = Mask.shl(c2 - c1);
4082 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4083 DAG.getConstant(c2 - c1, N1.getValueType()));
4085 Mask = Mask.lshr(c1 - c2);
4086 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4087 DAG.getConstant(c1 - c2, N1.getValueType()));
4089 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4090 DAG.getConstant(Mask, VT));
4094 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4095 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4096 unsigned BitSize = VT.getScalarSizeInBits();
4097 SDValue HiBitsMask =
4098 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4099 BitSize - N1C->getZExtValue()), VT);
4100 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4105 SDValue NewSHL = visitShiftByConstant(N, N1C);
4106 if (NewSHL.getNode())
4113 SDValue DAGCombiner::visitSRA(SDNode *N) {
4114 SDValue N0 = N->getOperand(0);
4115 SDValue N1 = N->getOperand(1);
4116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4118 EVT VT = N0.getValueType();
4119 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4122 if (VT.isVector()) {
4123 SDValue FoldedVOp = SimplifyVBinOp(N);
4124 if (FoldedVOp.getNode()) return FoldedVOp;
4126 N1C = isConstOrConstSplat(N1);
4129 // fold (sra c1, c2) -> (sra c1, c2)
4131 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4132 // fold (sra 0, x) -> 0
4133 if (N0C && N0C->isNullValue())
4135 // fold (sra -1, x) -> -1
4136 if (N0C && N0C->isAllOnesValue())
4138 // fold (sra x, (setge c, size(x))) -> undef
4139 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4140 return DAG.getUNDEF(VT);
4141 // fold (sra x, 0) -> x
4142 if (N1C && N1C->isNullValue())
4144 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4146 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4147 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4148 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4150 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4151 ExtVT, VT.getVectorNumElements());
4152 if ((!LegalOperations ||
4153 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4154 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4155 N0.getOperand(0), DAG.getValueType(ExtVT));
4158 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4159 if (N1C && N0.getOpcode() == ISD::SRA) {
4160 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4161 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4162 if (Sum >= OpSizeInBits)
4163 Sum = OpSizeInBits - 1;
4164 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4165 DAG.getConstant(Sum, N1.getValueType()));
4169 // fold (sra (shl X, m), (sub result_size, n))
4170 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4171 // result_size - n != m.
4172 // If truncate is free for the target sext(shl) is likely to result in better
4174 if (N0.getOpcode() == ISD::SHL && N1C) {
4175 // Get the two constanst of the shifts, CN0 = m, CN = n.
4176 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4178 LLVMContext &Ctx = *DAG.getContext();
4179 // Determine what the truncate's result bitsize and type would be.
4180 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4183 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4185 // Determine the residual right-shift amount.
4186 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4188 // If the shift is not a no-op (in which case this should be just a sign
4189 // extend already), the truncated to type is legal, sign_extend is legal
4190 // on that type, and the truncate to that type is both legal and free,
4191 // perform the transform.
4192 if ((ShiftAmt > 0) &&
4193 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4194 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4195 TLI.isTruncateFree(VT, TruncVT)) {
4197 SDValue Amt = DAG.getConstant(ShiftAmt,
4198 getShiftAmountTy(N0.getOperand(0).getValueType()));
4199 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4200 N0.getOperand(0), Amt);
4201 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4203 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4204 N->getValueType(0), Trunc);
4209 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4210 if (N1.getOpcode() == ISD::TRUNCATE &&
4211 N1.getOperand(0).getOpcode() == ISD::AND) {
4212 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4213 if (NewOp1.getNode())
4214 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4217 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4218 // if c1 is equal to the number of bits the trunc removes
4219 if (N0.getOpcode() == ISD::TRUNCATE &&
4220 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4221 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4222 N0.getOperand(0).hasOneUse() &&
4223 N0.getOperand(0).getOperand(1).hasOneUse() &&
4225 SDValue N0Op0 = N0.getOperand(0);
4226 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4227 unsigned LargeShiftVal = LargeShift->getZExtValue();
4228 EVT LargeVT = N0Op0.getValueType();
4230 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4232 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4233 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4234 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4235 N0Op0.getOperand(0), Amt);
4236 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4241 // Simplify, based on bits shifted out of the LHS.
4242 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4243 return SDValue(N, 0);
4246 // If the sign bit is known to be zero, switch this to a SRL.
4247 if (DAG.SignBitIsZero(N0))
4248 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4251 SDValue NewSRA = visitShiftByConstant(N, N1C);
4252 if (NewSRA.getNode())
4259 SDValue DAGCombiner::visitSRL(SDNode *N) {
4260 SDValue N0 = N->getOperand(0);
4261 SDValue N1 = N->getOperand(1);
4262 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4263 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4264 EVT VT = N0.getValueType();
4265 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4268 if (VT.isVector()) {
4269 SDValue FoldedVOp = SimplifyVBinOp(N);
4270 if (FoldedVOp.getNode()) return FoldedVOp;
4272 N1C = isConstOrConstSplat(N1);
4275 // fold (srl c1, c2) -> c1 >>u c2
4277 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4278 // fold (srl 0, x) -> 0
4279 if (N0C && N0C->isNullValue())
4281 // fold (srl x, c >= size(x)) -> undef
4282 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4283 return DAG.getUNDEF(VT);
4284 // fold (srl x, 0) -> x
4285 if (N1C && N1C->isNullValue())
4287 // if (srl x, c) is known to be zero, return 0
4288 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4289 APInt::getAllOnesValue(OpSizeInBits)))
4290 return DAG.getConstant(0, VT);
4292 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4293 if (N1C && N0.getOpcode() == ISD::SRL) {
4294 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4295 uint64_t c1 = N01C->getZExtValue();
4296 uint64_t c2 = N1C->getZExtValue();
4297 if (c1 + c2 >= OpSizeInBits)
4298 return DAG.getConstant(0, VT);
4299 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4300 DAG.getConstant(c1 + c2, N1.getValueType()));
4304 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4305 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4306 N0.getOperand(0).getOpcode() == ISD::SRL &&
4307 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4309 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4310 uint64_t c2 = N1C->getZExtValue();
4311 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4312 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4313 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4314 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4315 if (c1 + OpSizeInBits == InnerShiftSize) {
4316 if (c1 + c2 >= InnerShiftSize)
4317 return DAG.getConstant(0, VT);
4318 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4319 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4320 N0.getOperand(0)->getOperand(0),
4321 DAG.getConstant(c1 + c2, ShiftCountVT)));
4325 // fold (srl (shl x, c), c) -> (and x, cst2)
4326 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4327 unsigned BitSize = N0.getScalarValueSizeInBits();
4328 if (BitSize <= 64) {
4329 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4330 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4331 DAG.getConstant(~0ULL >> ShAmt, VT));
4335 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4336 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4337 // Shifting in all undef bits?
4338 EVT SmallVT = N0.getOperand(0).getValueType();
4339 unsigned BitSize = SmallVT.getScalarSizeInBits();
4340 if (N1C->getZExtValue() >= BitSize)
4341 return DAG.getUNDEF(VT);
4343 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4344 uint64_t ShiftAmt = N1C->getZExtValue();
4345 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4347 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4348 AddToWorkList(SmallShift.getNode());
4349 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4350 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4351 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4352 DAG.getConstant(Mask, VT));
4356 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4357 // bit, which is unmodified by sra.
4358 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4359 if (N0.getOpcode() == ISD::SRA)
4360 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4363 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4364 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4365 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4366 APInt KnownZero, KnownOne;
4367 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4369 // If any of the input bits are KnownOne, then the input couldn't be all
4370 // zeros, thus the result of the srl will always be zero.
4371 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4373 // If all of the bits input the to ctlz node are known to be zero, then
4374 // the result of the ctlz is "32" and the result of the shift is one.
4375 APInt UnknownBits = ~KnownZero;
4376 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4378 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4379 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4380 // Okay, we know that only that the single bit specified by UnknownBits
4381 // could be set on input to the CTLZ node. If this bit is set, the SRL
4382 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4383 // to an SRL/XOR pair, which is likely to simplify more.
4384 unsigned ShAmt = UnknownBits.countTrailingZeros();
4385 SDValue Op = N0.getOperand(0);
4388 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4389 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4390 AddToWorkList(Op.getNode());
4393 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4394 Op, DAG.getConstant(1, VT));
4398 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4399 if (N1.getOpcode() == ISD::TRUNCATE &&
4400 N1.getOperand(0).getOpcode() == ISD::AND) {
4401 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4402 if (NewOp1.getNode())
4403 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4406 // fold operands of srl based on knowledge that the low bits are not
4408 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4409 return SDValue(N, 0);
4412 SDValue NewSRL = visitShiftByConstant(N, N1C);
4413 if (NewSRL.getNode())
4417 // Attempt to convert a srl of a load into a narrower zero-extending load.
4418 SDValue NarrowLoad = ReduceLoadWidth(N);
4419 if (NarrowLoad.getNode())
4422 // Here is a common situation. We want to optimize:
4425 // %b = and i32 %a, 2
4426 // %c = srl i32 %b, 1
4427 // brcond i32 %c ...
4433 // %c = setcc eq %b, 0
4436 // However when after the source operand of SRL is optimized into AND, the SRL
4437 // itself may not be optimized further. Look for it and add the BRCOND into
4439 if (N->hasOneUse()) {
4440 SDNode *Use = *N->use_begin();
4441 if (Use->getOpcode() == ISD::BRCOND)
4443 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4444 // Also look pass the truncate.
4445 Use = *Use->use_begin();
4446 if (Use->getOpcode() == ISD::BRCOND)
4454 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4455 SDValue N0 = N->getOperand(0);
4456 EVT VT = N->getValueType(0);
4458 // fold (ctlz c1) -> c2
4459 if (isa<ConstantSDNode>(N0))
4460 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4464 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4465 SDValue N0 = N->getOperand(0);
4466 EVT VT = N->getValueType(0);
4468 // fold (ctlz_zero_undef c1) -> c2
4469 if (isa<ConstantSDNode>(N0))
4470 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4474 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4475 SDValue N0 = N->getOperand(0);
4476 EVT VT = N->getValueType(0);
4478 // fold (cttz c1) -> c2
4479 if (isa<ConstantSDNode>(N0))
4480 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4484 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4485 SDValue N0 = N->getOperand(0);
4486 EVT VT = N->getValueType(0);
4488 // fold (cttz_zero_undef c1) -> c2
4489 if (isa<ConstantSDNode>(N0))
4490 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4494 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4495 SDValue N0 = N->getOperand(0);
4496 EVT VT = N->getValueType(0);
4498 // fold (ctpop c1) -> c2
4499 if (isa<ConstantSDNode>(N0))
4500 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4504 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4505 SDValue N0 = N->getOperand(0);
4506 SDValue N1 = N->getOperand(1);
4507 SDValue N2 = N->getOperand(2);
4508 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4510 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4511 EVT VT = N->getValueType(0);
4512 EVT VT0 = N0.getValueType();
4514 // fold (select C, X, X) -> X
4517 // fold (select true, X, Y) -> X
4518 if (N0C && !N0C->isNullValue())
4520 // fold (select false, X, Y) -> Y
4521 if (N0C && N0C->isNullValue())
4523 // fold (select C, 1, X) -> (or C, X)
4524 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4525 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4526 // fold (select C, 0, 1) -> (xor C, 1)
4527 // We can't do this reliably if integer based booleans have different contents
4528 // to floating point based booleans. This is because we can't tell whether we
4529 // have an integer-based boolean or a floating-point-based boolean unless we
4530 // can find the SETCC that produced it and inspect its operands. This is
4531 // fairly easy if C is the SETCC node, but it can potentially be
4532 // undiscoverable (or not reasonably discoverable). For example, it could be
4533 // in another basic block or it could require searching a complicated
4535 if (VT.isInteger() &&
4536 (VT0 == MVT::i1 || (VT0.isInteger() &&
4537 TLI.getBooleanContents(false, false) ==
4538 TLI.getBooleanContents(false, true) &&
4539 TLI.getBooleanContents(false, false) ==
4540 TargetLowering::ZeroOrOneBooleanContent)) &&
4541 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4544 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4545 N0, DAG.getConstant(1, VT0));
4546 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4547 N0, DAG.getConstant(1, VT0));
4548 AddToWorkList(XORNode.getNode());
4550 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4551 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4553 // fold (select C, 0, X) -> (and (not C), X)
4554 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4555 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4556 AddToWorkList(NOTNode.getNode());
4557 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4559 // fold (select C, X, 1) -> (or (not C), X)
4560 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4561 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4562 AddToWorkList(NOTNode.getNode());
4563 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4565 // fold (select C, X, 0) -> (and C, X)
4566 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4567 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4568 // fold (select X, X, Y) -> (or X, Y)
4569 // fold (select X, 1, Y) -> (or X, Y)
4570 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4571 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4572 // fold (select X, Y, X) -> (and X, Y)
4573 // fold (select X, Y, 0) -> (and X, Y)
4574 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4575 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4577 // If we can fold this based on the true/false value, do so.
4578 if (SimplifySelectOps(N, N1, N2))
4579 return SDValue(N, 0); // Don't revisit N.
4581 // fold selects based on a setcc into other things, such as min/max/abs
4582 if (N0.getOpcode() == ISD::SETCC) {
4583 if ((!LegalOperations &&
4584 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4585 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4586 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4587 N0.getOperand(0), N0.getOperand(1),
4588 N1, N2, N0.getOperand(2));
4589 return SimplifySelect(SDLoc(N), N0, N1, N2);
4596 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4599 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4601 // Split the inputs.
4602 SDValue Lo, Hi, LL, LH, RL, RH;
4603 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4604 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4606 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4607 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4609 return std::make_pair(Lo, Hi);
4612 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4613 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4614 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4616 SDValue Cond = N->getOperand(0);
4617 SDValue LHS = N->getOperand(1);
4618 SDValue RHS = N->getOperand(2);
4619 MVT VT = N->getSimpleValueType(0);
4620 int NumElems = VT.getVectorNumElements();
4621 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4622 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4623 Cond.getOpcode() == ISD::BUILD_VECTOR);
4625 // We're sure we have an even number of elements due to the
4626 // concat_vectors we have as arguments to vselect.
4627 // Skip BV elements until we find one that's not an UNDEF
4628 // After we find an UNDEF element, keep looping until we get to half the
4629 // length of the BV and see if all the non-undef nodes are the same.
4630 ConstantSDNode *BottomHalf = nullptr;
4631 for (int i = 0; i < NumElems / 2; ++i) {
4632 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4635 if (BottomHalf == nullptr)
4636 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4637 else if (Cond->getOperand(i).getNode() != BottomHalf)
4641 // Do the same for the second half of the BuildVector
4642 ConstantSDNode *TopHalf = nullptr;
4643 for (int i = NumElems / 2; i < NumElems; ++i) {
4644 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4647 if (TopHalf == nullptr)
4648 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4649 else if (Cond->getOperand(i).getNode() != TopHalf)
4653 assert(TopHalf && BottomHalf &&
4654 "One half of the selector was all UNDEFs and the other was all the "
4655 "same value. This should have been addressed before this function.");
4657 ISD::CONCAT_VECTORS, dl, VT,
4658 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4659 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4662 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4663 SDValue N0 = N->getOperand(0);
4664 SDValue N1 = N->getOperand(1);
4665 SDValue N2 = N->getOperand(2);
4668 // Canonicalize integer abs.
4669 // vselect (setg[te] X, 0), X, -X ->
4670 // vselect (setgt X, -1), X, -X ->
4671 // vselect (setl[te] X, 0), -X, X ->
4672 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4673 if (N0.getOpcode() == ISD::SETCC) {
4674 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4675 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4677 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4679 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4680 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4681 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4682 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4683 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4684 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4685 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4688 EVT VT = LHS.getValueType();
4689 SDValue Shift = DAG.getNode(
4690 ISD::SRA, DL, VT, LHS,
4691 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4692 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4693 AddToWorkList(Shift.getNode());
4694 AddToWorkList(Add.getNode());
4695 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4699 // If the VSELECT result requires splitting and the mask is provided by a
4700 // SETCC, then split both nodes and its operands before legalization. This
4701 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4702 // and enables future optimizations (e.g. min/max pattern matching on X86).
4703 if (N0.getOpcode() == ISD::SETCC) {
4704 EVT VT = N->getValueType(0);
4706 // Check if any splitting is required.
4707 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4708 TargetLowering::TypeSplitVector)
4711 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4712 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4713 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4714 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4716 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4717 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4719 // Add the new VSELECT nodes to the work list in case they need to be split
4721 AddToWorkList(Lo.getNode());
4722 AddToWorkList(Hi.getNode());
4724 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4727 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4728 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4730 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4731 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4734 // The ConvertSelectToConcatVector function is assuming both the above
4735 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4737 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4738 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4739 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4740 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4748 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4749 SDValue N0 = N->getOperand(0);
4750 SDValue N1 = N->getOperand(1);
4751 SDValue N2 = N->getOperand(2);
4752 SDValue N3 = N->getOperand(3);
4753 SDValue N4 = N->getOperand(4);
4754 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4756 // fold select_cc lhs, rhs, x, x, cc -> x
4760 // Determine if the condition we're dealing with is constant
4761 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4762 N0, N1, CC, SDLoc(N), false);
4763 if (SCC.getNode()) {
4764 AddToWorkList(SCC.getNode());
4766 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4767 if (!SCCC->isNullValue())
4768 return N2; // cond always true -> true val
4770 return N3; // cond always false -> false val
4773 // Fold to a simpler select_cc
4774 if (SCC.getOpcode() == ISD::SETCC)
4775 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4776 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4780 // If we can fold this based on the true/false value, do so.
4781 if (SimplifySelectOps(N, N2, N3))
4782 return SDValue(N, 0); // Don't revisit N.
4784 // fold select_cc into other things, such as min/max/abs
4785 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4788 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4789 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4790 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4794 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4795 // dag node into a ConstantSDNode or a build_vector of constants.
4796 // This function is called by the DAGCombiner when visiting sext/zext/aext
4797 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4798 // Vector extends are not folded if operations are legal; this is to
4799 // avoid introducing illegal build_vector dag nodes.
4800 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4801 SelectionDAG &DAG, bool LegalTypes,
4802 bool LegalOperations) {
4803 unsigned Opcode = N->getOpcode();
4804 SDValue N0 = N->getOperand(0);
4805 EVT VT = N->getValueType(0);
4807 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4808 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4810 // fold (sext c1) -> c1
4811 // fold (zext c1) -> c1
4812 // fold (aext c1) -> c1
4813 if (isa<ConstantSDNode>(N0))
4814 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4816 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4817 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4818 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4819 EVT SVT = VT.getScalarType();
4820 if (!(VT.isVector() &&
4821 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4822 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4825 // We can fold this node into a build_vector.
4826 unsigned VTBits = SVT.getSizeInBits();
4827 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4828 unsigned ShAmt = VTBits - EVTBits;
4829 SmallVector<SDValue, 8> Elts;
4830 unsigned NumElts = N0->getNumOperands();
4833 for (unsigned i=0; i != NumElts; ++i) {
4834 SDValue Op = N0->getOperand(i);
4835 if (Op->getOpcode() == ISD::UNDEF) {
4836 Elts.push_back(DAG.getUNDEF(SVT));
4840 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4841 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4842 if (Opcode == ISD::SIGN_EXTEND)
4843 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4846 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4850 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4853 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4854 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4855 // transformation. Returns true if extension are possible and the above
4856 // mentioned transformation is profitable.
4857 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4859 SmallVectorImpl<SDNode *> &ExtendNodes,
4860 const TargetLowering &TLI) {
4861 bool HasCopyToRegUses = false;
4862 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4863 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4864 UE = N0.getNode()->use_end();
4869 if (UI.getUse().getResNo() != N0.getResNo())
4871 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4872 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4873 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4874 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4875 // Sign bits will be lost after a zext.
4878 for (unsigned i = 0; i != 2; ++i) {
4879 SDValue UseOp = User->getOperand(i);
4882 if (!isa<ConstantSDNode>(UseOp))
4887 ExtendNodes.push_back(User);
4890 // If truncates aren't free and there are users we can't
4891 // extend, it isn't worthwhile.
4894 // Remember if this value is live-out.
4895 if (User->getOpcode() == ISD::CopyToReg)
4896 HasCopyToRegUses = true;
4899 if (HasCopyToRegUses) {
4900 bool BothLiveOut = false;
4901 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4903 SDUse &Use = UI.getUse();
4904 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4910 // Both unextended and extended values are live out. There had better be
4911 // a good reason for the transformation.
4912 return ExtendNodes.size();
4917 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4918 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4919 ISD::NodeType ExtType) {
4920 // Extend SetCC uses if necessary.
4921 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4922 SDNode *SetCC = SetCCs[i];
4923 SmallVector<SDValue, 4> Ops;
4925 for (unsigned j = 0; j != 2; ++j) {
4926 SDValue SOp = SetCC->getOperand(j);
4928 Ops.push_back(ExtLoad);
4930 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4933 Ops.push_back(SetCC->getOperand(2));
4934 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4938 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4939 SDValue N0 = N->getOperand(0);
4940 EVT VT = N->getValueType(0);
4942 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4944 return SDValue(Res, 0);
4946 // fold (sext (sext x)) -> (sext x)
4947 // fold (sext (aext x)) -> (sext x)
4948 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4949 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4952 if (N0.getOpcode() == ISD::TRUNCATE) {
4953 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4954 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4955 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4956 if (NarrowLoad.getNode()) {
4957 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4958 if (NarrowLoad.getNode() != N0.getNode()) {
4959 CombineTo(N0.getNode(), NarrowLoad);
4960 // CombineTo deleted the truncate, if needed, but not what's under it.
4963 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4966 // See if the value being truncated is already sign extended. If so, just
4967 // eliminate the trunc/sext pair.
4968 SDValue Op = N0.getOperand(0);
4969 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4970 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4971 unsigned DestBits = VT.getScalarType().getSizeInBits();
4972 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4974 if (OpBits == DestBits) {
4975 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4976 // bits, it is already ready.
4977 if (NumSignBits > DestBits-MidBits)
4979 } else if (OpBits < DestBits) {
4980 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4981 // bits, just sext from i32.
4982 if (NumSignBits > OpBits-MidBits)
4983 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4985 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4986 // bits, just truncate to i32.
4987 if (NumSignBits > OpBits-MidBits)
4988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4991 // fold (sext (truncate x)) -> (sextinreg x).
4992 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4993 N0.getValueType())) {
4994 if (OpBits < DestBits)
4995 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4996 else if (OpBits > DestBits)
4997 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4998 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4999 DAG.getValueType(N0.getValueType()));
5003 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5004 // None of the supported targets knows how to perform load and sign extend
5005 // on vectors in one instruction. We only perform this transformation on
5007 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5008 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5009 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5010 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5011 bool DoXform = true;
5012 SmallVector<SDNode*, 4> SetCCs;
5013 if (!N0.hasOneUse())
5014 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5016 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5017 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5019 LN0->getBasePtr(), N0.getValueType(),
5020 LN0->getMemOperand());
5021 CombineTo(N, ExtLoad);
5022 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5023 N0.getValueType(), ExtLoad);
5024 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5025 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5031 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5032 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5033 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5034 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5035 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5036 EVT MemVT = LN0->getMemoryVT();
5037 if ((!LegalOperations && !LN0->isVolatile()) ||
5038 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5039 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5041 LN0->getBasePtr(), MemVT,
5042 LN0->getMemOperand());
5043 CombineTo(N, ExtLoad);
5044 CombineTo(N0.getNode(),
5045 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5046 N0.getValueType(), ExtLoad),
5047 ExtLoad.getValue(1));
5048 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5052 // fold (sext (and/or/xor (load x), cst)) ->
5053 // (and/or/xor (sextload x), (sext cst))
5054 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5055 N0.getOpcode() == ISD::XOR) &&
5056 isa<LoadSDNode>(N0.getOperand(0)) &&
5057 N0.getOperand(1).getOpcode() == ISD::Constant &&
5058 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5059 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5060 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5061 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5062 bool DoXform = true;
5063 SmallVector<SDNode*, 4> SetCCs;
5064 if (!N0.hasOneUse())
5065 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5068 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5069 LN0->getChain(), LN0->getBasePtr(),
5071 LN0->getMemOperand());
5072 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5073 Mask = Mask.sext(VT.getSizeInBits());
5074 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5075 ExtLoad, DAG.getConstant(Mask, VT));
5076 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5077 SDLoc(N0.getOperand(0)),
5078 N0.getOperand(0).getValueType(), ExtLoad);
5080 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5081 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5088 if (N0.getOpcode() == ISD::SETCC) {
5089 EVT N0VT = N0.getOperand(0).getValueType();
5090 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5091 // Only do this before legalize for now.
5092 if (VT.isVector() && !LegalOperations &&
5093 TLI.getBooleanContents(N0VT) ==
5094 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5095 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5096 // of the same size as the compared operands. Only optimize sext(setcc())
5097 // if this is the case.
5098 EVT SVT = getSetCCResultType(N0VT);
5100 // We know that the # elements of the results is the same as the
5101 // # elements of the compare (and the # elements of the compare result
5102 // for that matter). Check to see that they are the same size. If so,
5103 // we know that the element size of the sext'd result matches the
5104 // element size of the compare operands.
5105 if (VT.getSizeInBits() == SVT.getSizeInBits())
5106 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5108 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5110 // If the desired elements are smaller or larger than the source
5111 // elements we can use a matching integer vector type and then
5112 // truncate/sign extend
5113 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5114 if (SVT == MatchingVectorType) {
5115 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5116 N0.getOperand(0), N0.getOperand(1),
5117 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5118 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5122 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5123 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5125 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5127 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5128 NegOne, DAG.getConstant(0, VT),
5129 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5130 if (SCC.getNode()) return SCC;
5132 if (!VT.isVector()) {
5133 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5134 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5136 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5137 SDValue SetCC = DAG.getSetCC(DL,
5139 N0.getOperand(0), N0.getOperand(1), CC);
5140 EVT SelectVT = getSetCCResultType(VT);
5141 return DAG.getSelect(DL, VT,
5142 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5143 NegOne, DAG.getConstant(0, VT));
5149 // fold (sext x) -> (zext x) if the sign bit is known zero.
5150 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5151 DAG.SignBitIsZero(N0))
5152 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5157 // isTruncateOf - If N is a truncate of some other value, return true, record
5158 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5159 // This function computes KnownZero to avoid a duplicated call to
5160 // computeKnownBits in the caller.
5161 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5164 if (N->getOpcode() == ISD::TRUNCATE) {
5165 Op = N->getOperand(0);
5166 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5170 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5171 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5174 SDValue Op0 = N->getOperand(0);
5175 SDValue Op1 = N->getOperand(1);
5176 assert(Op0.getValueType() == Op1.getValueType());
5178 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5179 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5180 if (COp0 && COp0->isNullValue())
5182 else if (COp1 && COp1->isNullValue())
5187 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5189 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5195 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5196 SDValue N0 = N->getOperand(0);
5197 EVT VT = N->getValueType(0);
5199 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5201 return SDValue(Res, 0);
5203 // fold (zext (zext x)) -> (zext x)
5204 // fold (zext (aext x)) -> (zext x)
5205 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5206 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5209 // fold (zext (truncate x)) -> (zext x) or
5210 // (zext (truncate x)) -> (truncate x)
5211 // This is valid when the truncated bits of x are already zero.
5212 // FIXME: We should extend this to work for vectors too.
5215 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5216 APInt TruncatedBits =
5217 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5218 APInt(Op.getValueSizeInBits(), 0) :
5219 APInt::getBitsSet(Op.getValueSizeInBits(),
5220 N0.getValueSizeInBits(),
5221 std::min(Op.getValueSizeInBits(),
5222 VT.getSizeInBits()));
5223 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5224 if (VT.bitsGT(Op.getValueType()))
5225 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5226 if (VT.bitsLT(Op.getValueType()))
5227 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5233 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5234 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5235 if (N0.getOpcode() == ISD::TRUNCATE) {
5236 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5237 if (NarrowLoad.getNode()) {
5238 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5239 if (NarrowLoad.getNode() != N0.getNode()) {
5240 CombineTo(N0.getNode(), NarrowLoad);
5241 // CombineTo deleted the truncate, if needed, but not what's under it.
5244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5248 // fold (zext (truncate x)) -> (and x, mask)
5249 if (N0.getOpcode() == ISD::TRUNCATE &&
5250 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5252 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5253 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5254 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5255 if (NarrowLoad.getNode()) {
5256 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5257 if (NarrowLoad.getNode() != N0.getNode()) {
5258 CombineTo(N0.getNode(), NarrowLoad);
5259 // CombineTo deleted the truncate, if needed, but not what's under it.
5262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5265 SDValue Op = N0.getOperand(0);
5266 if (Op.getValueType().bitsLT(VT)) {
5267 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5268 AddToWorkList(Op.getNode());
5269 } else if (Op.getValueType().bitsGT(VT)) {
5270 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5271 AddToWorkList(Op.getNode());
5273 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5274 N0.getValueType().getScalarType());
5277 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5278 // if either of the casts is not free.
5279 if (N0.getOpcode() == ISD::AND &&
5280 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5281 N0.getOperand(1).getOpcode() == ISD::Constant &&
5282 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5283 N0.getValueType()) ||
5284 !TLI.isZExtFree(N0.getValueType(), VT))) {
5285 SDValue X = N0.getOperand(0).getOperand(0);
5286 if (X.getValueType().bitsLT(VT)) {
5287 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5288 } else if (X.getValueType().bitsGT(VT)) {
5289 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5291 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5292 Mask = Mask.zext(VT.getSizeInBits());
5293 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5294 X, DAG.getConstant(Mask, VT));
5297 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5298 // None of the supported targets knows how to perform load and vector_zext
5299 // on vectors in one instruction. We only perform this transformation on
5301 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5302 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5303 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5304 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5305 bool DoXform = true;
5306 SmallVector<SDNode*, 4> SetCCs;
5307 if (!N0.hasOneUse())
5308 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5310 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5311 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5313 LN0->getBasePtr(), N0.getValueType(),
5314 LN0->getMemOperand());
5315 CombineTo(N, ExtLoad);
5316 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5317 N0.getValueType(), ExtLoad);
5318 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5320 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5322 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5326 // fold (zext (and/or/xor (load x), cst)) ->
5327 // (and/or/xor (zextload x), (zext cst))
5328 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5329 N0.getOpcode() == ISD::XOR) &&
5330 isa<LoadSDNode>(N0.getOperand(0)) &&
5331 N0.getOperand(1).getOpcode() == ISD::Constant &&
5332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5333 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5334 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5335 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5336 bool DoXform = true;
5337 SmallVector<SDNode*, 4> SetCCs;
5338 if (!N0.hasOneUse())
5339 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5342 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5343 LN0->getChain(), LN0->getBasePtr(),
5345 LN0->getMemOperand());
5346 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5347 Mask = Mask.zext(VT.getSizeInBits());
5348 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5349 ExtLoad, DAG.getConstant(Mask, VT));
5350 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5351 SDLoc(N0.getOperand(0)),
5352 N0.getOperand(0).getValueType(), ExtLoad);
5354 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5355 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5357 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5362 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5363 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5364 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5365 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5366 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5367 EVT MemVT = LN0->getMemoryVT();
5368 if ((!LegalOperations && !LN0->isVolatile()) ||
5369 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5370 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5372 LN0->getBasePtr(), MemVT,
5373 LN0->getMemOperand());
5374 CombineTo(N, ExtLoad);
5375 CombineTo(N0.getNode(),
5376 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5378 ExtLoad.getValue(1));
5379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5383 if (N0.getOpcode() == ISD::SETCC) {
5384 if (!LegalOperations && VT.isVector() &&
5385 N0.getValueType().getVectorElementType() == MVT::i1) {
5386 EVT N0VT = N0.getOperand(0).getValueType();
5387 if (getSetCCResultType(N0VT) == N0.getValueType())
5390 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5391 // Only do this before legalize for now.
5392 EVT EltVT = VT.getVectorElementType();
5393 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5394 DAG.getConstant(1, EltVT));
5395 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5396 // We know that the # elements of the results is the same as the
5397 // # elements of the compare (and the # elements of the compare result
5398 // for that matter). Check to see that they are the same size. If so,
5399 // we know that the element size of the sext'd result matches the
5400 // element size of the compare operands.
5401 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5402 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5404 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5405 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5408 // If the desired elements are smaller or larger than the source
5409 // elements we can use a matching integer vector type and then
5410 // truncate/sign extend
5411 EVT MatchingElementType =
5412 EVT::getIntegerVT(*DAG.getContext(),
5413 N0VT.getScalarType().getSizeInBits());
5414 EVT MatchingVectorType =
5415 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5416 N0VT.getVectorNumElements());
5418 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5420 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5421 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5422 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5423 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5426 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5428 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5429 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5430 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5431 if (SCC.getNode()) return SCC;
5434 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5435 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5436 isa<ConstantSDNode>(N0.getOperand(1)) &&
5437 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5439 SDValue ShAmt = N0.getOperand(1);
5440 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5441 if (N0.getOpcode() == ISD::SHL) {
5442 SDValue InnerZExt = N0.getOperand(0);
5443 // If the original shl may be shifting out bits, do not perform this
5445 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5446 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5447 if (ShAmtVal > KnownZeroBits)
5453 // Ensure that the shift amount is wide enough for the shifted value.
5454 if (VT.getSizeInBits() >= 256)
5455 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5457 return DAG.getNode(N0.getOpcode(), DL, VT,
5458 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5465 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5466 SDValue N0 = N->getOperand(0);
5467 EVT VT = N->getValueType(0);
5469 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5471 return SDValue(Res, 0);
5473 // fold (aext (aext x)) -> (aext x)
5474 // fold (aext (zext x)) -> (zext x)
5475 // fold (aext (sext x)) -> (sext x)
5476 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5477 N0.getOpcode() == ISD::ZERO_EXTEND ||
5478 N0.getOpcode() == ISD::SIGN_EXTEND)
5479 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5481 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5482 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5483 if (N0.getOpcode() == ISD::TRUNCATE) {
5484 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5485 if (NarrowLoad.getNode()) {
5486 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5487 if (NarrowLoad.getNode() != N0.getNode()) {
5488 CombineTo(N0.getNode(), NarrowLoad);
5489 // CombineTo deleted the truncate, if needed, but not what's under it.
5492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5496 // fold (aext (truncate x))
5497 if (N0.getOpcode() == ISD::TRUNCATE) {
5498 SDValue TruncOp = N0.getOperand(0);
5499 if (TruncOp.getValueType() == VT)
5500 return TruncOp; // x iff x size == zext size.
5501 if (TruncOp.getValueType().bitsGT(VT))
5502 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5503 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5506 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5507 // if the trunc is not free.
5508 if (N0.getOpcode() == ISD::AND &&
5509 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5510 N0.getOperand(1).getOpcode() == ISD::Constant &&
5511 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5512 N0.getValueType())) {
5513 SDValue X = N0.getOperand(0).getOperand(0);
5514 if (X.getValueType().bitsLT(VT)) {
5515 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5516 } else if (X.getValueType().bitsGT(VT)) {
5517 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5519 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5520 Mask = Mask.zext(VT.getSizeInBits());
5521 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5522 X, DAG.getConstant(Mask, VT));
5525 // fold (aext (load x)) -> (aext (truncate (extload x)))
5526 // None of the supported targets knows how to perform load and any_ext
5527 // on vectors in one instruction. We only perform this transformation on
5529 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5530 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5531 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5532 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5533 bool DoXform = true;
5534 SmallVector<SDNode*, 4> SetCCs;
5535 if (!N0.hasOneUse())
5536 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5538 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5539 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5541 LN0->getBasePtr(), N0.getValueType(),
5542 LN0->getMemOperand());
5543 CombineTo(N, ExtLoad);
5544 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5545 N0.getValueType(), ExtLoad);
5546 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5547 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5549 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5553 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5554 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5555 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5556 if (N0.getOpcode() == ISD::LOAD &&
5557 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5559 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5560 ISD::LoadExtType ExtType = LN0->getExtensionType();
5561 EVT MemVT = LN0->getMemoryVT();
5562 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5563 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5564 VT, LN0->getChain(), LN0->getBasePtr(),
5565 MemVT, LN0->getMemOperand());
5566 CombineTo(N, ExtLoad);
5567 CombineTo(N0.getNode(),
5568 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5569 N0.getValueType(), ExtLoad),
5570 ExtLoad.getValue(1));
5571 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5575 if (N0.getOpcode() == ISD::SETCC) {
5577 // aext(setcc) -> vsetcc
5578 // aext(setcc) -> truncate(vsetcc)
5579 // aext(setcc) -> aext(vsetcc)
5580 // Only do this before legalize for now.
5581 if (VT.isVector() && !LegalOperations) {
5582 EVT N0VT = N0.getOperand(0).getValueType();
5583 // We know that the # elements of the results is the same as the
5584 // # elements of the compare (and the # elements of the compare result
5585 // for that matter). Check to see that they are the same size. If so,
5586 // we know that the element size of the sext'd result matches the
5587 // element size of the compare operands.
5588 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5589 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5591 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5592 // If the desired elements are smaller or larger than the source
5593 // elements we can use a matching integer vector type and then
5594 // truncate/any extend
5596 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5598 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5600 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5601 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5605 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5607 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5608 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5609 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5617 /// GetDemandedBits - See if the specified operand can be simplified with the
5618 /// knowledge that only the bits specified by Mask are used. If so, return the
5619 /// simpler operand, otherwise return a null SDValue.
5620 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5621 switch (V.getOpcode()) {
5623 case ISD::Constant: {
5624 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5625 assert(CV && "Const value should be ConstSDNode.");
5626 const APInt &CVal = CV->getAPIntValue();
5627 APInt NewVal = CVal & Mask;
5629 return DAG.getConstant(NewVal, V.getValueType());
5634 // If the LHS or RHS don't contribute bits to the or, drop them.
5635 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5636 return V.getOperand(1);
5637 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5638 return V.getOperand(0);
5641 // Only look at single-use SRLs.
5642 if (!V.getNode()->hasOneUse())
5644 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5645 // See if we can recursively simplify the LHS.
5646 unsigned Amt = RHSC->getZExtValue();
5648 // Watch out for shift count overflow though.
5649 if (Amt >= Mask.getBitWidth()) break;
5650 APInt NewMask = Mask << Amt;
5651 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5652 if (SimplifyLHS.getNode())
5653 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5654 SimplifyLHS, V.getOperand(1));
5660 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5661 /// bits and then truncated to a narrower type and where N is a multiple
5662 /// of number of bits of the narrower type, transform it to a narrower load
5663 /// from address + N / num of bits of new type. If the result is to be
5664 /// extended, also fold the extension to form a extending load.
5665 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5666 unsigned Opc = N->getOpcode();
5668 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5669 SDValue N0 = N->getOperand(0);
5670 EVT VT = N->getValueType(0);
5673 // This transformation isn't valid for vector loads.
5677 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5679 if (Opc == ISD::SIGN_EXTEND_INREG) {
5680 ExtType = ISD::SEXTLOAD;
5681 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5682 } else if (Opc == ISD::SRL) {
5683 // Another special-case: SRL is basically zero-extending a narrower value.
5684 ExtType = ISD::ZEXTLOAD;
5686 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5687 if (!N01) return SDValue();
5688 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5689 VT.getSizeInBits() - N01->getZExtValue());
5691 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5694 unsigned EVTBits = ExtVT.getSizeInBits();
5696 // Do not generate loads of non-round integer types since these can
5697 // be expensive (and would be wrong if the type is not byte sized).
5698 if (!ExtVT.isRound())
5702 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5703 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5704 ShAmt = N01->getZExtValue();
5705 // Is the shift amount a multiple of size of VT?
5706 if ((ShAmt & (EVTBits-1)) == 0) {
5707 N0 = N0.getOperand(0);
5708 // Is the load width a multiple of size of VT?
5709 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5713 // At this point, we must have a load or else we can't do the transform.
5714 if (!isa<LoadSDNode>(N0)) return SDValue();
5716 // Because a SRL must be assumed to *need* to zero-extend the high bits
5717 // (as opposed to anyext the high bits), we can't combine the zextload
5718 // lowering of SRL and an sextload.
5719 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5722 // If the shift amount is larger than the input type then we're not
5723 // accessing any of the loaded bytes. If the load was a zextload/extload
5724 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5725 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5730 // If the load is shifted left (and the result isn't shifted back right),
5731 // we can fold the truncate through the shift.
5732 unsigned ShLeftAmt = 0;
5733 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5734 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5735 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5736 ShLeftAmt = N01->getZExtValue();
5737 N0 = N0.getOperand(0);
5741 // If we haven't found a load, we can't narrow it. Don't transform one with
5742 // multiple uses, this would require adding a new load.
5743 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5746 // Don't change the width of a volatile load.
5747 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5748 if (LN0->isVolatile())
5751 // Verify that we are actually reducing a load width here.
5752 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5755 // For the transform to be legal, the load must produce only two values
5756 // (the value loaded and the chain). Don't transform a pre-increment
5757 // load, for example, which produces an extra value. Otherwise the
5758 // transformation is not equivalent, and the downstream logic to replace
5759 // uses gets things wrong.
5760 if (LN0->getNumValues() > 2)
5763 // If the load that we're shrinking is an extload and we're not just
5764 // discarding the extension we can't simply shrink the load. Bail.
5765 // TODO: It would be possible to merge the extensions in some cases.
5766 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5767 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5770 EVT PtrType = N0.getOperand(1).getValueType();
5772 if (PtrType == MVT::Untyped || PtrType.isExtended())
5773 // It's not possible to generate a constant of extended or untyped type.
5776 // For big endian targets, we need to adjust the offset to the pointer to
5777 // load the correct bytes.
5778 if (TLI.isBigEndian()) {
5779 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5780 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5781 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5784 uint64_t PtrOff = ShAmt / 8;
5785 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5786 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5787 PtrType, LN0->getBasePtr(),
5788 DAG.getConstant(PtrOff, PtrType));
5789 AddToWorkList(NewPtr.getNode());
5792 if (ExtType == ISD::NON_EXTLOAD)
5793 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5794 LN0->getPointerInfo().getWithOffset(PtrOff),
5795 LN0->isVolatile(), LN0->isNonTemporal(),
5796 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5798 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5799 LN0->getPointerInfo().getWithOffset(PtrOff),
5800 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5801 NewAlign, LN0->getTBAAInfo());
5803 // Replace the old load's chain with the new load's chain.
5804 WorkListRemover DeadNodes(*this);
5805 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5807 // Shift the result left, if we've swallowed a left shift.
5808 SDValue Result = Load;
5809 if (ShLeftAmt != 0) {
5810 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5811 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5813 // If the shift amount is as large as the result size (but, presumably,
5814 // no larger than the source) then the useful bits of the result are
5815 // zero; we can't simply return the shortened shift, because the result
5816 // of that operation is undefined.
5817 if (ShLeftAmt >= VT.getSizeInBits())
5818 Result = DAG.getConstant(0, VT);
5820 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5821 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5824 // Return the new loaded value.
5828 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5829 SDValue N0 = N->getOperand(0);
5830 SDValue N1 = N->getOperand(1);
5831 EVT VT = N->getValueType(0);
5832 EVT EVT = cast<VTSDNode>(N1)->getVT();
5833 unsigned VTBits = VT.getScalarType().getSizeInBits();
5834 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5836 // fold (sext_in_reg c1) -> c1
5837 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5838 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5840 // If the input is already sign extended, just drop the extension.
5841 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5844 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5845 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5846 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5847 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5848 N0.getOperand(0), N1);
5850 // fold (sext_in_reg (sext x)) -> (sext x)
5851 // fold (sext_in_reg (aext x)) -> (sext x)
5852 // if x is small enough.
5853 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5854 SDValue N00 = N0.getOperand(0);
5855 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5856 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5857 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5860 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5861 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5862 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5864 // fold operands of sext_in_reg based on knowledge that the top bits are not
5866 if (SimplifyDemandedBits(SDValue(N, 0)))
5867 return SDValue(N, 0);
5869 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5870 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5871 SDValue NarrowLoad = ReduceLoadWidth(N);
5872 if (NarrowLoad.getNode())
5875 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5876 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5877 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5878 if (N0.getOpcode() == ISD::SRL) {
5879 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5880 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5881 // We can turn this into an SRA iff the input to the SRL is already sign
5883 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5884 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5885 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5886 N0.getOperand(0), N0.getOperand(1));
5890 // fold (sext_inreg (extload x)) -> (sextload x)
5891 if (ISD::isEXTLoad(N0.getNode()) &&
5892 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5893 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5894 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5895 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5897 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5899 LN0->getBasePtr(), EVT,
5900 LN0->getMemOperand());
5901 CombineTo(N, ExtLoad);
5902 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5903 AddToWorkList(ExtLoad.getNode());
5904 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5906 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5907 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5909 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5910 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5911 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5915 LN0->getBasePtr(), EVT,
5916 LN0->getMemOperand());
5917 CombineTo(N, ExtLoad);
5918 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5922 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5923 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5924 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5925 N0.getOperand(1), false);
5926 if (BSwap.getNode())
5927 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5931 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5932 // into a build_vector.
5933 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5934 SmallVector<SDValue, 8> Elts;
5935 unsigned NumElts = N0->getNumOperands();
5936 unsigned ShAmt = VTBits - EVTBits;
5938 for (unsigned i = 0; i != NumElts; ++i) {
5939 SDValue Op = N0->getOperand(i);
5940 if (Op->getOpcode() == ISD::UNDEF) {
5945 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5946 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5947 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5948 Op.getValueType()));
5951 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5957 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5958 SDValue N0 = N->getOperand(0);
5959 EVT VT = N->getValueType(0);
5960 bool isLE = TLI.isLittleEndian();
5963 if (N0.getValueType() == N->getValueType(0))
5965 // fold (truncate c1) -> c1
5966 if (isa<ConstantSDNode>(N0))
5967 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5968 // fold (truncate (truncate x)) -> (truncate x)
5969 if (N0.getOpcode() == ISD::TRUNCATE)
5970 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5971 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5972 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5973 N0.getOpcode() == ISD::SIGN_EXTEND ||
5974 N0.getOpcode() == ISD::ANY_EXTEND) {
5975 if (N0.getOperand(0).getValueType().bitsLT(VT))
5976 // if the source is smaller than the dest, we still need an extend
5977 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5979 if (N0.getOperand(0).getValueType().bitsGT(VT))
5980 // if the source is larger than the dest, than we just need the truncate
5981 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5982 // if the source and dest are the same type, we can drop both the extend
5983 // and the truncate.
5984 return N0.getOperand(0);
5987 // Fold extract-and-trunc into a narrow extract. For example:
5988 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5989 // i32 y = TRUNCATE(i64 x)
5991 // v16i8 b = BITCAST (v2i64 val)
5992 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5994 // Note: We only run this optimization after type legalization (which often
5995 // creates this pattern) and before operation legalization after which
5996 // we need to be more careful about the vector instructions that we generate.
5997 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5998 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6000 EVT VecTy = N0.getOperand(0).getValueType();
6001 EVT ExTy = N0.getValueType();
6002 EVT TrTy = N->getValueType(0);
6004 unsigned NumElem = VecTy.getVectorNumElements();
6005 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6007 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6008 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6010 SDValue EltNo = N0->getOperand(1);
6011 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6012 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6013 EVT IndexTy = TLI.getVectorIdxTy();
6014 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6016 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6017 NVT, N0.getOperand(0));
6019 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6021 DAG.getConstant(Index, IndexTy));
6025 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6026 if (N0.getOpcode() == ISD::SELECT) {
6027 EVT SrcVT = N0.getValueType();
6028 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6029 TLI.isTruncateFree(SrcVT, VT)) {
6031 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6032 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6033 EVT SetCCVT = getSetCCResultType(VT);
6034 SDValue Cond = DAG.getSExtOrTrunc(N0.getOperand(0), SL, SetCCVT);
6035 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6039 // Fold a series of buildvector, bitcast, and truncate if possible.
6041 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6042 // (2xi32 (buildvector x, y)).
6043 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6044 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6045 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6046 N0.getOperand(0).hasOneUse()) {
6048 SDValue BuildVect = N0.getOperand(0);
6049 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6050 EVT TruncVecEltTy = VT.getVectorElementType();
6052 // Check that the element types match.
6053 if (BuildVectEltTy == TruncVecEltTy) {
6054 // Now we only need to compute the offset of the truncated elements.
6055 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6056 unsigned TruncVecNumElts = VT.getVectorNumElements();
6057 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6059 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6060 "Invalid number of elements");
6062 SmallVector<SDValue, 8> Opnds;
6063 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6064 Opnds.push_back(BuildVect.getOperand(i));
6066 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6070 // See if we can simplify the input to this truncate through knowledge that
6071 // only the low bits are being used.
6072 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6073 // Currently we only perform this optimization on scalars because vectors
6074 // may have different active low bits.
6075 if (!VT.isVector()) {
6077 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6078 VT.getSizeInBits()));
6079 if (Shorter.getNode())
6080 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6082 // fold (truncate (load x)) -> (smaller load x)
6083 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6084 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6085 SDValue Reduced = ReduceLoadWidth(N);
6086 if (Reduced.getNode())
6088 // Handle the case where the load remains an extending load even
6089 // after truncation.
6090 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6091 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6092 if (!LN0->isVolatile() &&
6093 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6094 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6095 VT, LN0->getChain(), LN0->getBasePtr(),
6097 LN0->getMemOperand());
6098 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6103 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6104 // where ... are all 'undef'.
6105 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6106 SmallVector<EVT, 8> VTs;
6109 unsigned NumDefs = 0;
6111 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6112 SDValue X = N0.getOperand(i);
6113 if (X.getOpcode() != ISD::UNDEF) {
6118 // Stop if more than one members are non-undef.
6121 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6122 VT.getVectorElementType(),
6123 X.getValueType().getVectorNumElements()));
6127 return DAG.getUNDEF(VT);
6130 assert(V.getNode() && "The single defined operand is empty!");
6131 SmallVector<SDValue, 8> Opnds;
6132 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6134 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6137 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6138 AddToWorkList(NV.getNode());
6139 Opnds.push_back(NV);
6141 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6145 // Simplify the operands using demanded-bits information.
6146 if (!VT.isVector() &&
6147 SimplifyDemandedBits(SDValue(N, 0)))
6148 return SDValue(N, 0);
6153 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6154 SDValue Elt = N->getOperand(i);
6155 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6156 return Elt.getNode();
6157 return Elt.getOperand(Elt.getResNo()).getNode();
6160 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6161 /// if load locations are consecutive.
6162 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6163 assert(N->getOpcode() == ISD::BUILD_PAIR);
6165 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6166 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6167 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6168 LD1->getAddressSpace() != LD2->getAddressSpace())
6170 EVT LD1VT = LD1->getValueType(0);
6172 if (ISD::isNON_EXTLoad(LD2) &&
6174 // If both are volatile this would reduce the number of volatile loads.
6175 // If one is volatile it might be ok, but play conservative and bail out.
6176 !LD1->isVolatile() &&
6177 !LD2->isVolatile() &&
6178 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6179 unsigned Align = LD1->getAlignment();
6180 unsigned NewAlign = TLI.getDataLayout()->
6181 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6183 if (NewAlign <= Align &&
6184 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6185 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6186 LD1->getBasePtr(), LD1->getPointerInfo(),
6187 false, false, false, Align);
6193 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6194 SDValue N0 = N->getOperand(0);
6195 EVT VT = N->getValueType(0);
6197 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6198 // Only do this before legalize, since afterward the target may be depending
6199 // on the bitconvert.
6200 // First check to see if this is all constant.
6202 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6204 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6206 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6207 assert(!DestEltVT.isVector() &&
6208 "Element type of vector ValueType must not be vector!");
6210 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6213 // If the input is a constant, let getNode fold it.
6214 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6215 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6216 if (Res.getNode() != N) {
6217 if (!LegalOperations ||
6218 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6221 // Folding it resulted in an illegal node, and it's too late to
6222 // do that. Clean up the old node and forego the transformation.
6223 // Ideally this won't happen very often, because instcombine
6224 // and the earlier dagcombine runs (where illegal nodes are
6225 // permitted) should have folded most of them already.
6226 DAG.DeleteNode(Res.getNode());
6230 // (conv (conv x, t1), t2) -> (conv x, t2)
6231 if (N0.getOpcode() == ISD::BITCAST)
6232 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6235 // fold (conv (load x)) -> (load (conv*)x)
6236 // If the resultant load doesn't need a higher alignment than the original!
6237 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6238 // Do not change the width of a volatile load.
6239 !cast<LoadSDNode>(N0)->isVolatile() &&
6240 // Do not remove the cast if the types differ in endian layout.
6241 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6242 TLI.hasBigEndianPartOrdering(VT) &&
6243 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6244 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6246 unsigned Align = TLI.getDataLayout()->
6247 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6248 unsigned OrigAlign = LN0->getAlignment();
6250 if (Align <= OrigAlign) {
6251 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6252 LN0->getBasePtr(), LN0->getPointerInfo(),
6253 LN0->isVolatile(), LN0->isNonTemporal(),
6254 LN0->isInvariant(), OrigAlign,
6255 LN0->getTBAAInfo());
6257 CombineTo(N0.getNode(),
6258 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6259 N0.getValueType(), Load),
6265 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6266 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6267 // This often reduces constant pool loads.
6268 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6269 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6270 N0.getNode()->hasOneUse() && VT.isInteger() &&
6271 !VT.isVector() && !N0.getValueType().isVector()) {
6272 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6274 AddToWorkList(NewConv.getNode());
6276 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6277 if (N0.getOpcode() == ISD::FNEG)
6278 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6279 NewConv, DAG.getConstant(SignBit, VT));
6280 assert(N0.getOpcode() == ISD::FABS);
6281 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6282 NewConv, DAG.getConstant(~SignBit, VT));
6285 // fold (bitconvert (fcopysign cst, x)) ->
6286 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6287 // Note that we don't handle (copysign x, cst) because this can always be
6288 // folded to an fneg or fabs.
6289 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6290 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6291 VT.isInteger() && !VT.isVector()) {
6292 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6293 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6294 if (isTypeLegal(IntXVT)) {
6295 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6296 IntXVT, N0.getOperand(1));
6297 AddToWorkList(X.getNode());
6299 // If X has a different width than the result/lhs, sext it or truncate it.
6300 unsigned VTWidth = VT.getSizeInBits();
6301 if (OrigXWidth < VTWidth) {
6302 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6303 AddToWorkList(X.getNode());
6304 } else if (OrigXWidth > VTWidth) {
6305 // To get the sign bit in the right place, we have to shift it right
6306 // before truncating.
6307 X = DAG.getNode(ISD::SRL, SDLoc(X),
6308 X.getValueType(), X,
6309 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6310 AddToWorkList(X.getNode());
6311 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6312 AddToWorkList(X.getNode());
6315 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6316 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6317 X, DAG.getConstant(SignBit, VT));
6318 AddToWorkList(X.getNode());
6320 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6321 VT, N0.getOperand(0));
6322 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6323 Cst, DAG.getConstant(~SignBit, VT));
6324 AddToWorkList(Cst.getNode());
6326 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6330 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6331 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6332 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6333 if (CombineLD.getNode())
6340 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6341 EVT VT = N->getValueType(0);
6342 return CombineConsecutiveLoads(N, VT);
6345 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6346 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6347 /// destination element value type.
6348 SDValue DAGCombiner::
6349 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6350 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6352 // If this is already the right type, we're done.
6353 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6355 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6356 unsigned DstBitSize = DstEltVT.getSizeInBits();
6358 // If this is a conversion of N elements of one type to N elements of another
6359 // type, convert each element. This handles FP<->INT cases.
6360 if (SrcBitSize == DstBitSize) {
6361 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6362 BV->getValueType(0).getVectorNumElements());
6364 // Due to the FP element handling below calling this routine recursively,
6365 // we can end up with a scalar-to-vector node here.
6366 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6367 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6368 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6369 DstEltVT, BV->getOperand(0)));
6371 SmallVector<SDValue, 8> Ops;
6372 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6373 SDValue Op = BV->getOperand(i);
6374 // If the vector element type is not legal, the BUILD_VECTOR operands
6375 // are promoted and implicitly truncated. Make that explicit here.
6376 if (Op.getValueType() != SrcEltVT)
6377 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6378 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6380 AddToWorkList(Ops.back().getNode());
6382 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6385 // Otherwise, we're growing or shrinking the elements. To avoid having to
6386 // handle annoying details of growing/shrinking FP values, we convert them to
6388 if (SrcEltVT.isFloatingPoint()) {
6389 // Convert the input float vector to a int vector where the elements are the
6391 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6392 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6393 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6397 // Now we know the input is an integer vector. If the output is a FP type,
6398 // convert to integer first, then to FP of the right size.
6399 if (DstEltVT.isFloatingPoint()) {
6400 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6401 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6402 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6404 // Next, convert to FP elements of the same size.
6405 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6408 // Okay, we know the src/dst types are both integers of differing types.
6409 // Handling growing first.
6410 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6411 if (SrcBitSize < DstBitSize) {
6412 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6414 SmallVector<SDValue, 8> Ops;
6415 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6416 i += NumInputsPerOutput) {
6417 bool isLE = TLI.isLittleEndian();
6418 APInt NewBits = APInt(DstBitSize, 0);
6419 bool EltIsUndef = true;
6420 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6421 // Shift the previously computed bits over.
6422 NewBits <<= SrcBitSize;
6423 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6424 if (Op.getOpcode() == ISD::UNDEF) continue;
6427 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6428 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6432 Ops.push_back(DAG.getUNDEF(DstEltVT));
6434 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6437 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6438 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6441 // Finally, this must be the case where we are shrinking elements: each input
6442 // turns into multiple outputs.
6443 bool isS2V = ISD::isScalarToVector(BV);
6444 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6445 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6446 NumOutputsPerInput*BV->getNumOperands());
6447 SmallVector<SDValue, 8> Ops;
6449 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6450 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6451 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6452 Ops.push_back(DAG.getUNDEF(DstEltVT));
6456 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6457 getAPIntValue().zextOrTrunc(SrcBitSize);
6459 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6460 APInt ThisVal = OpVal.trunc(DstBitSize);
6461 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6462 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6463 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6464 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6466 OpVal = OpVal.lshr(DstBitSize);
6469 // For big endian targets, swap the order of the pieces of each element.
6470 if (TLI.isBigEndian())
6471 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6474 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6477 SDValue DAGCombiner::visitFADD(SDNode *N) {
6478 SDValue N0 = N->getOperand(0);
6479 SDValue N1 = N->getOperand(1);
6480 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6481 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6482 EVT VT = N->getValueType(0);
6485 if (VT.isVector()) {
6486 SDValue FoldedVOp = SimplifyVBinOp(N);
6487 if (FoldedVOp.getNode()) return FoldedVOp;
6490 // fold (fadd c1, c2) -> c1 + c2
6492 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6493 // canonicalize constant to RHS
6494 if (N0CFP && !N1CFP)
6495 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6496 // fold (fadd A, 0) -> A
6497 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6498 N1CFP->getValueAPF().isZero())
6500 // fold (fadd A, (fneg B)) -> (fsub A, B)
6501 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6502 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6503 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6504 GetNegatedExpression(N1, DAG, LegalOperations));
6505 // fold (fadd (fneg A), B) -> (fsub B, A)
6506 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6507 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6508 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6509 GetNegatedExpression(N0, DAG, LegalOperations));
6511 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6512 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6513 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6514 isa<ConstantFPSDNode>(N0.getOperand(1)))
6515 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6516 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6517 N0.getOperand(1), N1));
6519 // No FP constant should be created after legalization as Instruction
6520 // Selection pass has hard time in dealing with FP constant.
6522 // We don't need test this condition for transformation like following, as
6523 // the DAG being transformed implies it is legal to take FP constant as
6526 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6528 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6530 // If allow, fold (fadd (fneg x), x) -> 0.0
6531 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6532 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6533 return DAG.getConstantFP(0.0, VT);
6535 // If allow, fold (fadd x, (fneg x)) -> 0.0
6536 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6537 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6538 return DAG.getConstantFP(0.0, VT);
6540 // In unsafe math mode, we can fold chains of FADD's of the same value
6541 // into multiplications. This transform is not safe in general because
6542 // we are reducing the number of rounding steps.
6543 if (DAG.getTarget().Options.UnsafeFPMath &&
6544 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6546 if (N0.getOpcode() == ISD::FMUL) {
6547 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6548 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6550 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6551 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6552 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6554 DAG.getConstantFP(1.0, VT));
6555 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6560 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6561 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563 DAG.getConstantFP(1.0, VT));
6564 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6568 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6569 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6570 N1.getOperand(0) == N1.getOperand(1) &&
6571 N0.getOperand(1) == N1.getOperand(0)) {
6572 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6574 DAG.getConstantFP(2.0, VT));
6575 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6576 N0.getOperand(1), NewCFP);
6579 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6580 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6581 N1.getOperand(0) == N1.getOperand(1) &&
6582 N0.getOperand(0) == N1.getOperand(0)) {
6583 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6585 DAG.getConstantFP(2.0, VT));
6586 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6587 N0.getOperand(0), NewCFP);
6591 if (N1.getOpcode() == ISD::FMUL) {
6592 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6593 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6595 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6596 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6599 DAG.getConstantFP(1.0, VT));
6600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6604 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6605 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6606 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6608 DAG.getConstantFP(1.0, VT));
6609 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6614 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6615 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6616 N0.getOperand(0) == N0.getOperand(1) &&
6617 N1.getOperand(1) == N0.getOperand(0)) {
6618 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620 DAG.getConstantFP(2.0, VT));
6621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622 N1.getOperand(1), NewCFP);
6625 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6626 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6627 N0.getOperand(0) == N0.getOperand(1) &&
6628 N1.getOperand(0) == N0.getOperand(0)) {
6629 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6631 DAG.getConstantFP(2.0, VT));
6632 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633 N1.getOperand(0), NewCFP);
6637 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6638 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6639 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6640 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6641 (N0.getOperand(0) == N1))
6642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6643 N1, DAG.getConstantFP(3.0, VT));
6646 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6647 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6648 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6649 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6650 N1.getOperand(0) == N0)
6651 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6652 N0, DAG.getConstantFP(3.0, VT));
6655 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6656 if (AllowNewFpConst &&
6657 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6658 N0.getOperand(0) == N0.getOperand(1) &&
6659 N1.getOperand(0) == N1.getOperand(1) &&
6660 N0.getOperand(0) == N1.getOperand(0))
6661 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6663 DAG.getConstantFP(4.0, VT));
6666 // FADD -> FMA combines:
6667 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6668 DAG.getTarget().Options.UnsafeFPMath) &&
6669 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6670 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6672 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6673 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6674 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6675 N0.getOperand(0), N0.getOperand(1), N1);
6677 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6678 // Note: Commutes FADD operands.
6679 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6680 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6681 N1.getOperand(0), N1.getOperand(1), N0);
6687 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6688 SDValue N0 = N->getOperand(0);
6689 SDValue N1 = N->getOperand(1);
6690 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6691 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6692 EVT VT = N->getValueType(0);
6696 if (VT.isVector()) {
6697 SDValue FoldedVOp = SimplifyVBinOp(N);
6698 if (FoldedVOp.getNode()) return FoldedVOp;
6701 // fold (fsub c1, c2) -> c1-c2
6703 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6704 // fold (fsub A, 0) -> A
6705 if (DAG.getTarget().Options.UnsafeFPMath &&
6706 N1CFP && N1CFP->getValueAPF().isZero())
6708 // fold (fsub 0, B) -> -B
6709 if (DAG.getTarget().Options.UnsafeFPMath &&
6710 N0CFP && N0CFP->getValueAPF().isZero()) {
6711 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6712 return GetNegatedExpression(N1, DAG, LegalOperations);
6713 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6714 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6716 // fold (fsub A, (fneg B)) -> (fadd A, B)
6717 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6718 return DAG.getNode(ISD::FADD, dl, VT, N0,
6719 GetNegatedExpression(N1, DAG, LegalOperations));
6721 // If 'unsafe math' is enabled, fold
6722 // (fsub x, x) -> 0.0 &
6723 // (fsub x, (fadd x, y)) -> (fneg y) &
6724 // (fsub x, (fadd y, x)) -> (fneg y)
6725 if (DAG.getTarget().Options.UnsafeFPMath) {
6727 return DAG.getConstantFP(0.0f, VT);
6729 if (N1.getOpcode() == ISD::FADD) {
6730 SDValue N10 = N1->getOperand(0);
6731 SDValue N11 = N1->getOperand(1);
6733 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6734 &DAG.getTarget().Options))
6735 return GetNegatedExpression(N11, DAG, LegalOperations);
6737 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6738 &DAG.getTarget().Options))
6739 return GetNegatedExpression(N10, DAG, LegalOperations);
6743 // FSUB -> FMA combines:
6744 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6745 DAG.getTarget().Options.UnsafeFPMath) &&
6746 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6747 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6749 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6750 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6751 return DAG.getNode(ISD::FMA, dl, VT,
6752 N0.getOperand(0), N0.getOperand(1),
6753 DAG.getNode(ISD::FNEG, dl, VT, N1));
6755 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6756 // Note: Commutes FSUB operands.
6757 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6758 return DAG.getNode(ISD::FMA, dl, VT,
6759 DAG.getNode(ISD::FNEG, dl, VT,
6761 N1.getOperand(1), N0);
6763 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6764 if (N0.getOpcode() == ISD::FNEG &&
6765 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6766 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6767 SDValue N00 = N0.getOperand(0).getOperand(0);
6768 SDValue N01 = N0.getOperand(0).getOperand(1);
6769 return DAG.getNode(ISD::FMA, dl, VT,
6770 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6771 DAG.getNode(ISD::FNEG, dl, VT, N1));
6778 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6779 SDValue N0 = N->getOperand(0);
6780 SDValue N1 = N->getOperand(1);
6781 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6783 EVT VT = N->getValueType(0);
6784 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6787 if (VT.isVector()) {
6788 SDValue FoldedVOp = SimplifyVBinOp(N);
6789 if (FoldedVOp.getNode()) return FoldedVOp;
6792 // fold (fmul c1, c2) -> c1*c2
6794 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6795 // canonicalize constant to RHS
6796 if (N0CFP && !N1CFP)
6797 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6798 // fold (fmul A, 0) -> 0
6799 if (DAG.getTarget().Options.UnsafeFPMath &&
6800 N1CFP && N1CFP->getValueAPF().isZero())
6802 // fold (fmul A, 0) -> 0, vector edition.
6803 if (DAG.getTarget().Options.UnsafeFPMath &&
6804 ISD::isBuildVectorAllZeros(N1.getNode()))
6806 // fold (fmul A, 1.0) -> A
6807 if (N1CFP && N1CFP->isExactlyValue(1.0))
6809 // fold (fmul X, 2.0) -> (fadd X, X)
6810 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6811 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6812 // fold (fmul X, -1.0) -> (fneg X)
6813 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6814 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6815 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6817 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6818 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6819 &DAG.getTarget().Options)) {
6820 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6821 &DAG.getTarget().Options)) {
6822 // Both can be negated for free, check to see if at least one is cheaper
6824 if (LHSNeg == 2 || RHSNeg == 2)
6825 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6826 GetNegatedExpression(N0, DAG, LegalOperations),
6827 GetNegatedExpression(N1, DAG, LegalOperations));
6831 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6832 if (DAG.getTarget().Options.UnsafeFPMath &&
6833 N1CFP && N0.getOpcode() == ISD::FMUL &&
6834 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6835 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6836 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6837 N0.getOperand(1), N1));
6842 SDValue DAGCombiner::visitFMA(SDNode *N) {
6843 SDValue N0 = N->getOperand(0);
6844 SDValue N1 = N->getOperand(1);
6845 SDValue N2 = N->getOperand(2);
6846 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6847 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6848 EVT VT = N->getValueType(0);
6851 if (DAG.getTarget().Options.UnsafeFPMath) {
6852 if (N0CFP && N0CFP->isZero())
6854 if (N1CFP && N1CFP->isZero())
6857 if (N0CFP && N0CFP->isExactlyValue(1.0))
6858 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6859 if (N1CFP && N1CFP->isExactlyValue(1.0))
6860 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6862 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6863 if (N0CFP && !N1CFP)
6864 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6866 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6867 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6868 N2.getOpcode() == ISD::FMUL &&
6869 N0 == N2.getOperand(0) &&
6870 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6871 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6872 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6876 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6877 if (DAG.getTarget().Options.UnsafeFPMath &&
6878 N0.getOpcode() == ISD::FMUL && N1CFP &&
6879 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6880 return DAG.getNode(ISD::FMA, dl, VT,
6882 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6886 // (fma x, 1, y) -> (fadd x, y)
6887 // (fma x, -1, y) -> (fadd (fneg x), y)
6889 if (N1CFP->isExactlyValue(1.0))
6890 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6892 if (N1CFP->isExactlyValue(-1.0) &&
6893 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6894 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6895 AddToWorkList(RHSNeg.getNode());
6896 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6900 // (fma x, c, x) -> (fmul x, (c+1))
6901 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6902 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6903 DAG.getNode(ISD::FADD, dl, VT,
6904 N1, DAG.getConstantFP(1.0, VT)));
6906 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6907 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6908 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6909 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6910 DAG.getNode(ISD::FADD, dl, VT,
6911 N1, DAG.getConstantFP(-1.0, VT)));
6917 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6918 SDValue N0 = N->getOperand(0);
6919 SDValue N1 = N->getOperand(1);
6920 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6921 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6922 EVT VT = N->getValueType(0);
6923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6926 if (VT.isVector()) {
6927 SDValue FoldedVOp = SimplifyVBinOp(N);
6928 if (FoldedVOp.getNode()) return FoldedVOp;
6931 // fold (fdiv c1, c2) -> c1/c2
6933 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6935 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6936 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6937 // Compute the reciprocal 1.0 / c2.
6938 APFloat N1APF = N1CFP->getValueAPF();
6939 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6940 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6941 // Only do the transform if the reciprocal is a legal fp immediate that
6942 // isn't too nasty (eg NaN, denormal, ...).
6943 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6944 (!LegalOperations ||
6945 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6946 // backend)... we should handle this gracefully after Legalize.
6947 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6948 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6949 TLI.isFPImmLegal(Recip, VT)))
6950 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6951 DAG.getConstantFP(Recip, VT));
6954 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6955 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6956 &DAG.getTarget().Options)) {
6957 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6958 &DAG.getTarget().Options)) {
6959 // Both can be negated for free, check to see if at least one is cheaper
6961 if (LHSNeg == 2 || RHSNeg == 2)
6962 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6963 GetNegatedExpression(N0, DAG, LegalOperations),
6964 GetNegatedExpression(N1, DAG, LegalOperations));
6971 SDValue DAGCombiner::visitFREM(SDNode *N) {
6972 SDValue N0 = N->getOperand(0);
6973 SDValue N1 = N->getOperand(1);
6974 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6975 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6976 EVT VT = N->getValueType(0);
6978 // fold (frem c1, c2) -> fmod(c1,c2)
6980 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6985 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6986 SDValue N0 = N->getOperand(0);
6987 SDValue N1 = N->getOperand(1);
6988 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6989 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6990 EVT VT = N->getValueType(0);
6992 if (N0CFP && N1CFP) // Constant fold
6993 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6996 const APFloat& V = N1CFP->getValueAPF();
6997 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6998 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6999 if (!V.isNegative()) {
7000 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7001 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7003 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7004 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7005 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7009 // copysign(fabs(x), y) -> copysign(x, y)
7010 // copysign(fneg(x), y) -> copysign(x, y)
7011 // copysign(copysign(x,z), y) -> copysign(x, y)
7012 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7013 N0.getOpcode() == ISD::FCOPYSIGN)
7014 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7015 N0.getOperand(0), N1);
7017 // copysign(x, abs(y)) -> abs(x)
7018 if (N1.getOpcode() == ISD::FABS)
7019 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7021 // copysign(x, copysign(y,z)) -> copysign(x, z)
7022 if (N1.getOpcode() == ISD::FCOPYSIGN)
7023 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7024 N0, N1.getOperand(1));
7026 // copysign(x, fp_extend(y)) -> copysign(x, y)
7027 // copysign(x, fp_round(y)) -> copysign(x, y)
7028 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7029 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7030 N0, N1.getOperand(0));
7035 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7036 SDValue N0 = N->getOperand(0);
7037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7038 EVT VT = N->getValueType(0);
7039 EVT OpVT = N0.getValueType();
7041 // fold (sint_to_fp c1) -> c1fp
7043 // ...but only if the target supports immediate floating-point values
7044 (!LegalOperations ||
7045 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7046 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7048 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7049 // but UINT_TO_FP is legal on this target, try to convert.
7050 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7051 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7052 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7053 if (DAG.SignBitIsZero(N0))
7054 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7057 // The next optimizations are desirable only if SELECT_CC can be lowered.
7058 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7059 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7060 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7062 (!LegalOperations ||
7063 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7065 { N0.getOperand(0), N0.getOperand(1),
7066 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7068 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7071 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7072 // (select_cc x, y, 1.0, 0.0,, cc)
7073 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7074 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7075 (!LegalOperations ||
7076 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7078 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7079 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7080 N0.getOperand(0).getOperand(2) };
7081 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7088 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7089 SDValue N0 = N->getOperand(0);
7090 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7091 EVT VT = N->getValueType(0);
7092 EVT OpVT = N0.getValueType();
7094 // fold (uint_to_fp c1) -> c1fp
7096 // ...but only if the target supports immediate floating-point values
7097 (!LegalOperations ||
7098 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7099 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7101 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7102 // but SINT_TO_FP is legal on this target, try to convert.
7103 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7104 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7105 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7106 if (DAG.SignBitIsZero(N0))
7107 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7110 // The next optimizations are desirable only if SELECT_CC can be lowered.
7111 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7112 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7114 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7115 (!LegalOperations ||
7116 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7118 { N0.getOperand(0), N0.getOperand(1),
7119 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7121 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7128 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7129 SDValue N0 = N->getOperand(0);
7130 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7131 EVT VT = N->getValueType(0);
7133 // fold (fp_to_sint c1fp) -> c1
7135 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7140 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7141 SDValue N0 = N->getOperand(0);
7142 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7143 EVT VT = N->getValueType(0);
7145 // fold (fp_to_uint c1fp) -> c1
7147 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7152 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7153 SDValue N0 = N->getOperand(0);
7154 SDValue N1 = N->getOperand(1);
7155 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7156 EVT VT = N->getValueType(0);
7158 // fold (fp_round c1fp) -> c1fp
7160 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7162 // fold (fp_round (fp_extend x)) -> x
7163 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7164 return N0.getOperand(0);
7166 // fold (fp_round (fp_round x)) -> (fp_round x)
7167 if (N0.getOpcode() == ISD::FP_ROUND) {
7168 // This is a value preserving truncation if both round's are.
7169 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7170 N0.getNode()->getConstantOperandVal(1) == 1;
7171 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7172 DAG.getIntPtrConstant(IsTrunc));
7175 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7176 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7177 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7178 N0.getOperand(0), N1);
7179 AddToWorkList(Tmp.getNode());
7180 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7181 Tmp, N0.getOperand(1));
7187 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7188 SDValue N0 = N->getOperand(0);
7189 EVT VT = N->getValueType(0);
7190 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7191 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7193 // fold (fp_round_inreg c1fp) -> c1fp
7194 if (N0CFP && isTypeLegal(EVT)) {
7195 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7196 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7202 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7203 SDValue N0 = N->getOperand(0);
7204 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7205 EVT VT = N->getValueType(0);
7207 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7208 if (N->hasOneUse() &&
7209 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7212 // fold (fp_extend c1fp) -> c1fp
7214 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7216 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7218 if (N0.getOpcode() == ISD::FP_ROUND
7219 && N0.getNode()->getConstantOperandVal(1) == 1) {
7220 SDValue In = N0.getOperand(0);
7221 if (In.getValueType() == VT) return In;
7222 if (VT.bitsLT(In.getValueType()))
7223 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7224 In, N0.getOperand(1));
7225 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7228 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7229 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7230 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7231 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7232 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7233 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7235 LN0->getBasePtr(), N0.getValueType(),
7236 LN0->getMemOperand());
7237 CombineTo(N, ExtLoad);
7238 CombineTo(N0.getNode(),
7239 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7240 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7241 ExtLoad.getValue(1));
7242 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7248 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7249 SDValue N0 = N->getOperand(0);
7250 EVT VT = N->getValueType(0);
7252 if (VT.isVector()) {
7253 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7254 if (FoldedVOp.getNode()) return FoldedVOp;
7257 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7258 &DAG.getTarget().Options))
7259 return GetNegatedExpression(N0, DAG, LegalOperations);
7261 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7262 // constant pool values.
7263 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7265 N0.getNode()->hasOneUse() &&
7266 N0.getOperand(0).getValueType().isInteger()) {
7267 SDValue Int = N0.getOperand(0);
7268 EVT IntVT = Int.getValueType();
7269 if (IntVT.isInteger() && !IntVT.isVector()) {
7270 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7271 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7272 AddToWorkList(Int.getNode());
7273 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7278 // (fneg (fmul c, x)) -> (fmul -c, x)
7279 if (N0.getOpcode() == ISD::FMUL) {
7280 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7282 APFloat CVal = CFP1->getValueAPF();
7284 if (Level >= AfterLegalizeDAG &&
7285 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7286 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7288 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7289 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7296 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7297 SDValue N0 = N->getOperand(0);
7298 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7299 EVT VT = N->getValueType(0);
7301 // fold (fceil c1) -> fceil(c1)
7303 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7308 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7309 SDValue N0 = N->getOperand(0);
7310 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7311 EVT VT = N->getValueType(0);
7313 // fold (ftrunc c1) -> ftrunc(c1)
7315 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7320 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7321 SDValue N0 = N->getOperand(0);
7322 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7323 EVT VT = N->getValueType(0);
7325 // fold (ffloor c1) -> ffloor(c1)
7327 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7332 SDValue DAGCombiner::visitFABS(SDNode *N) {
7333 SDValue N0 = N->getOperand(0);
7334 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7335 EVT VT = N->getValueType(0);
7337 if (VT.isVector()) {
7338 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7339 if (FoldedVOp.getNode()) return FoldedVOp;
7342 // fold (fabs c1) -> fabs(c1)
7344 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7345 // fold (fabs (fabs x)) -> (fabs x)
7346 if (N0.getOpcode() == ISD::FABS)
7347 return N->getOperand(0);
7348 // fold (fabs (fneg x)) -> (fabs x)
7349 // fold (fabs (fcopysign x, y)) -> (fabs x)
7350 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7351 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7353 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7354 // constant pool values.
7355 if (!TLI.isFAbsFree(VT) &&
7356 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7357 N0.getOperand(0).getValueType().isInteger() &&
7358 !N0.getOperand(0).getValueType().isVector()) {
7359 SDValue Int = N0.getOperand(0);
7360 EVT IntVT = Int.getValueType();
7361 if (IntVT.isInteger() && !IntVT.isVector()) {
7362 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7363 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7364 AddToWorkList(Int.getNode());
7365 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7366 N->getValueType(0), Int);
7373 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7374 SDValue Chain = N->getOperand(0);
7375 SDValue N1 = N->getOperand(1);
7376 SDValue N2 = N->getOperand(2);
7378 // If N is a constant we could fold this into a fallthrough or unconditional
7379 // branch. However that doesn't happen very often in normal code, because
7380 // Instcombine/SimplifyCFG should have handled the available opportunities.
7381 // If we did this folding here, it would be necessary to update the
7382 // MachineBasicBlock CFG, which is awkward.
7384 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7386 if (N1.getOpcode() == ISD::SETCC &&
7387 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7388 N1.getOperand(0).getValueType())) {
7389 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7390 Chain, N1.getOperand(2),
7391 N1.getOperand(0), N1.getOperand(1), N2);
7394 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7395 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7396 (N1.getOperand(0).hasOneUse() &&
7397 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7398 SDNode *Trunc = nullptr;
7399 if (N1.getOpcode() == ISD::TRUNCATE) {
7400 // Look pass the truncate.
7401 Trunc = N1.getNode();
7402 N1 = N1.getOperand(0);
7405 // Match this pattern so that we can generate simpler code:
7408 // %b = and i32 %a, 2
7409 // %c = srl i32 %b, 1
7410 // brcond i32 %c ...
7415 // %b = and i32 %a, 2
7416 // %c = setcc eq %b, 0
7419 // This applies only when the AND constant value has one bit set and the
7420 // SRL constant is equal to the log2 of the AND constant. The back-end is
7421 // smart enough to convert the result into a TEST/JMP sequence.
7422 SDValue Op0 = N1.getOperand(0);
7423 SDValue Op1 = N1.getOperand(1);
7425 if (Op0.getOpcode() == ISD::AND &&
7426 Op1.getOpcode() == ISD::Constant) {
7427 SDValue AndOp1 = Op0.getOperand(1);
7429 if (AndOp1.getOpcode() == ISD::Constant) {
7430 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7432 if (AndConst.isPowerOf2() &&
7433 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7435 DAG.getSetCC(SDLoc(N),
7436 getSetCCResultType(Op0.getValueType()),
7437 Op0, DAG.getConstant(0, Op0.getValueType()),
7440 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7441 MVT::Other, Chain, SetCC, N2);
7442 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7443 // will convert it back to (X & C1) >> C2.
7444 CombineTo(N, NewBRCond, false);
7445 // Truncate is dead.
7447 removeFromWorkList(Trunc);
7448 DAG.DeleteNode(Trunc);
7450 // Replace the uses of SRL with SETCC
7451 WorkListRemover DeadNodes(*this);
7452 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7453 removeFromWorkList(N1.getNode());
7454 DAG.DeleteNode(N1.getNode());
7455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7461 // Restore N1 if the above transformation doesn't match.
7462 N1 = N->getOperand(1);
7465 // Transform br(xor(x, y)) -> br(x != y)
7466 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7467 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7468 SDNode *TheXor = N1.getNode();
7469 SDValue Op0 = TheXor->getOperand(0);
7470 SDValue Op1 = TheXor->getOperand(1);
7471 if (Op0.getOpcode() == Op1.getOpcode()) {
7472 // Avoid missing important xor optimizations.
7473 SDValue Tmp = visitXOR(TheXor);
7474 if (Tmp.getNode()) {
7475 if (Tmp.getNode() != TheXor) {
7476 DEBUG(dbgs() << "\nReplacing.8 ";
7478 dbgs() << "\nWith: ";
7479 Tmp.getNode()->dump(&DAG);
7481 WorkListRemover DeadNodes(*this);
7482 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7483 removeFromWorkList(TheXor);
7484 DAG.DeleteNode(TheXor);
7485 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7486 MVT::Other, Chain, Tmp, N2);
7489 // visitXOR has changed XOR's operands or replaced the XOR completely,
7491 return SDValue(N, 0);
7495 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7497 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7498 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7499 Op0.getOpcode() == ISD::XOR) {
7500 TheXor = Op0.getNode();
7504 EVT SetCCVT = N1.getValueType();
7506 SetCCVT = getSetCCResultType(SetCCVT);
7507 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7510 Equal ? ISD::SETEQ : ISD::SETNE);
7511 // Replace the uses of XOR with SETCC
7512 WorkListRemover DeadNodes(*this);
7513 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7514 removeFromWorkList(N1.getNode());
7515 DAG.DeleteNode(N1.getNode());
7516 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7517 MVT::Other, Chain, SetCC, N2);
7524 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7526 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7527 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7528 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7530 // If N is a constant we could fold this into a fallthrough or unconditional
7531 // branch. However that doesn't happen very often in normal code, because
7532 // Instcombine/SimplifyCFG should have handled the available opportunities.
7533 // If we did this folding here, it would be necessary to update the
7534 // MachineBasicBlock CFG, which is awkward.
7536 // Use SimplifySetCC to simplify SETCC's.
7537 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7538 CondLHS, CondRHS, CC->get(), SDLoc(N),
7540 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7542 // fold to a simpler setcc
7543 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7544 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7545 N->getOperand(0), Simp.getOperand(2),
7546 Simp.getOperand(0), Simp.getOperand(1),
7552 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7553 /// uses N as its base pointer and that N may be folded in the load / store
7554 /// addressing mode.
7555 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7557 const TargetLowering &TLI) {
7559 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7560 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7562 VT = Use->getValueType(0);
7563 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7564 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7566 VT = ST->getValue().getValueType();
7570 TargetLowering::AddrMode AM;
7571 if (N->getOpcode() == ISD::ADD) {
7572 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7575 AM.BaseOffs = Offset->getSExtValue();
7579 } else if (N->getOpcode() == ISD::SUB) {
7580 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7583 AM.BaseOffs = -Offset->getSExtValue();
7590 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7593 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7594 /// pre-indexed load / store when the base pointer is an add or subtract
7595 /// and it has other uses besides the load / store. After the
7596 /// transformation, the new indexed load / store has effectively folded
7597 /// the add / subtract in and all of its other uses are redirected to the
7598 /// new load / store.
7599 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7600 if (Level < AfterLegalizeDAG)
7606 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7607 if (LD->isIndexed())
7609 VT = LD->getMemoryVT();
7610 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7611 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7613 Ptr = LD->getBasePtr();
7614 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7615 if (ST->isIndexed())
7617 VT = ST->getMemoryVT();
7618 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7619 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7621 Ptr = ST->getBasePtr();
7627 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7628 // out. There is no reason to make this a preinc/predec.
7629 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7630 Ptr.getNode()->hasOneUse())
7633 // Ask the target to do addressing mode selection.
7636 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7637 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7640 // Backends without true r+i pre-indexed forms may need to pass a
7641 // constant base with a variable offset so that constant coercion
7642 // will work with the patterns in canonical form.
7643 bool Swapped = false;
7644 if (isa<ConstantSDNode>(BasePtr)) {
7645 std::swap(BasePtr, Offset);
7649 // Don't create a indexed load / store with zero offset.
7650 if (isa<ConstantSDNode>(Offset) &&
7651 cast<ConstantSDNode>(Offset)->isNullValue())
7654 // Try turning it into a pre-indexed load / store except when:
7655 // 1) The new base ptr is a frame index.
7656 // 2) If N is a store and the new base ptr is either the same as or is a
7657 // predecessor of the value being stored.
7658 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7659 // that would create a cycle.
7660 // 4) All uses are load / store ops that use it as old base ptr.
7662 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7663 // (plus the implicit offset) to a register to preinc anyway.
7664 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7669 SDValue Val = cast<StoreSDNode>(N)->getValue();
7670 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7674 // If the offset is a constant, there may be other adds of constants that
7675 // can be folded with this one. We should do this to avoid having to keep
7676 // a copy of the original base pointer.
7677 SmallVector<SDNode *, 16> OtherUses;
7678 if (isa<ConstantSDNode>(Offset))
7679 for (SDNode *Use : BasePtr.getNode()->uses()) {
7680 if (Use == Ptr.getNode())
7683 if (Use->isPredecessorOf(N))
7686 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7691 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7692 if (Op1.getNode() == BasePtr.getNode())
7693 std::swap(Op0, Op1);
7694 assert(Op0.getNode() == BasePtr.getNode() &&
7695 "Use of ADD/SUB but not an operand");
7697 if (!isa<ConstantSDNode>(Op1)) {
7702 // FIXME: In some cases, we can be smarter about this.
7703 if (Op1.getValueType() != Offset.getValueType()) {
7708 OtherUses.push_back(Use);
7712 std::swap(BasePtr, Offset);
7714 // Now check for #3 and #4.
7715 bool RealUse = false;
7717 // Caches for hasPredecessorHelper
7718 SmallPtrSet<const SDNode *, 32> Visited;
7719 SmallVector<const SDNode *, 16> Worklist;
7721 for (SDNode *Use : Ptr.getNode()->uses()) {
7724 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7727 // If Ptr may be folded in addressing mode of other use, then it's
7728 // not profitable to do this transformation.
7729 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7738 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7739 BasePtr, Offset, AM);
7741 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7742 BasePtr, Offset, AM);
7745 DEBUG(dbgs() << "\nReplacing.4 ";
7747 dbgs() << "\nWith: ";
7748 Result.getNode()->dump(&DAG);
7750 WorkListRemover DeadNodes(*this);
7752 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7753 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7755 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7758 // Finally, since the node is now dead, remove it from the graph.
7762 std::swap(BasePtr, Offset);
7764 // Replace other uses of BasePtr that can be updated to use Ptr
7765 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7766 unsigned OffsetIdx = 1;
7767 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7769 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7770 BasePtr.getNode() && "Expected BasePtr operand");
7772 // We need to replace ptr0 in the following expression:
7773 // x0 * offset0 + y0 * ptr0 = t0
7775 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7777 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7778 // indexed load/store and the expresion that needs to be re-written.
7780 // Therefore, we have:
7781 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7783 ConstantSDNode *CN =
7784 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7786 APInt Offset0 = CN->getAPIntValue();
7787 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7789 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7790 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7791 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7792 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7794 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7796 APInt CNV = Offset0;
7797 if (X0 < 0) CNV = -CNV;
7798 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7799 else CNV = CNV - Offset1;
7801 // We can now generate the new expression.
7802 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7803 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7805 SDValue NewUse = DAG.getNode(Opcode,
7806 SDLoc(OtherUses[i]),
7807 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7808 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7809 removeFromWorkList(OtherUses[i]);
7810 DAG.DeleteNode(OtherUses[i]);
7813 // Replace the uses of Ptr with uses of the updated base value.
7814 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7815 removeFromWorkList(Ptr.getNode());
7816 DAG.DeleteNode(Ptr.getNode());
7821 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7822 /// add / sub of the base pointer node into a post-indexed load / store.
7823 /// The transformation folded the add / subtract into the new indexed
7824 /// load / store effectively and all of its uses are redirected to the
7825 /// new load / store.
7826 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7827 if (Level < AfterLegalizeDAG)
7833 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7834 if (LD->isIndexed())
7836 VT = LD->getMemoryVT();
7837 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7838 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7840 Ptr = LD->getBasePtr();
7841 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7842 if (ST->isIndexed())
7844 VT = ST->getMemoryVT();
7845 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7846 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7848 Ptr = ST->getBasePtr();
7854 if (Ptr.getNode()->hasOneUse())
7857 for (SDNode *Op : Ptr.getNode()->uses()) {
7859 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7864 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7865 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7866 // Don't create a indexed load / store with zero offset.
7867 if (isa<ConstantSDNode>(Offset) &&
7868 cast<ConstantSDNode>(Offset)->isNullValue())
7871 // Try turning it into a post-indexed load / store except when
7872 // 1) All uses are load / store ops that use it as base ptr (and
7873 // it may be folded as addressing mmode).
7874 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7875 // nor a successor of N. Otherwise, if Op is folded that would
7878 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7882 bool TryNext = false;
7883 for (SDNode *Use : BasePtr.getNode()->uses()) {
7884 if (Use == Ptr.getNode())
7887 // If all the uses are load / store addresses, then don't do the
7889 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7890 bool RealUse = false;
7891 for (SDNode *UseUse : Use->uses()) {
7892 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7907 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7908 SDValue Result = isLoad
7909 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7910 BasePtr, Offset, AM)
7911 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7912 BasePtr, Offset, AM);
7915 DEBUG(dbgs() << "\nReplacing.5 ";
7917 dbgs() << "\nWith: ";
7918 Result.getNode()->dump(&DAG);
7920 WorkListRemover DeadNodes(*this);
7922 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7923 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7925 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7928 // Finally, since the node is now dead, remove it from the graph.
7931 // Replace the uses of Use with uses of the updated base value.
7932 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7933 Result.getValue(isLoad ? 1 : 0));
7934 removeFromWorkList(Op);
7944 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7945 LoadSDNode *LD = cast<LoadSDNode>(N);
7946 SDValue Chain = LD->getChain();
7947 SDValue Ptr = LD->getBasePtr();
7949 // If load is not volatile and there are no uses of the loaded value (and
7950 // the updated indexed value in case of indexed loads), change uses of the
7951 // chain value into uses of the chain input (i.e. delete the dead load).
7952 if (!LD->isVolatile()) {
7953 if (N->getValueType(1) == MVT::Other) {
7955 if (!N->hasAnyUseOfValue(0)) {
7956 // It's not safe to use the two value CombineTo variant here. e.g.
7957 // v1, chain2 = load chain1, loc
7958 // v2, chain3 = load chain2, loc
7960 // Now we replace use of chain2 with chain1. This makes the second load
7961 // isomorphic to the one we are deleting, and thus makes this load live.
7962 DEBUG(dbgs() << "\nReplacing.6 ";
7964 dbgs() << "\nWith chain: ";
7965 Chain.getNode()->dump(&DAG);
7967 WorkListRemover DeadNodes(*this);
7968 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7970 if (N->use_empty()) {
7971 removeFromWorkList(N);
7975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7979 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7980 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7981 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7982 DEBUG(dbgs() << "\nReplacing.7 ";
7984 dbgs() << "\nWith: ";
7985 Undef.getNode()->dump(&DAG);
7986 dbgs() << " and 2 other values\n");
7987 WorkListRemover DeadNodes(*this);
7988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7989 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7990 DAG.getUNDEF(N->getValueType(1)));
7991 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7992 removeFromWorkList(N);
7994 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7999 // If this load is directly stored, replace the load value with the stored
8001 // TODO: Handle store large -> read small portion.
8002 // TODO: Handle TRUNCSTORE/LOADEXT
8003 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8004 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8005 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8006 if (PrevST->getBasePtr() == Ptr &&
8007 PrevST->getValue().getValueType() == N->getValueType(0))
8008 return CombineTo(N, Chain.getOperand(1), Chain);
8012 // Try to infer better alignment information than the load already has.
8013 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8014 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8015 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8017 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8018 LD->getValueType(0),
8019 Chain, Ptr, LD->getPointerInfo(),
8021 LD->isVolatile(), LD->isNonTemporal(), Align,
8023 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8028 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8029 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8031 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8032 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8035 if (UseAA && LD->isUnindexed()) {
8036 // Walk up chain skipping non-aliasing memory nodes.
8037 SDValue BetterChain = FindBetterChain(N, Chain);
8039 // If there is a better chain.
8040 if (Chain != BetterChain) {
8043 // Replace the chain to void dependency.
8044 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8045 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8046 BetterChain, Ptr, LD->getMemOperand());
8048 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8049 LD->getValueType(0),
8050 BetterChain, Ptr, LD->getMemoryVT(),
8051 LD->getMemOperand());
8054 // Create token factor to keep old chain connected.
8055 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8056 MVT::Other, Chain, ReplLoad.getValue(1));
8058 // Make sure the new and old chains are cleaned up.
8059 AddToWorkList(Token.getNode());
8061 // Replace uses with load result and token factor. Don't add users
8063 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8067 // Try transforming N to an indexed load.
8068 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8069 return SDValue(N, 0);
8071 // Try to slice up N to more direct loads if the slices are mapped to
8072 // different register banks or pairing can take place.
8074 return SDValue(N, 0);
8080 /// \brief Helper structure used to slice a load in smaller loads.
8081 /// Basically a slice is obtained from the following sequence:
8082 /// Origin = load Ty1, Base
8083 /// Shift = srl Ty1 Origin, CstTy Amount
8084 /// Inst = trunc Shift to Ty2
8086 /// Then, it will be rewriten into:
8087 /// Slice = load SliceTy, Base + SliceOffset
8088 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8090 /// SliceTy is deduced from the number of bits that are actually used to
8092 struct LoadedSlice {
8093 /// \brief Helper structure used to compute the cost of a slice.
8095 /// Are we optimizing for code size.
8100 unsigned CrossRegisterBanksCopies;
8104 Cost(bool ForCodeSize = false)
8105 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8106 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8108 /// \brief Get the cost of one isolated slice.
8109 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8110 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8111 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8112 EVT TruncType = LS.Inst->getValueType(0);
8113 EVT LoadedType = LS.getLoadedType();
8114 if (TruncType != LoadedType &&
8115 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8119 /// \brief Account for slicing gain in the current cost.
8120 /// Slicing provide a few gains like removing a shift or a
8121 /// truncate. This method allows to grow the cost of the original
8122 /// load with the gain from this slice.
8123 void addSliceGain(const LoadedSlice &LS) {
8124 // Each slice saves a truncate.
8125 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8126 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8127 LS.Inst->getOperand(0).getValueType()))
8129 // If there is a shift amount, this slice gets rid of it.
8132 // If this slice can merge a cross register bank copy, account for it.
8133 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8134 ++CrossRegisterBanksCopies;
8137 Cost &operator+=(const Cost &RHS) {
8139 Truncates += RHS.Truncates;
8140 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8146 bool operator==(const Cost &RHS) const {
8147 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8148 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8149 ZExts == RHS.ZExts && Shift == RHS.Shift;
8152 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8154 bool operator<(const Cost &RHS) const {
8155 // Assume cross register banks copies are as expensive as loads.
8156 // FIXME: Do we want some more target hooks?
8157 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8158 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8159 // Unless we are optimizing for code size, consider the
8160 // expensive operation first.
8161 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8162 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8163 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8164 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8167 bool operator>(const Cost &RHS) const { return RHS < *this; }
8169 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8171 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8173 // The last instruction that represent the slice. This should be a
8174 // truncate instruction.
8176 // The original load instruction.
8178 // The right shift amount in bits from the original load.
8180 // The DAG from which Origin came from.
8181 // This is used to get some contextual information about legal types, etc.
8184 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8185 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8186 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8188 LoadedSlice(const LoadedSlice &LS)
8189 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8191 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8192 /// \return Result is \p BitWidth and has used bits set to 1 and
8193 /// not used bits set to 0.
8194 APInt getUsedBits() const {
8195 // Reproduce the trunc(lshr) sequence:
8196 // - Start from the truncated value.
8197 // - Zero extend to the desired bit width.
8199 assert(Origin && "No original load to compare against.");
8200 unsigned BitWidth = Origin->getValueSizeInBits(0);
8201 assert(Inst && "This slice is not bound to an instruction");
8202 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8203 "Extracted slice is bigger than the whole type!");
8204 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8205 UsedBits.setAllBits();
8206 UsedBits = UsedBits.zext(BitWidth);
8211 /// \brief Get the size of the slice to be loaded in bytes.
8212 unsigned getLoadedSize() const {
8213 unsigned SliceSize = getUsedBits().countPopulation();
8214 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8215 return SliceSize / 8;
8218 /// \brief Get the type that will be loaded for this slice.
8219 /// Note: This may not be the final type for the slice.
8220 EVT getLoadedType() const {
8221 assert(DAG && "Missing context");
8222 LLVMContext &Ctxt = *DAG->getContext();
8223 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8226 /// \brief Get the alignment of the load used for this slice.
8227 unsigned getAlignment() const {
8228 unsigned Alignment = Origin->getAlignment();
8229 unsigned Offset = getOffsetFromBase();
8231 Alignment = MinAlign(Alignment, Alignment + Offset);
8235 /// \brief Check if this slice can be rewritten with legal operations.
8236 bool isLegal() const {
8237 // An invalid slice is not legal.
8238 if (!Origin || !Inst || !DAG)
8241 // Offsets are for indexed load only, we do not handle that.
8242 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8245 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8247 // Check that the type is legal.
8248 EVT SliceType = getLoadedType();
8249 if (!TLI.isTypeLegal(SliceType))
8252 // Check that the load is legal for this type.
8253 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8256 // Check that the offset can be computed.
8257 // 1. Check its type.
8258 EVT PtrType = Origin->getBasePtr().getValueType();
8259 if (PtrType == MVT::Untyped || PtrType.isExtended())
8262 // 2. Check that it fits in the immediate.
8263 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8266 // 3. Check that the computation is legal.
8267 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8270 // Check that the zext is legal if it needs one.
8271 EVT TruncateType = Inst->getValueType(0);
8272 if (TruncateType != SliceType &&
8273 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8279 /// \brief Get the offset in bytes of this slice in the original chunk of
8281 /// \pre DAG != nullptr.
8282 uint64_t getOffsetFromBase() const {
8283 assert(DAG && "Missing context.");
8285 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8286 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8287 uint64_t Offset = Shift / 8;
8288 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8289 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8290 "The size of the original loaded type is not a multiple of a"
8292 // If Offset is bigger than TySizeInBytes, it means we are loading all
8293 // zeros. This should have been optimized before in the process.
8294 assert(TySizeInBytes > Offset &&
8295 "Invalid shift amount for given loaded size");
8297 Offset = TySizeInBytes - Offset - getLoadedSize();
8301 /// \brief Generate the sequence of instructions to load the slice
8302 /// represented by this object and redirect the uses of this slice to
8303 /// this new sequence of instructions.
8304 /// \pre this->Inst && this->Origin are valid Instructions and this
8305 /// object passed the legal check: LoadedSlice::isLegal returned true.
8306 /// \return The last instruction of the sequence used to load the slice.
8307 SDValue loadSlice() const {
8308 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8309 const SDValue &OldBaseAddr = Origin->getBasePtr();
8310 SDValue BaseAddr = OldBaseAddr;
8311 // Get the offset in that chunk of bytes w.r.t. the endianess.
8312 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8313 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8315 // BaseAddr = BaseAddr + Offset.
8316 EVT ArithType = BaseAddr.getValueType();
8317 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8318 DAG->getConstant(Offset, ArithType));
8321 // Create the type of the loaded slice according to its size.
8322 EVT SliceType = getLoadedType();
8324 // Create the load for the slice.
8325 SDValue LastInst = DAG->getLoad(
8326 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8327 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8328 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8329 // If the final type is not the same as the loaded type, this means that
8330 // we have to pad with zero. Create a zero extend for that.
8331 EVT FinalType = Inst->getValueType(0);
8332 if (SliceType != FinalType)
8334 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8338 /// \brief Check if this slice can be merged with an expensive cross register
8339 /// bank copy. E.g.,
8341 /// f = bitcast i32 i to float
8342 bool canMergeExpensiveCrossRegisterBankCopy() const {
8343 if (!Inst || !Inst->hasOneUse())
8345 SDNode *Use = *Inst->use_begin();
8346 if (Use->getOpcode() != ISD::BITCAST)
8348 assert(DAG && "Missing context");
8349 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8350 EVT ResVT = Use->getValueType(0);
8351 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8352 const TargetRegisterClass *ArgRC =
8353 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8354 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8357 // At this point, we know that we perform a cross-register-bank copy.
8358 // Check if it is expensive.
8359 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8360 // Assume bitcasts are cheap, unless both register classes do not
8361 // explicitly share a common sub class.
8362 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8365 // Check if it will be merged with the load.
8366 // 1. Check the alignment constraint.
8367 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8368 ResVT.getTypeForEVT(*DAG->getContext()));
8370 if (RequiredAlignment > getAlignment())
8373 // 2. Check that the load is a legal operation for that type.
8374 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8377 // 3. Check that we do not have a zext in the way.
8378 if (Inst->getValueType(0) != getLoadedType())
8386 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8387 /// \p UsedBits looks like 0..0 1..1 0..0.
8388 static bool areUsedBitsDense(const APInt &UsedBits) {
8389 // If all the bits are one, this is dense!
8390 if (UsedBits.isAllOnesValue())
8393 // Get rid of the unused bits on the right.
8394 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8395 // Get rid of the unused bits on the left.
8396 if (NarrowedUsedBits.countLeadingZeros())
8397 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8398 // Check that the chunk of bits is completely used.
8399 return NarrowedUsedBits.isAllOnesValue();
8402 /// \brief Check whether or not \p First and \p Second are next to each other
8403 /// in memory. This means that there is no hole between the bits loaded
8404 /// by \p First and the bits loaded by \p Second.
8405 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8406 const LoadedSlice &Second) {
8407 assert(First.Origin == Second.Origin && First.Origin &&
8408 "Unable to match different memory origins.");
8409 APInt UsedBits = First.getUsedBits();
8410 assert((UsedBits & Second.getUsedBits()) == 0 &&
8411 "Slices are not supposed to overlap.");
8412 UsedBits |= Second.getUsedBits();
8413 return areUsedBitsDense(UsedBits);
8416 /// \brief Adjust the \p GlobalLSCost according to the target
8417 /// paring capabilities and the layout of the slices.
8418 /// \pre \p GlobalLSCost should account for at least as many loads as
8419 /// there is in the slices in \p LoadedSlices.
8420 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8421 LoadedSlice::Cost &GlobalLSCost) {
8422 unsigned NumberOfSlices = LoadedSlices.size();
8423 // If there is less than 2 elements, no pairing is possible.
8424 if (NumberOfSlices < 2)
8427 // Sort the slices so that elements that are likely to be next to each
8428 // other in memory are next to each other in the list.
8429 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8430 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8431 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8432 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8434 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8435 // First (resp. Second) is the first (resp. Second) potentially candidate
8436 // to be placed in a paired load.
8437 const LoadedSlice *First = nullptr;
8438 const LoadedSlice *Second = nullptr;
8439 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8440 // Set the beginning of the pair.
8443 Second = &LoadedSlices[CurrSlice];
8445 // If First is NULL, it means we start a new pair.
8446 // Get to the next slice.
8450 EVT LoadedType = First->getLoadedType();
8452 // If the types of the slices are different, we cannot pair them.
8453 if (LoadedType != Second->getLoadedType())
8456 // Check if the target supplies paired loads for this type.
8457 unsigned RequiredAlignment = 0;
8458 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8459 // move to the next pair, this type is hopeless.
8463 // Check if we meet the alignment requirement.
8464 if (RequiredAlignment > First->getAlignment())
8467 // Check that both loads are next to each other in memory.
8468 if (!areSlicesNextToEachOther(*First, *Second))
8471 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8472 --GlobalLSCost.Loads;
8473 // Move to the next pair.
8478 /// \brief Check the profitability of all involved LoadedSlice.
8479 /// Currently, it is considered profitable if there is exactly two
8480 /// involved slices (1) which are (2) next to each other in memory, and
8481 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8483 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8484 /// the elements themselves.
8486 /// FIXME: When the cost model will be mature enough, we can relax
8487 /// constraints (1) and (2).
8488 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8489 const APInt &UsedBits, bool ForCodeSize) {
8490 unsigned NumberOfSlices = LoadedSlices.size();
8491 if (StressLoadSlicing)
8492 return NumberOfSlices > 1;
8495 if (NumberOfSlices != 2)
8499 if (!areUsedBitsDense(UsedBits))
8503 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8504 // The original code has one big load.
8506 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8507 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8508 // Accumulate the cost of all the slices.
8509 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8510 GlobalSlicingCost += SliceCost;
8512 // Account as cost in the original configuration the gain obtained
8513 // with the current slices.
8514 OrigCost.addSliceGain(LS);
8517 // If the target supports paired load, adjust the cost accordingly.
8518 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8519 return OrigCost > GlobalSlicingCost;
8522 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8523 /// operations, split it in the various pieces being extracted.
8525 /// This sort of thing is introduced by SROA.
8526 /// This slicing takes care not to insert overlapping loads.
8527 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8528 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8529 if (Level < AfterLegalizeDAG)
8532 LoadSDNode *LD = cast<LoadSDNode>(N);
8533 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8534 !LD->getValueType(0).isInteger())
8537 // Keep track of already used bits to detect overlapping values.
8538 // In that case, we will just abort the transformation.
8539 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8541 SmallVector<LoadedSlice, 4> LoadedSlices;
8543 // Check if this load is used as several smaller chunks of bits.
8544 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8545 // of computation for each trunc.
8546 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8547 UI != UIEnd; ++UI) {
8548 // Skip the uses of the chain.
8549 if (UI.getUse().getResNo() != 0)
8555 // Check if this is a trunc(lshr).
8556 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8557 isa<ConstantSDNode>(User->getOperand(1))) {
8558 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8559 User = *User->use_begin();
8562 // At this point, User is a Truncate, iff we encountered, trunc or
8564 if (User->getOpcode() != ISD::TRUNCATE)
8567 // The width of the type must be a power of 2 and greater than 8-bits.
8568 // Otherwise the load cannot be represented in LLVM IR.
8569 // Moreover, if we shifted with a non-8-bits multiple, the slice
8570 // will be across several bytes. We do not support that.
8571 unsigned Width = User->getValueSizeInBits(0);
8572 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8575 // Build the slice for this chain of computations.
8576 LoadedSlice LS(User, LD, Shift, &DAG);
8577 APInt CurrentUsedBits = LS.getUsedBits();
8579 // Check if this slice overlaps with another.
8580 if ((CurrentUsedBits & UsedBits) != 0)
8582 // Update the bits used globally.
8583 UsedBits |= CurrentUsedBits;
8585 // Check if the new slice would be legal.
8589 // Record the slice.
8590 LoadedSlices.push_back(LS);
8593 // Abort slicing if it does not seem to be profitable.
8594 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8599 // Rewrite each chain to use an independent load.
8600 // By construction, each chain can be represented by a unique load.
8602 // Prepare the argument for the new token factor for all the slices.
8603 SmallVector<SDValue, 8> ArgChains;
8604 for (SmallVectorImpl<LoadedSlice>::const_iterator
8605 LSIt = LoadedSlices.begin(),
8606 LSItEnd = LoadedSlices.end();
8607 LSIt != LSItEnd; ++LSIt) {
8608 SDValue SliceInst = LSIt->loadSlice();
8609 CombineTo(LSIt->Inst, SliceInst, true);
8610 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8611 SliceInst = SliceInst.getOperand(0);
8612 assert(SliceInst->getOpcode() == ISD::LOAD &&
8613 "It takes more than a zext to get to the loaded slice!!");
8614 ArgChains.push_back(SliceInst.getValue(1));
8617 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8619 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8623 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8624 /// load is having specific bytes cleared out. If so, return the byte size
8625 /// being masked out and the shift amount.
8626 static std::pair<unsigned, unsigned>
8627 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8628 std::pair<unsigned, unsigned> Result(0, 0);
8630 // Check for the structure we're looking for.
8631 if (V->getOpcode() != ISD::AND ||
8632 !isa<ConstantSDNode>(V->getOperand(1)) ||
8633 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8636 // Check the chain and pointer.
8637 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8638 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8640 // The store should be chained directly to the load or be an operand of a
8642 if (LD == Chain.getNode())
8644 else if (Chain->getOpcode() != ISD::TokenFactor)
8645 return Result; // Fail.
8648 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8649 if (Chain->getOperand(i).getNode() == LD) {
8653 if (!isOk) return Result;
8656 // This only handles simple types.
8657 if (V.getValueType() != MVT::i16 &&
8658 V.getValueType() != MVT::i32 &&
8659 V.getValueType() != MVT::i64)
8662 // Check the constant mask. Invert it so that the bits being masked out are
8663 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8664 // follow the sign bit for uniformity.
8665 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8666 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8667 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8668 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8669 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8670 if (NotMaskLZ == 64) return Result; // All zero mask.
8672 // See if we have a continuous run of bits. If so, we have 0*1+0*
8673 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8676 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8677 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8678 NotMaskLZ -= 64-V.getValueSizeInBits();
8680 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8681 switch (MaskedBytes) {
8685 default: return Result; // All one mask, or 5-byte mask.
8688 // Verify that the first bit starts at a multiple of mask so that the access
8689 // is aligned the same as the access width.
8690 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8692 Result.first = MaskedBytes;
8693 Result.second = NotMaskTZ/8;
8698 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8699 /// provides a value as specified by MaskInfo. If so, replace the specified
8700 /// store with a narrower store of truncated IVal.
8702 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8703 SDValue IVal, StoreSDNode *St,
8705 unsigned NumBytes = MaskInfo.first;
8706 unsigned ByteShift = MaskInfo.second;
8707 SelectionDAG &DAG = DC->getDAG();
8709 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8710 // that uses this. If not, this is not a replacement.
8711 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8712 ByteShift*8, (ByteShift+NumBytes)*8);
8713 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8715 // Check that it is legal on the target to do this. It is legal if the new
8716 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8718 MVT VT = MVT::getIntegerVT(NumBytes*8);
8719 if (!DC->isTypeLegal(VT))
8722 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8723 // shifted by ByteShift and truncated down to NumBytes.
8725 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8726 DAG.getConstant(ByteShift*8,
8727 DC->getShiftAmountTy(IVal.getValueType())));
8729 // Figure out the offset for the store and the alignment of the access.
8731 unsigned NewAlign = St->getAlignment();
8733 if (DAG.getTargetLoweringInfo().isLittleEndian())
8734 StOffset = ByteShift;
8736 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8738 SDValue Ptr = St->getBasePtr();
8740 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8741 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8742 NewAlign = MinAlign(NewAlign, StOffset);
8745 // Truncate down to the new size.
8746 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8749 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8750 St->getPointerInfo().getWithOffset(StOffset),
8751 false, false, NewAlign).getNode();
8755 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8756 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8757 /// of the loaded bits, try narrowing the load and store if it would end up
8758 /// being a win for performance or code size.
8759 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8760 StoreSDNode *ST = cast<StoreSDNode>(N);
8761 if (ST->isVolatile())
8764 SDValue Chain = ST->getChain();
8765 SDValue Value = ST->getValue();
8766 SDValue Ptr = ST->getBasePtr();
8767 EVT VT = Value.getValueType();
8769 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8772 unsigned Opc = Value.getOpcode();
8774 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8775 // is a byte mask indicating a consecutive number of bytes, check to see if
8776 // Y is known to provide just those bytes. If so, we try to replace the
8777 // load + replace + store sequence with a single (narrower) store, which makes
8779 if (Opc == ISD::OR) {
8780 std::pair<unsigned, unsigned> MaskedLoad;
8781 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8782 if (MaskedLoad.first)
8783 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8784 Value.getOperand(1), ST,this))
8785 return SDValue(NewST, 0);
8787 // Or is commutative, so try swapping X and Y.
8788 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8789 if (MaskedLoad.first)
8790 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8791 Value.getOperand(0), ST,this))
8792 return SDValue(NewST, 0);
8795 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8796 Value.getOperand(1).getOpcode() != ISD::Constant)
8799 SDValue N0 = Value.getOperand(0);
8800 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8801 Chain == SDValue(N0.getNode(), 1)) {
8802 LoadSDNode *LD = cast<LoadSDNode>(N0);
8803 if (LD->getBasePtr() != Ptr ||
8804 LD->getPointerInfo().getAddrSpace() !=
8805 ST->getPointerInfo().getAddrSpace())
8808 // Find the type to narrow it the load / op / store to.
8809 SDValue N1 = Value.getOperand(1);
8810 unsigned BitWidth = N1.getValueSizeInBits();
8811 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8812 if (Opc == ISD::AND)
8813 Imm ^= APInt::getAllOnesValue(BitWidth);
8814 if (Imm == 0 || Imm.isAllOnesValue())
8816 unsigned ShAmt = Imm.countTrailingZeros();
8817 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8818 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8819 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8820 while (NewBW < BitWidth &&
8821 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8822 TLI.isNarrowingProfitable(VT, NewVT))) {
8823 NewBW = NextPowerOf2(NewBW);
8824 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8826 if (NewBW >= BitWidth)
8829 // If the lsb changed does not start at the type bitwidth boundary,
8830 // start at the previous one.
8832 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8833 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8834 std::min(BitWidth, ShAmt + NewBW));
8835 if ((Imm & Mask) == Imm) {
8836 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8837 if (Opc == ISD::AND)
8838 NewImm ^= APInt::getAllOnesValue(NewBW);
8839 uint64_t PtrOff = ShAmt / 8;
8840 // For big endian targets, we need to adjust the offset to the pointer to
8841 // load the correct bytes.
8842 if (TLI.isBigEndian())
8843 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8845 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8846 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8847 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8850 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8851 Ptr.getValueType(), Ptr,
8852 DAG.getConstant(PtrOff, Ptr.getValueType()));
8853 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8854 LD->getChain(), NewPtr,
8855 LD->getPointerInfo().getWithOffset(PtrOff),
8856 LD->isVolatile(), LD->isNonTemporal(),
8857 LD->isInvariant(), NewAlign,
8859 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8860 DAG.getConstant(NewImm, NewVT));
8861 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8863 ST->getPointerInfo().getWithOffset(PtrOff),
8864 false, false, NewAlign);
8866 AddToWorkList(NewPtr.getNode());
8867 AddToWorkList(NewLD.getNode());
8868 AddToWorkList(NewVal.getNode());
8869 WorkListRemover DeadNodes(*this);
8870 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8879 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8880 /// if the load value isn't used by any other operations, then consider
8881 /// transforming the pair to integer load / store operations if the target
8882 /// deems the transformation profitable.
8883 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8884 StoreSDNode *ST = cast<StoreSDNode>(N);
8885 SDValue Chain = ST->getChain();
8886 SDValue Value = ST->getValue();
8887 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8888 Value.hasOneUse() &&
8889 Chain == SDValue(Value.getNode(), 1)) {
8890 LoadSDNode *LD = cast<LoadSDNode>(Value);
8891 EVT VT = LD->getMemoryVT();
8892 if (!VT.isFloatingPoint() ||
8893 VT != ST->getMemoryVT() ||
8894 LD->isNonTemporal() ||
8895 ST->isNonTemporal() ||
8896 LD->getPointerInfo().getAddrSpace() != 0 ||
8897 ST->getPointerInfo().getAddrSpace() != 0)
8900 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8901 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8902 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8903 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8904 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8907 unsigned LDAlign = LD->getAlignment();
8908 unsigned STAlign = ST->getAlignment();
8909 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8910 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8911 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8914 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8915 LD->getChain(), LD->getBasePtr(),
8916 LD->getPointerInfo(),
8917 false, false, false, LDAlign);
8919 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8920 NewLD, ST->getBasePtr(),
8921 ST->getPointerInfo(),
8922 false, false, STAlign);
8924 AddToWorkList(NewLD.getNode());
8925 AddToWorkList(NewST.getNode());
8926 WorkListRemover DeadNodes(*this);
8927 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8935 /// Helper struct to parse and store a memory address as base + index + offset.
8936 /// We ignore sign extensions when it is safe to do so.
8937 /// The following two expressions are not equivalent. To differentiate we need
8938 /// to store whether there was a sign extension involved in the index
8940 /// (load (i64 add (i64 copyfromreg %c)
8941 /// (i64 signextend (add (i8 load %index)
8945 /// (load (i64 add (i64 copyfromreg %c)
8946 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8948 struct BaseIndexOffset {
8952 bool IsIndexSignExt;
8954 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8956 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8957 bool IsIndexSignExt) :
8958 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8960 bool equalBaseIndex(const BaseIndexOffset &Other) {
8961 return Other.Base == Base && Other.Index == Index &&
8962 Other.IsIndexSignExt == IsIndexSignExt;
8965 /// Parses tree in Ptr for base, index, offset addresses.
8966 static BaseIndexOffset match(SDValue Ptr) {
8967 bool IsIndexSignExt = false;
8969 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8970 // instruction, then it could be just the BASE or everything else we don't
8971 // know how to handle. Just use Ptr as BASE and give up.
8972 if (Ptr->getOpcode() != ISD::ADD)
8973 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8975 // We know that we have at least an ADD instruction. Try to pattern match
8976 // the simple case of BASE + OFFSET.
8977 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8978 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8979 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8983 // Inside a loop the current BASE pointer is calculated using an ADD and a
8984 // MUL instruction. In this case Ptr is the actual BASE pointer.
8985 // (i64 add (i64 %array_ptr)
8986 // (i64 mul (i64 %induction_var)
8987 // (i64 %element_size)))
8988 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8989 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8991 // Look at Base + Index + Offset cases.
8992 SDValue Base = Ptr->getOperand(0);
8993 SDValue IndexOffset = Ptr->getOperand(1);
8995 // Skip signextends.
8996 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8997 IndexOffset = IndexOffset->getOperand(0);
8998 IsIndexSignExt = true;
9001 // Either the case of Base + Index (no offset) or something else.
9002 if (IndexOffset->getOpcode() != ISD::ADD)
9003 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9005 // Now we have the case of Base + Index + offset.
9006 SDValue Index = IndexOffset->getOperand(0);
9007 SDValue Offset = IndexOffset->getOperand(1);
9009 if (!isa<ConstantSDNode>(Offset))
9010 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9012 // Ignore signextends.
9013 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9014 Index = Index->getOperand(0);
9015 IsIndexSignExt = true;
9016 } else IsIndexSignExt = false;
9018 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9019 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9023 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9024 /// is located in a sequence of memory operations connected by a chain.
9026 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9027 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9028 // Ptr to the mem node.
9029 LSBaseSDNode *MemNode;
9030 // Offset from the base ptr.
9031 int64_t OffsetFromBase;
9032 // What is the sequence number of this mem node.
9033 // Lowest mem operand in the DAG starts at zero.
9034 unsigned SequenceNum;
9037 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9038 EVT MemVT = St->getMemoryVT();
9039 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9040 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9041 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9043 // Don't merge vectors into wider inputs.
9044 if (MemVT.isVector() || !MemVT.isSimple())
9047 // Perform an early exit check. Do not bother looking at stored values that
9048 // are not constants or loads.
9049 SDValue StoredVal = St->getValue();
9050 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9051 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9055 // Only look at ends of store sequences.
9056 SDValue Chain = SDValue(St, 1);
9057 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9060 // This holds the base pointer, index, and the offset in bytes from the base
9062 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9064 // We must have a base and an offset.
9065 if (!BasePtr.Base.getNode())
9068 // Do not handle stores to undef base pointers.
9069 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9072 // Save the LoadSDNodes that we find in the chain.
9073 // We need to make sure that these nodes do not interfere with
9074 // any of the store nodes.
9075 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9077 // Save the StoreSDNodes that we find in the chain.
9078 SmallVector<MemOpLink, 8> StoreNodes;
9080 // Walk up the chain and look for nodes with offsets from the same
9081 // base pointer. Stop when reaching an instruction with a different kind
9082 // or instruction which has a different base pointer.
9084 StoreSDNode *Index = St;
9086 // If the chain has more than one use, then we can't reorder the mem ops.
9087 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9090 // Find the base pointer and offset for this memory node.
9091 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9093 // Check that the base pointer is the same as the original one.
9094 if (!Ptr.equalBaseIndex(BasePtr))
9097 // Check that the alignment is the same.
9098 if (Index->getAlignment() != St->getAlignment())
9101 // The memory operands must not be volatile.
9102 if (Index->isVolatile() || Index->isIndexed())
9106 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9107 if (St->isTruncatingStore())
9110 // The stored memory type must be the same.
9111 if (Index->getMemoryVT() != MemVT)
9114 // We do not allow unaligned stores because we want to prevent overriding
9116 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9119 // We found a potential memory operand to merge.
9120 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9122 // Find the next memory operand in the chain. If the next operand in the
9123 // chain is a store then move up and continue the scan with the next
9124 // memory operand. If the next operand is a load save it and use alias
9125 // information to check if it interferes with anything.
9126 SDNode *NextInChain = Index->getChain().getNode();
9128 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9129 // We found a store node. Use it for the next iteration.
9132 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9133 if (Ldn->isVolatile()) {
9138 // Save the load node for later. Continue the scan.
9139 AliasLoadNodes.push_back(Ldn);
9140 NextInChain = Ldn->getChain().getNode();
9149 // Check if there is anything to merge.
9150 if (StoreNodes.size() < 2)
9153 // Sort the memory operands according to their distance from the base pointer.
9154 std::sort(StoreNodes.begin(), StoreNodes.end(),
9155 [](MemOpLink LHS, MemOpLink RHS) {
9156 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9157 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9158 LHS.SequenceNum > RHS.SequenceNum);
9161 // Scan the memory operations on the chain and find the first non-consecutive
9162 // store memory address.
9163 unsigned LastConsecutiveStore = 0;
9164 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9165 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9167 // Check that the addresses are consecutive starting from the second
9168 // element in the list of stores.
9170 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9171 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9176 // Check if this store interferes with any of the loads that we found.
9177 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9178 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9182 // We found a load that alias with this store. Stop the sequence.
9186 // Mark this node as useful.
9187 LastConsecutiveStore = i;
9190 // The node with the lowest store address.
9191 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9193 // Store the constants into memory as one consecutive store.
9195 unsigned LastLegalType = 0;
9196 unsigned LastLegalVectorType = 0;
9197 bool NonZero = false;
9198 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9199 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9200 SDValue StoredVal = St->getValue();
9202 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9203 NonZero |= !C->isNullValue();
9204 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9205 NonZero |= !C->getConstantFPValue()->isNullValue();
9211 // Find a legal type for the constant store.
9212 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9213 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9214 if (TLI.isTypeLegal(StoreTy))
9215 LastLegalType = i+1;
9216 // Or check whether a truncstore is legal.
9217 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9218 TargetLowering::TypePromoteInteger) {
9219 EVT LegalizedStoredValueTy =
9220 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9221 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9222 LastLegalType = i+1;
9225 // Find a legal type for the vector store.
9226 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9227 if (TLI.isTypeLegal(Ty))
9228 LastLegalVectorType = i + 1;
9231 // We only use vectors if the constant is known to be zero and the
9232 // function is not marked with the noimplicitfloat attribute.
9233 if (NonZero || NoVectors)
9234 LastLegalVectorType = 0;
9236 // Check if we found a legal integer type to store.
9237 if (LastLegalType == 0 && LastLegalVectorType == 0)
9240 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9241 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9243 // Make sure we have something to merge.
9247 unsigned EarliestNodeUsed = 0;
9248 for (unsigned i=0; i < NumElem; ++i) {
9249 // Find a chain for the new wide-store operand. Notice that some
9250 // of the store nodes that we found may not be selected for inclusion
9251 // in the wide store. The chain we use needs to be the chain of the
9252 // earliest store node which is *used* and replaced by the wide store.
9253 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9254 EarliestNodeUsed = i;
9257 // The earliest Node in the DAG.
9258 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9259 SDLoc DL(StoreNodes[0].MemNode);
9263 // Find a legal type for the vector store.
9264 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9265 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9266 StoredVal = DAG.getConstant(0, Ty);
9268 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9269 APInt StoreInt(StoreBW, 0);
9271 // Construct a single integer constant which is made of the smaller
9273 bool IsLE = TLI.isLittleEndian();
9274 for (unsigned i = 0; i < NumElem ; ++i) {
9275 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9276 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9277 SDValue Val = St->getValue();
9278 StoreInt<<=ElementSizeBytes*8;
9279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9280 StoreInt|=C->getAPIntValue().zext(StoreBW);
9281 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9282 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9284 assert(false && "Invalid constant element type");
9288 // Create the new Load and Store operations.
9289 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9290 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9293 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9294 FirstInChain->getBasePtr(),
9295 FirstInChain->getPointerInfo(),
9297 FirstInChain->getAlignment());
9299 // Replace the first store with the new store
9300 CombineTo(EarliestOp, NewStore);
9301 // Erase all other stores.
9302 for (unsigned i = 0; i < NumElem ; ++i) {
9303 if (StoreNodes[i].MemNode == EarliestOp)
9305 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9306 // ReplaceAllUsesWith will replace all uses that existed when it was
9307 // called, but graph optimizations may cause new ones to appear. For
9308 // example, the case in pr14333 looks like
9310 // St's chain -> St -> another store -> X
9312 // And the only difference from St to the other store is the chain.
9313 // When we change it's chain to be St's chain they become identical,
9314 // get CSEed and the net result is that X is now a use of St.
9315 // Since we know that St is redundant, just iterate.
9316 while (!St->use_empty())
9317 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9318 removeFromWorkList(St);
9325 // Below we handle the case of multiple consecutive stores that
9326 // come from multiple consecutive loads. We merge them into a single
9327 // wide load and a single wide store.
9329 // Look for load nodes which are used by the stored values.
9330 SmallVector<MemOpLink, 8> LoadNodes;
9332 // Find acceptable loads. Loads need to have the same chain (token factor),
9333 // must not be zext, volatile, indexed, and they must be consecutive.
9334 BaseIndexOffset LdBasePtr;
9335 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9336 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9337 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9340 // Loads must only have one use.
9341 if (!Ld->hasNUsesOfValue(1, 0))
9344 // Check that the alignment is the same as the stores.
9345 if (Ld->getAlignment() != St->getAlignment())
9348 // The memory operands must not be volatile.
9349 if (Ld->isVolatile() || Ld->isIndexed())
9352 // We do not accept ext loads.
9353 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9356 // The stored memory type must be the same.
9357 if (Ld->getMemoryVT() != MemVT)
9360 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9361 // If this is not the first ptr that we check.
9362 if (LdBasePtr.Base.getNode()) {
9363 // The base ptr must be the same.
9364 if (!LdPtr.equalBaseIndex(LdBasePtr))
9367 // Check that all other base pointers are the same as this one.
9371 // We found a potential memory operand to merge.
9372 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9375 if (LoadNodes.size() < 2)
9378 // Scan the memory operations on the chain and find the first non-consecutive
9379 // load memory address. These variables hold the index in the store node
9381 unsigned LastConsecutiveLoad = 0;
9382 // This variable refers to the size and not index in the array.
9383 unsigned LastLegalVectorType = 0;
9384 unsigned LastLegalIntegerType = 0;
9385 StartAddress = LoadNodes[0].OffsetFromBase;
9386 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9387 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9388 // All loads much share the same chain.
9389 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9392 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9393 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9395 LastConsecutiveLoad = i;
9397 // Find a legal type for the vector store.
9398 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9399 if (TLI.isTypeLegal(StoreTy))
9400 LastLegalVectorType = i + 1;
9402 // Find a legal type for the integer store.
9403 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9404 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9405 if (TLI.isTypeLegal(StoreTy))
9406 LastLegalIntegerType = i + 1;
9407 // Or check whether a truncstore and extload is legal.
9408 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9409 TargetLowering::TypePromoteInteger) {
9410 EVT LegalizedStoredValueTy =
9411 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9412 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9413 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9414 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9415 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9416 LastLegalIntegerType = i+1;
9420 // Only use vector types if the vector type is larger than the integer type.
9421 // If they are the same, use integers.
9422 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9423 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9425 // We add +1 here because the LastXXX variables refer to location while
9426 // the NumElem refers to array/index size.
9427 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9428 NumElem = std::min(LastLegalType, NumElem);
9433 // The earliest Node in the DAG.
9434 unsigned EarliestNodeUsed = 0;
9435 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9436 for (unsigned i=1; i<NumElem; ++i) {
9437 // Find a chain for the new wide-store operand. Notice that some
9438 // of the store nodes that we found may not be selected for inclusion
9439 // in the wide store. The chain we use needs to be the chain of the
9440 // earliest store node which is *used* and replaced by the wide store.
9441 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9442 EarliestNodeUsed = i;
9445 // Find if it is better to use vectors or integers to load and store
9449 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9451 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9452 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9455 SDLoc LoadDL(LoadNodes[0].MemNode);
9456 SDLoc StoreDL(StoreNodes[0].MemNode);
9458 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9459 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9460 FirstLoad->getChain(),
9461 FirstLoad->getBasePtr(),
9462 FirstLoad->getPointerInfo(),
9463 false, false, false,
9464 FirstLoad->getAlignment());
9466 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9467 FirstInChain->getBasePtr(),
9468 FirstInChain->getPointerInfo(), false, false,
9469 FirstInChain->getAlignment());
9471 // Replace one of the loads with the new load.
9472 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9473 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9474 SDValue(NewLoad.getNode(), 1));
9476 // Remove the rest of the load chains.
9477 for (unsigned i = 1; i < NumElem ; ++i) {
9478 // Replace all chain users of the old load nodes with the chain of the new
9480 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9481 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9484 // Replace the first store with the new store.
9485 CombineTo(EarliestOp, NewStore);
9486 // Erase all other stores.
9487 for (unsigned i = 0; i < NumElem ; ++i) {
9488 // Remove all Store nodes.
9489 if (StoreNodes[i].MemNode == EarliestOp)
9491 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9492 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9493 removeFromWorkList(St);
9500 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9501 StoreSDNode *ST = cast<StoreSDNode>(N);
9502 SDValue Chain = ST->getChain();
9503 SDValue Value = ST->getValue();
9504 SDValue Ptr = ST->getBasePtr();
9506 // If this is a store of a bit convert, store the input value if the
9507 // resultant store does not need a higher alignment than the original.
9508 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9509 ST->isUnindexed()) {
9510 unsigned OrigAlign = ST->getAlignment();
9511 EVT SVT = Value.getOperand(0).getValueType();
9512 unsigned Align = TLI.getDataLayout()->
9513 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9514 if (Align <= OrigAlign &&
9515 ((!LegalOperations && !ST->isVolatile()) ||
9516 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9517 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9518 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9519 ST->isNonTemporal(), OrigAlign,
9523 // Turn 'store undef, Ptr' -> nothing.
9524 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9527 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9528 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9529 // NOTE: If the original store is volatile, this transform must not increase
9530 // the number of stores. For example, on x86-32 an f64 can be stored in one
9531 // processor operation but an i64 (which is not legal) requires two. So the
9532 // transform should not be done in this case.
9533 if (Value.getOpcode() != ISD::TargetConstantFP) {
9535 switch (CFP->getSimpleValueType(0).SimpleTy) {
9536 default: llvm_unreachable("Unknown FP type");
9537 case MVT::f16: // We don't do this for these yet.
9543 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9544 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9545 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9546 bitcastToAPInt().getZExtValue(), MVT::i32);
9547 return DAG.getStore(Chain, SDLoc(N), Tmp,
9548 Ptr, ST->getMemOperand());
9552 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9553 !ST->isVolatile()) ||
9554 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9555 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9556 getZExtValue(), MVT::i64);
9557 return DAG.getStore(Chain, SDLoc(N), Tmp,
9558 Ptr, ST->getMemOperand());
9561 if (!ST->isVolatile() &&
9562 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9563 // Many FP stores are not made apparent until after legalize, e.g. for
9564 // argument passing. Since this is so common, custom legalize the
9565 // 64-bit integer store into two 32-bit stores.
9566 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9567 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9568 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9569 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9571 unsigned Alignment = ST->getAlignment();
9572 bool isVolatile = ST->isVolatile();
9573 bool isNonTemporal = ST->isNonTemporal();
9574 const MDNode *TBAAInfo = ST->getTBAAInfo();
9576 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9577 Ptr, ST->getPointerInfo(),
9578 isVolatile, isNonTemporal,
9579 ST->getAlignment(), TBAAInfo);
9580 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9581 DAG.getConstant(4, Ptr.getValueType()));
9582 Alignment = MinAlign(Alignment, 4U);
9583 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9584 Ptr, ST->getPointerInfo().getWithOffset(4),
9585 isVolatile, isNonTemporal,
9586 Alignment, TBAAInfo);
9587 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9596 // Try to infer better alignment information than the store already has.
9597 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9598 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9599 if (Align > ST->getAlignment())
9600 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9601 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9602 ST->isVolatile(), ST->isNonTemporal(), Align,
9607 // Try transforming a pair floating point load / store ops to integer
9608 // load / store ops.
9609 SDValue NewST = TransformFPLoadStorePair(N);
9610 if (NewST.getNode())
9613 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9614 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9616 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9617 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9620 if (UseAA && ST->isUnindexed()) {
9621 // Walk up chain skipping non-aliasing memory nodes.
9622 SDValue BetterChain = FindBetterChain(N, Chain);
9624 // If there is a better chain.
9625 if (Chain != BetterChain) {
9628 // Replace the chain to avoid dependency.
9629 if (ST->isTruncatingStore()) {
9630 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9631 ST->getMemoryVT(), ST->getMemOperand());
9633 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9634 ST->getMemOperand());
9637 // Create token to keep both nodes around.
9638 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9639 MVT::Other, Chain, ReplStore);
9641 // Make sure the new and old chains are cleaned up.
9642 AddToWorkList(Token.getNode());
9644 // Don't add users to work list.
9645 return CombineTo(N, Token, false);
9649 // Try transforming N to an indexed store.
9650 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9651 return SDValue(N, 0);
9653 // FIXME: is there such a thing as a truncating indexed store?
9654 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9655 Value.getValueType().isInteger()) {
9656 // See if we can simplify the input to this truncstore with knowledge that
9657 // only the low bits are being used. For example:
9658 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9660 GetDemandedBits(Value,
9661 APInt::getLowBitsSet(
9662 Value.getValueType().getScalarType().getSizeInBits(),
9663 ST->getMemoryVT().getScalarType().getSizeInBits()));
9664 AddToWorkList(Value.getNode());
9665 if (Shorter.getNode())
9666 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9667 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9669 // Otherwise, see if we can simplify the operation with
9670 // SimplifyDemandedBits, which only works if the value has a single use.
9671 if (SimplifyDemandedBits(Value,
9672 APInt::getLowBitsSet(
9673 Value.getValueType().getScalarType().getSizeInBits(),
9674 ST->getMemoryVT().getScalarType().getSizeInBits())))
9675 return SDValue(N, 0);
9678 // If this is a load followed by a store to the same location, then the store
9680 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9681 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9682 ST->isUnindexed() && !ST->isVolatile() &&
9683 // There can't be any side effects between the load and store, such as
9685 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9686 // The store is dead, remove it.
9691 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9692 // truncating store. We can do this even if this is already a truncstore.
9693 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9694 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9695 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9696 ST->getMemoryVT())) {
9697 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9698 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9701 // Only perform this optimization before the types are legal, because we
9702 // don't want to perform this optimization on every DAGCombine invocation.
9704 bool EverChanged = false;
9707 // There can be multiple store sequences on the same chain.
9708 // Keep trying to merge store sequences until we are unable to do so
9709 // or until we merge the last store on the chain.
9710 bool Changed = MergeConsecutiveStores(ST);
9711 EverChanged |= Changed;
9712 if (!Changed) break;
9713 } while (ST->getOpcode() != ISD::DELETED_NODE);
9716 return SDValue(N, 0);
9719 return ReduceLoadOpStoreWidth(N);
9722 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9723 SDValue InVec = N->getOperand(0);
9724 SDValue InVal = N->getOperand(1);
9725 SDValue EltNo = N->getOperand(2);
9728 // If the inserted element is an UNDEF, just use the input vector.
9729 if (InVal.getOpcode() == ISD::UNDEF)
9732 EVT VT = InVec.getValueType();
9734 // If we can't generate a legal BUILD_VECTOR, exit
9735 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9738 // Check that we know which element is being inserted
9739 if (!isa<ConstantSDNode>(EltNo))
9741 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9743 // Canonicalize insert_vector_elt dag nodes.
9745 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9746 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9748 // Do this only if the child insert_vector node has one use; also
9749 // do this only if indices are both constants and Idx1 < Idx0.
9750 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9751 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9753 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9754 if (Elt < OtherElt) {
9756 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9757 InVec.getOperand(0), InVal, EltNo);
9758 AddToWorkList(NewOp.getNode());
9759 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9760 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9764 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9765 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9767 SmallVector<SDValue, 8> Ops;
9768 // Do not combine these two vectors if the output vector will not replace
9769 // the input vector.
9770 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9771 Ops.append(InVec.getNode()->op_begin(),
9772 InVec.getNode()->op_end());
9773 } else if (InVec.getOpcode() == ISD::UNDEF) {
9774 unsigned NElts = VT.getVectorNumElements();
9775 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9780 // Insert the element
9781 if (Elt < Ops.size()) {
9782 // All the operands of BUILD_VECTOR must have the same type;
9783 // we enforce that here.
9784 EVT OpVT = Ops[0].getValueType();
9785 if (InVal.getValueType() != OpVT)
9786 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9787 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9788 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9792 // Return the new vector
9793 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9796 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9797 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9798 EVT ResultVT = EVE->getValueType(0);
9799 EVT VecEltVT = InVecVT.getVectorElementType();
9800 unsigned Align = OriginalLoad->getAlignment();
9801 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9802 VecEltVT.getTypeForEVT(*DAG.getContext()));
9804 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9809 SDValue NewPtr = OriginalLoad->getBasePtr();
9811 EVT PtrType = NewPtr.getValueType();
9812 MachinePointerInfo MPI;
9813 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9814 int Elt = ConstEltNo->getZExtValue();
9815 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9816 if (TLI.isBigEndian())
9817 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9818 Offset = DAG.getConstant(PtrOff, PtrType);
9819 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9821 Offset = DAG.getNode(
9822 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9823 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9824 if (TLI.isBigEndian())
9825 Offset = DAG.getNode(
9826 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9827 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9828 MPI = OriginalLoad->getPointerInfo();
9830 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9832 // The replacement we need to do here is a little tricky: we need to
9833 // replace an extractelement of a load with a load.
9834 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9835 // Note that this replacement assumes that the extractvalue is the only
9836 // use of the load; that's okay because we don't want to perform this
9837 // transformation in other cases anyway.
9840 if (ResultVT.bitsGT(VecEltVT)) {
9841 // If the result type of vextract is wider than the load, then issue an
9842 // extending load instead.
9843 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9846 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9847 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9848 OriginalLoad->isNonTemporal(), Align,
9849 OriginalLoad->getTBAAInfo());
9850 Chain = Load.getValue(1);
9853 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9854 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9855 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9856 Chain = Load.getValue(1);
9857 if (ResultVT.bitsLT(VecEltVT))
9858 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9860 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9862 WorkListRemover DeadNodes(*this);
9863 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9864 SDValue To[] = { Load, Chain };
9865 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9866 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9867 // worklist explicitly as well.
9868 AddToWorkList(Load.getNode());
9869 AddUsersToWorkList(Load.getNode()); // Add users too
9870 // Make sure to revisit this node to clean it up; it will usually be dead.
9873 return SDValue(EVE, 0);
9876 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9877 // (vextract (scalar_to_vector val, 0) -> val
9878 SDValue InVec = N->getOperand(0);
9879 EVT VT = InVec.getValueType();
9880 EVT NVT = N->getValueType(0);
9882 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9883 // Check if the result type doesn't match the inserted element type. A
9884 // SCALAR_TO_VECTOR may truncate the inserted element and the
9885 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9886 SDValue InOp = InVec.getOperand(0);
9887 if (InOp.getValueType() != NVT) {
9888 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9889 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9894 SDValue EltNo = N->getOperand(1);
9895 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9897 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9898 // We only perform this optimization before the op legalization phase because
9899 // we may introduce new vector instructions which are not backed by TD
9900 // patterns. For example on AVX, extracting elements from a wide vector
9901 // without using extract_subvector. However, if we can find an underlying
9902 // scalar value, then we can always use that.
9903 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9905 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9906 int NumElem = VT.getVectorNumElements();
9907 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9908 // Find the new index to extract from.
9909 int OrigElt = SVOp->getMaskElt(Elt);
9911 // Extracting an undef index is undef.
9913 return DAG.getUNDEF(NVT);
9915 // Select the right vector half to extract from.
9917 if (OrigElt < NumElem) {
9918 SVInVec = InVec->getOperand(0);
9920 SVInVec = InVec->getOperand(1);
9924 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9925 SDValue InOp = SVInVec.getOperand(OrigElt);
9926 if (InOp.getValueType() != NVT) {
9927 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9928 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9934 // FIXME: We should handle recursing on other vector shuffles and
9935 // scalar_to_vector here as well.
9937 if (!LegalOperations) {
9938 EVT IndexTy = TLI.getVectorIdxTy();
9939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9940 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9944 bool BCNumEltsChanged = false;
9945 EVT ExtVT = VT.getVectorElementType();
9948 // If the result of load has to be truncated, then it's not necessarily
9950 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9953 if (InVec.getOpcode() == ISD::BITCAST) {
9954 // Don't duplicate a load with other uses.
9955 if (!InVec.hasOneUse())
9958 EVT BCVT = InVec.getOperand(0).getValueType();
9959 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9961 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9962 BCNumEltsChanged = true;
9963 InVec = InVec.getOperand(0);
9964 ExtVT = BCVT.getVectorElementType();
9967 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9968 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9969 ISD::isNormalLoad(InVec.getNode())) {
9970 SDValue Index = N->getOperand(1);
9971 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9972 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9976 // Perform only after legalization to ensure build_vector / vector_shuffle
9977 // optimizations have already been done.
9978 if (!LegalOperations) return SDValue();
9980 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9981 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9982 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9985 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9987 LoadSDNode *LN0 = nullptr;
9988 const ShuffleVectorSDNode *SVN = nullptr;
9989 if (ISD::isNormalLoad(InVec.getNode())) {
9990 LN0 = cast<LoadSDNode>(InVec);
9991 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9992 InVec.getOperand(0).getValueType() == ExtVT &&
9993 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9994 // Don't duplicate a load with other uses.
9995 if (!InVec.hasOneUse())
9998 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9999 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10000 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10002 // (load $addr+1*size)
10004 // Don't duplicate a load with other uses.
10005 if (!InVec.hasOneUse())
10008 // If the bit convert changed the number of elements, it is unsafe
10009 // to examine the mask.
10010 if (BCNumEltsChanged)
10013 // Select the input vector, guarding against out of range extract vector.
10014 unsigned NumElems = VT.getVectorNumElements();
10015 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10016 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10018 if (InVec.getOpcode() == ISD::BITCAST) {
10019 // Don't duplicate a load with other uses.
10020 if (!InVec.hasOneUse())
10023 InVec = InVec.getOperand(0);
10025 if (ISD::isNormalLoad(InVec.getNode())) {
10026 LN0 = cast<LoadSDNode>(InVec);
10027 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10028 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10032 // Make sure we found a non-volatile load and the extractelement is
10034 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10037 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10039 return DAG.getUNDEF(LVT);
10041 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10047 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10048 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10049 // We perform this optimization post type-legalization because
10050 // the type-legalizer often scalarizes integer-promoted vectors.
10051 // Performing this optimization before may create bit-casts which
10052 // will be type-legalized to complex code sequences.
10053 // We perform this optimization only before the operation legalizer because we
10054 // may introduce illegal operations.
10055 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10058 unsigned NumInScalars = N->getNumOperands();
10060 EVT VT = N->getValueType(0);
10062 // Check to see if this is a BUILD_VECTOR of a bunch of values
10063 // which come from any_extend or zero_extend nodes. If so, we can create
10064 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10065 // optimizations. We do not handle sign-extend because we can't fill the sign
10067 EVT SourceType = MVT::Other;
10068 bool AllAnyExt = true;
10070 for (unsigned i = 0; i != NumInScalars; ++i) {
10071 SDValue In = N->getOperand(i);
10072 // Ignore undef inputs.
10073 if (In.getOpcode() == ISD::UNDEF) continue;
10075 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10076 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10078 // Abort if the element is not an extension.
10079 if (!ZeroExt && !AnyExt) {
10080 SourceType = MVT::Other;
10084 // The input is a ZeroExt or AnyExt. Check the original type.
10085 EVT InTy = In.getOperand(0).getValueType();
10087 // Check that all of the widened source types are the same.
10088 if (SourceType == MVT::Other)
10091 else if (InTy != SourceType) {
10092 // Multiple income types. Abort.
10093 SourceType = MVT::Other;
10097 // Check if all of the extends are ANY_EXTENDs.
10098 AllAnyExt &= AnyExt;
10101 // In order to have valid types, all of the inputs must be extended from the
10102 // same source type and all of the inputs must be any or zero extend.
10103 // Scalar sizes must be a power of two.
10104 EVT OutScalarTy = VT.getScalarType();
10105 bool ValidTypes = SourceType != MVT::Other &&
10106 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10107 isPowerOf2_32(SourceType.getSizeInBits());
10109 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10110 // turn into a single shuffle instruction.
10114 bool isLE = TLI.isLittleEndian();
10115 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10116 assert(ElemRatio > 1 && "Invalid element size ratio");
10117 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10118 DAG.getConstant(0, SourceType);
10120 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10121 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10123 // Populate the new build_vector
10124 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10125 SDValue Cast = N->getOperand(i);
10126 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10127 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10128 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10130 if (Cast.getOpcode() == ISD::UNDEF)
10131 In = DAG.getUNDEF(SourceType);
10133 In = Cast->getOperand(0);
10134 unsigned Index = isLE ? (i * ElemRatio) :
10135 (i * ElemRatio + (ElemRatio - 1));
10137 assert(Index < Ops.size() && "Invalid index");
10141 // The type of the new BUILD_VECTOR node.
10142 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10143 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10144 "Invalid vector size");
10145 // Check if the new vector type is legal.
10146 if (!isTypeLegal(VecVT)) return SDValue();
10148 // Make the new BUILD_VECTOR.
10149 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10151 // The new BUILD_VECTOR node has the potential to be further optimized.
10152 AddToWorkList(BV.getNode());
10153 // Bitcast to the desired type.
10154 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10157 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10158 EVT VT = N->getValueType(0);
10160 unsigned NumInScalars = N->getNumOperands();
10163 EVT SrcVT = MVT::Other;
10164 unsigned Opcode = ISD::DELETED_NODE;
10165 unsigned NumDefs = 0;
10167 for (unsigned i = 0; i != NumInScalars; ++i) {
10168 SDValue In = N->getOperand(i);
10169 unsigned Opc = In.getOpcode();
10171 if (Opc == ISD::UNDEF)
10174 // If all scalar values are floats and converted from integers.
10175 if (Opcode == ISD::DELETED_NODE &&
10176 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10183 EVT InVT = In.getOperand(0).getValueType();
10185 // If all scalar values are typed differently, bail out. It's chosen to
10186 // simplify BUILD_VECTOR of integer types.
10187 if (SrcVT == MVT::Other)
10194 // If the vector has just one element defined, it's not worth to fold it into
10195 // a vectorized one.
10199 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10200 && "Should only handle conversion from integer to float.");
10201 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10203 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10205 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10208 SmallVector<SDValue, 8> Opnds;
10209 for (unsigned i = 0; i != NumInScalars; ++i) {
10210 SDValue In = N->getOperand(i);
10212 if (In.getOpcode() == ISD::UNDEF)
10213 Opnds.push_back(DAG.getUNDEF(SrcVT));
10215 Opnds.push_back(In.getOperand(0));
10217 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10218 AddToWorkList(BV.getNode());
10220 return DAG.getNode(Opcode, dl, VT, BV);
10223 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10224 unsigned NumInScalars = N->getNumOperands();
10226 EVT VT = N->getValueType(0);
10228 // A vector built entirely of undefs is undef.
10229 if (ISD::allOperandsUndef(N))
10230 return DAG.getUNDEF(VT);
10232 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10236 V = reduceBuildVecConvertToConvertBuildVec(N);
10240 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10241 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10242 // at most two distinct vectors, turn this into a shuffle node.
10244 // May only combine to shuffle after legalize if shuffle is legal.
10245 if (LegalOperations &&
10246 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10249 SDValue VecIn1, VecIn2;
10250 for (unsigned i = 0; i != NumInScalars; ++i) {
10251 // Ignore undef inputs.
10252 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10254 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10255 // constant index, bail out.
10256 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10257 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10258 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10262 // We allow up to two distinct input vectors.
10263 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10264 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10267 if (!VecIn1.getNode()) {
10268 VecIn1 = ExtractedFromVec;
10269 } else if (!VecIn2.getNode()) {
10270 VecIn2 = ExtractedFromVec;
10272 // Too many inputs.
10273 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10278 // If everything is good, we can make a shuffle operation.
10279 if (VecIn1.getNode()) {
10280 SmallVector<int, 8> Mask;
10281 for (unsigned i = 0; i != NumInScalars; ++i) {
10282 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10283 Mask.push_back(-1);
10287 // If extracting from the first vector, just use the index directly.
10288 SDValue Extract = N->getOperand(i);
10289 SDValue ExtVal = Extract.getOperand(1);
10290 if (Extract.getOperand(0) == VecIn1) {
10291 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10292 if (ExtIndex > VT.getVectorNumElements())
10295 Mask.push_back(ExtIndex);
10299 // Otherwise, use InIdx + VecSize
10300 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10301 Mask.push_back(Idx+NumInScalars);
10304 // We can't generate a shuffle node with mismatched input and output types.
10305 // Attempt to transform a single input vector to the correct type.
10306 if ((VT != VecIn1.getValueType())) {
10307 // We don't support shuffeling between TWO values of different types.
10308 if (VecIn2.getNode())
10311 // We only support widening of vectors which are half the size of the
10312 // output registers. For example XMM->YMM widening on X86 with AVX.
10313 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10316 // If the input vector type has a different base type to the output
10317 // vector type, bail out.
10318 if (VecIn1.getValueType().getVectorElementType() !=
10319 VT.getVectorElementType())
10322 // Widen the input vector by adding undef values.
10323 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10324 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10327 // If VecIn2 is unused then change it to undef.
10328 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10330 // Check that we were able to transform all incoming values to the same
10332 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10333 VecIn1.getValueType() != VT)
10336 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10337 if (!isTypeLegal(VT))
10340 // Return the new VECTOR_SHUFFLE node.
10344 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10350 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10351 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10352 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10353 // inputs come from at most two distinct vectors, turn this into a shuffle
10356 // If we only have one input vector, we don't need to do any concatenation.
10357 if (N->getNumOperands() == 1)
10358 return N->getOperand(0);
10360 // Check if all of the operands are undefs.
10361 EVT VT = N->getValueType(0);
10362 if (ISD::allOperandsUndef(N))
10363 return DAG.getUNDEF(VT);
10365 // Optimize concat_vectors where one of the vectors is undef.
10366 if (N->getNumOperands() == 2 &&
10367 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10368 SDValue In = N->getOperand(0);
10369 assert(In.getValueType().isVector() && "Must concat vectors");
10371 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10372 if (In->getOpcode() == ISD::BITCAST &&
10373 !In->getOperand(0)->getValueType(0).isVector()) {
10374 SDValue Scalar = In->getOperand(0);
10375 EVT SclTy = Scalar->getValueType(0);
10377 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10380 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10381 VT.getSizeInBits() / SclTy.getSizeInBits());
10382 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10385 SDLoc dl = SDLoc(N);
10386 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10387 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10391 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10392 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10393 if (N->getNumOperands() == 2 &&
10394 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10395 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10396 EVT VT = N->getValueType(0);
10397 SDValue N0 = N->getOperand(0);
10398 SDValue N1 = N->getOperand(1);
10399 SmallVector<SDValue, 8> Opnds;
10400 unsigned BuildVecNumElts = N0.getNumOperands();
10402 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10403 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10404 if (SclTy0.isFloatingPoint()) {
10405 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10406 Opnds.push_back(N0.getOperand(i));
10407 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10408 Opnds.push_back(N1.getOperand(i));
10410 // If BUILD_VECTOR are from built from integer, they may have different
10411 // operand types. Get the smaller type and truncate all operands to it.
10412 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10413 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10414 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10415 N0.getOperand(i)));
10416 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10417 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10418 N1.getOperand(i)));
10421 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10424 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10425 // nodes often generate nop CONCAT_VECTOR nodes.
10426 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10427 // place the incoming vectors at the exact same location.
10428 SDValue SingleSource = SDValue();
10429 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10431 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10432 SDValue Op = N->getOperand(i);
10434 if (Op.getOpcode() == ISD::UNDEF)
10437 // Check if this is the identity extract:
10438 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10441 // Find the single incoming vector for the extract_subvector.
10442 if (SingleSource.getNode()) {
10443 if (Op.getOperand(0) != SingleSource)
10446 SingleSource = Op.getOperand(0);
10448 // Check the source type is the same as the type of the result.
10449 // If not, this concat may extend the vector, so we can not
10450 // optimize it away.
10451 if (SingleSource.getValueType() != N->getValueType(0))
10455 unsigned IdentityIndex = i * PartNumElem;
10456 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10457 // The extract index must be constant.
10461 // Check that we are reading from the identity index.
10462 if (CS->getZExtValue() != IdentityIndex)
10466 if (SingleSource.getNode())
10467 return SingleSource;
10472 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10473 EVT NVT = N->getValueType(0);
10474 SDValue V = N->getOperand(0);
10476 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10478 // (extract_subvec (concat V1, V2, ...), i)
10481 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10483 if (V->getOperand(0).getValueType() != NVT)
10485 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10486 unsigned NumElems = NVT.getVectorNumElements();
10487 assert((Idx % NumElems) == 0 &&
10488 "IDX in concat is not a multiple of the result vector length.");
10489 return V->getOperand(Idx / NumElems);
10493 if (V->getOpcode() == ISD::BITCAST)
10494 V = V.getOperand(0);
10496 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10498 // Handle only simple case where vector being inserted and vector
10499 // being extracted are of same type, and are half size of larger vectors.
10500 EVT BigVT = V->getOperand(0).getValueType();
10501 EVT SmallVT = V->getOperand(1).getValueType();
10502 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10505 // Only handle cases where both indexes are constants with the same type.
10506 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10507 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10509 if (InsIdx && ExtIdx &&
10510 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10511 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10513 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10515 // indices are equal or bit offsets are equal => V1
10516 // otherwise => (extract_subvec V1, ExtIdx)
10517 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10518 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10519 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10520 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10521 DAG.getNode(ISD::BITCAST, dl,
10522 N->getOperand(0).getValueType(),
10523 V->getOperand(0)), N->getOperand(1));
10530 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10531 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10532 EVT VT = N->getValueType(0);
10533 unsigned NumElts = VT.getVectorNumElements();
10535 SDValue N0 = N->getOperand(0);
10536 SDValue N1 = N->getOperand(1);
10537 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10539 SmallVector<SDValue, 4> Ops;
10540 EVT ConcatVT = N0.getOperand(0).getValueType();
10541 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10542 unsigned NumConcats = NumElts / NumElemsPerConcat;
10544 // Look at every vector that's inserted. We're looking for exact
10545 // subvector-sized copies from a concatenated vector
10546 for (unsigned I = 0; I != NumConcats; ++I) {
10547 // Make sure we're dealing with a copy.
10548 unsigned Begin = I * NumElemsPerConcat;
10549 bool AllUndef = true, NoUndef = true;
10550 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10551 if (SVN->getMaskElt(J) >= 0)
10558 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10561 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10562 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10565 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10566 if (FirstElt < N0.getNumOperands())
10567 Ops.push_back(N0.getOperand(FirstElt));
10569 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10571 } else if (AllUndef) {
10572 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10573 } else { // Mixed with general masks and undefs, can't do optimization.
10578 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10581 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10582 EVT VT = N->getValueType(0);
10583 unsigned NumElts = VT.getVectorNumElements();
10585 SDValue N0 = N->getOperand(0);
10586 SDValue N1 = N->getOperand(1);
10588 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10590 // Canonicalize shuffle undef, undef -> undef
10591 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10592 return DAG.getUNDEF(VT);
10594 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10596 // Canonicalize shuffle v, v -> v, undef
10598 SmallVector<int, 8> NewMask;
10599 for (unsigned i = 0; i != NumElts; ++i) {
10600 int Idx = SVN->getMaskElt(i);
10601 if (Idx >= (int)NumElts) Idx -= NumElts;
10602 NewMask.push_back(Idx);
10604 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10608 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10609 if (N0.getOpcode() == ISD::UNDEF) {
10610 SmallVector<int, 8> NewMask;
10611 for (unsigned i = 0; i != NumElts; ++i) {
10612 int Idx = SVN->getMaskElt(i);
10614 if (Idx >= (int)NumElts)
10617 Idx = -1; // remove reference to lhs
10619 NewMask.push_back(Idx);
10621 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10625 // Remove references to rhs if it is undef
10626 if (N1.getOpcode() == ISD::UNDEF) {
10627 bool Changed = false;
10628 SmallVector<int, 8> NewMask;
10629 for (unsigned i = 0; i != NumElts; ++i) {
10630 int Idx = SVN->getMaskElt(i);
10631 if (Idx >= (int)NumElts) {
10635 NewMask.push_back(Idx);
10638 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10641 // If it is a splat, check if the argument vector is another splat or a
10642 // build_vector with all scalar elements the same.
10643 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10644 SDNode *V = N0.getNode();
10646 // If this is a bit convert that changes the element type of the vector but
10647 // not the number of vector elements, look through it. Be careful not to
10648 // look though conversions that change things like v4f32 to v2f64.
10649 if (V->getOpcode() == ISD::BITCAST) {
10650 SDValue ConvInput = V->getOperand(0);
10651 if (ConvInput.getValueType().isVector() &&
10652 ConvInput.getValueType().getVectorNumElements() == NumElts)
10653 V = ConvInput.getNode();
10656 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10657 assert(V->getNumOperands() == NumElts &&
10658 "BUILD_VECTOR has wrong number of operands");
10660 bool AllSame = true;
10661 for (unsigned i = 0; i != NumElts; ++i) {
10662 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10663 Base = V->getOperand(i);
10667 // Splat of <u, u, u, u>, return <u, u, u, u>
10668 if (!Base.getNode())
10670 for (unsigned i = 0; i != NumElts; ++i) {
10671 if (V->getOperand(i) != Base) {
10676 // Splat of <x, x, x, x>, return <x, x, x, x>
10682 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10683 Level < AfterLegalizeVectorOps &&
10684 (N1.getOpcode() == ISD::UNDEF ||
10685 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10686 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10687 SDValue V = partitionShuffleOfConcats(N, DAG);
10693 // If this shuffle node is simply a swizzle of another shuffle node,
10694 // and it reverses the swizzle of the previous shuffle then we can
10695 // optimize shuffle(shuffle(x, undef), undef) -> x.
10696 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10697 N1.getOpcode() == ISD::UNDEF) {
10699 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10701 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10702 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10705 // The incoming shuffle must be of the same type as the result of the
10706 // current shuffle.
10707 assert(OtherSV->getOperand(0).getValueType() == VT &&
10708 "Shuffle types don't match");
10710 SmallVector<int, 4> Mask;
10711 // Compute the combined shuffle mask.
10712 for (unsigned i = 0; i != NumElts; ++i) {
10713 int Idx = SVN->getMaskElt(i);
10714 assert(Idx < (int)NumElts && "Index references undef operand");
10715 // Next, this index comes from the first value, which is the incoming
10716 // shuffle. Adopt the incoming index.
10718 Idx = OtherSV->getMaskElt(Idx);
10719 Mask.push_back(Idx);
10722 bool IsIdentityMask = true;
10723 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10728 // The combined shuffle must map each index to itself.
10729 IsIdentityMask = (unsigned)Mask[i] == i;
10732 if (IsIdentityMask)
10733 // optimize shuffle(shuffle(x, undef), undef) -> x.
10734 return OtherSV->getOperand(0);
10736 // It may still be beneficial to combine the two shuffles if the
10737 // resulting shuffle is legal.
10738 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10739 if (TLI.isShuffleMaskLegal(Mask, VT))
10740 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10747 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10748 SDValue N0 = N->getOperand(0);
10749 SDValue N2 = N->getOperand(2);
10751 // If the input vector is a concatenation, and the insert replaces
10752 // one of the halves, we can optimize into a single concat_vectors.
10753 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10754 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10755 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10756 EVT VT = N->getValueType(0);
10758 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10759 // (concat_vectors Z, Y)
10761 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10762 N->getOperand(1), N0.getOperand(1));
10764 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10765 // (concat_vectors X, Z)
10766 if (InsIdx == VT.getVectorNumElements()/2)
10767 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10768 N0.getOperand(0), N->getOperand(1));
10774 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10775 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10776 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10777 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10778 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10779 EVT VT = N->getValueType(0);
10781 SDValue LHS = N->getOperand(0);
10782 SDValue RHS = N->getOperand(1);
10783 if (N->getOpcode() == ISD::AND) {
10784 if (RHS.getOpcode() == ISD::BITCAST)
10785 RHS = RHS.getOperand(0);
10786 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10787 SmallVector<int, 8> Indices;
10788 unsigned NumElts = RHS.getNumOperands();
10789 for (unsigned i = 0; i != NumElts; ++i) {
10790 SDValue Elt = RHS.getOperand(i);
10791 if (!isa<ConstantSDNode>(Elt))
10794 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10795 Indices.push_back(i);
10796 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10797 Indices.push_back(NumElts);
10802 // Let's see if the target supports this vector_shuffle.
10803 EVT RVT = RHS.getValueType();
10804 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10807 // Return the new VECTOR_SHUFFLE node.
10808 EVT EltVT = RVT.getVectorElementType();
10809 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10810 DAG.getConstant(0, EltVT));
10811 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10812 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10813 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10814 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10821 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10822 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10823 assert(N->getValueType(0).isVector() &&
10824 "SimplifyVBinOp only works on vectors!");
10826 SDValue LHS = N->getOperand(0);
10827 SDValue RHS = N->getOperand(1);
10828 SDValue Shuffle = XformToShuffleWithZero(N);
10829 if (Shuffle.getNode()) return Shuffle;
10831 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10833 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10834 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10835 // Check if both vectors are constants. If not bail out.
10836 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10837 cast<BuildVectorSDNode>(RHS)->isConstant()))
10840 SmallVector<SDValue, 8> Ops;
10841 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10842 SDValue LHSOp = LHS.getOperand(i);
10843 SDValue RHSOp = RHS.getOperand(i);
10845 // Can't fold divide by zero.
10846 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10847 N->getOpcode() == ISD::FDIV) {
10848 if ((RHSOp.getOpcode() == ISD::Constant &&
10849 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10850 (RHSOp.getOpcode() == ISD::ConstantFP &&
10851 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10855 EVT VT = LHSOp.getValueType();
10856 EVT RVT = RHSOp.getValueType();
10858 // Integer BUILD_VECTOR operands may have types larger than the element
10859 // size (e.g., when the element type is not legal). Prior to type
10860 // legalization, the types may not match between the two BUILD_VECTORS.
10861 // Truncate one of the operands to make them match.
10862 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10863 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10865 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10869 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10871 if (FoldOp.getOpcode() != ISD::UNDEF &&
10872 FoldOp.getOpcode() != ISD::Constant &&
10873 FoldOp.getOpcode() != ISD::ConstantFP)
10875 Ops.push_back(FoldOp);
10876 AddToWorkList(FoldOp.getNode());
10879 if (Ops.size() == LHS.getNumOperands())
10880 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10883 // Type legalization might introduce new shuffles in the DAG.
10884 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10885 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10886 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10887 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10888 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10889 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10890 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10891 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10893 if (SVN0->getMask().equals(SVN1->getMask())) {
10894 EVT VT = N->getValueType(0);
10895 SDValue UndefVector = LHS.getOperand(1);
10896 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10897 LHS.getOperand(0), RHS.getOperand(0));
10898 AddUsersToWorkList(N);
10899 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10900 &SVN0->getMask()[0]);
10907 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10908 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10909 assert(N->getValueType(0).isVector() &&
10910 "SimplifyVUnaryOp only works on vectors!");
10912 SDValue N0 = N->getOperand(0);
10914 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10917 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10918 SmallVector<SDValue, 8> Ops;
10919 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10920 SDValue Op = N0.getOperand(i);
10921 if (Op.getOpcode() != ISD::UNDEF &&
10922 Op.getOpcode() != ISD::ConstantFP)
10924 EVT EltVT = Op.getValueType();
10925 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10926 if (FoldOp.getOpcode() != ISD::UNDEF &&
10927 FoldOp.getOpcode() != ISD::ConstantFP)
10929 Ops.push_back(FoldOp);
10930 AddToWorkList(FoldOp.getNode());
10933 if (Ops.size() != N0.getNumOperands())
10936 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10939 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10940 SDValue N1, SDValue N2){
10941 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10943 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10944 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10946 // If we got a simplified select_cc node back from SimplifySelectCC, then
10947 // break it down into a new SETCC node, and a new SELECT node, and then return
10948 // the SELECT node, since we were called with a SELECT node.
10949 if (SCC.getNode()) {
10950 // Check to see if we got a select_cc back (to turn into setcc/select).
10951 // Otherwise, just return whatever node we got back, like fabs.
10952 if (SCC.getOpcode() == ISD::SELECT_CC) {
10953 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10955 SCC.getOperand(0), SCC.getOperand(1),
10956 SCC.getOperand(4));
10957 AddToWorkList(SETCC.getNode());
10958 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10959 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10967 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10968 /// are the two values being selected between, see if we can simplify the
10969 /// select. Callers of this should assume that TheSelect is deleted if this
10970 /// returns true. As such, they should return the appropriate thing (e.g. the
10971 /// node) back to the top-level of the DAG combiner loop to avoid it being
10973 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10976 // Cannot simplify select with vector condition
10977 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10979 // If this is a select from two identical things, try to pull the operation
10980 // through the select.
10981 if (LHS.getOpcode() != RHS.getOpcode() ||
10982 !LHS.hasOneUse() || !RHS.hasOneUse())
10985 // If this is a load and the token chain is identical, replace the select
10986 // of two loads with a load through a select of the address to load from.
10987 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10988 // constants have been dropped into the constant pool.
10989 if (LHS.getOpcode() == ISD::LOAD) {
10990 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10991 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10993 // Token chains must be identical.
10994 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10995 // Do not let this transformation reduce the number of volatile loads.
10996 LLD->isVolatile() || RLD->isVolatile() ||
10997 // If this is an EXTLOAD, the VT's must match.
10998 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10999 // If this is an EXTLOAD, the kind of extension must match.
11000 (LLD->getExtensionType() != RLD->getExtensionType() &&
11001 // The only exception is if one of the extensions is anyext.
11002 LLD->getExtensionType() != ISD::EXTLOAD &&
11003 RLD->getExtensionType() != ISD::EXTLOAD) ||
11004 // FIXME: this discards src value information. This is
11005 // over-conservative. It would be beneficial to be able to remember
11006 // both potential memory locations. Since we are discarding
11007 // src value info, don't do the transformation if the memory
11008 // locations are not in the default address space.
11009 LLD->getPointerInfo().getAddrSpace() != 0 ||
11010 RLD->getPointerInfo().getAddrSpace() != 0 ||
11011 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11012 LLD->getBasePtr().getValueType()))
11015 // Check that the select condition doesn't reach either load. If so,
11016 // folding this will induce a cycle into the DAG. If not, this is safe to
11017 // xform, so create a select of the addresses.
11019 if (TheSelect->getOpcode() == ISD::SELECT) {
11020 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11021 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11022 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11024 // The loads must not depend on one another.
11025 if (LLD->isPredecessorOf(RLD) ||
11026 RLD->isPredecessorOf(LLD))
11028 Addr = DAG.getSelect(SDLoc(TheSelect),
11029 LLD->getBasePtr().getValueType(),
11030 TheSelect->getOperand(0), LLD->getBasePtr(),
11031 RLD->getBasePtr());
11032 } else { // Otherwise SELECT_CC
11033 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11034 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11036 if ((LLD->hasAnyUseOfValue(1) &&
11037 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11038 (RLD->hasAnyUseOfValue(1) &&
11039 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11042 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11043 LLD->getBasePtr().getValueType(),
11044 TheSelect->getOperand(0),
11045 TheSelect->getOperand(1),
11046 LLD->getBasePtr(), RLD->getBasePtr(),
11047 TheSelect->getOperand(4));
11051 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11052 Load = DAG.getLoad(TheSelect->getValueType(0),
11054 // FIXME: Discards pointer and TBAA info.
11055 LLD->getChain(), Addr, MachinePointerInfo(),
11056 LLD->isVolatile(), LLD->isNonTemporal(),
11057 LLD->isInvariant(), LLD->getAlignment());
11059 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11060 RLD->getExtensionType() : LLD->getExtensionType(),
11062 TheSelect->getValueType(0),
11063 // FIXME: Discards pointer and TBAA info.
11064 LLD->getChain(), Addr, MachinePointerInfo(),
11065 LLD->getMemoryVT(), LLD->isVolatile(),
11066 LLD->isNonTemporal(), LLD->getAlignment());
11069 // Users of the select now use the result of the load.
11070 CombineTo(TheSelect, Load);
11072 // Users of the old loads now use the new load's chain. We know the
11073 // old-load value is dead now.
11074 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11075 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11082 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11083 /// where 'cond' is the comparison specified by CC.
11084 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11085 SDValue N2, SDValue N3,
11086 ISD::CondCode CC, bool NotExtCompare) {
11087 // (x ? y : y) -> y.
11088 if (N2 == N3) return N2;
11090 EVT VT = N2.getValueType();
11091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11092 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11093 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11095 // Determine if the condition we're dealing with is constant
11096 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11097 N0, N1, CC, DL, false);
11098 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11099 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11101 // fold select_cc true, x, y -> x
11102 if (SCCC && !SCCC->isNullValue())
11104 // fold select_cc false, x, y -> y
11105 if (SCCC && SCCC->isNullValue())
11108 // Check to see if we can simplify the select into an fabs node
11109 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11110 // Allow either -0.0 or 0.0
11111 if (CFP->getValueAPF().isZero()) {
11112 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11113 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11114 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11115 N2 == N3.getOperand(0))
11116 return DAG.getNode(ISD::FABS, DL, VT, N0);
11118 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11119 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11120 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11121 N2.getOperand(0) == N3)
11122 return DAG.getNode(ISD::FABS, DL, VT, N3);
11126 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11127 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11128 // in it. This is a win when the constant is not otherwise available because
11129 // it replaces two constant pool loads with one. We only do this if the FP
11130 // type is known to be legal, because if it isn't, then we are before legalize
11131 // types an we want the other legalization to happen first (e.g. to avoid
11132 // messing with soft float) and if the ConstantFP is not legal, because if
11133 // it is legal, we may not need to store the FP constant in a constant pool.
11134 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11135 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11136 if (TLI.isTypeLegal(N2.getValueType()) &&
11137 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11138 TargetLowering::Legal &&
11139 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11140 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11141 // If both constants have multiple uses, then we won't need to do an
11142 // extra load, they are likely around in registers for other users.
11143 (TV->hasOneUse() || FV->hasOneUse())) {
11144 Constant *Elts[] = {
11145 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11146 const_cast<ConstantFP*>(TV->getConstantFPValue())
11148 Type *FPTy = Elts[0]->getType();
11149 const DataLayout &TD = *TLI.getDataLayout();
11151 // Create a ConstantArray of the two constants.
11152 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11153 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11154 TD.getPrefTypeAlignment(FPTy));
11155 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11157 // Get the offsets to the 0 and 1 element of the array so that we can
11158 // select between them.
11159 SDValue Zero = DAG.getIntPtrConstant(0);
11160 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11161 SDValue One = DAG.getIntPtrConstant(EltSize);
11163 SDValue Cond = DAG.getSetCC(DL,
11164 getSetCCResultType(N0.getValueType()),
11166 AddToWorkList(Cond.getNode());
11167 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11169 AddToWorkList(CstOffset.getNode());
11170 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11172 AddToWorkList(CPIdx.getNode());
11173 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11174 MachinePointerInfo::getConstantPool(), false,
11175 false, false, Alignment);
11180 // Check to see if we can perform the "gzip trick", transforming
11181 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11182 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11183 (N1C->isNullValue() || // (a < 0) ? b : 0
11184 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11185 EVT XType = N0.getValueType();
11186 EVT AType = N2.getValueType();
11187 if (XType.bitsGE(AType)) {
11188 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11189 // single-bit constant.
11190 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11191 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11192 ShCtV = XType.getSizeInBits()-ShCtV-1;
11193 SDValue ShCt = DAG.getConstant(ShCtV,
11194 getShiftAmountTy(N0.getValueType()));
11195 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11197 AddToWorkList(Shift.getNode());
11199 if (XType.bitsGT(AType)) {
11200 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11201 AddToWorkList(Shift.getNode());
11204 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11207 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11209 DAG.getConstant(XType.getSizeInBits()-1,
11210 getShiftAmountTy(N0.getValueType())));
11211 AddToWorkList(Shift.getNode());
11213 if (XType.bitsGT(AType)) {
11214 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11215 AddToWorkList(Shift.getNode());
11218 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11222 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11223 // where y is has a single bit set.
11224 // A plaintext description would be, we can turn the SELECT_CC into an AND
11225 // when the condition can be materialized as an all-ones register. Any
11226 // single bit-test can be materialized as an all-ones register with
11227 // shift-left and shift-right-arith.
11228 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11229 N0->getValueType(0) == VT &&
11230 N1C && N1C->isNullValue() &&
11231 N2C && N2C->isNullValue()) {
11232 SDValue AndLHS = N0->getOperand(0);
11233 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11234 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11235 // Shift the tested bit over the sign bit.
11236 APInt AndMask = ConstAndRHS->getAPIntValue();
11238 DAG.getConstant(AndMask.countLeadingZeros(),
11239 getShiftAmountTy(AndLHS.getValueType()));
11240 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11242 // Now arithmetic right shift it all the way over, so the result is either
11243 // all-ones, or zero.
11245 DAG.getConstant(AndMask.getBitWidth()-1,
11246 getShiftAmountTy(Shl.getValueType()));
11247 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11249 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11253 // fold select C, 16, 0 -> shl C, 4
11254 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11255 TLI.getBooleanContents(N0.getValueType()) ==
11256 TargetLowering::ZeroOrOneBooleanContent) {
11258 // If the caller doesn't want us to simplify this into a zext of a compare,
11260 if (NotExtCompare && N2C->getAPIntValue() == 1)
11263 // Get a SetCC of the condition
11264 // NOTE: Don't create a SETCC if it's not legal on this target.
11265 if (!LegalOperations ||
11266 TLI.isOperationLegal(ISD::SETCC,
11267 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11269 // cast from setcc result type to select result type
11271 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11273 if (N2.getValueType().bitsLT(SCC.getValueType()))
11274 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11275 N2.getValueType());
11277 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11278 N2.getValueType(), SCC);
11280 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11281 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11282 N2.getValueType(), SCC);
11285 AddToWorkList(SCC.getNode());
11286 AddToWorkList(Temp.getNode());
11288 if (N2C->getAPIntValue() == 1)
11291 // shl setcc result by log2 n2c
11292 return DAG.getNode(
11293 ISD::SHL, DL, N2.getValueType(), Temp,
11294 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11295 getShiftAmountTy(Temp.getValueType())));
11299 // Check to see if this is the equivalent of setcc
11300 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11301 // otherwise, go ahead with the folds.
11302 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11303 EVT XType = N0.getValueType();
11304 if (!LegalOperations ||
11305 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11306 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11307 if (Res.getValueType() != VT)
11308 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11312 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11313 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11314 (!LegalOperations ||
11315 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11316 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11317 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11318 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11319 getShiftAmountTy(Ctlz.getValueType())));
11321 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11322 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11323 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11324 XType, DAG.getConstant(0, XType), N0);
11325 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11326 return DAG.getNode(ISD::SRL, DL, XType,
11327 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11328 DAG.getConstant(XType.getSizeInBits()-1,
11329 getShiftAmountTy(XType)));
11331 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11332 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11333 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11334 DAG.getConstant(XType.getSizeInBits()-1,
11335 getShiftAmountTy(N0.getValueType())));
11336 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11340 // Check to see if this is an integer abs.
11341 // select_cc setg[te] X, 0, X, -X ->
11342 // select_cc setgt X, -1, X, -X ->
11343 // select_cc setl[te] X, 0, -X, X ->
11344 // select_cc setlt X, 1, -X, X ->
11345 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11347 ConstantSDNode *SubC = nullptr;
11348 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11349 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11350 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11351 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11352 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11353 (N1C->isOne() && CC == ISD::SETLT)) &&
11354 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11355 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11357 EVT XType = N0.getValueType();
11358 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11359 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11361 DAG.getConstant(XType.getSizeInBits()-1,
11362 getShiftAmountTy(N0.getValueType())));
11363 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11365 AddToWorkList(Shift.getNode());
11366 AddToWorkList(Add.getNode());
11367 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11374 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11375 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11376 SDValue N1, ISD::CondCode Cond,
11377 SDLoc DL, bool foldBooleans) {
11378 TargetLowering::DAGCombinerInfo
11379 DagCombineInfo(DAG, Level, false, this);
11380 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11383 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11384 /// return a DAG expression to select that will generate the same value by
11385 /// multiplying by a magic number. See:
11386 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11387 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11388 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11392 // Avoid division by zero.
11393 if (!C->getAPIntValue())
11396 std::vector<SDNode*> Built;
11398 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11400 for (SDNode *N : Built)
11405 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11406 /// return a DAG expression to select that will generate the same value by
11407 /// multiplying by a magic number. See:
11408 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11409 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11410 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11414 // Avoid division by zero.
11415 if (!C->getAPIntValue())
11418 std::vector<SDNode*> Built;
11420 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11422 for (SDNode *N : Built)
11427 /// FindBaseOffset - Return true if base is a frame index, which is known not
11428 // to alias with anything but itself. Provides base object and offset as
11430 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11431 const GlobalValue *&GV, const void *&CV) {
11432 // Assume it is a primitive operation.
11433 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11435 // If it's an adding a simple constant then integrate the offset.
11436 if (Base.getOpcode() == ISD::ADD) {
11437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11438 Base = Base.getOperand(0);
11439 Offset += C->getZExtValue();
11443 // Return the underlying GlobalValue, and update the Offset. Return false
11444 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11445 // by multiple nodes with different offsets.
11446 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11447 GV = G->getGlobal();
11448 Offset += G->getOffset();
11452 // Return the underlying Constant value, and update the Offset. Return false
11453 // for ConstantSDNodes since the same constant pool entry may be represented
11454 // by multiple nodes with different offsets.
11455 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11456 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11457 : (const void *)C->getConstVal();
11458 Offset += C->getOffset();
11461 // If it's any of the following then it can't alias with anything but itself.
11462 return isa<FrameIndexSDNode>(Base);
11465 /// isAlias - Return true if there is any possibility that the two addresses
11467 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11468 // If they are the same then they must be aliases.
11469 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11471 // If they are both volatile then they cannot be reordered.
11472 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11474 // Gather base node and offset information.
11475 SDValue Base1, Base2;
11476 int64_t Offset1, Offset2;
11477 const GlobalValue *GV1, *GV2;
11478 const void *CV1, *CV2;
11479 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11480 Base1, Offset1, GV1, CV1);
11481 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11482 Base2, Offset2, GV2, CV2);
11484 // If they have a same base address then check to see if they overlap.
11485 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11486 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11487 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11489 // It is possible for different frame indices to alias each other, mostly
11490 // when tail call optimization reuses return address slots for arguments.
11491 // To catch this case, look up the actual index of frame indices to compute
11492 // the real alias relationship.
11493 if (isFrameIndex1 && isFrameIndex2) {
11494 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11495 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11496 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11497 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11498 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11501 // Otherwise, if we know what the bases are, and they aren't identical, then
11502 // we know they cannot alias.
11503 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11506 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11507 // compared to the size and offset of the access, we may be able to prove they
11508 // do not alias. This check is conservative for now to catch cases created by
11509 // splitting vector types.
11510 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11511 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11512 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11513 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11514 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11515 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11516 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11518 // There is no overlap between these relatively aligned accesses of similar
11519 // size, return no alias.
11520 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11521 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11525 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11526 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11528 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11529 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11533 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11534 // Use alias analysis information.
11535 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11536 Op1->getSrcValueOffset());
11537 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11538 Op0->getSrcValueOffset() - MinOffset;
11539 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11540 Op1->getSrcValueOffset() - MinOffset;
11541 AliasAnalysis::AliasResult AAResult =
11542 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11544 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11545 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11547 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11548 if (AAResult == AliasAnalysis::NoAlias)
11552 // Otherwise we have to assume they alias.
11556 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11557 /// looking for aliasing nodes and adding them to the Aliases vector.
11558 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11559 SmallVectorImpl<SDValue> &Aliases) {
11560 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11561 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11563 // Get alias information for node.
11564 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11567 Chains.push_back(OriginalChain);
11568 unsigned Depth = 0;
11570 // Look at each chain and determine if it is an alias. If so, add it to the
11571 // aliases list. If not, then continue up the chain looking for the next
11573 while (!Chains.empty()) {
11574 SDValue Chain = Chains.back();
11577 // For TokenFactor nodes, look at each operand and only continue up the
11578 // chain until we find two aliases. If we've seen two aliases, assume we'll
11579 // find more and revert to original chain since the xform is unlikely to be
11582 // FIXME: The depth check could be made to return the last non-aliasing
11583 // chain we found before we hit a tokenfactor rather than the original
11585 if (Depth > 6 || Aliases.size() == 2) {
11587 Aliases.push_back(OriginalChain);
11591 // Don't bother if we've been before.
11592 if (!Visited.insert(Chain.getNode()))
11595 switch (Chain.getOpcode()) {
11596 case ISD::EntryToken:
11597 // Entry token is ideal chain operand, but handled in FindBetterChain.
11602 // Get alias information for Chain.
11603 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11604 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11606 // If chain is alias then stop here.
11607 if (!(IsLoad && IsOpLoad) &&
11608 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11609 Aliases.push_back(Chain);
11611 // Look further up the chain.
11612 Chains.push_back(Chain.getOperand(0));
11618 case ISD::TokenFactor:
11619 // We have to check each of the operands of the token factor for "small"
11620 // token factors, so we queue them up. Adding the operands to the queue
11621 // (stack) in reverse order maintains the original order and increases the
11622 // likelihood that getNode will find a matching token factor (CSE.)
11623 if (Chain.getNumOperands() > 16) {
11624 Aliases.push_back(Chain);
11627 for (unsigned n = Chain.getNumOperands(); n;)
11628 Chains.push_back(Chain.getOperand(--n));
11633 // For all other instructions we will just have to take what we can get.
11634 Aliases.push_back(Chain);
11639 // We need to be careful here to also search for aliases through the
11640 // value operand of a store, etc. Consider the following situation:
11642 // L1 = load Token1, %52
11643 // S1 = store Token1, L1, %51
11644 // L2 = load Token1, %52+8
11645 // S2 = store Token1, L2, %51+8
11646 // Token2 = Token(S1, S2)
11647 // L3 = load Token2, %53
11648 // S3 = store Token2, L3, %52
11649 // L4 = load Token2, %53+8
11650 // S4 = store Token2, L4, %52+8
11651 // If we search for aliases of S3 (which loads address %52), and we look
11652 // only through the chain, then we'll miss the trivial dependence on L1
11653 // (which also loads from %52). We then might change all loads and
11654 // stores to use Token1 as their chain operand, which could result in
11655 // copying %53 into %52 before copying %52 into %51 (which should
11658 // The problem is, however, that searching for such data dependencies
11659 // can become expensive, and the cost is not directly related to the
11660 // chain depth. Instead, we'll rule out such configurations here by
11661 // insisting that we've visited all chain users (except for users
11662 // of the original chain, which is not necessary). When doing this,
11663 // we need to look through nodes we don't care about (otherwise, things
11664 // like register copies will interfere with trivial cases).
11666 SmallVector<const SDNode *, 16> Worklist;
11667 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11668 IE = Visited.end(); I != IE; ++I)
11669 if (*I != OriginalChain.getNode())
11670 Worklist.push_back(*I);
11672 while (!Worklist.empty()) {
11673 const SDNode *M = Worklist.pop_back_val();
11675 // We have already visited M, and want to make sure we've visited any uses
11676 // of M that we care about. For uses that we've not visisted, and don't
11677 // care about, queue them to the worklist.
11679 for (SDNode::use_iterator UI = M->use_begin(),
11680 UIE = M->use_end(); UI != UIE; ++UI)
11681 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11682 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11683 // We've not visited this use, and we care about it (it could have an
11684 // ordering dependency with the original node).
11686 Aliases.push_back(OriginalChain);
11690 // We've not visited this use, but we don't care about it. Mark it as
11691 // visited and enqueue it to the worklist.
11692 Worklist.push_back(*UI);
11697 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11698 /// for a better chain (aliasing node.)
11699 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11700 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11702 // Accumulate all the aliases to this node.
11703 GatherAllAliases(N, OldChain, Aliases);
11705 // If no operands then chain to entry token.
11706 if (Aliases.size() == 0)
11707 return DAG.getEntryNode();
11709 // If a single operand then chain to it. We don't need to revisit it.
11710 if (Aliases.size() == 1)
11713 // Construct a custom tailored token factor.
11714 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11717 // SelectionDAG::Combine - This is the entry point for the file.
11719 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11720 CodeGenOpt::Level OptLevel) {
11721 /// run - This is the main entry point to this class.
11723 DAGCombiner(*this, AA, OptLevel).Run(Level);