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/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFCOPYSIGN(SDNode *N);
280 SDValue visitSINT_TO_FP(SDNode *N);
281 SDValue visitUINT_TO_FP(SDNode *N);
282 SDValue visitFP_TO_SINT(SDNode *N);
283 SDValue visitFP_TO_UINT(SDNode *N);
284 SDValue visitFP_ROUND(SDNode *N);
285 SDValue visitFP_ROUND_INREG(SDNode *N);
286 SDValue visitFP_EXTEND(SDNode *N);
287 SDValue visitFNEG(SDNode *N);
288 SDValue visitFABS(SDNode *N);
289 SDValue visitFCEIL(SDNode *N);
290 SDValue visitFTRUNC(SDNode *N);
291 SDValue visitFFLOOR(SDNode *N);
292 SDValue visitBRCOND(SDNode *N);
293 SDValue visitBR_CC(SDNode *N);
294 SDValue visitLOAD(SDNode *N);
295 SDValue visitSTORE(SDNode *N);
296 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298 SDValue visitBUILD_VECTOR(SDNode *N);
299 SDValue visitCONCAT_VECTORS(SDNode *N);
300 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301 SDValue visitVECTOR_SHUFFLE(SDNode *N);
302 SDValue visitINSERT_SUBVECTOR(SDNode *N);
304 SDValue XformToShuffleWithZero(SDNode *N);
305 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
307 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
309 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313 SDValue N3, ISD::CondCode CC,
314 bool NotExtCompare = false);
315 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316 SDLoc DL, bool foldBooleans = true);
318 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
320 bool isOneUseSetCC(SDValue N) const;
322 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
324 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326 SDValue BuildSDIV(SDNode *N);
327 SDValue BuildSDIVPow2(SDNode *N);
328 SDValue BuildUDIV(SDNode *N);
329 SDValue BuildRSQRTE(SDNode *N);
330 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
331 bool DemandHighBits = true);
332 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
333 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
334 SDValue InnerPos, SDValue InnerNeg,
335 unsigned PosOpcode, unsigned NegOpcode,
337 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
338 SDValue ReduceLoadWidth(SDNode *N);
339 SDValue ReduceLoadOpStoreWidth(SDNode *N);
340 SDValue TransformFPLoadStorePair(SDNode *N);
341 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
342 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
344 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
346 /// Walk up chain skipping non-aliasing memory nodes,
347 /// looking for aliasing nodes and adding them to the Aliases vector.
348 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
349 SmallVectorImpl<SDValue> &Aliases);
351 /// Return true if there is any possibility that the two addresses overlap.
352 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
354 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
355 /// chain (aliasing node.)
356 SDValue FindBetterChain(SDNode *N, SDValue Chain);
358 /// Merge consecutive store operations into a wide store.
359 /// This optimization uses wide integers or vectors when possible.
360 /// \return True if some memory operations were changed.
361 bool MergeConsecutiveStores(StoreSDNode *N);
363 /// \brief Try to transform a truncation where C is a constant:
364 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
366 /// \p N needs to be a truncation and its first operand an AND. Other
367 /// requirements are checked by the function (e.g. that trunc is
368 /// single-use) and if missed an empty SDValue is returned.
369 SDValue distributeTruncateThroughAnd(SDNode *N);
372 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
373 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
374 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
375 AttributeSet FnAttrs =
376 DAG.getMachineFunction().getFunction()->getAttributes();
378 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
379 Attribute::OptimizeForSize) ||
380 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
383 /// Runs the dag combiner on all nodes in the work list
384 void Run(CombineLevel AtLevel);
386 SelectionDAG &getDAG() const { return DAG; }
388 /// Returns a type large enough to hold any valid shift amount - before type
389 /// legalization these can be huge.
390 EVT getShiftAmountTy(EVT LHSTy) {
391 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
392 if (LHSTy.isVector())
394 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
395 : TLI.getPointerTy();
398 /// This method returns true if we are running before type legalization or
399 /// if the specified VT is legal.
400 bool isTypeLegal(const EVT &VT) {
401 if (!LegalTypes) return true;
402 return TLI.isTypeLegal(VT);
405 /// Convenience wrapper around TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
414 /// This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
419 explicit WorklistRemover(DAGCombiner &dc)
420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
422 void NodeDeleted(SDNode *N, SDNode *E) override {
423 DC.removeFromWorklist(N);
428 //===----------------------------------------------------------------------===//
429 // TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433 ((DAGCombiner*)DC)->AddToWorklist(N);
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437 ((DAGCombiner*)DC)->removeFromWorklist(N);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461 //===----------------------------------------------------------------------===//
463 //===----------------------------------------------------------------------===//
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466 removeFromWorklist(N);
468 // If the operands of this node are only used by the node, they will now be
469 // dead. Make sure to re-visit them and recursively delete dead nodes.
470 for (const SDValue &Op : N->ops())
471 // For an operand generating multiple values, one of the values may
472 // become dead allowing further simplification (e.g. split index
473 // arithmetic from an indexed load).
474 if (Op->hasOneUse() || Op->getNumValues() > 1)
475 AddToWorklist(Op.getNode());
480 /// Return 1 if we can compute the negated form of the specified expression for
481 /// the same cost as the expression itself, or 2 if we can compute the negated
482 /// form more cheaply than the expression itself.
483 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
484 const TargetLowering &TLI,
485 const TargetOptions *Options,
486 unsigned Depth = 0) {
487 // fneg is removable even if it has multiple uses.
488 if (Op.getOpcode() == ISD::FNEG) return 2;
490 // Don't allow anything with multiple uses.
491 if (!Op.hasOneUse()) return 0;
493 // Don't recurse exponentially.
494 if (Depth > 6) return 0;
496 switch (Op.getOpcode()) {
497 default: return false;
498 case ISD::ConstantFP:
499 // Don't invert constant FP values after legalize. The negated constant
500 // isn't necessarily legal.
501 return LegalOperations ? 0 : 1;
503 // FIXME: determine better conditions for this xform.
504 if (!Options->UnsafeFPMath) return 0;
506 // After operation legalization, it might not be legal to create new FSUBs.
507 if (LegalOperations &&
508 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
515 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
516 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
519 // We can't turn -(A-B) into B-A when we honor signed zeros.
520 if (!Options->UnsafeFPMath) return 0;
522 // fold (fneg (fsub A, B)) -> (fsub B, A)
527 if (Options->HonorSignDependentRoundingFPMath()) return 0;
529 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
530 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
534 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
540 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
545 /// If isNegatibleForFree returns true, return the newly negated expression.
546 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
547 bool LegalOperations, unsigned Depth = 0) {
548 const TargetOptions &Options = DAG.getTarget().Options;
549 // fneg is removable even if it has multiple uses.
550 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
552 // Don't allow anything with multiple uses.
553 assert(Op.hasOneUse() && "Unknown reuse!");
555 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
556 switch (Op.getOpcode()) {
557 default: llvm_unreachable("Unknown code");
558 case ISD::ConstantFP: {
559 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
561 return DAG.getConstantFP(V, Op.getValueType());
564 // FIXME: determine better conditions for this xform.
565 assert(Options.UnsafeFPMath);
567 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
568 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
569 DAG.getTargetLoweringInfo(), &Options, Depth+1))
570 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
571 GetNegatedExpression(Op.getOperand(0), DAG,
572 LegalOperations, Depth+1),
574 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
575 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
576 GetNegatedExpression(Op.getOperand(1), DAG,
577 LegalOperations, Depth+1),
580 // We can't turn -(A-B) into B-A when we honor signed zeros.
581 assert(Options.UnsafeFPMath);
583 // fold (fneg (fsub 0, B)) -> B
584 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
585 if (N0CFP->getValueAPF().isZero())
586 return Op.getOperand(1);
588 // fold (fneg (fsub A, B)) -> (fsub B, A)
589 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
590 Op.getOperand(1), Op.getOperand(0));
594 assert(!Options.HonorSignDependentRoundingFPMath());
596 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
597 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
598 DAG.getTargetLoweringInfo(), &Options, Depth+1))
599 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
600 GetNegatedExpression(Op.getOperand(0), DAG,
601 LegalOperations, Depth+1),
604 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
605 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
607 GetNegatedExpression(Op.getOperand(1), DAG,
608 LegalOperations, Depth+1));
612 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
613 GetNegatedExpression(Op.getOperand(0), DAG,
614 LegalOperations, Depth+1));
616 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
617 GetNegatedExpression(Op.getOperand(0), DAG,
618 LegalOperations, Depth+1),
623 // Return true if this node is a setcc, or is a select_cc
624 // that selects between the target values used for true and false, making it
625 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
626 // the appropriate nodes based on the type of node we are checking. This
627 // simplifies life a bit for the callers.
628 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
630 if (N.getOpcode() == ISD::SETCC) {
631 LHS = N.getOperand(0);
632 RHS = N.getOperand(1);
633 CC = N.getOperand(2);
637 if (N.getOpcode() != ISD::SELECT_CC ||
638 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
639 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
642 LHS = N.getOperand(0);
643 RHS = N.getOperand(1);
644 CC = N.getOperand(4);
648 /// Return true if this is a SetCC-equivalent operation with only one use.
649 /// If this is true, it allows the users to invert the operation for free when
650 /// it is profitable to do so.
651 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
653 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
658 /// Returns true if N is a BUILD_VECTOR node whose
659 /// elements are all the same constant or undefined.
660 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
661 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
666 unsigned SplatBitSize;
668 EVT EltVT = N->getValueType(0).getVectorElementType();
669 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
671 EltVT.getSizeInBits() >= SplatBitSize);
674 // \brief Returns the SDNode if it is a constant BuildVector or constant.
675 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
676 if (isa<ConstantSDNode>(N))
678 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
679 if (BV && BV->isConstant())
684 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
686 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
687 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
690 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
691 BitVector UndefElements;
692 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
694 // BuildVectors can truncate their operands. Ignore that case here.
695 // FIXME: We blindly ignore splats which include undef which is overly
697 if (CN && UndefElements.none() &&
698 CN->getValueType(0) == N.getValueType().getScalarType())
705 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
707 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
708 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
711 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
712 BitVector UndefElements;
713 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
715 if (CN && UndefElements.none())
722 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
723 SDValue N0, SDValue N1) {
724 EVT VT = N0.getValueType();
725 if (N0.getOpcode() == Opc) {
726 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
727 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
728 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
729 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
730 if (!OpNode.getNode())
732 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
734 if (N0.hasOneUse()) {
735 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
737 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
738 if (!OpNode.getNode())
740 AddToWorklist(OpNode.getNode());
741 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
746 if (N1.getOpcode() == Opc) {
747 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
748 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
749 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
750 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
751 if (!OpNode.getNode())
753 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
755 if (N1.hasOneUse()) {
756 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
758 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
759 if (!OpNode.getNode())
761 AddToWorklist(OpNode.getNode());
762 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
770 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
772 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
774 DEBUG(dbgs() << "\nReplacing.1 ";
776 dbgs() << "\nWith: ";
777 To[0].getNode()->dump(&DAG);
778 dbgs() << " and " << NumTo-1 << " other values\n";
779 for (unsigned i = 0, e = NumTo; i != e; ++i)
780 assert((!To[i].getNode() ||
781 N->getValueType(i) == To[i].getValueType()) &&
782 "Cannot combine value to value of different type!"));
783 WorklistRemover DeadNodes(*this);
784 DAG.ReplaceAllUsesWith(N, To);
786 // Push the new nodes and any users onto the worklist
787 for (unsigned i = 0, e = NumTo; i != e; ++i) {
788 if (To[i].getNode()) {
789 AddToWorklist(To[i].getNode());
790 AddUsersToWorklist(To[i].getNode());
795 // Finally, if the node is now dead, remove it from the graph. The node
796 // may not be dead if the replacement process recursively simplified to
797 // something else needing this node.
799 deleteAndRecombine(N);
800 return SDValue(N, 0);
804 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
805 // Replace all uses. If any nodes become isomorphic to other nodes and
806 // are deleted, make sure to remove them from our worklist.
807 WorklistRemover DeadNodes(*this);
808 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
810 // Push the new node and any (possibly new) users onto the worklist.
811 AddToWorklist(TLO.New.getNode());
812 AddUsersToWorklist(TLO.New.getNode());
814 // Finally, if the node is now dead, remove it from the graph. The node
815 // may not be dead if the replacement process recursively simplified to
816 // something else needing this node.
817 if (TLO.Old.getNode()->use_empty())
818 deleteAndRecombine(TLO.Old.getNode());
821 /// Check the specified integer node value to see if it can be simplified or if
822 /// things it uses can be simplified by bit propagation. If so, return true.
823 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
824 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
825 APInt KnownZero, KnownOne;
826 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
830 AddToWorklist(Op.getNode());
832 // Replace the old value with the new one.
834 DEBUG(dbgs() << "\nReplacing.2 ";
835 TLO.Old.getNode()->dump(&DAG);
836 dbgs() << "\nWith: ";
837 TLO.New.getNode()->dump(&DAG);
840 CommitTargetLoweringOpt(TLO);
844 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
846 EVT VT = Load->getValueType(0);
847 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
849 DEBUG(dbgs() << "\nReplacing.9 ";
851 dbgs() << "\nWith: ";
852 Trunc.getNode()->dump(&DAG);
854 WorklistRemover DeadNodes(*this);
855 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
856 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
857 deleteAndRecombine(Load);
858 AddToWorklist(Trunc.getNode());
861 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
864 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
865 EVT MemVT = LD->getMemoryVT();
866 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
867 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
869 : LD->getExtensionType();
871 return DAG.getExtLoad(ExtType, dl, PVT,
872 LD->getChain(), LD->getBasePtr(),
873 MemVT, LD->getMemOperand());
876 unsigned Opc = Op.getOpcode();
879 case ISD::AssertSext:
880 return DAG.getNode(ISD::AssertSext, dl, PVT,
881 SExtPromoteOperand(Op.getOperand(0), PVT),
883 case ISD::AssertZext:
884 return DAG.getNode(ISD::AssertZext, dl, PVT,
885 ZExtPromoteOperand(Op.getOperand(0), PVT),
887 case ISD::Constant: {
889 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
890 return DAG.getNode(ExtOpc, dl, PVT, Op);
894 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
896 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
899 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
900 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
902 EVT OldVT = Op.getValueType();
904 bool Replace = false;
905 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
906 if (!NewOp.getNode())
908 AddToWorklist(NewOp.getNode());
911 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
912 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
913 DAG.getValueType(OldVT));
916 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
917 EVT OldVT = Op.getValueType();
919 bool Replace = false;
920 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
921 if (!NewOp.getNode())
923 AddToWorklist(NewOp.getNode());
926 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
927 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
930 /// Promote the specified integer binary operation if the target indicates it is
931 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
932 /// i32 since i16 instructions are longer.
933 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
934 if (!LegalOperations)
937 EVT VT = Op.getValueType();
938 if (VT.isVector() || !VT.isInteger())
941 // If operation type is 'undesirable', e.g. i16 on x86, consider
943 unsigned Opc = Op.getOpcode();
944 if (TLI.isTypeDesirableForOp(Opc, VT))
948 // Consult target whether it is a good idea to promote this operation and
949 // what's the right type to promote it to.
950 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
951 assert(PVT != VT && "Don't know what type to promote to!");
953 bool Replace0 = false;
954 SDValue N0 = Op.getOperand(0);
955 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
959 bool Replace1 = false;
960 SDValue N1 = Op.getOperand(1);
965 NN1 = PromoteOperand(N1, PVT, Replace1);
970 AddToWorklist(NN0.getNode());
972 AddToWorklist(NN1.getNode());
975 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
977 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
979 DEBUG(dbgs() << "\nPromoting ";
980 Op.getNode()->dump(&DAG));
982 return DAG.getNode(ISD::TRUNCATE, dl, VT,
983 DAG.getNode(Opc, dl, PVT, NN0, NN1));
988 /// Promote the specified integer shift operation if the target indicates it is
989 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
990 /// i32 since i16 instructions are longer.
991 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
992 if (!LegalOperations)
995 EVT VT = Op.getValueType();
996 if (VT.isVector() || !VT.isInteger())
999 // If operation type is 'undesirable', e.g. i16 on x86, consider
1001 unsigned Opc = Op.getOpcode();
1002 if (TLI.isTypeDesirableForOp(Opc, VT))
1006 // Consult target whether it is a good idea to promote this operation and
1007 // what's the right type to promote it to.
1008 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1009 assert(PVT != VT && "Don't know what type to promote to!");
1011 bool Replace = false;
1012 SDValue N0 = Op.getOperand(0);
1013 if (Opc == ISD::SRA)
1014 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1015 else if (Opc == ISD::SRL)
1016 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1018 N0 = PromoteOperand(N0, PVT, Replace);
1022 AddToWorklist(N0.getNode());
1024 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1026 DEBUG(dbgs() << "\nPromoting ";
1027 Op.getNode()->dump(&DAG));
1029 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1035 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1036 if (!LegalOperations)
1039 EVT VT = Op.getValueType();
1040 if (VT.isVector() || !VT.isInteger())
1043 // If operation type is 'undesirable', e.g. i16 on x86, consider
1045 unsigned Opc = Op.getOpcode();
1046 if (TLI.isTypeDesirableForOp(Opc, VT))
1050 // Consult target whether it is a good idea to promote this operation and
1051 // what's the right type to promote it to.
1052 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1053 assert(PVT != VT && "Don't know what type to promote to!");
1054 // fold (aext (aext x)) -> (aext x)
1055 // fold (aext (zext x)) -> (zext x)
1056 // fold (aext (sext x)) -> (sext x)
1057 DEBUG(dbgs() << "\nPromoting ";
1058 Op.getNode()->dump(&DAG));
1059 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1064 bool DAGCombiner::PromoteLoad(SDValue Op) {
1065 if (!LegalOperations)
1068 EVT VT = Op.getValueType();
1069 if (VT.isVector() || !VT.isInteger())
1072 // If operation type is 'undesirable', e.g. i16 on x86, consider
1074 unsigned Opc = Op.getOpcode();
1075 if (TLI.isTypeDesirableForOp(Opc, VT))
1079 // Consult target whether it is a good idea to promote this operation and
1080 // what's the right type to promote it to.
1081 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1082 assert(PVT != VT && "Don't know what type to promote to!");
1085 SDNode *N = Op.getNode();
1086 LoadSDNode *LD = cast<LoadSDNode>(N);
1087 EVT MemVT = LD->getMemoryVT();
1088 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1089 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1091 : LD->getExtensionType();
1092 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1093 LD->getChain(), LD->getBasePtr(),
1094 MemVT, LD->getMemOperand());
1095 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1097 DEBUG(dbgs() << "\nPromoting ";
1100 Result.getNode()->dump(&DAG);
1102 WorklistRemover DeadNodes(*this);
1103 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1104 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1105 deleteAndRecombine(N);
1106 AddToWorklist(Result.getNode());
1112 /// \brief Recursively delete a node which has no uses and any operands for
1113 /// which it is the only use.
1115 /// Note that this both deletes the nodes and removes them from the worklist.
1116 /// It also adds any nodes who have had a user deleted to the worklist as they
1117 /// may now have only one use and subject to other combines.
1118 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1119 if (!N->use_empty())
1122 SmallSetVector<SDNode *, 16> Nodes;
1125 N = Nodes.pop_back_val();
1129 if (N->use_empty()) {
1130 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1131 Nodes.insert(N->getOperand(i).getNode());
1133 removeFromWorklist(N);
1138 } while (!Nodes.empty());
1142 //===----------------------------------------------------------------------===//
1143 // Main DAG Combiner implementation
1144 //===----------------------------------------------------------------------===//
1146 void DAGCombiner::Run(CombineLevel AtLevel) {
1147 // set the instance variables, so that the various visit routines may use it.
1149 LegalOperations = Level >= AfterLegalizeVectorOps;
1150 LegalTypes = Level >= AfterLegalizeTypes;
1152 // Add all the dag nodes to the worklist.
1153 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1154 E = DAG.allnodes_end(); I != E; ++I)
1157 // Create a dummy node (which is not added to allnodes), that adds a reference
1158 // to the root node, preventing it from being deleted, and tracking any
1159 // changes of the root.
1160 HandleSDNode Dummy(DAG.getRoot());
1162 // while the worklist isn't empty, find a node and
1163 // try and combine it.
1164 while (!WorklistMap.empty()) {
1166 // The Worklist holds the SDNodes in order, but it may contain null entries.
1168 N = Worklist.pop_back_val();
1171 bool GoodWorklistEntry = WorklistMap.erase(N);
1172 (void)GoodWorklistEntry;
1173 assert(GoodWorklistEntry &&
1174 "Found a worklist entry without a corresponding map entry!");
1176 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1177 // N is deleted from the DAG, since they too may now be dead or may have a
1178 // reduced number of uses, allowing other xforms.
1179 if (recursivelyDeleteUnusedNodes(N))
1182 WorklistRemover DeadNodes(*this);
1184 // If this combine is running after legalizing the DAG, re-legalize any
1185 // nodes pulled off the worklist.
1186 if (Level == AfterLegalizeDAG) {
1187 SmallSetVector<SDNode *, 16> UpdatedNodes;
1188 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1190 for (SDNode *LN : UpdatedNodes) {
1192 AddUsersToWorklist(LN);
1198 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1200 // Add any operands of the new node which have not yet been combined to the
1201 // worklist as well. Because the worklist uniques things already, this
1202 // won't repeatedly process the same operand.
1203 CombinedNodes.insert(N);
1204 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1205 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1206 AddToWorklist(N->getOperand(i).getNode());
1208 SDValue RV = combine(N);
1215 // If we get back the same node we passed in, rather than a new node or
1216 // zero, we know that the node must have defined multiple values and
1217 // CombineTo was used. Since CombineTo takes care of the worklist
1218 // mechanics for us, we have no work to do in this case.
1219 if (RV.getNode() == N)
1222 assert(N->getOpcode() != ISD::DELETED_NODE &&
1223 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1224 "Node was deleted but visit returned new node!");
1226 DEBUG(dbgs() << " ... into: ";
1227 RV.getNode()->dump(&DAG));
1229 // Transfer debug value.
1230 DAG.TransferDbgValues(SDValue(N, 0), RV);
1231 if (N->getNumValues() == RV.getNode()->getNumValues())
1232 DAG.ReplaceAllUsesWith(N, RV.getNode());
1234 assert(N->getValueType(0) == RV.getValueType() &&
1235 N->getNumValues() == 1 && "Type mismatch");
1237 DAG.ReplaceAllUsesWith(N, &OpV);
1240 // Push the new node and any users onto the worklist
1241 AddToWorklist(RV.getNode());
1242 AddUsersToWorklist(RV.getNode());
1244 // Finally, if the node is now dead, remove it from the graph. The node
1245 // may not be dead if the replacement process recursively simplified to
1246 // something else needing this node. This will also take care of adding any
1247 // operands which have lost a user to the worklist.
1248 recursivelyDeleteUnusedNodes(N);
1251 // If the root changed (e.g. it was a dead load, update the root).
1252 DAG.setRoot(Dummy.getValue());
1253 DAG.RemoveDeadNodes();
1256 SDValue DAGCombiner::visit(SDNode *N) {
1257 switch (N->getOpcode()) {
1259 case ISD::TokenFactor: return visitTokenFactor(N);
1260 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1261 case ISD::ADD: return visitADD(N);
1262 case ISD::SUB: return visitSUB(N);
1263 case ISD::ADDC: return visitADDC(N);
1264 case ISD::SUBC: return visitSUBC(N);
1265 case ISD::ADDE: return visitADDE(N);
1266 case ISD::SUBE: return visitSUBE(N);
1267 case ISD::MUL: return visitMUL(N);
1268 case ISD::SDIV: return visitSDIV(N);
1269 case ISD::UDIV: return visitUDIV(N);
1270 case ISD::SREM: return visitSREM(N);
1271 case ISD::UREM: return visitUREM(N);
1272 case ISD::MULHU: return visitMULHU(N);
1273 case ISD::MULHS: return visitMULHS(N);
1274 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1275 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1276 case ISD::SMULO: return visitSMULO(N);
1277 case ISD::UMULO: return visitUMULO(N);
1278 case ISD::SDIVREM: return visitSDIVREM(N);
1279 case ISD::UDIVREM: return visitUDIVREM(N);
1280 case ISD::AND: return visitAND(N);
1281 case ISD::OR: return visitOR(N);
1282 case ISD::XOR: return visitXOR(N);
1283 case ISD::SHL: return visitSHL(N);
1284 case ISD::SRA: return visitSRA(N);
1285 case ISD::SRL: return visitSRL(N);
1287 case ISD::ROTL: return visitRotate(N);
1288 case ISD::CTLZ: return visitCTLZ(N);
1289 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1290 case ISD::CTTZ: return visitCTTZ(N);
1291 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1292 case ISD::CTPOP: return visitCTPOP(N);
1293 case ISD::SELECT: return visitSELECT(N);
1294 case ISD::VSELECT: return visitVSELECT(N);
1295 case ISD::SELECT_CC: return visitSELECT_CC(N);
1296 case ISD::SETCC: return visitSETCC(N);
1297 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1298 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1299 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1300 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1301 case ISD::TRUNCATE: return visitTRUNCATE(N);
1302 case ISD::BITCAST: return visitBITCAST(N);
1303 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1304 case ISD::FADD: return visitFADD(N);
1305 case ISD::FSUB: return visitFSUB(N);
1306 case ISD::FMUL: return visitFMUL(N);
1307 case ISD::FMA: return visitFMA(N);
1308 case ISD::FDIV: return visitFDIV(N);
1309 case ISD::FREM: return visitFREM(N);
1310 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1311 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1312 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1313 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1314 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1315 case ISD::FP_ROUND: return visitFP_ROUND(N);
1316 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1317 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1318 case ISD::FNEG: return visitFNEG(N);
1319 case ISD::FABS: return visitFABS(N);
1320 case ISD::FFLOOR: return visitFFLOOR(N);
1321 case ISD::FCEIL: return visitFCEIL(N);
1322 case ISD::FTRUNC: return visitFTRUNC(N);
1323 case ISD::BRCOND: return visitBRCOND(N);
1324 case ISD::BR_CC: return visitBR_CC(N);
1325 case ISD::LOAD: return visitLOAD(N);
1326 case ISD::STORE: return visitSTORE(N);
1327 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1328 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1329 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1330 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1331 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1332 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1333 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1338 SDValue DAGCombiner::combine(SDNode *N) {
1339 SDValue RV = visit(N);
1341 // If nothing happened, try a target-specific DAG combine.
1342 if (!RV.getNode()) {
1343 assert(N->getOpcode() != ISD::DELETED_NODE &&
1344 "Node was deleted but visit returned NULL!");
1346 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1347 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1349 // Expose the DAG combiner to the target combiner impls.
1350 TargetLowering::DAGCombinerInfo
1351 DagCombineInfo(DAG, Level, false, this);
1353 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357 // If nothing happened still, try promoting the operation.
1358 if (!RV.getNode()) {
1359 switch (N->getOpcode()) {
1367 RV = PromoteIntBinOp(SDValue(N, 0));
1372 RV = PromoteIntShiftOp(SDValue(N, 0));
1374 case ISD::SIGN_EXTEND:
1375 case ISD::ZERO_EXTEND:
1376 case ISD::ANY_EXTEND:
1377 RV = PromoteExtend(SDValue(N, 0));
1380 if (PromoteLoad(SDValue(N, 0)))
1386 // If N is a commutative binary node, try commuting it to enable more
1388 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1389 N->getNumValues() == 1) {
1390 SDValue N0 = N->getOperand(0);
1391 SDValue N1 = N->getOperand(1);
1393 // Constant operands are canonicalized to RHS.
1394 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1395 SDValue Ops[] = {N1, N0};
1397 if (const BinaryWithFlagsSDNode *BinNode =
1398 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1399 CSENode = DAG.getNodeIfExists(
1400 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1401 BinNode->hasNoSignedWrap(), BinNode->isExact());
1403 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1406 return SDValue(CSENode, 0);
1413 /// Given a node, return its input chain if it has one, otherwise return a null
1415 static SDValue getInputChainForNode(SDNode *N) {
1416 if (unsigned NumOps = N->getNumOperands()) {
1417 if (N->getOperand(0).getValueType() == MVT::Other)
1418 return N->getOperand(0);
1419 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1420 return N->getOperand(NumOps-1);
1421 for (unsigned i = 1; i < NumOps-1; ++i)
1422 if (N->getOperand(i).getValueType() == MVT::Other)
1423 return N->getOperand(i);
1428 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1429 // If N has two operands, where one has an input chain equal to the other,
1430 // the 'other' chain is redundant.
1431 if (N->getNumOperands() == 2) {
1432 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1433 return N->getOperand(0);
1434 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1435 return N->getOperand(1);
1438 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1439 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1440 SmallPtrSet<SDNode*, 16> SeenOps;
1441 bool Changed = false; // If we should replace this token factor.
1443 // Start out with this token factor.
1446 // Iterate through token factors. The TFs grows when new token factors are
1448 for (unsigned i = 0; i < TFs.size(); ++i) {
1449 SDNode *TF = TFs[i];
1451 // Check each of the operands.
1452 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1453 SDValue Op = TF->getOperand(i);
1455 switch (Op.getOpcode()) {
1456 case ISD::EntryToken:
1457 // Entry tokens don't need to be added to the list. They are
1462 case ISD::TokenFactor:
1463 if (Op.hasOneUse() &&
1464 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1465 // Queue up for processing.
1466 TFs.push_back(Op.getNode());
1467 // Clean up in case the token factor is removed.
1468 AddToWorklist(Op.getNode());
1475 // Only add if it isn't already in the list.
1476 if (SeenOps.insert(Op.getNode()))
1487 // If we've change things around then replace token factor.
1490 // The entry token is the only possible outcome.
1491 Result = DAG.getEntryNode();
1493 // New and improved token factor.
1494 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1497 // Don't add users to work list.
1498 return CombineTo(N, Result, false);
1504 /// MERGE_VALUES can always be eliminated.
1505 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1506 WorklistRemover DeadNodes(*this);
1507 // Replacing results may cause a different MERGE_VALUES to suddenly
1508 // be CSE'd with N, and carry its uses with it. Iterate until no
1509 // uses remain, to ensure that the node can be safely deleted.
1510 // First add the users of this node to the work list so that they
1511 // can be tried again once they have new operands.
1512 AddUsersToWorklist(N);
1514 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1515 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1516 } while (!N->use_empty());
1517 deleteAndRecombine(N);
1518 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1521 SDValue DAGCombiner::visitADD(SDNode *N) {
1522 SDValue N0 = N->getOperand(0);
1523 SDValue N1 = N->getOperand(1);
1524 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1526 EVT VT = N0.getValueType();
1529 if (VT.isVector()) {
1530 SDValue FoldedVOp = SimplifyVBinOp(N);
1531 if (FoldedVOp.getNode()) return FoldedVOp;
1533 // fold (add x, 0) -> x, vector edition
1534 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1536 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1540 // fold (add x, undef) -> undef
1541 if (N0.getOpcode() == ISD::UNDEF)
1543 if (N1.getOpcode() == ISD::UNDEF)
1545 // fold (add c1, c2) -> c1+c2
1547 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1548 // canonicalize constant to RHS
1550 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1551 // fold (add x, 0) -> x
1552 if (N1C && N1C->isNullValue())
1554 // fold (add Sym, c) -> Sym+c
1555 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1556 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1557 GA->getOpcode() == ISD::GlobalAddress)
1558 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1560 (uint64_t)N1C->getSExtValue());
1561 // fold ((c1-A)+c2) -> (c1+c2)-A
1562 if (N1C && N0.getOpcode() == ISD::SUB)
1563 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1564 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1565 DAG.getConstant(N1C->getAPIntValue()+
1566 N0C->getAPIntValue(), VT),
1569 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1572 // fold ((0-A) + B) -> B-A
1573 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1574 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1575 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1576 // fold (A + (0-B)) -> A-B
1577 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1578 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1579 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1580 // fold (A+(B-A)) -> B
1581 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1582 return N1.getOperand(0);
1583 // fold ((B-A)+A) -> B
1584 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1585 return N0.getOperand(0);
1586 // fold (A+(B-(A+C))) to (B-C)
1587 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1588 N0 == N1.getOperand(1).getOperand(0))
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1590 N1.getOperand(1).getOperand(1));
1591 // fold (A+(B-(C+A))) to (B-C)
1592 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1593 N0 == N1.getOperand(1).getOperand(1))
1594 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1595 N1.getOperand(1).getOperand(0));
1596 // fold (A+((B-A)+or-C)) to (B+or-C)
1597 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1598 N1.getOperand(0).getOpcode() == ISD::SUB &&
1599 N0 == N1.getOperand(0).getOperand(1))
1600 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1601 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1603 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1604 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1605 SDValue N00 = N0.getOperand(0);
1606 SDValue N01 = N0.getOperand(1);
1607 SDValue N10 = N1.getOperand(0);
1608 SDValue N11 = N1.getOperand(1);
1610 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1611 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1612 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1613 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1616 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1617 return SDValue(N, 0);
1619 // fold (a+b) -> (a|b) iff a and b share no bits.
1620 if (VT.isInteger() && !VT.isVector()) {
1621 APInt LHSZero, LHSOne;
1622 APInt RHSZero, RHSOne;
1623 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1625 if (LHSZero.getBoolValue()) {
1626 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1628 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1629 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1630 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1631 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1632 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1637 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1638 if (N1.getOpcode() == ISD::SHL &&
1639 N1.getOperand(0).getOpcode() == ISD::SUB)
1640 if (ConstantSDNode *C =
1641 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1642 if (C->getAPIntValue() == 0)
1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1644 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1645 N1.getOperand(0).getOperand(1),
1647 if (N0.getOpcode() == ISD::SHL &&
1648 N0.getOperand(0).getOpcode() == ISD::SUB)
1649 if (ConstantSDNode *C =
1650 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1651 if (C->getAPIntValue() == 0)
1652 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1653 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1654 N0.getOperand(0).getOperand(1),
1657 if (N1.getOpcode() == ISD::AND) {
1658 SDValue AndOp0 = N1.getOperand(0);
1659 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1660 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1661 unsigned DestBits = VT.getScalarType().getSizeInBits();
1663 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1664 // and similar xforms where the inner op is either ~0 or 0.
1665 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1667 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1671 // add (sext i1), X -> sub X, (zext i1)
1672 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1673 N0.getOperand(0).getValueType() == MVT::i1 &&
1674 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1676 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1677 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1683 SDValue DAGCombiner::visitADDC(SDNode *N) {
1684 SDValue N0 = N->getOperand(0);
1685 SDValue N1 = N->getOperand(1);
1686 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1688 EVT VT = N0.getValueType();
1690 // If the flag result is dead, turn this into an ADD.
1691 if (!N->hasAnyUseOfValue(1))
1692 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1693 DAG.getNode(ISD::CARRY_FALSE,
1694 SDLoc(N), MVT::Glue));
1696 // canonicalize constant to RHS.
1698 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1700 // fold (addc x, 0) -> x + no carry out
1701 if (N1C && N1C->isNullValue())
1702 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1703 SDLoc(N), MVT::Glue));
1705 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1706 APInt LHSZero, LHSOne;
1707 APInt RHSZero, RHSOne;
1708 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1710 if (LHSZero.getBoolValue()) {
1711 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1713 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1714 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1715 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1716 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1717 DAG.getNode(ISD::CARRY_FALSE,
1718 SDLoc(N), MVT::Glue));
1724 SDValue DAGCombiner::visitADDE(SDNode *N) {
1725 SDValue N0 = N->getOperand(0);
1726 SDValue N1 = N->getOperand(1);
1727 SDValue CarryIn = N->getOperand(2);
1728 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1729 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1731 // canonicalize constant to RHS
1733 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1736 // fold (adde x, y, false) -> (addc x, y)
1737 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1738 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1743 // Since it may not be valid to emit a fold to zero for vector initializers
1744 // check if we can before folding.
1745 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1747 bool LegalOperations, bool LegalTypes) {
1749 return DAG.getConstant(0, VT);
1750 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1751 return DAG.getConstant(0, VT);
1755 SDValue DAGCombiner::visitSUB(SDNode *N) {
1756 SDValue N0 = N->getOperand(0);
1757 SDValue N1 = N->getOperand(1);
1758 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1759 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1760 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1761 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1762 EVT VT = N0.getValueType();
1765 if (VT.isVector()) {
1766 SDValue FoldedVOp = SimplifyVBinOp(N);
1767 if (FoldedVOp.getNode()) return FoldedVOp;
1769 // fold (sub x, 0) -> x, vector edition
1770 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1774 // fold (sub x, x) -> 0
1775 // FIXME: Refactor this and xor and other similar operations together.
1777 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1778 // fold (sub c1, c2) -> c1-c2
1780 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1781 // fold (sub x, c) -> (add x, -c)
1783 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1784 DAG.getConstant(-N1C->getAPIntValue(), VT));
1785 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1786 if (N0C && N0C->isAllOnesValue())
1787 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1788 // fold A-(A-B) -> B
1789 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1790 return N1.getOperand(1);
1791 // fold (A+B)-A -> B
1792 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1793 return N0.getOperand(1);
1794 // fold (A+B)-B -> A
1795 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1796 return N0.getOperand(0);
1797 // fold C2-(A+C1) -> (C2-C1)-A
1798 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1799 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1801 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1804 // fold ((A+(B+or-C))-B) -> A+or-C
1805 if (N0.getOpcode() == ISD::ADD &&
1806 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1807 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1808 N0.getOperand(1).getOperand(0) == N1)
1809 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1810 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1811 // fold ((A+(C+B))-B) -> A+C
1812 if (N0.getOpcode() == ISD::ADD &&
1813 N0.getOperand(1).getOpcode() == ISD::ADD &&
1814 N0.getOperand(1).getOperand(1) == N1)
1815 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1816 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1817 // fold ((A-(B-C))-C) -> A-B
1818 if (N0.getOpcode() == ISD::SUB &&
1819 N0.getOperand(1).getOpcode() == ISD::SUB &&
1820 N0.getOperand(1).getOperand(1) == N1)
1821 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1822 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1824 // If either operand of a sub is undef, the result is undef
1825 if (N0.getOpcode() == ISD::UNDEF)
1827 if (N1.getOpcode() == ISD::UNDEF)
1830 // If the relocation model supports it, consider symbol offsets.
1831 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1832 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1833 // fold (sub Sym, c) -> Sym-c
1834 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1835 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1837 (uint64_t)N1C->getSExtValue());
1838 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1839 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1840 if (GA->getGlobal() == GB->getGlobal())
1841 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1848 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1849 SDValue N0 = N->getOperand(0);
1850 SDValue N1 = N->getOperand(1);
1851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1853 EVT VT = N0.getValueType();
1855 // If the flag result is dead, turn this into an SUB.
1856 if (!N->hasAnyUseOfValue(1))
1857 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1858 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1861 // fold (subc x, x) -> 0 + no borrow
1863 return CombineTo(N, DAG.getConstant(0, VT),
1864 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1867 // fold (subc x, 0) -> x + no borrow
1868 if (N1C && N1C->isNullValue())
1869 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1872 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1873 if (N0C && N0C->isAllOnesValue())
1874 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1875 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1881 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1882 SDValue N0 = N->getOperand(0);
1883 SDValue N1 = N->getOperand(1);
1884 SDValue CarryIn = N->getOperand(2);
1886 // fold (sube x, y, false) -> (subc x, y)
1887 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1888 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1893 SDValue DAGCombiner::visitMUL(SDNode *N) {
1894 SDValue N0 = N->getOperand(0);
1895 SDValue N1 = N->getOperand(1);
1896 EVT VT = N0.getValueType();
1898 // fold (mul x, undef) -> 0
1899 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1900 return DAG.getConstant(0, VT);
1902 bool N0IsConst = false;
1903 bool N1IsConst = false;
1904 APInt ConstValue0, ConstValue1;
1906 if (VT.isVector()) {
1907 SDValue FoldedVOp = SimplifyVBinOp(N);
1908 if (FoldedVOp.getNode()) return FoldedVOp;
1910 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1911 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1913 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1914 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1916 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1917 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1921 // fold (mul c1, c2) -> c1*c2
1922 if (N0IsConst && N1IsConst)
1923 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1925 // canonicalize constant to RHS
1926 if (N0IsConst && !N1IsConst)
1927 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1928 // fold (mul x, 0) -> 0
1929 if (N1IsConst && ConstValue1 == 0)
1931 // We require a splat of the entire scalar bit width for non-contiguous
1934 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1935 // fold (mul x, 1) -> x
1936 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1938 // fold (mul x, -1) -> 0-x
1939 if (N1IsConst && ConstValue1.isAllOnesValue())
1940 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1941 DAG.getConstant(0, VT), N0);
1942 // fold (mul x, (1 << c)) -> x << c
1943 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1944 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1945 DAG.getConstant(ConstValue1.logBase2(),
1946 getShiftAmountTy(N0.getValueType())));
1947 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1948 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1949 unsigned Log2Val = (-ConstValue1).logBase2();
1950 // FIXME: If the input is something that is easily negated (e.g. a
1951 // single-use add), we should put the negate there.
1952 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1953 DAG.getConstant(0, VT),
1954 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1955 DAG.getConstant(Log2Val,
1956 getShiftAmountTy(N0.getValueType()))));
1960 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1961 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1)))) {
1964 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1965 N1, N0.getOperand(1));
1966 AddToWorklist(C3.getNode());
1967 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1968 N0.getOperand(0), C3);
1971 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1974 SDValue Sh(nullptr,0), Y(nullptr,0);
1975 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1976 if (N0.getOpcode() == ISD::SHL &&
1977 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1978 isa<ConstantSDNode>(N0.getOperand(1))) &&
1979 N0.getNode()->hasOneUse()) {
1981 } else if (N1.getOpcode() == ISD::SHL &&
1982 isa<ConstantSDNode>(N1.getOperand(1)) &&
1983 N1.getNode()->hasOneUse()) {
1988 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1989 Sh.getOperand(0), Y);
1990 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1991 Mul, Sh.getOperand(1));
1995 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1996 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1997 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1998 isa<ConstantSDNode>(N0.getOperand(1))))
1999 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2000 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2001 N0.getOperand(0), N1),
2002 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2003 N0.getOperand(1), N1));
2006 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2013 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2014 SDValue N0 = N->getOperand(0);
2015 SDValue N1 = N->getOperand(1);
2016 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2017 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2018 EVT VT = N->getValueType(0);
2021 if (VT.isVector()) {
2022 SDValue FoldedVOp = SimplifyVBinOp(N);
2023 if (FoldedVOp.getNode()) return FoldedVOp;
2026 // fold (sdiv c1, c2) -> c1/c2
2027 if (N0C && N1C && !N1C->isNullValue())
2028 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2029 // fold (sdiv X, 1) -> X
2030 if (N1C && N1C->getAPIntValue() == 1LL)
2032 // fold (sdiv X, -1) -> 0-X
2033 if (N1C && N1C->isAllOnesValue())
2034 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2035 DAG.getConstant(0, VT), N0);
2036 // If we know the sign bits of both operands are zero, strength reduce to a
2037 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2038 if (!VT.isVector()) {
2039 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2040 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2044 // fold (sdiv X, pow2) -> simple ops after legalize
2045 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2046 (-N1C->getAPIntValue()).isPowerOf2())) {
2047 // If dividing by powers of two is cheap, then don't perform the following
2049 if (TLI.isPow2SDivCheap())
2052 // Target-specific implementation of sdiv x, pow2.
2053 SDValue Res = BuildSDIVPow2(N);
2057 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2059 // Splat the sign bit into the register
2061 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2062 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2063 getShiftAmountTy(N0.getValueType())));
2064 AddToWorklist(SGN.getNode());
2066 // Add (N0 < 0) ? abs2 - 1 : 0;
2068 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2069 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2070 getShiftAmountTy(SGN.getValueType())));
2071 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2072 AddToWorklist(SRL.getNode());
2073 AddToWorklist(ADD.getNode()); // Divide by pow2
2074 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2075 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2077 // If we're dividing by a positive value, we're done. Otherwise, we must
2078 // negate the result.
2079 if (N1C->getAPIntValue().isNonNegative())
2082 AddToWorklist(SRA.getNode());
2083 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2086 // if integer divide is expensive and we satisfy the requirements, emit an
2087 // alternate sequence.
2088 if (N1C && !TLI.isIntDivCheap()) {
2089 SDValue Op = BuildSDIV(N);
2090 if (Op.getNode()) return Op;
2094 if (N0.getOpcode() == ISD::UNDEF)
2095 return DAG.getConstant(0, VT);
2096 // X / undef -> undef
2097 if (N1.getOpcode() == ISD::UNDEF)
2103 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2104 SDValue N0 = N->getOperand(0);
2105 SDValue N1 = N->getOperand(1);
2106 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2107 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2108 EVT VT = N->getValueType(0);
2111 if (VT.isVector()) {
2112 SDValue FoldedVOp = SimplifyVBinOp(N);
2113 if (FoldedVOp.getNode()) return FoldedVOp;
2116 // fold (udiv c1, c2) -> c1/c2
2117 if (N0C && N1C && !N1C->isNullValue())
2118 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2119 // fold (udiv x, (1 << c)) -> x >>u c
2120 if (N1C && N1C->getAPIntValue().isPowerOf2())
2121 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2122 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2123 getShiftAmountTy(N0.getValueType())));
2124 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2125 if (N1.getOpcode() == ISD::SHL) {
2126 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2127 if (SHC->getAPIntValue().isPowerOf2()) {
2128 EVT ADDVT = N1.getOperand(1).getValueType();
2129 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2131 DAG.getConstant(SHC->getAPIntValue()
2134 AddToWorklist(Add.getNode());
2135 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2139 // fold (udiv x, c) -> alternate
2140 if (N1C && !TLI.isIntDivCheap()) {
2141 SDValue Op = BuildUDIV(N);
2142 if (Op.getNode()) return Op;
2146 if (N0.getOpcode() == ISD::UNDEF)
2147 return DAG.getConstant(0, VT);
2148 // X / undef -> undef
2149 if (N1.getOpcode() == ISD::UNDEF)
2155 SDValue DAGCombiner::visitSREM(SDNode *N) {
2156 SDValue N0 = N->getOperand(0);
2157 SDValue N1 = N->getOperand(1);
2158 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2159 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2160 EVT VT = N->getValueType(0);
2162 // fold (srem c1, c2) -> c1%c2
2163 if (N0C && N1C && !N1C->isNullValue())
2164 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2165 // If we know the sign bits of both operands are zero, strength reduce to a
2166 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2167 if (!VT.isVector()) {
2168 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2169 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2172 // If X/C can be simplified by the division-by-constant logic, lower
2173 // X%C to the equivalent of X-X/C*C.
2174 if (N1C && !N1C->isNullValue()) {
2175 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2176 AddToWorklist(Div.getNode());
2177 SDValue OptimizedDiv = combine(Div.getNode());
2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2182 AddToWorklist(Mul.getNode());
2188 if (N0.getOpcode() == ISD::UNDEF)
2189 return DAG.getConstant(0, VT);
2190 // X % undef -> undef
2191 if (N1.getOpcode() == ISD::UNDEF)
2197 SDValue DAGCombiner::visitUREM(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
2200 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2201 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2202 EVT VT = N->getValueType(0);
2204 // fold (urem c1, c2) -> c1%c2
2205 if (N0C && N1C && !N1C->isNullValue())
2206 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2207 // fold (urem x, pow2) -> (and x, pow2-1)
2208 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2209 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2210 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2211 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2212 if (N1.getOpcode() == ISD::SHL) {
2213 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2214 if (SHC->getAPIntValue().isPowerOf2()) {
2216 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2217 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2219 AddToWorklist(Add.getNode());
2220 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2225 // If X/C can be simplified by the division-by-constant logic, lower
2226 // X%C to the equivalent of X-X/C*C.
2227 if (N1C && !N1C->isNullValue()) {
2228 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2229 AddToWorklist(Div.getNode());
2230 SDValue OptimizedDiv = combine(Div.getNode());
2231 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2232 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2234 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2235 AddToWorklist(Mul.getNode());
2241 if (N0.getOpcode() == ISD::UNDEF)
2242 return DAG.getConstant(0, VT);
2243 // X % undef -> undef
2244 if (N1.getOpcode() == ISD::UNDEF)
2250 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2251 SDValue N0 = N->getOperand(0);
2252 SDValue N1 = N->getOperand(1);
2253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2254 EVT VT = N->getValueType(0);
2257 // fold (mulhs x, 0) -> 0
2258 if (N1C && N1C->isNullValue())
2260 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2261 if (N1C && N1C->getAPIntValue() == 1)
2262 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2263 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2264 getShiftAmountTy(N0.getValueType())));
2265 // fold (mulhs x, undef) -> 0
2266 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2267 return DAG.getConstant(0, VT);
2269 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2271 if (VT.isSimple() && !VT.isVector()) {
2272 MVT Simple = VT.getSimpleVT();
2273 unsigned SimpleSize = Simple.getSizeInBits();
2274 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2275 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2276 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2277 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2278 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2279 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2280 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2281 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2288 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
2291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292 EVT VT = N->getValueType(0);
2295 // fold (mulhu x, 0) -> 0
2296 if (N1C && N1C->isNullValue())
2298 // fold (mulhu x, 1) -> 0
2299 if (N1C && N1C->getAPIntValue() == 1)
2300 return DAG.getConstant(0, N0.getValueType());
2301 // fold (mulhu x, undef) -> 0
2302 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2303 return DAG.getConstant(0, VT);
2305 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2313 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2314 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2315 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2316 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2317 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2324 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2325 /// give the opcodes for the two computations that are being performed. Return
2326 /// true if a simplification was made.
2327 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2329 // If the high half is not needed, just compute the low half.
2330 bool HiExists = N->hasAnyUseOfValue(1);
2332 (!LegalOperations ||
2333 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2334 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2335 return CombineTo(N, Res, Res);
2338 // If the low half is not needed, just compute the high half.
2339 bool LoExists = N->hasAnyUseOfValue(0);
2341 (!LegalOperations ||
2342 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2343 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2344 return CombineTo(N, Res, Res);
2347 // If both halves are used, return as it is.
2348 if (LoExists && HiExists)
2351 // If the two computed results can be simplified separately, separate them.
2353 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2354 AddToWorklist(Lo.getNode());
2355 SDValue LoOpt = combine(Lo.getNode());
2356 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2357 (!LegalOperations ||
2358 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2359 return CombineTo(N, LoOpt, LoOpt);
2363 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2364 AddToWorklist(Hi.getNode());
2365 SDValue HiOpt = combine(Hi.getNode());
2366 if (HiOpt.getNode() && HiOpt != Hi &&
2367 (!LegalOperations ||
2368 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2369 return CombineTo(N, HiOpt, HiOpt);
2375 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
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::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2390 SDValue Hi = DAG.getNode(ISD::SIGN_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::visitUMUL_LOHI(SDNode *N) {
2406 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2407 if (Res.getNode()) return Res;
2409 EVT VT = N->getValueType(0);
2412 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2414 if (VT.isSimple() && !VT.isVector()) {
2415 MVT Simple = VT.getSimpleVT();
2416 unsigned SimpleSize = Simple.getSizeInBits();
2417 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2418 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2419 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2420 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2421 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2422 // Compute the high part as N1.
2423 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2424 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2425 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2426 // Compute the low part as N0.
2427 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2428 return CombineTo(N, Lo, Hi);
2435 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2436 // (smulo x, 2) -> (saddo x, x)
2437 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2438 if (C2->getAPIntValue() == 2)
2439 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2440 N->getOperand(0), N->getOperand(0));
2445 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2446 // (umulo x, 2) -> (uaddo x, x)
2447 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2448 if (C2->getAPIntValue() == 2)
2449 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2450 N->getOperand(0), N->getOperand(0));
2455 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2456 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2457 if (Res.getNode()) return Res;
2462 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2463 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2464 if (Res.getNode()) return Res;
2469 /// If this is a binary operator with two operands of the same opcode, try to
2471 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2472 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2473 EVT VT = N0.getValueType();
2474 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2476 // Bail early if none of these transforms apply.
2477 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2479 // For each of OP in AND/OR/XOR:
2480 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2481 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2482 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2483 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2485 // do not sink logical op inside of a vector extend, since it may combine
2487 EVT Op0VT = N0.getOperand(0).getValueType();
2488 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2489 N0.getOpcode() == ISD::SIGN_EXTEND ||
2490 // Avoid infinite looping with PromoteIntBinOp.
2491 (N0.getOpcode() == ISD::ANY_EXTEND &&
2492 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2493 (N0.getOpcode() == ISD::TRUNCATE &&
2494 (!TLI.isZExtFree(VT, Op0VT) ||
2495 !TLI.isTruncateFree(Op0VT, VT)) &&
2496 TLI.isTypeLegal(Op0VT))) &&
2498 Op0VT == N1.getOperand(0).getValueType() &&
2499 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2500 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2501 N0.getOperand(0).getValueType(),
2502 N0.getOperand(0), N1.getOperand(0));
2503 AddToWorklist(ORNode.getNode());
2504 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2507 // For each of OP in SHL/SRL/SRA/AND...
2508 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2509 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2510 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2511 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2512 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2513 N0.getOperand(1) == N1.getOperand(1)) {
2514 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2515 N0.getOperand(0).getValueType(),
2516 N0.getOperand(0), N1.getOperand(0));
2517 AddToWorklist(ORNode.getNode());
2518 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2519 ORNode, N0.getOperand(1));
2522 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2523 // Only perform this optimization after type legalization and before
2524 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2525 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2526 // we don't want to undo this promotion.
2527 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2529 if ((N0.getOpcode() == ISD::BITCAST ||
2530 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2531 Level == AfterLegalizeTypes) {
2532 SDValue In0 = N0.getOperand(0);
2533 SDValue In1 = N1.getOperand(0);
2534 EVT In0Ty = In0.getValueType();
2535 EVT In1Ty = In1.getValueType();
2537 // If both incoming values are integers, and the original types are the
2539 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2540 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2541 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2542 AddToWorklist(Op.getNode());
2547 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2548 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2549 // If both shuffles use the same mask, and both shuffle within a single
2550 // vector, then it is worthwhile to move the swizzle after the operation.
2551 // The type-legalizer generates this pattern when loading illegal
2552 // vector types from memory. In many cases this allows additional shuffle
2554 // There are other cases where moving the shuffle after the xor/and/or
2555 // is profitable even if shuffles don't perform a swizzle.
2556 // If both shuffles use the same mask, and both shuffles have the same first
2557 // or second operand, then it might still be profitable to move the shuffle
2558 // after the xor/and/or operation.
2559 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2560 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2561 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2563 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2564 "Inputs to shuffles are not the same type");
2566 // Check that both shuffles use the same mask. The masks are known to be of
2567 // the same length because the result vector type is the same.
2568 // Check also that shuffles have only one use to avoid introducing extra
2570 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2571 SVN0->getMask().equals(SVN1->getMask())) {
2572 SDValue ShOp = N0->getOperand(1);
2574 // Don't try to fold this node if it requires introducing a
2575 // build vector of all zeros that might be illegal at this stage.
2576 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2578 ShOp = DAG.getConstant(0, VT);
2583 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2584 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2585 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2586 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2587 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2588 N0->getOperand(0), N1->getOperand(0));
2589 AddToWorklist(NewNode.getNode());
2590 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2591 &SVN0->getMask()[0]);
2594 // Don't try to fold this node if it requires introducing a
2595 // build vector of all zeros that might be illegal at this stage.
2596 ShOp = N0->getOperand(0);
2597 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2599 ShOp = DAG.getConstant(0, VT);
2604 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2605 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2606 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2607 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2608 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2609 N0->getOperand(1), N1->getOperand(1));
2610 AddToWorklist(NewNode.getNode());
2611 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2612 &SVN0->getMask()[0]);
2620 SDValue DAGCombiner::visitAND(SDNode *N) {
2621 SDValue N0 = N->getOperand(0);
2622 SDValue N1 = N->getOperand(1);
2623 SDValue LL, LR, RL, RR, CC0, CC1;
2624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2626 EVT VT = N1.getValueType();
2627 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2630 if (VT.isVector()) {
2631 SDValue FoldedVOp = SimplifyVBinOp(N);
2632 if (FoldedVOp.getNode()) return FoldedVOp;
2634 // fold (and x, 0) -> 0, vector edition
2635 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2636 // do not return N0, because undef node may exist in N0
2637 return DAG.getConstant(
2638 APInt::getNullValue(
2639 N0.getValueType().getScalarType().getSizeInBits()),
2641 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2642 // do not return N1, because undef node may exist in N1
2643 return DAG.getConstant(
2644 APInt::getNullValue(
2645 N1.getValueType().getScalarType().getSizeInBits()),
2648 // fold (and x, -1) -> x, vector edition
2649 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2651 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2655 // fold (and x, undef) -> 0
2656 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2657 return DAG.getConstant(0, VT);
2658 // fold (and c1, c2) -> c1&c2
2660 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2661 // canonicalize constant to RHS
2663 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2664 // fold (and x, -1) -> x
2665 if (N1C && N1C->isAllOnesValue())
2667 // if (and x, c) is known to be zero, return 0
2668 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2669 APInt::getAllOnesValue(BitWidth)))
2670 return DAG.getConstant(0, VT);
2672 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2675 // fold (and (or x, C), D) -> D if (C & D) == D
2676 if (N1C && N0.getOpcode() == ISD::OR)
2677 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2678 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2680 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2681 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2682 SDValue N0Op0 = N0.getOperand(0);
2683 APInt Mask = ~N1C->getAPIntValue();
2684 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2685 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2686 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2687 N0.getValueType(), N0Op0);
2689 // Replace uses of the AND with uses of the Zero extend node.
2692 // We actually want to replace all uses of the any_extend with the
2693 // zero_extend, to avoid duplicating things. This will later cause this
2694 // AND to be folded.
2695 CombineTo(N0.getNode(), Zext);
2696 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2699 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2700 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2701 // already be zero by virtue of the width of the base type of the load.
2703 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2705 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2706 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2707 N0.getOpcode() == ISD::LOAD) {
2708 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2709 N0 : N0.getOperand(0) );
2711 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2712 // This can be a pure constant or a vector splat, in which case we treat the
2713 // vector as a scalar and use the splat value.
2714 APInt Constant = APInt::getNullValue(1);
2715 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2716 Constant = C->getAPIntValue();
2717 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2718 APInt SplatValue, SplatUndef;
2719 unsigned SplatBitSize;
2721 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2722 SplatBitSize, HasAnyUndefs);
2724 // Undef bits can contribute to a possible optimisation if set, so
2726 SplatValue |= SplatUndef;
2728 // The splat value may be something like "0x00FFFFFF", which means 0 for
2729 // the first vector value and FF for the rest, repeating. We need a mask
2730 // that will apply equally to all members of the vector, so AND all the
2731 // lanes of the constant together.
2732 EVT VT = Vector->getValueType(0);
2733 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2735 // If the splat value has been compressed to a bitlength lower
2736 // than the size of the vector lane, we need to re-expand it to
2738 if (BitWidth > SplatBitSize)
2739 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2740 SplatBitSize < BitWidth;
2741 SplatBitSize = SplatBitSize * 2)
2742 SplatValue |= SplatValue.shl(SplatBitSize);
2744 Constant = APInt::getAllOnesValue(BitWidth);
2745 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2746 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2750 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2751 // actually legal and isn't going to get expanded, else this is a false
2753 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2754 Load->getMemoryVT());
2756 // Resize the constant to the same size as the original memory access before
2757 // extension. If it is still the AllOnesValue then this AND is completely
2760 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2763 switch (Load->getExtensionType()) {
2764 default: B = false; break;
2765 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2767 case ISD::NON_EXTLOAD: B = true; break;
2770 if (B && Constant.isAllOnesValue()) {
2771 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2772 // preserve semantics once we get rid of the AND.
2773 SDValue NewLoad(Load, 0);
2774 if (Load->getExtensionType() == ISD::EXTLOAD) {
2775 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2776 Load->getValueType(0), SDLoc(Load),
2777 Load->getChain(), Load->getBasePtr(),
2778 Load->getOffset(), Load->getMemoryVT(),
2779 Load->getMemOperand());
2780 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2781 if (Load->getNumValues() == 3) {
2782 // PRE/POST_INC loads have 3 values.
2783 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2784 NewLoad.getValue(2) };
2785 CombineTo(Load, To, 3, true);
2787 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2791 // Fold the AND away, taking care not to fold to the old load node if we
2793 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2795 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2798 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2799 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2800 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2801 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2803 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2804 LL.getValueType().isInteger()) {
2805 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2806 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2807 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2808 LR.getValueType(), LL, RL);
2809 AddToWorklist(ORNode.getNode());
2810 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2812 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2813 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2814 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2815 LR.getValueType(), LL, RL);
2816 AddToWorklist(ANDNode.getNode());
2817 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2819 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2820 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2821 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2822 LR.getValueType(), LL, RL);
2823 AddToWorklist(ORNode.getNode());
2824 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2827 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2828 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2829 Op0 == Op1 && LL.getValueType().isInteger() &&
2830 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2831 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2832 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2833 cast<ConstantSDNode>(RR)->isNullValue()))) {
2834 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2835 LL, DAG.getConstant(1, LL.getValueType()));
2836 AddToWorklist(ADDNode.getNode());
2837 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2838 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2840 // canonicalize equivalent to ll == rl
2841 if (LL == RR && LR == RL) {
2842 Op1 = ISD::getSetCCSwappedOperands(Op1);
2845 if (LL == RL && LR == RR) {
2846 bool isInteger = LL.getValueType().isInteger();
2847 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2848 if (Result != ISD::SETCC_INVALID &&
2849 (!LegalOperations ||
2850 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2851 TLI.isOperationLegal(ISD::SETCC,
2852 getSetCCResultType(N0.getSimpleValueType())))))
2853 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2858 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2859 if (N0.getOpcode() == N1.getOpcode()) {
2860 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2861 if (Tmp.getNode()) return Tmp;
2864 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2865 // fold (and (sra)) -> (and (srl)) when possible.
2866 if (!VT.isVector() &&
2867 SimplifyDemandedBits(SDValue(N, 0)))
2868 return SDValue(N, 0);
2870 // fold (zext_inreg (extload x)) -> (zextload x)
2871 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2872 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2873 EVT MemVT = LN0->getMemoryVT();
2874 // If we zero all the possible extended bits, then we can turn this into
2875 // a zextload if we are running before legalize or the operation is legal.
2876 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2877 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2878 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2879 ((!LegalOperations && !LN0->isVolatile()) ||
2880 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2881 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2882 LN0->getChain(), LN0->getBasePtr(),
2883 MemVT, LN0->getMemOperand());
2885 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2886 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2889 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2890 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2892 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2893 EVT MemVT = LN0->getMemoryVT();
2894 // If we zero all the possible extended bits, then we can turn this into
2895 // a zextload if we are running before legalize or the operation is legal.
2896 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2897 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2898 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2899 ((!LegalOperations && !LN0->isVolatile()) ||
2900 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2901 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2902 LN0->getChain(), LN0->getBasePtr(),
2903 MemVT, LN0->getMemOperand());
2905 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2906 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2910 // fold (and (load x), 255) -> (zextload x, i8)
2911 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2912 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2913 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2914 (N0.getOpcode() == ISD::ANY_EXTEND &&
2915 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2916 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2917 LoadSDNode *LN0 = HasAnyExt
2918 ? cast<LoadSDNode>(N0.getOperand(0))
2919 : cast<LoadSDNode>(N0);
2920 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2921 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2922 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2923 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2924 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2925 EVT LoadedVT = LN0->getMemoryVT();
2927 if (ExtVT == LoadedVT &&
2928 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2929 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2932 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2933 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2934 LN0->getMemOperand());
2936 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2937 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2940 // Do not change the width of a volatile load.
2941 // Do not generate loads of non-round integer types since these can
2942 // be expensive (and would be wrong if the type is not byte sized).
2943 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2944 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2945 EVT PtrType = LN0->getOperand(1).getValueType();
2947 unsigned Alignment = LN0->getAlignment();
2948 SDValue NewPtr = LN0->getBasePtr();
2950 // For big endian targets, we need to add an offset to the pointer
2951 // to load the correct bytes. For little endian systems, we merely
2952 // need to read fewer bytes from the same pointer.
2953 if (TLI.isBigEndian()) {
2954 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2955 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2956 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2957 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2958 NewPtr, DAG.getConstant(PtrOff, PtrType));
2959 Alignment = MinAlign(Alignment, PtrOff);
2962 AddToWorklist(NewPtr.getNode());
2964 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2966 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2967 LN0->getChain(), NewPtr,
2968 LN0->getPointerInfo(),
2969 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2970 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2972 CombineTo(LN0, Load, Load.getValue(1));
2973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2979 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2980 VT.getSizeInBits() <= 64) {
2981 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2982 APInt ADDC = ADDI->getAPIntValue();
2983 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2984 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2985 // immediate for an add, but it is legal if its top c2 bits are set,
2986 // transform the ADD so the immediate doesn't need to be materialized
2988 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2989 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2990 SRLI->getZExtValue());
2991 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2993 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2995 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2996 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2997 CombineTo(N0.getNode(), NewAdd);
2998 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3006 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3007 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3008 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3009 N0.getOperand(1), false);
3010 if (BSwap.getNode())
3017 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3018 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3019 bool DemandHighBits) {
3020 if (!LegalOperations)
3023 EVT VT = N->getValueType(0);
3024 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3026 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3029 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3030 bool LookPassAnd0 = false;
3031 bool LookPassAnd1 = false;
3032 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3034 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3036 if (N0.getOpcode() == ISD::AND) {
3037 if (!N0.getNode()->hasOneUse())
3039 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3040 if (!N01C || N01C->getZExtValue() != 0xFF00)
3042 N0 = N0.getOperand(0);
3043 LookPassAnd0 = true;
3046 if (N1.getOpcode() == ISD::AND) {
3047 if (!N1.getNode()->hasOneUse())
3049 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3050 if (!N11C || N11C->getZExtValue() != 0xFF)
3052 N1 = N1.getOperand(0);
3053 LookPassAnd1 = true;
3056 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3058 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3060 if (!N0.getNode()->hasOneUse() ||
3061 !N1.getNode()->hasOneUse())
3064 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3065 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3068 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3071 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3072 SDValue N00 = N0->getOperand(0);
3073 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3074 if (!N00.getNode()->hasOneUse())
3076 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3077 if (!N001C || N001C->getZExtValue() != 0xFF)
3079 N00 = N00.getOperand(0);
3080 LookPassAnd0 = true;
3083 SDValue N10 = N1->getOperand(0);
3084 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3085 if (!N10.getNode()->hasOneUse())
3087 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3088 if (!N101C || N101C->getZExtValue() != 0xFF00)
3090 N10 = N10.getOperand(0);
3091 LookPassAnd1 = true;
3097 // Make sure everything beyond the low halfword gets set to zero since the SRL
3098 // 16 will clear the top bits.
3099 unsigned OpSizeInBits = VT.getSizeInBits();
3100 if (DemandHighBits && OpSizeInBits > 16) {
3101 // If the left-shift isn't masked out then the only way this is a bswap is
3102 // if all bits beyond the low 8 are 0. In that case the entire pattern
3103 // reduces to a left shift anyway: leave it for other parts of the combiner.
3107 // However, if the right shift isn't masked out then it might be because
3108 // it's not needed. See if we can spot that too.
3109 if (!LookPassAnd1 &&
3110 !DAG.MaskedValueIsZero(
3111 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3115 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3116 if (OpSizeInBits > 16)
3117 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3118 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3122 /// Return true if the specified node is an element that makes up a 32-bit
3123 /// packed halfword byteswap.
3124 /// ((x & 0x000000ff) << 8) |
3125 /// ((x & 0x0000ff00) >> 8) |
3126 /// ((x & 0x00ff0000) << 8) |
3127 /// ((x & 0xff000000) >> 8)
3128 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3129 if (!N.getNode()->hasOneUse())
3132 unsigned Opc = N.getOpcode();
3133 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3141 switch (N1C->getZExtValue()) {
3144 case 0xFF: Num = 0; break;
3145 case 0xFF00: Num = 1; break;
3146 case 0xFF0000: Num = 2; break;
3147 case 0xFF000000: Num = 3; break;
3150 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3151 SDValue N0 = N.getOperand(0);
3152 if (Opc == ISD::AND) {
3153 if (Num == 0 || Num == 2) {
3155 // (x >> 8) & 0xff0000
3156 if (N0.getOpcode() != ISD::SRL)
3158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159 if (!C || C->getZExtValue() != 8)
3162 // (x << 8) & 0xff00
3163 // (x << 8) & 0xff000000
3164 if (N0.getOpcode() != ISD::SHL)
3166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3167 if (!C || C->getZExtValue() != 8)
3170 } else if (Opc == ISD::SHL) {
3172 // (x & 0xff0000) << 8
3173 if (Num != 0 && Num != 2)
3175 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3176 if (!C || C->getZExtValue() != 8)
3178 } else { // Opc == ISD::SRL
3179 // (x & 0xff00) >> 8
3180 // (x & 0xff000000) >> 8
3181 if (Num != 1 && Num != 3)
3183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3184 if (!C || C->getZExtValue() != 8)
3191 Parts[Num] = N0.getOperand(0).getNode();
3195 /// Match a 32-bit packed halfword bswap. That is
3196 /// ((x & 0x000000ff) << 8) |
3197 /// ((x & 0x0000ff00) >> 8) |
3198 /// ((x & 0x00ff0000) << 8) |
3199 /// ((x & 0xff000000) >> 8)
3200 /// => (rotl (bswap x), 16)
3201 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3202 if (!LegalOperations)
3205 EVT VT = N->getValueType(0);
3208 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3211 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3213 // (or (or (and), (and)), (or (and), (and)))
3214 // (or (or (or (and), (and)), (and)), (and))
3215 if (N0.getOpcode() != ISD::OR)
3217 SDValue N00 = N0.getOperand(0);
3218 SDValue N01 = N0.getOperand(1);
3220 if (N1.getOpcode() == ISD::OR &&
3221 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3222 // (or (or (and), (and)), (or (and), (and)))
3223 SDValue N000 = N00.getOperand(0);
3224 if (!isBSwapHWordElement(N000, Parts))
3227 SDValue N001 = N00.getOperand(1);
3228 if (!isBSwapHWordElement(N001, Parts))
3230 SDValue N010 = N01.getOperand(0);
3231 if (!isBSwapHWordElement(N010, Parts))
3233 SDValue N011 = N01.getOperand(1);
3234 if (!isBSwapHWordElement(N011, Parts))
3237 // (or (or (or (and), (and)), (and)), (and))
3238 if (!isBSwapHWordElement(N1, Parts))
3240 if (!isBSwapHWordElement(N01, Parts))
3242 if (N00.getOpcode() != ISD::OR)
3244 SDValue N000 = N00.getOperand(0);
3245 if (!isBSwapHWordElement(N000, Parts))
3247 SDValue N001 = N00.getOperand(1);
3248 if (!isBSwapHWordElement(N001, Parts))
3252 // Make sure the parts are all coming from the same node.
3253 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3256 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3257 SDValue(Parts[0],0));
3259 // Result of the bswap should be rotated by 16. If it's not legal, then
3260 // do (x << 16) | (x >> 16).
3261 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3262 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3263 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3264 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3265 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3266 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3267 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3268 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3271 SDValue DAGCombiner::visitOR(SDNode *N) {
3272 SDValue N0 = N->getOperand(0);
3273 SDValue N1 = N->getOperand(1);
3274 SDValue LL, LR, RL, RR, CC0, CC1;
3275 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3277 EVT VT = N1.getValueType();
3280 if (VT.isVector()) {
3281 SDValue FoldedVOp = SimplifyVBinOp(N);
3282 if (FoldedVOp.getNode()) return FoldedVOp;
3284 // fold (or x, 0) -> x, vector edition
3285 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3287 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3290 // fold (or x, -1) -> -1, vector edition
3291 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3292 // do not return N0, because undef node may exist in N0
3293 return DAG.getConstant(
3294 APInt::getAllOnesValue(
3295 N0.getValueType().getScalarType().getSizeInBits()),
3297 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3298 // do not return N1, because undef node may exist in N1
3299 return DAG.getConstant(
3300 APInt::getAllOnesValue(
3301 N1.getValueType().getScalarType().getSizeInBits()),
3304 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3305 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3306 // Do this only if the resulting shuffle is legal.
3307 if (isa<ShuffleVectorSDNode>(N0) &&
3308 isa<ShuffleVectorSDNode>(N1) &&
3309 // Avoid folding a node with illegal type.
3310 TLI.isTypeLegal(VT) &&
3311 N0->getOperand(1) == N1->getOperand(1) &&
3312 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3313 bool CanFold = true;
3314 unsigned NumElts = VT.getVectorNumElements();
3315 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3316 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3317 // We construct two shuffle masks:
3318 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3319 // and N1 as the second operand.
3320 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3321 // and N0 as the second operand.
3322 // We do this because OR is commutable and therefore there might be
3323 // two ways to fold this node into a shuffle.
3324 SmallVector<int,4> Mask1;
3325 SmallVector<int,4> Mask2;
3327 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3328 int M0 = SV0->getMaskElt(i);
3329 int M1 = SV1->getMaskElt(i);
3331 // Both shuffle indexes are undef. Propagate Undef.
3332 if (M0 < 0 && M1 < 0) {
3333 Mask1.push_back(M0);
3334 Mask2.push_back(M0);
3338 if (M0 < 0 || M1 < 0 ||
3339 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3340 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3345 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3346 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3350 // Fold this sequence only if the resulting shuffle is 'legal'.
3351 if (TLI.isShuffleMaskLegal(Mask1, VT))
3352 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3353 N1->getOperand(0), &Mask1[0]);
3354 if (TLI.isShuffleMaskLegal(Mask2, VT))
3355 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3356 N0->getOperand(0), &Mask2[0]);
3361 // fold (or x, undef) -> -1
3362 if (!LegalOperations &&
3363 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3364 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3365 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3367 // fold (or c1, c2) -> c1|c2
3369 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3370 // canonicalize constant to RHS
3372 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3373 // fold (or x, 0) -> x
3374 if (N1C && N1C->isNullValue())
3376 // fold (or x, -1) -> -1
3377 if (N1C && N1C->isAllOnesValue())
3379 // fold (or x, c) -> c iff (x & ~c) == 0
3380 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3383 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3384 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3385 if (BSwap.getNode())
3387 BSwap = MatchBSwapHWordLow(N, N0, N1);
3388 if (BSwap.getNode())
3392 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3395 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3396 // iff (c1 & c2) == 0.
3397 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3398 isa<ConstantSDNode>(N0.getOperand(1))) {
3399 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3400 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3401 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3404 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3405 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3406 N0.getOperand(0), N1), COR);
3409 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3410 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3411 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3412 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3414 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3415 LL.getValueType().isInteger()) {
3416 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3417 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3418 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3419 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3420 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3421 LR.getValueType(), LL, RL);
3422 AddToWorklist(ORNode.getNode());
3423 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3425 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3426 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3427 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3428 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3429 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3430 LR.getValueType(), LL, RL);
3431 AddToWorklist(ANDNode.getNode());
3432 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3435 // canonicalize equivalent to ll == rl
3436 if (LL == RR && LR == RL) {
3437 Op1 = ISD::getSetCCSwappedOperands(Op1);
3440 if (LL == RL && LR == RR) {
3441 bool isInteger = LL.getValueType().isInteger();
3442 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3443 if (Result != ISD::SETCC_INVALID &&
3444 (!LegalOperations ||
3445 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3446 TLI.isOperationLegal(ISD::SETCC,
3447 getSetCCResultType(N0.getValueType())))))
3448 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3453 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3454 if (N0.getOpcode() == N1.getOpcode()) {
3455 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3456 if (Tmp.getNode()) return Tmp;
3459 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3460 if (N0.getOpcode() == ISD::AND &&
3461 N1.getOpcode() == ISD::AND &&
3462 N0.getOperand(1).getOpcode() == ISD::Constant &&
3463 N1.getOperand(1).getOpcode() == ISD::Constant &&
3464 // Don't increase # computations.
3465 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3466 // We can only do this xform if we know that bits from X that are set in C2
3467 // but not in C1 are already zero. Likewise for Y.
3468 const APInt &LHSMask =
3469 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3470 const APInt &RHSMask =
3471 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3473 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3474 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3475 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3476 N0.getOperand(0), N1.getOperand(0));
3477 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3478 DAG.getConstant(LHSMask | RHSMask, VT));
3482 // See if this is some rotate idiom.
3483 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3484 return SDValue(Rot, 0);
3486 // Simplify the operands using demanded-bits information.
3487 if (!VT.isVector() &&
3488 SimplifyDemandedBits(SDValue(N, 0)))
3489 return SDValue(N, 0);
3494 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3495 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3496 if (Op.getOpcode() == ISD::AND) {
3497 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3498 Mask = Op.getOperand(1);
3499 Op = Op.getOperand(0);
3505 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3513 // Return true if we can prove that, whenever Neg and Pos are both in the
3514 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3515 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3517 // (or (shift1 X, Neg), (shift2 X, Pos))
3519 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3520 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3521 // to consider shift amounts with defined behavior.
3522 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3523 // If OpSize is a power of 2 then:
3525 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3526 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3528 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3529 // for the stronger condition:
3531 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3533 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3534 // we can just replace Neg with Neg' for the rest of the function.
3536 // In other cases we check for the even stronger condition:
3538 // Neg == OpSize - Pos [B]
3540 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3541 // behavior if Pos == 0 (and consequently Neg == OpSize).
3543 // We could actually use [A] whenever OpSize is a power of 2, but the
3544 // only extra cases that it would match are those uninteresting ones
3545 // where Neg and Pos are never in range at the same time. E.g. for
3546 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3547 // as well as (sub 32, Pos), but:
3549 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3551 // always invokes undefined behavior for 32-bit X.
3553 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3554 unsigned MaskLoBits = 0;
3555 if (Neg.getOpcode() == ISD::AND &&
3556 isPowerOf2_64(OpSize) &&
3557 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3558 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3559 Neg = Neg.getOperand(0);
3560 MaskLoBits = Log2_64(OpSize);
3563 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3564 if (Neg.getOpcode() != ISD::SUB)
3566 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3569 SDValue NegOp1 = Neg.getOperand(1);
3571 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3572 // Pos'. The truncation is redundant for the purpose of the equality.
3574 Pos.getOpcode() == ISD::AND &&
3575 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3576 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3577 Pos = Pos.getOperand(0);
3579 // The condition we need is now:
3581 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3583 // If NegOp1 == Pos then we need:
3585 // OpSize & Mask == NegC & Mask
3587 // (because "x & Mask" is a truncation and distributes through subtraction).
3590 Width = NegC->getAPIntValue();
3591 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3592 // Then the condition we want to prove becomes:
3594 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3596 // which, again because "x & Mask" is a truncation, becomes:
3598 // NegC & Mask == (OpSize - PosC) & Mask
3599 // OpSize & Mask == (NegC + PosC) & Mask
3600 else if (Pos.getOpcode() == ISD::ADD &&
3601 Pos.getOperand(0) == NegOp1 &&
3602 Pos.getOperand(1).getOpcode() == ISD::Constant)
3603 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3604 NegC->getAPIntValue());
3608 // Now we just need to check that OpSize & Mask == Width & Mask.
3610 // Opsize & Mask is 0 since Mask is Opsize - 1.
3611 return Width.getLoBits(MaskLoBits) == 0;
3612 return Width == OpSize;
3615 // A subroutine of MatchRotate used once we have found an OR of two opposite
3616 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3617 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3618 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3619 // Neg with outer conversions stripped away.
3620 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3621 SDValue Neg, SDValue InnerPos,
3622 SDValue InnerNeg, unsigned PosOpcode,
3623 unsigned NegOpcode, SDLoc DL) {
3624 // fold (or (shl x, (*ext y)),
3625 // (srl x, (*ext (sub 32, y)))) ->
3626 // (rotl x, y) or (rotr x, (sub 32, y))
3628 // fold (or (shl x, (*ext (sub 32, y))),
3629 // (srl x, (*ext y))) ->
3630 // (rotr x, y) or (rotl x, (sub 32, y))
3631 EVT VT = Shifted.getValueType();
3632 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3633 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3634 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3635 HasPos ? Pos : Neg).getNode();
3641 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3642 // idioms for rotate, and if the target supports rotation instructions, generate
3644 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3645 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3646 EVT VT = LHS.getValueType();
3647 if (!TLI.isTypeLegal(VT)) return nullptr;
3649 // The target must have at least one rotate flavor.
3650 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3651 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3652 if (!HasROTL && !HasROTR) return nullptr;
3654 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3655 SDValue LHSShift; // The shift.
3656 SDValue LHSMask; // AND value if any.
3657 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3658 return nullptr; // Not part of a rotate.
3660 SDValue RHSShift; // The shift.
3661 SDValue RHSMask; // AND value if any.
3662 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3663 return nullptr; // Not part of a rotate.
3665 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3666 return nullptr; // Not shifting the same value.
3668 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3669 return nullptr; // Shifts must disagree.
3671 // Canonicalize shl to left side in a shl/srl pair.
3672 if (RHSShift.getOpcode() == ISD::SHL) {
3673 std::swap(LHS, RHS);
3674 std::swap(LHSShift, RHSShift);
3675 std::swap(LHSMask , RHSMask );
3678 unsigned OpSizeInBits = VT.getSizeInBits();
3679 SDValue LHSShiftArg = LHSShift.getOperand(0);
3680 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3681 SDValue RHSShiftArg = RHSShift.getOperand(0);
3682 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3684 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3685 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3686 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3687 RHSShiftAmt.getOpcode() == ISD::Constant) {
3688 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3689 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3690 if ((LShVal + RShVal) != OpSizeInBits)
3693 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3694 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3696 // If there is an AND of either shifted operand, apply it to the result.
3697 if (LHSMask.getNode() || RHSMask.getNode()) {
3698 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3700 if (LHSMask.getNode()) {
3701 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3702 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3704 if (RHSMask.getNode()) {
3705 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3706 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3709 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3712 return Rot.getNode();
3715 // If there is a mask here, and we have a variable shift, we can't be sure
3716 // that we're masking out the right stuff.
3717 if (LHSMask.getNode() || RHSMask.getNode())
3720 // If the shift amount is sign/zext/any-extended just peel it off.
3721 SDValue LExtOp0 = LHSShiftAmt;
3722 SDValue RExtOp0 = RHSShiftAmt;
3723 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3724 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3725 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3726 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3727 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3728 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3729 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3730 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3731 LExtOp0 = LHSShiftAmt.getOperand(0);
3732 RExtOp0 = RHSShiftAmt.getOperand(0);
3735 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3736 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3740 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3741 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3748 SDValue DAGCombiner::visitXOR(SDNode *N) {
3749 SDValue N0 = N->getOperand(0);
3750 SDValue N1 = N->getOperand(1);
3751 SDValue LHS, RHS, CC;
3752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3754 EVT VT = N0.getValueType();
3757 if (VT.isVector()) {
3758 SDValue FoldedVOp = SimplifyVBinOp(N);
3759 if (FoldedVOp.getNode()) return FoldedVOp;
3761 // fold (xor x, 0) -> x, vector edition
3762 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3764 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3768 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3769 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3770 return DAG.getConstant(0, VT);
3771 // fold (xor x, undef) -> undef
3772 if (N0.getOpcode() == ISD::UNDEF)
3774 if (N1.getOpcode() == ISD::UNDEF)
3776 // fold (xor c1, c2) -> c1^c2
3778 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3779 // canonicalize constant to RHS
3781 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3782 // fold (xor x, 0) -> x
3783 if (N1C && N1C->isNullValue())
3786 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3790 // fold !(x cc y) -> (x !cc y)
3791 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3792 bool isInt = LHS.getValueType().isInteger();
3793 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3796 if (!LegalOperations ||
3797 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3798 switch (N0.getOpcode()) {
3800 llvm_unreachable("Unhandled SetCC Equivalent!");
3802 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3803 case ISD::SELECT_CC:
3804 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3805 N0.getOperand(3), NotCC);
3810 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3811 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3812 N0.getNode()->hasOneUse() &&
3813 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3814 SDValue V = N0.getOperand(0);
3815 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3816 DAG.getConstant(1, V.getValueType()));
3817 AddToWorklist(V.getNode());
3818 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3821 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3822 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3823 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3824 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3825 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3826 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3827 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3828 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3829 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3830 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3833 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3834 if (N1C && N1C->isAllOnesValue() &&
3835 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3836 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3837 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3838 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3839 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3840 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3841 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3842 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3845 // fold (xor (and x, y), y) -> (and (not x), y)
3846 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3847 N0->getOperand(1) == N1) {
3848 SDValue X = N0->getOperand(0);
3849 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3850 AddToWorklist(NotX.getNode());
3851 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3853 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3854 if (N1C && N0.getOpcode() == ISD::XOR) {
3855 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3856 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3858 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3859 DAG.getConstant(N1C->getAPIntValue() ^
3860 N00C->getAPIntValue(), VT));
3862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3863 DAG.getConstant(N1C->getAPIntValue() ^
3864 N01C->getAPIntValue(), VT));
3866 // fold (xor x, x) -> 0
3868 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3870 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3871 if (N0.getOpcode() == N1.getOpcode()) {
3872 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3873 if (Tmp.getNode()) return Tmp;
3876 // Simplify the expression using non-local knowledge.
3877 if (!VT.isVector() &&
3878 SimplifyDemandedBits(SDValue(N, 0)))
3879 return SDValue(N, 0);
3884 /// Handle transforms common to the three shifts, when the shift amount is a
3886 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3887 // We can't and shouldn't fold opaque constants.
3888 if (Amt->isOpaque())
3891 SDNode *LHS = N->getOperand(0).getNode();
3892 if (!LHS->hasOneUse()) return SDValue();
3894 // We want to pull some binops through shifts, so that we have (and (shift))
3895 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3896 // thing happens with address calculations, so it's important to canonicalize
3898 bool HighBitSet = false; // Can we transform this if the high bit is set?
3900 switch (LHS->getOpcode()) {
3901 default: return SDValue();
3904 HighBitSet = false; // We can only transform sra if the high bit is clear.
3907 HighBitSet = true; // We can only transform sra if the high bit is set.
3910 if (N->getOpcode() != ISD::SHL)
3911 return SDValue(); // only shl(add) not sr[al](add).
3912 HighBitSet = false; // We can only transform sra if the high bit is clear.
3916 // We require the RHS of the binop to be a constant and not opaque as well.
3917 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3918 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3920 // FIXME: disable this unless the input to the binop is a shift by a constant.
3921 // If it is not a shift, it pessimizes some common cases like:
3923 // void foo(int *X, int i) { X[i & 1235] = 1; }
3924 // int bar(int *X, int i) { return X[i & 255]; }
3925 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3926 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3927 BinOpLHSVal->getOpcode() != ISD::SRA &&
3928 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3929 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3932 EVT VT = N->getValueType(0);
3934 // If this is a signed shift right, and the high bit is modified by the
3935 // logical operation, do not perform the transformation. The highBitSet
3936 // boolean indicates the value of the high bit of the constant which would
3937 // cause it to be modified for this operation.
3938 if (N->getOpcode() == ISD::SRA) {
3939 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3940 if (BinOpRHSSignSet != HighBitSet)
3944 if (!TLI.isDesirableToCommuteWithShift(LHS))
3947 // Fold the constants, shifting the binop RHS by the shift amount.
3948 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3950 LHS->getOperand(1), N->getOperand(1));
3951 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3953 // Create the new shift.
3954 SDValue NewShift = DAG.getNode(N->getOpcode(),
3955 SDLoc(LHS->getOperand(0)),
3956 VT, LHS->getOperand(0), N->getOperand(1));
3958 // Create the new binop.
3959 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3962 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3963 assert(N->getOpcode() == ISD::TRUNCATE);
3964 assert(N->getOperand(0).getOpcode() == ISD::AND);
3966 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3967 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3968 SDValue N01 = N->getOperand(0).getOperand(1);
3970 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3971 EVT TruncVT = N->getValueType(0);
3972 SDValue N00 = N->getOperand(0).getOperand(0);
3973 APInt TruncC = N01C->getAPIntValue();
3974 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3976 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3977 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3978 DAG.getConstant(TruncC, TruncVT));
3985 SDValue DAGCombiner::visitRotate(SDNode *N) {
3986 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3987 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3988 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3989 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3990 if (NewOp1.getNode())
3991 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3992 N->getOperand(0), NewOp1);
3997 SDValue DAGCombiner::visitSHL(SDNode *N) {
3998 SDValue N0 = N->getOperand(0);
3999 SDValue N1 = N->getOperand(1);
4000 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4001 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4002 EVT VT = N0.getValueType();
4003 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4006 if (VT.isVector()) {
4007 SDValue FoldedVOp = SimplifyVBinOp(N);
4008 if (FoldedVOp.getNode()) return FoldedVOp;
4010 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4011 // If setcc produces all-one true value then:
4012 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4013 if (N1CV && N1CV->isConstant()) {
4014 if (N0.getOpcode() == ISD::AND) {
4015 SDValue N00 = N0->getOperand(0);
4016 SDValue N01 = N0->getOperand(1);
4017 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4019 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4020 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4021 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4022 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4024 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4027 N1C = isConstOrConstSplat(N1);
4032 // fold (shl c1, c2) -> c1<<c2
4034 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4035 // fold (shl 0, x) -> 0
4036 if (N0C && N0C->isNullValue())
4038 // fold (shl x, c >= size(x)) -> undef
4039 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4040 return DAG.getUNDEF(VT);
4041 // fold (shl x, 0) -> x
4042 if (N1C && N1C->isNullValue())
4044 // fold (shl undef, x) -> 0
4045 if (N0.getOpcode() == ISD::UNDEF)
4046 return DAG.getConstant(0, VT);
4047 // if (shl x, c) is known to be zero, return 0
4048 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4049 APInt::getAllOnesValue(OpSizeInBits)))
4050 return DAG.getConstant(0, VT);
4051 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4052 if (N1.getOpcode() == ISD::TRUNCATE &&
4053 N1.getOperand(0).getOpcode() == ISD::AND) {
4054 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4055 if (NewOp1.getNode())
4056 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4059 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4060 return SDValue(N, 0);
4062 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4063 if (N1C && N0.getOpcode() == ISD::SHL) {
4064 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4065 uint64_t c1 = N0C1->getZExtValue();
4066 uint64_t c2 = N1C->getZExtValue();
4067 if (c1 + c2 >= OpSizeInBits)
4068 return DAG.getConstant(0, VT);
4069 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4070 DAG.getConstant(c1 + c2, N1.getValueType()));
4074 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4075 // For this to be valid, the second form must not preserve any of the bits
4076 // that are shifted out by the inner shift in the first form. This means
4077 // the outer shift size must be >= the number of bits added by the ext.
4078 // As a corollary, we don't care what kind of ext it is.
4079 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4080 N0.getOpcode() == ISD::ANY_EXTEND ||
4081 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4082 N0.getOperand(0).getOpcode() == ISD::SHL) {
4083 SDValue N0Op0 = N0.getOperand(0);
4084 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4085 uint64_t c1 = N0Op0C1->getZExtValue();
4086 uint64_t c2 = N1C->getZExtValue();
4087 EVT InnerShiftVT = N0Op0.getValueType();
4088 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4089 if (c2 >= OpSizeInBits - InnerShiftSize) {
4090 if (c1 + c2 >= OpSizeInBits)
4091 return DAG.getConstant(0, VT);
4092 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4093 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4094 N0Op0->getOperand(0)),
4095 DAG.getConstant(c1 + c2, N1.getValueType()));
4100 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4101 // Only fold this if the inner zext has no other uses to avoid increasing
4102 // the total number of instructions.
4103 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4104 N0.getOperand(0).getOpcode() == ISD::SRL) {
4105 SDValue N0Op0 = N0.getOperand(0);
4106 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4107 uint64_t c1 = N0Op0C1->getZExtValue();
4108 if (c1 < VT.getScalarSizeInBits()) {
4109 uint64_t c2 = N1C->getZExtValue();
4111 SDValue NewOp0 = N0.getOperand(0);
4112 EVT CountVT = NewOp0.getOperand(1).getValueType();
4113 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4114 NewOp0, DAG.getConstant(c2, CountVT));
4115 AddToWorklist(NewSHL.getNode());
4116 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4122 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4123 // (and (srl x, (sub c1, c2), MASK)
4124 // Only fold this if the inner shift has no other uses -- if it does, folding
4125 // this will increase the total number of instructions.
4126 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4127 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4128 uint64_t c1 = N0C1->getZExtValue();
4129 if (c1 < OpSizeInBits) {
4130 uint64_t c2 = N1C->getZExtValue();
4131 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4134 Mask = Mask.shl(c2 - c1);
4135 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4136 DAG.getConstant(c2 - c1, N1.getValueType()));
4138 Mask = Mask.lshr(c1 - c2);
4139 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4140 DAG.getConstant(c1 - c2, N1.getValueType()));
4142 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4143 DAG.getConstant(Mask, VT));
4147 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4148 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4149 unsigned BitSize = VT.getScalarSizeInBits();
4150 SDValue HiBitsMask =
4151 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4152 BitSize - N1C->getZExtValue()), VT);
4153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4157 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4158 // Variant of version done on multiply, except mul by a power of 2 is turned
4161 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4162 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4163 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4164 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4165 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4166 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4170 SDValue NewSHL = visitShiftByConstant(N, N1C);
4171 if (NewSHL.getNode())
4178 SDValue DAGCombiner::visitSRA(SDNode *N) {
4179 SDValue N0 = N->getOperand(0);
4180 SDValue N1 = N->getOperand(1);
4181 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4182 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4183 EVT VT = N0.getValueType();
4184 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4187 if (VT.isVector()) {
4188 SDValue FoldedVOp = SimplifyVBinOp(N);
4189 if (FoldedVOp.getNode()) return FoldedVOp;
4191 N1C = isConstOrConstSplat(N1);
4194 // fold (sra c1, c2) -> (sra c1, c2)
4196 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4197 // fold (sra 0, x) -> 0
4198 if (N0C && N0C->isNullValue())
4200 // fold (sra -1, x) -> -1
4201 if (N0C && N0C->isAllOnesValue())
4203 // fold (sra x, (setge c, size(x))) -> undef
4204 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4205 return DAG.getUNDEF(VT);
4206 // fold (sra x, 0) -> x
4207 if (N1C && N1C->isNullValue())
4209 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4211 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4212 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4213 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4215 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4216 ExtVT, VT.getVectorNumElements());
4217 if ((!LegalOperations ||
4218 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4219 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4220 N0.getOperand(0), DAG.getValueType(ExtVT));
4223 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4224 if (N1C && N0.getOpcode() == ISD::SRA) {
4225 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4226 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4227 if (Sum >= OpSizeInBits)
4228 Sum = OpSizeInBits - 1;
4229 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4230 DAG.getConstant(Sum, N1.getValueType()));
4234 // fold (sra (shl X, m), (sub result_size, n))
4235 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4236 // result_size - n != m.
4237 // If truncate is free for the target sext(shl) is likely to result in better
4239 if (N0.getOpcode() == ISD::SHL && N1C) {
4240 // Get the two constanst of the shifts, CN0 = m, CN = n.
4241 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4243 LLVMContext &Ctx = *DAG.getContext();
4244 // Determine what the truncate's result bitsize and type would be.
4245 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4248 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4250 // Determine the residual right-shift amount.
4251 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4253 // If the shift is not a no-op (in which case this should be just a sign
4254 // extend already), the truncated to type is legal, sign_extend is legal
4255 // on that type, and the truncate to that type is both legal and free,
4256 // perform the transform.
4257 if ((ShiftAmt > 0) &&
4258 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4259 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4260 TLI.isTruncateFree(VT, TruncVT)) {
4262 SDValue Amt = DAG.getConstant(ShiftAmt,
4263 getShiftAmountTy(N0.getOperand(0).getValueType()));
4264 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4265 N0.getOperand(0), Amt);
4266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4268 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4269 N->getValueType(0), Trunc);
4274 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4275 if (N1.getOpcode() == ISD::TRUNCATE &&
4276 N1.getOperand(0).getOpcode() == ISD::AND) {
4277 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4278 if (NewOp1.getNode())
4279 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4282 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4283 // if c1 is equal to the number of bits the trunc removes
4284 if (N0.getOpcode() == ISD::TRUNCATE &&
4285 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4286 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4287 N0.getOperand(0).hasOneUse() &&
4288 N0.getOperand(0).getOperand(1).hasOneUse() &&
4290 SDValue N0Op0 = N0.getOperand(0);
4291 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4292 unsigned LargeShiftVal = LargeShift->getZExtValue();
4293 EVT LargeVT = N0Op0.getValueType();
4295 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4297 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4298 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4299 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4300 N0Op0.getOperand(0), Amt);
4301 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4306 // Simplify, based on bits shifted out of the LHS.
4307 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4308 return SDValue(N, 0);
4311 // If the sign bit is known to be zero, switch this to a SRL.
4312 if (DAG.SignBitIsZero(N0))
4313 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4316 SDValue NewSRA = visitShiftByConstant(N, N1C);
4317 if (NewSRA.getNode())
4324 SDValue DAGCombiner::visitSRL(SDNode *N) {
4325 SDValue N0 = N->getOperand(0);
4326 SDValue N1 = N->getOperand(1);
4327 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4329 EVT VT = N0.getValueType();
4330 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4333 if (VT.isVector()) {
4334 SDValue FoldedVOp = SimplifyVBinOp(N);
4335 if (FoldedVOp.getNode()) return FoldedVOp;
4337 N1C = isConstOrConstSplat(N1);
4340 // fold (srl c1, c2) -> c1 >>u c2
4342 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4343 // fold (srl 0, x) -> 0
4344 if (N0C && N0C->isNullValue())
4346 // fold (srl x, c >= size(x)) -> undef
4347 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4348 return DAG.getUNDEF(VT);
4349 // fold (srl x, 0) -> x
4350 if (N1C && N1C->isNullValue())
4352 // if (srl x, c) is known to be zero, return 0
4353 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4354 APInt::getAllOnesValue(OpSizeInBits)))
4355 return DAG.getConstant(0, VT);
4357 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4358 if (N1C && N0.getOpcode() == ISD::SRL) {
4359 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4360 uint64_t c1 = N01C->getZExtValue();
4361 uint64_t c2 = N1C->getZExtValue();
4362 if (c1 + c2 >= OpSizeInBits)
4363 return DAG.getConstant(0, VT);
4364 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4365 DAG.getConstant(c1 + c2, N1.getValueType()));
4369 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4370 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4371 N0.getOperand(0).getOpcode() == ISD::SRL &&
4372 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4374 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4375 uint64_t c2 = N1C->getZExtValue();
4376 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4377 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4378 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4379 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4380 if (c1 + OpSizeInBits == InnerShiftSize) {
4381 if (c1 + c2 >= InnerShiftSize)
4382 return DAG.getConstant(0, VT);
4383 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4384 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4385 N0.getOperand(0)->getOperand(0),
4386 DAG.getConstant(c1 + c2, ShiftCountVT)));
4390 // fold (srl (shl x, c), c) -> (and x, cst2)
4391 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4392 unsigned BitSize = N0.getScalarValueSizeInBits();
4393 if (BitSize <= 64) {
4394 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4395 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4396 DAG.getConstant(~0ULL >> ShAmt, VT));
4400 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4401 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4402 // Shifting in all undef bits?
4403 EVT SmallVT = N0.getOperand(0).getValueType();
4404 unsigned BitSize = SmallVT.getScalarSizeInBits();
4405 if (N1C->getZExtValue() >= BitSize)
4406 return DAG.getUNDEF(VT);
4408 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4409 uint64_t ShiftAmt = N1C->getZExtValue();
4410 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4412 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4413 AddToWorklist(SmallShift.getNode());
4414 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4415 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4416 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4417 DAG.getConstant(Mask, VT));
4421 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4422 // bit, which is unmodified by sra.
4423 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4424 if (N0.getOpcode() == ISD::SRA)
4425 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4428 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4429 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4430 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4431 APInt KnownZero, KnownOne;
4432 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4434 // If any of the input bits are KnownOne, then the input couldn't be all
4435 // zeros, thus the result of the srl will always be zero.
4436 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4438 // If all of the bits input the to ctlz node are known to be zero, then
4439 // the result of the ctlz is "32" and the result of the shift is one.
4440 APInt UnknownBits = ~KnownZero;
4441 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4443 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4444 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4445 // Okay, we know that only that the single bit specified by UnknownBits
4446 // could be set on input to the CTLZ node. If this bit is set, the SRL
4447 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4448 // to an SRL/XOR pair, which is likely to simplify more.
4449 unsigned ShAmt = UnknownBits.countTrailingZeros();
4450 SDValue Op = N0.getOperand(0);
4453 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4454 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4455 AddToWorklist(Op.getNode());
4458 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4459 Op, DAG.getConstant(1, VT));
4463 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4464 if (N1.getOpcode() == ISD::TRUNCATE &&
4465 N1.getOperand(0).getOpcode() == ISD::AND) {
4466 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4467 if (NewOp1.getNode())
4468 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4471 // fold operands of srl based on knowledge that the low bits are not
4473 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4474 return SDValue(N, 0);
4477 SDValue NewSRL = visitShiftByConstant(N, N1C);
4478 if (NewSRL.getNode())
4482 // Attempt to convert a srl of a load into a narrower zero-extending load.
4483 SDValue NarrowLoad = ReduceLoadWidth(N);
4484 if (NarrowLoad.getNode())
4487 // Here is a common situation. We want to optimize:
4490 // %b = and i32 %a, 2
4491 // %c = srl i32 %b, 1
4492 // brcond i32 %c ...
4498 // %c = setcc eq %b, 0
4501 // However when after the source operand of SRL is optimized into AND, the SRL
4502 // itself may not be optimized further. Look for it and add the BRCOND into
4504 if (N->hasOneUse()) {
4505 SDNode *Use = *N->use_begin();
4506 if (Use->getOpcode() == ISD::BRCOND)
4508 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4509 // Also look pass the truncate.
4510 Use = *Use->use_begin();
4511 if (Use->getOpcode() == ISD::BRCOND)
4519 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4520 SDValue N0 = N->getOperand(0);
4521 EVT VT = N->getValueType(0);
4523 // fold (ctlz c1) -> c2
4524 if (isa<ConstantSDNode>(N0))
4525 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4529 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4530 SDValue N0 = N->getOperand(0);
4531 EVT VT = N->getValueType(0);
4533 // fold (ctlz_zero_undef c1) -> c2
4534 if (isa<ConstantSDNode>(N0))
4535 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4539 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4540 SDValue N0 = N->getOperand(0);
4541 EVT VT = N->getValueType(0);
4543 // fold (cttz c1) -> c2
4544 if (isa<ConstantSDNode>(N0))
4545 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4549 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4550 SDValue N0 = N->getOperand(0);
4551 EVT VT = N->getValueType(0);
4553 // fold (cttz_zero_undef c1) -> c2
4554 if (isa<ConstantSDNode>(N0))
4555 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4559 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4560 SDValue N0 = N->getOperand(0);
4561 EVT VT = N->getValueType(0);
4563 // fold (ctpop c1) -> c2
4564 if (isa<ConstantSDNode>(N0))
4565 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4569 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4570 SDValue N0 = N->getOperand(0);
4571 SDValue N1 = N->getOperand(1);
4572 SDValue N2 = N->getOperand(2);
4573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4575 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4576 EVT VT = N->getValueType(0);
4577 EVT VT0 = N0.getValueType();
4579 // fold (select C, X, X) -> X
4582 // fold (select true, X, Y) -> X
4583 if (N0C && !N0C->isNullValue())
4585 // fold (select false, X, Y) -> Y
4586 if (N0C && N0C->isNullValue())
4588 // fold (select C, 1, X) -> (or C, X)
4589 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4590 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4591 // fold (select C, 0, 1) -> (xor C, 1)
4592 // We can't do this reliably if integer based booleans have different contents
4593 // to floating point based booleans. This is because we can't tell whether we
4594 // have an integer-based boolean or a floating-point-based boolean unless we
4595 // can find the SETCC that produced it and inspect its operands. This is
4596 // fairly easy if C is the SETCC node, but it can potentially be
4597 // undiscoverable (or not reasonably discoverable). For example, it could be
4598 // in another basic block or it could require searching a complicated
4600 if (VT.isInteger() &&
4601 (VT0 == MVT::i1 || (VT0.isInteger() &&
4602 TLI.getBooleanContents(false, false) ==
4603 TLI.getBooleanContents(false, true) &&
4604 TLI.getBooleanContents(false, false) ==
4605 TargetLowering::ZeroOrOneBooleanContent)) &&
4606 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4609 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4610 N0, DAG.getConstant(1, VT0));
4611 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4612 N0, DAG.getConstant(1, VT0));
4613 AddToWorklist(XORNode.getNode());
4615 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4616 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4618 // fold (select C, 0, X) -> (and (not C), X)
4619 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4620 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4621 AddToWorklist(NOTNode.getNode());
4622 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4624 // fold (select C, X, 1) -> (or (not C), X)
4625 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4626 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4627 AddToWorklist(NOTNode.getNode());
4628 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4630 // fold (select C, X, 0) -> (and C, X)
4631 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4632 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4633 // fold (select X, X, Y) -> (or X, Y)
4634 // fold (select X, 1, Y) -> (or X, Y)
4635 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4637 // fold (select X, Y, X) -> (and X, Y)
4638 // fold (select X, Y, 0) -> (and X, Y)
4639 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4640 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4642 // If we can fold this based on the true/false value, do so.
4643 if (SimplifySelectOps(N, N1, N2))
4644 return SDValue(N, 0); // Don't revisit N.
4646 // fold selects based on a setcc into other things, such as min/max/abs
4647 if (N0.getOpcode() == ISD::SETCC) {
4648 if ((!LegalOperations &&
4649 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4650 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4651 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4652 N0.getOperand(0), N0.getOperand(1),
4653 N1, N2, N0.getOperand(2));
4654 return SimplifySelect(SDLoc(N), N0, N1, N2);
4661 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4664 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4666 // Split the inputs.
4667 SDValue Lo, Hi, LL, LH, RL, RH;
4668 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4669 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4671 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4672 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4674 return std::make_pair(Lo, Hi);
4677 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4678 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4679 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4681 SDValue Cond = N->getOperand(0);
4682 SDValue LHS = N->getOperand(1);
4683 SDValue RHS = N->getOperand(2);
4684 EVT VT = N->getValueType(0);
4685 int NumElems = VT.getVectorNumElements();
4686 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4687 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4688 Cond.getOpcode() == ISD::BUILD_VECTOR);
4690 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4691 // binary ones here.
4692 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4695 // We're sure we have an even number of elements due to the
4696 // concat_vectors we have as arguments to vselect.
4697 // Skip BV elements until we find one that's not an UNDEF
4698 // After we find an UNDEF element, keep looping until we get to half the
4699 // length of the BV and see if all the non-undef nodes are the same.
4700 ConstantSDNode *BottomHalf = nullptr;
4701 for (int i = 0; i < NumElems / 2; ++i) {
4702 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4705 if (BottomHalf == nullptr)
4706 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4707 else if (Cond->getOperand(i).getNode() != BottomHalf)
4711 // Do the same for the second half of the BuildVector
4712 ConstantSDNode *TopHalf = nullptr;
4713 for (int i = NumElems / 2; i < NumElems; ++i) {
4714 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4717 if (TopHalf == nullptr)
4718 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4719 else if (Cond->getOperand(i).getNode() != TopHalf)
4723 assert(TopHalf && BottomHalf &&
4724 "One half of the selector was all UNDEFs and the other was all the "
4725 "same value. This should have been addressed before this function.");
4727 ISD::CONCAT_VECTORS, dl, VT,
4728 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4729 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4732 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4733 SDValue N0 = N->getOperand(0);
4734 SDValue N1 = N->getOperand(1);
4735 SDValue N2 = N->getOperand(2);
4738 // Canonicalize integer abs.
4739 // vselect (setg[te] X, 0), X, -X ->
4740 // vselect (setgt X, -1), X, -X ->
4741 // vselect (setl[te] X, 0), -X, X ->
4742 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4743 if (N0.getOpcode() == ISD::SETCC) {
4744 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4745 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4747 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4749 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4750 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4751 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4752 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4753 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4754 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4755 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4758 EVT VT = LHS.getValueType();
4759 SDValue Shift = DAG.getNode(
4760 ISD::SRA, DL, VT, LHS,
4761 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4762 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4763 AddToWorklist(Shift.getNode());
4764 AddToWorklist(Add.getNode());
4765 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769 // If the VSELECT result requires splitting and the mask is provided by a
4770 // SETCC, then split both nodes and its operands before legalization. This
4771 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4772 // and enables future optimizations (e.g. min/max pattern matching on X86).
4773 if (N0.getOpcode() == ISD::SETCC) {
4774 EVT VT = N->getValueType(0);
4776 // Check if any splitting is required.
4777 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4778 TargetLowering::TypeSplitVector)
4781 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4782 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4783 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4784 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4786 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4787 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4789 // Add the new VSELECT nodes to the work list in case they need to be split
4791 AddToWorklist(Lo.getNode());
4792 AddToWorklist(Hi.getNode());
4794 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4797 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4798 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4800 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4801 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4804 // The ConvertSelectToConcatVector function is assuming both the above
4805 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4807 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4808 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4809 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4810 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4818 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4819 SDValue N0 = N->getOperand(0);
4820 SDValue N1 = N->getOperand(1);
4821 SDValue N2 = N->getOperand(2);
4822 SDValue N3 = N->getOperand(3);
4823 SDValue N4 = N->getOperand(4);
4824 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4826 // fold select_cc lhs, rhs, x, x, cc -> x
4830 // Determine if the condition we're dealing with is constant
4831 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4832 N0, N1, CC, SDLoc(N), false);
4833 if (SCC.getNode()) {
4834 AddToWorklist(SCC.getNode());
4836 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4837 if (!SCCC->isNullValue())
4838 return N2; // cond always true -> true val
4840 return N3; // cond always false -> false val
4843 // Fold to a simpler select_cc
4844 if (SCC.getOpcode() == ISD::SETCC)
4845 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4846 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850 // If we can fold this based on the true/false value, do so.
4851 if (SimplifySelectOps(N, N2, N3))
4852 return SDValue(N, 0); // Don't revisit N.
4854 // fold select_cc into other things, such as min/max/abs
4855 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4858 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4859 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4860 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4864 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4865 // dag node into a ConstantSDNode or a build_vector of constants.
4866 // This function is called by the DAGCombiner when visiting sext/zext/aext
4867 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4868 // Vector extends are not folded if operations are legal; this is to
4869 // avoid introducing illegal build_vector dag nodes.
4870 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4871 SelectionDAG &DAG, bool LegalTypes,
4872 bool LegalOperations) {
4873 unsigned Opcode = N->getOpcode();
4874 SDValue N0 = N->getOperand(0);
4875 EVT VT = N->getValueType(0);
4877 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4878 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4880 // fold (sext c1) -> c1
4881 // fold (zext c1) -> c1
4882 // fold (aext c1) -> c1
4883 if (isa<ConstantSDNode>(N0))
4884 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4886 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4887 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4888 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4889 EVT SVT = VT.getScalarType();
4890 if (!(VT.isVector() &&
4891 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4892 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4895 // We can fold this node into a build_vector.
4896 unsigned VTBits = SVT.getSizeInBits();
4897 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4898 unsigned ShAmt = VTBits - EVTBits;
4899 SmallVector<SDValue, 8> Elts;
4900 unsigned NumElts = N0->getNumOperands();
4903 for (unsigned i=0; i != NumElts; ++i) {
4904 SDValue Op = N0->getOperand(i);
4905 if (Op->getOpcode() == ISD::UNDEF) {
4906 Elts.push_back(DAG.getUNDEF(SVT));
4910 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4911 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4912 if (Opcode == ISD::SIGN_EXTEND)
4913 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4916 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4920 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4923 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4924 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4925 // transformation. Returns true if extension are possible and the above
4926 // mentioned transformation is profitable.
4927 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4929 SmallVectorImpl<SDNode *> &ExtendNodes,
4930 const TargetLowering &TLI) {
4931 bool HasCopyToRegUses = false;
4932 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4933 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4934 UE = N0.getNode()->use_end();
4939 if (UI.getUse().getResNo() != N0.getResNo())
4941 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4942 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4943 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4944 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4945 // Sign bits will be lost after a zext.
4948 for (unsigned i = 0; i != 2; ++i) {
4949 SDValue UseOp = User->getOperand(i);
4952 if (!isa<ConstantSDNode>(UseOp))
4957 ExtendNodes.push_back(User);
4960 // If truncates aren't free and there are users we can't
4961 // extend, it isn't worthwhile.
4964 // Remember if this value is live-out.
4965 if (User->getOpcode() == ISD::CopyToReg)
4966 HasCopyToRegUses = true;
4969 if (HasCopyToRegUses) {
4970 bool BothLiveOut = false;
4971 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4973 SDUse &Use = UI.getUse();
4974 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4980 // Both unextended and extended values are live out. There had better be
4981 // a good reason for the transformation.
4982 return ExtendNodes.size();
4987 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4988 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4989 ISD::NodeType ExtType) {
4990 // Extend SetCC uses if necessary.
4991 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4992 SDNode *SetCC = SetCCs[i];
4993 SmallVector<SDValue, 4> Ops;
4995 for (unsigned j = 0; j != 2; ++j) {
4996 SDValue SOp = SetCC->getOperand(j);
4998 Ops.push_back(ExtLoad);
5000 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5003 Ops.push_back(SetCC->getOperand(2));
5004 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5008 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5009 SDValue N0 = N->getOperand(0);
5010 EVT VT = N->getValueType(0);
5012 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5014 return SDValue(Res, 0);
5016 // fold (sext (sext x)) -> (sext x)
5017 // fold (sext (aext x)) -> (sext x)
5018 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5019 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5022 if (N0.getOpcode() == ISD::TRUNCATE) {
5023 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5024 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5025 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5026 if (NarrowLoad.getNode()) {
5027 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5028 if (NarrowLoad.getNode() != N0.getNode()) {
5029 CombineTo(N0.getNode(), NarrowLoad);
5030 // CombineTo deleted the truncate, if needed, but not what's under it.
5033 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5036 // See if the value being truncated is already sign extended. If so, just
5037 // eliminate the trunc/sext pair.
5038 SDValue Op = N0.getOperand(0);
5039 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5040 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5041 unsigned DestBits = VT.getScalarType().getSizeInBits();
5042 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5044 if (OpBits == DestBits) {
5045 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5046 // bits, it is already ready.
5047 if (NumSignBits > DestBits-MidBits)
5049 } else if (OpBits < DestBits) {
5050 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5051 // bits, just sext from i32.
5052 if (NumSignBits > OpBits-MidBits)
5053 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5055 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5056 // bits, just truncate to i32.
5057 if (NumSignBits > OpBits-MidBits)
5058 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5061 // fold (sext (truncate x)) -> (sextinreg x).
5062 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5063 N0.getValueType())) {
5064 if (OpBits < DestBits)
5065 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5066 else if (OpBits > DestBits)
5067 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5068 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5069 DAG.getValueType(N0.getValueType()));
5073 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5074 // None of the supported targets knows how to perform load and sign extend
5075 // on vectors in one instruction. We only perform this transformation on
5077 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5078 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5079 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5080 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5081 bool DoXform = true;
5082 SmallVector<SDNode*, 4> SetCCs;
5083 if (!N0.hasOneUse())
5084 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5087 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5089 LN0->getBasePtr(), N0.getValueType(),
5090 LN0->getMemOperand());
5091 CombineTo(N, ExtLoad);
5092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5093 N0.getValueType(), ExtLoad);
5094 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5095 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5097 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5101 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5102 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5103 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5104 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5105 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5106 EVT MemVT = LN0->getMemoryVT();
5107 if ((!LegalOperations && !LN0->isVolatile()) ||
5108 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5109 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5111 LN0->getBasePtr(), MemVT,
5112 LN0->getMemOperand());
5113 CombineTo(N, ExtLoad);
5114 CombineTo(N0.getNode(),
5115 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5116 N0.getValueType(), ExtLoad),
5117 ExtLoad.getValue(1));
5118 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5122 // fold (sext (and/or/xor (load x), cst)) ->
5123 // (and/or/xor (sextload x), (sext cst))
5124 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5125 N0.getOpcode() == ISD::XOR) &&
5126 isa<LoadSDNode>(N0.getOperand(0)) &&
5127 N0.getOperand(1).getOpcode() == ISD::Constant &&
5128 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5129 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5130 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5131 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5132 bool DoXform = true;
5133 SmallVector<SDNode*, 4> SetCCs;
5134 if (!N0.hasOneUse())
5135 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5138 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5139 LN0->getChain(), LN0->getBasePtr(),
5141 LN0->getMemOperand());
5142 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5143 Mask = Mask.sext(VT.getSizeInBits());
5144 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5145 ExtLoad, DAG.getConstant(Mask, VT));
5146 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5147 SDLoc(N0.getOperand(0)),
5148 N0.getOperand(0).getValueType(), ExtLoad);
5150 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5151 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5158 if (N0.getOpcode() == ISD::SETCC) {
5159 EVT N0VT = N0.getOperand(0).getValueType();
5160 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5161 // Only do this before legalize for now.
5162 if (VT.isVector() && !LegalOperations &&
5163 TLI.getBooleanContents(N0VT) ==
5164 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5165 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5166 // of the same size as the compared operands. Only optimize sext(setcc())
5167 // if this is the case.
5168 EVT SVT = getSetCCResultType(N0VT);
5170 // We know that the # elements of the results is the same as the
5171 // # elements of the compare (and the # elements of the compare result
5172 // for that matter). Check to see that they are the same size. If so,
5173 // we know that the element size of the sext'd result matches the
5174 // element size of the compare operands.
5175 if (VT.getSizeInBits() == SVT.getSizeInBits())
5176 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5178 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5180 // If the desired elements are smaller or larger than the source
5181 // elements we can use a matching integer vector type and then
5182 // truncate/sign extend
5183 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5184 if (SVT == MatchingVectorType) {
5185 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5186 N0.getOperand(0), N0.getOperand(1),
5187 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5188 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5192 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5193 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5195 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5197 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5198 NegOne, DAG.getConstant(0, VT),
5199 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5200 if (SCC.getNode()) return SCC;
5202 if (!VT.isVector()) {
5203 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5204 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5206 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5207 SDValue SetCC = DAG.getSetCC(DL,
5209 N0.getOperand(0), N0.getOperand(1), CC);
5210 EVT SelectVT = getSetCCResultType(VT);
5211 return DAG.getSelect(DL, VT,
5212 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5213 NegOne, DAG.getConstant(0, VT));
5219 // fold (sext x) -> (zext x) if the sign bit is known zero.
5220 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5221 DAG.SignBitIsZero(N0))
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5227 // isTruncateOf - If N is a truncate of some other value, return true, record
5228 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5229 // This function computes KnownZero to avoid a duplicated call to
5230 // computeKnownBits in the caller.
5231 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5234 if (N->getOpcode() == ISD::TRUNCATE) {
5235 Op = N->getOperand(0);
5236 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5241 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5244 SDValue Op0 = N->getOperand(0);
5245 SDValue Op1 = N->getOperand(1);
5246 assert(Op0.getValueType() == Op1.getValueType());
5248 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5249 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5250 if (COp0 && COp0->isNullValue())
5252 else if (COp1 && COp1->isNullValue())
5257 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5259 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5265 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5266 SDValue N0 = N->getOperand(0);
5267 EVT VT = N->getValueType(0);
5269 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5271 return SDValue(Res, 0);
5273 // fold (zext (zext x)) -> (zext x)
5274 // fold (zext (aext x)) -> (zext x)
5275 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5276 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5279 // fold (zext (truncate x)) -> (zext x) or
5280 // (zext (truncate x)) -> (truncate x)
5281 // This is valid when the truncated bits of x are already zero.
5282 // FIXME: We should extend this to work for vectors too.
5285 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5286 APInt TruncatedBits =
5287 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5288 APInt(Op.getValueSizeInBits(), 0) :
5289 APInt::getBitsSet(Op.getValueSizeInBits(),
5290 N0.getValueSizeInBits(),
5291 std::min(Op.getValueSizeInBits(),
5292 VT.getSizeInBits()));
5293 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5294 if (VT.bitsGT(Op.getValueType()))
5295 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5296 if (VT.bitsLT(Op.getValueType()))
5297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5303 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5304 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5305 if (N0.getOpcode() == ISD::TRUNCATE) {
5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5307 if (NarrowLoad.getNode()) {
5308 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5309 if (NarrowLoad.getNode() != N0.getNode()) {
5310 CombineTo(N0.getNode(), NarrowLoad);
5311 // CombineTo deleted the truncate, if needed, but not what's under it.
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5318 // fold (zext (truncate x)) -> (and x, mask)
5319 if (N0.getOpcode() == ISD::TRUNCATE &&
5320 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5322 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5323 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5324 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5325 if (NarrowLoad.getNode()) {
5326 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5327 if (NarrowLoad.getNode() != N0.getNode()) {
5328 CombineTo(N0.getNode(), NarrowLoad);
5329 // CombineTo deleted the truncate, if needed, but not what's under it.
5332 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5335 SDValue Op = N0.getOperand(0);
5336 if (Op.getValueType().bitsLT(VT)) {
5337 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5338 AddToWorklist(Op.getNode());
5339 } else if (Op.getValueType().bitsGT(VT)) {
5340 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5341 AddToWorklist(Op.getNode());
5343 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5344 N0.getValueType().getScalarType());
5347 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5348 // if either of the casts is not free.
5349 if (N0.getOpcode() == ISD::AND &&
5350 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5351 N0.getOperand(1).getOpcode() == ISD::Constant &&
5352 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5353 N0.getValueType()) ||
5354 !TLI.isZExtFree(N0.getValueType(), VT))) {
5355 SDValue X = N0.getOperand(0).getOperand(0);
5356 if (X.getValueType().bitsLT(VT)) {
5357 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5358 } else if (X.getValueType().bitsGT(VT)) {
5359 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5361 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5362 Mask = Mask.zext(VT.getSizeInBits());
5363 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5364 X, DAG.getConstant(Mask, VT));
5367 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5368 // None of the supported targets knows how to perform load and vector_zext
5369 // on vectors in one instruction. We only perform this transformation on
5371 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5372 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5373 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5375 bool DoXform = true;
5376 SmallVector<SDNode*, 4> SetCCs;
5377 if (!N0.hasOneUse())
5378 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5380 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5381 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5383 LN0->getBasePtr(), N0.getValueType(),
5384 LN0->getMemOperand());
5385 CombineTo(N, ExtLoad);
5386 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5387 N0.getValueType(), ExtLoad);
5388 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5390 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5392 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5396 // fold (zext (and/or/xor (load x), cst)) ->
5397 // (and/or/xor (zextload x), (zext cst))
5398 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5399 N0.getOpcode() == ISD::XOR) &&
5400 isa<LoadSDNode>(N0.getOperand(0)) &&
5401 N0.getOperand(1).getOpcode() == ISD::Constant &&
5402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5403 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5404 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5405 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5406 bool DoXform = true;
5407 SmallVector<SDNode*, 4> SetCCs;
5408 if (!N0.hasOneUse())
5409 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5413 LN0->getChain(), LN0->getBasePtr(),
5415 LN0->getMemOperand());
5416 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5417 Mask = Mask.zext(VT.getSizeInBits());
5418 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5419 ExtLoad, DAG.getConstant(Mask, VT));
5420 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5421 SDLoc(N0.getOperand(0)),
5422 N0.getOperand(0).getValueType(), ExtLoad);
5424 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5432 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5433 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5434 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5435 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5436 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5437 EVT MemVT = LN0->getMemoryVT();
5438 if ((!LegalOperations && !LN0->isVolatile()) ||
5439 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5440 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5442 LN0->getBasePtr(), MemVT,
5443 LN0->getMemOperand());
5444 CombineTo(N, ExtLoad);
5445 CombineTo(N0.getNode(),
5446 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5448 ExtLoad.getValue(1));
5449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5453 if (N0.getOpcode() == ISD::SETCC) {
5454 if (!LegalOperations && VT.isVector() &&
5455 N0.getValueType().getVectorElementType() == MVT::i1) {
5456 EVT N0VT = N0.getOperand(0).getValueType();
5457 if (getSetCCResultType(N0VT) == N0.getValueType())
5460 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5461 // Only do this before legalize for now.
5462 EVT EltVT = VT.getVectorElementType();
5463 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5464 DAG.getConstant(1, EltVT));
5465 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5466 // We know that the # elements of the results is the same as the
5467 // # elements of the compare (and the # elements of the compare result
5468 // for that matter). Check to see that they are the same size. If so,
5469 // we know that the element size of the sext'd result matches the
5470 // element size of the compare operands.
5471 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5472 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5474 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5478 // If the desired elements are smaller or larger than the source
5479 // elements we can use a matching integer vector type and then
5480 // truncate/sign extend
5481 EVT MatchingElementType =
5482 EVT::getIntegerVT(*DAG.getContext(),
5483 N0VT.getScalarType().getSizeInBits());
5484 EVT MatchingVectorType =
5485 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5486 N0VT.getVectorNumElements());
5488 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5490 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5491 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5492 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5493 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5496 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5498 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5499 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5500 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5501 if (SCC.getNode()) return SCC;
5504 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5505 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5506 isa<ConstantSDNode>(N0.getOperand(1)) &&
5507 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5509 SDValue ShAmt = N0.getOperand(1);
5510 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5511 if (N0.getOpcode() == ISD::SHL) {
5512 SDValue InnerZExt = N0.getOperand(0);
5513 // If the original shl may be shifting out bits, do not perform this
5515 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5516 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5517 if (ShAmtVal > KnownZeroBits)
5523 // Ensure that the shift amount is wide enough for the shifted value.
5524 if (VT.getSizeInBits() >= 256)
5525 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5527 return DAG.getNode(N0.getOpcode(), DL, VT,
5528 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5535 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5536 SDValue N0 = N->getOperand(0);
5537 EVT VT = N->getValueType(0);
5539 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5541 return SDValue(Res, 0);
5543 // fold (aext (aext x)) -> (aext x)
5544 // fold (aext (zext x)) -> (zext x)
5545 // fold (aext (sext x)) -> (sext x)
5546 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5547 N0.getOpcode() == ISD::ZERO_EXTEND ||
5548 N0.getOpcode() == ISD::SIGN_EXTEND)
5549 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5551 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5552 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5553 if (N0.getOpcode() == ISD::TRUNCATE) {
5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
5556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
5558 CombineTo(N0.getNode(), NarrowLoad);
5559 // CombineTo deleted the truncate, if needed, but not what's under it.
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5566 // fold (aext (truncate x))
5567 if (N0.getOpcode() == ISD::TRUNCATE) {
5568 SDValue TruncOp = N0.getOperand(0);
5569 if (TruncOp.getValueType() == VT)
5570 return TruncOp; // x iff x size == zext size.
5571 if (TruncOp.getValueType().bitsGT(VT))
5572 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5573 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5576 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5577 // if the trunc is not free.
5578 if (N0.getOpcode() == ISD::AND &&
5579 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5580 N0.getOperand(1).getOpcode() == ISD::Constant &&
5581 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5582 N0.getValueType())) {
5583 SDValue X = N0.getOperand(0).getOperand(0);
5584 if (X.getValueType().bitsLT(VT)) {
5585 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5586 } else if (X.getValueType().bitsGT(VT)) {
5587 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5589 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5590 Mask = Mask.zext(VT.getSizeInBits());
5591 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5592 X, DAG.getConstant(Mask, VT));
5595 // fold (aext (load x)) -> (aext (truncate (extload x)))
5596 // None of the supported targets knows how to perform load and any_ext
5597 // on vectors in one instruction. We only perform this transformation on
5599 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5600 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5601 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5602 bool DoXform = true;
5603 SmallVector<SDNode*, 4> SetCCs;
5604 if (!N0.hasOneUse())
5605 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5607 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5608 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5610 LN0->getBasePtr(), N0.getValueType(),
5611 LN0->getMemOperand());
5612 CombineTo(N, ExtLoad);
5613 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5614 N0.getValueType(), ExtLoad);
5615 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5616 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5618 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5623 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5624 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5625 if (N0.getOpcode() == ISD::LOAD &&
5626 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5628 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5629 ISD::LoadExtType ExtType = LN0->getExtensionType();
5630 EVT MemVT = LN0->getMemoryVT();
5631 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5632 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5633 VT, LN0->getChain(), LN0->getBasePtr(),
5634 MemVT, LN0->getMemOperand());
5635 CombineTo(N, ExtLoad);
5636 CombineTo(N0.getNode(),
5637 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5638 N0.getValueType(), ExtLoad),
5639 ExtLoad.getValue(1));
5640 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5644 if (N0.getOpcode() == ISD::SETCC) {
5646 // aext(setcc) -> vsetcc
5647 // aext(setcc) -> truncate(vsetcc)
5648 // aext(setcc) -> aext(vsetcc)
5649 // Only do this before legalize for now.
5650 if (VT.isVector() && !LegalOperations) {
5651 EVT N0VT = N0.getOperand(0).getValueType();
5652 // We know that the # elements of the results is the same as the
5653 // # elements of the compare (and the # elements of the compare result
5654 // for that matter). Check to see that they are the same size. If so,
5655 // we know that the element size of the sext'd result matches the
5656 // element size of the compare operands.
5657 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5658 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5660 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5661 // If the desired elements are smaller or larger than the source
5662 // elements we can use a matching integer vector type and then
5663 // truncate/any extend
5665 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5667 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5669 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5670 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5676 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5677 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5678 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5686 /// See if the specified operand can be simplified with the knowledge that only
5687 /// the bits specified by Mask are used. If so, return the simpler operand,
5688 /// otherwise return a null SDValue.
5689 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5690 switch (V.getOpcode()) {
5692 case ISD::Constant: {
5693 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5694 assert(CV && "Const value should be ConstSDNode.");
5695 const APInt &CVal = CV->getAPIntValue();
5696 APInt NewVal = CVal & Mask;
5698 return DAG.getConstant(NewVal, V.getValueType());
5703 // If the LHS or RHS don't contribute bits to the or, drop them.
5704 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5705 return V.getOperand(1);
5706 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5707 return V.getOperand(0);
5710 // Only look at single-use SRLs.
5711 if (!V.getNode()->hasOneUse())
5713 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5714 // See if we can recursively simplify the LHS.
5715 unsigned Amt = RHSC->getZExtValue();
5717 // Watch out for shift count overflow though.
5718 if (Amt >= Mask.getBitWidth()) break;
5719 APInt NewMask = Mask << Amt;
5720 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5721 if (SimplifyLHS.getNode())
5722 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5723 SimplifyLHS, V.getOperand(1));
5729 /// If the result of a wider load is shifted to right of N bits and then
5730 /// truncated to a narrower type and where N is a multiple of number of bits of
5731 /// the narrower type, transform it to a narrower load from address + N / num of
5732 /// bits of new type. If the result is to be extended, also fold the extension
5733 /// to form a extending load.
5734 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5735 unsigned Opc = N->getOpcode();
5737 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5738 SDValue N0 = N->getOperand(0);
5739 EVT VT = N->getValueType(0);
5742 // This transformation isn't valid for vector loads.
5746 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5748 if (Opc == ISD::SIGN_EXTEND_INREG) {
5749 ExtType = ISD::SEXTLOAD;
5750 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5751 } else if (Opc == ISD::SRL) {
5752 // Another special-case: SRL is basically zero-extending a narrower value.
5753 ExtType = ISD::ZEXTLOAD;
5755 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5756 if (!N01) return SDValue();
5757 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5758 VT.getSizeInBits() - N01->getZExtValue());
5760 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5763 unsigned EVTBits = ExtVT.getSizeInBits();
5765 // Do not generate loads of non-round integer types since these can
5766 // be expensive (and would be wrong if the type is not byte sized).
5767 if (!ExtVT.isRound())
5771 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5772 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5773 ShAmt = N01->getZExtValue();
5774 // Is the shift amount a multiple of size of VT?
5775 if ((ShAmt & (EVTBits-1)) == 0) {
5776 N0 = N0.getOperand(0);
5777 // Is the load width a multiple of size of VT?
5778 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782 // At this point, we must have a load or else we can't do the transform.
5783 if (!isa<LoadSDNode>(N0)) return SDValue();
5785 // Because a SRL must be assumed to *need* to zero-extend the high bits
5786 // (as opposed to anyext the high bits), we can't combine the zextload
5787 // lowering of SRL and an sextload.
5788 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5791 // If the shift amount is larger than the input type then we're not
5792 // accessing any of the loaded bytes. If the load was a zextload/extload
5793 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5794 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5799 // If the load is shifted left (and the result isn't shifted back right),
5800 // we can fold the truncate through the shift.
5801 unsigned ShLeftAmt = 0;
5802 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5803 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5804 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5805 ShLeftAmt = N01->getZExtValue();
5806 N0 = N0.getOperand(0);
5810 // If we haven't found a load, we can't narrow it. Don't transform one with
5811 // multiple uses, this would require adding a new load.
5812 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5815 // Don't change the width of a volatile load.
5816 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5817 if (LN0->isVolatile())
5820 // Verify that we are actually reducing a load width here.
5821 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5824 // For the transform to be legal, the load must produce only two values
5825 // (the value loaded and the chain). Don't transform a pre-increment
5826 // load, for example, which produces an extra value. Otherwise the
5827 // transformation is not equivalent, and the downstream logic to replace
5828 // uses gets things wrong.
5829 if (LN0->getNumValues() > 2)
5832 // If the load that we're shrinking is an extload and we're not just
5833 // discarding the extension we can't simply shrink the load. Bail.
5834 // TODO: It would be possible to merge the extensions in some cases.
5835 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5836 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5839 EVT PtrType = N0.getOperand(1).getValueType();
5841 if (PtrType == MVT::Untyped || PtrType.isExtended())
5842 // It's not possible to generate a constant of extended or untyped type.
5845 // For big endian targets, we need to adjust the offset to the pointer to
5846 // load the correct bytes.
5847 if (TLI.isBigEndian()) {
5848 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5849 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5850 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5853 uint64_t PtrOff = ShAmt / 8;
5854 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5855 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5856 PtrType, LN0->getBasePtr(),
5857 DAG.getConstant(PtrOff, PtrType));
5858 AddToWorklist(NewPtr.getNode());
5861 if (ExtType == ISD::NON_EXTLOAD)
5862 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5863 LN0->getPointerInfo().getWithOffset(PtrOff),
5864 LN0->isVolatile(), LN0->isNonTemporal(),
5865 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5867 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5868 LN0->getPointerInfo().getWithOffset(PtrOff),
5869 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5870 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5872 // Replace the old load's chain with the new load's chain.
5873 WorklistRemover DeadNodes(*this);
5874 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5876 // Shift the result left, if we've swallowed a left shift.
5877 SDValue Result = Load;
5878 if (ShLeftAmt != 0) {
5879 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5880 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5882 // If the shift amount is as large as the result size (but, presumably,
5883 // no larger than the source) then the useful bits of the result are
5884 // zero; we can't simply return the shortened shift, because the result
5885 // of that operation is undefined.
5886 if (ShLeftAmt >= VT.getSizeInBits())
5887 Result = DAG.getConstant(0, VT);
5889 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5890 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5893 // Return the new loaded value.
5897 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5898 SDValue N0 = N->getOperand(0);
5899 SDValue N1 = N->getOperand(1);
5900 EVT VT = N->getValueType(0);
5901 EVT EVT = cast<VTSDNode>(N1)->getVT();
5902 unsigned VTBits = VT.getScalarType().getSizeInBits();
5903 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5905 // fold (sext_in_reg c1) -> c1
5906 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5907 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5909 // If the input is already sign extended, just drop the extension.
5910 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5913 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5914 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5915 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5917 N0.getOperand(0), N1);
5919 // fold (sext_in_reg (sext x)) -> (sext x)
5920 // fold (sext_in_reg (aext x)) -> (sext x)
5921 // if x is small enough.
5922 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5923 SDValue N00 = N0.getOperand(0);
5924 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5925 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5926 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5929 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5930 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5931 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5933 // fold operands of sext_in_reg based on knowledge that the top bits are not
5935 if (SimplifyDemandedBits(SDValue(N, 0)))
5936 return SDValue(N, 0);
5938 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5939 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5940 SDValue NarrowLoad = ReduceLoadWidth(N);
5941 if (NarrowLoad.getNode())
5944 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5945 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5946 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5947 if (N0.getOpcode() == ISD::SRL) {
5948 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5949 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5950 // We can turn this into an SRA iff the input to the SRL is already sign
5952 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5953 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5954 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5955 N0.getOperand(0), N0.getOperand(1));
5959 // fold (sext_inreg (extload x)) -> (sextload x)
5960 if (ISD::isEXTLoad(N0.getNode()) &&
5961 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5962 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5963 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5964 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5966 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5968 LN0->getBasePtr(), EVT,
5969 LN0->getMemOperand());
5970 CombineTo(N, ExtLoad);
5971 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5972 AddToWorklist(ExtLoad.getNode());
5973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5975 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5976 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5978 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5979 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5980 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5981 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5982 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5984 LN0->getBasePtr(), EVT,
5985 LN0->getMemOperand());
5986 CombineTo(N, ExtLoad);
5987 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5991 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5992 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5993 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5994 N0.getOperand(1), false);
5995 if (BSwap.getNode())
5996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6001 // into a build_vector.
6002 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6003 SmallVector<SDValue, 8> Elts;
6004 unsigned NumElts = N0->getNumOperands();
6005 unsigned ShAmt = VTBits - EVTBits;
6007 for (unsigned i = 0; i != NumElts; ++i) {
6008 SDValue Op = N0->getOperand(i);
6009 if (Op->getOpcode() == ISD::UNDEF) {
6014 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6015 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6016 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6017 Op.getValueType()));
6020 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6026 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6027 SDValue N0 = N->getOperand(0);
6028 EVT VT = N->getValueType(0);
6029 bool isLE = TLI.isLittleEndian();
6032 if (N0.getValueType() == N->getValueType(0))
6034 // fold (truncate c1) -> c1
6035 if (isa<ConstantSDNode>(N0))
6036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6037 // fold (truncate (truncate x)) -> (truncate x)
6038 if (N0.getOpcode() == ISD::TRUNCATE)
6039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6040 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6041 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6042 N0.getOpcode() == ISD::SIGN_EXTEND ||
6043 N0.getOpcode() == ISD::ANY_EXTEND) {
6044 if (N0.getOperand(0).getValueType().bitsLT(VT))
6045 // if the source is smaller than the dest, we still need an extend
6046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6048 if (N0.getOperand(0).getValueType().bitsGT(VT))
6049 // if the source is larger than the dest, than we just need the truncate
6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6051 // if the source and dest are the same type, we can drop both the extend
6052 // and the truncate.
6053 return N0.getOperand(0);
6056 // Fold extract-and-trunc into a narrow extract. For example:
6057 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6058 // i32 y = TRUNCATE(i64 x)
6060 // v16i8 b = BITCAST (v2i64 val)
6061 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6063 // Note: We only run this optimization after type legalization (which often
6064 // creates this pattern) and before operation legalization after which
6065 // we need to be more careful about the vector instructions that we generate.
6066 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6067 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6069 EVT VecTy = N0.getOperand(0).getValueType();
6070 EVT ExTy = N0.getValueType();
6071 EVT TrTy = N->getValueType(0);
6073 unsigned NumElem = VecTy.getVectorNumElements();
6074 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6076 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6077 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6079 SDValue EltNo = N0->getOperand(1);
6080 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6081 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6082 EVT IndexTy = TLI.getVectorIdxTy();
6083 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6085 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6086 NVT, N0.getOperand(0));
6088 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6090 DAG.getConstant(Index, IndexTy));
6094 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6095 if (N0.getOpcode() == ISD::SELECT) {
6096 EVT SrcVT = N0.getValueType();
6097 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6098 TLI.isTruncateFree(SrcVT, VT)) {
6100 SDValue Cond = N0.getOperand(0);
6101 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6102 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6103 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107 // Fold a series of buildvector, bitcast, and truncate if possible.
6109 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6110 // (2xi32 (buildvector x, y)).
6111 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6112 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6113 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6114 N0.getOperand(0).hasOneUse()) {
6116 SDValue BuildVect = N0.getOperand(0);
6117 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6118 EVT TruncVecEltTy = VT.getVectorElementType();
6120 // Check that the element types match.
6121 if (BuildVectEltTy == TruncVecEltTy) {
6122 // Now we only need to compute the offset of the truncated elements.
6123 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6124 unsigned TruncVecNumElts = VT.getVectorNumElements();
6125 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6127 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6128 "Invalid number of elements");
6130 SmallVector<SDValue, 8> Opnds;
6131 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6132 Opnds.push_back(BuildVect.getOperand(i));
6134 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138 // See if we can simplify the input to this truncate through knowledge that
6139 // only the low bits are being used.
6140 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6141 // Currently we only perform this optimization on scalars because vectors
6142 // may have different active low bits.
6143 if (!VT.isVector()) {
6145 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6146 VT.getSizeInBits()));
6147 if (Shorter.getNode())
6148 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6150 // fold (truncate (load x)) -> (smaller load x)
6151 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6152 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6153 SDValue Reduced = ReduceLoadWidth(N);
6154 if (Reduced.getNode())
6156 // Handle the case where the load remains an extending load even
6157 // after truncation.
6158 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6159 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6160 if (!LN0->isVolatile() &&
6161 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6162 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6163 VT, LN0->getChain(), LN0->getBasePtr(),
6165 LN0->getMemOperand());
6166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6171 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6172 // where ... are all 'undef'.
6173 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6174 SmallVector<EVT, 8> VTs;
6177 unsigned NumDefs = 0;
6179 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6180 SDValue X = N0.getOperand(i);
6181 if (X.getOpcode() != ISD::UNDEF) {
6186 // Stop if more than one members are non-undef.
6189 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6190 VT.getVectorElementType(),
6191 X.getValueType().getVectorNumElements()));
6195 return DAG.getUNDEF(VT);
6198 assert(V.getNode() && "The single defined operand is empty!");
6199 SmallVector<SDValue, 8> Opnds;
6200 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6202 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6205 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6206 AddToWorklist(NV.getNode());
6207 Opnds.push_back(NV);
6209 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213 // Simplify the operands using demanded-bits information.
6214 if (!VT.isVector() &&
6215 SimplifyDemandedBits(SDValue(N, 0)))
6216 return SDValue(N, 0);
6221 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6222 SDValue Elt = N->getOperand(i);
6223 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6224 return Elt.getNode();
6225 return Elt.getOperand(Elt.getResNo()).getNode();
6228 /// build_pair (load, load) -> load
6229 /// if load locations are consecutive.
6230 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6231 assert(N->getOpcode() == ISD::BUILD_PAIR);
6233 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6234 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6235 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6236 LD1->getAddressSpace() != LD2->getAddressSpace())
6238 EVT LD1VT = LD1->getValueType(0);
6240 if (ISD::isNON_EXTLoad(LD2) &&
6242 // If both are volatile this would reduce the number of volatile loads.
6243 // If one is volatile it might be ok, but play conservative and bail out.
6244 !LD1->isVolatile() &&
6245 !LD2->isVolatile() &&
6246 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6247 unsigned Align = LD1->getAlignment();
6248 unsigned NewAlign = TLI.getDataLayout()->
6249 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6251 if (NewAlign <= Align &&
6252 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6253 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6254 LD1->getBasePtr(), LD1->getPointerInfo(),
6255 false, false, false, Align);
6261 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6262 SDValue N0 = N->getOperand(0);
6263 EVT VT = N->getValueType(0);
6265 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6266 // Only do this before legalize, since afterward the target may be depending
6267 // on the bitconvert.
6268 // First check to see if this is all constant.
6270 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6272 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6274 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6275 assert(!DestEltVT.isVector() &&
6276 "Element type of vector ValueType must not be vector!");
6278 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6281 // If the input is a constant, let getNode fold it.
6282 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6283 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6284 if (Res.getNode() != N) {
6285 if (!LegalOperations ||
6286 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6289 // Folding it resulted in an illegal node, and it's too late to
6290 // do that. Clean up the old node and forego the transformation.
6291 // Ideally this won't happen very often, because instcombine
6292 // and the earlier dagcombine runs (where illegal nodes are
6293 // permitted) should have folded most of them already.
6294 deleteAndRecombine(Res.getNode());
6298 // (conv (conv x, t1), t2) -> (conv x, t2)
6299 if (N0.getOpcode() == ISD::BITCAST)
6300 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6303 // fold (conv (load x)) -> (load (conv*)x)
6304 // If the resultant load doesn't need a higher alignment than the original!
6305 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6306 // Do not change the width of a volatile load.
6307 !cast<LoadSDNode>(N0)->isVolatile() &&
6308 // Do not remove the cast if the types differ in endian layout.
6309 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6310 TLI.hasBigEndianPartOrdering(VT) &&
6311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6312 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6314 unsigned Align = TLI.getDataLayout()->
6315 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6316 unsigned OrigAlign = LN0->getAlignment();
6318 if (Align <= OrigAlign) {
6319 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6320 LN0->getBasePtr(), LN0->getPointerInfo(),
6321 LN0->isVolatile(), LN0->isNonTemporal(),
6322 LN0->isInvariant(), OrigAlign,
6324 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6329 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6330 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6331 // This often reduces constant pool loads.
6332 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6333 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6334 N0.getNode()->hasOneUse() && VT.isInteger() &&
6335 !VT.isVector() && !N0.getValueType().isVector()) {
6336 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6338 AddToWorklist(NewConv.getNode());
6340 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6341 if (N0.getOpcode() == ISD::FNEG)
6342 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6343 NewConv, DAG.getConstant(SignBit, VT));
6344 assert(N0.getOpcode() == ISD::FABS);
6345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6346 NewConv, DAG.getConstant(~SignBit, VT));
6349 // fold (bitconvert (fcopysign cst, x)) ->
6350 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6351 // Note that we don't handle (copysign x, cst) because this can always be
6352 // folded to an fneg or fabs.
6353 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6354 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6355 VT.isInteger() && !VT.isVector()) {
6356 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6357 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6358 if (isTypeLegal(IntXVT)) {
6359 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6360 IntXVT, N0.getOperand(1));
6361 AddToWorklist(X.getNode());
6363 // If X has a different width than the result/lhs, sext it or truncate it.
6364 unsigned VTWidth = VT.getSizeInBits();
6365 if (OrigXWidth < VTWidth) {
6366 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6367 AddToWorklist(X.getNode());
6368 } else if (OrigXWidth > VTWidth) {
6369 // To get the sign bit in the right place, we have to shift it right
6370 // before truncating.
6371 X = DAG.getNode(ISD::SRL, SDLoc(X),
6372 X.getValueType(), X,
6373 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6374 AddToWorklist(X.getNode());
6375 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6376 AddToWorklist(X.getNode());
6379 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6380 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6381 X, DAG.getConstant(SignBit, VT));
6382 AddToWorklist(X.getNode());
6384 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6385 VT, N0.getOperand(0));
6386 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6387 Cst, DAG.getConstant(~SignBit, VT));
6388 AddToWorklist(Cst.getNode());
6390 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6395 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6396 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6397 if (CombineLD.getNode())
6404 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6405 EVT VT = N->getValueType(0);
6406 return CombineConsecutiveLoads(N, VT);
6409 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6410 /// operands. DstEltVT indicates the destination element value type.
6411 SDValue DAGCombiner::
6412 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6413 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6415 // If this is already the right type, we're done.
6416 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6418 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6419 unsigned DstBitSize = DstEltVT.getSizeInBits();
6421 // If this is a conversion of N elements of one type to N elements of another
6422 // type, convert each element. This handles FP<->INT cases.
6423 if (SrcBitSize == DstBitSize) {
6424 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6425 BV->getValueType(0).getVectorNumElements());
6427 // Due to the FP element handling below calling this routine recursively,
6428 // we can end up with a scalar-to-vector node here.
6429 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6430 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6431 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6432 DstEltVT, BV->getOperand(0)));
6434 SmallVector<SDValue, 8> Ops;
6435 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6436 SDValue Op = BV->getOperand(i);
6437 // If the vector element type is not legal, the BUILD_VECTOR operands
6438 // are promoted and implicitly truncated. Make that explicit here.
6439 if (Op.getValueType() != SrcEltVT)
6440 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6441 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6443 AddToWorklist(Ops.back().getNode());
6445 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6448 // Otherwise, we're growing or shrinking the elements. To avoid having to
6449 // handle annoying details of growing/shrinking FP values, we convert them to
6451 if (SrcEltVT.isFloatingPoint()) {
6452 // Convert the input float vector to a int vector where the elements are the
6454 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6455 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6456 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6460 // Now we know the input is an integer vector. If the output is a FP type,
6461 // convert to integer first, then to FP of the right size.
6462 if (DstEltVT.isFloatingPoint()) {
6463 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6464 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6465 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6467 // Next, convert to FP elements of the same size.
6468 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6471 // Okay, we know the src/dst types are both integers of differing types.
6472 // Handling growing first.
6473 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6474 if (SrcBitSize < DstBitSize) {
6475 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6477 SmallVector<SDValue, 8> Ops;
6478 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6479 i += NumInputsPerOutput) {
6480 bool isLE = TLI.isLittleEndian();
6481 APInt NewBits = APInt(DstBitSize, 0);
6482 bool EltIsUndef = true;
6483 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6484 // Shift the previously computed bits over.
6485 NewBits <<= SrcBitSize;
6486 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6487 if (Op.getOpcode() == ISD::UNDEF) continue;
6490 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6491 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6495 Ops.push_back(DAG.getUNDEF(DstEltVT));
6497 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6500 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6501 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6504 // Finally, this must be the case where we are shrinking elements: each input
6505 // turns into multiple outputs.
6506 bool isS2V = ISD::isScalarToVector(BV);
6507 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6508 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6509 NumOutputsPerInput*BV->getNumOperands());
6510 SmallVector<SDValue, 8> Ops;
6512 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6513 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6514 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6515 Ops.push_back(DAG.getUNDEF(DstEltVT));
6519 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6520 getAPIntValue().zextOrTrunc(SrcBitSize);
6522 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6523 APInt ThisVal = OpVal.trunc(DstBitSize);
6524 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6525 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6526 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6527 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6529 OpVal = OpVal.lshr(DstBitSize);
6532 // For big endian targets, swap the order of the pieces of each element.
6533 if (TLI.isBigEndian())
6534 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6537 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6540 SDValue DAGCombiner::visitFADD(SDNode *N) {
6541 SDValue N0 = N->getOperand(0);
6542 SDValue N1 = N->getOperand(1);
6543 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6544 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6545 EVT VT = N->getValueType(0);
6546 const TargetOptions &Options = DAG.getTarget().Options;
6549 if (VT.isVector()) {
6550 SDValue FoldedVOp = SimplifyVBinOp(N);
6551 if (FoldedVOp.getNode()) return FoldedVOp;
6554 // fold (fadd c1, c2) -> c1 + c2
6556 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6558 // canonicalize constant to RHS
6559 if (N0CFP && !N1CFP)
6560 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6562 // fold (fadd A, (fneg B)) -> (fsub A, B)
6563 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6564 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6565 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6566 GetNegatedExpression(N1, DAG, LegalOperations));
6568 // fold (fadd (fneg A), B) -> (fsub B, A)
6569 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6570 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6571 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6572 GetNegatedExpression(N0, DAG, LegalOperations));
6574 // If 'unsafe math' is enabled, fold lots of things.
6575 if (Options.UnsafeFPMath) {
6576 // No FP constant should be created after legalization as Instruction
6577 // Selection pass has a hard time dealing with FP constants.
6578 bool AllowNewConst = (Level < AfterLegalizeDAG);
6580 // fold (fadd A, 0) -> A
6581 if (N1CFP && N1CFP->getValueAPF().isZero())
6584 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6585 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6586 isa<ConstantFPSDNode>(N0.getOperand(1)))
6587 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6588 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589 N0.getOperand(1), N1));
6591 // If allowed, fold (fadd (fneg x), x) -> 0.0
6592 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6593 return DAG.getConstantFP(0.0, VT);
6595 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6596 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6597 return DAG.getConstantFP(0.0, VT);
6599 // We can fold chains of FADD's of the same value into multiplications.
6600 // This transform is not safe in general because we are reducing the number
6601 // of rounding steps.
6602 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6603 if (N0.getOpcode() == ISD::FMUL) {
6604 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6605 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6607 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6608 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6609 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6611 DAG.getConstantFP(1.0, VT));
6612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6617 N1.getOperand(0) == N1.getOperand(1) &&
6618 N0.getOperand(0) == N1.getOperand(0)) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(2.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623 N0.getOperand(0), NewCFP);
6627 if (N1.getOpcode() == ISD::FMUL) {
6628 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6629 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6631 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6632 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635 DAG.getConstantFP(1.0, VT));
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6639 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6640 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6641 N0.getOperand(0) == N0.getOperand(1) &&
6642 N1.getOperand(0) == N0.getOperand(0)) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(2.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6650 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6651 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6652 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6653 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6654 (N0.getOperand(0) == N1))
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656 N1, DAG.getConstantFP(3.0, VT));
6659 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6660 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6661 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6662 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6663 N1.getOperand(0) == N0)
6664 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6665 N0, DAG.getConstantFP(3.0, VT));
6668 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6669 if (AllowNewConst &&
6670 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6671 N0.getOperand(0) == N0.getOperand(1) &&
6672 N1.getOperand(0) == N1.getOperand(1) &&
6673 N0.getOperand(0) == N1.getOperand(0))
6674 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6675 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6677 } // enable-unsafe-fp-math
6679 // FADD -> FMA combines:
6680 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6683 ->getTargetLowering()
6684 ->isFMAFasterThanFMulAndFAdd(VT) &&
6685 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6687 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6688 if (N0.getOpcode() == ISD::FMUL &&
6689 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6690 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6691 N0.getOperand(0), N0.getOperand(1), N1);
6693 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6694 // Note: Commutes FADD operands.
6695 if (N1.getOpcode() == ISD::FMUL &&
6696 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6697 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6698 N1.getOperand(0), N1.getOperand(1), N0);
6704 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6705 SDValue N0 = N->getOperand(0);
6706 SDValue N1 = N->getOperand(1);
6707 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6708 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6709 EVT VT = N->getValueType(0);
6711 const TargetOptions &Options = DAG.getTarget().Options;
6714 if (VT.isVector()) {
6715 SDValue FoldedVOp = SimplifyVBinOp(N);
6716 if (FoldedVOp.getNode()) return FoldedVOp;
6719 // fold (fsub c1, c2) -> c1-c2
6721 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6723 // fold (fsub A, (fneg B)) -> (fadd A, B)
6724 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6725 return DAG.getNode(ISD::FADD, dl, VT, N0,
6726 GetNegatedExpression(N1, DAG, LegalOperations));
6728 // If 'unsafe math' is enabled, fold lots of things.
6729 if (Options.UnsafeFPMath) {
6731 if (N1CFP && N1CFP->getValueAPF().isZero())
6734 // (fsub 0, B) -> -B
6735 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6736 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6737 return GetNegatedExpression(N1, DAG, LegalOperations);
6738 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6739 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6742 // (fsub x, x) -> 0.0
6744 return DAG.getConstantFP(0.0f, VT);
6746 // (fsub x, (fadd x, y)) -> (fneg y)
6747 // (fsub x, (fadd y, x)) -> (fneg y)
6748 if (N1.getOpcode() == ISD::FADD) {
6749 SDValue N10 = N1->getOperand(0);
6750 SDValue N11 = N1->getOperand(1);
6752 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6753 return GetNegatedExpression(N11, DAG, LegalOperations);
6755 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6756 return GetNegatedExpression(N10, DAG, LegalOperations);
6760 // FSUB -> FMA combines:
6761 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6762 DAG.getTarget().getSubtargetImpl()
6763 ->getTargetLowering()
6764 ->isFMAFasterThanFMulAndFAdd(VT) &&
6765 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6767 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6768 if (N0.getOpcode() == ISD::FMUL &&
6769 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6770 return DAG.getNode(ISD::FMA, dl, VT,
6771 N0.getOperand(0), N0.getOperand(1),
6772 DAG.getNode(ISD::FNEG, dl, VT, N1));
6774 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6775 // Note: Commutes FSUB operands.
6776 if (N1.getOpcode() == ISD::FMUL &&
6777 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6778 return DAG.getNode(ISD::FMA, dl, VT,
6779 DAG.getNode(ISD::FNEG, dl, VT,
6781 N1.getOperand(1), N0);
6783 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6784 if (N0.getOpcode() == ISD::FNEG &&
6785 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6786 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6787 TLI.enableAggressiveFMAFusion(VT))) {
6788 SDValue N00 = N0.getOperand(0).getOperand(0);
6789 SDValue N01 = N0.getOperand(0).getOperand(1);
6790 return DAG.getNode(ISD::FMA, dl, VT,
6791 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6792 DAG.getNode(ISD::FNEG, dl, VT, N1));
6799 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6800 SDValue N0 = N->getOperand(0);
6801 SDValue N1 = N->getOperand(1);
6802 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6803 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6804 EVT VT = N->getValueType(0);
6805 const TargetOptions &Options = DAG.getTarget().Options;
6808 if (VT.isVector()) {
6809 // This just handles C1 * C2 for vectors. Other vector folds are below.
6810 SDValue FoldedVOp = SimplifyVBinOp(N);
6811 if (FoldedVOp.getNode())
6813 // Canonicalize vector constant to RHS.
6814 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6815 N1.getOpcode() != ISD::BUILD_VECTOR)
6816 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6817 if (BV0->isConstant())
6818 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6821 // fold (fmul c1, c2) -> c1*c2
6823 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6825 // canonicalize constant to RHS
6826 if (N0CFP && !N1CFP)
6827 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6829 // fold (fmul A, 1.0) -> A
6830 if (N1CFP && N1CFP->isExactlyValue(1.0))
6833 if (Options.UnsafeFPMath) {
6834 // fold (fmul A, 0) -> 0
6835 if (N1CFP && N1CFP->getValueAPF().isZero())
6838 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6839 if (N0.getOpcode() == ISD::FMUL) {
6840 // Fold scalars or any vector constants (not just splats).
6841 // This fold is done in general by InstCombine, but extra fmul insts
6842 // may have been generated during lowering.
6843 SDValue N01 = N0.getOperand(1);
6844 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6845 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6846 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6847 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6849 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6850 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6854 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6855 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6856 // during an early run of DAGCombiner can prevent folding with fmuls
6857 // inserted during lowering.
6858 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6860 const SDValue Two = DAG.getConstantFP(2.0, VT);
6861 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6866 // fold (fmul X, 2.0) -> (fadd X, X)
6867 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6868 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6870 // fold (fmul X, -1.0) -> (fneg X)
6871 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6872 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6873 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6875 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6876 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6877 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6878 // Both can be negated for free, check to see if at least one is cheaper
6880 if (LHSNeg == 2 || RHSNeg == 2)
6881 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6882 GetNegatedExpression(N0, DAG, LegalOperations),
6883 GetNegatedExpression(N1, DAG, LegalOperations));
6890 SDValue DAGCombiner::visitFMA(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
6893 SDValue N2 = N->getOperand(2);
6894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6895 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6896 EVT VT = N->getValueType(0);
6898 const TargetOptions &Options = DAG.getTarget().Options;
6900 // Constant fold FMA.
6901 if (isa<ConstantFPSDNode>(N0) &&
6902 isa<ConstantFPSDNode>(N1) &&
6903 isa<ConstantFPSDNode>(N2)) {
6904 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6907 if (Options.UnsafeFPMath) {
6908 if (N0CFP && N0CFP->isZero())
6910 if (N1CFP && N1CFP->isZero())
6913 if (N0CFP && N0CFP->isExactlyValue(1.0))
6914 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6915 if (N1CFP && N1CFP->isExactlyValue(1.0))
6916 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6918 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6919 if (N0CFP && !N1CFP)
6920 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6922 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6923 if (Options.UnsafeFPMath && N1CFP &&
6924 N2.getOpcode() == ISD::FMUL &&
6925 N0 == N2.getOperand(0) &&
6926 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6927 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6928 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6932 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6933 if (Options.UnsafeFPMath &&
6934 N0.getOpcode() == ISD::FMUL && N1CFP &&
6935 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6936 return DAG.getNode(ISD::FMA, dl, VT,
6938 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6942 // (fma x, 1, y) -> (fadd x, y)
6943 // (fma x, -1, y) -> (fadd (fneg x), y)
6945 if (N1CFP->isExactlyValue(1.0))
6946 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6948 if (N1CFP->isExactlyValue(-1.0) &&
6949 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6950 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6951 AddToWorklist(RHSNeg.getNode());
6952 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6956 // (fma x, c, x) -> (fmul x, (c+1))
6957 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6958 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6959 DAG.getNode(ISD::FADD, dl, VT,
6960 N1, DAG.getConstantFP(1.0, VT)));
6962 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6963 if (Options.UnsafeFPMath && N1CFP &&
6964 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6965 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6966 DAG.getNode(ISD::FADD, dl, VT,
6967 N1, DAG.getConstantFP(-1.0, VT)));
6973 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6974 SDValue N0 = N->getOperand(0);
6975 SDValue N1 = N->getOperand(1);
6976 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6977 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6978 EVT VT = N->getValueType(0);
6979 const TargetOptions &Options = DAG.getTarget().Options;
6982 if (VT.isVector()) {
6983 SDValue FoldedVOp = SimplifyVBinOp(N);
6984 if (FoldedVOp.getNode()) return FoldedVOp;
6987 // fold (fdiv c1, c2) -> c1/c2
6989 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6991 if (Options.UnsafeFPMath) {
6992 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6994 // Compute the reciprocal 1.0 / c2.
6995 APFloat N1APF = N1CFP->getValueAPF();
6996 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6997 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6998 // Only do the transform if the reciprocal is a legal fp immediate that
6999 // isn't too nasty (eg NaN, denormal, ...).
7000 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7001 (!LegalOperations ||
7002 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7003 // backend)... we should handle this gracefully after Legalize.
7004 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7005 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7006 TLI.isFPImmLegal(Recip, VT)))
7007 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7008 DAG.getConstantFP(Recip, VT));
7010 // If this FDIV is part of a reciprocal square root, it may be folded
7011 // into a target-specific square root estimate instruction.
7012 if (SDValue SqrtOp = BuildRSQRTE(N))
7016 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7017 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7018 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7019 // Both can be negated for free, check to see if at least one is cheaper
7021 if (LHSNeg == 2 || RHSNeg == 2)
7022 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7023 GetNegatedExpression(N0, DAG, LegalOperations),
7024 GetNegatedExpression(N1, DAG, LegalOperations));
7031 SDValue DAGCombiner::visitFREM(SDNode *N) {
7032 SDValue N0 = N->getOperand(0);
7033 SDValue N1 = N->getOperand(1);
7034 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7035 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7036 EVT VT = N->getValueType(0);
7038 // fold (frem c1, c2) -> fmod(c1,c2)
7040 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7045 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7046 SDValue N0 = N->getOperand(0);
7047 SDValue N1 = N->getOperand(1);
7048 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7049 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7050 EVT VT = N->getValueType(0);
7052 if (N0CFP && N1CFP) // Constant fold
7053 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7056 const APFloat& V = N1CFP->getValueAPF();
7057 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7058 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7059 if (!V.isNegative()) {
7060 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7061 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7063 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7064 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7065 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7069 // copysign(fabs(x), y) -> copysign(x, y)
7070 // copysign(fneg(x), y) -> copysign(x, y)
7071 // copysign(copysign(x,z), y) -> copysign(x, y)
7072 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7073 N0.getOpcode() == ISD::FCOPYSIGN)
7074 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7075 N0.getOperand(0), N1);
7077 // copysign(x, abs(y)) -> abs(x)
7078 if (N1.getOpcode() == ISD::FABS)
7079 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7081 // copysign(x, copysign(y,z)) -> copysign(x, z)
7082 if (N1.getOpcode() == ISD::FCOPYSIGN)
7083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7084 N0, N1.getOperand(1));
7086 // copysign(x, fp_extend(y)) -> copysign(x, y)
7087 // copysign(x, fp_round(y)) -> copysign(x, y)
7088 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7089 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7090 N0, N1.getOperand(0));
7095 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7099 EVT OpVT = N0.getValueType();
7101 // fold (sint_to_fp c1) -> c1fp
7103 // ...but only if the target supports immediate floating-point values
7104 (!LegalOperations ||
7105 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7106 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7108 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7109 // but UINT_TO_FP is legal on this target, try to convert.
7110 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7111 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7112 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7113 if (DAG.SignBitIsZero(N0))
7114 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7117 // The next optimizations are desirable only if SELECT_CC can be lowered.
7118 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7119 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7120 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7122 (!LegalOperations ||
7123 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7125 { N0.getOperand(0), N0.getOperand(1),
7126 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7128 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7131 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7132 // (select_cc x, y, 1.0, 0.0,, cc)
7133 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7134 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7135 (!LegalOperations ||
7136 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7138 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7139 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7140 N0.getOperand(0).getOperand(2) };
7141 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7148 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7149 SDValue N0 = N->getOperand(0);
7150 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7151 EVT VT = N->getValueType(0);
7152 EVT OpVT = N0.getValueType();
7154 // fold (uint_to_fp c1) -> c1fp
7156 // ...but only if the target supports immediate floating-point values
7157 (!LegalOperations ||
7158 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7159 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7161 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7162 // but SINT_TO_FP is legal on this target, try to convert.
7163 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7164 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7165 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7166 if (DAG.SignBitIsZero(N0))
7167 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7170 // The next optimizations are desirable only if SELECT_CC can be lowered.
7171 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7172 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7174 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7175 (!LegalOperations ||
7176 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7178 { N0.getOperand(0), N0.getOperand(1),
7179 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7181 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7188 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7189 SDValue N0 = N->getOperand(0);
7190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191 EVT VT = N->getValueType(0);
7193 // fold (fp_to_sint c1fp) -> c1
7195 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7200 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7201 SDValue N0 = N->getOperand(0);
7202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7203 EVT VT = N->getValueType(0);
7205 // fold (fp_to_uint c1fp) -> c1
7207 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7212 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7213 SDValue N0 = N->getOperand(0);
7214 SDValue N1 = N->getOperand(1);
7215 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7216 EVT VT = N->getValueType(0);
7218 // fold (fp_round c1fp) -> c1fp
7220 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7222 // fold (fp_round (fp_extend x)) -> x
7223 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7224 return N0.getOperand(0);
7226 // fold (fp_round (fp_round x)) -> (fp_round x)
7227 if (N0.getOpcode() == ISD::FP_ROUND) {
7228 // This is a value preserving truncation if both round's are.
7229 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7230 N0.getNode()->getConstantOperandVal(1) == 1;
7231 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7232 DAG.getIntPtrConstant(IsTrunc));
7235 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7236 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7237 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7238 N0.getOperand(0), N1);
7239 AddToWorklist(Tmp.getNode());
7240 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7241 Tmp, N0.getOperand(1));
7247 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7248 SDValue N0 = N->getOperand(0);
7249 EVT VT = N->getValueType(0);
7250 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7251 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7253 // fold (fp_round_inreg c1fp) -> c1fp
7254 if (N0CFP && isTypeLegal(EVT)) {
7255 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7256 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7262 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7263 SDValue N0 = N->getOperand(0);
7264 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7265 EVT VT = N->getValueType(0);
7267 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7268 if (N->hasOneUse() &&
7269 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7272 // fold (fp_extend c1fp) -> c1fp
7274 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7276 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7278 if (N0.getOpcode() == ISD::FP_ROUND
7279 && N0.getNode()->getConstantOperandVal(1) == 1) {
7280 SDValue In = N0.getOperand(0);
7281 if (In.getValueType() == VT) return In;
7282 if (VT.bitsLT(In.getValueType()))
7283 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7284 In, N0.getOperand(1));
7285 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7288 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7289 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7290 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7291 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7292 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7294 LN0->getBasePtr(), N0.getValueType(),
7295 LN0->getMemOperand());
7296 CombineTo(N, ExtLoad);
7297 CombineTo(N0.getNode(),
7298 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7299 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7300 ExtLoad.getValue(1));
7301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7307 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7308 SDValue N0 = N->getOperand(0);
7309 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7310 EVT VT = N->getValueType(0);
7312 // fold (fceil c1) -> fceil(c1)
7314 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7319 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7320 SDValue N0 = N->getOperand(0);
7321 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7322 EVT VT = N->getValueType(0);
7324 // fold (ftrunc c1) -> ftrunc(c1)
7326 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7331 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7332 SDValue N0 = N->getOperand(0);
7333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334 EVT VT = N->getValueType(0);
7336 // fold (ffloor c1) -> ffloor(c1)
7338 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7343 // FIXME: FNEG and FABS have a lot in common; refactor.
7344 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7345 SDValue N0 = N->getOperand(0);
7346 EVT VT = N->getValueType(0);
7348 if (VT.isVector()) {
7349 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7350 if (FoldedVOp.getNode()) return FoldedVOp;
7353 // Constant fold FNEG.
7354 if (isa<ConstantFPSDNode>(N0))
7355 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7357 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7358 &DAG.getTarget().Options))
7359 return GetNegatedExpression(N0, DAG, LegalOperations);
7361 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7362 // constant pool values.
7363 if (!TLI.isFNegFree(VT) &&
7364 N0.getOpcode() == ISD::BITCAST &&
7365 N0.getNode()->hasOneUse()) {
7366 SDValue Int = N0.getOperand(0);
7367 EVT IntVT = Int.getValueType();
7368 if (IntVT.isInteger() && !IntVT.isVector()) {
7370 if (N0.getValueType().isVector()) {
7371 // For a vector, get a mask such as 0x80... per scalar element
7373 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7374 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7376 // For a scalar, just generate 0x80...
7377 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7379 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7380 DAG.getConstant(SignMask, IntVT));
7381 AddToWorklist(Int.getNode());
7382 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7386 // (fneg (fmul c, x)) -> (fmul -c, x)
7387 if (N0.getOpcode() == ISD::FMUL) {
7388 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7390 APFloat CVal = CFP1->getValueAPF();
7392 if (Level >= AfterLegalizeDAG &&
7393 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7394 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7396 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7397 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7404 SDValue DAGCombiner::visitFABS(SDNode *N) {
7405 SDValue N0 = N->getOperand(0);
7406 EVT VT = N->getValueType(0);
7408 if (VT.isVector()) {
7409 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7410 if (FoldedVOp.getNode()) return FoldedVOp;
7413 // fold (fabs c1) -> fabs(c1)
7414 if (isa<ConstantFPSDNode>(N0))
7415 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7417 // fold (fabs (fabs x)) -> (fabs x)
7418 if (N0.getOpcode() == ISD::FABS)
7419 return N->getOperand(0);
7421 // fold (fabs (fneg x)) -> (fabs x)
7422 // fold (fabs (fcopysign x, y)) -> (fabs x)
7423 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7424 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7426 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7427 // constant pool values.
7428 if (!TLI.isFAbsFree(VT) &&
7429 N0.getOpcode() == ISD::BITCAST &&
7430 N0.getNode()->hasOneUse()) {
7431 SDValue Int = N0.getOperand(0);
7432 EVT IntVT = Int.getValueType();
7433 if (IntVT.isInteger() && !IntVT.isVector()) {
7435 if (N0.getValueType().isVector()) {
7436 // For a vector, get a mask such as 0x7f... per scalar element
7438 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7439 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7441 // For a scalar, just generate 0x7f...
7442 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7444 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7445 DAG.getConstant(SignMask, IntVT));
7446 AddToWorklist(Int.getNode());
7447 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7454 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7455 SDValue Chain = N->getOperand(0);
7456 SDValue N1 = N->getOperand(1);
7457 SDValue N2 = N->getOperand(2);
7459 // If N is a constant we could fold this into a fallthrough or unconditional
7460 // branch. However that doesn't happen very often in normal code, because
7461 // Instcombine/SimplifyCFG should have handled the available opportunities.
7462 // If we did this folding here, it would be necessary to update the
7463 // MachineBasicBlock CFG, which is awkward.
7465 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7467 if (N1.getOpcode() == ISD::SETCC &&
7468 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7469 N1.getOperand(0).getValueType())) {
7470 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7471 Chain, N1.getOperand(2),
7472 N1.getOperand(0), N1.getOperand(1), N2);
7475 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7476 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7477 (N1.getOperand(0).hasOneUse() &&
7478 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7479 SDNode *Trunc = nullptr;
7480 if (N1.getOpcode() == ISD::TRUNCATE) {
7481 // Look pass the truncate.
7482 Trunc = N1.getNode();
7483 N1 = N1.getOperand(0);
7486 // Match this pattern so that we can generate simpler code:
7489 // %b = and i32 %a, 2
7490 // %c = srl i32 %b, 1
7491 // brcond i32 %c ...
7496 // %b = and i32 %a, 2
7497 // %c = setcc eq %b, 0
7500 // This applies only when the AND constant value has one bit set and the
7501 // SRL constant is equal to the log2 of the AND constant. The back-end is
7502 // smart enough to convert the result into a TEST/JMP sequence.
7503 SDValue Op0 = N1.getOperand(0);
7504 SDValue Op1 = N1.getOperand(1);
7506 if (Op0.getOpcode() == ISD::AND &&
7507 Op1.getOpcode() == ISD::Constant) {
7508 SDValue AndOp1 = Op0.getOperand(1);
7510 if (AndOp1.getOpcode() == ISD::Constant) {
7511 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7513 if (AndConst.isPowerOf2() &&
7514 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7516 DAG.getSetCC(SDLoc(N),
7517 getSetCCResultType(Op0.getValueType()),
7518 Op0, DAG.getConstant(0, Op0.getValueType()),
7521 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7522 MVT::Other, Chain, SetCC, N2);
7523 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7524 // will convert it back to (X & C1) >> C2.
7525 CombineTo(N, NewBRCond, false);
7526 // Truncate is dead.
7528 deleteAndRecombine(Trunc);
7529 // Replace the uses of SRL with SETCC
7530 WorklistRemover DeadNodes(*this);
7531 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7532 deleteAndRecombine(N1.getNode());
7533 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7539 // Restore N1 if the above transformation doesn't match.
7540 N1 = N->getOperand(1);
7543 // Transform br(xor(x, y)) -> br(x != y)
7544 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7545 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7546 SDNode *TheXor = N1.getNode();
7547 SDValue Op0 = TheXor->getOperand(0);
7548 SDValue Op1 = TheXor->getOperand(1);
7549 if (Op0.getOpcode() == Op1.getOpcode()) {
7550 // Avoid missing important xor optimizations.
7551 SDValue Tmp = visitXOR(TheXor);
7552 if (Tmp.getNode()) {
7553 if (Tmp.getNode() != TheXor) {
7554 DEBUG(dbgs() << "\nReplacing.8 ";
7556 dbgs() << "\nWith: ";
7557 Tmp.getNode()->dump(&DAG);
7559 WorklistRemover DeadNodes(*this);
7560 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7561 deleteAndRecombine(TheXor);
7562 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7563 MVT::Other, Chain, Tmp, N2);
7566 // visitXOR has changed XOR's operands or replaced the XOR completely,
7568 return SDValue(N, 0);
7572 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7574 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7575 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7576 Op0.getOpcode() == ISD::XOR) {
7577 TheXor = Op0.getNode();
7581 EVT SetCCVT = N1.getValueType();
7583 SetCCVT = getSetCCResultType(SetCCVT);
7584 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7587 Equal ? ISD::SETEQ : ISD::SETNE);
7588 // Replace the uses of XOR with SETCC
7589 WorklistRemover DeadNodes(*this);
7590 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7591 deleteAndRecombine(N1.getNode());
7592 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7593 MVT::Other, Chain, SetCC, N2);
7600 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7602 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7603 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7604 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7606 // If N is a constant we could fold this into a fallthrough or unconditional
7607 // branch. However that doesn't happen very often in normal code, because
7608 // Instcombine/SimplifyCFG should have handled the available opportunities.
7609 // If we did this folding here, it would be necessary to update the
7610 // MachineBasicBlock CFG, which is awkward.
7612 // Use SimplifySetCC to simplify SETCC's.
7613 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7614 CondLHS, CondRHS, CC->get(), SDLoc(N),
7616 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7618 // fold to a simpler setcc
7619 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7620 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7621 N->getOperand(0), Simp.getOperand(2),
7622 Simp.getOperand(0), Simp.getOperand(1),
7628 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7629 /// and that N may be folded in the load / store addressing mode.
7630 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7632 const TargetLowering &TLI) {
7634 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7635 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7637 VT = Use->getValueType(0);
7638 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7639 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7641 VT = ST->getValue().getValueType();
7645 TargetLowering::AddrMode AM;
7646 if (N->getOpcode() == ISD::ADD) {
7647 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7650 AM.BaseOffs = Offset->getSExtValue();
7654 } else if (N->getOpcode() == ISD::SUB) {
7655 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7658 AM.BaseOffs = -Offset->getSExtValue();
7665 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7668 /// Try turning a load/store into a pre-indexed load/store when the base
7669 /// pointer is an add or subtract and it has other uses besides the load/store.
7670 /// After the transformation, the new indexed load/store has effectively folded
7671 /// the add/subtract in and all of its other uses are redirected to the
7673 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7674 if (Level < AfterLegalizeDAG)
7680 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7681 if (LD->isIndexed())
7683 VT = LD->getMemoryVT();
7684 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7685 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7687 Ptr = LD->getBasePtr();
7688 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7689 if (ST->isIndexed())
7691 VT = ST->getMemoryVT();
7692 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7693 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7695 Ptr = ST->getBasePtr();
7701 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7702 // out. There is no reason to make this a preinc/predec.
7703 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7704 Ptr.getNode()->hasOneUse())
7707 // Ask the target to do addressing mode selection.
7710 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7711 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7714 // Backends without true r+i pre-indexed forms may need to pass a
7715 // constant base with a variable offset so that constant coercion
7716 // will work with the patterns in canonical form.
7717 bool Swapped = false;
7718 if (isa<ConstantSDNode>(BasePtr)) {
7719 std::swap(BasePtr, Offset);
7723 // Don't create a indexed load / store with zero offset.
7724 if (isa<ConstantSDNode>(Offset) &&
7725 cast<ConstantSDNode>(Offset)->isNullValue())
7728 // Try turning it into a pre-indexed load / store except when:
7729 // 1) The new base ptr is a frame index.
7730 // 2) If N is a store and the new base ptr is either the same as or is a
7731 // predecessor of the value being stored.
7732 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7733 // that would create a cycle.
7734 // 4) All uses are load / store ops that use it as old base ptr.
7736 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7737 // (plus the implicit offset) to a register to preinc anyway.
7738 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7743 SDValue Val = cast<StoreSDNode>(N)->getValue();
7744 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7748 // If the offset is a constant, there may be other adds of constants that
7749 // can be folded with this one. We should do this to avoid having to keep
7750 // a copy of the original base pointer.
7751 SmallVector<SDNode *, 16> OtherUses;
7752 if (isa<ConstantSDNode>(Offset))
7753 for (SDNode *Use : BasePtr.getNode()->uses()) {
7754 if (Use == Ptr.getNode())
7757 if (Use->isPredecessorOf(N))
7760 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7765 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7766 if (Op1.getNode() == BasePtr.getNode())
7767 std::swap(Op0, Op1);
7768 assert(Op0.getNode() == BasePtr.getNode() &&
7769 "Use of ADD/SUB but not an operand");
7771 if (!isa<ConstantSDNode>(Op1)) {
7776 // FIXME: In some cases, we can be smarter about this.
7777 if (Op1.getValueType() != Offset.getValueType()) {
7782 OtherUses.push_back(Use);
7786 std::swap(BasePtr, Offset);
7788 // Now check for #3 and #4.
7789 bool RealUse = false;
7791 // Caches for hasPredecessorHelper
7792 SmallPtrSet<const SDNode *, 32> Visited;
7793 SmallVector<const SDNode *, 16> Worklist;
7795 for (SDNode *Use : Ptr.getNode()->uses()) {
7798 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7801 // If Ptr may be folded in addressing mode of other use, then it's
7802 // not profitable to do this transformation.
7803 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7812 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7813 BasePtr, Offset, AM);
7815 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7816 BasePtr, Offset, AM);
7819 DEBUG(dbgs() << "\nReplacing.4 ";
7821 dbgs() << "\nWith: ";
7822 Result.getNode()->dump(&DAG);
7824 WorklistRemover DeadNodes(*this);
7826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7827 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7829 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7832 // Finally, since the node is now dead, remove it from the graph.
7833 deleteAndRecombine(N);
7836 std::swap(BasePtr, Offset);
7838 // Replace other uses of BasePtr that can be updated to use Ptr
7839 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7840 unsigned OffsetIdx = 1;
7841 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7843 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7844 BasePtr.getNode() && "Expected BasePtr operand");
7846 // We need to replace ptr0 in the following expression:
7847 // x0 * offset0 + y0 * ptr0 = t0
7849 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7851 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7852 // indexed load/store and the expresion that needs to be re-written.
7854 // Therefore, we have:
7855 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7857 ConstantSDNode *CN =
7858 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7860 APInt Offset0 = CN->getAPIntValue();
7861 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7863 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7864 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7865 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7866 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7868 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7870 APInt CNV = Offset0;
7871 if (X0 < 0) CNV = -CNV;
7872 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7873 else CNV = CNV - Offset1;
7875 // We can now generate the new expression.
7876 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7877 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7879 SDValue NewUse = DAG.getNode(Opcode,
7880 SDLoc(OtherUses[i]),
7881 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7882 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7883 deleteAndRecombine(OtherUses[i]);
7886 // Replace the uses of Ptr with uses of the updated base value.
7887 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7888 deleteAndRecombine(Ptr.getNode());
7893 /// Try to combine a load/store with a add/sub of the base pointer node into a
7894 /// post-indexed load/store. The transformation folded the add/subtract into the
7895 /// new indexed load/store effectively and all of its uses are redirected to the
7897 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7898 if (Level < AfterLegalizeDAG)
7904 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7905 if (LD->isIndexed())
7907 VT = LD->getMemoryVT();
7908 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7909 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7911 Ptr = LD->getBasePtr();
7912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7913 if (ST->isIndexed())
7915 VT = ST->getMemoryVT();
7916 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7917 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7919 Ptr = ST->getBasePtr();
7925 if (Ptr.getNode()->hasOneUse())
7928 for (SDNode *Op : Ptr.getNode()->uses()) {
7930 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7935 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7936 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7937 // Don't create a indexed load / store with zero offset.
7938 if (isa<ConstantSDNode>(Offset) &&
7939 cast<ConstantSDNode>(Offset)->isNullValue())
7942 // Try turning it into a post-indexed load / store except when
7943 // 1) All uses are load / store ops that use it as base ptr (and
7944 // it may be folded as addressing mmode).
7945 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7946 // nor a successor of N. Otherwise, if Op is folded that would
7949 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7953 bool TryNext = false;
7954 for (SDNode *Use : BasePtr.getNode()->uses()) {
7955 if (Use == Ptr.getNode())
7958 // If all the uses are load / store addresses, then don't do the
7960 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7961 bool RealUse = false;
7962 for (SDNode *UseUse : Use->uses()) {
7963 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7978 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7979 SDValue Result = isLoad
7980 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7981 BasePtr, Offset, AM)
7982 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7983 BasePtr, Offset, AM);
7986 DEBUG(dbgs() << "\nReplacing.5 ";
7988 dbgs() << "\nWith: ";
7989 Result.getNode()->dump(&DAG);
7991 WorklistRemover DeadNodes(*this);
7993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7996 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7999 // Finally, since the node is now dead, remove it from the graph.
8000 deleteAndRecombine(N);
8002 // Replace the uses of Use with uses of the updated base value.
8003 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8004 Result.getValue(isLoad ? 1 : 0));
8005 deleteAndRecombine(Op);
8014 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8015 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8016 ISD::MemIndexedMode AM = LD->getAddressingMode();
8017 assert(AM != ISD::UNINDEXED);
8018 SDValue BP = LD->getOperand(1);
8019 SDValue Inc = LD->getOperand(2);
8021 // Some backends use TargetConstants for load offsets, but don't expect
8022 // TargetConstants in general ADD nodes. We can convert these constants into
8023 // regular Constants (if the constant is not opaque).
8024 assert((Inc.getOpcode() != ISD::TargetConstant ||
8025 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8026 "Cannot split out indexing using opaque target constants");
8027 if (Inc.getOpcode() == ISD::TargetConstant) {
8028 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8029 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8030 ConstInc->getValueType(0));
8034 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8035 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8038 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8039 LoadSDNode *LD = cast<LoadSDNode>(N);
8040 SDValue Chain = LD->getChain();
8041 SDValue Ptr = LD->getBasePtr();
8043 // If load is not volatile and there are no uses of the loaded value (and
8044 // the updated indexed value in case of indexed loads), change uses of the
8045 // chain value into uses of the chain input (i.e. delete the dead load).
8046 if (!LD->isVolatile()) {
8047 if (N->getValueType(1) == MVT::Other) {
8049 if (!N->hasAnyUseOfValue(0)) {
8050 // It's not safe to use the two value CombineTo variant here. e.g.
8051 // v1, chain2 = load chain1, loc
8052 // v2, chain3 = load chain2, loc
8054 // Now we replace use of chain2 with chain1. This makes the second load
8055 // isomorphic to the one we are deleting, and thus makes this load live.
8056 DEBUG(dbgs() << "\nReplacing.6 ";
8058 dbgs() << "\nWith chain: ";
8059 Chain.getNode()->dump(&DAG);
8061 WorklistRemover DeadNodes(*this);
8062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8065 deleteAndRecombine(N);
8067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8071 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8073 // If this load has an opaque TargetConstant offset, then we cannot split
8074 // the indexing into an add/sub directly (that TargetConstant may not be
8075 // valid for a different type of node, and we cannot convert an opaque
8076 // target constant into a regular constant).
8077 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8078 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8080 if (!N->hasAnyUseOfValue(0) &&
8081 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8082 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8084 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8085 Index = SplitIndexingFromLoad(LD);
8086 // Try to fold the base pointer arithmetic into subsequent loads and
8088 AddUsersToWorklist(N);
8090 Index = DAG.getUNDEF(N->getValueType(1));
8091 DEBUG(dbgs() << "\nReplacing.7 ";
8093 dbgs() << "\nWith: ";
8094 Undef.getNode()->dump(&DAG);
8095 dbgs() << " and 2 other values\n");
8096 WorklistRemover DeadNodes(*this);
8097 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8098 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8099 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8100 deleteAndRecombine(N);
8101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8106 // If this load is directly stored, replace the load value with the stored
8108 // TODO: Handle store large -> read small portion.
8109 // TODO: Handle TRUNCSTORE/LOADEXT
8110 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8111 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8112 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8113 if (PrevST->getBasePtr() == Ptr &&
8114 PrevST->getValue().getValueType() == N->getValueType(0))
8115 return CombineTo(N, Chain.getOperand(1), Chain);
8119 // Try to infer better alignment information than the load already has.
8120 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8121 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8122 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8124 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8125 LD->getValueType(0),
8126 Chain, Ptr, LD->getPointerInfo(),
8128 LD->isVolatile(), LD->isNonTemporal(),
8129 LD->isInvariant(), Align, LD->getAAInfo());
8130 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8135 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8136 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8138 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8139 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8142 if (UseAA && LD->isUnindexed()) {
8143 // Walk up chain skipping non-aliasing memory nodes.
8144 SDValue BetterChain = FindBetterChain(N, Chain);
8146 // If there is a better chain.
8147 if (Chain != BetterChain) {
8150 // Replace the chain to void dependency.
8151 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8152 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8153 BetterChain, Ptr, LD->getMemOperand());
8155 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8156 LD->getValueType(0),
8157 BetterChain, Ptr, LD->getMemoryVT(),
8158 LD->getMemOperand());
8161 // Create token factor to keep old chain connected.
8162 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8163 MVT::Other, Chain, ReplLoad.getValue(1));
8165 // Make sure the new and old chains are cleaned up.
8166 AddToWorklist(Token.getNode());
8168 // Replace uses with load result and token factor. Don't add users
8170 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8174 // Try transforming N to an indexed load.
8175 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8176 return SDValue(N, 0);
8178 // Try to slice up N to more direct loads if the slices are mapped to
8179 // different register banks or pairing can take place.
8181 return SDValue(N, 0);
8187 /// \brief Helper structure used to slice a load in smaller loads.
8188 /// Basically a slice is obtained from the following sequence:
8189 /// Origin = load Ty1, Base
8190 /// Shift = srl Ty1 Origin, CstTy Amount
8191 /// Inst = trunc Shift to Ty2
8193 /// Then, it will be rewriten into:
8194 /// Slice = load SliceTy, Base + SliceOffset
8195 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8197 /// SliceTy is deduced from the number of bits that are actually used to
8199 struct LoadedSlice {
8200 /// \brief Helper structure used to compute the cost of a slice.
8202 /// Are we optimizing for code size.
8207 unsigned CrossRegisterBanksCopies;
8211 Cost(bool ForCodeSize = false)
8212 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8213 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8215 /// \brief Get the cost of one isolated slice.
8216 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8217 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8218 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8219 EVT TruncType = LS.Inst->getValueType(0);
8220 EVT LoadedType = LS.getLoadedType();
8221 if (TruncType != LoadedType &&
8222 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8226 /// \brief Account for slicing gain in the current cost.
8227 /// Slicing provide a few gains like removing a shift or a
8228 /// truncate. This method allows to grow the cost of the original
8229 /// load with the gain from this slice.
8230 void addSliceGain(const LoadedSlice &LS) {
8231 // Each slice saves a truncate.
8232 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8233 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8234 LS.Inst->getOperand(0).getValueType()))
8236 // If there is a shift amount, this slice gets rid of it.
8239 // If this slice can merge a cross register bank copy, account for it.
8240 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8241 ++CrossRegisterBanksCopies;
8244 Cost &operator+=(const Cost &RHS) {
8246 Truncates += RHS.Truncates;
8247 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8253 bool operator==(const Cost &RHS) const {
8254 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8255 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8256 ZExts == RHS.ZExts && Shift == RHS.Shift;
8259 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8261 bool operator<(const Cost &RHS) const {
8262 // Assume cross register banks copies are as expensive as loads.
8263 // FIXME: Do we want some more target hooks?
8264 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8265 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8266 // Unless we are optimizing for code size, consider the
8267 // expensive operation first.
8268 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8269 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8270 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8271 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8274 bool operator>(const Cost &RHS) const { return RHS < *this; }
8276 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8278 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8280 // The last instruction that represent the slice. This should be a
8281 // truncate instruction.
8283 // The original load instruction.
8285 // The right shift amount in bits from the original load.
8287 // The DAG from which Origin came from.
8288 // This is used to get some contextual information about legal types, etc.
8291 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8292 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8293 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8295 LoadedSlice(const LoadedSlice &LS)
8296 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8298 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8299 /// \return Result is \p BitWidth and has used bits set to 1 and
8300 /// not used bits set to 0.
8301 APInt getUsedBits() const {
8302 // Reproduce the trunc(lshr) sequence:
8303 // - Start from the truncated value.
8304 // - Zero extend to the desired bit width.
8306 assert(Origin && "No original load to compare against.");
8307 unsigned BitWidth = Origin->getValueSizeInBits(0);
8308 assert(Inst && "This slice is not bound to an instruction");
8309 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8310 "Extracted slice is bigger than the whole type!");
8311 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8312 UsedBits.setAllBits();
8313 UsedBits = UsedBits.zext(BitWidth);
8318 /// \brief Get the size of the slice to be loaded in bytes.
8319 unsigned getLoadedSize() const {
8320 unsigned SliceSize = getUsedBits().countPopulation();
8321 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8322 return SliceSize / 8;
8325 /// \brief Get the type that will be loaded for this slice.
8326 /// Note: This may not be the final type for the slice.
8327 EVT getLoadedType() const {
8328 assert(DAG && "Missing context");
8329 LLVMContext &Ctxt = *DAG->getContext();
8330 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8333 /// \brief Get the alignment of the load used for this slice.
8334 unsigned getAlignment() const {
8335 unsigned Alignment = Origin->getAlignment();
8336 unsigned Offset = getOffsetFromBase();
8338 Alignment = MinAlign(Alignment, Alignment + Offset);
8342 /// \brief Check if this slice can be rewritten with legal operations.
8343 bool isLegal() const {
8344 // An invalid slice is not legal.
8345 if (!Origin || !Inst || !DAG)
8348 // Offsets are for indexed load only, we do not handle that.
8349 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8352 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8354 // Check that the type is legal.
8355 EVT SliceType = getLoadedType();
8356 if (!TLI.isTypeLegal(SliceType))
8359 // Check that the load is legal for this type.
8360 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8363 // Check that the offset can be computed.
8364 // 1. Check its type.
8365 EVT PtrType = Origin->getBasePtr().getValueType();
8366 if (PtrType == MVT::Untyped || PtrType.isExtended())
8369 // 2. Check that it fits in the immediate.
8370 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8373 // 3. Check that the computation is legal.
8374 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8377 // Check that the zext is legal if it needs one.
8378 EVT TruncateType = Inst->getValueType(0);
8379 if (TruncateType != SliceType &&
8380 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8386 /// \brief Get the offset in bytes of this slice in the original chunk of
8388 /// \pre DAG != nullptr.
8389 uint64_t getOffsetFromBase() const {
8390 assert(DAG && "Missing context.");
8392 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8393 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8394 uint64_t Offset = Shift / 8;
8395 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8396 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8397 "The size of the original loaded type is not a multiple of a"
8399 // If Offset is bigger than TySizeInBytes, it means we are loading all
8400 // zeros. This should have been optimized before in the process.
8401 assert(TySizeInBytes > Offset &&
8402 "Invalid shift amount for given loaded size");
8404 Offset = TySizeInBytes - Offset - getLoadedSize();
8408 /// \brief Generate the sequence of instructions to load the slice
8409 /// represented by this object and redirect the uses of this slice to
8410 /// this new sequence of instructions.
8411 /// \pre this->Inst && this->Origin are valid Instructions and this
8412 /// object passed the legal check: LoadedSlice::isLegal returned true.
8413 /// \return The last instruction of the sequence used to load the slice.
8414 SDValue loadSlice() const {
8415 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8416 const SDValue &OldBaseAddr = Origin->getBasePtr();
8417 SDValue BaseAddr = OldBaseAddr;
8418 // Get the offset in that chunk of bytes w.r.t. the endianess.
8419 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8420 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8422 // BaseAddr = BaseAddr + Offset.
8423 EVT ArithType = BaseAddr.getValueType();
8424 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8425 DAG->getConstant(Offset, ArithType));
8428 // Create the type of the loaded slice according to its size.
8429 EVT SliceType = getLoadedType();
8431 // Create the load for the slice.
8432 SDValue LastInst = DAG->getLoad(
8433 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8434 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8435 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8436 // If the final type is not the same as the loaded type, this means that
8437 // we have to pad with zero. Create a zero extend for that.
8438 EVT FinalType = Inst->getValueType(0);
8439 if (SliceType != FinalType)
8441 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8445 /// \brief Check if this slice can be merged with an expensive cross register
8446 /// bank copy. E.g.,
8448 /// f = bitcast i32 i to float
8449 bool canMergeExpensiveCrossRegisterBankCopy() const {
8450 if (!Inst || !Inst->hasOneUse())
8452 SDNode *Use = *Inst->use_begin();
8453 if (Use->getOpcode() != ISD::BITCAST)
8455 assert(DAG && "Missing context");
8456 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8457 EVT ResVT = Use->getValueType(0);
8458 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8459 const TargetRegisterClass *ArgRC =
8460 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8461 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8464 // At this point, we know that we perform a cross-register-bank copy.
8465 // Check if it is expensive.
8466 const TargetRegisterInfo *TRI =
8467 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8468 // Assume bitcasts are cheap, unless both register classes do not
8469 // explicitly share a common sub class.
8470 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8473 // Check if it will be merged with the load.
8474 // 1. Check the alignment constraint.
8475 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8476 ResVT.getTypeForEVT(*DAG->getContext()));
8478 if (RequiredAlignment > getAlignment())
8481 // 2. Check that the load is a legal operation for that type.
8482 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8485 // 3. Check that we do not have a zext in the way.
8486 if (Inst->getValueType(0) != getLoadedType())
8494 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8495 /// \p UsedBits looks like 0..0 1..1 0..0.
8496 static bool areUsedBitsDense(const APInt &UsedBits) {
8497 // If all the bits are one, this is dense!
8498 if (UsedBits.isAllOnesValue())
8501 // Get rid of the unused bits on the right.
8502 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8503 // Get rid of the unused bits on the left.
8504 if (NarrowedUsedBits.countLeadingZeros())
8505 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8506 // Check that the chunk of bits is completely used.
8507 return NarrowedUsedBits.isAllOnesValue();
8510 /// \brief Check whether or not \p First and \p Second are next to each other
8511 /// in memory. This means that there is no hole between the bits loaded
8512 /// by \p First and the bits loaded by \p Second.
8513 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8514 const LoadedSlice &Second) {
8515 assert(First.Origin == Second.Origin && First.Origin &&
8516 "Unable to match different memory origins.");
8517 APInt UsedBits = First.getUsedBits();
8518 assert((UsedBits & Second.getUsedBits()) == 0 &&
8519 "Slices are not supposed to overlap.");
8520 UsedBits |= Second.getUsedBits();
8521 return areUsedBitsDense(UsedBits);
8524 /// \brief Adjust the \p GlobalLSCost according to the target
8525 /// paring capabilities and the layout of the slices.
8526 /// \pre \p GlobalLSCost should account for at least as many loads as
8527 /// there is in the slices in \p LoadedSlices.
8528 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8529 LoadedSlice::Cost &GlobalLSCost) {
8530 unsigned NumberOfSlices = LoadedSlices.size();
8531 // If there is less than 2 elements, no pairing is possible.
8532 if (NumberOfSlices < 2)
8535 // Sort the slices so that elements that are likely to be next to each
8536 // other in memory are next to each other in the list.
8537 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8538 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8539 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8540 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8542 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8543 // First (resp. Second) is the first (resp. Second) potentially candidate
8544 // to be placed in a paired load.
8545 const LoadedSlice *First = nullptr;
8546 const LoadedSlice *Second = nullptr;
8547 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8548 // Set the beginning of the pair.
8551 Second = &LoadedSlices[CurrSlice];
8553 // If First is NULL, it means we start a new pair.
8554 // Get to the next slice.
8558 EVT LoadedType = First->getLoadedType();
8560 // If the types of the slices are different, we cannot pair them.
8561 if (LoadedType != Second->getLoadedType())
8564 // Check if the target supplies paired loads for this type.
8565 unsigned RequiredAlignment = 0;
8566 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8567 // move to the next pair, this type is hopeless.
8571 // Check if we meet the alignment requirement.
8572 if (RequiredAlignment > First->getAlignment())
8575 // Check that both loads are next to each other in memory.
8576 if (!areSlicesNextToEachOther(*First, *Second))
8579 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8580 --GlobalLSCost.Loads;
8581 // Move to the next pair.
8586 /// \brief Check the profitability of all involved LoadedSlice.
8587 /// Currently, it is considered profitable if there is exactly two
8588 /// involved slices (1) which are (2) next to each other in memory, and
8589 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8591 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8592 /// the elements themselves.
8594 /// FIXME: When the cost model will be mature enough, we can relax
8595 /// constraints (1) and (2).
8596 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8597 const APInt &UsedBits, bool ForCodeSize) {
8598 unsigned NumberOfSlices = LoadedSlices.size();
8599 if (StressLoadSlicing)
8600 return NumberOfSlices > 1;
8603 if (NumberOfSlices != 2)
8607 if (!areUsedBitsDense(UsedBits))
8611 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8612 // The original code has one big load.
8614 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8615 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8616 // Accumulate the cost of all the slices.
8617 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8618 GlobalSlicingCost += SliceCost;
8620 // Account as cost in the original configuration the gain obtained
8621 // with the current slices.
8622 OrigCost.addSliceGain(LS);
8625 // If the target supports paired load, adjust the cost accordingly.
8626 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8627 return OrigCost > GlobalSlicingCost;
8630 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8631 /// operations, split it in the various pieces being extracted.
8633 /// This sort of thing is introduced by SROA.
8634 /// This slicing takes care not to insert overlapping loads.
8635 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8636 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8637 if (Level < AfterLegalizeDAG)
8640 LoadSDNode *LD = cast<LoadSDNode>(N);
8641 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8642 !LD->getValueType(0).isInteger())
8645 // Keep track of already used bits to detect overlapping values.
8646 // In that case, we will just abort the transformation.
8647 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8649 SmallVector<LoadedSlice, 4> LoadedSlices;
8651 // Check if this load is used as several smaller chunks of bits.
8652 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8653 // of computation for each trunc.
8654 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8655 UI != UIEnd; ++UI) {
8656 // Skip the uses of the chain.
8657 if (UI.getUse().getResNo() != 0)
8663 // Check if this is a trunc(lshr).
8664 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8665 isa<ConstantSDNode>(User->getOperand(1))) {
8666 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8667 User = *User->use_begin();
8670 // At this point, User is a Truncate, iff we encountered, trunc or
8672 if (User->getOpcode() != ISD::TRUNCATE)
8675 // The width of the type must be a power of 2 and greater than 8-bits.
8676 // Otherwise the load cannot be represented in LLVM IR.
8677 // Moreover, if we shifted with a non-8-bits multiple, the slice
8678 // will be across several bytes. We do not support that.
8679 unsigned Width = User->getValueSizeInBits(0);
8680 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8683 // Build the slice for this chain of computations.
8684 LoadedSlice LS(User, LD, Shift, &DAG);
8685 APInt CurrentUsedBits = LS.getUsedBits();
8687 // Check if this slice overlaps with another.
8688 if ((CurrentUsedBits & UsedBits) != 0)
8690 // Update the bits used globally.
8691 UsedBits |= CurrentUsedBits;
8693 // Check if the new slice would be legal.
8697 // Record the slice.
8698 LoadedSlices.push_back(LS);
8701 // Abort slicing if it does not seem to be profitable.
8702 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8707 // Rewrite each chain to use an independent load.
8708 // By construction, each chain can be represented by a unique load.
8710 // Prepare the argument for the new token factor for all the slices.
8711 SmallVector<SDValue, 8> ArgChains;
8712 for (SmallVectorImpl<LoadedSlice>::const_iterator
8713 LSIt = LoadedSlices.begin(),
8714 LSItEnd = LoadedSlices.end();
8715 LSIt != LSItEnd; ++LSIt) {
8716 SDValue SliceInst = LSIt->loadSlice();
8717 CombineTo(LSIt->Inst, SliceInst, true);
8718 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8719 SliceInst = SliceInst.getOperand(0);
8720 assert(SliceInst->getOpcode() == ISD::LOAD &&
8721 "It takes more than a zext to get to the loaded slice!!");
8722 ArgChains.push_back(SliceInst.getValue(1));
8725 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8727 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8731 /// Check to see if V is (and load (ptr), imm), where the load is having
8732 /// specific bytes cleared out. If so, return the byte size being masked out
8733 /// and the shift amount.
8734 static std::pair<unsigned, unsigned>
8735 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8736 std::pair<unsigned, unsigned> Result(0, 0);
8738 // Check for the structure we're looking for.
8739 if (V->getOpcode() != ISD::AND ||
8740 !isa<ConstantSDNode>(V->getOperand(1)) ||
8741 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8744 // Check the chain and pointer.
8745 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8746 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8748 // The store should be chained directly to the load or be an operand of a
8750 if (LD == Chain.getNode())
8752 else if (Chain->getOpcode() != ISD::TokenFactor)
8753 return Result; // Fail.
8756 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8757 if (Chain->getOperand(i).getNode() == LD) {
8761 if (!isOk) return Result;
8764 // This only handles simple types.
8765 if (V.getValueType() != MVT::i16 &&
8766 V.getValueType() != MVT::i32 &&
8767 V.getValueType() != MVT::i64)
8770 // Check the constant mask. Invert it so that the bits being masked out are
8771 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8772 // follow the sign bit for uniformity.
8773 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8774 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8775 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8776 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8777 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8778 if (NotMaskLZ == 64) return Result; // All zero mask.
8780 // See if we have a continuous run of bits. If so, we have 0*1+0*
8781 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8784 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8785 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8786 NotMaskLZ -= 64-V.getValueSizeInBits();
8788 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8789 switch (MaskedBytes) {
8793 default: return Result; // All one mask, or 5-byte mask.
8796 // Verify that the first bit starts at a multiple of mask so that the access
8797 // is aligned the same as the access width.
8798 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8800 Result.first = MaskedBytes;
8801 Result.second = NotMaskTZ/8;
8806 /// Check to see if IVal is something that provides a value as specified by
8807 /// MaskInfo. If so, replace the specified store with a narrower store of
8810 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8811 SDValue IVal, StoreSDNode *St,
8813 unsigned NumBytes = MaskInfo.first;
8814 unsigned ByteShift = MaskInfo.second;
8815 SelectionDAG &DAG = DC->getDAG();
8817 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8818 // that uses this. If not, this is not a replacement.
8819 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8820 ByteShift*8, (ByteShift+NumBytes)*8);
8821 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8823 // Check that it is legal on the target to do this. It is legal if the new
8824 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8826 MVT VT = MVT::getIntegerVT(NumBytes*8);
8827 if (!DC->isTypeLegal(VT))
8830 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8831 // shifted by ByteShift and truncated down to NumBytes.
8833 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8834 DAG.getConstant(ByteShift*8,
8835 DC->getShiftAmountTy(IVal.getValueType())));
8837 // Figure out the offset for the store and the alignment of the access.
8839 unsigned NewAlign = St->getAlignment();
8841 if (DAG.getTargetLoweringInfo().isLittleEndian())
8842 StOffset = ByteShift;
8844 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8846 SDValue Ptr = St->getBasePtr();
8848 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8849 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8850 NewAlign = MinAlign(NewAlign, StOffset);
8853 // Truncate down to the new size.
8854 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8857 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8858 St->getPointerInfo().getWithOffset(StOffset),
8859 false, false, NewAlign).getNode();
8863 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8864 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8865 /// narrowing the load and store if it would end up being a win for performance
8867 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8868 StoreSDNode *ST = cast<StoreSDNode>(N);
8869 if (ST->isVolatile())
8872 SDValue Chain = ST->getChain();
8873 SDValue Value = ST->getValue();
8874 SDValue Ptr = ST->getBasePtr();
8875 EVT VT = Value.getValueType();
8877 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8880 unsigned Opc = Value.getOpcode();
8882 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8883 // is a byte mask indicating a consecutive number of bytes, check to see if
8884 // Y is known to provide just those bytes. If so, we try to replace the
8885 // load + replace + store sequence with a single (narrower) store, which makes
8887 if (Opc == ISD::OR) {
8888 std::pair<unsigned, unsigned> MaskedLoad;
8889 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8890 if (MaskedLoad.first)
8891 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8892 Value.getOperand(1), ST,this))
8893 return SDValue(NewST, 0);
8895 // Or is commutative, so try swapping X and Y.
8896 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8897 if (MaskedLoad.first)
8898 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8899 Value.getOperand(0), ST,this))
8900 return SDValue(NewST, 0);
8903 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8904 Value.getOperand(1).getOpcode() != ISD::Constant)
8907 SDValue N0 = Value.getOperand(0);
8908 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8909 Chain == SDValue(N0.getNode(), 1)) {
8910 LoadSDNode *LD = cast<LoadSDNode>(N0);
8911 if (LD->getBasePtr() != Ptr ||
8912 LD->getPointerInfo().getAddrSpace() !=
8913 ST->getPointerInfo().getAddrSpace())
8916 // Find the type to narrow it the load / op / store to.
8917 SDValue N1 = Value.getOperand(1);
8918 unsigned BitWidth = N1.getValueSizeInBits();
8919 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8920 if (Opc == ISD::AND)
8921 Imm ^= APInt::getAllOnesValue(BitWidth);
8922 if (Imm == 0 || Imm.isAllOnesValue())
8924 unsigned ShAmt = Imm.countTrailingZeros();
8925 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8926 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8927 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8928 while (NewBW < BitWidth &&
8929 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8930 TLI.isNarrowingProfitable(VT, NewVT))) {
8931 NewBW = NextPowerOf2(NewBW);
8932 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8934 if (NewBW >= BitWidth)
8937 // If the lsb changed does not start at the type bitwidth boundary,
8938 // start at the previous one.
8940 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8941 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8942 std::min(BitWidth, ShAmt + NewBW));
8943 if ((Imm & Mask) == Imm) {
8944 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8945 if (Opc == ISD::AND)
8946 NewImm ^= APInt::getAllOnesValue(NewBW);
8947 uint64_t PtrOff = ShAmt / 8;
8948 // For big endian targets, we need to adjust the offset to the pointer to
8949 // load the correct bytes.
8950 if (TLI.isBigEndian())
8951 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8953 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8954 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8955 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8958 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8959 Ptr.getValueType(), Ptr,
8960 DAG.getConstant(PtrOff, Ptr.getValueType()));
8961 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8962 LD->getChain(), NewPtr,
8963 LD->getPointerInfo().getWithOffset(PtrOff),
8964 LD->isVolatile(), LD->isNonTemporal(),
8965 LD->isInvariant(), NewAlign,
8967 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8968 DAG.getConstant(NewImm, NewVT));
8969 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8971 ST->getPointerInfo().getWithOffset(PtrOff),
8972 false, false, NewAlign);
8974 AddToWorklist(NewPtr.getNode());
8975 AddToWorklist(NewLD.getNode());
8976 AddToWorklist(NewVal.getNode());
8977 WorklistRemover DeadNodes(*this);
8978 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8987 /// For a given floating point load / store pair, if the load value isn't used
8988 /// by any other operations, then consider transforming the pair to integer
8989 /// load / store operations if the target deems the transformation profitable.
8990 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8991 StoreSDNode *ST = cast<StoreSDNode>(N);
8992 SDValue Chain = ST->getChain();
8993 SDValue Value = ST->getValue();
8994 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8995 Value.hasOneUse() &&
8996 Chain == SDValue(Value.getNode(), 1)) {
8997 LoadSDNode *LD = cast<LoadSDNode>(Value);
8998 EVT VT = LD->getMemoryVT();
8999 if (!VT.isFloatingPoint() ||
9000 VT != ST->getMemoryVT() ||
9001 LD->isNonTemporal() ||
9002 ST->isNonTemporal() ||
9003 LD->getPointerInfo().getAddrSpace() != 0 ||
9004 ST->getPointerInfo().getAddrSpace() != 0)
9007 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9008 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9009 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9010 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9011 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9014 unsigned LDAlign = LD->getAlignment();
9015 unsigned STAlign = ST->getAlignment();
9016 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9017 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9018 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9021 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9022 LD->getChain(), LD->getBasePtr(),
9023 LD->getPointerInfo(),
9024 false, false, false, LDAlign);
9026 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9027 NewLD, ST->getBasePtr(),
9028 ST->getPointerInfo(),
9029 false, false, STAlign);
9031 AddToWorklist(NewLD.getNode());
9032 AddToWorklist(NewST.getNode());
9033 WorklistRemover DeadNodes(*this);
9034 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9042 /// Helper struct to parse and store a memory address as base + index + offset.
9043 /// We ignore sign extensions when it is safe to do so.
9044 /// The following two expressions are not equivalent. To differentiate we need
9045 /// to store whether there was a sign extension involved in the index
9047 /// (load (i64 add (i64 copyfromreg %c)
9048 /// (i64 signextend (add (i8 load %index)
9052 /// (load (i64 add (i64 copyfromreg %c)
9053 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9055 struct BaseIndexOffset {
9059 bool IsIndexSignExt;
9061 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9063 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9064 bool IsIndexSignExt) :
9065 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9067 bool equalBaseIndex(const BaseIndexOffset &Other) {
9068 return Other.Base == Base && Other.Index == Index &&
9069 Other.IsIndexSignExt == IsIndexSignExt;
9072 /// Parses tree in Ptr for base, index, offset addresses.
9073 static BaseIndexOffset match(SDValue Ptr) {
9074 bool IsIndexSignExt = false;
9076 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9077 // instruction, then it could be just the BASE or everything else we don't
9078 // know how to handle. Just use Ptr as BASE and give up.
9079 if (Ptr->getOpcode() != ISD::ADD)
9080 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9082 // We know that we have at least an ADD instruction. Try to pattern match
9083 // the simple case of BASE + OFFSET.
9084 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9085 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9086 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9090 // Inside a loop the current BASE pointer is calculated using an ADD and a
9091 // MUL instruction. In this case Ptr is the actual BASE pointer.
9092 // (i64 add (i64 %array_ptr)
9093 // (i64 mul (i64 %induction_var)
9094 // (i64 %element_size)))
9095 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9096 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9098 // Look at Base + Index + Offset cases.
9099 SDValue Base = Ptr->getOperand(0);
9100 SDValue IndexOffset = Ptr->getOperand(1);
9102 // Skip signextends.
9103 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9104 IndexOffset = IndexOffset->getOperand(0);
9105 IsIndexSignExt = true;
9108 // Either the case of Base + Index (no offset) or something else.
9109 if (IndexOffset->getOpcode() != ISD::ADD)
9110 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9112 // Now we have the case of Base + Index + offset.
9113 SDValue Index = IndexOffset->getOperand(0);
9114 SDValue Offset = IndexOffset->getOperand(1);
9116 if (!isa<ConstantSDNode>(Offset))
9117 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9119 // Ignore signextends.
9120 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9121 Index = Index->getOperand(0);
9122 IsIndexSignExt = true;
9123 } else IsIndexSignExt = false;
9125 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9126 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9130 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9131 /// is located in a sequence of memory operations connected by a chain.
9133 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9134 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9135 // Ptr to the mem node.
9136 LSBaseSDNode *MemNode;
9137 // Offset from the base ptr.
9138 int64_t OffsetFromBase;
9139 // What is the sequence number of this mem node.
9140 // Lowest mem operand in the DAG starts at zero.
9141 unsigned SequenceNum;
9144 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9145 EVT MemVT = St->getMemoryVT();
9146 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9147 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9148 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9150 // Don't merge vectors into wider inputs.
9151 if (MemVT.isVector() || !MemVT.isSimple())
9154 // Perform an early exit check. Do not bother looking at stored values that
9155 // are not constants or loads.
9156 SDValue StoredVal = St->getValue();
9157 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9158 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9162 // Only look at ends of store sequences.
9163 SDValue Chain = SDValue(St, 0);
9164 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9167 // This holds the base pointer, index, and the offset in bytes from the base
9169 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9171 // We must have a base and an offset.
9172 if (!BasePtr.Base.getNode())
9175 // Do not handle stores to undef base pointers.
9176 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9179 // Save the LoadSDNodes that we find in the chain.
9180 // We need to make sure that these nodes do not interfere with
9181 // any of the store nodes.
9182 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9184 // Save the StoreSDNodes that we find in the chain.
9185 SmallVector<MemOpLink, 8> StoreNodes;
9187 // Walk up the chain and look for nodes with offsets from the same
9188 // base pointer. Stop when reaching an instruction with a different kind
9189 // or instruction which has a different base pointer.
9191 StoreSDNode *Index = St;
9193 // If the chain has more than one use, then we can't reorder the mem ops.
9194 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9197 // Find the base pointer and offset for this memory node.
9198 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9200 // Check that the base pointer is the same as the original one.
9201 if (!Ptr.equalBaseIndex(BasePtr))
9204 // Check that the alignment is the same.
9205 if (Index->getAlignment() != St->getAlignment())
9208 // The memory operands must not be volatile.
9209 if (Index->isVolatile() || Index->isIndexed())
9213 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9214 if (St->isTruncatingStore())
9217 // The stored memory type must be the same.
9218 if (Index->getMemoryVT() != MemVT)
9221 // We do not allow unaligned stores because we want to prevent overriding
9223 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9226 // We found a potential memory operand to merge.
9227 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9229 // Find the next memory operand in the chain. If the next operand in the
9230 // chain is a store then move up and continue the scan with the next
9231 // memory operand. If the next operand is a load save it and use alias
9232 // information to check if it interferes with anything.
9233 SDNode *NextInChain = Index->getChain().getNode();
9235 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9236 // We found a store node. Use it for the next iteration.
9239 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9240 if (Ldn->isVolatile()) {
9245 // Save the load node for later. Continue the scan.
9246 AliasLoadNodes.push_back(Ldn);
9247 NextInChain = Ldn->getChain().getNode();
9256 // Check if there is anything to merge.
9257 if (StoreNodes.size() < 2)
9260 // Sort the memory operands according to their distance from the base pointer.
9261 std::sort(StoreNodes.begin(), StoreNodes.end(),
9262 [](MemOpLink LHS, MemOpLink RHS) {
9263 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9264 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9265 LHS.SequenceNum > RHS.SequenceNum);
9268 // Scan the memory operations on the chain and find the first non-consecutive
9269 // store memory address.
9270 unsigned LastConsecutiveStore = 0;
9271 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9272 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9274 // Check that the addresses are consecutive starting from the second
9275 // element in the list of stores.
9277 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9278 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9283 // Check if this store interferes with any of the loads that we found.
9284 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9285 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9289 // We found a load that alias with this store. Stop the sequence.
9293 // Mark this node as useful.
9294 LastConsecutiveStore = i;
9297 // The node with the lowest store address.
9298 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9300 // Store the constants into memory as one consecutive store.
9302 unsigned LastLegalType = 0;
9303 unsigned LastLegalVectorType = 0;
9304 bool NonZero = false;
9305 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9306 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9307 SDValue StoredVal = St->getValue();
9309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9310 NonZero |= !C->isNullValue();
9311 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9312 NonZero |= !C->getConstantFPValue()->isNullValue();
9318 // Find a legal type for the constant store.
9319 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9320 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9321 if (TLI.isTypeLegal(StoreTy))
9322 LastLegalType = i+1;
9323 // Or check whether a truncstore is legal.
9324 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9325 TargetLowering::TypePromoteInteger) {
9326 EVT LegalizedStoredValueTy =
9327 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9328 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9329 LastLegalType = i+1;
9332 // Find a legal type for the vector store.
9333 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9334 if (TLI.isTypeLegal(Ty))
9335 LastLegalVectorType = i + 1;
9338 // We only use vectors if the constant is known to be zero and the
9339 // function is not marked with the noimplicitfloat attribute.
9340 if (NonZero || NoVectors)
9341 LastLegalVectorType = 0;
9343 // Check if we found a legal integer type to store.
9344 if (LastLegalType == 0 && LastLegalVectorType == 0)
9347 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9348 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9350 // Make sure we have something to merge.
9354 unsigned EarliestNodeUsed = 0;
9355 for (unsigned i=0; i < NumElem; ++i) {
9356 // Find a chain for the new wide-store operand. Notice that some
9357 // of the store nodes that we found may not be selected for inclusion
9358 // in the wide store. The chain we use needs to be the chain of the
9359 // earliest store node which is *used* and replaced by the wide store.
9360 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9361 EarliestNodeUsed = i;
9364 // The earliest Node in the DAG.
9365 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9366 SDLoc DL(StoreNodes[0].MemNode);
9370 // Find a legal type for the vector store.
9371 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9372 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9373 StoredVal = DAG.getConstant(0, Ty);
9375 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9376 APInt StoreInt(StoreBW, 0);
9378 // Construct a single integer constant which is made of the smaller
9380 bool IsLE = TLI.isLittleEndian();
9381 for (unsigned i = 0; i < NumElem ; ++i) {
9382 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9383 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9384 SDValue Val = St->getValue();
9385 StoreInt<<=ElementSizeBytes*8;
9386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9387 StoreInt|=C->getAPIntValue().zext(StoreBW);
9388 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9389 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9391 assert(false && "Invalid constant element type");
9395 // Create the new Load and Store operations.
9396 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9397 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9400 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9401 FirstInChain->getBasePtr(),
9402 FirstInChain->getPointerInfo(),
9404 FirstInChain->getAlignment());
9406 // Replace the first store with the new store
9407 CombineTo(EarliestOp, NewStore);
9408 // Erase all other stores.
9409 for (unsigned i = 0; i < NumElem ; ++i) {
9410 if (StoreNodes[i].MemNode == EarliestOp)
9412 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9413 // ReplaceAllUsesWith will replace all uses that existed when it was
9414 // called, but graph optimizations may cause new ones to appear. For
9415 // example, the case in pr14333 looks like
9417 // St's chain -> St -> another store -> X
9419 // And the only difference from St to the other store is the chain.
9420 // When we change it's chain to be St's chain they become identical,
9421 // get CSEed and the net result is that X is now a use of St.
9422 // Since we know that St is redundant, just iterate.
9423 while (!St->use_empty())
9424 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9425 deleteAndRecombine(St);
9431 // Below we handle the case of multiple consecutive stores that
9432 // come from multiple consecutive loads. We merge them into a single
9433 // wide load and a single wide store.
9435 // Look for load nodes which are used by the stored values.
9436 SmallVector<MemOpLink, 8> LoadNodes;
9438 // Find acceptable loads. Loads need to have the same chain (token factor),
9439 // must not be zext, volatile, indexed, and they must be consecutive.
9440 BaseIndexOffset LdBasePtr;
9441 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9442 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9443 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9446 // Loads must only have one use.
9447 if (!Ld->hasNUsesOfValue(1, 0))
9450 // Check that the alignment is the same as the stores.
9451 if (Ld->getAlignment() != St->getAlignment())
9454 // The memory operands must not be volatile.
9455 if (Ld->isVolatile() || Ld->isIndexed())
9458 // We do not accept ext loads.
9459 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9462 // The stored memory type must be the same.
9463 if (Ld->getMemoryVT() != MemVT)
9466 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9467 // If this is not the first ptr that we check.
9468 if (LdBasePtr.Base.getNode()) {
9469 // The base ptr must be the same.
9470 if (!LdPtr.equalBaseIndex(LdBasePtr))
9473 // Check that all other base pointers are the same as this one.
9477 // We found a potential memory operand to merge.
9478 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9481 if (LoadNodes.size() < 2)
9484 // If we have load/store pair instructions and we only have two values,
9486 unsigned RequiredAlignment;
9487 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9488 St->getAlignment() >= RequiredAlignment)
9491 // Scan the memory operations on the chain and find the first non-consecutive
9492 // load memory address. These variables hold the index in the store node
9494 unsigned LastConsecutiveLoad = 0;
9495 // This variable refers to the size and not index in the array.
9496 unsigned LastLegalVectorType = 0;
9497 unsigned LastLegalIntegerType = 0;
9498 StartAddress = LoadNodes[0].OffsetFromBase;
9499 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9500 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9501 // All loads much share the same chain.
9502 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9505 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9506 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9508 LastConsecutiveLoad = i;
9510 // Find a legal type for the vector store.
9511 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9512 if (TLI.isTypeLegal(StoreTy))
9513 LastLegalVectorType = i + 1;
9515 // Find a legal type for the integer store.
9516 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9517 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9518 if (TLI.isTypeLegal(StoreTy))
9519 LastLegalIntegerType = i + 1;
9520 // Or check whether a truncstore and extload is legal.
9521 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9522 TargetLowering::TypePromoteInteger) {
9523 EVT LegalizedStoredValueTy =
9524 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9525 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9526 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9527 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9528 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9529 LastLegalIntegerType = i+1;
9533 // Only use vector types if the vector type is larger than the integer type.
9534 // If they are the same, use integers.
9535 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9536 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9538 // We add +1 here because the LastXXX variables refer to location while
9539 // the NumElem refers to array/index size.
9540 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9541 NumElem = std::min(LastLegalType, NumElem);
9546 // The earliest Node in the DAG.
9547 unsigned EarliestNodeUsed = 0;
9548 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9549 for (unsigned i=1; i<NumElem; ++i) {
9550 // Find a chain for the new wide-store operand. Notice that some
9551 // of the store nodes that we found may not be selected for inclusion
9552 // in the wide store. The chain we use needs to be the chain of the
9553 // earliest store node which is *used* and replaced by the wide store.
9554 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9555 EarliestNodeUsed = i;
9558 // Find if it is better to use vectors or integers to load and store
9562 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9564 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9565 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9568 SDLoc LoadDL(LoadNodes[0].MemNode);
9569 SDLoc StoreDL(StoreNodes[0].MemNode);
9571 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9572 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9573 FirstLoad->getChain(),
9574 FirstLoad->getBasePtr(),
9575 FirstLoad->getPointerInfo(),
9576 false, false, false,
9577 FirstLoad->getAlignment());
9579 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9580 FirstInChain->getBasePtr(),
9581 FirstInChain->getPointerInfo(), false, false,
9582 FirstInChain->getAlignment());
9584 // Replace one of the loads with the new load.
9585 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9586 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9587 SDValue(NewLoad.getNode(), 1));
9589 // Remove the rest of the load chains.
9590 for (unsigned i = 1; i < NumElem ; ++i) {
9591 // Replace all chain users of the old load nodes with the chain of the new
9593 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9594 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9597 // Replace the first store with the new store.
9598 CombineTo(EarliestOp, NewStore);
9599 // Erase all other stores.
9600 for (unsigned i = 0; i < NumElem ; ++i) {
9601 // Remove all Store nodes.
9602 if (StoreNodes[i].MemNode == EarliestOp)
9604 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9605 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9606 deleteAndRecombine(St);
9612 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9613 StoreSDNode *ST = cast<StoreSDNode>(N);
9614 SDValue Chain = ST->getChain();
9615 SDValue Value = ST->getValue();
9616 SDValue Ptr = ST->getBasePtr();
9618 // If this is a store of a bit convert, store the input value if the
9619 // resultant store does not need a higher alignment than the original.
9620 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9621 ST->isUnindexed()) {
9622 unsigned OrigAlign = ST->getAlignment();
9623 EVT SVT = Value.getOperand(0).getValueType();
9624 unsigned Align = TLI.getDataLayout()->
9625 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9626 if (Align <= OrigAlign &&
9627 ((!LegalOperations && !ST->isVolatile()) ||
9628 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9629 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9630 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9631 ST->isNonTemporal(), OrigAlign,
9635 // Turn 'store undef, Ptr' -> nothing.
9636 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9639 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9640 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9641 // NOTE: If the original store is volatile, this transform must not increase
9642 // the number of stores. For example, on x86-32 an f64 can be stored in one
9643 // processor operation but an i64 (which is not legal) requires two. So the
9644 // transform should not be done in this case.
9645 if (Value.getOpcode() != ISD::TargetConstantFP) {
9647 switch (CFP->getSimpleValueType(0).SimpleTy) {
9648 default: llvm_unreachable("Unknown FP type");
9649 case MVT::f16: // We don't do this for these yet.
9655 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9656 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9657 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9658 bitcastToAPInt().getZExtValue(), MVT::i32);
9659 return DAG.getStore(Chain, SDLoc(N), Tmp,
9660 Ptr, ST->getMemOperand());
9664 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9665 !ST->isVolatile()) ||
9666 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9667 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9668 getZExtValue(), MVT::i64);
9669 return DAG.getStore(Chain, SDLoc(N), Tmp,
9670 Ptr, ST->getMemOperand());
9673 if (!ST->isVolatile() &&
9674 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9675 // Many FP stores are not made apparent until after legalize, e.g. for
9676 // argument passing. Since this is so common, custom legalize the
9677 // 64-bit integer store into two 32-bit stores.
9678 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9679 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9680 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9681 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9683 unsigned Alignment = ST->getAlignment();
9684 bool isVolatile = ST->isVolatile();
9685 bool isNonTemporal = ST->isNonTemporal();
9686 AAMDNodes AAInfo = ST->getAAInfo();
9688 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9689 Ptr, ST->getPointerInfo(),
9690 isVolatile, isNonTemporal,
9691 ST->getAlignment(), AAInfo);
9692 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9693 DAG.getConstant(4, Ptr.getValueType()));
9694 Alignment = MinAlign(Alignment, 4U);
9695 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9696 Ptr, ST->getPointerInfo().getWithOffset(4),
9697 isVolatile, isNonTemporal,
9699 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9708 // Try to infer better alignment information than the store already has.
9709 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9710 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9711 if (Align > ST->getAlignment())
9712 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9713 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9714 ST->isVolatile(), ST->isNonTemporal(), Align,
9719 // Try transforming a pair floating point load / store ops to integer
9720 // load / store ops.
9721 SDValue NewST = TransformFPLoadStorePair(N);
9722 if (NewST.getNode())
9725 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9726 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9728 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9729 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9732 if (UseAA && ST->isUnindexed()) {
9733 // Walk up chain skipping non-aliasing memory nodes.
9734 SDValue BetterChain = FindBetterChain(N, Chain);
9736 // If there is a better chain.
9737 if (Chain != BetterChain) {
9740 // Replace the chain to avoid dependency.
9741 if (ST->isTruncatingStore()) {
9742 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9743 ST->getMemoryVT(), ST->getMemOperand());
9745 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9746 ST->getMemOperand());
9749 // Create token to keep both nodes around.
9750 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9751 MVT::Other, Chain, ReplStore);
9753 // Make sure the new and old chains are cleaned up.
9754 AddToWorklist(Token.getNode());
9756 // Don't add users to work list.
9757 return CombineTo(N, Token, false);
9761 // Try transforming N to an indexed store.
9762 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9763 return SDValue(N, 0);
9765 // FIXME: is there such a thing as a truncating indexed store?
9766 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9767 Value.getValueType().isInteger()) {
9768 // See if we can simplify the input to this truncstore with knowledge that
9769 // only the low bits are being used. For example:
9770 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9772 GetDemandedBits(Value,
9773 APInt::getLowBitsSet(
9774 Value.getValueType().getScalarType().getSizeInBits(),
9775 ST->getMemoryVT().getScalarType().getSizeInBits()));
9776 AddToWorklist(Value.getNode());
9777 if (Shorter.getNode())
9778 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9779 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9781 // Otherwise, see if we can simplify the operation with
9782 // SimplifyDemandedBits, which only works if the value has a single use.
9783 if (SimplifyDemandedBits(Value,
9784 APInt::getLowBitsSet(
9785 Value.getValueType().getScalarType().getSizeInBits(),
9786 ST->getMemoryVT().getScalarType().getSizeInBits())))
9787 return SDValue(N, 0);
9790 // If this is a load followed by a store to the same location, then the store
9792 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9793 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9794 ST->isUnindexed() && !ST->isVolatile() &&
9795 // There can't be any side effects between the load and store, such as
9797 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9798 // The store is dead, remove it.
9802 // If this is a store followed by a store with the same value to the same
9803 // location, then the store is dead/noop.
9804 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9805 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9806 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9807 ST1->isUnindexed() &&
9808 !ST1->isVolatile() &&
9809 // There can't be any side effects between the two stores, such as
9811 Chain.reachesChainWithoutSideEffects(SDValue(ST1, 0))) {
9812 // The store is dead, remove it.
9817 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9818 // truncating store. We can do this even if this is already a truncstore.
9819 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9820 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9821 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9822 ST->getMemoryVT())) {
9823 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9824 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9827 // Only perform this optimization before the types are legal, because we
9828 // don't want to perform this optimization on every DAGCombine invocation.
9830 bool EverChanged = false;
9833 // There can be multiple store sequences on the same chain.
9834 // Keep trying to merge store sequences until we are unable to do so
9835 // or until we merge the last store on the chain.
9836 bool Changed = MergeConsecutiveStores(ST);
9837 EverChanged |= Changed;
9838 if (!Changed) break;
9839 } while (ST->getOpcode() != ISD::DELETED_NODE);
9842 return SDValue(N, 0);
9845 return ReduceLoadOpStoreWidth(N);
9848 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9849 SDValue InVec = N->getOperand(0);
9850 SDValue InVal = N->getOperand(1);
9851 SDValue EltNo = N->getOperand(2);
9854 // If the inserted element is an UNDEF, just use the input vector.
9855 if (InVal.getOpcode() == ISD::UNDEF)
9858 EVT VT = InVec.getValueType();
9860 // If we can't generate a legal BUILD_VECTOR, exit
9861 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9864 // Check that we know which element is being inserted
9865 if (!isa<ConstantSDNode>(EltNo))
9867 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9869 // Canonicalize insert_vector_elt dag nodes.
9871 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9872 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9874 // Do this only if the child insert_vector node has one use; also
9875 // do this only if indices are both constants and Idx1 < Idx0.
9876 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9877 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9879 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9880 if (Elt < OtherElt) {
9882 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9883 InVec.getOperand(0), InVal, EltNo);
9884 AddToWorklist(NewOp.getNode());
9885 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9886 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9890 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9891 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9893 SmallVector<SDValue, 8> Ops;
9894 // Do not combine these two vectors if the output vector will not replace
9895 // the input vector.
9896 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9897 Ops.append(InVec.getNode()->op_begin(),
9898 InVec.getNode()->op_end());
9899 } else if (InVec.getOpcode() == ISD::UNDEF) {
9900 unsigned NElts = VT.getVectorNumElements();
9901 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9906 // Insert the element
9907 if (Elt < Ops.size()) {
9908 // All the operands of BUILD_VECTOR must have the same type;
9909 // we enforce that here.
9910 EVT OpVT = Ops[0].getValueType();
9911 if (InVal.getValueType() != OpVT)
9912 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9913 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9914 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9918 // Return the new vector
9919 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9922 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9923 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9924 EVT ResultVT = EVE->getValueType(0);
9925 EVT VecEltVT = InVecVT.getVectorElementType();
9926 unsigned Align = OriginalLoad->getAlignment();
9927 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9928 VecEltVT.getTypeForEVT(*DAG.getContext()));
9930 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9935 SDValue NewPtr = OriginalLoad->getBasePtr();
9937 EVT PtrType = NewPtr.getValueType();
9938 MachinePointerInfo MPI;
9939 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9940 int Elt = ConstEltNo->getZExtValue();
9941 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9942 if (TLI.isBigEndian())
9943 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9944 Offset = DAG.getConstant(PtrOff, PtrType);
9945 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9947 Offset = DAG.getNode(
9948 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9949 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9950 if (TLI.isBigEndian())
9951 Offset = DAG.getNode(
9952 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9953 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9954 MPI = OriginalLoad->getPointerInfo();
9956 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9958 // The replacement we need to do here is a little tricky: we need to
9959 // replace an extractelement of a load with a load.
9960 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9961 // Note that this replacement assumes that the extractvalue is the only
9962 // use of the load; that's okay because we don't want to perform this
9963 // transformation in other cases anyway.
9966 if (ResultVT.bitsGT(VecEltVT)) {
9967 // If the result type of vextract is wider than the load, then issue an
9968 // extending load instead.
9969 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9972 Load = DAG.getExtLoad(
9973 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9974 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9975 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9976 Chain = Load.getValue(1);
9979 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9980 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9981 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9982 Chain = Load.getValue(1);
9983 if (ResultVT.bitsLT(VecEltVT))
9984 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9986 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9988 WorklistRemover DeadNodes(*this);
9989 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9990 SDValue To[] = { Load, Chain };
9991 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9992 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9993 // worklist explicitly as well.
9994 AddToWorklist(Load.getNode());
9995 AddUsersToWorklist(Load.getNode()); // Add users too
9996 // Make sure to revisit this node to clean it up; it will usually be dead.
9999 return SDValue(EVE, 0);
10002 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10003 // (vextract (scalar_to_vector val, 0) -> val
10004 SDValue InVec = N->getOperand(0);
10005 EVT VT = InVec.getValueType();
10006 EVT NVT = N->getValueType(0);
10008 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10009 // Check if the result type doesn't match the inserted element type. A
10010 // SCALAR_TO_VECTOR may truncate the inserted element and the
10011 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10012 SDValue InOp = InVec.getOperand(0);
10013 if (InOp.getValueType() != NVT) {
10014 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10015 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10020 SDValue EltNo = N->getOperand(1);
10021 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10023 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10024 // We only perform this optimization before the op legalization phase because
10025 // we may introduce new vector instructions which are not backed by TD
10026 // patterns. For example on AVX, extracting elements from a wide vector
10027 // without using extract_subvector. However, if we can find an underlying
10028 // scalar value, then we can always use that.
10029 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10031 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10032 int NumElem = VT.getVectorNumElements();
10033 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10034 // Find the new index to extract from.
10035 int OrigElt = SVOp->getMaskElt(Elt);
10037 // Extracting an undef index is undef.
10039 return DAG.getUNDEF(NVT);
10041 // Select the right vector half to extract from.
10043 if (OrigElt < NumElem) {
10044 SVInVec = InVec->getOperand(0);
10046 SVInVec = InVec->getOperand(1);
10047 OrigElt -= NumElem;
10050 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10051 SDValue InOp = SVInVec.getOperand(OrigElt);
10052 if (InOp.getValueType() != NVT) {
10053 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10054 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10060 // FIXME: We should handle recursing on other vector shuffles and
10061 // scalar_to_vector here as well.
10063 if (!LegalOperations) {
10064 EVT IndexTy = TLI.getVectorIdxTy();
10065 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10066 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10070 bool BCNumEltsChanged = false;
10071 EVT ExtVT = VT.getVectorElementType();
10074 // If the result of load has to be truncated, then it's not necessarily
10076 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10079 if (InVec.getOpcode() == ISD::BITCAST) {
10080 // Don't duplicate a load with other uses.
10081 if (!InVec.hasOneUse())
10084 EVT BCVT = InVec.getOperand(0).getValueType();
10085 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10087 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10088 BCNumEltsChanged = true;
10089 InVec = InVec.getOperand(0);
10090 ExtVT = BCVT.getVectorElementType();
10093 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10094 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10095 ISD::isNormalLoad(InVec.getNode()) &&
10096 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10097 SDValue Index = N->getOperand(1);
10098 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10099 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10103 // Perform only after legalization to ensure build_vector / vector_shuffle
10104 // optimizations have already been done.
10105 if (!LegalOperations) return SDValue();
10107 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10108 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10109 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10112 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10114 LoadSDNode *LN0 = nullptr;
10115 const ShuffleVectorSDNode *SVN = nullptr;
10116 if (ISD::isNormalLoad(InVec.getNode())) {
10117 LN0 = cast<LoadSDNode>(InVec);
10118 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10119 InVec.getOperand(0).getValueType() == ExtVT &&
10120 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10121 // Don't duplicate a load with other uses.
10122 if (!InVec.hasOneUse())
10125 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10126 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10127 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10129 // (load $addr+1*size)
10131 // Don't duplicate a load with other uses.
10132 if (!InVec.hasOneUse())
10135 // If the bit convert changed the number of elements, it is unsafe
10136 // to examine the mask.
10137 if (BCNumEltsChanged)
10140 // Select the input vector, guarding against out of range extract vector.
10141 unsigned NumElems = VT.getVectorNumElements();
10142 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10143 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10145 if (InVec.getOpcode() == ISD::BITCAST) {
10146 // Don't duplicate a load with other uses.
10147 if (!InVec.hasOneUse())
10150 InVec = InVec.getOperand(0);
10152 if (ISD::isNormalLoad(InVec.getNode())) {
10153 LN0 = cast<LoadSDNode>(InVec);
10154 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10155 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10159 // Make sure we found a non-volatile load and the extractelement is
10161 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10164 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10166 return DAG.getUNDEF(LVT);
10168 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10174 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10175 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10176 // We perform this optimization post type-legalization because
10177 // the type-legalizer often scalarizes integer-promoted vectors.
10178 // Performing this optimization before may create bit-casts which
10179 // will be type-legalized to complex code sequences.
10180 // We perform this optimization only before the operation legalizer because we
10181 // may introduce illegal operations.
10182 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10185 unsigned NumInScalars = N->getNumOperands();
10187 EVT VT = N->getValueType(0);
10189 // Check to see if this is a BUILD_VECTOR of a bunch of values
10190 // which come from any_extend or zero_extend nodes. If so, we can create
10191 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10192 // optimizations. We do not handle sign-extend because we can't fill the sign
10194 EVT SourceType = MVT::Other;
10195 bool AllAnyExt = true;
10197 for (unsigned i = 0; i != NumInScalars; ++i) {
10198 SDValue In = N->getOperand(i);
10199 // Ignore undef inputs.
10200 if (In.getOpcode() == ISD::UNDEF) continue;
10202 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10203 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10205 // Abort if the element is not an extension.
10206 if (!ZeroExt && !AnyExt) {
10207 SourceType = MVT::Other;
10211 // The input is a ZeroExt or AnyExt. Check the original type.
10212 EVT InTy = In.getOperand(0).getValueType();
10214 // Check that all of the widened source types are the same.
10215 if (SourceType == MVT::Other)
10218 else if (InTy != SourceType) {
10219 // Multiple income types. Abort.
10220 SourceType = MVT::Other;
10224 // Check if all of the extends are ANY_EXTENDs.
10225 AllAnyExt &= AnyExt;
10228 // In order to have valid types, all of the inputs must be extended from the
10229 // same source type and all of the inputs must be any or zero extend.
10230 // Scalar sizes must be a power of two.
10231 EVT OutScalarTy = VT.getScalarType();
10232 bool ValidTypes = SourceType != MVT::Other &&
10233 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10234 isPowerOf2_32(SourceType.getSizeInBits());
10236 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10237 // turn into a single shuffle instruction.
10241 bool isLE = TLI.isLittleEndian();
10242 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10243 assert(ElemRatio > 1 && "Invalid element size ratio");
10244 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10245 DAG.getConstant(0, SourceType);
10247 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10248 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10250 // Populate the new build_vector
10251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10252 SDValue Cast = N->getOperand(i);
10253 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10254 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10255 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10257 if (Cast.getOpcode() == ISD::UNDEF)
10258 In = DAG.getUNDEF(SourceType);
10260 In = Cast->getOperand(0);
10261 unsigned Index = isLE ? (i * ElemRatio) :
10262 (i * ElemRatio + (ElemRatio - 1));
10264 assert(Index < Ops.size() && "Invalid index");
10268 // The type of the new BUILD_VECTOR node.
10269 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10270 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10271 "Invalid vector size");
10272 // Check if the new vector type is legal.
10273 if (!isTypeLegal(VecVT)) return SDValue();
10275 // Make the new BUILD_VECTOR.
10276 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10278 // The new BUILD_VECTOR node has the potential to be further optimized.
10279 AddToWorklist(BV.getNode());
10280 // Bitcast to the desired type.
10281 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10284 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10285 EVT VT = N->getValueType(0);
10287 unsigned NumInScalars = N->getNumOperands();
10290 EVT SrcVT = MVT::Other;
10291 unsigned Opcode = ISD::DELETED_NODE;
10292 unsigned NumDefs = 0;
10294 for (unsigned i = 0; i != NumInScalars; ++i) {
10295 SDValue In = N->getOperand(i);
10296 unsigned Opc = In.getOpcode();
10298 if (Opc == ISD::UNDEF)
10301 // If all scalar values are floats and converted from integers.
10302 if (Opcode == ISD::DELETED_NODE &&
10303 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10310 EVT InVT = In.getOperand(0).getValueType();
10312 // If all scalar values are typed differently, bail out. It's chosen to
10313 // simplify BUILD_VECTOR of integer types.
10314 if (SrcVT == MVT::Other)
10321 // If the vector has just one element defined, it's not worth to fold it into
10322 // a vectorized one.
10326 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10327 && "Should only handle conversion from integer to float.");
10328 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10330 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10332 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10335 SmallVector<SDValue, 8> Opnds;
10336 for (unsigned i = 0; i != NumInScalars; ++i) {
10337 SDValue In = N->getOperand(i);
10339 if (In.getOpcode() == ISD::UNDEF)
10340 Opnds.push_back(DAG.getUNDEF(SrcVT));
10342 Opnds.push_back(In.getOperand(0));
10344 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10345 AddToWorklist(BV.getNode());
10347 return DAG.getNode(Opcode, dl, VT, BV);
10350 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10351 unsigned NumInScalars = N->getNumOperands();
10353 EVT VT = N->getValueType(0);
10355 // A vector built entirely of undefs is undef.
10356 if (ISD::allOperandsUndef(N))
10357 return DAG.getUNDEF(VT);
10359 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10363 V = reduceBuildVecConvertToConvertBuildVec(N);
10367 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10368 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10369 // at most two distinct vectors, turn this into a shuffle node.
10371 // May only combine to shuffle after legalize if shuffle is legal.
10372 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10375 SDValue VecIn1, VecIn2;
10376 for (unsigned i = 0; i != NumInScalars; ++i) {
10377 // Ignore undef inputs.
10378 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10380 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10381 // constant index, bail out.
10382 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10383 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10384 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10388 // We allow up to two distinct input vectors.
10389 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10390 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10393 if (!VecIn1.getNode()) {
10394 VecIn1 = ExtractedFromVec;
10395 } else if (!VecIn2.getNode()) {
10396 VecIn2 = ExtractedFromVec;
10398 // Too many inputs.
10399 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10404 // If everything is good, we can make a shuffle operation.
10405 if (VecIn1.getNode()) {
10406 SmallVector<int, 8> Mask;
10407 for (unsigned i = 0; i != NumInScalars; ++i) {
10408 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10409 Mask.push_back(-1);
10413 // If extracting from the first vector, just use the index directly.
10414 SDValue Extract = N->getOperand(i);
10415 SDValue ExtVal = Extract.getOperand(1);
10416 if (Extract.getOperand(0) == VecIn1) {
10417 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10418 if (ExtIndex > VT.getVectorNumElements())
10421 Mask.push_back(ExtIndex);
10425 // Otherwise, use InIdx + VecSize
10426 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10427 Mask.push_back(Idx+NumInScalars);
10430 // We can't generate a shuffle node with mismatched input and output types.
10431 // Attempt to transform a single input vector to the correct type.
10432 if ((VT != VecIn1.getValueType())) {
10433 // We don't support shuffeling between TWO values of different types.
10434 if (VecIn2.getNode())
10437 // We only support widening of vectors which are half the size of the
10438 // output registers. For example XMM->YMM widening on X86 with AVX.
10439 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10442 // If the input vector type has a different base type to the output
10443 // vector type, bail out.
10444 if (VecIn1.getValueType().getVectorElementType() !=
10445 VT.getVectorElementType())
10448 // Widen the input vector by adding undef values.
10449 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10450 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10453 // If VecIn2 is unused then change it to undef.
10454 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10456 // Check that we were able to transform all incoming values to the same
10458 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10459 VecIn1.getValueType() != VT)
10462 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10463 if (!isTypeLegal(VT))
10466 // Return the new VECTOR_SHUFFLE node.
10470 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10476 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10477 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10478 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10479 // inputs come from at most two distinct vectors, turn this into a shuffle
10482 // If we only have one input vector, we don't need to do any concatenation.
10483 if (N->getNumOperands() == 1)
10484 return N->getOperand(0);
10486 // Check if all of the operands are undefs.
10487 EVT VT = N->getValueType(0);
10488 if (ISD::allOperandsUndef(N))
10489 return DAG.getUNDEF(VT);
10491 // Optimize concat_vectors where one of the vectors is undef.
10492 if (N->getNumOperands() == 2 &&
10493 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10494 SDValue In = N->getOperand(0);
10495 assert(In.getValueType().isVector() && "Must concat vectors");
10497 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10498 if (In->getOpcode() == ISD::BITCAST &&
10499 !In->getOperand(0)->getValueType(0).isVector()) {
10500 SDValue Scalar = In->getOperand(0);
10501 EVT SclTy = Scalar->getValueType(0);
10503 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10506 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10507 VT.getSizeInBits() / SclTy.getSizeInBits());
10508 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10511 SDLoc dl = SDLoc(N);
10512 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10513 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10517 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10518 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10519 if (N->getNumOperands() == 2 &&
10520 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10521 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10522 EVT VT = N->getValueType(0);
10523 SDValue N0 = N->getOperand(0);
10524 SDValue N1 = N->getOperand(1);
10525 SmallVector<SDValue, 8> Opnds;
10526 unsigned BuildVecNumElts = N0.getNumOperands();
10528 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10529 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10530 if (SclTy0.isFloatingPoint()) {
10531 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10532 Opnds.push_back(N0.getOperand(i));
10533 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10534 Opnds.push_back(N1.getOperand(i));
10536 // If BUILD_VECTOR are from built from integer, they may have different
10537 // operand types. Get the smaller type and truncate all operands to it.
10538 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10539 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10540 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10541 N0.getOperand(i)));
10542 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10543 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10544 N1.getOperand(i)));
10547 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10550 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10551 // nodes often generate nop CONCAT_VECTOR nodes.
10552 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10553 // place the incoming vectors at the exact same location.
10554 SDValue SingleSource = SDValue();
10555 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10557 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10558 SDValue Op = N->getOperand(i);
10560 if (Op.getOpcode() == ISD::UNDEF)
10563 // Check if this is the identity extract:
10564 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10567 // Find the single incoming vector for the extract_subvector.
10568 if (SingleSource.getNode()) {
10569 if (Op.getOperand(0) != SingleSource)
10572 SingleSource = Op.getOperand(0);
10574 // Check the source type is the same as the type of the result.
10575 // If not, this concat may extend the vector, so we can not
10576 // optimize it away.
10577 if (SingleSource.getValueType() != N->getValueType(0))
10581 unsigned IdentityIndex = i * PartNumElem;
10582 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10583 // The extract index must be constant.
10587 // Check that we are reading from the identity index.
10588 if (CS->getZExtValue() != IdentityIndex)
10592 if (SingleSource.getNode())
10593 return SingleSource;
10598 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10599 EVT NVT = N->getValueType(0);
10600 SDValue V = N->getOperand(0);
10602 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10604 // (extract_subvec (concat V1, V2, ...), i)
10607 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10609 if (V->getOperand(0).getValueType() != NVT)
10611 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10612 unsigned NumElems = NVT.getVectorNumElements();
10613 assert((Idx % NumElems) == 0 &&
10614 "IDX in concat is not a multiple of the result vector length.");
10615 return V->getOperand(Idx / NumElems);
10619 if (V->getOpcode() == ISD::BITCAST)
10620 V = V.getOperand(0);
10622 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10624 // Handle only simple case where vector being inserted and vector
10625 // being extracted are of same type, and are half size of larger vectors.
10626 EVT BigVT = V->getOperand(0).getValueType();
10627 EVT SmallVT = V->getOperand(1).getValueType();
10628 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10631 // Only handle cases where both indexes are constants with the same type.
10632 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10633 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10635 if (InsIdx && ExtIdx &&
10636 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10637 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10639 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10641 // indices are equal or bit offsets are equal => V1
10642 // otherwise => (extract_subvec V1, ExtIdx)
10643 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10644 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10645 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10646 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10647 DAG.getNode(ISD::BITCAST, dl,
10648 N->getOperand(0).getValueType(),
10649 V->getOperand(0)), N->getOperand(1));
10656 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10657 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10658 EVT VT = N->getValueType(0);
10659 unsigned NumElts = VT.getVectorNumElements();
10661 SDValue N0 = N->getOperand(0);
10662 SDValue N1 = N->getOperand(1);
10663 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10665 SmallVector<SDValue, 4> Ops;
10666 EVT ConcatVT = N0.getOperand(0).getValueType();
10667 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10668 unsigned NumConcats = NumElts / NumElemsPerConcat;
10670 // Look at every vector that's inserted. We're looking for exact
10671 // subvector-sized copies from a concatenated vector
10672 for (unsigned I = 0; I != NumConcats; ++I) {
10673 // Make sure we're dealing with a copy.
10674 unsigned Begin = I * NumElemsPerConcat;
10675 bool AllUndef = true, NoUndef = true;
10676 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10677 if (SVN->getMaskElt(J) >= 0)
10684 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10687 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10688 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10691 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10692 if (FirstElt < N0.getNumOperands())
10693 Ops.push_back(N0.getOperand(FirstElt));
10695 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10697 } else if (AllUndef) {
10698 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10699 } else { // Mixed with general masks and undefs, can't do optimization.
10704 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10707 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10708 EVT VT = N->getValueType(0);
10709 unsigned NumElts = VT.getVectorNumElements();
10711 SDValue N0 = N->getOperand(0);
10712 SDValue N1 = N->getOperand(1);
10714 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10716 // Canonicalize shuffle undef, undef -> undef
10717 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10718 return DAG.getUNDEF(VT);
10720 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10722 // Canonicalize shuffle v, v -> v, undef
10724 SmallVector<int, 8> NewMask;
10725 for (unsigned i = 0; i != NumElts; ++i) {
10726 int Idx = SVN->getMaskElt(i);
10727 if (Idx >= (int)NumElts) Idx -= NumElts;
10728 NewMask.push_back(Idx);
10730 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10734 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10735 if (N0.getOpcode() == ISD::UNDEF) {
10736 SmallVector<int, 8> NewMask;
10737 for (unsigned i = 0; i != NumElts; ++i) {
10738 int Idx = SVN->getMaskElt(i);
10740 if (Idx >= (int)NumElts)
10743 Idx = -1; // remove reference to lhs
10745 NewMask.push_back(Idx);
10747 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10751 // Remove references to rhs if it is undef
10752 if (N1.getOpcode() == ISD::UNDEF) {
10753 bool Changed = false;
10754 SmallVector<int, 8> NewMask;
10755 for (unsigned i = 0; i != NumElts; ++i) {
10756 int Idx = SVN->getMaskElt(i);
10757 if (Idx >= (int)NumElts) {
10761 NewMask.push_back(Idx);
10764 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10767 // If it is a splat, check if the argument vector is another splat or a
10768 // build_vector with all scalar elements the same.
10769 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10770 SDNode *V = N0.getNode();
10772 // If this is a bit convert that changes the element type of the vector but
10773 // not the number of vector elements, look through it. Be careful not to
10774 // look though conversions that change things like v4f32 to v2f64.
10775 if (V->getOpcode() == ISD::BITCAST) {
10776 SDValue ConvInput = V->getOperand(0);
10777 if (ConvInput.getValueType().isVector() &&
10778 ConvInput.getValueType().getVectorNumElements() == NumElts)
10779 V = ConvInput.getNode();
10782 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10783 assert(V->getNumOperands() == NumElts &&
10784 "BUILD_VECTOR has wrong number of operands");
10786 bool AllSame = true;
10787 for (unsigned i = 0; i != NumElts; ++i) {
10788 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10789 Base = V->getOperand(i);
10793 // Splat of <u, u, u, u>, return <u, u, u, u>
10794 if (!Base.getNode())
10796 for (unsigned i = 0; i != NumElts; ++i) {
10797 if (V->getOperand(i) != Base) {
10802 // Splat of <x, x, x, x>, return <x, x, x, x>
10808 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10809 Level < AfterLegalizeVectorOps &&
10810 (N1.getOpcode() == ISD::UNDEF ||
10811 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10812 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10813 SDValue V = partitionShuffleOfConcats(N, DAG);
10819 // If this shuffle node is simply a swizzle of another shuffle node,
10820 // then try to simplify it.
10821 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10822 N1.getOpcode() == ISD::UNDEF) {
10824 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10826 // The incoming shuffle must be of the same type as the result of the
10827 // current shuffle.
10828 assert(OtherSV->getOperand(0).getValueType() == VT &&
10829 "Shuffle types don't match");
10831 SmallVector<int, 4> Mask;
10832 // Compute the combined shuffle mask.
10833 for (unsigned i = 0; i != NumElts; ++i) {
10834 int Idx = SVN->getMaskElt(i);
10835 assert(Idx < (int)NumElts && "Index references undef operand");
10836 // Next, this index comes from the first value, which is the incoming
10837 // shuffle. Adopt the incoming index.
10839 Idx = OtherSV->getMaskElt(Idx);
10840 Mask.push_back(Idx);
10843 // Check if all indices in Mask are Undef. In case, propagate Undef.
10844 bool isUndefMask = true;
10845 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10846 isUndefMask &= Mask[i] < 0;
10849 return DAG.getUNDEF(VT);
10851 bool CommuteOperands = false;
10852 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10853 // To be valid, the combine shuffle mask should only reference elements
10854 // from one of the two vectors in input to the inner shufflevector.
10855 bool IsValidMask = true;
10856 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10857 // See if the combined mask only reference undefs or elements coming
10858 // from the first shufflevector operand.
10859 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10861 if (!IsValidMask) {
10862 IsValidMask = true;
10863 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10864 // Check that all the elements come from the second shuffle operand.
10865 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10866 CommuteOperands = IsValidMask;
10869 // Early exit if the combined shuffle mask is not valid.
10874 // See if this pair of shuffles can be safely folded according to either
10875 // of the following rules:
10876 // shuffle(shuffle(x, y), undef) -> x
10877 // shuffle(shuffle(x, undef), undef) -> x
10878 // shuffle(shuffle(x, y), undef) -> y
10879 bool IsIdentityMask = true;
10880 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10881 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10886 // The combined shuffle must map each index to itself.
10887 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10890 if (IsIdentityMask) {
10891 if (CommuteOperands)
10892 // optimize shuffle(shuffle(x, y), undef) -> y.
10893 return OtherSV->getOperand(1);
10895 // optimize shuffle(shuffle(x, undef), undef) -> x
10896 // optimize shuffle(shuffle(x, y), undef) -> x
10897 return OtherSV->getOperand(0);
10900 // It may still be beneficial to combine the two shuffles if the
10901 // resulting shuffle is legal.
10902 if (TLI.isTypeLegal(VT)) {
10903 if (!CommuteOperands) {
10904 if (TLI.isShuffleMaskLegal(Mask, VT))
10905 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10906 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10907 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10910 // Compute the commuted shuffle mask.
10911 for (unsigned i = 0; i != NumElts; ++i) {
10915 else if (idx < (int)NumElts)
10916 Mask[i] = idx + NumElts;
10918 Mask[i] = idx - NumElts;
10921 if (TLI.isShuffleMaskLegal(Mask, VT))
10922 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10923 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10929 // Canonicalize shuffles according to rules:
10930 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10931 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10932 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10933 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10934 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10935 TLI.isTypeLegal(VT)) {
10936 // The incoming shuffle must be of the same type as the result of the
10937 // current shuffle.
10938 assert(N1->getOperand(0).getValueType() == VT &&
10939 "Shuffle types don't match");
10941 SDValue SV0 = N1->getOperand(0);
10942 SDValue SV1 = N1->getOperand(1);
10943 bool HasSameOp0 = N0 == SV0;
10944 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10945 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10946 // Commute the operands of this shuffle so that next rule
10948 return DAG.getCommutedVectorShuffle(*SVN);
10951 // Try to fold according to rules:
10952 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10953 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10954 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10955 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10956 // Don't try to fold shuffles with illegal type.
10957 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10958 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10959 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10961 // The incoming shuffle must be of the same type as the result of the
10962 // current shuffle.
10963 assert(OtherSV->getOperand(0).getValueType() == VT &&
10964 "Shuffle types don't match");
10966 SDValue SV0 = OtherSV->getOperand(0);
10967 SDValue SV1 = OtherSV->getOperand(1);
10968 bool HasSameOp0 = N1 == SV0;
10969 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10970 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10974 SmallVector<int, 4> Mask;
10975 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10976 // operand, and SV1 as the second operand.
10977 for (unsigned i = 0; i != NumElts; ++i) {
10978 int Idx = SVN->getMaskElt(i);
10980 // Propagate Undef.
10981 Mask.push_back(Idx);
10985 if (Idx < (int)NumElts) {
10986 Idx = OtherSV->getMaskElt(Idx);
10987 if (IsSV1Undef && Idx >= (int) NumElts)
10988 Idx = -1; // Propagate Undef.
10990 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10992 Mask.push_back(Idx);
10995 // Check if all indices in Mask are Undef. In case, propagate Undef.
10996 bool isUndefMask = true;
10997 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10998 isUndefMask &= Mask[i] < 0;
11001 return DAG.getUNDEF(VT);
11003 // Avoid introducing shuffles with illegal mask.
11004 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11006 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11007 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11008 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11009 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11016 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11017 SDValue N0 = N->getOperand(0);
11018 SDValue N2 = N->getOperand(2);
11020 // If the input vector is a concatenation, and the insert replaces
11021 // one of the halves, we can optimize into a single concat_vectors.
11022 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11023 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11024 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11025 EVT VT = N->getValueType(0);
11027 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11028 // (concat_vectors Z, Y)
11030 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11031 N->getOperand(1), N0.getOperand(1));
11033 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11034 // (concat_vectors X, Z)
11035 if (InsIdx == VT.getVectorNumElements()/2)
11036 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11037 N0.getOperand(0), N->getOperand(1));
11043 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11044 /// with the destination vector and a zero vector.
11045 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11046 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11047 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11048 EVT VT = N->getValueType(0);
11050 SDValue LHS = N->getOperand(0);
11051 SDValue RHS = N->getOperand(1);
11052 if (N->getOpcode() == ISD::AND) {
11053 if (RHS.getOpcode() == ISD::BITCAST)
11054 RHS = RHS.getOperand(0);
11055 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11056 SmallVector<int, 8> Indices;
11057 unsigned NumElts = RHS.getNumOperands();
11058 for (unsigned i = 0; i != NumElts; ++i) {
11059 SDValue Elt = RHS.getOperand(i);
11060 if (!isa<ConstantSDNode>(Elt))
11063 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11064 Indices.push_back(i);
11065 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11066 Indices.push_back(NumElts);
11071 // Let's see if the target supports this vector_shuffle.
11072 EVT RVT = RHS.getValueType();
11073 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11076 // Return the new VECTOR_SHUFFLE node.
11077 EVT EltVT = RVT.getVectorElementType();
11078 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11079 DAG.getConstant(0, EltVT));
11080 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11081 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11082 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11083 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11090 /// Visit a binary vector operation, like ADD.
11091 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11092 assert(N->getValueType(0).isVector() &&
11093 "SimplifyVBinOp only works on vectors!");
11095 SDValue LHS = N->getOperand(0);
11096 SDValue RHS = N->getOperand(1);
11097 SDValue Shuffle = XformToShuffleWithZero(N);
11098 if (Shuffle.getNode()) return Shuffle;
11100 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11102 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11103 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11104 // Check if both vectors are constants. If not bail out.
11105 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11106 cast<BuildVectorSDNode>(RHS)->isConstant()))
11109 SmallVector<SDValue, 8> Ops;
11110 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11111 SDValue LHSOp = LHS.getOperand(i);
11112 SDValue RHSOp = RHS.getOperand(i);
11114 // Can't fold divide by zero.
11115 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11116 N->getOpcode() == ISD::FDIV) {
11117 if ((RHSOp.getOpcode() == ISD::Constant &&
11118 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11119 (RHSOp.getOpcode() == ISD::ConstantFP &&
11120 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11124 EVT VT = LHSOp.getValueType();
11125 EVT RVT = RHSOp.getValueType();
11127 // Integer BUILD_VECTOR operands may have types larger than the element
11128 // size (e.g., when the element type is not legal). Prior to type
11129 // legalization, the types may not match between the two BUILD_VECTORS.
11130 // Truncate one of the operands to make them match.
11131 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11132 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11134 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11138 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11140 if (FoldOp.getOpcode() != ISD::UNDEF &&
11141 FoldOp.getOpcode() != ISD::Constant &&
11142 FoldOp.getOpcode() != ISD::ConstantFP)
11144 Ops.push_back(FoldOp);
11145 AddToWorklist(FoldOp.getNode());
11148 if (Ops.size() == LHS.getNumOperands())
11149 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11152 // Type legalization might introduce new shuffles in the DAG.
11153 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11154 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11155 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11156 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11157 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11158 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11159 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11160 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11162 if (SVN0->getMask().equals(SVN1->getMask())) {
11163 EVT VT = N->getValueType(0);
11164 SDValue UndefVector = LHS.getOperand(1);
11165 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11166 LHS.getOperand(0), RHS.getOperand(0));
11167 AddUsersToWorklist(N);
11168 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11169 &SVN0->getMask()[0]);
11176 /// Visit a binary vector operation, like FABS/FNEG.
11177 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11178 assert(N->getValueType(0).isVector() &&
11179 "SimplifyVUnaryOp only works on vectors!");
11181 SDValue N0 = N->getOperand(0);
11183 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11186 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11187 SmallVector<SDValue, 8> Ops;
11188 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11189 SDValue Op = N0.getOperand(i);
11190 if (Op.getOpcode() != ISD::UNDEF &&
11191 Op.getOpcode() != ISD::ConstantFP)
11193 EVT EltVT = Op.getValueType();
11194 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11195 if (FoldOp.getOpcode() != ISD::UNDEF &&
11196 FoldOp.getOpcode() != ISD::ConstantFP)
11198 Ops.push_back(FoldOp);
11199 AddToWorklist(FoldOp.getNode());
11202 if (Ops.size() != N0.getNumOperands())
11205 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11208 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11209 SDValue N1, SDValue N2){
11210 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11212 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11213 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11215 // If we got a simplified select_cc node back from SimplifySelectCC, then
11216 // break it down into a new SETCC node, and a new SELECT node, and then return
11217 // the SELECT node, since we were called with a SELECT node.
11218 if (SCC.getNode()) {
11219 // Check to see if we got a select_cc back (to turn into setcc/select).
11220 // Otherwise, just return whatever node we got back, like fabs.
11221 if (SCC.getOpcode() == ISD::SELECT_CC) {
11222 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11224 SCC.getOperand(0), SCC.getOperand(1),
11225 SCC.getOperand(4));
11226 AddToWorklist(SETCC.getNode());
11227 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11228 SCC.getOperand(2), SCC.getOperand(3));
11236 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11237 /// being selected between, see if we can simplify the select. Callers of this
11238 /// should assume that TheSelect is deleted if this returns true. As such, they
11239 /// should return the appropriate thing (e.g. the node) back to the top-level of
11240 /// the DAG combiner loop to avoid it being looked at.
11241 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11244 // Cannot simplify select with vector condition
11245 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11247 // If this is a select from two identical things, try to pull the operation
11248 // through the select.
11249 if (LHS.getOpcode() != RHS.getOpcode() ||
11250 !LHS.hasOneUse() || !RHS.hasOneUse())
11253 // If this is a load and the token chain is identical, replace the select
11254 // of two loads with a load through a select of the address to load from.
11255 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11256 // constants have been dropped into the constant pool.
11257 if (LHS.getOpcode() == ISD::LOAD) {
11258 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11259 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11261 // Token chains must be identical.
11262 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11263 // Do not let this transformation reduce the number of volatile loads.
11264 LLD->isVolatile() || RLD->isVolatile() ||
11265 // If this is an EXTLOAD, the VT's must match.
11266 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11267 // If this is an EXTLOAD, the kind of extension must match.
11268 (LLD->getExtensionType() != RLD->getExtensionType() &&
11269 // The only exception is if one of the extensions is anyext.
11270 LLD->getExtensionType() != ISD::EXTLOAD &&
11271 RLD->getExtensionType() != ISD::EXTLOAD) ||
11272 // FIXME: this discards src value information. This is
11273 // over-conservative. It would be beneficial to be able to remember
11274 // both potential memory locations. Since we are discarding
11275 // src value info, don't do the transformation if the memory
11276 // locations are not in the default address space.
11277 LLD->getPointerInfo().getAddrSpace() != 0 ||
11278 RLD->getPointerInfo().getAddrSpace() != 0 ||
11279 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11280 LLD->getBasePtr().getValueType()))
11283 // Check that the select condition doesn't reach either load. If so,
11284 // folding this will induce a cycle into the DAG. If not, this is safe to
11285 // xform, so create a select of the addresses.
11287 if (TheSelect->getOpcode() == ISD::SELECT) {
11288 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11289 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11290 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11292 // The loads must not depend on one another.
11293 if (LLD->isPredecessorOf(RLD) ||
11294 RLD->isPredecessorOf(LLD))
11296 Addr = DAG.getSelect(SDLoc(TheSelect),
11297 LLD->getBasePtr().getValueType(),
11298 TheSelect->getOperand(0), LLD->getBasePtr(),
11299 RLD->getBasePtr());
11300 } else { // Otherwise SELECT_CC
11301 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11302 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11304 if ((LLD->hasAnyUseOfValue(1) &&
11305 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11306 (RLD->hasAnyUseOfValue(1) &&
11307 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11310 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11311 LLD->getBasePtr().getValueType(),
11312 TheSelect->getOperand(0),
11313 TheSelect->getOperand(1),
11314 LLD->getBasePtr(), RLD->getBasePtr(),
11315 TheSelect->getOperand(4));
11319 // It is safe to replace the two loads if they have different alignments,
11320 // but the new load must be the minimum (most restrictive) alignment of the
11322 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11323 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11324 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11325 Load = DAG.getLoad(TheSelect->getValueType(0),
11327 // FIXME: Discards pointer and AA info.
11328 LLD->getChain(), Addr, MachinePointerInfo(),
11329 LLD->isVolatile(), LLD->isNonTemporal(),
11330 isInvariant, Alignment);
11332 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11333 RLD->getExtensionType() : LLD->getExtensionType(),
11335 TheSelect->getValueType(0),
11336 // FIXME: Discards pointer and AA info.
11337 LLD->getChain(), Addr, MachinePointerInfo(),
11338 LLD->getMemoryVT(), LLD->isVolatile(),
11339 LLD->isNonTemporal(), isInvariant, Alignment);
11342 // Users of the select now use the result of the load.
11343 CombineTo(TheSelect, Load);
11345 // Users of the old loads now use the new load's chain. We know the
11346 // old-load value is dead now.
11347 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11348 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11355 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11356 /// where 'cond' is the comparison specified by CC.
11357 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11358 SDValue N2, SDValue N3,
11359 ISD::CondCode CC, bool NotExtCompare) {
11360 // (x ? y : y) -> y.
11361 if (N2 == N3) return N2;
11363 EVT VT = N2.getValueType();
11364 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11365 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11366 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11368 // Determine if the condition we're dealing with is constant
11369 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11370 N0, N1, CC, DL, false);
11371 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11372 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11374 // fold select_cc true, x, y -> x
11375 if (SCCC && !SCCC->isNullValue())
11377 // fold select_cc false, x, y -> y
11378 if (SCCC && SCCC->isNullValue())
11381 // Check to see if we can simplify the select into an fabs node
11382 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11383 // Allow either -0.0 or 0.0
11384 if (CFP->getValueAPF().isZero()) {
11385 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11386 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11387 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11388 N2 == N3.getOperand(0))
11389 return DAG.getNode(ISD::FABS, DL, VT, N0);
11391 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11392 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11393 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11394 N2.getOperand(0) == N3)
11395 return DAG.getNode(ISD::FABS, DL, VT, N3);
11399 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11400 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11401 // in it. This is a win when the constant is not otherwise available because
11402 // it replaces two constant pool loads with one. We only do this if the FP
11403 // type is known to be legal, because if it isn't, then we are before legalize
11404 // types an we want the other legalization to happen first (e.g. to avoid
11405 // messing with soft float) and if the ConstantFP is not legal, because if
11406 // it is legal, we may not need to store the FP constant in a constant pool.
11407 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11408 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11409 if (TLI.isTypeLegal(N2.getValueType()) &&
11410 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11411 TargetLowering::Legal &&
11412 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11413 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11414 // If both constants have multiple uses, then we won't need to do an
11415 // extra load, they are likely around in registers for other users.
11416 (TV->hasOneUse() || FV->hasOneUse())) {
11417 Constant *Elts[] = {
11418 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11419 const_cast<ConstantFP*>(TV->getConstantFPValue())
11421 Type *FPTy = Elts[0]->getType();
11422 const DataLayout &TD = *TLI.getDataLayout();
11424 // Create a ConstantArray of the two constants.
11425 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11426 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11427 TD.getPrefTypeAlignment(FPTy));
11428 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11430 // Get the offsets to the 0 and 1 element of the array so that we can
11431 // select between them.
11432 SDValue Zero = DAG.getIntPtrConstant(0);
11433 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11434 SDValue One = DAG.getIntPtrConstant(EltSize);
11436 SDValue Cond = DAG.getSetCC(DL,
11437 getSetCCResultType(N0.getValueType()),
11439 AddToWorklist(Cond.getNode());
11440 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11442 AddToWorklist(CstOffset.getNode());
11443 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11445 AddToWorklist(CPIdx.getNode());
11446 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11447 MachinePointerInfo::getConstantPool(), false,
11448 false, false, Alignment);
11453 // Check to see if we can perform the "gzip trick", transforming
11454 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11455 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11456 (N1C->isNullValue() || // (a < 0) ? b : 0
11457 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11458 EVT XType = N0.getValueType();
11459 EVT AType = N2.getValueType();
11460 if (XType.bitsGE(AType)) {
11461 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11462 // single-bit constant.
11463 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11464 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11465 ShCtV = XType.getSizeInBits()-ShCtV-1;
11466 SDValue ShCt = DAG.getConstant(ShCtV,
11467 getShiftAmountTy(N0.getValueType()));
11468 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11470 AddToWorklist(Shift.getNode());
11472 if (XType.bitsGT(AType)) {
11473 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11474 AddToWorklist(Shift.getNode());
11477 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11480 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11482 DAG.getConstant(XType.getSizeInBits()-1,
11483 getShiftAmountTy(N0.getValueType())));
11484 AddToWorklist(Shift.getNode());
11486 if (XType.bitsGT(AType)) {
11487 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11488 AddToWorklist(Shift.getNode());
11491 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11495 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11496 // where y is has a single bit set.
11497 // A plaintext description would be, we can turn the SELECT_CC into an AND
11498 // when the condition can be materialized as an all-ones register. Any
11499 // single bit-test can be materialized as an all-ones register with
11500 // shift-left and shift-right-arith.
11501 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11502 N0->getValueType(0) == VT &&
11503 N1C && N1C->isNullValue() &&
11504 N2C && N2C->isNullValue()) {
11505 SDValue AndLHS = N0->getOperand(0);
11506 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11507 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11508 // Shift the tested bit over the sign bit.
11509 APInt AndMask = ConstAndRHS->getAPIntValue();
11511 DAG.getConstant(AndMask.countLeadingZeros(),
11512 getShiftAmountTy(AndLHS.getValueType()));
11513 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11515 // Now arithmetic right shift it all the way over, so the result is either
11516 // all-ones, or zero.
11518 DAG.getConstant(AndMask.getBitWidth()-1,
11519 getShiftAmountTy(Shl.getValueType()));
11520 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11522 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11526 // fold select C, 16, 0 -> shl C, 4
11527 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11528 TLI.getBooleanContents(N0.getValueType()) ==
11529 TargetLowering::ZeroOrOneBooleanContent) {
11531 // If the caller doesn't want us to simplify this into a zext of a compare,
11533 if (NotExtCompare && N2C->getAPIntValue() == 1)
11536 // Get a SetCC of the condition
11537 // NOTE: Don't create a SETCC if it's not legal on this target.
11538 if (!LegalOperations ||
11539 TLI.isOperationLegal(ISD::SETCC,
11540 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11542 // cast from setcc result type to select result type
11544 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11546 if (N2.getValueType().bitsLT(SCC.getValueType()))
11547 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11548 N2.getValueType());
11550 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11551 N2.getValueType(), SCC);
11553 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11554 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11555 N2.getValueType(), SCC);
11558 AddToWorklist(SCC.getNode());
11559 AddToWorklist(Temp.getNode());
11561 if (N2C->getAPIntValue() == 1)
11564 // shl setcc result by log2 n2c
11565 return DAG.getNode(
11566 ISD::SHL, DL, N2.getValueType(), Temp,
11567 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11568 getShiftAmountTy(Temp.getValueType())));
11572 // Check to see if this is the equivalent of setcc
11573 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11574 // otherwise, go ahead with the folds.
11575 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11576 EVT XType = N0.getValueType();
11577 if (!LegalOperations ||
11578 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11579 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11580 if (Res.getValueType() != VT)
11581 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11585 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11586 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11587 (!LegalOperations ||
11588 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11589 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11590 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11591 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11592 getShiftAmountTy(Ctlz.getValueType())));
11594 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11595 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11596 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11597 XType, DAG.getConstant(0, XType), N0);
11598 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11599 return DAG.getNode(ISD::SRL, DL, XType,
11600 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11601 DAG.getConstant(XType.getSizeInBits()-1,
11602 getShiftAmountTy(XType)));
11604 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11605 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11606 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11607 DAG.getConstant(XType.getSizeInBits()-1,
11608 getShiftAmountTy(N0.getValueType())));
11609 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11613 // Check to see if this is an integer abs.
11614 // select_cc setg[te] X, 0, X, -X ->
11615 // select_cc setgt X, -1, X, -X ->
11616 // select_cc setl[te] X, 0, -X, X ->
11617 // select_cc setlt X, 1, -X, X ->
11618 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11620 ConstantSDNode *SubC = nullptr;
11621 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11622 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11623 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11624 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11625 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11626 (N1C->isOne() && CC == ISD::SETLT)) &&
11627 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11628 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11630 EVT XType = N0.getValueType();
11631 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11632 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11634 DAG.getConstant(XType.getSizeInBits()-1,
11635 getShiftAmountTy(N0.getValueType())));
11636 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11638 AddToWorklist(Shift.getNode());
11639 AddToWorklist(Add.getNode());
11640 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11647 /// This is a stub for TargetLowering::SimplifySetCC.
11648 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11649 SDValue N1, ISD::CondCode Cond,
11650 SDLoc DL, bool foldBooleans) {
11651 TargetLowering::DAGCombinerInfo
11652 DagCombineInfo(DAG, Level, false, this);
11653 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11656 /// Given an ISD::SDIV node expressing a divide by constant, return
11657 /// a DAG expression to select that will generate the same value by multiplying
11658 /// by a magic number.
11659 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11660 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11661 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11665 // Avoid division by zero.
11666 if (!C->getAPIntValue())
11669 std::vector<SDNode*> Built;
11671 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11673 for (SDNode *N : Built)
11678 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11679 /// DAG expression that will generate the same value by right shifting.
11680 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11681 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11685 // Avoid division by zero.
11686 if (!C->getAPIntValue())
11689 std::vector<SDNode *> Built;
11690 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11692 for (SDNode *N : Built)
11697 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11698 /// expression that will generate the same value by multiplying by a magic
11700 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11701 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11702 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11706 // Avoid division by zero.
11707 if (!C->getAPIntValue())
11710 std::vector<SDNode*> Built;
11712 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11714 for (SDNode *N : Built)
11719 /// Given an ISD::FDIV node with either a direct or indirect ISD::FSQRT operand,
11720 /// generate a DAG expression using a reciprocal square root estimate op.
11721 SDValue DAGCombiner::BuildRSQRTE(SDNode *N) {
11722 // Expose the DAG combiner to the target combiner implementations.
11723 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11725 EVT VT = N->getValueType(0);
11726 SDValue N1 = N->getOperand(1);
11728 if (N1.getOpcode() == ISD::FSQRT) {
11729 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0), DCI)) {
11730 AddToWorklist(RV.getNode());
11731 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
11733 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
11734 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
11735 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0).getOperand(0), DCI)) {
11736 DCI.AddToWorklist(RV.getNode());
11737 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
11738 AddToWorklist(RV.getNode());
11739 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
11741 } else if (N1.getOpcode() == ISD::FP_ROUND &&
11742 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
11743 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0).getOperand(0), DCI)) {
11744 DCI.AddToWorklist(RV.getNode());
11745 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
11746 AddToWorklist(RV.getNode());
11747 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
11754 /// Return true if base is a frame index, which is known not to alias with
11755 /// anything but itself. Provides base object and offset as results.
11756 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11757 const GlobalValue *&GV, const void *&CV) {
11758 // Assume it is a primitive operation.
11759 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11761 // If it's an adding a simple constant then integrate the offset.
11762 if (Base.getOpcode() == ISD::ADD) {
11763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11764 Base = Base.getOperand(0);
11765 Offset += C->getZExtValue();
11769 // Return the underlying GlobalValue, and update the Offset. Return false
11770 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11771 // by multiple nodes with different offsets.
11772 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11773 GV = G->getGlobal();
11774 Offset += G->getOffset();
11778 // Return the underlying Constant value, and update the Offset. Return false
11779 // for ConstantSDNodes since the same constant pool entry may be represented
11780 // by multiple nodes with different offsets.
11781 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11782 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11783 : (const void *)C->getConstVal();
11784 Offset += C->getOffset();
11787 // If it's any of the following then it can't alias with anything but itself.
11788 return isa<FrameIndexSDNode>(Base);
11791 /// Return true if there is any possibility that the two addresses overlap.
11792 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11793 // If they are the same then they must be aliases.
11794 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11796 // If they are both volatile then they cannot be reordered.
11797 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11799 // Gather base node and offset information.
11800 SDValue Base1, Base2;
11801 int64_t Offset1, Offset2;
11802 const GlobalValue *GV1, *GV2;
11803 const void *CV1, *CV2;
11804 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11805 Base1, Offset1, GV1, CV1);
11806 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11807 Base2, Offset2, GV2, CV2);
11809 // If they have a same base address then check to see if they overlap.
11810 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11811 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11812 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11814 // It is possible for different frame indices to alias each other, mostly
11815 // when tail call optimization reuses return address slots for arguments.
11816 // To catch this case, look up the actual index of frame indices to compute
11817 // the real alias relationship.
11818 if (isFrameIndex1 && isFrameIndex2) {
11819 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11820 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11821 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11822 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11823 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11826 // Otherwise, if we know what the bases are, and they aren't identical, then
11827 // we know they cannot alias.
11828 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11831 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11832 // compared to the size and offset of the access, we may be able to prove they
11833 // do not alias. This check is conservative for now to catch cases created by
11834 // splitting vector types.
11835 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11836 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11837 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11838 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11839 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11840 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11841 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11843 // There is no overlap between these relatively aligned accesses of similar
11844 // size, return no alias.
11845 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11846 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11850 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11851 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11853 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11854 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11858 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11859 // Use alias analysis information.
11860 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11861 Op1->getSrcValueOffset());
11862 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11863 Op0->getSrcValueOffset() - MinOffset;
11864 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11865 Op1->getSrcValueOffset() - MinOffset;
11866 AliasAnalysis::AliasResult AAResult =
11867 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11869 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11870 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11872 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11873 if (AAResult == AliasAnalysis::NoAlias)
11877 // Otherwise we have to assume they alias.
11881 /// Walk up chain skipping non-aliasing memory nodes,
11882 /// looking for aliasing nodes and adding them to the Aliases vector.
11883 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11884 SmallVectorImpl<SDValue> &Aliases) {
11885 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11886 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11888 // Get alias information for node.
11889 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11892 Chains.push_back(OriginalChain);
11893 unsigned Depth = 0;
11895 // Look at each chain and determine if it is an alias. If so, add it to the
11896 // aliases list. If not, then continue up the chain looking for the next
11898 while (!Chains.empty()) {
11899 SDValue Chain = Chains.back();
11902 // For TokenFactor nodes, look at each operand and only continue up the
11903 // chain until we find two aliases. If we've seen two aliases, assume we'll
11904 // find more and revert to original chain since the xform is unlikely to be
11907 // FIXME: The depth check could be made to return the last non-aliasing
11908 // chain we found before we hit a tokenfactor rather than the original
11910 if (Depth > 6 || Aliases.size() == 2) {
11912 Aliases.push_back(OriginalChain);
11916 // Don't bother if we've been before.
11917 if (!Visited.insert(Chain.getNode()))
11920 switch (Chain.getOpcode()) {
11921 case ISD::EntryToken:
11922 // Entry token is ideal chain operand, but handled in FindBetterChain.
11927 // Get alias information for Chain.
11928 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11929 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11931 // If chain is alias then stop here.
11932 if (!(IsLoad && IsOpLoad) &&
11933 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11934 Aliases.push_back(Chain);
11936 // Look further up the chain.
11937 Chains.push_back(Chain.getOperand(0));
11943 case ISD::TokenFactor:
11944 // We have to check each of the operands of the token factor for "small"
11945 // token factors, so we queue them up. Adding the operands to the queue
11946 // (stack) in reverse order maintains the original order and increases the
11947 // likelihood that getNode will find a matching token factor (CSE.)
11948 if (Chain.getNumOperands() > 16) {
11949 Aliases.push_back(Chain);
11952 for (unsigned n = Chain.getNumOperands(); n;)
11953 Chains.push_back(Chain.getOperand(--n));
11958 // For all other instructions we will just have to take what we can get.
11959 Aliases.push_back(Chain);
11964 // We need to be careful here to also search for aliases through the
11965 // value operand of a store, etc. Consider the following situation:
11967 // L1 = load Token1, %52
11968 // S1 = store Token1, L1, %51
11969 // L2 = load Token1, %52+8
11970 // S2 = store Token1, L2, %51+8
11971 // Token2 = Token(S1, S2)
11972 // L3 = load Token2, %53
11973 // S3 = store Token2, L3, %52
11974 // L4 = load Token2, %53+8
11975 // S4 = store Token2, L4, %52+8
11976 // If we search for aliases of S3 (which loads address %52), and we look
11977 // only through the chain, then we'll miss the trivial dependence on L1
11978 // (which also loads from %52). We then might change all loads and
11979 // stores to use Token1 as their chain operand, which could result in
11980 // copying %53 into %52 before copying %52 into %51 (which should
11983 // The problem is, however, that searching for such data dependencies
11984 // can become expensive, and the cost is not directly related to the
11985 // chain depth. Instead, we'll rule out such configurations here by
11986 // insisting that we've visited all chain users (except for users
11987 // of the original chain, which is not necessary). When doing this,
11988 // we need to look through nodes we don't care about (otherwise, things
11989 // like register copies will interfere with trivial cases).
11991 SmallVector<const SDNode *, 16> Worklist;
11992 for (const SDNode *N : Visited)
11993 if (N != OriginalChain.getNode())
11994 Worklist.push_back(N);
11996 while (!Worklist.empty()) {
11997 const SDNode *M = Worklist.pop_back_val();
11999 // We have already visited M, and want to make sure we've visited any uses
12000 // of M that we care about. For uses that we've not visisted, and don't
12001 // care about, queue them to the worklist.
12003 for (SDNode::use_iterator UI = M->use_begin(),
12004 UIE = M->use_end(); UI != UIE; ++UI)
12005 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12006 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12007 // We've not visited this use, and we care about it (it could have an
12008 // ordering dependency with the original node).
12010 Aliases.push_back(OriginalChain);
12014 // We've not visited this use, but we don't care about it. Mark it as
12015 // visited and enqueue it to the worklist.
12016 Worklist.push_back(*UI);
12021 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12022 /// (aliasing node.)
12023 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12024 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12026 // Accumulate all the aliases to this node.
12027 GatherAllAliases(N, OldChain, Aliases);
12029 // If no operands then chain to entry token.
12030 if (Aliases.size() == 0)
12031 return DAG.getEntryNode();
12033 // If a single operand then chain to it. We don't need to revisit it.
12034 if (Aliases.size() == 1)
12037 // Construct a custom tailored token factor.
12038 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12041 /// This is the entry point for the file.
12042 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12043 CodeGenOpt::Level OptLevel) {
12044 /// This is the main entry point to this class.
12045 DAGCombiner(*this, AA, OptLevel).Run(Level);