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 "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 /// \brief Set of nodes which have been combined (at least once).
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
113 // AA - Used for DAG load/store alias analysis.
116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
127 SDValue visit(SDNode *N);
130 /// AddToWorklist - Add to the work list making sure its instance is at the
131 /// back (next to be processed.)
132 void AddToWorklist(SDNode *N) {
133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
142 /// removeFromWorklist - 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 /// SimplifyDemandedBits - Check the specified integer node value to see if
177 /// it can be simplified or if things it uses can be simplified by bit
178 /// propagation. 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 bool SliceUpLoad(SDNode *N);
191 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
194 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196 /// \param EltNo index of the vector element to load.
197 /// \param OriginalLoad load that EVE came from to be replaced.
198 /// \returns EVE on success SDValue() on failure.
199 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue PromoteIntBinOp(SDValue Op);
206 SDValue PromoteIntShiftOp(SDValue Op);
207 SDValue PromoteExtend(SDValue Op);
208 bool PromoteLoad(SDValue Op);
210 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212 ISD::NodeType ExtType);
214 /// combine - call the node-specific routine that knows how to fold each
215 /// particular type of node. If that doesn't do anything, try the
216 /// target-specific DAG combines.
217 SDValue combine(SDNode *N);
219 // Visitation implementation - Implement dag node combining for different
220 // node types. The semantics are as follows:
222 // SDValue.getNode() == 0 - No change was made
223 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
224 // otherwise - N should be replaced by the returned Operand.
226 SDValue visitTokenFactor(SDNode *N);
227 SDValue visitMERGE_VALUES(SDNode *N);
228 SDValue visitADD(SDNode *N);
229 SDValue visitSUB(SDNode *N);
230 SDValue visitADDC(SDNode *N);
231 SDValue visitSUBC(SDNode *N);
232 SDValue visitADDE(SDNode *N);
233 SDValue visitSUBE(SDNode *N);
234 SDValue visitMUL(SDNode *N);
235 SDValue visitSDIV(SDNode *N);
236 SDValue visitUDIV(SDNode *N);
237 SDValue visitSREM(SDNode *N);
238 SDValue visitUREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitAND(SDNode *N);
248 SDValue visitOR(SDNode *N);
249 SDValue visitXOR(SDNode *N);
250 SDValue SimplifyVBinOp(SDNode *N);
251 SDValue SimplifyVUnaryOp(SDNode *N);
252 SDValue visitSHL(SDNode *N);
253 SDValue visitSRA(SDNode *N);
254 SDValue visitSRL(SDNode *N);
255 SDValue visitRotate(SDNode *N);
256 SDValue visitCTLZ(SDNode *N);
257 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258 SDValue visitCTTZ(SDNode *N);
259 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTPOP(SDNode *N);
261 SDValue visitSELECT(SDNode *N);
262 SDValue visitVSELECT(SDNode *N);
263 SDValue visitSELECT_CC(SDNode *N);
264 SDValue visitSETCC(SDNode *N);
265 SDValue visitSIGN_EXTEND(SDNode *N);
266 SDValue visitZERO_EXTEND(SDNode *N);
267 SDValue visitANY_EXTEND(SDNode *N);
268 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269 SDValue visitTRUNCATE(SDNode *N);
270 SDValue visitBITCAST(SDNode *N);
271 SDValue visitBUILD_PAIR(SDNode *N);
272 SDValue visitFADD(SDNode *N);
273 SDValue visitFSUB(SDNode *N);
274 SDValue visitFMUL(SDNode *N);
275 SDValue visitFMA(SDNode *N);
276 SDValue visitFDIV(SDNode *N);
277 SDValue visitFREM(SDNode *N);
278 SDValue visitFCOPYSIGN(SDNode *N);
279 SDValue visitSINT_TO_FP(SDNode *N);
280 SDValue visitUINT_TO_FP(SDNode *N);
281 SDValue visitFP_TO_SINT(SDNode *N);
282 SDValue visitFP_TO_UINT(SDNode *N);
283 SDValue visitFP_ROUND(SDNode *N);
284 SDValue visitFP_ROUND_INREG(SDNode *N);
285 SDValue visitFP_EXTEND(SDNode *N);
286 SDValue visitFNEG(SDNode *N);
287 SDValue visitFABS(SDNode *N);
288 SDValue visitFCEIL(SDNode *N);
289 SDValue visitFTRUNC(SDNode *N);
290 SDValue visitFFLOOR(SDNode *N);
291 SDValue visitBRCOND(SDNode *N);
292 SDValue visitBR_CC(SDNode *N);
293 SDValue visitLOAD(SDNode *N);
294 SDValue visitSTORE(SDNode *N);
295 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297 SDValue visitBUILD_VECTOR(SDNode *N);
298 SDValue visitCONCAT_VECTORS(SDNode *N);
299 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300 SDValue visitVECTOR_SHUFFLE(SDNode *N);
301 SDValue visitINSERT_SUBVECTOR(SDNode *N);
303 SDValue XformToShuffleWithZero(SDNode *N);
304 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312 SDValue N3, ISD::CondCode CC,
313 bool NotExtCompare = false);
314 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315 SDLoc DL, bool foldBooleans = true);
317 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 bool isOneUseSetCC(SDValue N) const;
321 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325 SDValue BuildSDIV(SDNode *N);
326 SDValue BuildSDIVPow2(SDNode *N);
327 SDValue BuildUDIV(SDNode *N);
328 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329 bool DemandHighBits = true);
330 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332 SDValue InnerPos, SDValue InnerNeg,
333 unsigned PosOpcode, unsigned NegOpcode,
335 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336 SDValue ReduceLoadWidth(SDNode *N);
337 SDValue ReduceLoadOpStoreWidth(SDNode *N);
338 SDValue TransformFPLoadStorePair(SDNode *N);
339 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345 /// looking for aliasing nodes and adding them to the Aliases vector.
346 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347 SmallVectorImpl<SDValue> &Aliases);
349 /// isAlias - Return true if there is any possibility that the two addresses
351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354 /// looking for a better chain (aliasing node.)
355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
382 /// Run - runs the dag combiner on all nodes in the work list
383 void Run(CombineLevel AtLevel);
385 SelectionDAG &getDAG() const { return DAG; }
387 /// getShiftAmountTy - Returns a type large enough to hold any valid
388 /// shift amount - before type legalization these can be huge.
389 EVT getShiftAmountTy(EVT LHSTy) {
390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
397 /// isTypeLegal - This method returns true if we are running before type
398 /// legalization or if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
404 /// getSetCCResultType - Convenience wrapper around
405 /// TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
414 /// WorklistRemover - 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())
472 AddToWorklist(Op.getNode());
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481 const TargetLowering &TLI,
482 const TargetOptions *Options,
483 unsigned Depth = 0) {
484 // fneg is removable even if it has multiple uses.
485 if (Op.getOpcode() == ISD::FNEG) return 2;
487 // Don't allow anything with multiple uses.
488 if (!Op.hasOneUse()) return 0;
490 // Don't recurse exponentially.
491 if (Depth > 6) return 0;
493 switch (Op.getOpcode()) {
494 default: return false;
495 case ISD::ConstantFP:
496 // Don't invert constant FP values after legalize. The negated constant
497 // isn't necessarily legal.
498 return LegalOperations ? 0 : 1;
500 // FIXME: determine better conditions for this xform.
501 if (!Options->UnsafeFPMath) return 0;
503 // After operation legalization, it might not be legal to create new FSUBs.
504 if (LegalOperations &&
505 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516 // We can't turn -(A-B) into B-A when we honor signed zeros.
517 if (!Options->UnsafeFPMath) return 0;
519 // fold (fneg (fsub A, B)) -> (fsub B, A)
524 if (Options->HonorSignDependentRoundingFPMath()) return 0;
526 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
531 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
537 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545 bool LegalOperations, unsigned Depth = 0) {
546 // fneg is removable even if it has multiple uses.
547 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
549 // Don't allow anything with multiple uses.
550 assert(Op.hasOneUse() && "Unknown reuse!");
552 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553 switch (Op.getOpcode()) {
554 default: llvm_unreachable("Unknown code");
555 case ISD::ConstantFP: {
556 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
558 return DAG.getConstantFP(V, Op.getValueType());
561 // FIXME: determine better conditions for this xform.
562 assert(DAG.getTarget().Options.UnsafeFPMath);
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566 DAG.getTargetLoweringInfo(),
567 &DAG.getTarget().Options, Depth+1))
568 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(0), DAG,
570 LegalOperations, Depth+1),
572 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1),
578 // We can't turn -(A-B) into B-A when we honor signed zeros.
579 assert(DAG.getTarget().Options.UnsafeFPMath);
581 // fold (fneg (fsub 0, B)) -> B
582 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583 if (N0CFP->getValueAPF().isZero())
584 return Op.getOperand(1);
586 // fold (fneg (fsub A, B)) -> (fsub B, A)
587 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588 Op.getOperand(1), Op.getOperand(0));
592 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596 DAG.getTargetLoweringInfo(),
597 &DAG.getTarget().Options, Depth+1))
598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1));
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(0), DAG,
613 LegalOperations, Depth+1));
615 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1),
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
647 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use. If this is true, it allows the users to invert the operation for
649 // free when it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
657 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
665 unsigned SplatBitSize;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
670 EltVT.getSizeInBits() >= SplatBitSize);
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
693 // BuildVectors can truncate their operands. Ignore that case here.
694 // FIXME: We blindly ignore splats which include undef which is overly
696 if (CN && UndefElements.none() &&
697 CN->getValueType(0) == N.getValueType().getScalarType())
704 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
705 SDValue N0, SDValue N1) {
706 EVT VT = N0.getValueType();
707 if (N0.getOpcode() == Opc) {
708 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
709 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
710 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
711 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
712 if (!OpNode.getNode())
714 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
716 if (N0.hasOneUse()) {
717 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
719 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
720 if (!OpNode.getNode())
722 AddToWorklist(OpNode.getNode());
723 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
728 if (N1.getOpcode() == Opc) {
729 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
730 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
731 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
737 if (N1.hasOneUse()) {
738 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
752 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
754 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
756 DEBUG(dbgs() << "\nReplacing.1 ";
758 dbgs() << "\nWith: ";
759 To[0].getNode()->dump(&DAG);
760 dbgs() << " and " << NumTo-1 << " other values\n";
761 for (unsigned i = 0, e = NumTo; i != e; ++i)
762 assert((!To[i].getNode() ||
763 N->getValueType(i) == To[i].getValueType()) &&
764 "Cannot combine value to value of different type!"));
765 WorklistRemover DeadNodes(*this);
766 DAG.ReplaceAllUsesWith(N, To);
768 // Push the new nodes and any users onto the worklist
769 for (unsigned i = 0, e = NumTo; i != e; ++i) {
770 if (To[i].getNode()) {
771 AddToWorklist(To[i].getNode());
772 AddUsersToWorklist(To[i].getNode());
777 // Finally, if the node is now dead, remove it from the graph. The node
778 // may not be dead if the replacement process recursively simplified to
779 // something else needing this node.
781 deleteAndRecombine(N);
782 return SDValue(N, 0);
786 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
787 // Replace all uses. If any nodes become isomorphic to other nodes and
788 // are deleted, make sure to remove them from our worklist.
789 WorklistRemover DeadNodes(*this);
790 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
792 // Push the new node and any (possibly new) users onto the worklist.
793 AddToWorklist(TLO.New.getNode());
794 AddUsersToWorklist(TLO.New.getNode());
796 // Finally, if the node is now dead, remove it from the graph. The node
797 // may not be dead if the replacement process recursively simplified to
798 // something else needing this node.
799 if (TLO.Old.getNode()->use_empty())
800 deleteAndRecombine(TLO.Old.getNode());
803 /// SimplifyDemandedBits - Check the specified integer node value to see if
804 /// it can be simplified or if things it uses can be simplified by bit
805 /// propagation. If so, return true.
806 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
807 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
808 APInt KnownZero, KnownOne;
809 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
813 AddToWorklist(Op.getNode());
815 // Replace the old value with the new one.
817 DEBUG(dbgs() << "\nReplacing.2 ";
818 TLO.Old.getNode()->dump(&DAG);
819 dbgs() << "\nWith: ";
820 TLO.New.getNode()->dump(&DAG);
823 CommitTargetLoweringOpt(TLO);
827 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
829 EVT VT = Load->getValueType(0);
830 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
832 DEBUG(dbgs() << "\nReplacing.9 ";
834 dbgs() << "\nWith: ";
835 Trunc.getNode()->dump(&DAG);
837 WorklistRemover DeadNodes(*this);
838 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
839 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
840 deleteAndRecombine(Load);
841 AddToWorklist(Trunc.getNode());
844 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
848 EVT MemVT = LD->getMemoryVT();
849 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
850 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
852 : LD->getExtensionType();
854 return DAG.getExtLoad(ExtType, dl, PVT,
855 LD->getChain(), LD->getBasePtr(),
856 MemVT, LD->getMemOperand());
859 unsigned Opc = Op.getOpcode();
862 case ISD::AssertSext:
863 return DAG.getNode(ISD::AssertSext, dl, PVT,
864 SExtPromoteOperand(Op.getOperand(0), PVT),
866 case ISD::AssertZext:
867 return DAG.getNode(ISD::AssertZext, dl, PVT,
868 ZExtPromoteOperand(Op.getOperand(0), PVT),
870 case ISD::Constant: {
872 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
873 return DAG.getNode(ExtOpc, dl, PVT, Op);
877 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
879 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
882 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
883 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
885 EVT OldVT = Op.getValueType();
887 bool Replace = false;
888 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
889 if (!NewOp.getNode())
891 AddToWorklist(NewOp.getNode());
894 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
895 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
896 DAG.getValueType(OldVT));
899 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
900 EVT OldVT = Op.getValueType();
902 bool Replace = false;
903 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
904 if (!NewOp.getNode())
906 AddToWorklist(NewOp.getNode());
909 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
910 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
913 /// PromoteIntBinOp - Promote the specified integer binary operation if the
914 /// target indicates it is beneficial. e.g. On x86, it's usually better to
915 /// promote i16 operations to i32 since i16 instructions are longer.
916 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
917 if (!LegalOperations)
920 EVT VT = Op.getValueType();
921 if (VT.isVector() || !VT.isInteger())
924 // If operation type is 'undesirable', e.g. i16 on x86, consider
926 unsigned Opc = Op.getOpcode();
927 if (TLI.isTypeDesirableForOp(Opc, VT))
931 // Consult target whether it is a good idea to promote this operation and
932 // what's the right type to promote it to.
933 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
934 assert(PVT != VT && "Don't know what type to promote to!");
936 bool Replace0 = false;
937 SDValue N0 = Op.getOperand(0);
938 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
942 bool Replace1 = false;
943 SDValue N1 = Op.getOperand(1);
948 NN1 = PromoteOperand(N1, PVT, Replace1);
953 AddToWorklist(NN0.getNode());
955 AddToWorklist(NN1.getNode());
958 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
960 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
962 DEBUG(dbgs() << "\nPromoting ";
963 Op.getNode()->dump(&DAG));
965 return DAG.getNode(ISD::TRUNCATE, dl, VT,
966 DAG.getNode(Opc, dl, PVT, NN0, NN1));
971 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
972 /// target indicates it is beneficial. e.g. On x86, it's usually better to
973 /// promote i16 operations to i32 since i16 instructions are longer.
974 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
975 if (!LegalOperations)
978 EVT VT = Op.getValueType();
979 if (VT.isVector() || !VT.isInteger())
982 // If operation type is 'undesirable', e.g. i16 on x86, consider
984 unsigned Opc = Op.getOpcode();
985 if (TLI.isTypeDesirableForOp(Opc, VT))
989 // Consult target whether it is a good idea to promote this operation and
990 // what's the right type to promote it to.
991 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
992 assert(PVT != VT && "Don't know what type to promote to!");
994 bool Replace = false;
995 SDValue N0 = Op.getOperand(0);
997 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
998 else if (Opc == ISD::SRL)
999 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1001 N0 = PromoteOperand(N0, PVT, Replace);
1005 AddToWorklist(N0.getNode());
1007 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1009 DEBUG(dbgs() << "\nPromoting ";
1010 Op.getNode()->dump(&DAG));
1012 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1013 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1018 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1019 if (!LegalOperations)
1022 EVT VT = Op.getValueType();
1023 if (VT.isVector() || !VT.isInteger())
1026 // If operation type is 'undesirable', e.g. i16 on x86, consider
1028 unsigned Opc = Op.getOpcode();
1029 if (TLI.isTypeDesirableForOp(Opc, VT))
1033 // Consult target whether it is a good idea to promote this operation and
1034 // what's the right type to promote it to.
1035 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1036 assert(PVT != VT && "Don't know what type to promote to!");
1037 // fold (aext (aext x)) -> (aext x)
1038 // fold (aext (zext x)) -> (zext x)
1039 // fold (aext (sext x)) -> (sext x)
1040 DEBUG(dbgs() << "\nPromoting ";
1041 Op.getNode()->dump(&DAG));
1042 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1047 bool DAGCombiner::PromoteLoad(SDValue Op) {
1048 if (!LegalOperations)
1051 EVT VT = Op.getValueType();
1052 if (VT.isVector() || !VT.isInteger())
1055 // If operation type is 'undesirable', e.g. i16 on x86, consider
1057 unsigned Opc = Op.getOpcode();
1058 if (TLI.isTypeDesirableForOp(Opc, VT))
1062 // Consult target whether it is a good idea to promote this operation and
1063 // what's the right type to promote it to.
1064 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065 assert(PVT != VT && "Don't know what type to promote to!");
1068 SDNode *N = Op.getNode();
1069 LoadSDNode *LD = cast<LoadSDNode>(N);
1070 EVT MemVT = LD->getMemoryVT();
1071 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1072 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1074 : LD->getExtensionType();
1075 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1076 LD->getChain(), LD->getBasePtr(),
1077 MemVT, LD->getMemOperand());
1078 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1080 DEBUG(dbgs() << "\nPromoting ";
1083 Result.getNode()->dump(&DAG);
1085 WorklistRemover DeadNodes(*this);
1086 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1087 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1088 deleteAndRecombine(N);
1089 AddToWorklist(Result.getNode());
1095 /// \brief Recursively delete a node which has no uses and any operands for
1096 /// which it is the only use.
1098 /// Note that this both deletes the nodes and removes them from the worklist.
1099 /// It also adds any nodes who have had a user deleted to the worklist as they
1100 /// may now have only one use and subject to other combines.
1101 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1102 if (!N->use_empty())
1105 SmallSetVector<SDNode *, 16> Nodes;
1108 N = Nodes.pop_back_val();
1112 if (N->use_empty()) {
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1114 Nodes.insert(N->getOperand(i).getNode());
1116 removeFromWorklist(N);
1121 } while (!Nodes.empty());
1125 //===----------------------------------------------------------------------===//
1126 // Main DAG Combiner implementation
1127 //===----------------------------------------------------------------------===//
1129 void DAGCombiner::Run(CombineLevel AtLevel) {
1130 // set the instance variables, so that the various visit routines may use it.
1132 LegalOperations = Level >= AfterLegalizeVectorOps;
1133 LegalTypes = Level >= AfterLegalizeTypes;
1135 // Add all the dag nodes to the worklist.
1136 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1137 E = DAG.allnodes_end(); I != E; ++I)
1140 // Create a dummy node (which is not added to allnodes), that adds a reference
1141 // to the root node, preventing it from being deleted, and tracking any
1142 // changes of the root.
1143 HandleSDNode Dummy(DAG.getRoot());
1145 // while the worklist isn't empty, find a node and
1146 // try and combine it.
1147 while (!WorklistMap.empty()) {
1149 // The Worklist holds the SDNodes in order, but it may contain null entries.
1151 N = Worklist.pop_back_val();
1154 bool GoodWorklistEntry = WorklistMap.erase(N);
1155 (void)GoodWorklistEntry;
1156 assert(GoodWorklistEntry &&
1157 "Found a worklist entry without a corresponding map entry!");
1159 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1160 // N is deleted from the DAG, since they too may now be dead or may have a
1161 // reduced number of uses, allowing other xforms.
1162 if (recursivelyDeleteUnusedNodes(N))
1165 WorklistRemover DeadNodes(*this);
1167 // If this combine is running after legalizing the DAG, re-legalize any
1168 // nodes pulled off the worklist.
1169 if (Level == AfterLegalizeDAG) {
1170 SmallSetVector<SDNode *, 16> UpdatedNodes;
1171 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1173 for (SDNode *LN : UpdatedNodes) {
1175 AddUsersToWorklist(LN);
1181 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1183 // Add any operands of the new node which have not yet been combined to the
1184 // worklist as well. Because the worklist uniques things already, this
1185 // won't repeatedly process the same operand.
1186 CombinedNodes.insert(N);
1187 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1188 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1189 AddToWorklist(N->getOperand(i).getNode());
1191 SDValue RV = combine(N);
1198 // If we get back the same node we passed in, rather than a new node or
1199 // zero, we know that the node must have defined multiple values and
1200 // CombineTo was used. Since CombineTo takes care of the worklist
1201 // mechanics for us, we have no work to do in this case.
1202 if (RV.getNode() == N)
1205 assert(N->getOpcode() != ISD::DELETED_NODE &&
1206 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1207 "Node was deleted but visit returned new node!");
1209 DEBUG(dbgs() << " ... into: ";
1210 RV.getNode()->dump(&DAG));
1212 // Transfer debug value.
1213 DAG.TransferDbgValues(SDValue(N, 0), RV);
1214 if (N->getNumValues() == RV.getNode()->getNumValues())
1215 DAG.ReplaceAllUsesWith(N, RV.getNode());
1217 assert(N->getValueType(0) == RV.getValueType() &&
1218 N->getNumValues() == 1 && "Type mismatch");
1220 DAG.ReplaceAllUsesWith(N, &OpV);
1223 // Push the new node and any users onto the worklist
1224 AddToWorklist(RV.getNode());
1225 AddUsersToWorklist(RV.getNode());
1227 // Finally, if the node is now dead, remove it from the graph. The node
1228 // may not be dead if the replacement process recursively simplified to
1229 // something else needing this node. This will also take care of adding any
1230 // operands which have lost a user to the worklist.
1231 recursivelyDeleteUnusedNodes(N);
1234 // If the root changed (e.g. it was a dead load, update the root).
1235 DAG.setRoot(Dummy.getValue());
1236 DAG.RemoveDeadNodes();
1239 SDValue DAGCombiner::visit(SDNode *N) {
1240 switch (N->getOpcode()) {
1242 case ISD::TokenFactor: return visitTokenFactor(N);
1243 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1244 case ISD::ADD: return visitADD(N);
1245 case ISD::SUB: return visitSUB(N);
1246 case ISD::ADDC: return visitADDC(N);
1247 case ISD::SUBC: return visitSUBC(N);
1248 case ISD::ADDE: return visitADDE(N);
1249 case ISD::SUBE: return visitSUBE(N);
1250 case ISD::MUL: return visitMUL(N);
1251 case ISD::SDIV: return visitSDIV(N);
1252 case ISD::UDIV: return visitUDIV(N);
1253 case ISD::SREM: return visitSREM(N);
1254 case ISD::UREM: return visitUREM(N);
1255 case ISD::MULHU: return visitMULHU(N);
1256 case ISD::MULHS: return visitMULHS(N);
1257 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1258 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1259 case ISD::SMULO: return visitSMULO(N);
1260 case ISD::UMULO: return visitUMULO(N);
1261 case ISD::SDIVREM: return visitSDIVREM(N);
1262 case ISD::UDIVREM: return visitUDIVREM(N);
1263 case ISD::AND: return visitAND(N);
1264 case ISD::OR: return visitOR(N);
1265 case ISD::XOR: return visitXOR(N);
1266 case ISD::SHL: return visitSHL(N);
1267 case ISD::SRA: return visitSRA(N);
1268 case ISD::SRL: return visitSRL(N);
1270 case ISD::ROTL: return visitRotate(N);
1271 case ISD::CTLZ: return visitCTLZ(N);
1272 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1273 case ISD::CTTZ: return visitCTTZ(N);
1274 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1275 case ISD::CTPOP: return visitCTPOP(N);
1276 case ISD::SELECT: return visitSELECT(N);
1277 case ISD::VSELECT: return visitVSELECT(N);
1278 case ISD::SELECT_CC: return visitSELECT_CC(N);
1279 case ISD::SETCC: return visitSETCC(N);
1280 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1281 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1282 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1283 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1284 case ISD::TRUNCATE: return visitTRUNCATE(N);
1285 case ISD::BITCAST: return visitBITCAST(N);
1286 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1287 case ISD::FADD: return visitFADD(N);
1288 case ISD::FSUB: return visitFSUB(N);
1289 case ISD::FMUL: return visitFMUL(N);
1290 case ISD::FMA: return visitFMA(N);
1291 case ISD::FDIV: return visitFDIV(N);
1292 case ISD::FREM: return visitFREM(N);
1293 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1294 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1295 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1296 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1297 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1298 case ISD::FP_ROUND: return visitFP_ROUND(N);
1299 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1300 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1301 case ISD::FNEG: return visitFNEG(N);
1302 case ISD::FABS: return visitFABS(N);
1303 case ISD::FFLOOR: return visitFFLOOR(N);
1304 case ISD::FCEIL: return visitFCEIL(N);
1305 case ISD::FTRUNC: return visitFTRUNC(N);
1306 case ISD::BRCOND: return visitBRCOND(N);
1307 case ISD::BR_CC: return visitBR_CC(N);
1308 case ISD::LOAD: return visitLOAD(N);
1309 case ISD::STORE: return visitSTORE(N);
1310 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1311 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1312 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1313 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1314 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1315 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1316 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1321 SDValue DAGCombiner::combine(SDNode *N) {
1322 SDValue RV = visit(N);
1324 // If nothing happened, try a target-specific DAG combine.
1325 if (!RV.getNode()) {
1326 assert(N->getOpcode() != ISD::DELETED_NODE &&
1327 "Node was deleted but visit returned NULL!");
1329 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1330 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1332 // Expose the DAG combiner to the target combiner impls.
1333 TargetLowering::DAGCombinerInfo
1334 DagCombineInfo(DAG, Level, false, this);
1336 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1340 // If nothing happened still, try promoting the operation.
1341 if (!RV.getNode()) {
1342 switch (N->getOpcode()) {
1350 RV = PromoteIntBinOp(SDValue(N, 0));
1355 RV = PromoteIntShiftOp(SDValue(N, 0));
1357 case ISD::SIGN_EXTEND:
1358 case ISD::ZERO_EXTEND:
1359 case ISD::ANY_EXTEND:
1360 RV = PromoteExtend(SDValue(N, 0));
1363 if (PromoteLoad(SDValue(N, 0)))
1369 // If N is a commutative binary node, try commuting it to enable more
1371 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1372 N->getNumValues() == 1) {
1373 SDValue N0 = N->getOperand(0);
1374 SDValue N1 = N->getOperand(1);
1376 // Constant operands are canonicalized to RHS.
1377 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1378 SDValue Ops[] = {N1, N0};
1380 if (const BinaryWithFlagsSDNode *BinNode =
1381 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1382 CSENode = DAG.getNodeIfExists(
1383 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1384 BinNode->hasNoSignedWrap(), BinNode->isExact());
1386 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1389 return SDValue(CSENode, 0);
1396 /// getInputChainForNode - Given a node, return its input chain if it has one,
1397 /// otherwise return a null sd operand.
1398 static SDValue getInputChainForNode(SDNode *N) {
1399 if (unsigned NumOps = N->getNumOperands()) {
1400 if (N->getOperand(0).getValueType() == MVT::Other)
1401 return N->getOperand(0);
1402 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1403 return N->getOperand(NumOps-1);
1404 for (unsigned i = 1; i < NumOps-1; ++i)
1405 if (N->getOperand(i).getValueType() == MVT::Other)
1406 return N->getOperand(i);
1411 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1412 // If N has two operands, where one has an input chain equal to the other,
1413 // the 'other' chain is redundant.
1414 if (N->getNumOperands() == 2) {
1415 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1416 return N->getOperand(0);
1417 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1418 return N->getOperand(1);
1421 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1422 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1423 SmallPtrSet<SDNode*, 16> SeenOps;
1424 bool Changed = false; // If we should replace this token factor.
1426 // Start out with this token factor.
1429 // Iterate through token factors. The TFs grows when new token factors are
1431 for (unsigned i = 0; i < TFs.size(); ++i) {
1432 SDNode *TF = TFs[i];
1434 // Check each of the operands.
1435 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1436 SDValue Op = TF->getOperand(i);
1438 switch (Op.getOpcode()) {
1439 case ISD::EntryToken:
1440 // Entry tokens don't need to be added to the list. They are
1445 case ISD::TokenFactor:
1446 if (Op.hasOneUse() &&
1447 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1448 // Queue up for processing.
1449 TFs.push_back(Op.getNode());
1450 // Clean up in case the token factor is removed.
1451 AddToWorklist(Op.getNode());
1458 // Only add if it isn't already in the list.
1459 if (SeenOps.insert(Op.getNode()))
1470 // If we've change things around then replace token factor.
1473 // The entry token is the only possible outcome.
1474 Result = DAG.getEntryNode();
1476 // New and improved token factor.
1477 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1480 // Don't add users to work list.
1481 return CombineTo(N, Result, false);
1487 /// MERGE_VALUES can always be eliminated.
1488 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1489 WorklistRemover DeadNodes(*this);
1490 // Replacing results may cause a different MERGE_VALUES to suddenly
1491 // be CSE'd with N, and carry its uses with it. Iterate until no
1492 // uses remain, to ensure that the node can be safely deleted.
1493 // First add the users of this node to the work list so that they
1494 // can be tried again once they have new operands.
1495 AddUsersToWorklist(N);
1497 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1498 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1499 } while (!N->use_empty());
1500 deleteAndRecombine(N);
1501 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1505 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1506 SelectionDAG &DAG) {
1507 EVT VT = N0.getValueType();
1508 SDValue N00 = N0.getOperand(0);
1509 SDValue N01 = N0.getOperand(1);
1510 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1512 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1513 isa<ConstantSDNode>(N00.getOperand(1))) {
1514 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1515 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1516 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1517 N00.getOperand(0), N01),
1518 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1519 N00.getOperand(1), N01));
1520 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1526 SDValue DAGCombiner::visitADD(SDNode *N) {
1527 SDValue N0 = N->getOperand(0);
1528 SDValue N1 = N->getOperand(1);
1529 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1531 EVT VT = N0.getValueType();
1534 if (VT.isVector()) {
1535 SDValue FoldedVOp = SimplifyVBinOp(N);
1536 if (FoldedVOp.getNode()) return FoldedVOp;
1538 // fold (add x, 0) -> x, vector edition
1539 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1541 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1545 // fold (add x, undef) -> undef
1546 if (N0.getOpcode() == ISD::UNDEF)
1548 if (N1.getOpcode() == ISD::UNDEF)
1550 // fold (add c1, c2) -> c1+c2
1552 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1553 // canonicalize constant to RHS
1555 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1556 // fold (add x, 0) -> x
1557 if (N1C && N1C->isNullValue())
1559 // fold (add Sym, c) -> Sym+c
1560 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1561 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1562 GA->getOpcode() == ISD::GlobalAddress)
1563 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1565 (uint64_t)N1C->getSExtValue());
1566 // fold ((c1-A)+c2) -> (c1+c2)-A
1567 if (N1C && N0.getOpcode() == ISD::SUB)
1568 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570 DAG.getConstant(N1C->getAPIntValue()+
1571 N0C->getAPIntValue(), VT),
1574 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1577 // fold ((0-A) + B) -> B-A
1578 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1579 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1581 // fold (A + (0-B)) -> A-B
1582 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1583 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1584 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1585 // fold (A+(B-A)) -> B
1586 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1587 return N1.getOperand(0);
1588 // fold ((B-A)+A) -> B
1589 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1590 return N0.getOperand(0);
1591 // fold (A+(B-(A+C))) to (B-C)
1592 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1593 N0 == N1.getOperand(1).getOperand(0))
1594 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1595 N1.getOperand(1).getOperand(1));
1596 // fold (A+(B-(C+A))) to (B-C)
1597 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1598 N0 == N1.getOperand(1).getOperand(1))
1599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1600 N1.getOperand(1).getOperand(0));
1601 // fold (A+((B-A)+or-C)) to (B+or-C)
1602 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1603 N1.getOperand(0).getOpcode() == ISD::SUB &&
1604 N0 == N1.getOperand(0).getOperand(1))
1605 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1606 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1608 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1609 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1610 SDValue N00 = N0.getOperand(0);
1611 SDValue N01 = N0.getOperand(1);
1612 SDValue N10 = N1.getOperand(0);
1613 SDValue N11 = N1.getOperand(1);
1615 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1616 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1617 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1618 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1621 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1622 return SDValue(N, 0);
1624 // fold (a+b) -> (a|b) iff a and b share no bits.
1625 if (VT.isInteger() && !VT.isVector()) {
1626 APInt LHSZero, LHSOne;
1627 APInt RHSZero, RHSOne;
1628 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1630 if (LHSZero.getBoolValue()) {
1631 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1633 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1634 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1635 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1636 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1637 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1642 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1643 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1644 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1645 if (Result.getNode()) return Result;
1647 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1648 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1649 if (Result.getNode()) return Result;
1652 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1653 if (N1.getOpcode() == ISD::SHL &&
1654 N1.getOperand(0).getOpcode() == ISD::SUB)
1655 if (ConstantSDNode *C =
1656 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1657 if (C->getAPIntValue() == 0)
1658 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1659 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1660 N1.getOperand(0).getOperand(1),
1662 if (N0.getOpcode() == ISD::SHL &&
1663 N0.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
1667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669 N0.getOperand(0).getOperand(1),
1672 if (N1.getOpcode() == ISD::AND) {
1673 SDValue AndOp0 = N1.getOperand(0);
1674 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1675 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1676 unsigned DestBits = VT.getScalarType().getSizeInBits();
1678 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1679 // and similar xforms where the inner op is either ~0 or 0.
1680 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1682 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1686 // add (sext i1), X -> sub X, (zext i1)
1687 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1688 N0.getOperand(0).getValueType() == MVT::i1 &&
1689 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1691 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1692 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1698 SDValue DAGCombiner::visitADDC(SDNode *N) {
1699 SDValue N0 = N->getOperand(0);
1700 SDValue N1 = N->getOperand(1);
1701 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1703 EVT VT = N0.getValueType();
1705 // If the flag result is dead, turn this into an ADD.
1706 if (!N->hasAnyUseOfValue(1))
1707 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1708 DAG.getNode(ISD::CARRY_FALSE,
1709 SDLoc(N), MVT::Glue));
1711 // canonicalize constant to RHS.
1713 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1715 // fold (addc x, 0) -> x + no carry out
1716 if (N1C && N1C->isNullValue())
1717 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1718 SDLoc(N), MVT::Glue));
1720 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1721 APInt LHSZero, LHSOne;
1722 APInt RHSZero, RHSOne;
1723 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1725 if (LHSZero.getBoolValue()) {
1726 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1728 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1729 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1730 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1731 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1732 DAG.getNode(ISD::CARRY_FALSE,
1733 SDLoc(N), MVT::Glue));
1739 SDValue DAGCombiner::visitADDE(SDNode *N) {
1740 SDValue N0 = N->getOperand(0);
1741 SDValue N1 = N->getOperand(1);
1742 SDValue CarryIn = N->getOperand(2);
1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1746 // canonicalize constant to RHS
1748 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1751 // fold (adde x, y, false) -> (addc x, y)
1752 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1758 // Since it may not be valid to emit a fold to zero for vector initializers
1759 // check if we can before folding.
1760 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1762 bool LegalOperations, bool LegalTypes) {
1764 return DAG.getConstant(0, VT);
1765 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1766 return DAG.getConstant(0, VT);
1770 SDValue DAGCombiner::visitSUB(SDNode *N) {
1771 SDValue N0 = N->getOperand(0);
1772 SDValue N1 = N->getOperand(1);
1773 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1774 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1775 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1776 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1777 EVT VT = N0.getValueType();
1780 if (VT.isVector()) {
1781 SDValue FoldedVOp = SimplifyVBinOp(N);
1782 if (FoldedVOp.getNode()) return FoldedVOp;
1784 // fold (sub x, 0) -> x, vector edition
1785 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1789 // fold (sub x, x) -> 0
1790 // FIXME: Refactor this and xor and other similar operations together.
1792 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1793 // fold (sub c1, c2) -> c1-c2
1795 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1796 // fold (sub x, c) -> (add x, -c)
1798 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1799 DAG.getConstant(-N1C->getAPIntValue(), VT));
1800 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1801 if (N0C && N0C->isAllOnesValue())
1802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1803 // fold A-(A-B) -> B
1804 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1805 return N1.getOperand(1);
1806 // fold (A+B)-A -> B
1807 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1808 return N0.getOperand(1);
1809 // fold (A+B)-B -> A
1810 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1811 return N0.getOperand(0);
1812 // fold C2-(A+C1) -> (C2-C1)-A
1813 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1814 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1816 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1819 // fold ((A+(B+or-C))-B) -> A+or-C
1820 if (N0.getOpcode() == ISD::ADD &&
1821 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1822 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1823 N0.getOperand(1).getOperand(0) == N1)
1824 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1825 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1826 // fold ((A+(C+B))-B) -> A+C
1827 if (N0.getOpcode() == ISD::ADD &&
1828 N0.getOperand(1).getOpcode() == ISD::ADD &&
1829 N0.getOperand(1).getOperand(1) == N1)
1830 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1831 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1832 // fold ((A-(B-C))-C) -> A-B
1833 if (N0.getOpcode() == ISD::SUB &&
1834 N0.getOperand(1).getOpcode() == ISD::SUB &&
1835 N0.getOperand(1).getOperand(1) == N1)
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1839 // If either operand of a sub is undef, the result is undef
1840 if (N0.getOpcode() == ISD::UNDEF)
1842 if (N1.getOpcode() == ISD::UNDEF)
1845 // If the relocation model supports it, consider symbol offsets.
1846 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1847 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1848 // fold (sub Sym, c) -> Sym-c
1849 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1850 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1852 (uint64_t)N1C->getSExtValue());
1853 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1854 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1855 if (GA->getGlobal() == GB->getGlobal())
1856 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1863 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
1866 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1867 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1868 EVT VT = N0.getValueType();
1870 // If the flag result is dead, turn this into an SUB.
1871 if (!N->hasAnyUseOfValue(1))
1872 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1873 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1876 // fold (subc x, x) -> 0 + no borrow
1878 return CombineTo(N, DAG.getConstant(0, VT),
1879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1882 // fold (subc x, 0) -> x + no borrow
1883 if (N1C && N1C->isNullValue())
1884 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1887 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1888 if (N0C && N0C->isAllOnesValue())
1889 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1890 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1897 SDValue N0 = N->getOperand(0);
1898 SDValue N1 = N->getOperand(1);
1899 SDValue CarryIn = N->getOperand(2);
1901 // fold (sube x, y, false) -> (subc x, y)
1902 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1903 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1908 SDValue DAGCombiner::visitMUL(SDNode *N) {
1909 SDValue N0 = N->getOperand(0);
1910 SDValue N1 = N->getOperand(1);
1911 EVT VT = N0.getValueType();
1913 // fold (mul x, undef) -> 0
1914 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1915 return DAG.getConstant(0, VT);
1917 bool N0IsConst = false;
1918 bool N1IsConst = false;
1919 APInt ConstValue0, ConstValue1;
1921 if (VT.isVector()) {
1922 SDValue FoldedVOp = SimplifyVBinOp(N);
1923 if (FoldedVOp.getNode()) return FoldedVOp;
1925 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1926 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1928 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1929 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1931 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1932 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1936 // fold (mul c1, c2) -> c1*c2
1937 if (N0IsConst && N1IsConst)
1938 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1940 // canonicalize constant to RHS
1941 if (N0IsConst && !N1IsConst)
1942 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1943 // fold (mul x, 0) -> 0
1944 if (N1IsConst && ConstValue1 == 0)
1946 // We require a splat of the entire scalar bit width for non-contiguous
1949 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1950 // fold (mul x, 1) -> x
1951 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1953 // fold (mul x, -1) -> 0-x
1954 if (N1IsConst && ConstValue1.isAllOnesValue())
1955 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1956 DAG.getConstant(0, VT), N0);
1957 // fold (mul x, (1 << c)) -> x << c
1958 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1959 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1960 DAG.getConstant(ConstValue1.logBase2(),
1961 getShiftAmountTy(N0.getValueType())));
1962 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1963 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1964 unsigned Log2Val = (-ConstValue1).logBase2();
1965 // FIXME: If the input is something that is easily negated (e.g. a
1966 // single-use add), we should put the negate there.
1967 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1968 DAG.getConstant(0, VT),
1969 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1970 DAG.getConstant(Log2Val,
1971 getShiftAmountTy(N0.getValueType()))));
1975 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1976 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1977 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1978 isa<ConstantSDNode>(N0.getOperand(1)))) {
1979 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1980 N1, N0.getOperand(1));
1981 AddToWorklist(C3.getNode());
1982 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1983 N0.getOperand(0), C3);
1986 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1989 SDValue Sh(nullptr,0), Y(nullptr,0);
1990 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1991 if (N0.getOpcode() == ISD::SHL &&
1992 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1993 isa<ConstantSDNode>(N0.getOperand(1))) &&
1994 N0.getNode()->hasOneUse()) {
1996 } else if (N1.getOpcode() == ISD::SHL &&
1997 isa<ConstantSDNode>(N1.getOperand(1)) &&
1998 N1.getNode()->hasOneUse()) {
2003 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004 Sh.getOperand(0), Y);
2005 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2006 Mul, Sh.getOperand(1));
2010 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2011 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2012 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013 isa<ConstantSDNode>(N0.getOperand(1))))
2014 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2015 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2016 N0.getOperand(0), N1),
2017 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2018 N0.getOperand(1), N1));
2021 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2028 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2032 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2033 EVT VT = N->getValueType(0);
2036 if (VT.isVector()) {
2037 SDValue FoldedVOp = SimplifyVBinOp(N);
2038 if (FoldedVOp.getNode()) return FoldedVOp;
2041 // fold (sdiv c1, c2) -> c1/c2
2042 if (N0C && N1C && !N1C->isNullValue())
2043 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2044 // fold (sdiv X, 1) -> X
2045 if (N1C && N1C->getAPIntValue() == 1LL)
2047 // fold (sdiv X, -1) -> 0-X
2048 if (N1C && N1C->isAllOnesValue())
2049 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2050 DAG.getConstant(0, VT), N0);
2051 // If we know the sign bits of both operands are zero, strength reduce to a
2052 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2053 if (!VT.isVector()) {
2054 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2055 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2059 // fold (sdiv X, pow2) -> simple ops after legalize
2060 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2061 (-N1C->getAPIntValue()).isPowerOf2())) {
2062 // If dividing by powers of two is cheap, then don't perform the following
2064 if (TLI.isPow2DivCheap())
2067 // Target-specific implementation of sdiv x, pow2.
2068 SDValue Res = BuildSDIVPow2(N);
2072 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2074 // Splat the sign bit into the register
2076 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2077 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2078 getShiftAmountTy(N0.getValueType())));
2079 AddToWorklist(SGN.getNode());
2081 // Add (N0 < 0) ? abs2 - 1 : 0;
2083 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2084 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2085 getShiftAmountTy(SGN.getValueType())));
2086 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2087 AddToWorklist(SRL.getNode());
2088 AddToWorklist(ADD.getNode()); // Divide by pow2
2089 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2090 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2092 // If we're dividing by a positive value, we're done. Otherwise, we must
2093 // negate the result.
2094 if (N1C->getAPIntValue().isNonNegative())
2097 AddToWorklist(SRA.getNode());
2098 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2101 // if integer divide is expensive and we satisfy the requirements, emit an
2102 // alternate sequence.
2103 if (N1C && !TLI.isIntDivCheap()) {
2104 SDValue Op = BuildSDIV(N);
2105 if (Op.getNode()) return Op;
2109 if (N0.getOpcode() == ISD::UNDEF)
2110 return DAG.getConstant(0, VT);
2111 // X / undef -> undef
2112 if (N1.getOpcode() == ISD::UNDEF)
2118 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2119 SDValue N0 = N->getOperand(0);
2120 SDValue N1 = N->getOperand(1);
2121 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123 EVT VT = N->getValueType(0);
2126 if (VT.isVector()) {
2127 SDValue FoldedVOp = SimplifyVBinOp(N);
2128 if (FoldedVOp.getNode()) return FoldedVOp;
2131 // fold (udiv c1, c2) -> c1/c2
2132 if (N0C && N1C && !N1C->isNullValue())
2133 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2134 // fold (udiv x, (1 << c)) -> x >>u c
2135 if (N1C && N1C->getAPIntValue().isPowerOf2())
2136 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2137 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2138 getShiftAmountTy(N0.getValueType())));
2139 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2140 if (N1.getOpcode() == ISD::SHL) {
2141 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2142 if (SHC->getAPIntValue().isPowerOf2()) {
2143 EVT ADDVT = N1.getOperand(1).getValueType();
2144 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2146 DAG.getConstant(SHC->getAPIntValue()
2149 AddToWorklist(Add.getNode());
2150 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2154 // fold (udiv x, c) -> alternate
2155 if (N1C && !TLI.isIntDivCheap()) {
2156 SDValue Op = BuildUDIV(N);
2157 if (Op.getNode()) return Op;
2161 if (N0.getOpcode() == ISD::UNDEF)
2162 return DAG.getConstant(0, VT);
2163 // X / undef -> undef
2164 if (N1.getOpcode() == ISD::UNDEF)
2170 SDValue DAGCombiner::visitSREM(SDNode *N) {
2171 SDValue N0 = N->getOperand(0);
2172 SDValue N1 = N->getOperand(1);
2173 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2174 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2175 EVT VT = N->getValueType(0);
2177 // fold (srem c1, c2) -> c1%c2
2178 if (N0C && N1C && !N1C->isNullValue())
2179 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2180 // If we know the sign bits of both operands are zero, strength reduce to a
2181 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2182 if (!VT.isVector()) {
2183 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2184 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
2189 if (N1C && !N1C->isNullValue()) {
2190 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2191 AddToWorklist(Div.getNode());
2192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2197 AddToWorklist(Mul.getNode());
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2212 SDValue DAGCombiner::visitUREM(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
2215 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2216 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2217 EVT VT = N->getValueType(0);
2219 // fold (urem c1, c2) -> c1%c2
2220 if (N0C && N1C && !N1C->isNullValue())
2221 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2222 // fold (urem x, pow2) -> (and x, pow2-1)
2223 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2225 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2226 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2227 if (N1.getOpcode() == ISD::SHL) {
2228 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2229 if (SHC->getAPIntValue().isPowerOf2()) {
2231 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2232 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2234 AddToWorklist(Add.getNode());
2235 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2240 // If X/C can be simplified by the division-by-constant logic, lower
2241 // X%C to the equivalent of X-X/C*C.
2242 if (N1C && !N1C->isNullValue()) {
2243 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2244 AddToWorklist(Div.getNode());
2245 SDValue OptimizedDiv = combine(Div.getNode());
2246 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2247 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2249 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2250 AddToWorklist(Mul.getNode());
2256 if (N0.getOpcode() == ISD::UNDEF)
2257 return DAG.getConstant(0, VT);
2258 // X % undef -> undef
2259 if (N1.getOpcode() == ISD::UNDEF)
2265 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2266 SDValue N0 = N->getOperand(0);
2267 SDValue N1 = N->getOperand(1);
2268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2269 EVT VT = N->getValueType(0);
2272 // fold (mulhs x, 0) -> 0
2273 if (N1C && N1C->isNullValue())
2275 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2276 if (N1C && N1C->getAPIntValue() == 1)
2277 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2278 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2279 getShiftAmountTy(N0.getValueType())));
2280 // fold (mulhs x, undef) -> 0
2281 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2282 return DAG.getConstant(0, VT);
2284 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2286 if (VT.isSimple() && !VT.isVector()) {
2287 MVT Simple = VT.getSimpleVT();
2288 unsigned SimpleSize = Simple.getSizeInBits();
2289 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2290 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2291 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2292 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2293 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2294 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2295 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2296 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2303 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2304 SDValue N0 = N->getOperand(0);
2305 SDValue N1 = N->getOperand(1);
2306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2307 EVT VT = N->getValueType(0);
2310 // fold (mulhu x, 0) -> 0
2311 if (N1C && N1C->isNullValue())
2313 // fold (mulhu x, 1) -> 0
2314 if (N1C && N1C->getAPIntValue() == 1)
2315 return DAG.getConstant(0, N0.getValueType());
2316 // fold (mulhu x, undef) -> 0
2317 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2318 return DAG.getConstant(0, VT);
2320 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2322 if (VT.isSimple() && !VT.isVector()) {
2323 MVT Simple = VT.getSimpleVT();
2324 unsigned SimpleSize = Simple.getSizeInBits();
2325 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2326 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2327 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2328 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2329 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2330 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2331 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2332 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2339 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2340 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2341 /// that are being performed. Return true if a simplification was made.
2343 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2345 // If the high half is not needed, just compute the low half.
2346 bool HiExists = N->hasAnyUseOfValue(1);
2348 (!LegalOperations ||
2349 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2350 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2351 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2352 return CombineTo(N, Res, Res);
2355 // If the low half is not needed, just compute the high half.
2356 bool LoExists = N->hasAnyUseOfValue(0);
2358 (!LegalOperations ||
2359 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2360 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2361 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2362 return CombineTo(N, Res, Res);
2365 // If both halves are used, return as it is.
2366 if (LoExists && HiExists)
2369 // If the two computed results can be simplified separately, separate them.
2371 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2372 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2373 AddToWorklist(Lo.getNode());
2374 SDValue LoOpt = combine(Lo.getNode());
2375 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2376 (!LegalOperations ||
2377 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2378 return CombineTo(N, LoOpt, LoOpt);
2382 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2383 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2384 AddToWorklist(Hi.getNode());
2385 SDValue HiOpt = combine(Hi.getNode());
2386 if (HiOpt.getNode() && HiOpt != Hi &&
2387 (!LegalOperations ||
2388 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2389 return CombineTo(N, HiOpt, HiOpt);
2395 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2397 if (Res.getNode()) return Res;
2399 EVT VT = N->getValueType(0);
2402 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2404 if (VT.isSimple() && !VT.isVector()) {
2405 MVT Simple = VT.getSimpleVT();
2406 unsigned SimpleSize = Simple.getSizeInBits();
2407 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2408 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2409 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2410 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2411 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2412 // Compute the high part as N1.
2413 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2414 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2415 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2416 // Compute the low part as N0.
2417 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2418 return CombineTo(N, Lo, Hi);
2425 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2427 if (Res.getNode()) return Res;
2429 EVT VT = N->getValueType(0);
2432 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2434 if (VT.isSimple() && !VT.isVector()) {
2435 MVT Simple = VT.getSimpleVT();
2436 unsigned SimpleSize = Simple.getSizeInBits();
2437 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2438 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2439 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2440 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2441 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2442 // Compute the high part as N1.
2443 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2444 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2445 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2446 // Compute the low part as N0.
2447 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2448 return CombineTo(N, Lo, Hi);
2455 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2456 // (smulo x, 2) -> (saddo x, x)
2457 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458 if (C2->getAPIntValue() == 2)
2459 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2460 N->getOperand(0), N->getOperand(0));
2465 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2466 // (umulo x, 2) -> (uaddo x, x)
2467 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2468 if (C2->getAPIntValue() == 2)
2469 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2470 N->getOperand(0), N->getOperand(0));
2475 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2477 if (Res.getNode()) return Res;
2482 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2484 if (Res.getNode()) return Res;
2489 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2490 /// two operands of the same opcode, try to simplify it.
2491 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2492 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2493 EVT VT = N0.getValueType();
2494 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2496 // Bail early if none of these transforms apply.
2497 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2499 // For each of OP in AND/OR/XOR:
2500 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2501 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2502 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2503 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2505 // do not sink logical op inside of a vector extend, since it may combine
2507 EVT Op0VT = N0.getOperand(0).getValueType();
2508 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2509 N0.getOpcode() == ISD::SIGN_EXTEND ||
2510 // Avoid infinite looping with PromoteIntBinOp.
2511 (N0.getOpcode() == ISD::ANY_EXTEND &&
2512 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2513 (N0.getOpcode() == ISD::TRUNCATE &&
2514 (!TLI.isZExtFree(VT, Op0VT) ||
2515 !TLI.isTruncateFree(Op0VT, VT)) &&
2516 TLI.isTypeLegal(Op0VT))) &&
2518 Op0VT == N1.getOperand(0).getValueType() &&
2519 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2520 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2521 N0.getOperand(0).getValueType(),
2522 N0.getOperand(0), N1.getOperand(0));
2523 AddToWorklist(ORNode.getNode());
2524 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2527 // For each of OP in SHL/SRL/SRA/AND...
2528 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2529 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2530 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2531 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2532 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2533 N0.getOperand(1) == N1.getOperand(1)) {
2534 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2535 N0.getOperand(0).getValueType(),
2536 N0.getOperand(0), N1.getOperand(0));
2537 AddToWorklist(ORNode.getNode());
2538 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2539 ORNode, N0.getOperand(1));
2542 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2543 // Only perform this optimization after type legalization and before
2544 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2545 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2546 // we don't want to undo this promotion.
2547 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2549 if ((N0.getOpcode() == ISD::BITCAST ||
2550 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2551 Level == AfterLegalizeTypes) {
2552 SDValue In0 = N0.getOperand(0);
2553 SDValue In1 = N1.getOperand(0);
2554 EVT In0Ty = In0.getValueType();
2555 EVT In1Ty = In1.getValueType();
2557 // If both incoming values are integers, and the original types are the
2559 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2560 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2561 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2562 AddToWorklist(Op.getNode());
2567 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2568 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2569 // If both shuffles use the same mask, and both shuffle within a single
2570 // vector, then it is worthwhile to move the swizzle after the operation.
2571 // The type-legalizer generates this pattern when loading illegal
2572 // vector types from memory. In many cases this allows additional shuffle
2574 // There are other cases where moving the shuffle after the xor/and/or
2575 // is profitable even if shuffles don't perform a swizzle.
2576 // If both shuffles use the same mask, and both shuffles have the same first
2577 // or second operand, then it might still be profitable to move the shuffle
2578 // after the xor/and/or operation.
2579 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2580 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2581 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2583 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2584 "Inputs to shuffles are not the same type");
2586 // Check that both shuffles use the same mask. The masks are known to be of
2587 // the same length because the result vector type is the same.
2588 // Check also that shuffles have only one use to avoid introducing extra
2590 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2591 SVN0->getMask().equals(SVN1->getMask())) {
2592 SDValue ShOp = N0->getOperand(1);
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 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2598 ShOp = DAG.getConstant(0, VT);
2603 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2604 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2605 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2606 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2607 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2608 N0->getOperand(0), N1->getOperand(0));
2609 AddToWorklist(NewNode.getNode());
2610 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2611 &SVN0->getMask()[0]);
2614 // Don't try to fold this node if it requires introducing a
2615 // build vector of all zeros that might be illegal at this stage.
2616 ShOp = N0->getOperand(0);
2617 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619 ShOp = DAG.getConstant(0, VT);
2624 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2625 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2626 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2627 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2628 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629 N0->getOperand(1), N1->getOperand(1));
2630 AddToWorklist(NewNode.getNode());
2631 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2632 &SVN0->getMask()[0]);
2640 SDValue DAGCombiner::visitAND(SDNode *N) {
2641 SDValue N0 = N->getOperand(0);
2642 SDValue N1 = N->getOperand(1);
2643 SDValue LL, LR, RL, RR, CC0, CC1;
2644 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2645 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2646 EVT VT = N1.getValueType();
2647 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2650 if (VT.isVector()) {
2651 SDValue FoldedVOp = SimplifyVBinOp(N);
2652 if (FoldedVOp.getNode()) return FoldedVOp;
2654 // fold (and x, 0) -> 0, vector edition
2655 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2657 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2660 // fold (and x, -1) -> x, vector edition
2661 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2663 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2667 // fold (and x, undef) -> 0
2668 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2669 return DAG.getConstant(0, VT);
2670 // fold (and c1, c2) -> c1&c2
2672 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2673 // canonicalize constant to RHS
2675 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2676 // fold (and x, -1) -> x
2677 if (N1C && N1C->isAllOnesValue())
2679 // if (and x, c) is known to be zero, return 0
2680 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2681 APInt::getAllOnesValue(BitWidth)))
2682 return DAG.getConstant(0, VT);
2684 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2687 // fold (and (or x, C), D) -> D if (C & D) == D
2688 if (N1C && N0.getOpcode() == ISD::OR)
2689 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2690 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2692 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2693 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2694 SDValue N0Op0 = N0.getOperand(0);
2695 APInt Mask = ~N1C->getAPIntValue();
2696 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2697 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2698 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2699 N0.getValueType(), N0Op0);
2701 // Replace uses of the AND with uses of the Zero extend node.
2704 // We actually want to replace all uses of the any_extend with the
2705 // zero_extend, to avoid duplicating things. This will later cause this
2706 // AND to be folded.
2707 CombineTo(N0.getNode(), Zext);
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2711 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2712 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2713 // already be zero by virtue of the width of the base type of the load.
2715 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2717 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2718 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2719 N0.getOpcode() == ISD::LOAD) {
2720 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2721 N0 : N0.getOperand(0) );
2723 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2724 // This can be a pure constant or a vector splat, in which case we treat the
2725 // vector as a scalar and use the splat value.
2726 APInt Constant = APInt::getNullValue(1);
2727 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2728 Constant = C->getAPIntValue();
2729 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2730 APInt SplatValue, SplatUndef;
2731 unsigned SplatBitSize;
2733 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2734 SplatBitSize, HasAnyUndefs);
2736 // Undef bits can contribute to a possible optimisation if set, so
2738 SplatValue |= SplatUndef;
2740 // The splat value may be something like "0x00FFFFFF", which means 0 for
2741 // the first vector value and FF for the rest, repeating. We need a mask
2742 // that will apply equally to all members of the vector, so AND all the
2743 // lanes of the constant together.
2744 EVT VT = Vector->getValueType(0);
2745 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2747 // If the splat value has been compressed to a bitlength lower
2748 // than the size of the vector lane, we need to re-expand it to
2750 if (BitWidth > SplatBitSize)
2751 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2752 SplatBitSize < BitWidth;
2753 SplatBitSize = SplatBitSize * 2)
2754 SplatValue |= SplatValue.shl(SplatBitSize);
2756 Constant = APInt::getAllOnesValue(BitWidth);
2757 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2758 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2762 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2763 // actually legal and isn't going to get expanded, else this is a false
2765 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2766 Load->getMemoryVT());
2768 // Resize the constant to the same size as the original memory access before
2769 // extension. If it is still the AllOnesValue then this AND is completely
2772 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2775 switch (Load->getExtensionType()) {
2776 default: B = false; break;
2777 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2779 case ISD::NON_EXTLOAD: B = true; break;
2782 if (B && Constant.isAllOnesValue()) {
2783 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2784 // preserve semantics once we get rid of the AND.
2785 SDValue NewLoad(Load, 0);
2786 if (Load->getExtensionType() == ISD::EXTLOAD) {
2787 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2788 Load->getValueType(0), SDLoc(Load),
2789 Load->getChain(), Load->getBasePtr(),
2790 Load->getOffset(), Load->getMemoryVT(),
2791 Load->getMemOperand());
2792 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2793 if (Load->getNumValues() == 3) {
2794 // PRE/POST_INC loads have 3 values.
2795 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2796 NewLoad.getValue(2) };
2797 CombineTo(Load, To, 3, true);
2799 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2803 // Fold the AND away, taking care not to fold to the old load node if we
2805 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2810 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2811 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2812 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2813 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2815 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2816 LL.getValueType().isInteger()) {
2817 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2818 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2819 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2820 LR.getValueType(), LL, RL);
2821 AddToWorklist(ORNode.getNode());
2822 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2824 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2825 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2826 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2827 LR.getValueType(), LL, RL);
2828 AddToWorklist(ANDNode.getNode());
2829 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2831 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2832 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2833 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2834 LR.getValueType(), LL, RL);
2835 AddToWorklist(ORNode.getNode());
2836 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2839 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2840 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2841 Op0 == Op1 && LL.getValueType().isInteger() &&
2842 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2843 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2844 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2845 cast<ConstantSDNode>(RR)->isNullValue()))) {
2846 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2847 LL, DAG.getConstant(1, LL.getValueType()));
2848 AddToWorklist(ADDNode.getNode());
2849 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2850 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2852 // canonicalize equivalent to ll == rl
2853 if (LL == RR && LR == RL) {
2854 Op1 = ISD::getSetCCSwappedOperands(Op1);
2857 if (LL == RL && LR == RR) {
2858 bool isInteger = LL.getValueType().isInteger();
2859 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2860 if (Result != ISD::SETCC_INVALID &&
2861 (!LegalOperations ||
2862 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2863 TLI.isOperationLegal(ISD::SETCC,
2864 getSetCCResultType(N0.getSimpleValueType())))))
2865 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2870 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2871 if (N0.getOpcode() == N1.getOpcode()) {
2872 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2873 if (Tmp.getNode()) return Tmp;
2876 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2877 // fold (and (sra)) -> (and (srl)) when possible.
2878 if (!VT.isVector() &&
2879 SimplifyDemandedBits(SDValue(N, 0)))
2880 return SDValue(N, 0);
2882 // fold (zext_inreg (extload x)) -> (zextload x)
2883 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2884 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2885 EVT MemVT = LN0->getMemoryVT();
2886 // If we zero all the possible extended bits, then we can turn this into
2887 // a zextload if we are running before legalize or the operation is legal.
2888 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2889 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2890 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2891 ((!LegalOperations && !LN0->isVolatile()) ||
2892 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2893 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2894 LN0->getChain(), LN0->getBasePtr(),
2895 MemVT, LN0->getMemOperand());
2897 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2898 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2901 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2902 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2905 EVT MemVT = LN0->getMemoryVT();
2906 // If we zero all the possible extended bits, then we can turn this into
2907 // a zextload if we are running before legalize or the operation is legal.
2908 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2909 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2910 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2911 ((!LegalOperations && !LN0->isVolatile()) ||
2912 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2914 LN0->getChain(), LN0->getBasePtr(),
2915 MemVT, LN0->getMemOperand());
2917 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2918 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2922 // fold (and (load x), 255) -> (zextload x, i8)
2923 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2924 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2925 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2926 (N0.getOpcode() == ISD::ANY_EXTEND &&
2927 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2928 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2929 LoadSDNode *LN0 = HasAnyExt
2930 ? cast<LoadSDNode>(N0.getOperand(0))
2931 : cast<LoadSDNode>(N0);
2932 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2933 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2934 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2935 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2936 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2937 EVT LoadedVT = LN0->getMemoryVT();
2939 if (ExtVT == LoadedVT &&
2940 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2941 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2944 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2945 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2946 LN0->getMemOperand());
2948 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2952 // Do not change the width of a volatile load.
2953 // Do not generate loads of non-round integer types since these can
2954 // be expensive (and would be wrong if the type is not byte sized).
2955 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2956 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2957 EVT PtrType = LN0->getOperand(1).getValueType();
2959 unsigned Alignment = LN0->getAlignment();
2960 SDValue NewPtr = LN0->getBasePtr();
2962 // For big endian targets, we need to add an offset to the pointer
2963 // to load the correct bytes. For little endian systems, we merely
2964 // need to read fewer bytes from the same pointer.
2965 if (TLI.isBigEndian()) {
2966 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2967 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2968 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2969 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2970 NewPtr, DAG.getConstant(PtrOff, PtrType));
2971 Alignment = MinAlign(Alignment, PtrOff);
2974 AddToWorklist(NewPtr.getNode());
2976 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2979 LN0->getChain(), NewPtr,
2980 LN0->getPointerInfo(),
2981 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2982 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2984 CombineTo(LN0, Load, Load.getValue(1));
2985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2991 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2992 VT.getSizeInBits() <= 64) {
2993 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2994 APInt ADDC = ADDI->getAPIntValue();
2995 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2996 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2997 // immediate for an add, but it is legal if its top c2 bits are set,
2998 // transform the ADD so the immediate doesn't need to be materialized
3000 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3001 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3002 SRLI->getZExtValue());
3003 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3005 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3007 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3008 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3009 CombineTo(N0.getNode(), NewAdd);
3010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3019 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3020 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3021 N0.getOperand(1), false);
3022 if (BSwap.getNode())
3029 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3031 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3032 bool DemandHighBits) {
3033 if (!LegalOperations)
3036 EVT VT = N->getValueType(0);
3037 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3039 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3042 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3043 bool LookPassAnd0 = false;
3044 bool LookPassAnd1 = false;
3045 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3047 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3049 if (N0.getOpcode() == ISD::AND) {
3050 if (!N0.getNode()->hasOneUse())
3052 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3053 if (!N01C || N01C->getZExtValue() != 0xFF00)
3055 N0 = N0.getOperand(0);
3056 LookPassAnd0 = true;
3059 if (N1.getOpcode() == ISD::AND) {
3060 if (!N1.getNode()->hasOneUse())
3062 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3063 if (!N11C || N11C->getZExtValue() != 0xFF)
3065 N1 = N1.getOperand(0);
3066 LookPassAnd1 = true;
3069 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3071 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3073 if (!N0.getNode()->hasOneUse() ||
3074 !N1.getNode()->hasOneUse())
3077 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3081 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3084 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3085 SDValue N00 = N0->getOperand(0);
3086 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3087 if (!N00.getNode()->hasOneUse())
3089 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3090 if (!N001C || N001C->getZExtValue() != 0xFF)
3092 N00 = N00.getOperand(0);
3093 LookPassAnd0 = true;
3096 SDValue N10 = N1->getOperand(0);
3097 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3098 if (!N10.getNode()->hasOneUse())
3100 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3101 if (!N101C || N101C->getZExtValue() != 0xFF00)
3103 N10 = N10.getOperand(0);
3104 LookPassAnd1 = true;
3110 // Make sure everything beyond the low halfword gets set to zero since the SRL
3111 // 16 will clear the top bits.
3112 unsigned OpSizeInBits = VT.getSizeInBits();
3113 if (DemandHighBits && OpSizeInBits > 16) {
3114 // If the left-shift isn't masked out then the only way this is a bswap is
3115 // if all bits beyond the low 8 are 0. In that case the entire pattern
3116 // reduces to a left shift anyway: leave it for other parts of the combiner.
3120 // However, if the right shift isn't masked out then it might be because
3121 // it's not needed. See if we can spot that too.
3122 if (!LookPassAnd1 &&
3123 !DAG.MaskedValueIsZero(
3124 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3128 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3129 if (OpSizeInBits > 16)
3130 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3131 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3135 /// isBSwapHWordElement - Return true if the specified node is an element
3136 /// that makes up a 32-bit packed halfword byteswap. i.e.
3137 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3138 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3139 if (!N.getNode()->hasOneUse())
3142 unsigned Opc = N.getOpcode();
3143 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3151 switch (N1C->getZExtValue()) {
3154 case 0xFF: Num = 0; break;
3155 case 0xFF00: Num = 1; break;
3156 case 0xFF0000: Num = 2; break;
3157 case 0xFF000000: Num = 3; break;
3160 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3161 SDValue N0 = N.getOperand(0);
3162 if (Opc == ISD::AND) {
3163 if (Num == 0 || Num == 2) {
3165 // (x >> 8) & 0xff0000
3166 if (N0.getOpcode() != ISD::SRL)
3168 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3169 if (!C || C->getZExtValue() != 8)
3172 // (x << 8) & 0xff00
3173 // (x << 8) & 0xff000000
3174 if (N0.getOpcode() != ISD::SHL)
3176 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3177 if (!C || C->getZExtValue() != 8)
3180 } else if (Opc == ISD::SHL) {
3182 // (x & 0xff0000) << 8
3183 if (Num != 0 && Num != 2)
3185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186 if (!C || C->getZExtValue() != 8)
3188 } else { // Opc == ISD::SRL
3189 // (x & 0xff00) >> 8
3190 // (x & 0xff000000) >> 8
3191 if (Num != 1 && Num != 3)
3193 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3194 if (!C || C->getZExtValue() != 8)
3201 Parts[Num] = N0.getOperand(0).getNode();
3205 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3206 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3207 /// => (rotl (bswap x), 16)
3208 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3209 if (!LegalOperations)
3212 EVT VT = N->getValueType(0);
3215 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3218 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3220 // (or (or (and), (and)), (or (and), (and)))
3221 // (or (or (or (and), (and)), (and)), (and))
3222 if (N0.getOpcode() != ISD::OR)
3224 SDValue N00 = N0.getOperand(0);
3225 SDValue N01 = N0.getOperand(1);
3227 if (N1.getOpcode() == ISD::OR &&
3228 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3229 // (or (or (and), (and)), (or (and), (and)))
3230 SDValue N000 = N00.getOperand(0);
3231 if (!isBSwapHWordElement(N000, Parts))
3234 SDValue N001 = N00.getOperand(1);
3235 if (!isBSwapHWordElement(N001, Parts))
3237 SDValue N010 = N01.getOperand(0);
3238 if (!isBSwapHWordElement(N010, Parts))
3240 SDValue N011 = N01.getOperand(1);
3241 if (!isBSwapHWordElement(N011, Parts))
3244 // (or (or (or (and), (and)), (and)), (and))
3245 if (!isBSwapHWordElement(N1, Parts))
3247 if (!isBSwapHWordElement(N01, Parts))
3249 if (N00.getOpcode() != ISD::OR)
3251 SDValue N000 = N00.getOperand(0);
3252 if (!isBSwapHWordElement(N000, Parts))
3254 SDValue N001 = N00.getOperand(1);
3255 if (!isBSwapHWordElement(N001, Parts))
3259 // Make sure the parts are all coming from the same node.
3260 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3263 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3264 SDValue(Parts[0],0));
3266 // Result of the bswap should be rotated by 16. If it's not legal, then
3267 // do (x << 16) | (x >> 16).
3268 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3269 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3270 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3271 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3272 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3273 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3274 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3275 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3278 SDValue DAGCombiner::visitOR(SDNode *N) {
3279 SDValue N0 = N->getOperand(0);
3280 SDValue N1 = N->getOperand(1);
3281 SDValue LL, LR, RL, RR, CC0, CC1;
3282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3284 EVT VT = N1.getValueType();
3287 if (VT.isVector()) {
3288 SDValue FoldedVOp = SimplifyVBinOp(N);
3289 if (FoldedVOp.getNode()) return FoldedVOp;
3291 // fold (or x, 0) -> x, vector edition
3292 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3294 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3297 // fold (or x, -1) -> -1, vector edition
3298 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3300 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3303 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3304 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3305 // Do this only if the resulting shuffle is legal.
3306 if (isa<ShuffleVectorSDNode>(N0) &&
3307 isa<ShuffleVectorSDNode>(N1) &&
3308 // Avoid folding a node with illegal type.
3309 TLI.isTypeLegal(VT) &&
3310 N0->getOperand(1) == N1->getOperand(1) &&
3311 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3312 bool CanFold = true;
3313 unsigned NumElts = VT.getVectorNumElements();
3314 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3315 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3316 // We construct two shuffle masks:
3317 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3318 // and N1 as the second operand.
3319 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3320 // and N0 as the second operand.
3321 // We do this because OR is commutable and therefore there might be
3322 // two ways to fold this node into a shuffle.
3323 SmallVector<int,4> Mask1;
3324 SmallVector<int,4> Mask2;
3326 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3327 int M0 = SV0->getMaskElt(i);
3328 int M1 = SV1->getMaskElt(i);
3330 // Both shuffle indexes are undef. Propagate Undef.
3331 if (M0 < 0 && M1 < 0) {
3332 Mask1.push_back(M0);
3333 Mask2.push_back(M0);
3337 if (M0 < 0 || M1 < 0 ||
3338 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3339 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3344 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3345 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3349 // Fold this sequence only if the resulting shuffle is 'legal'.
3350 if (TLI.isShuffleMaskLegal(Mask1, VT))
3351 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3352 N1->getOperand(0), &Mask1[0]);
3353 if (TLI.isShuffleMaskLegal(Mask2, VT))
3354 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3355 N0->getOperand(0), &Mask2[0]);
3360 // fold (or x, undef) -> -1
3361 if (!LegalOperations &&
3362 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3363 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3364 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3366 // fold (or c1, c2) -> c1|c2
3368 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3369 // canonicalize constant to RHS
3371 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3372 // fold (or x, 0) -> x
3373 if (N1C && N1C->isNullValue())
3375 // fold (or x, -1) -> -1
3376 if (N1C && N1C->isAllOnesValue())
3378 // fold (or x, c) -> c iff (x & ~c) == 0
3379 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3382 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3383 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3384 if (BSwap.getNode())
3386 BSwap = MatchBSwapHWordLow(N, N0, N1);
3387 if (BSwap.getNode())
3391 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3394 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3395 // iff (c1 & c2) == 0.
3396 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3397 isa<ConstantSDNode>(N0.getOperand(1))) {
3398 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3399 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3400 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3403 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3404 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3405 N0.getOperand(0), N1), COR);
3408 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3409 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3410 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3411 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3413 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3414 LL.getValueType().isInteger()) {
3415 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3416 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3417 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3418 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3419 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3420 LR.getValueType(), LL, RL);
3421 AddToWorklist(ORNode.getNode());
3422 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3424 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3425 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3426 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3427 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3428 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3429 LR.getValueType(), LL, RL);
3430 AddToWorklist(ANDNode.getNode());
3431 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3434 // canonicalize equivalent to ll == rl
3435 if (LL == RR && LR == RL) {
3436 Op1 = ISD::getSetCCSwappedOperands(Op1);
3439 if (LL == RL && LR == RR) {
3440 bool isInteger = LL.getValueType().isInteger();
3441 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3442 if (Result != ISD::SETCC_INVALID &&
3443 (!LegalOperations ||
3444 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3445 TLI.isOperationLegal(ISD::SETCC,
3446 getSetCCResultType(N0.getValueType())))))
3447 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3452 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3453 if (N0.getOpcode() == N1.getOpcode()) {
3454 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3455 if (Tmp.getNode()) return Tmp;
3458 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3459 if (N0.getOpcode() == ISD::AND &&
3460 N1.getOpcode() == ISD::AND &&
3461 N0.getOperand(1).getOpcode() == ISD::Constant &&
3462 N1.getOperand(1).getOpcode() == ISD::Constant &&
3463 // Don't increase # computations.
3464 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3465 // We can only do this xform if we know that bits from X that are set in C2
3466 // but not in C1 are already zero. Likewise for Y.
3467 const APInt &LHSMask =
3468 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3469 const APInt &RHSMask =
3470 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3472 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3473 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3474 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3475 N0.getOperand(0), N1.getOperand(0));
3476 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3477 DAG.getConstant(LHSMask | RHSMask, VT));
3481 // See if this is some rotate idiom.
3482 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3483 return SDValue(Rot, 0);
3485 // Simplify the operands using demanded-bits information.
3486 if (!VT.isVector() &&
3487 SimplifyDemandedBits(SDValue(N, 0)))
3488 return SDValue(N, 0);
3493 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3494 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3495 if (Op.getOpcode() == ISD::AND) {
3496 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3497 Mask = Op.getOperand(1);
3498 Op = Op.getOperand(0);
3504 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3512 // Return true if we can prove that, whenever Neg and Pos are both in the
3513 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3514 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3516 // (or (shift1 X, Neg), (shift2 X, Pos))
3518 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3519 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3520 // to consider shift amounts with defined behavior.
3521 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3522 // If OpSize is a power of 2 then:
3524 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3525 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3527 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3528 // for the stronger condition:
3530 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3532 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3533 // we can just replace Neg with Neg' for the rest of the function.
3535 // In other cases we check for the even stronger condition:
3537 // Neg == OpSize - Pos [B]
3539 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3540 // behavior if Pos == 0 (and consequently Neg == OpSize).
3542 // We could actually use [A] whenever OpSize is a power of 2, but the
3543 // only extra cases that it would match are those uninteresting ones
3544 // where Neg and Pos are never in range at the same time. E.g. for
3545 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3546 // as well as (sub 32, Pos), but:
3548 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3550 // always invokes undefined behavior for 32-bit X.
3552 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3553 unsigned MaskLoBits = 0;
3554 if (Neg.getOpcode() == ISD::AND &&
3555 isPowerOf2_64(OpSize) &&
3556 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3557 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3558 Neg = Neg.getOperand(0);
3559 MaskLoBits = Log2_64(OpSize);
3562 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3563 if (Neg.getOpcode() != ISD::SUB)
3565 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3568 SDValue NegOp1 = Neg.getOperand(1);
3570 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3571 // Pos'. The truncation is redundant for the purpose of the equality.
3573 Pos.getOpcode() == ISD::AND &&
3574 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3575 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3576 Pos = Pos.getOperand(0);
3578 // The condition we need is now:
3580 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3582 // If NegOp1 == Pos then we need:
3584 // OpSize & Mask == NegC & Mask
3586 // (because "x & Mask" is a truncation and distributes through subtraction).
3589 Width = NegC->getAPIntValue();
3590 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3591 // Then the condition we want to prove becomes:
3593 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3595 // which, again because "x & Mask" is a truncation, becomes:
3597 // NegC & Mask == (OpSize - PosC) & Mask
3598 // OpSize & Mask == (NegC + PosC) & Mask
3599 else if (Pos.getOpcode() == ISD::ADD &&
3600 Pos.getOperand(0) == NegOp1 &&
3601 Pos.getOperand(1).getOpcode() == ISD::Constant)
3602 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3603 NegC->getAPIntValue());
3607 // Now we just need to check that OpSize & Mask == Width & Mask.
3609 // Opsize & Mask is 0 since Mask is Opsize - 1.
3610 return Width.getLoBits(MaskLoBits) == 0;
3611 return Width == OpSize;
3614 // A subroutine of MatchRotate used once we have found an OR of two opposite
3615 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3616 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3617 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3618 // Neg with outer conversions stripped away.
3619 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3620 SDValue Neg, SDValue InnerPos,
3621 SDValue InnerNeg, unsigned PosOpcode,
3622 unsigned NegOpcode, SDLoc DL) {
3623 // fold (or (shl x, (*ext y)),
3624 // (srl x, (*ext (sub 32, y)))) ->
3625 // (rotl x, y) or (rotr x, (sub 32, y))
3627 // fold (or (shl x, (*ext (sub 32, y))),
3628 // (srl x, (*ext y))) ->
3629 // (rotr x, y) or (rotl x, (sub 32, y))
3630 EVT VT = Shifted.getValueType();
3631 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3632 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3633 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3634 HasPos ? Pos : Neg).getNode();
3640 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3641 // idioms for rotate, and if the target supports rotation instructions, generate
3643 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3644 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3645 EVT VT = LHS.getValueType();
3646 if (!TLI.isTypeLegal(VT)) return nullptr;
3648 // The target must have at least one rotate flavor.
3649 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3650 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3651 if (!HasROTL && !HasROTR) return nullptr;
3653 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3654 SDValue LHSShift; // The shift.
3655 SDValue LHSMask; // AND value if any.
3656 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3657 return nullptr; // Not part of a rotate.
3659 SDValue RHSShift; // The shift.
3660 SDValue RHSMask; // AND value if any.
3661 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3662 return nullptr; // Not part of a rotate.
3664 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3665 return nullptr; // Not shifting the same value.
3667 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3668 return nullptr; // Shifts must disagree.
3670 // Canonicalize shl to left side in a shl/srl pair.
3671 if (RHSShift.getOpcode() == ISD::SHL) {
3672 std::swap(LHS, RHS);
3673 std::swap(LHSShift, RHSShift);
3674 std::swap(LHSMask , RHSMask );
3677 unsigned OpSizeInBits = VT.getSizeInBits();
3678 SDValue LHSShiftArg = LHSShift.getOperand(0);
3679 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3680 SDValue RHSShiftArg = RHSShift.getOperand(0);
3681 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3683 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3684 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3685 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3686 RHSShiftAmt.getOpcode() == ISD::Constant) {
3687 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3688 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3689 if ((LShVal + RShVal) != OpSizeInBits)
3692 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3693 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3695 // If there is an AND of either shifted operand, apply it to the result.
3696 if (LHSMask.getNode() || RHSMask.getNode()) {
3697 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3699 if (LHSMask.getNode()) {
3700 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3701 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3703 if (RHSMask.getNode()) {
3704 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3705 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3708 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3711 return Rot.getNode();
3714 // If there is a mask here, and we have a variable shift, we can't be sure
3715 // that we're masking out the right stuff.
3716 if (LHSMask.getNode() || RHSMask.getNode())
3719 // If the shift amount is sign/zext/any-extended just peel it off.
3720 SDValue LExtOp0 = LHSShiftAmt;
3721 SDValue RExtOp0 = RHSShiftAmt;
3722 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3723 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3724 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3725 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3726 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3730 LExtOp0 = LHSShiftAmt.getOperand(0);
3731 RExtOp0 = RHSShiftAmt.getOperand(0);
3734 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3735 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3739 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3740 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3747 SDValue DAGCombiner::visitXOR(SDNode *N) {
3748 SDValue N0 = N->getOperand(0);
3749 SDValue N1 = N->getOperand(1);
3750 SDValue LHS, RHS, CC;
3751 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3753 EVT VT = N0.getValueType();
3756 if (VT.isVector()) {
3757 SDValue FoldedVOp = SimplifyVBinOp(N);
3758 if (FoldedVOp.getNode()) return FoldedVOp;
3760 // fold (xor x, 0) -> x, vector edition
3761 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3763 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3767 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3768 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3769 return DAG.getConstant(0, VT);
3770 // fold (xor x, undef) -> undef
3771 if (N0.getOpcode() == ISD::UNDEF)
3773 if (N1.getOpcode() == ISD::UNDEF)
3775 // fold (xor c1, c2) -> c1^c2
3777 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3778 // canonicalize constant to RHS
3780 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3781 // fold (xor x, 0) -> x
3782 if (N1C && N1C->isNullValue())
3785 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3789 // fold !(x cc y) -> (x !cc y)
3790 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3791 bool isInt = LHS.getValueType().isInteger();
3792 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3795 if (!LegalOperations ||
3796 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3797 switch (N0.getOpcode()) {
3799 llvm_unreachable("Unhandled SetCC Equivalent!");
3801 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3802 case ISD::SELECT_CC:
3803 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3804 N0.getOperand(3), NotCC);
3809 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3810 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3811 N0.getNode()->hasOneUse() &&
3812 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3813 SDValue V = N0.getOperand(0);
3814 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3815 DAG.getConstant(1, V.getValueType()));
3816 AddToWorklist(V.getNode());
3817 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3820 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3821 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3822 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3823 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3824 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3825 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3826 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3827 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3828 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3829 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3832 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3833 if (N1C && N1C->isAllOnesValue() &&
3834 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3835 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3836 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3837 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3838 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3839 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3840 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3841 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3844 // fold (xor (and x, y), y) -> (and (not x), y)
3845 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3846 N0->getOperand(1) == N1) {
3847 SDValue X = N0->getOperand(0);
3848 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3849 AddToWorklist(NotX.getNode());
3850 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3852 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3853 if (N1C && N0.getOpcode() == ISD::XOR) {
3854 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3855 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3857 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3858 DAG.getConstant(N1C->getAPIntValue() ^
3859 N00C->getAPIntValue(), VT));
3861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3862 DAG.getConstant(N1C->getAPIntValue() ^
3863 N01C->getAPIntValue(), VT));
3865 // fold (xor x, x) -> 0
3867 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3869 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3870 if (N0.getOpcode() == N1.getOpcode()) {
3871 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3872 if (Tmp.getNode()) return Tmp;
3875 // Simplify the expression using non-local knowledge.
3876 if (!VT.isVector() &&
3877 SimplifyDemandedBits(SDValue(N, 0)))
3878 return SDValue(N, 0);
3883 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3884 /// the shift amount is a constant.
3885 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3886 // We can't and shouldn't fold opaque constants.
3887 if (Amt->isOpaque())
3890 SDNode *LHS = N->getOperand(0).getNode();
3891 if (!LHS->hasOneUse()) return SDValue();
3893 // We want to pull some binops through shifts, so that we have (and (shift))
3894 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3895 // thing happens with address calculations, so it's important to canonicalize
3897 bool HighBitSet = false; // Can we transform this if the high bit is set?
3899 switch (LHS->getOpcode()) {
3900 default: return SDValue();
3903 HighBitSet = false; // We can only transform sra if the high bit is clear.
3906 HighBitSet = true; // We can only transform sra if the high bit is set.
3909 if (N->getOpcode() != ISD::SHL)
3910 return SDValue(); // only shl(add) not sr[al](add).
3911 HighBitSet = false; // We can only transform sra if the high bit is clear.
3915 // We require the RHS of the binop to be a constant and not opaque as well.
3916 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3917 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3919 // FIXME: disable this unless the input to the binop is a shift by a constant.
3920 // If it is not a shift, it pessimizes some common cases like:
3922 // void foo(int *X, int i) { X[i & 1235] = 1; }
3923 // int bar(int *X, int i) { return X[i & 255]; }
3924 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3925 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3926 BinOpLHSVal->getOpcode() != ISD::SRA &&
3927 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3928 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3931 EVT VT = N->getValueType(0);
3933 // If this is a signed shift right, and the high bit is modified by the
3934 // logical operation, do not perform the transformation. The highBitSet
3935 // boolean indicates the value of the high bit of the constant which would
3936 // cause it to be modified for this operation.
3937 if (N->getOpcode() == ISD::SRA) {
3938 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3939 if (BinOpRHSSignSet != HighBitSet)
3943 if (!TLI.isDesirableToCommuteWithShift(LHS))
3946 // Fold the constants, shifting the binop RHS by the shift amount.
3947 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3949 LHS->getOperand(1), N->getOperand(1));
3950 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3952 // Create the new shift.
3953 SDValue NewShift = DAG.getNode(N->getOpcode(),
3954 SDLoc(LHS->getOperand(0)),
3955 VT, LHS->getOperand(0), N->getOperand(1));
3957 // Create the new binop.
3958 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3961 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3962 assert(N->getOpcode() == ISD::TRUNCATE);
3963 assert(N->getOperand(0).getOpcode() == ISD::AND);
3965 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3966 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3967 SDValue N01 = N->getOperand(0).getOperand(1);
3969 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3970 EVT TruncVT = N->getValueType(0);
3971 SDValue N00 = N->getOperand(0).getOperand(0);
3972 APInt TruncC = N01C->getAPIntValue();
3973 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3975 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3976 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3977 DAG.getConstant(TruncC, TruncVT));
3984 SDValue DAGCombiner::visitRotate(SDNode *N) {
3985 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3986 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3987 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3988 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3989 if (NewOp1.getNode())
3990 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3991 N->getOperand(0), NewOp1);
3996 SDValue DAGCombiner::visitSHL(SDNode *N) {
3997 SDValue N0 = N->getOperand(0);
3998 SDValue N1 = N->getOperand(1);
3999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4000 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4001 EVT VT = N0.getValueType();
4002 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4005 if (VT.isVector()) {
4006 SDValue FoldedVOp = SimplifyVBinOp(N);
4007 if (FoldedVOp.getNode()) return FoldedVOp;
4009 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4010 // If setcc produces all-one true value then:
4011 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4012 if (N1CV && N1CV->isConstant()) {
4013 if (N0.getOpcode() == ISD::AND) {
4014 SDValue N00 = N0->getOperand(0);
4015 SDValue N01 = N0->getOperand(1);
4016 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4018 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4019 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4020 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4021 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4023 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4026 N1C = isConstOrConstSplat(N1);
4031 // fold (shl c1, c2) -> c1<<c2
4033 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4034 // fold (shl 0, x) -> 0
4035 if (N0C && N0C->isNullValue())
4037 // fold (shl x, c >= size(x)) -> undef
4038 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4039 return DAG.getUNDEF(VT);
4040 // fold (shl x, 0) -> x
4041 if (N1C && N1C->isNullValue())
4043 // fold (shl undef, x) -> 0
4044 if (N0.getOpcode() == ISD::UNDEF)
4045 return DAG.getConstant(0, VT);
4046 // if (shl x, c) is known to be zero, return 0
4047 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4048 APInt::getAllOnesValue(OpSizeInBits)))
4049 return DAG.getConstant(0, VT);
4050 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4051 if (N1.getOpcode() == ISD::TRUNCATE &&
4052 N1.getOperand(0).getOpcode() == ISD::AND) {
4053 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4054 if (NewOp1.getNode())
4055 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4058 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4059 return SDValue(N, 0);
4061 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4062 if (N1C && N0.getOpcode() == ISD::SHL) {
4063 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064 uint64_t c1 = N0C1->getZExtValue();
4065 uint64_t c2 = N1C->getZExtValue();
4066 if (c1 + c2 >= OpSizeInBits)
4067 return DAG.getConstant(0, VT);
4068 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4069 DAG.getConstant(c1 + c2, N1.getValueType()));
4073 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4074 // For this to be valid, the second form must not preserve any of the bits
4075 // that are shifted out by the inner shift in the first form. This means
4076 // the outer shift size must be >= the number of bits added by the ext.
4077 // As a corollary, we don't care what kind of ext it is.
4078 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4079 N0.getOpcode() == ISD::ANY_EXTEND ||
4080 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4081 N0.getOperand(0).getOpcode() == ISD::SHL) {
4082 SDValue N0Op0 = N0.getOperand(0);
4083 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4084 uint64_t c1 = N0Op0C1->getZExtValue();
4085 uint64_t c2 = N1C->getZExtValue();
4086 EVT InnerShiftVT = N0Op0.getValueType();
4087 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4088 if (c2 >= OpSizeInBits - InnerShiftSize) {
4089 if (c1 + c2 >= OpSizeInBits)
4090 return DAG.getConstant(0, VT);
4091 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4092 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4093 N0Op0->getOperand(0)),
4094 DAG.getConstant(c1 + c2, N1.getValueType()));
4099 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4100 // Only fold this if the inner zext has no other uses to avoid increasing
4101 // the total number of instructions.
4102 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4103 N0.getOperand(0).getOpcode() == ISD::SRL) {
4104 SDValue N0Op0 = N0.getOperand(0);
4105 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4106 uint64_t c1 = N0Op0C1->getZExtValue();
4107 if (c1 < VT.getScalarSizeInBits()) {
4108 uint64_t c2 = N1C->getZExtValue();
4110 SDValue NewOp0 = N0.getOperand(0);
4111 EVT CountVT = NewOp0.getOperand(1).getValueType();
4112 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4113 NewOp0, DAG.getConstant(c2, CountVT));
4114 AddToWorklist(NewSHL.getNode());
4115 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4121 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4122 // (and (srl x, (sub c1, c2), MASK)
4123 // Only fold this if the inner shift has no other uses -- if it does, folding
4124 // this will increase the total number of instructions.
4125 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4126 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4127 uint64_t c1 = N0C1->getZExtValue();
4128 if (c1 < OpSizeInBits) {
4129 uint64_t c2 = N1C->getZExtValue();
4130 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4133 Mask = Mask.shl(c2 - c1);
4134 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4135 DAG.getConstant(c2 - c1, N1.getValueType()));
4137 Mask = Mask.lshr(c1 - c2);
4138 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4139 DAG.getConstant(c1 - c2, N1.getValueType()));
4141 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4142 DAG.getConstant(Mask, VT));
4146 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4147 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4148 unsigned BitSize = VT.getScalarSizeInBits();
4149 SDValue HiBitsMask =
4150 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4151 BitSize - N1C->getZExtValue()), VT);
4152 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4157 SDValue NewSHL = visitShiftByConstant(N, N1C);
4158 if (NewSHL.getNode())
4165 SDValue DAGCombiner::visitSRA(SDNode *N) {
4166 SDValue N0 = N->getOperand(0);
4167 SDValue N1 = N->getOperand(1);
4168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4170 EVT VT = N0.getValueType();
4171 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4174 if (VT.isVector()) {
4175 SDValue FoldedVOp = SimplifyVBinOp(N);
4176 if (FoldedVOp.getNode()) return FoldedVOp;
4178 N1C = isConstOrConstSplat(N1);
4181 // fold (sra c1, c2) -> (sra c1, c2)
4183 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4184 // fold (sra 0, x) -> 0
4185 if (N0C && N0C->isNullValue())
4187 // fold (sra -1, x) -> -1
4188 if (N0C && N0C->isAllOnesValue())
4190 // fold (sra x, (setge c, size(x))) -> undef
4191 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4192 return DAG.getUNDEF(VT);
4193 // fold (sra x, 0) -> x
4194 if (N1C && N1C->isNullValue())
4196 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4198 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4199 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4200 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4202 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4203 ExtVT, VT.getVectorNumElements());
4204 if ((!LegalOperations ||
4205 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4206 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4207 N0.getOperand(0), DAG.getValueType(ExtVT));
4210 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4211 if (N1C && N0.getOpcode() == ISD::SRA) {
4212 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4213 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4214 if (Sum >= OpSizeInBits)
4215 Sum = OpSizeInBits - 1;
4216 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4217 DAG.getConstant(Sum, N1.getValueType()));
4221 // fold (sra (shl X, m), (sub result_size, n))
4222 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4223 // result_size - n != m.
4224 // If truncate is free for the target sext(shl) is likely to result in better
4226 if (N0.getOpcode() == ISD::SHL && N1C) {
4227 // Get the two constanst of the shifts, CN0 = m, CN = n.
4228 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4230 LLVMContext &Ctx = *DAG.getContext();
4231 // Determine what the truncate's result bitsize and type would be.
4232 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4235 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4237 // Determine the residual right-shift amount.
4238 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4240 // If the shift is not a no-op (in which case this should be just a sign
4241 // extend already), the truncated to type is legal, sign_extend is legal
4242 // on that type, and the truncate to that type is both legal and free,
4243 // perform the transform.
4244 if ((ShiftAmt > 0) &&
4245 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4246 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4247 TLI.isTruncateFree(VT, TruncVT)) {
4249 SDValue Amt = DAG.getConstant(ShiftAmt,
4250 getShiftAmountTy(N0.getOperand(0).getValueType()));
4251 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4252 N0.getOperand(0), Amt);
4253 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4255 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4256 N->getValueType(0), Trunc);
4261 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4262 if (N1.getOpcode() == ISD::TRUNCATE &&
4263 N1.getOperand(0).getOpcode() == ISD::AND) {
4264 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4265 if (NewOp1.getNode())
4266 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4269 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4270 // if c1 is equal to the number of bits the trunc removes
4271 if (N0.getOpcode() == ISD::TRUNCATE &&
4272 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4273 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4274 N0.getOperand(0).hasOneUse() &&
4275 N0.getOperand(0).getOperand(1).hasOneUse() &&
4277 SDValue N0Op0 = N0.getOperand(0);
4278 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4279 unsigned LargeShiftVal = LargeShift->getZExtValue();
4280 EVT LargeVT = N0Op0.getValueType();
4282 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4284 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4285 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4286 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4287 N0Op0.getOperand(0), Amt);
4288 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4293 // Simplify, based on bits shifted out of the LHS.
4294 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4295 return SDValue(N, 0);
4298 // If the sign bit is known to be zero, switch this to a SRL.
4299 if (DAG.SignBitIsZero(N0))
4300 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4303 SDValue NewSRA = visitShiftByConstant(N, N1C);
4304 if (NewSRA.getNode())
4311 SDValue DAGCombiner::visitSRL(SDNode *N) {
4312 SDValue N0 = N->getOperand(0);
4313 SDValue N1 = N->getOperand(1);
4314 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4316 EVT VT = N0.getValueType();
4317 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4320 if (VT.isVector()) {
4321 SDValue FoldedVOp = SimplifyVBinOp(N);
4322 if (FoldedVOp.getNode()) return FoldedVOp;
4324 N1C = isConstOrConstSplat(N1);
4327 // fold (srl c1, c2) -> c1 >>u c2
4329 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4330 // fold (srl 0, x) -> 0
4331 if (N0C && N0C->isNullValue())
4333 // fold (srl x, c >= size(x)) -> undef
4334 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4335 return DAG.getUNDEF(VT);
4336 // fold (srl x, 0) -> x
4337 if (N1C && N1C->isNullValue())
4339 // if (srl x, c) is known to be zero, return 0
4340 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4341 APInt::getAllOnesValue(OpSizeInBits)))
4342 return DAG.getConstant(0, VT);
4344 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4345 if (N1C && N0.getOpcode() == ISD::SRL) {
4346 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4347 uint64_t c1 = N01C->getZExtValue();
4348 uint64_t c2 = N1C->getZExtValue();
4349 if (c1 + c2 >= OpSizeInBits)
4350 return DAG.getConstant(0, VT);
4351 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4352 DAG.getConstant(c1 + c2, N1.getValueType()));
4356 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4357 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4358 N0.getOperand(0).getOpcode() == ISD::SRL &&
4359 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4361 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4362 uint64_t c2 = N1C->getZExtValue();
4363 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4364 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4365 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4366 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4367 if (c1 + OpSizeInBits == InnerShiftSize) {
4368 if (c1 + c2 >= InnerShiftSize)
4369 return DAG.getConstant(0, VT);
4370 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4371 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4372 N0.getOperand(0)->getOperand(0),
4373 DAG.getConstant(c1 + c2, ShiftCountVT)));
4377 // fold (srl (shl x, c), c) -> (and x, cst2)
4378 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4379 unsigned BitSize = N0.getScalarValueSizeInBits();
4380 if (BitSize <= 64) {
4381 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4382 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4383 DAG.getConstant(~0ULL >> ShAmt, VT));
4387 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4388 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4389 // Shifting in all undef bits?
4390 EVT SmallVT = N0.getOperand(0).getValueType();
4391 unsigned BitSize = SmallVT.getScalarSizeInBits();
4392 if (N1C->getZExtValue() >= BitSize)
4393 return DAG.getUNDEF(VT);
4395 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4396 uint64_t ShiftAmt = N1C->getZExtValue();
4397 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4399 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4400 AddToWorklist(SmallShift.getNode());
4401 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4402 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4403 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4404 DAG.getConstant(Mask, VT));
4408 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4409 // bit, which is unmodified by sra.
4410 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4411 if (N0.getOpcode() == ISD::SRA)
4412 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4415 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4416 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4417 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4418 APInt KnownZero, KnownOne;
4419 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4421 // If any of the input bits are KnownOne, then the input couldn't be all
4422 // zeros, thus the result of the srl will always be zero.
4423 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4425 // If all of the bits input the to ctlz node are known to be zero, then
4426 // the result of the ctlz is "32" and the result of the shift is one.
4427 APInt UnknownBits = ~KnownZero;
4428 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4430 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4431 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4432 // Okay, we know that only that the single bit specified by UnknownBits
4433 // could be set on input to the CTLZ node. If this bit is set, the SRL
4434 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4435 // to an SRL/XOR pair, which is likely to simplify more.
4436 unsigned ShAmt = UnknownBits.countTrailingZeros();
4437 SDValue Op = N0.getOperand(0);
4440 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4441 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4442 AddToWorklist(Op.getNode());
4445 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4446 Op, DAG.getConstant(1, VT));
4450 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4451 if (N1.getOpcode() == ISD::TRUNCATE &&
4452 N1.getOperand(0).getOpcode() == ISD::AND) {
4453 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4454 if (NewOp1.getNode())
4455 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4458 // fold operands of srl based on knowledge that the low bits are not
4460 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4461 return SDValue(N, 0);
4464 SDValue NewSRL = visitShiftByConstant(N, N1C);
4465 if (NewSRL.getNode())
4469 // Attempt to convert a srl of a load into a narrower zero-extending load.
4470 SDValue NarrowLoad = ReduceLoadWidth(N);
4471 if (NarrowLoad.getNode())
4474 // Here is a common situation. We want to optimize:
4477 // %b = and i32 %a, 2
4478 // %c = srl i32 %b, 1
4479 // brcond i32 %c ...
4485 // %c = setcc eq %b, 0
4488 // However when after the source operand of SRL is optimized into AND, the SRL
4489 // itself may not be optimized further. Look for it and add the BRCOND into
4491 if (N->hasOneUse()) {
4492 SDNode *Use = *N->use_begin();
4493 if (Use->getOpcode() == ISD::BRCOND)
4495 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4496 // Also look pass the truncate.
4497 Use = *Use->use_begin();
4498 if (Use->getOpcode() == ISD::BRCOND)
4506 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4510 // fold (ctlz c1) -> c2
4511 if (isa<ConstantSDNode>(N0))
4512 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4516 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
4518 EVT VT = N->getValueType(0);
4520 // fold (ctlz_zero_undef c1) -> c2
4521 if (isa<ConstantSDNode>(N0))
4522 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4526 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 EVT VT = N->getValueType(0);
4530 // fold (cttz c1) -> c2
4531 if (isa<ConstantSDNode>(N0))
4532 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4536 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4540 // fold (cttz_zero_undef c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
4542 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4546 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
4548 EVT VT = N->getValueType(0);
4550 // fold (ctpop c1) -> c2
4551 if (isa<ConstantSDNode>(N0))
4552 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4556 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4557 SDValue N0 = N->getOperand(0);
4558 SDValue N1 = N->getOperand(1);
4559 SDValue N2 = N->getOperand(2);
4560 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4562 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4563 EVT VT = N->getValueType(0);
4564 EVT VT0 = N0.getValueType();
4566 // fold (select C, X, X) -> X
4569 // fold (select true, X, Y) -> X
4570 if (N0C && !N0C->isNullValue())
4572 // fold (select false, X, Y) -> Y
4573 if (N0C && N0C->isNullValue())
4575 // fold (select C, 1, X) -> (or C, X)
4576 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4577 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4578 // fold (select C, 0, 1) -> (xor C, 1)
4579 // We can't do this reliably if integer based booleans have different contents
4580 // to floating point based booleans. This is because we can't tell whether we
4581 // have an integer-based boolean or a floating-point-based boolean unless we
4582 // can find the SETCC that produced it and inspect its operands. This is
4583 // fairly easy if C is the SETCC node, but it can potentially be
4584 // undiscoverable (or not reasonably discoverable). For example, it could be
4585 // in another basic block or it could require searching a complicated
4587 if (VT.isInteger() &&
4588 (VT0 == MVT::i1 || (VT0.isInteger() &&
4589 TLI.getBooleanContents(false, false) ==
4590 TLI.getBooleanContents(false, true) &&
4591 TLI.getBooleanContents(false, false) ==
4592 TargetLowering::ZeroOrOneBooleanContent)) &&
4593 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4596 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4597 N0, DAG.getConstant(1, VT0));
4598 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4599 N0, DAG.getConstant(1, VT0));
4600 AddToWorklist(XORNode.getNode());
4602 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4603 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4605 // fold (select C, 0, X) -> (and (not C), X)
4606 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4607 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4608 AddToWorklist(NOTNode.getNode());
4609 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4611 // fold (select C, X, 1) -> (or (not C), X)
4612 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4613 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4614 AddToWorklist(NOTNode.getNode());
4615 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4617 // fold (select C, X, 0) -> (and C, X)
4618 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4619 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4620 // fold (select X, X, Y) -> (or X, Y)
4621 // fold (select X, 1, Y) -> (or X, Y)
4622 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4623 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4624 // fold (select X, Y, X) -> (and X, Y)
4625 // fold (select X, Y, 0) -> (and X, Y)
4626 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4627 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4629 // If we can fold this based on the true/false value, do so.
4630 if (SimplifySelectOps(N, N1, N2))
4631 return SDValue(N, 0); // Don't revisit N.
4633 // fold selects based on a setcc into other things, such as min/max/abs
4634 if (N0.getOpcode() == ISD::SETCC) {
4635 if ((!LegalOperations &&
4636 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4637 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4638 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4639 N0.getOperand(0), N0.getOperand(1),
4640 N1, N2, N0.getOperand(2));
4641 return SimplifySelect(SDLoc(N), N0, N1, N2);
4648 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4651 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4653 // Split the inputs.
4654 SDValue Lo, Hi, LL, LH, RL, RH;
4655 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4656 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4658 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4659 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4661 return std::make_pair(Lo, Hi);
4664 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4665 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4666 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4668 SDValue Cond = N->getOperand(0);
4669 SDValue LHS = N->getOperand(1);
4670 SDValue RHS = N->getOperand(2);
4671 MVT VT = N->getSimpleValueType(0);
4672 int NumElems = VT.getVectorNumElements();
4673 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4674 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4675 Cond.getOpcode() == ISD::BUILD_VECTOR);
4677 // We're sure we have an even number of elements due to the
4678 // concat_vectors we have as arguments to vselect.
4679 // Skip BV elements until we find one that's not an UNDEF
4680 // After we find an UNDEF element, keep looping until we get to half the
4681 // length of the BV and see if all the non-undef nodes are the same.
4682 ConstantSDNode *BottomHalf = nullptr;
4683 for (int i = 0; i < NumElems / 2; ++i) {
4684 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4687 if (BottomHalf == nullptr)
4688 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4689 else if (Cond->getOperand(i).getNode() != BottomHalf)
4693 // Do the same for the second half of the BuildVector
4694 ConstantSDNode *TopHalf = nullptr;
4695 for (int i = NumElems / 2; i < NumElems; ++i) {
4696 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4699 if (TopHalf == nullptr)
4700 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4701 else if (Cond->getOperand(i).getNode() != TopHalf)
4705 assert(TopHalf && BottomHalf &&
4706 "One half of the selector was all UNDEFs and the other was all the "
4707 "same value. This should have been addressed before this function.");
4709 ISD::CONCAT_VECTORS, dl, VT,
4710 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4711 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4714 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4715 SDValue N0 = N->getOperand(0);
4716 SDValue N1 = N->getOperand(1);
4717 SDValue N2 = N->getOperand(2);
4720 // Canonicalize integer abs.
4721 // vselect (setg[te] X, 0), X, -X ->
4722 // vselect (setgt X, -1), X, -X ->
4723 // vselect (setl[te] X, 0), -X, X ->
4724 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4725 if (N0.getOpcode() == ISD::SETCC) {
4726 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4727 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4729 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4731 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4732 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4733 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4734 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4735 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4736 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4737 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4740 EVT VT = LHS.getValueType();
4741 SDValue Shift = DAG.getNode(
4742 ISD::SRA, DL, VT, LHS,
4743 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4744 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4745 AddToWorklist(Shift.getNode());
4746 AddToWorklist(Add.getNode());
4747 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4751 // If the VSELECT result requires splitting and the mask is provided by a
4752 // SETCC, then split both nodes and its operands before legalization. This
4753 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4754 // and enables future optimizations (e.g. min/max pattern matching on X86).
4755 if (N0.getOpcode() == ISD::SETCC) {
4756 EVT VT = N->getValueType(0);
4758 // Check if any splitting is required.
4759 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4760 TargetLowering::TypeSplitVector)
4763 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4764 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4765 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4766 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4768 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4769 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4771 // Add the new VSELECT nodes to the work list in case they need to be split
4773 AddToWorklist(Lo.getNode());
4774 AddToWorklist(Hi.getNode());
4776 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4779 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4780 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4782 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4783 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4786 // The ConvertSelectToConcatVector function is assuming both the above
4787 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4789 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4790 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4791 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4792 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4800 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 SDValue N1 = N->getOperand(1);
4803 SDValue N2 = N->getOperand(2);
4804 SDValue N3 = N->getOperand(3);
4805 SDValue N4 = N->getOperand(4);
4806 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4808 // fold select_cc lhs, rhs, x, x, cc -> x
4812 // Determine if the condition we're dealing with is constant
4813 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4814 N0, N1, CC, SDLoc(N), false);
4815 if (SCC.getNode()) {
4816 AddToWorklist(SCC.getNode());
4818 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4819 if (!SCCC->isNullValue())
4820 return N2; // cond always true -> true val
4822 return N3; // cond always false -> false val
4825 // Fold to a simpler select_cc
4826 if (SCC.getOpcode() == ISD::SETCC)
4827 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4828 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4832 // If we can fold this based on the true/false value, do so.
4833 if (SimplifySelectOps(N, N2, N3))
4834 return SDValue(N, 0); // Don't revisit N.
4836 // fold select_cc into other things, such as min/max/abs
4837 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4840 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4841 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4842 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4846 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4847 // dag node into a ConstantSDNode or a build_vector of constants.
4848 // This function is called by the DAGCombiner when visiting sext/zext/aext
4849 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4850 // Vector extends are not folded if operations are legal; this is to
4851 // avoid introducing illegal build_vector dag nodes.
4852 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4853 SelectionDAG &DAG, bool LegalTypes,
4854 bool LegalOperations) {
4855 unsigned Opcode = N->getOpcode();
4856 SDValue N0 = N->getOperand(0);
4857 EVT VT = N->getValueType(0);
4859 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4860 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4862 // fold (sext c1) -> c1
4863 // fold (zext c1) -> c1
4864 // fold (aext c1) -> c1
4865 if (isa<ConstantSDNode>(N0))
4866 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4868 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4869 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4870 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4871 EVT SVT = VT.getScalarType();
4872 if (!(VT.isVector() &&
4873 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4874 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4877 // We can fold this node into a build_vector.
4878 unsigned VTBits = SVT.getSizeInBits();
4879 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4880 unsigned ShAmt = VTBits - EVTBits;
4881 SmallVector<SDValue, 8> Elts;
4882 unsigned NumElts = N0->getNumOperands();
4885 for (unsigned i=0; i != NumElts; ++i) {
4886 SDValue Op = N0->getOperand(i);
4887 if (Op->getOpcode() == ISD::UNDEF) {
4888 Elts.push_back(DAG.getUNDEF(SVT));
4892 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4893 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4894 if (Opcode == ISD::SIGN_EXTEND)
4895 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4898 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4902 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4905 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4906 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4907 // transformation. Returns true if extension are possible and the above
4908 // mentioned transformation is profitable.
4909 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4911 SmallVectorImpl<SDNode *> &ExtendNodes,
4912 const TargetLowering &TLI) {
4913 bool HasCopyToRegUses = false;
4914 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4915 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4916 UE = N0.getNode()->use_end();
4921 if (UI.getUse().getResNo() != N0.getResNo())
4923 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4924 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4925 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4926 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4927 // Sign bits will be lost after a zext.
4930 for (unsigned i = 0; i != 2; ++i) {
4931 SDValue UseOp = User->getOperand(i);
4934 if (!isa<ConstantSDNode>(UseOp))
4939 ExtendNodes.push_back(User);
4942 // If truncates aren't free and there are users we can't
4943 // extend, it isn't worthwhile.
4946 // Remember if this value is live-out.
4947 if (User->getOpcode() == ISD::CopyToReg)
4948 HasCopyToRegUses = true;
4951 if (HasCopyToRegUses) {
4952 bool BothLiveOut = false;
4953 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4955 SDUse &Use = UI.getUse();
4956 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4962 // Both unextended and extended values are live out. There had better be
4963 // a good reason for the transformation.
4964 return ExtendNodes.size();
4969 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4970 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4971 ISD::NodeType ExtType) {
4972 // Extend SetCC uses if necessary.
4973 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4974 SDNode *SetCC = SetCCs[i];
4975 SmallVector<SDValue, 4> Ops;
4977 for (unsigned j = 0; j != 2; ++j) {
4978 SDValue SOp = SetCC->getOperand(j);
4980 Ops.push_back(ExtLoad);
4982 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4985 Ops.push_back(SetCC->getOperand(2));
4986 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4990 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4991 SDValue N0 = N->getOperand(0);
4992 EVT VT = N->getValueType(0);
4994 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4996 return SDValue(Res, 0);
4998 // fold (sext (sext x)) -> (sext x)
4999 // fold (sext (aext x)) -> (sext x)
5000 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5001 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5004 if (N0.getOpcode() == ISD::TRUNCATE) {
5005 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5006 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5007 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5008 if (NarrowLoad.getNode()) {
5009 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5010 if (NarrowLoad.getNode() != N0.getNode()) {
5011 CombineTo(N0.getNode(), NarrowLoad);
5012 // CombineTo deleted the truncate, if needed, but not what's under it.
5015 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5018 // See if the value being truncated is already sign extended. If so, just
5019 // eliminate the trunc/sext pair.
5020 SDValue Op = N0.getOperand(0);
5021 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5022 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5023 unsigned DestBits = VT.getScalarType().getSizeInBits();
5024 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5026 if (OpBits == DestBits) {
5027 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5028 // bits, it is already ready.
5029 if (NumSignBits > DestBits-MidBits)
5031 } else if (OpBits < DestBits) {
5032 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5033 // bits, just sext from i32.
5034 if (NumSignBits > OpBits-MidBits)
5035 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5037 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5038 // bits, just truncate to i32.
5039 if (NumSignBits > OpBits-MidBits)
5040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5043 // fold (sext (truncate x)) -> (sextinreg x).
5044 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5045 N0.getValueType())) {
5046 if (OpBits < DestBits)
5047 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5048 else if (OpBits > DestBits)
5049 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5050 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5051 DAG.getValueType(N0.getValueType()));
5055 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5056 // None of the supported targets knows how to perform load and sign extend
5057 // on vectors in one instruction. We only perform this transformation on
5059 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5060 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5061 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5062 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5063 bool DoXform = true;
5064 SmallVector<SDNode*, 4> SetCCs;
5065 if (!N0.hasOneUse())
5066 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5068 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5069 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5071 LN0->getBasePtr(), N0.getValueType(),
5072 LN0->getMemOperand());
5073 CombineTo(N, ExtLoad);
5074 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5075 N0.getValueType(), ExtLoad);
5076 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5077 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5083 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5084 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5085 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5086 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5087 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5088 EVT MemVT = LN0->getMemoryVT();
5089 if ((!LegalOperations && !LN0->isVolatile()) ||
5090 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5093 LN0->getBasePtr(), MemVT,
5094 LN0->getMemOperand());
5095 CombineTo(N, ExtLoad);
5096 CombineTo(N0.getNode(),
5097 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5098 N0.getValueType(), ExtLoad),
5099 ExtLoad.getValue(1));
5100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5104 // fold (sext (and/or/xor (load x), cst)) ->
5105 // (and/or/xor (sextload x), (sext cst))
5106 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5107 N0.getOpcode() == ISD::XOR) &&
5108 isa<LoadSDNode>(N0.getOperand(0)) &&
5109 N0.getOperand(1).getOpcode() == ISD::Constant &&
5110 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5111 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5112 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5113 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5114 bool DoXform = true;
5115 SmallVector<SDNode*, 4> SetCCs;
5116 if (!N0.hasOneUse())
5117 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5120 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5121 LN0->getChain(), LN0->getBasePtr(),
5123 LN0->getMemOperand());
5124 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5125 Mask = Mask.sext(VT.getSizeInBits());
5126 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5127 ExtLoad, DAG.getConstant(Mask, VT));
5128 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5129 SDLoc(N0.getOperand(0)),
5130 N0.getOperand(0).getValueType(), ExtLoad);
5132 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5133 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5140 if (N0.getOpcode() == ISD::SETCC) {
5141 EVT N0VT = N0.getOperand(0).getValueType();
5142 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5143 // Only do this before legalize for now.
5144 if (VT.isVector() && !LegalOperations &&
5145 TLI.getBooleanContents(N0VT) ==
5146 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5147 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5148 // of the same size as the compared operands. Only optimize sext(setcc())
5149 // if this is the case.
5150 EVT SVT = getSetCCResultType(N0VT);
5152 // We know that the # elements of the results is the same as the
5153 // # elements of the compare (and the # elements of the compare result
5154 // for that matter). Check to see that they are the same size. If so,
5155 // we know that the element size of the sext'd result matches the
5156 // element size of the compare operands.
5157 if (VT.getSizeInBits() == SVT.getSizeInBits())
5158 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5160 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5162 // If the desired elements are smaller or larger than the source
5163 // elements we can use a matching integer vector type and then
5164 // truncate/sign extend
5165 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5166 if (SVT == MatchingVectorType) {
5167 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5168 N0.getOperand(0), N0.getOperand(1),
5169 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5170 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5174 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5175 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5177 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5179 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5180 NegOne, DAG.getConstant(0, VT),
5181 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5182 if (SCC.getNode()) return SCC;
5184 if (!VT.isVector()) {
5185 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5186 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5188 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5189 SDValue SetCC = DAG.getSetCC(DL,
5191 N0.getOperand(0), N0.getOperand(1), CC);
5192 EVT SelectVT = getSetCCResultType(VT);
5193 return DAG.getSelect(DL, VT,
5194 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5195 NegOne, DAG.getConstant(0, VT));
5201 // fold (sext x) -> (zext x) if the sign bit is known zero.
5202 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5203 DAG.SignBitIsZero(N0))
5204 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5209 // isTruncateOf - If N is a truncate of some other value, return true, record
5210 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5211 // This function computes KnownZero to avoid a duplicated call to
5212 // computeKnownBits in the caller.
5213 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5216 if (N->getOpcode() == ISD::TRUNCATE) {
5217 Op = N->getOperand(0);
5218 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5222 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5223 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5226 SDValue Op0 = N->getOperand(0);
5227 SDValue Op1 = N->getOperand(1);
5228 assert(Op0.getValueType() == Op1.getValueType());
5230 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5231 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5232 if (COp0 && COp0->isNullValue())
5234 else if (COp1 && COp1->isNullValue())
5239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5241 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5247 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5248 SDValue N0 = N->getOperand(0);
5249 EVT VT = N->getValueType(0);
5251 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5253 return SDValue(Res, 0);
5255 // fold (zext (zext x)) -> (zext x)
5256 // fold (zext (aext x)) -> (zext x)
5257 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5258 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5261 // fold (zext (truncate x)) -> (zext x) or
5262 // (zext (truncate x)) -> (truncate x)
5263 // This is valid when the truncated bits of x are already zero.
5264 // FIXME: We should extend this to work for vectors too.
5267 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5268 APInt TruncatedBits =
5269 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5270 APInt(Op.getValueSizeInBits(), 0) :
5271 APInt::getBitsSet(Op.getValueSizeInBits(),
5272 N0.getValueSizeInBits(),
5273 std::min(Op.getValueSizeInBits(),
5274 VT.getSizeInBits()));
5275 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5276 if (VT.bitsGT(Op.getValueType()))
5277 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5278 if (VT.bitsLT(Op.getValueType()))
5279 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5285 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5286 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5287 if (N0.getOpcode() == ISD::TRUNCATE) {
5288 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5289 if (NarrowLoad.getNode()) {
5290 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5291 if (NarrowLoad.getNode() != N0.getNode()) {
5292 CombineTo(N0.getNode(), NarrowLoad);
5293 // CombineTo deleted the truncate, if needed, but not what's under it.
5296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5300 // fold (zext (truncate x)) -> (and x, mask)
5301 if (N0.getOpcode() == ISD::TRUNCATE &&
5302 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5304 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5305 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
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!
5317 SDValue Op = N0.getOperand(0);
5318 if (Op.getValueType().bitsLT(VT)) {
5319 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5320 AddToWorklist(Op.getNode());
5321 } else if (Op.getValueType().bitsGT(VT)) {
5322 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5323 AddToWorklist(Op.getNode());
5325 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5326 N0.getValueType().getScalarType());
5329 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5330 // if either of the casts is not free.
5331 if (N0.getOpcode() == ISD::AND &&
5332 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5333 N0.getOperand(1).getOpcode() == ISD::Constant &&
5334 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5335 N0.getValueType()) ||
5336 !TLI.isZExtFree(N0.getValueType(), VT))) {
5337 SDValue X = N0.getOperand(0).getOperand(0);
5338 if (X.getValueType().bitsLT(VT)) {
5339 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5340 } else if (X.getValueType().bitsGT(VT)) {
5341 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344 Mask = Mask.zext(VT.getSizeInBits());
5345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5346 X, DAG.getConstant(Mask, VT));
5349 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5350 // None of the supported targets knows how to perform load and vector_zext
5351 // on vectors in one instruction. We only perform this transformation on
5353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5354 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5355 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5356 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5357 bool DoXform = true;
5358 SmallVector<SDNode*, 4> SetCCs;
5359 if (!N0.hasOneUse())
5360 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5365 LN0->getBasePtr(), N0.getValueType(),
5366 LN0->getMemOperand());
5367 CombineTo(N, ExtLoad);
5368 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5369 N0.getValueType(), ExtLoad);
5370 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5372 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5378 // fold (zext (and/or/xor (load x), cst)) ->
5379 // (and/or/xor (zextload x), (zext cst))
5380 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5381 N0.getOpcode() == ISD::XOR) &&
5382 isa<LoadSDNode>(N0.getOperand(0)) &&
5383 N0.getOperand(1).getOpcode() == ISD::Constant &&
5384 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5385 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5386 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5387 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5388 bool DoXform = true;
5389 SmallVector<SDNode*, 4> SetCCs;
5390 if (!N0.hasOneUse())
5391 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5394 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5395 LN0->getChain(), LN0->getBasePtr(),
5397 LN0->getMemOperand());
5398 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5399 Mask = Mask.zext(VT.getSizeInBits());
5400 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5401 ExtLoad, DAG.getConstant(Mask, VT));
5402 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5403 SDLoc(N0.getOperand(0)),
5404 N0.getOperand(0).getValueType(), ExtLoad);
5406 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5407 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5414 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5415 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5416 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5417 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5418 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5419 EVT MemVT = LN0->getMemoryVT();
5420 if ((!LegalOperations && !LN0->isVolatile()) ||
5421 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5422 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5424 LN0->getBasePtr(), MemVT,
5425 LN0->getMemOperand());
5426 CombineTo(N, ExtLoad);
5427 CombineTo(N0.getNode(),
5428 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5430 ExtLoad.getValue(1));
5431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5435 if (N0.getOpcode() == ISD::SETCC) {
5436 if (!LegalOperations && VT.isVector() &&
5437 N0.getValueType().getVectorElementType() == MVT::i1) {
5438 EVT N0VT = N0.getOperand(0).getValueType();
5439 if (getSetCCResultType(N0VT) == N0.getValueType())
5442 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5443 // Only do this before legalize for now.
5444 EVT EltVT = VT.getVectorElementType();
5445 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5446 DAG.getConstant(1, EltVT));
5447 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5448 // We know that the # elements of the results is the same as the
5449 // # elements of the compare (and the # elements of the compare result
5450 // for that matter). Check to see that they are the same size. If so,
5451 // we know that the element size of the sext'd result matches the
5452 // element size of the compare operands.
5453 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5454 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5456 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5457 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5460 // If the desired elements are smaller or larger than the source
5461 // elements we can use a matching integer vector type and then
5462 // truncate/sign extend
5463 EVT MatchingElementType =
5464 EVT::getIntegerVT(*DAG.getContext(),
5465 N0VT.getScalarType().getSizeInBits());
5466 EVT MatchingVectorType =
5467 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5468 N0VT.getVectorNumElements());
5470 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5472 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5473 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5474 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5478 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5480 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5481 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5482 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5483 if (SCC.getNode()) return SCC;
5486 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5487 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5488 isa<ConstantSDNode>(N0.getOperand(1)) &&
5489 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5491 SDValue ShAmt = N0.getOperand(1);
5492 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5493 if (N0.getOpcode() == ISD::SHL) {
5494 SDValue InnerZExt = N0.getOperand(0);
5495 // If the original shl may be shifting out bits, do not perform this
5497 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5498 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5499 if (ShAmtVal > KnownZeroBits)
5505 // Ensure that the shift amount is wide enough for the shifted value.
5506 if (VT.getSizeInBits() >= 256)
5507 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5509 return DAG.getNode(N0.getOpcode(), DL, VT,
5510 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5517 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5518 SDValue N0 = N->getOperand(0);
5519 EVT VT = N->getValueType(0);
5521 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5523 return SDValue(Res, 0);
5525 // fold (aext (aext x)) -> (aext x)
5526 // fold (aext (zext x)) -> (zext x)
5527 // fold (aext (sext x)) -> (sext x)
5528 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5529 N0.getOpcode() == ISD::ZERO_EXTEND ||
5530 N0.getOpcode() == ISD::SIGN_EXTEND)
5531 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5533 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5534 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5535 if (N0.getOpcode() == ISD::TRUNCATE) {
5536 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5537 if (NarrowLoad.getNode()) {
5538 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5539 if (NarrowLoad.getNode() != N0.getNode()) {
5540 CombineTo(N0.getNode(), NarrowLoad);
5541 // CombineTo deleted the truncate, if needed, but not what's under it.
5544 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5548 // fold (aext (truncate x))
5549 if (N0.getOpcode() == ISD::TRUNCATE) {
5550 SDValue TruncOp = N0.getOperand(0);
5551 if (TruncOp.getValueType() == VT)
5552 return TruncOp; // x iff x size == zext size.
5553 if (TruncOp.getValueType().bitsGT(VT))
5554 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5555 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5558 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5559 // if the trunc is not free.
5560 if (N0.getOpcode() == ISD::AND &&
5561 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5562 N0.getOperand(1).getOpcode() == ISD::Constant &&
5563 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5564 N0.getValueType())) {
5565 SDValue X = N0.getOperand(0).getOperand(0);
5566 if (X.getValueType().bitsLT(VT)) {
5567 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5568 } else if (X.getValueType().bitsGT(VT)) {
5569 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5571 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5572 Mask = Mask.zext(VT.getSizeInBits());
5573 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5574 X, DAG.getConstant(Mask, VT));
5577 // fold (aext (load x)) -> (aext (truncate (extload x)))
5578 // None of the supported targets knows how to perform load and any_ext
5579 // on vectors in one instruction. We only perform this transformation on
5581 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5582 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5583 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5584 bool DoXform = true;
5585 SmallVector<SDNode*, 4> SetCCs;
5586 if (!N0.hasOneUse())
5587 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5589 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5590 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5592 LN0->getBasePtr(), N0.getValueType(),
5593 LN0->getMemOperand());
5594 CombineTo(N, ExtLoad);
5595 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5596 N0.getValueType(), ExtLoad);
5597 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5598 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5604 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5605 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5606 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5607 if (N0.getOpcode() == ISD::LOAD &&
5608 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611 ISD::LoadExtType ExtType = LN0->getExtensionType();
5612 EVT MemVT = LN0->getMemoryVT();
5613 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5614 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5615 VT, LN0->getChain(), LN0->getBasePtr(),
5616 MemVT, LN0->getMemOperand());
5617 CombineTo(N, ExtLoad);
5618 CombineTo(N0.getNode(),
5619 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5620 N0.getValueType(), ExtLoad),
5621 ExtLoad.getValue(1));
5622 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5626 if (N0.getOpcode() == ISD::SETCC) {
5628 // aext(setcc) -> vsetcc
5629 // aext(setcc) -> truncate(vsetcc)
5630 // aext(setcc) -> aext(vsetcc)
5631 // Only do this before legalize for now.
5632 if (VT.isVector() && !LegalOperations) {
5633 EVT N0VT = N0.getOperand(0).getValueType();
5634 // We know that the # elements of the results is the same as the
5635 // # elements of the compare (and the # elements of the compare result
5636 // for that matter). Check to see that they are the same size. If so,
5637 // we know that the element size of the sext'd result matches the
5638 // element size of the compare operands.
5639 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5640 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5642 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5643 // If the desired elements are smaller or larger than the source
5644 // elements we can use a matching integer vector type and then
5645 // truncate/any extend
5647 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5649 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5651 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5652 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5656 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5658 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5659 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5660 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5668 /// GetDemandedBits - See if the specified operand can be simplified with the
5669 /// knowledge that only the bits specified by Mask are used. If so, return the
5670 /// simpler operand, otherwise return a null SDValue.
5671 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5672 switch (V.getOpcode()) {
5674 case ISD::Constant: {
5675 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5676 assert(CV && "Const value should be ConstSDNode.");
5677 const APInt &CVal = CV->getAPIntValue();
5678 APInt NewVal = CVal & Mask;
5680 return DAG.getConstant(NewVal, V.getValueType());
5685 // If the LHS or RHS don't contribute bits to the or, drop them.
5686 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5687 return V.getOperand(1);
5688 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5689 return V.getOperand(0);
5692 // Only look at single-use SRLs.
5693 if (!V.getNode()->hasOneUse())
5695 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5696 // See if we can recursively simplify the LHS.
5697 unsigned Amt = RHSC->getZExtValue();
5699 // Watch out for shift count overflow though.
5700 if (Amt >= Mask.getBitWidth()) break;
5701 APInt NewMask = Mask << Amt;
5702 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5703 if (SimplifyLHS.getNode())
5704 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5705 SimplifyLHS, V.getOperand(1));
5711 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5712 /// bits and then truncated to a narrower type and where N is a multiple
5713 /// of number of bits of the narrower type, transform it to a narrower load
5714 /// from address + N / num of bits of new type. If the result is to be
5715 /// extended, also fold the extension to form a extending load.
5716 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5717 unsigned Opc = N->getOpcode();
5719 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5720 SDValue N0 = N->getOperand(0);
5721 EVT VT = N->getValueType(0);
5724 // This transformation isn't valid for vector loads.
5728 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5730 if (Opc == ISD::SIGN_EXTEND_INREG) {
5731 ExtType = ISD::SEXTLOAD;
5732 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5733 } else if (Opc == ISD::SRL) {
5734 // Another special-case: SRL is basically zero-extending a narrower value.
5735 ExtType = ISD::ZEXTLOAD;
5737 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5738 if (!N01) return SDValue();
5739 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5740 VT.getSizeInBits() - N01->getZExtValue());
5742 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5745 unsigned EVTBits = ExtVT.getSizeInBits();
5747 // Do not generate loads of non-round integer types since these can
5748 // be expensive (and would be wrong if the type is not byte sized).
5749 if (!ExtVT.isRound())
5753 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5754 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5755 ShAmt = N01->getZExtValue();
5756 // Is the shift amount a multiple of size of VT?
5757 if ((ShAmt & (EVTBits-1)) == 0) {
5758 N0 = N0.getOperand(0);
5759 // Is the load width a multiple of size of VT?
5760 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5764 // At this point, we must have a load or else we can't do the transform.
5765 if (!isa<LoadSDNode>(N0)) return SDValue();
5767 // Because a SRL must be assumed to *need* to zero-extend the high bits
5768 // (as opposed to anyext the high bits), we can't combine the zextload
5769 // lowering of SRL and an sextload.
5770 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5773 // If the shift amount is larger than the input type then we're not
5774 // accessing any of the loaded bytes. If the load was a zextload/extload
5775 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5776 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5781 // If the load is shifted left (and the result isn't shifted back right),
5782 // we can fold the truncate through the shift.
5783 unsigned ShLeftAmt = 0;
5784 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5785 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5786 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5787 ShLeftAmt = N01->getZExtValue();
5788 N0 = N0.getOperand(0);
5792 // If we haven't found a load, we can't narrow it. Don't transform one with
5793 // multiple uses, this would require adding a new load.
5794 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5797 // Don't change the width of a volatile load.
5798 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5799 if (LN0->isVolatile())
5802 // Verify that we are actually reducing a load width here.
5803 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5806 // For the transform to be legal, the load must produce only two values
5807 // (the value loaded and the chain). Don't transform a pre-increment
5808 // load, for example, which produces an extra value. Otherwise the
5809 // transformation is not equivalent, and the downstream logic to replace
5810 // uses gets things wrong.
5811 if (LN0->getNumValues() > 2)
5814 // If the load that we're shrinking is an extload and we're not just
5815 // discarding the extension we can't simply shrink the load. Bail.
5816 // TODO: It would be possible to merge the extensions in some cases.
5817 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5818 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5821 EVT PtrType = N0.getOperand(1).getValueType();
5823 if (PtrType == MVT::Untyped || PtrType.isExtended())
5824 // It's not possible to generate a constant of extended or untyped type.
5827 // For big endian targets, we need to adjust the offset to the pointer to
5828 // load the correct bytes.
5829 if (TLI.isBigEndian()) {
5830 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5831 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5832 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5835 uint64_t PtrOff = ShAmt / 8;
5836 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5837 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5838 PtrType, LN0->getBasePtr(),
5839 DAG.getConstant(PtrOff, PtrType));
5840 AddToWorklist(NewPtr.getNode());
5843 if (ExtType == ISD::NON_EXTLOAD)
5844 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5845 LN0->getPointerInfo().getWithOffset(PtrOff),
5846 LN0->isVolatile(), LN0->isNonTemporal(),
5847 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5849 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5850 LN0->getPointerInfo().getWithOffset(PtrOff),
5851 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5852 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5854 // Replace the old load's chain with the new load's chain.
5855 WorklistRemover DeadNodes(*this);
5856 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5858 // Shift the result left, if we've swallowed a left shift.
5859 SDValue Result = Load;
5860 if (ShLeftAmt != 0) {
5861 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5862 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5864 // If the shift amount is as large as the result size (but, presumably,
5865 // no larger than the source) then the useful bits of the result are
5866 // zero; we can't simply return the shortened shift, because the result
5867 // of that operation is undefined.
5868 if (ShLeftAmt >= VT.getSizeInBits())
5869 Result = DAG.getConstant(0, VT);
5871 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5872 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5875 // Return the new loaded value.
5879 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5880 SDValue N0 = N->getOperand(0);
5881 SDValue N1 = N->getOperand(1);
5882 EVT VT = N->getValueType(0);
5883 EVT EVT = cast<VTSDNode>(N1)->getVT();
5884 unsigned VTBits = VT.getScalarType().getSizeInBits();
5885 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5887 // fold (sext_in_reg c1) -> c1
5888 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5889 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5891 // If the input is already sign extended, just drop the extension.
5892 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5895 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5896 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5897 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5898 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5899 N0.getOperand(0), N1);
5901 // fold (sext_in_reg (sext x)) -> (sext x)
5902 // fold (sext_in_reg (aext x)) -> (sext x)
5903 // if x is small enough.
5904 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5905 SDValue N00 = N0.getOperand(0);
5906 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5907 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5908 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5911 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5912 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5913 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5915 // fold operands of sext_in_reg based on knowledge that the top bits are not
5917 if (SimplifyDemandedBits(SDValue(N, 0)))
5918 return SDValue(N, 0);
5920 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5921 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5922 SDValue NarrowLoad = ReduceLoadWidth(N);
5923 if (NarrowLoad.getNode())
5926 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5927 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5928 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5929 if (N0.getOpcode() == ISD::SRL) {
5930 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5931 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5932 // We can turn this into an SRA iff the input to the SRL is already sign
5934 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5935 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5936 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5937 N0.getOperand(0), N0.getOperand(1));
5941 // fold (sext_inreg (extload x)) -> (sextload x)
5942 if (ISD::isEXTLoad(N0.getNode()) &&
5943 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5944 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5945 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5946 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5948 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5950 LN0->getBasePtr(), EVT,
5951 LN0->getMemOperand());
5952 CombineTo(N, ExtLoad);
5953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5954 AddToWorklist(ExtLoad.getNode());
5955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5957 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5958 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5960 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5961 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5962 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5963 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5964 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5966 LN0->getBasePtr(), EVT,
5967 LN0->getMemOperand());
5968 CombineTo(N, ExtLoad);
5969 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5973 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5974 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5975 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5976 N0.getOperand(1), false);
5977 if (BSwap.getNode())
5978 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5982 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5983 // into a build_vector.
5984 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5985 SmallVector<SDValue, 8> Elts;
5986 unsigned NumElts = N0->getNumOperands();
5987 unsigned ShAmt = VTBits - EVTBits;
5989 for (unsigned i = 0; i != NumElts; ++i) {
5990 SDValue Op = N0->getOperand(i);
5991 if (Op->getOpcode() == ISD::UNDEF) {
5996 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5997 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5998 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5999 Op.getValueType()));
6002 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6008 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6009 SDValue N0 = N->getOperand(0);
6010 EVT VT = N->getValueType(0);
6011 bool isLE = TLI.isLittleEndian();
6014 if (N0.getValueType() == N->getValueType(0))
6016 // fold (truncate c1) -> c1
6017 if (isa<ConstantSDNode>(N0))
6018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6019 // fold (truncate (truncate x)) -> (truncate x)
6020 if (N0.getOpcode() == ISD::TRUNCATE)
6021 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6022 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6023 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6024 N0.getOpcode() == ISD::SIGN_EXTEND ||
6025 N0.getOpcode() == ISD::ANY_EXTEND) {
6026 if (N0.getOperand(0).getValueType().bitsLT(VT))
6027 // if the source is smaller than the dest, we still need an extend
6028 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6030 if (N0.getOperand(0).getValueType().bitsGT(VT))
6031 // if the source is larger than the dest, than we just need the truncate
6032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6033 // if the source and dest are the same type, we can drop both the extend
6034 // and the truncate.
6035 return N0.getOperand(0);
6038 // Fold extract-and-trunc into a narrow extract. For example:
6039 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6040 // i32 y = TRUNCATE(i64 x)
6042 // v16i8 b = BITCAST (v2i64 val)
6043 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6045 // Note: We only run this optimization after type legalization (which often
6046 // creates this pattern) and before operation legalization after which
6047 // we need to be more careful about the vector instructions that we generate.
6048 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6049 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6051 EVT VecTy = N0.getOperand(0).getValueType();
6052 EVT ExTy = N0.getValueType();
6053 EVT TrTy = N->getValueType(0);
6055 unsigned NumElem = VecTy.getVectorNumElements();
6056 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6059 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6061 SDValue EltNo = N0->getOperand(1);
6062 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6063 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6064 EVT IndexTy = TLI.getVectorIdxTy();
6065 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6067 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6068 NVT, N0.getOperand(0));
6070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6072 DAG.getConstant(Index, IndexTy));
6076 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6077 if (N0.getOpcode() == ISD::SELECT) {
6078 EVT SrcVT = N0.getValueType();
6079 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6080 TLI.isTruncateFree(SrcVT, VT)) {
6082 SDValue Cond = N0.getOperand(0);
6083 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6084 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6085 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6089 // Fold a series of buildvector, bitcast, and truncate if possible.
6091 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6092 // (2xi32 (buildvector x, y)).
6093 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6094 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6095 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6096 N0.getOperand(0).hasOneUse()) {
6098 SDValue BuildVect = N0.getOperand(0);
6099 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6100 EVT TruncVecEltTy = VT.getVectorElementType();
6102 // Check that the element types match.
6103 if (BuildVectEltTy == TruncVecEltTy) {
6104 // Now we only need to compute the offset of the truncated elements.
6105 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6106 unsigned TruncVecNumElts = VT.getVectorNumElements();
6107 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6109 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6110 "Invalid number of elements");
6112 SmallVector<SDValue, 8> Opnds;
6113 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6114 Opnds.push_back(BuildVect.getOperand(i));
6116 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6120 // See if we can simplify the input to this truncate through knowledge that
6121 // only the low bits are being used.
6122 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6123 // Currently we only perform this optimization on scalars because vectors
6124 // may have different active low bits.
6125 if (!VT.isVector()) {
6127 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6128 VT.getSizeInBits()));
6129 if (Shorter.getNode())
6130 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6132 // fold (truncate (load x)) -> (smaller load x)
6133 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6134 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6135 SDValue Reduced = ReduceLoadWidth(N);
6136 if (Reduced.getNode())
6138 // Handle the case where the load remains an extending load even
6139 // after truncation.
6140 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6141 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6142 if (!LN0->isVolatile() &&
6143 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6144 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6145 VT, LN0->getChain(), LN0->getBasePtr(),
6147 LN0->getMemOperand());
6148 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6153 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6154 // where ... are all 'undef'.
6155 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6156 SmallVector<EVT, 8> VTs;
6159 unsigned NumDefs = 0;
6161 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6162 SDValue X = N0.getOperand(i);
6163 if (X.getOpcode() != ISD::UNDEF) {
6168 // Stop if more than one members are non-undef.
6171 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6172 VT.getVectorElementType(),
6173 X.getValueType().getVectorNumElements()));
6177 return DAG.getUNDEF(VT);
6180 assert(V.getNode() && "The single defined operand is empty!");
6181 SmallVector<SDValue, 8> Opnds;
6182 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6184 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6187 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6188 AddToWorklist(NV.getNode());
6189 Opnds.push_back(NV);
6191 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6195 // Simplify the operands using demanded-bits information.
6196 if (!VT.isVector() &&
6197 SimplifyDemandedBits(SDValue(N, 0)))
6198 return SDValue(N, 0);
6203 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6204 SDValue Elt = N->getOperand(i);
6205 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6206 return Elt.getNode();
6207 return Elt.getOperand(Elt.getResNo()).getNode();
6210 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6211 /// if load locations are consecutive.
6212 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6213 assert(N->getOpcode() == ISD::BUILD_PAIR);
6215 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6216 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6217 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6218 LD1->getAddressSpace() != LD2->getAddressSpace())
6220 EVT LD1VT = LD1->getValueType(0);
6222 if (ISD::isNON_EXTLoad(LD2) &&
6224 // If both are volatile this would reduce the number of volatile loads.
6225 // If one is volatile it might be ok, but play conservative and bail out.
6226 !LD1->isVolatile() &&
6227 !LD2->isVolatile() &&
6228 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6229 unsigned Align = LD1->getAlignment();
6230 unsigned NewAlign = TLI.getDataLayout()->
6231 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6233 if (NewAlign <= Align &&
6234 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6235 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6236 LD1->getBasePtr(), LD1->getPointerInfo(),
6237 false, false, false, Align);
6243 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6244 SDValue N0 = N->getOperand(0);
6245 EVT VT = N->getValueType(0);
6247 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6248 // Only do this before legalize, since afterward the target may be depending
6249 // on the bitconvert.
6250 // First check to see if this is all constant.
6252 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6254 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6256 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6257 assert(!DestEltVT.isVector() &&
6258 "Element type of vector ValueType must not be vector!");
6260 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6263 // If the input is a constant, let getNode fold it.
6264 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6265 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6266 if (Res.getNode() != N) {
6267 if (!LegalOperations ||
6268 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6271 // Folding it resulted in an illegal node, and it's too late to
6272 // do that. Clean up the old node and forego the transformation.
6273 // Ideally this won't happen very often, because instcombine
6274 // and the earlier dagcombine runs (where illegal nodes are
6275 // permitted) should have folded most of them already.
6276 deleteAndRecombine(Res.getNode());
6280 // (conv (conv x, t1), t2) -> (conv x, t2)
6281 if (N0.getOpcode() == ISD::BITCAST)
6282 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6285 // fold (conv (load x)) -> (load (conv*)x)
6286 // If the resultant load doesn't need a higher alignment than the original!
6287 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6288 // Do not change the width of a volatile load.
6289 !cast<LoadSDNode>(N0)->isVolatile() &&
6290 // Do not remove the cast if the types differ in endian layout.
6291 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6292 TLI.hasBigEndianPartOrdering(VT) &&
6293 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6294 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6296 unsigned Align = TLI.getDataLayout()->
6297 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6298 unsigned OrigAlign = LN0->getAlignment();
6300 if (Align <= OrigAlign) {
6301 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6302 LN0->getBasePtr(), LN0->getPointerInfo(),
6303 LN0->isVolatile(), LN0->isNonTemporal(),
6304 LN0->isInvariant(), OrigAlign,
6306 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6311 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6312 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6313 // This often reduces constant pool loads.
6314 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6315 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6316 N0.getNode()->hasOneUse() && VT.isInteger() &&
6317 !VT.isVector() && !N0.getValueType().isVector()) {
6318 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6320 AddToWorklist(NewConv.getNode());
6322 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6323 if (N0.getOpcode() == ISD::FNEG)
6324 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6325 NewConv, DAG.getConstant(SignBit, VT));
6326 assert(N0.getOpcode() == ISD::FABS);
6327 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6328 NewConv, DAG.getConstant(~SignBit, VT));
6331 // fold (bitconvert (fcopysign cst, x)) ->
6332 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6333 // Note that we don't handle (copysign x, cst) because this can always be
6334 // folded to an fneg or fabs.
6335 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6336 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6337 VT.isInteger() && !VT.isVector()) {
6338 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6339 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6340 if (isTypeLegal(IntXVT)) {
6341 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6342 IntXVT, N0.getOperand(1));
6343 AddToWorklist(X.getNode());
6345 // If X has a different width than the result/lhs, sext it or truncate it.
6346 unsigned VTWidth = VT.getSizeInBits();
6347 if (OrigXWidth < VTWidth) {
6348 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6349 AddToWorklist(X.getNode());
6350 } else if (OrigXWidth > VTWidth) {
6351 // To get the sign bit in the right place, we have to shift it right
6352 // before truncating.
6353 X = DAG.getNode(ISD::SRL, SDLoc(X),
6354 X.getValueType(), X,
6355 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6356 AddToWorklist(X.getNode());
6357 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6358 AddToWorklist(X.getNode());
6361 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6362 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6363 X, DAG.getConstant(SignBit, VT));
6364 AddToWorklist(X.getNode());
6366 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6367 VT, N0.getOperand(0));
6368 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6369 Cst, DAG.getConstant(~SignBit, VT));
6370 AddToWorklist(Cst.getNode());
6372 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6376 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6377 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6378 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6379 if (CombineLD.getNode())
6386 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6387 EVT VT = N->getValueType(0);
6388 return CombineConsecutiveLoads(N, VT);
6391 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6392 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6393 /// destination element value type.
6394 SDValue DAGCombiner::
6395 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6396 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6398 // If this is already the right type, we're done.
6399 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6401 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6402 unsigned DstBitSize = DstEltVT.getSizeInBits();
6404 // If this is a conversion of N elements of one type to N elements of another
6405 // type, convert each element. This handles FP<->INT cases.
6406 if (SrcBitSize == DstBitSize) {
6407 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6408 BV->getValueType(0).getVectorNumElements());
6410 // Due to the FP element handling below calling this routine recursively,
6411 // we can end up with a scalar-to-vector node here.
6412 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6413 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6414 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6415 DstEltVT, BV->getOperand(0)));
6417 SmallVector<SDValue, 8> Ops;
6418 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6419 SDValue Op = BV->getOperand(i);
6420 // If the vector element type is not legal, the BUILD_VECTOR operands
6421 // are promoted and implicitly truncated. Make that explicit here.
6422 if (Op.getValueType() != SrcEltVT)
6423 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6424 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6426 AddToWorklist(Ops.back().getNode());
6428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6431 // Otherwise, we're growing or shrinking the elements. To avoid having to
6432 // handle annoying details of growing/shrinking FP values, we convert them to
6434 if (SrcEltVT.isFloatingPoint()) {
6435 // Convert the input float vector to a int vector where the elements are the
6437 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6438 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6439 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6443 // Now we know the input is an integer vector. If the output is a FP type,
6444 // convert to integer first, then to FP of the right size.
6445 if (DstEltVT.isFloatingPoint()) {
6446 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6447 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6448 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6450 // Next, convert to FP elements of the same size.
6451 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6454 // Okay, we know the src/dst types are both integers of differing types.
6455 // Handling growing first.
6456 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6457 if (SrcBitSize < DstBitSize) {
6458 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6460 SmallVector<SDValue, 8> Ops;
6461 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6462 i += NumInputsPerOutput) {
6463 bool isLE = TLI.isLittleEndian();
6464 APInt NewBits = APInt(DstBitSize, 0);
6465 bool EltIsUndef = true;
6466 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6467 // Shift the previously computed bits over.
6468 NewBits <<= SrcBitSize;
6469 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6470 if (Op.getOpcode() == ISD::UNDEF) continue;
6473 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6474 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6478 Ops.push_back(DAG.getUNDEF(DstEltVT));
6480 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6483 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6484 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6487 // Finally, this must be the case where we are shrinking elements: each input
6488 // turns into multiple outputs.
6489 bool isS2V = ISD::isScalarToVector(BV);
6490 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6491 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6492 NumOutputsPerInput*BV->getNumOperands());
6493 SmallVector<SDValue, 8> Ops;
6495 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6496 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6497 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6498 Ops.push_back(DAG.getUNDEF(DstEltVT));
6502 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6503 getAPIntValue().zextOrTrunc(SrcBitSize);
6505 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6506 APInt ThisVal = OpVal.trunc(DstBitSize);
6507 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6508 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6509 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6510 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6512 OpVal = OpVal.lshr(DstBitSize);
6515 // For big endian targets, swap the order of the pieces of each element.
6516 if (TLI.isBigEndian())
6517 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6520 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6523 SDValue DAGCombiner::visitFADD(SDNode *N) {
6524 SDValue N0 = N->getOperand(0);
6525 SDValue N1 = N->getOperand(1);
6526 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6527 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6528 EVT VT = N->getValueType(0);
6531 if (VT.isVector()) {
6532 SDValue FoldedVOp = SimplifyVBinOp(N);
6533 if (FoldedVOp.getNode()) return FoldedVOp;
6536 // fold (fadd c1, c2) -> c1 + c2
6538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6539 // canonicalize constant to RHS
6540 if (N0CFP && !N1CFP)
6541 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6542 // fold (fadd A, 0) -> A
6543 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6544 N1CFP->getValueAPF().isZero())
6546 // fold (fadd A, (fneg B)) -> (fsub A, B)
6547 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6548 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6549 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6550 GetNegatedExpression(N1, DAG, LegalOperations));
6551 // fold (fadd (fneg A), B) -> (fsub B, A)
6552 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6553 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6554 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6555 GetNegatedExpression(N0, DAG, LegalOperations));
6557 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6558 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6559 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6560 isa<ConstantFPSDNode>(N0.getOperand(1)))
6561 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6562 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563 N0.getOperand(1), N1));
6565 // No FP constant should be created after legalization as Instruction
6566 // Selection pass has hard time in dealing with FP constant.
6568 // We don't need test this condition for transformation like following, as
6569 // the DAG being transformed implies it is legal to take FP constant as
6572 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6574 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6576 // If allow, fold (fadd (fneg x), x) -> 0.0
6577 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6578 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6579 return DAG.getConstantFP(0.0, VT);
6581 // If allow, fold (fadd x, (fneg x)) -> 0.0
6582 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6583 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6584 return DAG.getConstantFP(0.0, VT);
6586 // In unsafe math mode, we can fold chains of FADD's of the same value
6587 // into multiplications. This transform is not safe in general because
6588 // we are reducing the number of rounding steps.
6589 if (DAG.getTarget().Options.UnsafeFPMath &&
6590 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6592 if (N0.getOpcode() == ISD::FMUL) {
6593 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6594 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6596 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6597 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6598 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6600 DAG.getConstantFP(1.0, VT));
6601 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6605 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6606 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6607 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6609 DAG.getConstantFP(1.0, VT));
6610 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6614 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6615 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6616 N1.getOperand(0) == N1.getOperand(1) &&
6617 N0.getOperand(1) == N1.getOperand(0)) {
6618 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620 DAG.getConstantFP(2.0, VT));
6621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622 N0.getOperand(1), NewCFP);
6625 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6626 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6627 N1.getOperand(0) == N1.getOperand(1) &&
6628 N0.getOperand(0) == N1.getOperand(0)) {
6629 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6631 DAG.getConstantFP(2.0, VT));
6632 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633 N0.getOperand(0), NewCFP);
6637 if (N1.getOpcode() == ISD::FMUL) {
6638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6639 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6641 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6642 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(1.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6650 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6651 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6652 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6654 DAG.getConstantFP(1.0, VT));
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6660 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6661 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6662 N0.getOperand(0) == N0.getOperand(1) &&
6663 N1.getOperand(1) == N0.getOperand(0)) {
6664 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6666 DAG.getConstantFP(2.0, VT));
6667 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6668 N1.getOperand(1), NewCFP);
6671 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6672 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6673 N0.getOperand(0) == N0.getOperand(1) &&
6674 N1.getOperand(0) == N0.getOperand(0)) {
6675 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6677 DAG.getConstantFP(2.0, VT));
6678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679 N1.getOperand(0), NewCFP);
6683 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6684 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6685 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6686 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6687 (N0.getOperand(0) == N1))
6688 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6689 N1, DAG.getConstantFP(3.0, VT));
6692 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6693 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6694 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6695 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6696 N1.getOperand(0) == N0)
6697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6698 N0, DAG.getConstantFP(3.0, VT));
6701 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6702 if (AllowNewFpConst &&
6703 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6704 N0.getOperand(0) == N0.getOperand(1) &&
6705 N1.getOperand(0) == N1.getOperand(1) &&
6706 N0.getOperand(0) == N1.getOperand(0))
6707 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6709 DAG.getConstantFP(4.0, VT));
6712 // FADD -> FMA combines:
6713 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6714 DAG.getTarget().Options.UnsafeFPMath) &&
6717 ->getTargetLowering()
6718 ->isFMAFasterThanFMulAndFAdd(VT) &&
6719 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6721 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6722 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6723 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6724 N0.getOperand(0), N0.getOperand(1), N1);
6726 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6727 // Note: Commutes FADD operands.
6728 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6729 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6730 N1.getOperand(0), N1.getOperand(1), N0);
6736 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 SDValue N1 = N->getOperand(1);
6739 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6740 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6741 EVT VT = N->getValueType(0);
6745 if (VT.isVector()) {
6746 SDValue FoldedVOp = SimplifyVBinOp(N);
6747 if (FoldedVOp.getNode()) return FoldedVOp;
6750 // fold (fsub c1, c2) -> c1-c2
6752 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6753 // fold (fsub A, 0) -> A
6754 if (DAG.getTarget().Options.UnsafeFPMath &&
6755 N1CFP && N1CFP->getValueAPF().isZero())
6757 // fold (fsub 0, B) -> -B
6758 if (DAG.getTarget().Options.UnsafeFPMath &&
6759 N0CFP && N0CFP->getValueAPF().isZero()) {
6760 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6761 return GetNegatedExpression(N1, DAG, LegalOperations);
6762 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6763 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6765 // fold (fsub A, (fneg B)) -> (fadd A, B)
6766 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6767 return DAG.getNode(ISD::FADD, dl, VT, N0,
6768 GetNegatedExpression(N1, DAG, LegalOperations));
6770 // If 'unsafe math' is enabled, fold
6771 // (fsub x, x) -> 0.0 &
6772 // (fsub x, (fadd x, y)) -> (fneg y) &
6773 // (fsub x, (fadd y, x)) -> (fneg y)
6774 if (DAG.getTarget().Options.UnsafeFPMath) {
6776 return DAG.getConstantFP(0.0f, VT);
6778 if (N1.getOpcode() == ISD::FADD) {
6779 SDValue N10 = N1->getOperand(0);
6780 SDValue N11 = N1->getOperand(1);
6782 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6783 &DAG.getTarget().Options))
6784 return GetNegatedExpression(N11, DAG, LegalOperations);
6786 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6787 &DAG.getTarget().Options))
6788 return GetNegatedExpression(N10, DAG, LegalOperations);
6792 // FSUB -> FMA combines:
6793 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6794 DAG.getTarget().Options.UnsafeFPMath) &&
6797 ->getTargetLowering()
6798 ->isFMAFasterThanFMulAndFAdd(VT) &&
6799 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6801 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6802 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6803 return DAG.getNode(ISD::FMA, dl, VT,
6804 N0.getOperand(0), N0.getOperand(1),
6805 DAG.getNode(ISD::FNEG, dl, VT, N1));
6807 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6808 // Note: Commutes FSUB operands.
6809 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6810 return DAG.getNode(ISD::FMA, dl, VT,
6811 DAG.getNode(ISD::FNEG, dl, VT,
6813 N1.getOperand(1), N0);
6815 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6816 if (N0.getOpcode() == ISD::FNEG &&
6817 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6818 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6819 SDValue N00 = N0.getOperand(0).getOperand(0);
6820 SDValue N01 = N0.getOperand(0).getOperand(1);
6821 return DAG.getNode(ISD::FMA, dl, VT,
6822 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6823 DAG.getNode(ISD::FNEG, dl, VT, N1));
6830 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6831 SDValue N0 = N->getOperand(0);
6832 SDValue N1 = N->getOperand(1);
6833 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6834 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6835 EVT VT = N->getValueType(0);
6836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6839 if (VT.isVector()) {
6840 SDValue FoldedVOp = SimplifyVBinOp(N);
6841 if (FoldedVOp.getNode()) return FoldedVOp;
6844 // fold (fmul c1, c2) -> c1*c2
6846 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6847 // canonicalize constant to RHS
6848 if (N0CFP && !N1CFP)
6849 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6850 // fold (fmul A, 0) -> 0
6851 if (DAG.getTarget().Options.UnsafeFPMath &&
6852 N1CFP && N1CFP->getValueAPF().isZero())
6854 // fold (fmul A, 0) -> 0, vector edition.
6855 if (DAG.getTarget().Options.UnsafeFPMath &&
6856 ISD::isBuildVectorAllZeros(N1.getNode()))
6858 // fold (fmul A, 1.0) -> A
6859 if (N1CFP && N1CFP->isExactlyValue(1.0))
6861 // fold (fmul X, 2.0) -> (fadd X, X)
6862 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6863 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6864 // fold (fmul X, -1.0) -> (fneg X)
6865 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6866 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6867 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6869 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6870 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6871 &DAG.getTarget().Options)) {
6872 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6873 &DAG.getTarget().Options)) {
6874 // Both can be negated for free, check to see if at least one is cheaper
6876 if (LHSNeg == 2 || RHSNeg == 2)
6877 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6878 GetNegatedExpression(N0, DAG, LegalOperations),
6879 GetNegatedExpression(N1, DAG, LegalOperations));
6883 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6884 if (DAG.getTarget().Options.UnsafeFPMath &&
6885 N1CFP && N0.getOpcode() == ISD::FMUL &&
6886 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6887 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6888 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6889 N0.getOperand(1), N1));
6894 SDValue DAGCombiner::visitFMA(SDNode *N) {
6895 SDValue N0 = N->getOperand(0);
6896 SDValue N1 = N->getOperand(1);
6897 SDValue N2 = N->getOperand(2);
6898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6899 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6900 EVT VT = N->getValueType(0);
6904 // Constant fold FMA.
6905 if (isa<ConstantFPSDNode>(N0) &&
6906 isa<ConstantFPSDNode>(N1) &&
6907 isa<ConstantFPSDNode>(N2)) {
6908 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6911 if (DAG.getTarget().Options.UnsafeFPMath) {
6912 if (N0CFP && N0CFP->isZero())
6914 if (N1CFP && N1CFP->isZero())
6917 if (N0CFP && N0CFP->isExactlyValue(1.0))
6918 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6919 if (N1CFP && N1CFP->isExactlyValue(1.0))
6920 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6922 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6923 if (N0CFP && !N1CFP)
6924 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6926 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6927 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6928 N2.getOpcode() == ISD::FMUL &&
6929 N0 == N2.getOperand(0) &&
6930 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6931 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6932 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6936 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6937 if (DAG.getTarget().Options.UnsafeFPMath &&
6938 N0.getOpcode() == ISD::FMUL && N1CFP &&
6939 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6940 return DAG.getNode(ISD::FMA, dl, VT,
6942 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6946 // (fma x, 1, y) -> (fadd x, y)
6947 // (fma x, -1, y) -> (fadd (fneg x), y)
6949 if (N1CFP->isExactlyValue(1.0))
6950 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6952 if (N1CFP->isExactlyValue(-1.0) &&
6953 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6954 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6955 AddToWorklist(RHSNeg.getNode());
6956 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6960 // (fma x, c, x) -> (fmul x, (c+1))
6961 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6962 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6963 DAG.getNode(ISD::FADD, dl, VT,
6964 N1, DAG.getConstantFP(1.0, VT)));
6966 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6967 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6968 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6969 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6970 DAG.getNode(ISD::FADD, dl, VT,
6971 N1, DAG.getConstantFP(-1.0, VT)));
6977 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6978 SDValue N0 = N->getOperand(0);
6979 SDValue N1 = N->getOperand(1);
6980 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6981 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6982 EVT VT = N->getValueType(0);
6983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6986 if (VT.isVector()) {
6987 SDValue FoldedVOp = SimplifyVBinOp(N);
6988 if (FoldedVOp.getNode()) return FoldedVOp;
6991 // fold (fdiv c1, c2) -> c1/c2
6993 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6995 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6996 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6997 // Compute the reciprocal 1.0 / c2.
6998 APFloat N1APF = N1CFP->getValueAPF();
6999 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7000 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7001 // Only do the transform if the reciprocal is a legal fp immediate that
7002 // isn't too nasty (eg NaN, denormal, ...).
7003 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7004 (!LegalOperations ||
7005 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7006 // backend)... we should handle this gracefully after Legalize.
7007 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7008 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7009 TLI.isFPImmLegal(Recip, VT)))
7010 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7011 DAG.getConstantFP(Recip, VT));
7014 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7015 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7016 &DAG.getTarget().Options)) {
7017 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7018 &DAG.getTarget().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::visitFNEG(SDNode *N) {
7308 SDValue N0 = N->getOperand(0);
7309 EVT VT = N->getValueType(0);
7311 // Constant fold FNEG.
7312 if (isa<ConstantFPSDNode>(N0))
7313 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7315 if (VT.isVector()) {
7316 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7317 if (FoldedVOp.getNode()) return FoldedVOp;
7320 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7321 &DAG.getTarget().Options))
7322 return GetNegatedExpression(N0, DAG, LegalOperations);
7324 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7325 // constant pool values.
7326 // TODO: We can also optimize for vectors here, but we need to make sure
7327 // that the sign mask is created properly for each vector element.
7328 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7330 N0.getNode()->hasOneUse() &&
7331 N0.getOperand(0).getValueType().isInteger()) {
7332 SDValue Int = N0.getOperand(0);
7333 EVT IntVT = Int.getValueType();
7334 if (IntVT.isInteger() && !IntVT.isVector()) {
7335 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7336 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7337 AddToWorklist(Int.getNode());
7338 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7343 // (fneg (fmul c, x)) -> (fmul -c, x)
7344 if (N0.getOpcode() == ISD::FMUL) {
7345 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7347 APFloat CVal = CFP1->getValueAPF();
7349 if (Level >= AfterLegalizeDAG &&
7350 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7351 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7353 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7354 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7361 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7362 SDValue N0 = N->getOperand(0);
7363 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7364 EVT VT = N->getValueType(0);
7366 // fold (fceil c1) -> fceil(c1)
7368 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7373 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7374 SDValue N0 = N->getOperand(0);
7375 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7376 EVT VT = N->getValueType(0);
7378 // fold (ftrunc c1) -> ftrunc(c1)
7380 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7385 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7386 SDValue N0 = N->getOperand(0);
7387 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7388 EVT VT = N->getValueType(0);
7390 // fold (ffloor c1) -> ffloor(c1)
7392 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7397 SDValue DAGCombiner::visitFABS(SDNode *N) {
7398 SDValue N0 = N->getOperand(0);
7399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7400 EVT VT = N->getValueType(0);
7402 if (VT.isVector()) {
7403 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7404 if (FoldedVOp.getNode()) return FoldedVOp;
7407 // fold (fabs c1) -> fabs(c1)
7409 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7410 // fold (fabs (fabs x)) -> (fabs x)
7411 if (N0.getOpcode() == ISD::FABS)
7412 return N->getOperand(0);
7413 // fold (fabs (fneg x)) -> (fabs x)
7414 // fold (fabs (fcopysign x, y)) -> (fabs x)
7415 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7416 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7418 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7419 // constant pool values.
7420 if (!TLI.isFAbsFree(VT) &&
7421 N0.getOpcode() == ISD::BITCAST &&
7422 N0.getNode()->hasOneUse()) {
7423 SDValue Int = N0.getOperand(0);
7424 EVT IntVT = Int.getValueType();
7425 if (IntVT.isInteger() && !IntVT.isVector()) {
7427 if (N0.getValueType().isVector()) {
7428 // For a vector, get a mask such as 0x7f... per scalar element
7430 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7431 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7433 // For a scalar, just generate 0x7f...
7434 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7436 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7437 DAG.getConstant(SignMask, IntVT));
7438 AddToWorklist(Int.getNode());
7439 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7446 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7447 SDValue Chain = N->getOperand(0);
7448 SDValue N1 = N->getOperand(1);
7449 SDValue N2 = N->getOperand(2);
7451 // If N is a constant we could fold this into a fallthrough or unconditional
7452 // branch. However that doesn't happen very often in normal code, because
7453 // Instcombine/SimplifyCFG should have handled the available opportunities.
7454 // If we did this folding here, it would be necessary to update the
7455 // MachineBasicBlock CFG, which is awkward.
7457 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7459 if (N1.getOpcode() == ISD::SETCC &&
7460 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7461 N1.getOperand(0).getValueType())) {
7462 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7463 Chain, N1.getOperand(2),
7464 N1.getOperand(0), N1.getOperand(1), N2);
7467 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7468 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7469 (N1.getOperand(0).hasOneUse() &&
7470 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7471 SDNode *Trunc = nullptr;
7472 if (N1.getOpcode() == ISD::TRUNCATE) {
7473 // Look pass the truncate.
7474 Trunc = N1.getNode();
7475 N1 = N1.getOperand(0);
7478 // Match this pattern so that we can generate simpler code:
7481 // %b = and i32 %a, 2
7482 // %c = srl i32 %b, 1
7483 // brcond i32 %c ...
7488 // %b = and i32 %a, 2
7489 // %c = setcc eq %b, 0
7492 // This applies only when the AND constant value has one bit set and the
7493 // SRL constant is equal to the log2 of the AND constant. The back-end is
7494 // smart enough to convert the result into a TEST/JMP sequence.
7495 SDValue Op0 = N1.getOperand(0);
7496 SDValue Op1 = N1.getOperand(1);
7498 if (Op0.getOpcode() == ISD::AND &&
7499 Op1.getOpcode() == ISD::Constant) {
7500 SDValue AndOp1 = Op0.getOperand(1);
7502 if (AndOp1.getOpcode() == ISD::Constant) {
7503 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7505 if (AndConst.isPowerOf2() &&
7506 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7508 DAG.getSetCC(SDLoc(N),
7509 getSetCCResultType(Op0.getValueType()),
7510 Op0, DAG.getConstant(0, Op0.getValueType()),
7513 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7514 MVT::Other, Chain, SetCC, N2);
7515 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7516 // will convert it back to (X & C1) >> C2.
7517 CombineTo(N, NewBRCond, false);
7518 // Truncate is dead.
7520 deleteAndRecombine(Trunc);
7521 // Replace the uses of SRL with SETCC
7522 WorklistRemover DeadNodes(*this);
7523 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7524 deleteAndRecombine(N1.getNode());
7525 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7531 // Restore N1 if the above transformation doesn't match.
7532 N1 = N->getOperand(1);
7535 // Transform br(xor(x, y)) -> br(x != y)
7536 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7537 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7538 SDNode *TheXor = N1.getNode();
7539 SDValue Op0 = TheXor->getOperand(0);
7540 SDValue Op1 = TheXor->getOperand(1);
7541 if (Op0.getOpcode() == Op1.getOpcode()) {
7542 // Avoid missing important xor optimizations.
7543 SDValue Tmp = visitXOR(TheXor);
7544 if (Tmp.getNode()) {
7545 if (Tmp.getNode() != TheXor) {
7546 DEBUG(dbgs() << "\nReplacing.8 ";
7548 dbgs() << "\nWith: ";
7549 Tmp.getNode()->dump(&DAG);
7551 WorklistRemover DeadNodes(*this);
7552 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7553 deleteAndRecombine(TheXor);
7554 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7555 MVT::Other, Chain, Tmp, N2);
7558 // visitXOR has changed XOR's operands or replaced the XOR completely,
7560 return SDValue(N, 0);
7564 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7566 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7567 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7568 Op0.getOpcode() == ISD::XOR) {
7569 TheXor = Op0.getNode();
7573 EVT SetCCVT = N1.getValueType();
7575 SetCCVT = getSetCCResultType(SetCCVT);
7576 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7579 Equal ? ISD::SETEQ : ISD::SETNE);
7580 // Replace the uses of XOR with SETCC
7581 WorklistRemover DeadNodes(*this);
7582 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7583 deleteAndRecombine(N1.getNode());
7584 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7585 MVT::Other, Chain, SetCC, N2);
7592 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7594 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7595 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7596 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7598 // If N is a constant we could fold this into a fallthrough or unconditional
7599 // branch. However that doesn't happen very often in normal code, because
7600 // Instcombine/SimplifyCFG should have handled the available opportunities.
7601 // If we did this folding here, it would be necessary to update the
7602 // MachineBasicBlock CFG, which is awkward.
7604 // Use SimplifySetCC to simplify SETCC's.
7605 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7606 CondLHS, CondRHS, CC->get(), SDLoc(N),
7608 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7610 // fold to a simpler setcc
7611 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7612 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7613 N->getOperand(0), Simp.getOperand(2),
7614 Simp.getOperand(0), Simp.getOperand(1),
7620 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7621 /// uses N as its base pointer and that N may be folded in the load / store
7622 /// addressing mode.
7623 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7625 const TargetLowering &TLI) {
7627 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7628 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7630 VT = Use->getValueType(0);
7631 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7632 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7634 VT = ST->getValue().getValueType();
7638 TargetLowering::AddrMode AM;
7639 if (N->getOpcode() == ISD::ADD) {
7640 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7643 AM.BaseOffs = Offset->getSExtValue();
7647 } else if (N->getOpcode() == ISD::SUB) {
7648 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7651 AM.BaseOffs = -Offset->getSExtValue();
7658 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7661 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7662 /// pre-indexed load / store when the base pointer is an add or subtract
7663 /// and it has other uses besides the load / store. After the
7664 /// transformation, the new indexed load / store has effectively folded
7665 /// the add / subtract in and all of its other uses are redirected to the
7666 /// new load / store.
7667 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7668 if (Level < AfterLegalizeDAG)
7674 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7675 if (LD->isIndexed())
7677 VT = LD->getMemoryVT();
7678 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7679 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7681 Ptr = LD->getBasePtr();
7682 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7683 if (ST->isIndexed())
7685 VT = ST->getMemoryVT();
7686 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7687 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7689 Ptr = ST->getBasePtr();
7695 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7696 // out. There is no reason to make this a preinc/predec.
7697 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7698 Ptr.getNode()->hasOneUse())
7701 // Ask the target to do addressing mode selection.
7704 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7705 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7708 // Backends without true r+i pre-indexed forms may need to pass a
7709 // constant base with a variable offset so that constant coercion
7710 // will work with the patterns in canonical form.
7711 bool Swapped = false;
7712 if (isa<ConstantSDNode>(BasePtr)) {
7713 std::swap(BasePtr, Offset);
7717 // Don't create a indexed load / store with zero offset.
7718 if (isa<ConstantSDNode>(Offset) &&
7719 cast<ConstantSDNode>(Offset)->isNullValue())
7722 // Try turning it into a pre-indexed load / store except when:
7723 // 1) The new base ptr is a frame index.
7724 // 2) If N is a store and the new base ptr is either the same as or is a
7725 // predecessor of the value being stored.
7726 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7727 // that would create a cycle.
7728 // 4) All uses are load / store ops that use it as old base ptr.
7730 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7731 // (plus the implicit offset) to a register to preinc anyway.
7732 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7737 SDValue Val = cast<StoreSDNode>(N)->getValue();
7738 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7742 // If the offset is a constant, there may be other adds of constants that
7743 // can be folded with this one. We should do this to avoid having to keep
7744 // a copy of the original base pointer.
7745 SmallVector<SDNode *, 16> OtherUses;
7746 if (isa<ConstantSDNode>(Offset))
7747 for (SDNode *Use : BasePtr.getNode()->uses()) {
7748 if (Use == Ptr.getNode())
7751 if (Use->isPredecessorOf(N))
7754 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7759 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7760 if (Op1.getNode() == BasePtr.getNode())
7761 std::swap(Op0, Op1);
7762 assert(Op0.getNode() == BasePtr.getNode() &&
7763 "Use of ADD/SUB but not an operand");
7765 if (!isa<ConstantSDNode>(Op1)) {
7770 // FIXME: In some cases, we can be smarter about this.
7771 if (Op1.getValueType() != Offset.getValueType()) {
7776 OtherUses.push_back(Use);
7780 std::swap(BasePtr, Offset);
7782 // Now check for #3 and #4.
7783 bool RealUse = false;
7785 // Caches for hasPredecessorHelper
7786 SmallPtrSet<const SDNode *, 32> Visited;
7787 SmallVector<const SDNode *, 16> Worklist;
7789 for (SDNode *Use : Ptr.getNode()->uses()) {
7792 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7795 // If Ptr may be folded in addressing mode of other use, then it's
7796 // not profitable to do this transformation.
7797 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7806 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7807 BasePtr, Offset, AM);
7809 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7810 BasePtr, Offset, AM);
7813 DEBUG(dbgs() << "\nReplacing.4 ";
7815 dbgs() << "\nWith: ";
7816 Result.getNode()->dump(&DAG);
7818 WorklistRemover DeadNodes(*this);
7820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7821 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7823 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7826 // Finally, since the node is now dead, remove it from the graph.
7827 deleteAndRecombine(N);
7830 std::swap(BasePtr, Offset);
7832 // Replace other uses of BasePtr that can be updated to use Ptr
7833 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7834 unsigned OffsetIdx = 1;
7835 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7837 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7838 BasePtr.getNode() && "Expected BasePtr operand");
7840 // We need to replace ptr0 in the following expression:
7841 // x0 * offset0 + y0 * ptr0 = t0
7843 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7845 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7846 // indexed load/store and the expresion that needs to be re-written.
7848 // Therefore, we have:
7849 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7851 ConstantSDNode *CN =
7852 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7854 APInt Offset0 = CN->getAPIntValue();
7855 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7857 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7858 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7859 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7860 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7862 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7864 APInt CNV = Offset0;
7865 if (X0 < 0) CNV = -CNV;
7866 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7867 else CNV = CNV - Offset1;
7869 // We can now generate the new expression.
7870 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7871 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7873 SDValue NewUse = DAG.getNode(Opcode,
7874 SDLoc(OtherUses[i]),
7875 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7876 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7877 deleteAndRecombine(OtherUses[i]);
7880 // Replace the uses of Ptr with uses of the updated base value.
7881 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7882 deleteAndRecombine(Ptr.getNode());
7887 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7888 /// add / sub of the base pointer node into a post-indexed load / store.
7889 /// The transformation folded the add / subtract into the new indexed
7890 /// load / store effectively and all of its uses are redirected to the
7891 /// new load / store.
7892 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7893 if (Level < AfterLegalizeDAG)
7899 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7900 if (LD->isIndexed())
7902 VT = LD->getMemoryVT();
7903 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7904 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7906 Ptr = LD->getBasePtr();
7907 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7908 if (ST->isIndexed())
7910 VT = ST->getMemoryVT();
7911 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7912 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7914 Ptr = ST->getBasePtr();
7920 if (Ptr.getNode()->hasOneUse())
7923 for (SDNode *Op : Ptr.getNode()->uses()) {
7925 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7930 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7931 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7932 // Don't create a indexed load / store with zero offset.
7933 if (isa<ConstantSDNode>(Offset) &&
7934 cast<ConstantSDNode>(Offset)->isNullValue())
7937 // Try turning it into a post-indexed load / store except when
7938 // 1) All uses are load / store ops that use it as base ptr (and
7939 // it may be folded as addressing mmode).
7940 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7941 // nor a successor of N. Otherwise, if Op is folded that would
7944 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7948 bool TryNext = false;
7949 for (SDNode *Use : BasePtr.getNode()->uses()) {
7950 if (Use == Ptr.getNode())
7953 // If all the uses are load / store addresses, then don't do the
7955 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7956 bool RealUse = false;
7957 for (SDNode *UseUse : Use->uses()) {
7958 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7973 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7974 SDValue Result = isLoad
7975 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7976 BasePtr, Offset, AM)
7977 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7978 BasePtr, Offset, AM);
7981 DEBUG(dbgs() << "\nReplacing.5 ";
7983 dbgs() << "\nWith: ";
7984 Result.getNode()->dump(&DAG);
7986 WorklistRemover DeadNodes(*this);
7988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7989 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7991 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7994 // Finally, since the node is now dead, remove it from the graph.
7995 deleteAndRecombine(N);
7997 // Replace the uses of Use with uses of the updated base value.
7998 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7999 Result.getValue(isLoad ? 1 : 0));
8000 deleteAndRecombine(Op);
8009 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8010 LoadSDNode *LD = cast<LoadSDNode>(N);
8011 SDValue Chain = LD->getChain();
8012 SDValue Ptr = LD->getBasePtr();
8014 // If load is not volatile and there are no uses of the loaded value (and
8015 // the updated indexed value in case of indexed loads), change uses of the
8016 // chain value into uses of the chain input (i.e. delete the dead load).
8017 if (!LD->isVolatile()) {
8018 if (N->getValueType(1) == MVT::Other) {
8020 if (!N->hasAnyUseOfValue(0)) {
8021 // It's not safe to use the two value CombineTo variant here. e.g.
8022 // v1, chain2 = load chain1, loc
8023 // v2, chain3 = load chain2, loc
8025 // Now we replace use of chain2 with chain1. This makes the second load
8026 // isomorphic to the one we are deleting, and thus makes this load live.
8027 DEBUG(dbgs() << "\nReplacing.6 ";
8029 dbgs() << "\nWith chain: ";
8030 Chain.getNode()->dump(&DAG);
8032 WorklistRemover DeadNodes(*this);
8033 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8036 deleteAndRecombine(N);
8038 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8042 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8043 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8044 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8045 DEBUG(dbgs() << "\nReplacing.7 ";
8047 dbgs() << "\nWith: ";
8048 Undef.getNode()->dump(&DAG);
8049 dbgs() << " and 2 other values\n");
8050 WorklistRemover DeadNodes(*this);
8051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8053 DAG.getUNDEF(N->getValueType(1)));
8054 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8055 deleteAndRecombine(N);
8056 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8061 // If this load is directly stored, replace the load value with the stored
8063 // TODO: Handle store large -> read small portion.
8064 // TODO: Handle TRUNCSTORE/LOADEXT
8065 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8066 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8067 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8068 if (PrevST->getBasePtr() == Ptr &&
8069 PrevST->getValue().getValueType() == N->getValueType(0))
8070 return CombineTo(N, Chain.getOperand(1), Chain);
8074 // Try to infer better alignment information than the load already has.
8075 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8076 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8077 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8079 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8080 LD->getValueType(0),
8081 Chain, Ptr, LD->getPointerInfo(),
8083 LD->isVolatile(), LD->isNonTemporal(),
8084 LD->isInvariant(), Align, LD->getAAInfo());
8085 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8090 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8091 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8093 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8094 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8097 if (UseAA && LD->isUnindexed()) {
8098 // Walk up chain skipping non-aliasing memory nodes.
8099 SDValue BetterChain = FindBetterChain(N, Chain);
8101 // If there is a better chain.
8102 if (Chain != BetterChain) {
8105 // Replace the chain to void dependency.
8106 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8107 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8108 BetterChain, Ptr, LD->getMemOperand());
8110 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8111 LD->getValueType(0),
8112 BetterChain, Ptr, LD->getMemoryVT(),
8113 LD->getMemOperand());
8116 // Create token factor to keep old chain connected.
8117 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8118 MVT::Other, Chain, ReplLoad.getValue(1));
8120 // Make sure the new and old chains are cleaned up.
8121 AddToWorklist(Token.getNode());
8123 // Replace uses with load result and token factor. Don't add users
8125 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8129 // Try transforming N to an indexed load.
8130 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8131 return SDValue(N, 0);
8133 // Try to slice up N to more direct loads if the slices are mapped to
8134 // different register banks or pairing can take place.
8136 return SDValue(N, 0);
8142 /// \brief Helper structure used to slice a load in smaller loads.
8143 /// Basically a slice is obtained from the following sequence:
8144 /// Origin = load Ty1, Base
8145 /// Shift = srl Ty1 Origin, CstTy Amount
8146 /// Inst = trunc Shift to Ty2
8148 /// Then, it will be rewriten into:
8149 /// Slice = load SliceTy, Base + SliceOffset
8150 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8152 /// SliceTy is deduced from the number of bits that are actually used to
8154 struct LoadedSlice {
8155 /// \brief Helper structure used to compute the cost of a slice.
8157 /// Are we optimizing for code size.
8162 unsigned CrossRegisterBanksCopies;
8166 Cost(bool ForCodeSize = false)
8167 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8168 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8170 /// \brief Get the cost of one isolated slice.
8171 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8172 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8173 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8174 EVT TruncType = LS.Inst->getValueType(0);
8175 EVT LoadedType = LS.getLoadedType();
8176 if (TruncType != LoadedType &&
8177 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8181 /// \brief Account for slicing gain in the current cost.
8182 /// Slicing provide a few gains like removing a shift or a
8183 /// truncate. This method allows to grow the cost of the original
8184 /// load with the gain from this slice.
8185 void addSliceGain(const LoadedSlice &LS) {
8186 // Each slice saves a truncate.
8187 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8188 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8189 LS.Inst->getOperand(0).getValueType()))
8191 // If there is a shift amount, this slice gets rid of it.
8194 // If this slice can merge a cross register bank copy, account for it.
8195 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8196 ++CrossRegisterBanksCopies;
8199 Cost &operator+=(const Cost &RHS) {
8201 Truncates += RHS.Truncates;
8202 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8208 bool operator==(const Cost &RHS) const {
8209 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8210 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8211 ZExts == RHS.ZExts && Shift == RHS.Shift;
8214 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8216 bool operator<(const Cost &RHS) const {
8217 // Assume cross register banks copies are as expensive as loads.
8218 // FIXME: Do we want some more target hooks?
8219 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8220 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8221 // Unless we are optimizing for code size, consider the
8222 // expensive operation first.
8223 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8224 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8225 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8226 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8229 bool operator>(const Cost &RHS) const { return RHS < *this; }
8231 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8233 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8235 // The last instruction that represent the slice. This should be a
8236 // truncate instruction.
8238 // The original load instruction.
8240 // The right shift amount in bits from the original load.
8242 // The DAG from which Origin came from.
8243 // This is used to get some contextual information about legal types, etc.
8246 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8247 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8248 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8250 LoadedSlice(const LoadedSlice &LS)
8251 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8253 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8254 /// \return Result is \p BitWidth and has used bits set to 1 and
8255 /// not used bits set to 0.
8256 APInt getUsedBits() const {
8257 // Reproduce the trunc(lshr) sequence:
8258 // - Start from the truncated value.
8259 // - Zero extend to the desired bit width.
8261 assert(Origin && "No original load to compare against.");
8262 unsigned BitWidth = Origin->getValueSizeInBits(0);
8263 assert(Inst && "This slice is not bound to an instruction");
8264 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8265 "Extracted slice is bigger than the whole type!");
8266 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8267 UsedBits.setAllBits();
8268 UsedBits = UsedBits.zext(BitWidth);
8273 /// \brief Get the size of the slice to be loaded in bytes.
8274 unsigned getLoadedSize() const {
8275 unsigned SliceSize = getUsedBits().countPopulation();
8276 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8277 return SliceSize / 8;
8280 /// \brief Get the type that will be loaded for this slice.
8281 /// Note: This may not be the final type for the slice.
8282 EVT getLoadedType() const {
8283 assert(DAG && "Missing context");
8284 LLVMContext &Ctxt = *DAG->getContext();
8285 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8288 /// \brief Get the alignment of the load used for this slice.
8289 unsigned getAlignment() const {
8290 unsigned Alignment = Origin->getAlignment();
8291 unsigned Offset = getOffsetFromBase();
8293 Alignment = MinAlign(Alignment, Alignment + Offset);
8297 /// \brief Check if this slice can be rewritten with legal operations.
8298 bool isLegal() const {
8299 // An invalid slice is not legal.
8300 if (!Origin || !Inst || !DAG)
8303 // Offsets are for indexed load only, we do not handle that.
8304 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8307 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8309 // Check that the type is legal.
8310 EVT SliceType = getLoadedType();
8311 if (!TLI.isTypeLegal(SliceType))
8314 // Check that the load is legal for this type.
8315 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8318 // Check that the offset can be computed.
8319 // 1. Check its type.
8320 EVT PtrType = Origin->getBasePtr().getValueType();
8321 if (PtrType == MVT::Untyped || PtrType.isExtended())
8324 // 2. Check that it fits in the immediate.
8325 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8328 // 3. Check that the computation is legal.
8329 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8332 // Check that the zext is legal if it needs one.
8333 EVT TruncateType = Inst->getValueType(0);
8334 if (TruncateType != SliceType &&
8335 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8341 /// \brief Get the offset in bytes of this slice in the original chunk of
8343 /// \pre DAG != nullptr.
8344 uint64_t getOffsetFromBase() const {
8345 assert(DAG && "Missing context.");
8347 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8348 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8349 uint64_t Offset = Shift / 8;
8350 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8351 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8352 "The size of the original loaded type is not a multiple of a"
8354 // If Offset is bigger than TySizeInBytes, it means we are loading all
8355 // zeros. This should have been optimized before in the process.
8356 assert(TySizeInBytes > Offset &&
8357 "Invalid shift amount for given loaded size");
8359 Offset = TySizeInBytes - Offset - getLoadedSize();
8363 /// \brief Generate the sequence of instructions to load the slice
8364 /// represented by this object and redirect the uses of this slice to
8365 /// this new sequence of instructions.
8366 /// \pre this->Inst && this->Origin are valid Instructions and this
8367 /// object passed the legal check: LoadedSlice::isLegal returned true.
8368 /// \return The last instruction of the sequence used to load the slice.
8369 SDValue loadSlice() const {
8370 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8371 const SDValue &OldBaseAddr = Origin->getBasePtr();
8372 SDValue BaseAddr = OldBaseAddr;
8373 // Get the offset in that chunk of bytes w.r.t. the endianess.
8374 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8375 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8377 // BaseAddr = BaseAddr + Offset.
8378 EVT ArithType = BaseAddr.getValueType();
8379 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8380 DAG->getConstant(Offset, ArithType));
8383 // Create the type of the loaded slice according to its size.
8384 EVT SliceType = getLoadedType();
8386 // Create the load for the slice.
8387 SDValue LastInst = DAG->getLoad(
8388 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8389 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8390 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8391 // If the final type is not the same as the loaded type, this means that
8392 // we have to pad with zero. Create a zero extend for that.
8393 EVT FinalType = Inst->getValueType(0);
8394 if (SliceType != FinalType)
8396 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8400 /// \brief Check if this slice can be merged with an expensive cross register
8401 /// bank copy. E.g.,
8403 /// f = bitcast i32 i to float
8404 bool canMergeExpensiveCrossRegisterBankCopy() const {
8405 if (!Inst || !Inst->hasOneUse())
8407 SDNode *Use = *Inst->use_begin();
8408 if (Use->getOpcode() != ISD::BITCAST)
8410 assert(DAG && "Missing context");
8411 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8412 EVT ResVT = Use->getValueType(0);
8413 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8414 const TargetRegisterClass *ArgRC =
8415 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8416 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8419 // At this point, we know that we perform a cross-register-bank copy.
8420 // Check if it is expensive.
8421 const TargetRegisterInfo *TRI =
8422 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8423 // Assume bitcasts are cheap, unless both register classes do not
8424 // explicitly share a common sub class.
8425 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8428 // Check if it will be merged with the load.
8429 // 1. Check the alignment constraint.
8430 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8431 ResVT.getTypeForEVT(*DAG->getContext()));
8433 if (RequiredAlignment > getAlignment())
8436 // 2. Check that the load is a legal operation for that type.
8437 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8440 // 3. Check that we do not have a zext in the way.
8441 if (Inst->getValueType(0) != getLoadedType())
8449 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8450 /// \p UsedBits looks like 0..0 1..1 0..0.
8451 static bool areUsedBitsDense(const APInt &UsedBits) {
8452 // If all the bits are one, this is dense!
8453 if (UsedBits.isAllOnesValue())
8456 // Get rid of the unused bits on the right.
8457 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8458 // Get rid of the unused bits on the left.
8459 if (NarrowedUsedBits.countLeadingZeros())
8460 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8461 // Check that the chunk of bits is completely used.
8462 return NarrowedUsedBits.isAllOnesValue();
8465 /// \brief Check whether or not \p First and \p Second are next to each other
8466 /// in memory. This means that there is no hole between the bits loaded
8467 /// by \p First and the bits loaded by \p Second.
8468 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8469 const LoadedSlice &Second) {
8470 assert(First.Origin == Second.Origin && First.Origin &&
8471 "Unable to match different memory origins.");
8472 APInt UsedBits = First.getUsedBits();
8473 assert((UsedBits & Second.getUsedBits()) == 0 &&
8474 "Slices are not supposed to overlap.");
8475 UsedBits |= Second.getUsedBits();
8476 return areUsedBitsDense(UsedBits);
8479 /// \brief Adjust the \p GlobalLSCost according to the target
8480 /// paring capabilities and the layout of the slices.
8481 /// \pre \p GlobalLSCost should account for at least as many loads as
8482 /// there is in the slices in \p LoadedSlices.
8483 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8484 LoadedSlice::Cost &GlobalLSCost) {
8485 unsigned NumberOfSlices = LoadedSlices.size();
8486 // If there is less than 2 elements, no pairing is possible.
8487 if (NumberOfSlices < 2)
8490 // Sort the slices so that elements that are likely to be next to each
8491 // other in memory are next to each other in the list.
8492 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8493 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8494 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8495 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8497 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8498 // First (resp. Second) is the first (resp. Second) potentially candidate
8499 // to be placed in a paired load.
8500 const LoadedSlice *First = nullptr;
8501 const LoadedSlice *Second = nullptr;
8502 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8503 // Set the beginning of the pair.
8506 Second = &LoadedSlices[CurrSlice];
8508 // If First is NULL, it means we start a new pair.
8509 // Get to the next slice.
8513 EVT LoadedType = First->getLoadedType();
8515 // If the types of the slices are different, we cannot pair them.
8516 if (LoadedType != Second->getLoadedType())
8519 // Check if the target supplies paired loads for this type.
8520 unsigned RequiredAlignment = 0;
8521 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8522 // move to the next pair, this type is hopeless.
8526 // Check if we meet the alignment requirement.
8527 if (RequiredAlignment > First->getAlignment())
8530 // Check that both loads are next to each other in memory.
8531 if (!areSlicesNextToEachOther(*First, *Second))
8534 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8535 --GlobalLSCost.Loads;
8536 // Move to the next pair.
8541 /// \brief Check the profitability of all involved LoadedSlice.
8542 /// Currently, it is considered profitable if there is exactly two
8543 /// involved slices (1) which are (2) next to each other in memory, and
8544 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8546 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8547 /// the elements themselves.
8549 /// FIXME: When the cost model will be mature enough, we can relax
8550 /// constraints (1) and (2).
8551 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8552 const APInt &UsedBits, bool ForCodeSize) {
8553 unsigned NumberOfSlices = LoadedSlices.size();
8554 if (StressLoadSlicing)
8555 return NumberOfSlices > 1;
8558 if (NumberOfSlices != 2)
8562 if (!areUsedBitsDense(UsedBits))
8566 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8567 // The original code has one big load.
8569 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8570 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8571 // Accumulate the cost of all the slices.
8572 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8573 GlobalSlicingCost += SliceCost;
8575 // Account as cost in the original configuration the gain obtained
8576 // with the current slices.
8577 OrigCost.addSliceGain(LS);
8580 // If the target supports paired load, adjust the cost accordingly.
8581 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8582 return OrigCost > GlobalSlicingCost;
8585 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8586 /// operations, split it in the various pieces being extracted.
8588 /// This sort of thing is introduced by SROA.
8589 /// This slicing takes care not to insert overlapping loads.
8590 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8591 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8592 if (Level < AfterLegalizeDAG)
8595 LoadSDNode *LD = cast<LoadSDNode>(N);
8596 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8597 !LD->getValueType(0).isInteger())
8600 // Keep track of already used bits to detect overlapping values.
8601 // In that case, we will just abort the transformation.
8602 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8604 SmallVector<LoadedSlice, 4> LoadedSlices;
8606 // Check if this load is used as several smaller chunks of bits.
8607 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8608 // of computation for each trunc.
8609 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8610 UI != UIEnd; ++UI) {
8611 // Skip the uses of the chain.
8612 if (UI.getUse().getResNo() != 0)
8618 // Check if this is a trunc(lshr).
8619 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8620 isa<ConstantSDNode>(User->getOperand(1))) {
8621 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8622 User = *User->use_begin();
8625 // At this point, User is a Truncate, iff we encountered, trunc or
8627 if (User->getOpcode() != ISD::TRUNCATE)
8630 // The width of the type must be a power of 2 and greater than 8-bits.
8631 // Otherwise the load cannot be represented in LLVM IR.
8632 // Moreover, if we shifted with a non-8-bits multiple, the slice
8633 // will be across several bytes. We do not support that.
8634 unsigned Width = User->getValueSizeInBits(0);
8635 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8638 // Build the slice for this chain of computations.
8639 LoadedSlice LS(User, LD, Shift, &DAG);
8640 APInt CurrentUsedBits = LS.getUsedBits();
8642 // Check if this slice overlaps with another.
8643 if ((CurrentUsedBits & UsedBits) != 0)
8645 // Update the bits used globally.
8646 UsedBits |= CurrentUsedBits;
8648 // Check if the new slice would be legal.
8652 // Record the slice.
8653 LoadedSlices.push_back(LS);
8656 // Abort slicing if it does not seem to be profitable.
8657 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8662 // Rewrite each chain to use an independent load.
8663 // By construction, each chain can be represented by a unique load.
8665 // Prepare the argument for the new token factor for all the slices.
8666 SmallVector<SDValue, 8> ArgChains;
8667 for (SmallVectorImpl<LoadedSlice>::const_iterator
8668 LSIt = LoadedSlices.begin(),
8669 LSItEnd = LoadedSlices.end();
8670 LSIt != LSItEnd; ++LSIt) {
8671 SDValue SliceInst = LSIt->loadSlice();
8672 CombineTo(LSIt->Inst, SliceInst, true);
8673 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8674 SliceInst = SliceInst.getOperand(0);
8675 assert(SliceInst->getOpcode() == ISD::LOAD &&
8676 "It takes more than a zext to get to the loaded slice!!");
8677 ArgChains.push_back(SliceInst.getValue(1));
8680 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8682 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8686 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8687 /// load is having specific bytes cleared out. If so, return the byte size
8688 /// being masked out and the shift amount.
8689 static std::pair<unsigned, unsigned>
8690 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8691 std::pair<unsigned, unsigned> Result(0, 0);
8693 // Check for the structure we're looking for.
8694 if (V->getOpcode() != ISD::AND ||
8695 !isa<ConstantSDNode>(V->getOperand(1)) ||
8696 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8699 // Check the chain and pointer.
8700 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8701 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8703 // The store should be chained directly to the load or be an operand of a
8705 if (LD == Chain.getNode())
8707 else if (Chain->getOpcode() != ISD::TokenFactor)
8708 return Result; // Fail.
8711 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8712 if (Chain->getOperand(i).getNode() == LD) {
8716 if (!isOk) return Result;
8719 // This only handles simple types.
8720 if (V.getValueType() != MVT::i16 &&
8721 V.getValueType() != MVT::i32 &&
8722 V.getValueType() != MVT::i64)
8725 // Check the constant mask. Invert it so that the bits being masked out are
8726 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8727 // follow the sign bit for uniformity.
8728 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8729 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8730 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8731 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8732 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8733 if (NotMaskLZ == 64) return Result; // All zero mask.
8735 // See if we have a continuous run of bits. If so, we have 0*1+0*
8736 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8739 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8740 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8741 NotMaskLZ -= 64-V.getValueSizeInBits();
8743 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8744 switch (MaskedBytes) {
8748 default: return Result; // All one mask, or 5-byte mask.
8751 // Verify that the first bit starts at a multiple of mask so that the access
8752 // is aligned the same as the access width.
8753 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8755 Result.first = MaskedBytes;
8756 Result.second = NotMaskTZ/8;
8761 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8762 /// provides a value as specified by MaskInfo. If so, replace the specified
8763 /// store with a narrower store of truncated IVal.
8765 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8766 SDValue IVal, StoreSDNode *St,
8768 unsigned NumBytes = MaskInfo.first;
8769 unsigned ByteShift = MaskInfo.second;
8770 SelectionDAG &DAG = DC->getDAG();
8772 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8773 // that uses this. If not, this is not a replacement.
8774 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8775 ByteShift*8, (ByteShift+NumBytes)*8);
8776 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8778 // Check that it is legal on the target to do this. It is legal if the new
8779 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8781 MVT VT = MVT::getIntegerVT(NumBytes*8);
8782 if (!DC->isTypeLegal(VT))
8785 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8786 // shifted by ByteShift and truncated down to NumBytes.
8788 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8789 DAG.getConstant(ByteShift*8,
8790 DC->getShiftAmountTy(IVal.getValueType())));
8792 // Figure out the offset for the store and the alignment of the access.
8794 unsigned NewAlign = St->getAlignment();
8796 if (DAG.getTargetLoweringInfo().isLittleEndian())
8797 StOffset = ByteShift;
8799 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8801 SDValue Ptr = St->getBasePtr();
8803 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8804 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8805 NewAlign = MinAlign(NewAlign, StOffset);
8808 // Truncate down to the new size.
8809 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8812 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8813 St->getPointerInfo().getWithOffset(StOffset),
8814 false, false, NewAlign).getNode();
8818 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8819 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8820 /// of the loaded bits, try narrowing the load and store if it would end up
8821 /// being a win for performance or code size.
8822 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8823 StoreSDNode *ST = cast<StoreSDNode>(N);
8824 if (ST->isVolatile())
8827 SDValue Chain = ST->getChain();
8828 SDValue Value = ST->getValue();
8829 SDValue Ptr = ST->getBasePtr();
8830 EVT VT = Value.getValueType();
8832 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8835 unsigned Opc = Value.getOpcode();
8837 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8838 // is a byte mask indicating a consecutive number of bytes, check to see if
8839 // Y is known to provide just those bytes. If so, we try to replace the
8840 // load + replace + store sequence with a single (narrower) store, which makes
8842 if (Opc == ISD::OR) {
8843 std::pair<unsigned, unsigned> MaskedLoad;
8844 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8845 if (MaskedLoad.first)
8846 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8847 Value.getOperand(1), ST,this))
8848 return SDValue(NewST, 0);
8850 // Or is commutative, so try swapping X and Y.
8851 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8852 if (MaskedLoad.first)
8853 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8854 Value.getOperand(0), ST,this))
8855 return SDValue(NewST, 0);
8858 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8859 Value.getOperand(1).getOpcode() != ISD::Constant)
8862 SDValue N0 = Value.getOperand(0);
8863 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8864 Chain == SDValue(N0.getNode(), 1)) {
8865 LoadSDNode *LD = cast<LoadSDNode>(N0);
8866 if (LD->getBasePtr() != Ptr ||
8867 LD->getPointerInfo().getAddrSpace() !=
8868 ST->getPointerInfo().getAddrSpace())
8871 // Find the type to narrow it the load / op / store to.
8872 SDValue N1 = Value.getOperand(1);
8873 unsigned BitWidth = N1.getValueSizeInBits();
8874 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8875 if (Opc == ISD::AND)
8876 Imm ^= APInt::getAllOnesValue(BitWidth);
8877 if (Imm == 0 || Imm.isAllOnesValue())
8879 unsigned ShAmt = Imm.countTrailingZeros();
8880 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8881 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8882 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8883 while (NewBW < BitWidth &&
8884 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8885 TLI.isNarrowingProfitable(VT, NewVT))) {
8886 NewBW = NextPowerOf2(NewBW);
8887 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8889 if (NewBW >= BitWidth)
8892 // If the lsb changed does not start at the type bitwidth boundary,
8893 // start at the previous one.
8895 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8896 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8897 std::min(BitWidth, ShAmt + NewBW));
8898 if ((Imm & Mask) == Imm) {
8899 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8900 if (Opc == ISD::AND)
8901 NewImm ^= APInt::getAllOnesValue(NewBW);
8902 uint64_t PtrOff = ShAmt / 8;
8903 // For big endian targets, we need to adjust the offset to the pointer to
8904 // load the correct bytes.
8905 if (TLI.isBigEndian())
8906 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8908 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8909 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8910 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8913 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8914 Ptr.getValueType(), Ptr,
8915 DAG.getConstant(PtrOff, Ptr.getValueType()));
8916 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8917 LD->getChain(), NewPtr,
8918 LD->getPointerInfo().getWithOffset(PtrOff),
8919 LD->isVolatile(), LD->isNonTemporal(),
8920 LD->isInvariant(), NewAlign,
8922 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8923 DAG.getConstant(NewImm, NewVT));
8924 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8926 ST->getPointerInfo().getWithOffset(PtrOff),
8927 false, false, NewAlign);
8929 AddToWorklist(NewPtr.getNode());
8930 AddToWorklist(NewLD.getNode());
8931 AddToWorklist(NewVal.getNode());
8932 WorklistRemover DeadNodes(*this);
8933 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8942 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8943 /// if the load value isn't used by any other operations, then consider
8944 /// transforming the pair to integer load / store operations if the target
8945 /// deems the transformation profitable.
8946 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8947 StoreSDNode *ST = cast<StoreSDNode>(N);
8948 SDValue Chain = ST->getChain();
8949 SDValue Value = ST->getValue();
8950 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8951 Value.hasOneUse() &&
8952 Chain == SDValue(Value.getNode(), 1)) {
8953 LoadSDNode *LD = cast<LoadSDNode>(Value);
8954 EVT VT = LD->getMemoryVT();
8955 if (!VT.isFloatingPoint() ||
8956 VT != ST->getMemoryVT() ||
8957 LD->isNonTemporal() ||
8958 ST->isNonTemporal() ||
8959 LD->getPointerInfo().getAddrSpace() != 0 ||
8960 ST->getPointerInfo().getAddrSpace() != 0)
8963 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8964 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8965 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8966 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8967 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8970 unsigned LDAlign = LD->getAlignment();
8971 unsigned STAlign = ST->getAlignment();
8972 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8973 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8974 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8977 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8978 LD->getChain(), LD->getBasePtr(),
8979 LD->getPointerInfo(),
8980 false, false, false, LDAlign);
8982 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8983 NewLD, ST->getBasePtr(),
8984 ST->getPointerInfo(),
8985 false, false, STAlign);
8987 AddToWorklist(NewLD.getNode());
8988 AddToWorklist(NewST.getNode());
8989 WorklistRemover DeadNodes(*this);
8990 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8998 /// Helper struct to parse and store a memory address as base + index + offset.
8999 /// We ignore sign extensions when it is safe to do so.
9000 /// The following two expressions are not equivalent. To differentiate we need
9001 /// to store whether there was a sign extension involved in the index
9003 /// (load (i64 add (i64 copyfromreg %c)
9004 /// (i64 signextend (add (i8 load %index)
9008 /// (load (i64 add (i64 copyfromreg %c)
9009 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9011 struct BaseIndexOffset {
9015 bool IsIndexSignExt;
9017 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9019 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9020 bool IsIndexSignExt) :
9021 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9023 bool equalBaseIndex(const BaseIndexOffset &Other) {
9024 return Other.Base == Base && Other.Index == Index &&
9025 Other.IsIndexSignExt == IsIndexSignExt;
9028 /// Parses tree in Ptr for base, index, offset addresses.
9029 static BaseIndexOffset match(SDValue Ptr) {
9030 bool IsIndexSignExt = false;
9032 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9033 // instruction, then it could be just the BASE or everything else we don't
9034 // know how to handle. Just use Ptr as BASE and give up.
9035 if (Ptr->getOpcode() != ISD::ADD)
9036 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9038 // We know that we have at least an ADD instruction. Try to pattern match
9039 // the simple case of BASE + OFFSET.
9040 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9041 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9042 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9046 // Inside a loop the current BASE pointer is calculated using an ADD and a
9047 // MUL instruction. In this case Ptr is the actual BASE pointer.
9048 // (i64 add (i64 %array_ptr)
9049 // (i64 mul (i64 %induction_var)
9050 // (i64 %element_size)))
9051 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9052 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9054 // Look at Base + Index + Offset cases.
9055 SDValue Base = Ptr->getOperand(0);
9056 SDValue IndexOffset = Ptr->getOperand(1);
9058 // Skip signextends.
9059 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9060 IndexOffset = IndexOffset->getOperand(0);
9061 IsIndexSignExt = true;
9064 // Either the case of Base + Index (no offset) or something else.
9065 if (IndexOffset->getOpcode() != ISD::ADD)
9066 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9068 // Now we have the case of Base + Index + offset.
9069 SDValue Index = IndexOffset->getOperand(0);
9070 SDValue Offset = IndexOffset->getOperand(1);
9072 if (!isa<ConstantSDNode>(Offset))
9073 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9075 // Ignore signextends.
9076 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9077 Index = Index->getOperand(0);
9078 IsIndexSignExt = true;
9079 } else IsIndexSignExt = false;
9081 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9082 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9086 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9087 /// is located in a sequence of memory operations connected by a chain.
9089 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9090 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9091 // Ptr to the mem node.
9092 LSBaseSDNode *MemNode;
9093 // Offset from the base ptr.
9094 int64_t OffsetFromBase;
9095 // What is the sequence number of this mem node.
9096 // Lowest mem operand in the DAG starts at zero.
9097 unsigned SequenceNum;
9100 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9101 EVT MemVT = St->getMemoryVT();
9102 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9103 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9104 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9106 // Don't merge vectors into wider inputs.
9107 if (MemVT.isVector() || !MemVT.isSimple())
9110 // Perform an early exit check. Do not bother looking at stored values that
9111 // are not constants or loads.
9112 SDValue StoredVal = St->getValue();
9113 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9114 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9118 // Only look at ends of store sequences.
9119 SDValue Chain = SDValue(St, 0);
9120 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9123 // This holds the base pointer, index, and the offset in bytes from the base
9125 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9127 // We must have a base and an offset.
9128 if (!BasePtr.Base.getNode())
9131 // Do not handle stores to undef base pointers.
9132 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9135 // Save the LoadSDNodes that we find in the chain.
9136 // We need to make sure that these nodes do not interfere with
9137 // any of the store nodes.
9138 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9140 // Save the StoreSDNodes that we find in the chain.
9141 SmallVector<MemOpLink, 8> StoreNodes;
9143 // Walk up the chain and look for nodes with offsets from the same
9144 // base pointer. Stop when reaching an instruction with a different kind
9145 // or instruction which has a different base pointer.
9147 StoreSDNode *Index = St;
9149 // If the chain has more than one use, then we can't reorder the mem ops.
9150 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9153 // Find the base pointer and offset for this memory node.
9154 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9156 // Check that the base pointer is the same as the original one.
9157 if (!Ptr.equalBaseIndex(BasePtr))
9160 // Check that the alignment is the same.
9161 if (Index->getAlignment() != St->getAlignment())
9164 // The memory operands must not be volatile.
9165 if (Index->isVolatile() || Index->isIndexed())
9169 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9170 if (St->isTruncatingStore())
9173 // The stored memory type must be the same.
9174 if (Index->getMemoryVT() != MemVT)
9177 // We do not allow unaligned stores because we want to prevent overriding
9179 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9182 // We found a potential memory operand to merge.
9183 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9185 // Find the next memory operand in the chain. If the next operand in the
9186 // chain is a store then move up and continue the scan with the next
9187 // memory operand. If the next operand is a load save it and use alias
9188 // information to check if it interferes with anything.
9189 SDNode *NextInChain = Index->getChain().getNode();
9191 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9192 // We found a store node. Use it for the next iteration.
9195 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9196 if (Ldn->isVolatile()) {
9201 // Save the load node for later. Continue the scan.
9202 AliasLoadNodes.push_back(Ldn);
9203 NextInChain = Ldn->getChain().getNode();
9212 // Check if there is anything to merge.
9213 if (StoreNodes.size() < 2)
9216 // Sort the memory operands according to their distance from the base pointer.
9217 std::sort(StoreNodes.begin(), StoreNodes.end(),
9218 [](MemOpLink LHS, MemOpLink RHS) {
9219 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9220 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9221 LHS.SequenceNum > RHS.SequenceNum);
9224 // Scan the memory operations on the chain and find the first non-consecutive
9225 // store memory address.
9226 unsigned LastConsecutiveStore = 0;
9227 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9228 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9230 // Check that the addresses are consecutive starting from the second
9231 // element in the list of stores.
9233 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9234 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9239 // Check if this store interferes with any of the loads that we found.
9240 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9241 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9245 // We found a load that alias with this store. Stop the sequence.
9249 // Mark this node as useful.
9250 LastConsecutiveStore = i;
9253 // The node with the lowest store address.
9254 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9256 // Store the constants into memory as one consecutive store.
9258 unsigned LastLegalType = 0;
9259 unsigned LastLegalVectorType = 0;
9260 bool NonZero = false;
9261 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9262 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9263 SDValue StoredVal = St->getValue();
9265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9266 NonZero |= !C->isNullValue();
9267 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9268 NonZero |= !C->getConstantFPValue()->isNullValue();
9274 // Find a legal type for the constant store.
9275 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9276 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9277 if (TLI.isTypeLegal(StoreTy))
9278 LastLegalType = i+1;
9279 // Or check whether a truncstore is legal.
9280 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9281 TargetLowering::TypePromoteInteger) {
9282 EVT LegalizedStoredValueTy =
9283 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9284 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9285 LastLegalType = i+1;
9288 // Find a legal type for the vector store.
9289 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9290 if (TLI.isTypeLegal(Ty))
9291 LastLegalVectorType = i + 1;
9294 // We only use vectors if the constant is known to be zero and the
9295 // function is not marked with the noimplicitfloat attribute.
9296 if (NonZero || NoVectors)
9297 LastLegalVectorType = 0;
9299 // Check if we found a legal integer type to store.
9300 if (LastLegalType == 0 && LastLegalVectorType == 0)
9303 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9304 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9306 // Make sure we have something to merge.
9310 unsigned EarliestNodeUsed = 0;
9311 for (unsigned i=0; i < NumElem; ++i) {
9312 // Find a chain for the new wide-store operand. Notice that some
9313 // of the store nodes that we found may not be selected for inclusion
9314 // in the wide store. The chain we use needs to be the chain of the
9315 // earliest store node which is *used* and replaced by the wide store.
9316 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9317 EarliestNodeUsed = i;
9320 // The earliest Node in the DAG.
9321 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9322 SDLoc DL(StoreNodes[0].MemNode);
9326 // Find a legal type for the vector store.
9327 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9328 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9329 StoredVal = DAG.getConstant(0, Ty);
9331 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9332 APInt StoreInt(StoreBW, 0);
9334 // Construct a single integer constant which is made of the smaller
9336 bool IsLE = TLI.isLittleEndian();
9337 for (unsigned i = 0; i < NumElem ; ++i) {
9338 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9339 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9340 SDValue Val = St->getValue();
9341 StoreInt<<=ElementSizeBytes*8;
9342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9343 StoreInt|=C->getAPIntValue().zext(StoreBW);
9344 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9345 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9347 assert(false && "Invalid constant element type");
9351 // Create the new Load and Store operations.
9352 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9353 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9356 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9357 FirstInChain->getBasePtr(),
9358 FirstInChain->getPointerInfo(),
9360 FirstInChain->getAlignment());
9362 // Replace the first store with the new store
9363 CombineTo(EarliestOp, NewStore);
9364 // Erase all other stores.
9365 for (unsigned i = 0; i < NumElem ; ++i) {
9366 if (StoreNodes[i].MemNode == EarliestOp)
9368 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9369 // ReplaceAllUsesWith will replace all uses that existed when it was
9370 // called, but graph optimizations may cause new ones to appear. For
9371 // example, the case in pr14333 looks like
9373 // St's chain -> St -> another store -> X
9375 // And the only difference from St to the other store is the chain.
9376 // When we change it's chain to be St's chain they become identical,
9377 // get CSEed and the net result is that X is now a use of St.
9378 // Since we know that St is redundant, just iterate.
9379 while (!St->use_empty())
9380 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9381 deleteAndRecombine(St);
9387 // Below we handle the case of multiple consecutive stores that
9388 // come from multiple consecutive loads. We merge them into a single
9389 // wide load and a single wide store.
9391 // Look for load nodes which are used by the stored values.
9392 SmallVector<MemOpLink, 8> LoadNodes;
9394 // Find acceptable loads. Loads need to have the same chain (token factor),
9395 // must not be zext, volatile, indexed, and they must be consecutive.
9396 BaseIndexOffset LdBasePtr;
9397 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9398 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9399 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9402 // Loads must only have one use.
9403 if (!Ld->hasNUsesOfValue(1, 0))
9406 // Check that the alignment is the same as the stores.
9407 if (Ld->getAlignment() != St->getAlignment())
9410 // The memory operands must not be volatile.
9411 if (Ld->isVolatile() || Ld->isIndexed())
9414 // We do not accept ext loads.
9415 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9418 // The stored memory type must be the same.
9419 if (Ld->getMemoryVT() != MemVT)
9422 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9423 // If this is not the first ptr that we check.
9424 if (LdBasePtr.Base.getNode()) {
9425 // The base ptr must be the same.
9426 if (!LdPtr.equalBaseIndex(LdBasePtr))
9429 // Check that all other base pointers are the same as this one.
9433 // We found a potential memory operand to merge.
9434 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9437 if (LoadNodes.size() < 2)
9440 // If we have load/store pair instructions and we only have two values,
9442 unsigned RequiredAlignment;
9443 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9444 St->getAlignment() >= RequiredAlignment)
9447 // Scan the memory operations on the chain and find the first non-consecutive
9448 // load memory address. These variables hold the index in the store node
9450 unsigned LastConsecutiveLoad = 0;
9451 // This variable refers to the size and not index in the array.
9452 unsigned LastLegalVectorType = 0;
9453 unsigned LastLegalIntegerType = 0;
9454 StartAddress = LoadNodes[0].OffsetFromBase;
9455 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9456 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9457 // All loads much share the same chain.
9458 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9461 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9462 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9464 LastConsecutiveLoad = i;
9466 // Find a legal type for the vector store.
9467 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9468 if (TLI.isTypeLegal(StoreTy))
9469 LastLegalVectorType = i + 1;
9471 // Find a legal type for the integer store.
9472 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9473 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9474 if (TLI.isTypeLegal(StoreTy))
9475 LastLegalIntegerType = i + 1;
9476 // Or check whether a truncstore and extload is legal.
9477 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9478 TargetLowering::TypePromoteInteger) {
9479 EVT LegalizedStoredValueTy =
9480 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9481 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9482 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9483 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9484 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9485 LastLegalIntegerType = i+1;
9489 // Only use vector types if the vector type is larger than the integer type.
9490 // If they are the same, use integers.
9491 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9492 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9494 // We add +1 here because the LastXXX variables refer to location while
9495 // the NumElem refers to array/index size.
9496 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9497 NumElem = std::min(LastLegalType, NumElem);
9502 // The earliest Node in the DAG.
9503 unsigned EarliestNodeUsed = 0;
9504 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9505 for (unsigned i=1; i<NumElem; ++i) {
9506 // Find a chain for the new wide-store operand. Notice that some
9507 // of the store nodes that we found may not be selected for inclusion
9508 // in the wide store. The chain we use needs to be the chain of the
9509 // earliest store node which is *used* and replaced by the wide store.
9510 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9511 EarliestNodeUsed = i;
9514 // Find if it is better to use vectors or integers to load and store
9518 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9520 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9521 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9524 SDLoc LoadDL(LoadNodes[0].MemNode);
9525 SDLoc StoreDL(StoreNodes[0].MemNode);
9527 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9528 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9529 FirstLoad->getChain(),
9530 FirstLoad->getBasePtr(),
9531 FirstLoad->getPointerInfo(),
9532 false, false, false,
9533 FirstLoad->getAlignment());
9535 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9536 FirstInChain->getBasePtr(),
9537 FirstInChain->getPointerInfo(), false, false,
9538 FirstInChain->getAlignment());
9540 // Replace one of the loads with the new load.
9541 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9542 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9543 SDValue(NewLoad.getNode(), 1));
9545 // Remove the rest of the load chains.
9546 for (unsigned i = 1; i < NumElem ; ++i) {
9547 // Replace all chain users of the old load nodes with the chain of the new
9549 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9550 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9553 // Replace the first store with the new store.
9554 CombineTo(EarliestOp, NewStore);
9555 // Erase all other stores.
9556 for (unsigned i = 0; i < NumElem ; ++i) {
9557 // Remove all Store nodes.
9558 if (StoreNodes[i].MemNode == EarliestOp)
9560 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9561 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9562 deleteAndRecombine(St);
9568 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9569 StoreSDNode *ST = cast<StoreSDNode>(N);
9570 SDValue Chain = ST->getChain();
9571 SDValue Value = ST->getValue();
9572 SDValue Ptr = ST->getBasePtr();
9574 // If this is a store of a bit convert, store the input value if the
9575 // resultant store does not need a higher alignment than the original.
9576 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9577 ST->isUnindexed()) {
9578 unsigned OrigAlign = ST->getAlignment();
9579 EVT SVT = Value.getOperand(0).getValueType();
9580 unsigned Align = TLI.getDataLayout()->
9581 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9582 if (Align <= OrigAlign &&
9583 ((!LegalOperations && !ST->isVolatile()) ||
9584 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9585 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9586 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9587 ST->isNonTemporal(), OrigAlign,
9591 // Turn 'store undef, Ptr' -> nothing.
9592 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9595 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9596 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9597 // NOTE: If the original store is volatile, this transform must not increase
9598 // the number of stores. For example, on x86-32 an f64 can be stored in one
9599 // processor operation but an i64 (which is not legal) requires two. So the
9600 // transform should not be done in this case.
9601 if (Value.getOpcode() != ISD::TargetConstantFP) {
9603 switch (CFP->getSimpleValueType(0).SimpleTy) {
9604 default: llvm_unreachable("Unknown FP type");
9605 case MVT::f16: // We don't do this for these yet.
9611 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9612 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9613 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9614 bitcastToAPInt().getZExtValue(), MVT::i32);
9615 return DAG.getStore(Chain, SDLoc(N), Tmp,
9616 Ptr, ST->getMemOperand());
9620 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9621 !ST->isVolatile()) ||
9622 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9623 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9624 getZExtValue(), MVT::i64);
9625 return DAG.getStore(Chain, SDLoc(N), Tmp,
9626 Ptr, ST->getMemOperand());
9629 if (!ST->isVolatile() &&
9630 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9631 // Many FP stores are not made apparent until after legalize, e.g. for
9632 // argument passing. Since this is so common, custom legalize the
9633 // 64-bit integer store into two 32-bit stores.
9634 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9635 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9636 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9637 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9639 unsigned Alignment = ST->getAlignment();
9640 bool isVolatile = ST->isVolatile();
9641 bool isNonTemporal = ST->isNonTemporal();
9642 AAMDNodes AAInfo = ST->getAAInfo();
9644 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9645 Ptr, ST->getPointerInfo(),
9646 isVolatile, isNonTemporal,
9647 ST->getAlignment(), AAInfo);
9648 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9649 DAG.getConstant(4, Ptr.getValueType()));
9650 Alignment = MinAlign(Alignment, 4U);
9651 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9652 Ptr, ST->getPointerInfo().getWithOffset(4),
9653 isVolatile, isNonTemporal,
9655 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9664 // Try to infer better alignment information than the store already has.
9665 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9666 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9667 if (Align > ST->getAlignment())
9668 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9669 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9670 ST->isVolatile(), ST->isNonTemporal(), Align,
9675 // Try transforming a pair floating point load / store ops to integer
9676 // load / store ops.
9677 SDValue NewST = TransformFPLoadStorePair(N);
9678 if (NewST.getNode())
9681 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9682 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9684 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9685 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9688 if (UseAA && ST->isUnindexed()) {
9689 // Walk up chain skipping non-aliasing memory nodes.
9690 SDValue BetterChain = FindBetterChain(N, Chain);
9692 // If there is a better chain.
9693 if (Chain != BetterChain) {
9696 // Replace the chain to avoid dependency.
9697 if (ST->isTruncatingStore()) {
9698 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9699 ST->getMemoryVT(), ST->getMemOperand());
9701 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9702 ST->getMemOperand());
9705 // Create token to keep both nodes around.
9706 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9707 MVT::Other, Chain, ReplStore);
9709 // Make sure the new and old chains are cleaned up.
9710 AddToWorklist(Token.getNode());
9712 // Don't add users to work list.
9713 return CombineTo(N, Token, false);
9717 // Try transforming N to an indexed store.
9718 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9719 return SDValue(N, 0);
9721 // FIXME: is there such a thing as a truncating indexed store?
9722 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9723 Value.getValueType().isInteger()) {
9724 // See if we can simplify the input to this truncstore with knowledge that
9725 // only the low bits are being used. For example:
9726 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9728 GetDemandedBits(Value,
9729 APInt::getLowBitsSet(
9730 Value.getValueType().getScalarType().getSizeInBits(),
9731 ST->getMemoryVT().getScalarType().getSizeInBits()));
9732 AddToWorklist(Value.getNode());
9733 if (Shorter.getNode())
9734 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9735 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9737 // Otherwise, see if we can simplify the operation with
9738 // SimplifyDemandedBits, which only works if the value has a single use.
9739 if (SimplifyDemandedBits(Value,
9740 APInt::getLowBitsSet(
9741 Value.getValueType().getScalarType().getSizeInBits(),
9742 ST->getMemoryVT().getScalarType().getSizeInBits())))
9743 return SDValue(N, 0);
9746 // If this is a load followed by a store to the same location, then the store
9748 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9749 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9750 ST->isUnindexed() && !ST->isVolatile() &&
9751 // There can't be any side effects between the load and store, such as
9753 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9754 // The store is dead, remove it.
9759 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9760 // truncating store. We can do this even if this is already a truncstore.
9761 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9762 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9763 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9764 ST->getMemoryVT())) {
9765 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9766 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9769 // Only perform this optimization before the types are legal, because we
9770 // don't want to perform this optimization on every DAGCombine invocation.
9772 bool EverChanged = false;
9775 // There can be multiple store sequences on the same chain.
9776 // Keep trying to merge store sequences until we are unable to do so
9777 // or until we merge the last store on the chain.
9778 bool Changed = MergeConsecutiveStores(ST);
9779 EverChanged |= Changed;
9780 if (!Changed) break;
9781 } while (ST->getOpcode() != ISD::DELETED_NODE);
9784 return SDValue(N, 0);
9787 return ReduceLoadOpStoreWidth(N);
9790 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9791 SDValue InVec = N->getOperand(0);
9792 SDValue InVal = N->getOperand(1);
9793 SDValue EltNo = N->getOperand(2);
9796 // If the inserted element is an UNDEF, just use the input vector.
9797 if (InVal.getOpcode() == ISD::UNDEF)
9800 EVT VT = InVec.getValueType();
9802 // If we can't generate a legal BUILD_VECTOR, exit
9803 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9806 // Check that we know which element is being inserted
9807 if (!isa<ConstantSDNode>(EltNo))
9809 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9811 // Canonicalize insert_vector_elt dag nodes.
9813 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9814 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9816 // Do this only if the child insert_vector node has one use; also
9817 // do this only if indices are both constants and Idx1 < Idx0.
9818 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9819 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9821 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9822 if (Elt < OtherElt) {
9824 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9825 InVec.getOperand(0), InVal, EltNo);
9826 AddToWorklist(NewOp.getNode());
9827 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9828 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9832 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9833 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9835 SmallVector<SDValue, 8> Ops;
9836 // Do not combine these two vectors if the output vector will not replace
9837 // the input vector.
9838 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9839 Ops.append(InVec.getNode()->op_begin(),
9840 InVec.getNode()->op_end());
9841 } else if (InVec.getOpcode() == ISD::UNDEF) {
9842 unsigned NElts = VT.getVectorNumElements();
9843 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9848 // Insert the element
9849 if (Elt < Ops.size()) {
9850 // All the operands of BUILD_VECTOR must have the same type;
9851 // we enforce that here.
9852 EVT OpVT = Ops[0].getValueType();
9853 if (InVal.getValueType() != OpVT)
9854 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9855 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9856 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9860 // Return the new vector
9861 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9864 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9865 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9866 EVT ResultVT = EVE->getValueType(0);
9867 EVT VecEltVT = InVecVT.getVectorElementType();
9868 unsigned Align = OriginalLoad->getAlignment();
9869 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9870 VecEltVT.getTypeForEVT(*DAG.getContext()));
9872 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9877 SDValue NewPtr = OriginalLoad->getBasePtr();
9879 EVT PtrType = NewPtr.getValueType();
9880 MachinePointerInfo MPI;
9881 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9882 int Elt = ConstEltNo->getZExtValue();
9883 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9884 if (TLI.isBigEndian())
9885 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9886 Offset = DAG.getConstant(PtrOff, PtrType);
9887 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9889 Offset = DAG.getNode(
9890 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9891 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9892 if (TLI.isBigEndian())
9893 Offset = DAG.getNode(
9894 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9895 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9896 MPI = OriginalLoad->getPointerInfo();
9898 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9900 // The replacement we need to do here is a little tricky: we need to
9901 // replace an extractelement of a load with a load.
9902 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9903 // Note that this replacement assumes that the extractvalue is the only
9904 // use of the load; that's okay because we don't want to perform this
9905 // transformation in other cases anyway.
9908 if (ResultVT.bitsGT(VecEltVT)) {
9909 // If the result type of vextract is wider than the load, then issue an
9910 // extending load instead.
9911 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9914 Load = DAG.getExtLoad(
9915 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9916 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9917 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9918 Chain = Load.getValue(1);
9921 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9922 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9923 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9924 Chain = Load.getValue(1);
9925 if (ResultVT.bitsLT(VecEltVT))
9926 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9928 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9930 WorklistRemover DeadNodes(*this);
9931 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9932 SDValue To[] = { Load, Chain };
9933 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9934 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9935 // worklist explicitly as well.
9936 AddToWorklist(Load.getNode());
9937 AddUsersToWorklist(Load.getNode()); // Add users too
9938 // Make sure to revisit this node to clean it up; it will usually be dead.
9941 return SDValue(EVE, 0);
9944 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9945 // (vextract (scalar_to_vector val, 0) -> val
9946 SDValue InVec = N->getOperand(0);
9947 EVT VT = InVec.getValueType();
9948 EVT NVT = N->getValueType(0);
9950 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9951 // Check if the result type doesn't match the inserted element type. A
9952 // SCALAR_TO_VECTOR may truncate the inserted element and the
9953 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9954 SDValue InOp = InVec.getOperand(0);
9955 if (InOp.getValueType() != NVT) {
9956 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9957 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9962 SDValue EltNo = N->getOperand(1);
9963 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9965 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9966 // We only perform this optimization before the op legalization phase because
9967 // we may introduce new vector instructions which are not backed by TD
9968 // patterns. For example on AVX, extracting elements from a wide vector
9969 // without using extract_subvector. However, if we can find an underlying
9970 // scalar value, then we can always use that.
9971 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9973 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9974 int NumElem = VT.getVectorNumElements();
9975 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9976 // Find the new index to extract from.
9977 int OrigElt = SVOp->getMaskElt(Elt);
9979 // Extracting an undef index is undef.
9981 return DAG.getUNDEF(NVT);
9983 // Select the right vector half to extract from.
9985 if (OrigElt < NumElem) {
9986 SVInVec = InVec->getOperand(0);
9988 SVInVec = InVec->getOperand(1);
9992 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9993 SDValue InOp = SVInVec.getOperand(OrigElt);
9994 if (InOp.getValueType() != NVT) {
9995 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9996 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10002 // FIXME: We should handle recursing on other vector shuffles and
10003 // scalar_to_vector here as well.
10005 if (!LegalOperations) {
10006 EVT IndexTy = TLI.getVectorIdxTy();
10007 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10008 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10012 bool BCNumEltsChanged = false;
10013 EVT ExtVT = VT.getVectorElementType();
10016 // If the result of load has to be truncated, then it's not necessarily
10018 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10021 if (InVec.getOpcode() == ISD::BITCAST) {
10022 // Don't duplicate a load with other uses.
10023 if (!InVec.hasOneUse())
10026 EVT BCVT = InVec.getOperand(0).getValueType();
10027 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10029 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10030 BCNumEltsChanged = true;
10031 InVec = InVec.getOperand(0);
10032 ExtVT = BCVT.getVectorElementType();
10035 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10036 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10037 ISD::isNormalLoad(InVec.getNode()) &&
10038 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10039 SDValue Index = N->getOperand(1);
10040 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10041 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10045 // Perform only after legalization to ensure build_vector / vector_shuffle
10046 // optimizations have already been done.
10047 if (!LegalOperations) return SDValue();
10049 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10050 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10051 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10054 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10056 LoadSDNode *LN0 = nullptr;
10057 const ShuffleVectorSDNode *SVN = nullptr;
10058 if (ISD::isNormalLoad(InVec.getNode())) {
10059 LN0 = cast<LoadSDNode>(InVec);
10060 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10061 InVec.getOperand(0).getValueType() == ExtVT &&
10062 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10063 // Don't duplicate a load with other uses.
10064 if (!InVec.hasOneUse())
10067 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10068 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10069 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10071 // (load $addr+1*size)
10073 // Don't duplicate a load with other uses.
10074 if (!InVec.hasOneUse())
10077 // If the bit convert changed the number of elements, it is unsafe
10078 // to examine the mask.
10079 if (BCNumEltsChanged)
10082 // Select the input vector, guarding against out of range extract vector.
10083 unsigned NumElems = VT.getVectorNumElements();
10084 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10085 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10087 if (InVec.getOpcode() == ISD::BITCAST) {
10088 // Don't duplicate a load with other uses.
10089 if (!InVec.hasOneUse())
10092 InVec = InVec.getOperand(0);
10094 if (ISD::isNormalLoad(InVec.getNode())) {
10095 LN0 = cast<LoadSDNode>(InVec);
10096 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10097 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10101 // Make sure we found a non-volatile load and the extractelement is
10103 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10106 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10108 return DAG.getUNDEF(LVT);
10110 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10116 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10117 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10118 // We perform this optimization post type-legalization because
10119 // the type-legalizer often scalarizes integer-promoted vectors.
10120 // Performing this optimization before may create bit-casts which
10121 // will be type-legalized to complex code sequences.
10122 // We perform this optimization only before the operation legalizer because we
10123 // may introduce illegal operations.
10124 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10127 unsigned NumInScalars = N->getNumOperands();
10129 EVT VT = N->getValueType(0);
10131 // Check to see if this is a BUILD_VECTOR of a bunch of values
10132 // which come from any_extend or zero_extend nodes. If so, we can create
10133 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10134 // optimizations. We do not handle sign-extend because we can't fill the sign
10136 EVT SourceType = MVT::Other;
10137 bool AllAnyExt = true;
10139 for (unsigned i = 0; i != NumInScalars; ++i) {
10140 SDValue In = N->getOperand(i);
10141 // Ignore undef inputs.
10142 if (In.getOpcode() == ISD::UNDEF) continue;
10144 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10145 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10147 // Abort if the element is not an extension.
10148 if (!ZeroExt && !AnyExt) {
10149 SourceType = MVT::Other;
10153 // The input is a ZeroExt or AnyExt. Check the original type.
10154 EVT InTy = In.getOperand(0).getValueType();
10156 // Check that all of the widened source types are the same.
10157 if (SourceType == MVT::Other)
10160 else if (InTy != SourceType) {
10161 // Multiple income types. Abort.
10162 SourceType = MVT::Other;
10166 // Check if all of the extends are ANY_EXTENDs.
10167 AllAnyExt &= AnyExt;
10170 // In order to have valid types, all of the inputs must be extended from the
10171 // same source type and all of the inputs must be any or zero extend.
10172 // Scalar sizes must be a power of two.
10173 EVT OutScalarTy = VT.getScalarType();
10174 bool ValidTypes = SourceType != MVT::Other &&
10175 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10176 isPowerOf2_32(SourceType.getSizeInBits());
10178 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10179 // turn into a single shuffle instruction.
10183 bool isLE = TLI.isLittleEndian();
10184 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10185 assert(ElemRatio > 1 && "Invalid element size ratio");
10186 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10187 DAG.getConstant(0, SourceType);
10189 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10190 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10192 // Populate the new build_vector
10193 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10194 SDValue Cast = N->getOperand(i);
10195 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10196 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10197 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10199 if (Cast.getOpcode() == ISD::UNDEF)
10200 In = DAG.getUNDEF(SourceType);
10202 In = Cast->getOperand(0);
10203 unsigned Index = isLE ? (i * ElemRatio) :
10204 (i * ElemRatio + (ElemRatio - 1));
10206 assert(Index < Ops.size() && "Invalid index");
10210 // The type of the new BUILD_VECTOR node.
10211 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10212 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10213 "Invalid vector size");
10214 // Check if the new vector type is legal.
10215 if (!isTypeLegal(VecVT)) return SDValue();
10217 // Make the new BUILD_VECTOR.
10218 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10220 // The new BUILD_VECTOR node has the potential to be further optimized.
10221 AddToWorklist(BV.getNode());
10222 // Bitcast to the desired type.
10223 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10226 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10227 EVT VT = N->getValueType(0);
10229 unsigned NumInScalars = N->getNumOperands();
10232 EVT SrcVT = MVT::Other;
10233 unsigned Opcode = ISD::DELETED_NODE;
10234 unsigned NumDefs = 0;
10236 for (unsigned i = 0; i != NumInScalars; ++i) {
10237 SDValue In = N->getOperand(i);
10238 unsigned Opc = In.getOpcode();
10240 if (Opc == ISD::UNDEF)
10243 // If all scalar values are floats and converted from integers.
10244 if (Opcode == ISD::DELETED_NODE &&
10245 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10252 EVT InVT = In.getOperand(0).getValueType();
10254 // If all scalar values are typed differently, bail out. It's chosen to
10255 // simplify BUILD_VECTOR of integer types.
10256 if (SrcVT == MVT::Other)
10263 // If the vector has just one element defined, it's not worth to fold it into
10264 // a vectorized one.
10268 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10269 && "Should only handle conversion from integer to float.");
10270 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10272 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10274 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10277 SmallVector<SDValue, 8> Opnds;
10278 for (unsigned i = 0; i != NumInScalars; ++i) {
10279 SDValue In = N->getOperand(i);
10281 if (In.getOpcode() == ISD::UNDEF)
10282 Opnds.push_back(DAG.getUNDEF(SrcVT));
10284 Opnds.push_back(In.getOperand(0));
10286 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10287 AddToWorklist(BV.getNode());
10289 return DAG.getNode(Opcode, dl, VT, BV);
10292 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10293 unsigned NumInScalars = N->getNumOperands();
10295 EVT VT = N->getValueType(0);
10297 // A vector built entirely of undefs is undef.
10298 if (ISD::allOperandsUndef(N))
10299 return DAG.getUNDEF(VT);
10301 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10305 V = reduceBuildVecConvertToConvertBuildVec(N);
10309 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10310 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10311 // at most two distinct vectors, turn this into a shuffle node.
10313 // May only combine to shuffle after legalize if shuffle is legal.
10314 if (LegalOperations &&
10315 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10318 SDValue VecIn1, VecIn2;
10319 for (unsigned i = 0; i != NumInScalars; ++i) {
10320 // Ignore undef inputs.
10321 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10323 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10324 // constant index, bail out.
10325 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10326 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10327 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10331 // We allow up to two distinct input vectors.
10332 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10333 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10336 if (!VecIn1.getNode()) {
10337 VecIn1 = ExtractedFromVec;
10338 } else if (!VecIn2.getNode()) {
10339 VecIn2 = ExtractedFromVec;
10341 // Too many inputs.
10342 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10347 // If everything is good, we can make a shuffle operation.
10348 if (VecIn1.getNode()) {
10349 SmallVector<int, 8> Mask;
10350 for (unsigned i = 0; i != NumInScalars; ++i) {
10351 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10352 Mask.push_back(-1);
10356 // If extracting from the first vector, just use the index directly.
10357 SDValue Extract = N->getOperand(i);
10358 SDValue ExtVal = Extract.getOperand(1);
10359 if (Extract.getOperand(0) == VecIn1) {
10360 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10361 if (ExtIndex > VT.getVectorNumElements())
10364 Mask.push_back(ExtIndex);
10368 // Otherwise, use InIdx + VecSize
10369 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10370 Mask.push_back(Idx+NumInScalars);
10373 // We can't generate a shuffle node with mismatched input and output types.
10374 // Attempt to transform a single input vector to the correct type.
10375 if ((VT != VecIn1.getValueType())) {
10376 // We don't support shuffeling between TWO values of different types.
10377 if (VecIn2.getNode())
10380 // We only support widening of vectors which are half the size of the
10381 // output registers. For example XMM->YMM widening on X86 with AVX.
10382 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10385 // If the input vector type has a different base type to the output
10386 // vector type, bail out.
10387 if (VecIn1.getValueType().getVectorElementType() !=
10388 VT.getVectorElementType())
10391 // Widen the input vector by adding undef values.
10392 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10393 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10396 // If VecIn2 is unused then change it to undef.
10397 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10399 // Check that we were able to transform all incoming values to the same
10401 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10402 VecIn1.getValueType() != VT)
10405 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10406 if (!isTypeLegal(VT))
10409 // Return the new VECTOR_SHUFFLE node.
10413 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10419 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10420 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10421 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10422 // inputs come from at most two distinct vectors, turn this into a shuffle
10425 // If we only have one input vector, we don't need to do any concatenation.
10426 if (N->getNumOperands() == 1)
10427 return N->getOperand(0);
10429 // Check if all of the operands are undefs.
10430 EVT VT = N->getValueType(0);
10431 if (ISD::allOperandsUndef(N))
10432 return DAG.getUNDEF(VT);
10434 // Optimize concat_vectors where one of the vectors is undef.
10435 if (N->getNumOperands() == 2 &&
10436 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10437 SDValue In = N->getOperand(0);
10438 assert(In.getValueType().isVector() && "Must concat vectors");
10440 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10441 if (In->getOpcode() == ISD::BITCAST &&
10442 !In->getOperand(0)->getValueType(0).isVector()) {
10443 SDValue Scalar = In->getOperand(0);
10444 EVT SclTy = Scalar->getValueType(0);
10446 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10449 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10450 VT.getSizeInBits() / SclTy.getSizeInBits());
10451 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10454 SDLoc dl = SDLoc(N);
10455 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10456 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10460 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10461 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10462 if (N->getNumOperands() == 2 &&
10463 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10464 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10465 EVT VT = N->getValueType(0);
10466 SDValue N0 = N->getOperand(0);
10467 SDValue N1 = N->getOperand(1);
10468 SmallVector<SDValue, 8> Opnds;
10469 unsigned BuildVecNumElts = N0.getNumOperands();
10471 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10472 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10473 if (SclTy0.isFloatingPoint()) {
10474 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10475 Opnds.push_back(N0.getOperand(i));
10476 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10477 Opnds.push_back(N1.getOperand(i));
10479 // If BUILD_VECTOR are from built from integer, they may have different
10480 // operand types. Get the smaller type and truncate all operands to it.
10481 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10482 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10483 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10484 N0.getOperand(i)));
10485 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10486 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10487 N1.getOperand(i)));
10490 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10493 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10494 // nodes often generate nop CONCAT_VECTOR nodes.
10495 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10496 // place the incoming vectors at the exact same location.
10497 SDValue SingleSource = SDValue();
10498 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10500 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10501 SDValue Op = N->getOperand(i);
10503 if (Op.getOpcode() == ISD::UNDEF)
10506 // Check if this is the identity extract:
10507 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10510 // Find the single incoming vector for the extract_subvector.
10511 if (SingleSource.getNode()) {
10512 if (Op.getOperand(0) != SingleSource)
10515 SingleSource = Op.getOperand(0);
10517 // Check the source type is the same as the type of the result.
10518 // If not, this concat may extend the vector, so we can not
10519 // optimize it away.
10520 if (SingleSource.getValueType() != N->getValueType(0))
10524 unsigned IdentityIndex = i * PartNumElem;
10525 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10526 // The extract index must be constant.
10530 // Check that we are reading from the identity index.
10531 if (CS->getZExtValue() != IdentityIndex)
10535 if (SingleSource.getNode())
10536 return SingleSource;
10541 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10542 EVT NVT = N->getValueType(0);
10543 SDValue V = N->getOperand(0);
10545 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10547 // (extract_subvec (concat V1, V2, ...), i)
10550 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10552 if (V->getOperand(0).getValueType() != NVT)
10554 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10555 unsigned NumElems = NVT.getVectorNumElements();
10556 assert((Idx % NumElems) == 0 &&
10557 "IDX in concat is not a multiple of the result vector length.");
10558 return V->getOperand(Idx / NumElems);
10562 if (V->getOpcode() == ISD::BITCAST)
10563 V = V.getOperand(0);
10565 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10567 // Handle only simple case where vector being inserted and vector
10568 // being extracted are of same type, and are half size of larger vectors.
10569 EVT BigVT = V->getOperand(0).getValueType();
10570 EVT SmallVT = V->getOperand(1).getValueType();
10571 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10574 // Only handle cases where both indexes are constants with the same type.
10575 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10576 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10578 if (InsIdx && ExtIdx &&
10579 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10580 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10582 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10584 // indices are equal or bit offsets are equal => V1
10585 // otherwise => (extract_subvec V1, ExtIdx)
10586 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10587 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10588 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10589 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10590 DAG.getNode(ISD::BITCAST, dl,
10591 N->getOperand(0).getValueType(),
10592 V->getOperand(0)), N->getOperand(1));
10599 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10600 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10601 EVT VT = N->getValueType(0);
10602 unsigned NumElts = VT.getVectorNumElements();
10604 SDValue N0 = N->getOperand(0);
10605 SDValue N1 = N->getOperand(1);
10606 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10608 SmallVector<SDValue, 4> Ops;
10609 EVT ConcatVT = N0.getOperand(0).getValueType();
10610 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10611 unsigned NumConcats = NumElts / NumElemsPerConcat;
10613 // Look at every vector that's inserted. We're looking for exact
10614 // subvector-sized copies from a concatenated vector
10615 for (unsigned I = 0; I != NumConcats; ++I) {
10616 // Make sure we're dealing with a copy.
10617 unsigned Begin = I * NumElemsPerConcat;
10618 bool AllUndef = true, NoUndef = true;
10619 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10620 if (SVN->getMaskElt(J) >= 0)
10627 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10630 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10631 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10634 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10635 if (FirstElt < N0.getNumOperands())
10636 Ops.push_back(N0.getOperand(FirstElt));
10638 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10640 } else if (AllUndef) {
10641 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10642 } else { // Mixed with general masks and undefs, can't do optimization.
10647 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10650 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10651 EVT VT = N->getValueType(0);
10652 unsigned NumElts = VT.getVectorNumElements();
10654 SDValue N0 = N->getOperand(0);
10655 SDValue N1 = N->getOperand(1);
10657 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10659 // Canonicalize shuffle undef, undef -> undef
10660 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10661 return DAG.getUNDEF(VT);
10663 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10665 // Canonicalize shuffle v, v -> v, undef
10667 SmallVector<int, 8> NewMask;
10668 for (unsigned i = 0; i != NumElts; ++i) {
10669 int Idx = SVN->getMaskElt(i);
10670 if (Idx >= (int)NumElts) Idx -= NumElts;
10671 NewMask.push_back(Idx);
10673 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10677 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10678 if (N0.getOpcode() == ISD::UNDEF) {
10679 SmallVector<int, 8> NewMask;
10680 for (unsigned i = 0; i != NumElts; ++i) {
10681 int Idx = SVN->getMaskElt(i);
10683 if (Idx >= (int)NumElts)
10686 Idx = -1; // remove reference to lhs
10688 NewMask.push_back(Idx);
10690 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10694 // Remove references to rhs if it is undef
10695 if (N1.getOpcode() == ISD::UNDEF) {
10696 bool Changed = false;
10697 SmallVector<int, 8> NewMask;
10698 for (unsigned i = 0; i != NumElts; ++i) {
10699 int Idx = SVN->getMaskElt(i);
10700 if (Idx >= (int)NumElts) {
10704 NewMask.push_back(Idx);
10707 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10710 // If it is a splat, check if the argument vector is another splat or a
10711 // build_vector with all scalar elements the same.
10712 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10713 SDNode *V = N0.getNode();
10715 // If this is a bit convert that changes the element type of the vector but
10716 // not the number of vector elements, look through it. Be careful not to
10717 // look though conversions that change things like v4f32 to v2f64.
10718 if (V->getOpcode() == ISD::BITCAST) {
10719 SDValue ConvInput = V->getOperand(0);
10720 if (ConvInput.getValueType().isVector() &&
10721 ConvInput.getValueType().getVectorNumElements() == NumElts)
10722 V = ConvInput.getNode();
10725 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10726 assert(V->getNumOperands() == NumElts &&
10727 "BUILD_VECTOR has wrong number of operands");
10729 bool AllSame = true;
10730 for (unsigned i = 0; i != NumElts; ++i) {
10731 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10732 Base = V->getOperand(i);
10736 // Splat of <u, u, u, u>, return <u, u, u, u>
10737 if (!Base.getNode())
10739 for (unsigned i = 0; i != NumElts; ++i) {
10740 if (V->getOperand(i) != Base) {
10745 // Splat of <x, x, x, x>, return <x, x, x, x>
10751 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10752 Level < AfterLegalizeVectorOps &&
10753 (N1.getOpcode() == ISD::UNDEF ||
10754 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10755 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10756 SDValue V = partitionShuffleOfConcats(N, DAG);
10762 // If this shuffle node is simply a swizzle of another shuffle node,
10763 // then try to simplify it.
10764 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10765 N1.getOpcode() == ISD::UNDEF) {
10767 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10769 // The incoming shuffle must be of the same type as the result of the
10770 // current shuffle.
10771 assert(OtherSV->getOperand(0).getValueType() == VT &&
10772 "Shuffle types don't match");
10774 SmallVector<int, 4> Mask;
10775 // Compute the combined shuffle mask.
10776 for (unsigned i = 0; i != NumElts; ++i) {
10777 int Idx = SVN->getMaskElt(i);
10778 assert(Idx < (int)NumElts && "Index references undef operand");
10779 // Next, this index comes from the first value, which is the incoming
10780 // shuffle. Adopt the incoming index.
10782 Idx = OtherSV->getMaskElt(Idx);
10783 Mask.push_back(Idx);
10786 bool CommuteOperands = false;
10787 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10788 // To be valid, the combine shuffle mask should only reference elements
10789 // from one of the two vectors in input to the inner shufflevector.
10790 bool IsValidMask = true;
10791 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10792 // See if the combined mask only reference undefs or elements coming
10793 // from the first shufflevector operand.
10794 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10796 if (!IsValidMask) {
10797 IsValidMask = true;
10798 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10799 // Check that all the elements come from the second shuffle operand.
10800 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10801 CommuteOperands = IsValidMask;
10804 // Early exit if the combined shuffle mask is not valid.
10809 // See if this pair of shuffles can be safely folded according to either
10810 // of the following rules:
10811 // shuffle(shuffle(x, y), undef) -> x
10812 // shuffle(shuffle(x, undef), undef) -> x
10813 // shuffle(shuffle(x, y), undef) -> y
10814 bool IsIdentityMask = true;
10815 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10816 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10821 // The combined shuffle must map each index to itself.
10822 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10825 if (IsIdentityMask) {
10826 if (CommuteOperands)
10827 // optimize shuffle(shuffle(x, y), undef) -> y.
10828 return OtherSV->getOperand(1);
10830 // optimize shuffle(shuffle(x, undef), undef) -> x
10831 // optimize shuffle(shuffle(x, y), undef) -> x
10832 return OtherSV->getOperand(0);
10835 // It may still be beneficial to combine the two shuffles if the
10836 // resulting shuffle is legal.
10837 if (TLI.isTypeLegal(VT)) {
10838 if (!CommuteOperands) {
10839 if (TLI.isShuffleMaskLegal(Mask, VT))
10840 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10841 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10842 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10845 // Compute the commuted shuffle mask.
10846 for (unsigned i = 0; i != NumElts; ++i) {
10850 else if (idx < (int)NumElts)
10851 Mask[i] = idx + NumElts;
10853 Mask[i] = idx - NumElts;
10856 if (TLI.isShuffleMaskLegal(Mask, VT))
10857 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10858 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10864 // Canonicalize shuffles according to rules:
10865 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10866 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10867 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10868 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10869 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10870 TLI.isTypeLegal(VT)) {
10871 // The incoming shuffle must be of the same type as the result of the
10872 // current shuffle.
10873 assert(N1->getOperand(0).getValueType() == VT &&
10874 "Shuffle types don't match");
10876 SDValue SV0 = N1->getOperand(0);
10877 SDValue SV1 = N1->getOperand(1);
10878 bool HasSameOp0 = N0 == SV0;
10879 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10880 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10881 // Commute the operands of this shuffle so that next rule
10883 return DAG.getCommutedVectorShuffle(*SVN);
10886 // Try to fold according to rules:
10887 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10888 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10889 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10890 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10891 // Don't try to fold shuffles with illegal type.
10892 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10893 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10894 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10896 // The incoming shuffle must be of the same type as the result of the
10897 // current shuffle.
10898 assert(OtherSV->getOperand(0).getValueType() == VT &&
10899 "Shuffle types don't match");
10901 SDValue SV0 = OtherSV->getOperand(0);
10902 SDValue SV1 = OtherSV->getOperand(1);
10903 bool HasSameOp0 = N1 == SV0;
10904 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10905 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10909 SmallVector<int, 4> Mask;
10910 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10911 // operand, and SV1 as the second operand.
10912 for (unsigned i = 0; i != NumElts; ++i) {
10913 int Idx = SVN->getMaskElt(i);
10915 // Propagate Undef.
10916 Mask.push_back(Idx);
10920 if (Idx < (int)NumElts) {
10921 Idx = OtherSV->getMaskElt(Idx);
10922 if (IsSV1Undef && Idx >= (int) NumElts)
10923 Idx = -1; // Propagate Undef.
10925 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10927 Mask.push_back(Idx);
10930 // Avoid introducing shuffles with illegal mask.
10931 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10933 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10934 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10935 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10936 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10943 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10944 SDValue N0 = N->getOperand(0);
10945 SDValue N2 = N->getOperand(2);
10947 // If the input vector is a concatenation, and the insert replaces
10948 // one of the halves, we can optimize into a single concat_vectors.
10949 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10950 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10951 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10952 EVT VT = N->getValueType(0);
10954 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10955 // (concat_vectors Z, Y)
10957 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10958 N->getOperand(1), N0.getOperand(1));
10960 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10961 // (concat_vectors X, Z)
10962 if (InsIdx == VT.getVectorNumElements()/2)
10963 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10964 N0.getOperand(0), N->getOperand(1));
10970 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10971 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10972 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10973 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10974 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10975 EVT VT = N->getValueType(0);
10977 SDValue LHS = N->getOperand(0);
10978 SDValue RHS = N->getOperand(1);
10979 if (N->getOpcode() == ISD::AND) {
10980 if (RHS.getOpcode() == ISD::BITCAST)
10981 RHS = RHS.getOperand(0);
10982 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10983 SmallVector<int, 8> Indices;
10984 unsigned NumElts = RHS.getNumOperands();
10985 for (unsigned i = 0; i != NumElts; ++i) {
10986 SDValue Elt = RHS.getOperand(i);
10987 if (!isa<ConstantSDNode>(Elt))
10990 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10991 Indices.push_back(i);
10992 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10993 Indices.push_back(NumElts);
10998 // Let's see if the target supports this vector_shuffle.
10999 EVT RVT = RHS.getValueType();
11000 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11003 // Return the new VECTOR_SHUFFLE node.
11004 EVT EltVT = RVT.getVectorElementType();
11005 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11006 DAG.getConstant(0, EltVT));
11007 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11008 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11009 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11010 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11017 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11018 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11019 assert(N->getValueType(0).isVector() &&
11020 "SimplifyVBinOp only works on vectors!");
11022 SDValue LHS = N->getOperand(0);
11023 SDValue RHS = N->getOperand(1);
11024 SDValue Shuffle = XformToShuffleWithZero(N);
11025 if (Shuffle.getNode()) return Shuffle;
11027 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11029 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11030 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11031 // Check if both vectors are constants. If not bail out.
11032 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11033 cast<BuildVectorSDNode>(RHS)->isConstant()))
11036 SmallVector<SDValue, 8> Ops;
11037 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11038 SDValue LHSOp = LHS.getOperand(i);
11039 SDValue RHSOp = RHS.getOperand(i);
11041 // Can't fold divide by zero.
11042 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11043 N->getOpcode() == ISD::FDIV) {
11044 if ((RHSOp.getOpcode() == ISD::Constant &&
11045 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11046 (RHSOp.getOpcode() == ISD::ConstantFP &&
11047 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11051 EVT VT = LHSOp.getValueType();
11052 EVT RVT = RHSOp.getValueType();
11054 // Integer BUILD_VECTOR operands may have types larger than the element
11055 // size (e.g., when the element type is not legal). Prior to type
11056 // legalization, the types may not match between the two BUILD_VECTORS.
11057 // Truncate one of the operands to make them match.
11058 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11059 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11061 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11065 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11067 if (FoldOp.getOpcode() != ISD::UNDEF &&
11068 FoldOp.getOpcode() != ISD::Constant &&
11069 FoldOp.getOpcode() != ISD::ConstantFP)
11071 Ops.push_back(FoldOp);
11072 AddToWorklist(FoldOp.getNode());
11075 if (Ops.size() == LHS.getNumOperands())
11076 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11079 // Type legalization might introduce new shuffles in the DAG.
11080 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11081 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11082 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11083 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11084 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11085 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11086 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11087 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11089 if (SVN0->getMask().equals(SVN1->getMask())) {
11090 EVT VT = N->getValueType(0);
11091 SDValue UndefVector = LHS.getOperand(1);
11092 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11093 LHS.getOperand(0), RHS.getOperand(0));
11094 AddUsersToWorklist(N);
11095 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11096 &SVN0->getMask()[0]);
11103 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11104 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11105 assert(N->getValueType(0).isVector() &&
11106 "SimplifyVUnaryOp only works on vectors!");
11108 SDValue N0 = N->getOperand(0);
11110 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11113 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11114 SmallVector<SDValue, 8> Ops;
11115 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11116 SDValue Op = N0.getOperand(i);
11117 if (Op.getOpcode() != ISD::UNDEF &&
11118 Op.getOpcode() != ISD::ConstantFP)
11120 EVT EltVT = Op.getValueType();
11121 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11122 if (FoldOp.getOpcode() != ISD::UNDEF &&
11123 FoldOp.getOpcode() != ISD::ConstantFP)
11125 Ops.push_back(FoldOp);
11126 AddToWorklist(FoldOp.getNode());
11129 if (Ops.size() != N0.getNumOperands())
11132 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11135 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11136 SDValue N1, SDValue N2){
11137 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11139 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11140 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11142 // If we got a simplified select_cc node back from SimplifySelectCC, then
11143 // break it down into a new SETCC node, and a new SELECT node, and then return
11144 // the SELECT node, since we were called with a SELECT node.
11145 if (SCC.getNode()) {
11146 // Check to see if we got a select_cc back (to turn into setcc/select).
11147 // Otherwise, just return whatever node we got back, like fabs.
11148 if (SCC.getOpcode() == ISD::SELECT_CC) {
11149 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11151 SCC.getOperand(0), SCC.getOperand(1),
11152 SCC.getOperand(4));
11153 AddToWorklist(SETCC.getNode());
11154 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11155 SCC.getOperand(2), SCC.getOperand(3));
11163 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11164 /// are the two values being selected between, see if we can simplify the
11165 /// select. Callers of this should assume that TheSelect is deleted if this
11166 /// returns true. As such, they should return the appropriate thing (e.g. the
11167 /// node) back to the top-level of the DAG combiner loop to avoid it being
11169 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11172 // Cannot simplify select with vector condition
11173 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11175 // If this is a select from two identical things, try to pull the operation
11176 // through the select.
11177 if (LHS.getOpcode() != RHS.getOpcode() ||
11178 !LHS.hasOneUse() || !RHS.hasOneUse())
11181 // If this is a load and the token chain is identical, replace the select
11182 // of two loads with a load through a select of the address to load from.
11183 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11184 // constants have been dropped into the constant pool.
11185 if (LHS.getOpcode() == ISD::LOAD) {
11186 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11187 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11189 // Token chains must be identical.
11190 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11191 // Do not let this transformation reduce the number of volatile loads.
11192 LLD->isVolatile() || RLD->isVolatile() ||
11193 // If this is an EXTLOAD, the VT's must match.
11194 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11195 // If this is an EXTLOAD, the kind of extension must match.
11196 (LLD->getExtensionType() != RLD->getExtensionType() &&
11197 // The only exception is if one of the extensions is anyext.
11198 LLD->getExtensionType() != ISD::EXTLOAD &&
11199 RLD->getExtensionType() != ISD::EXTLOAD) ||
11200 // FIXME: this discards src value information. This is
11201 // over-conservative. It would be beneficial to be able to remember
11202 // both potential memory locations. Since we are discarding
11203 // src value info, don't do the transformation if the memory
11204 // locations are not in the default address space.
11205 LLD->getPointerInfo().getAddrSpace() != 0 ||
11206 RLD->getPointerInfo().getAddrSpace() != 0 ||
11207 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11208 LLD->getBasePtr().getValueType()))
11211 // Check that the select condition doesn't reach either load. If so,
11212 // folding this will induce a cycle into the DAG. If not, this is safe to
11213 // xform, so create a select of the addresses.
11215 if (TheSelect->getOpcode() == ISD::SELECT) {
11216 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11217 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11218 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11220 // The loads must not depend on one another.
11221 if (LLD->isPredecessorOf(RLD) ||
11222 RLD->isPredecessorOf(LLD))
11224 Addr = DAG.getSelect(SDLoc(TheSelect),
11225 LLD->getBasePtr().getValueType(),
11226 TheSelect->getOperand(0), LLD->getBasePtr(),
11227 RLD->getBasePtr());
11228 } else { // Otherwise SELECT_CC
11229 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11230 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11232 if ((LLD->hasAnyUseOfValue(1) &&
11233 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11234 (RLD->hasAnyUseOfValue(1) &&
11235 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11238 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11239 LLD->getBasePtr().getValueType(),
11240 TheSelect->getOperand(0),
11241 TheSelect->getOperand(1),
11242 LLD->getBasePtr(), RLD->getBasePtr(),
11243 TheSelect->getOperand(4));
11247 // It is safe to replace the two loads if they have different alignments,
11248 // but the new load must be the minimum (most restrictive) alignment of the
11250 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11251 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11252 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11253 Load = DAG.getLoad(TheSelect->getValueType(0),
11255 // FIXME: Discards pointer and AA info.
11256 LLD->getChain(), Addr, MachinePointerInfo(),
11257 LLD->isVolatile(), LLD->isNonTemporal(),
11258 isInvariant, Alignment);
11260 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11261 RLD->getExtensionType() : LLD->getExtensionType(),
11263 TheSelect->getValueType(0),
11264 // FIXME: Discards pointer and AA info.
11265 LLD->getChain(), Addr, MachinePointerInfo(),
11266 LLD->getMemoryVT(), LLD->isVolatile(),
11267 LLD->isNonTemporal(), isInvariant, Alignment);
11270 // Users of the select now use the result of the load.
11271 CombineTo(TheSelect, Load);
11273 // Users of the old loads now use the new load's chain. We know the
11274 // old-load value is dead now.
11275 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11276 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11283 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11284 /// where 'cond' is the comparison specified by CC.
11285 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11286 SDValue N2, SDValue N3,
11287 ISD::CondCode CC, bool NotExtCompare) {
11288 // (x ? y : y) -> y.
11289 if (N2 == N3) return N2;
11291 EVT VT = N2.getValueType();
11292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11293 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11294 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11296 // Determine if the condition we're dealing with is constant
11297 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11298 N0, N1, CC, DL, false);
11299 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11300 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11302 // fold select_cc true, x, y -> x
11303 if (SCCC && !SCCC->isNullValue())
11305 // fold select_cc false, x, y -> y
11306 if (SCCC && SCCC->isNullValue())
11309 // Check to see if we can simplify the select into an fabs node
11310 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11311 // Allow either -0.0 or 0.0
11312 if (CFP->getValueAPF().isZero()) {
11313 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11314 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11315 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11316 N2 == N3.getOperand(0))
11317 return DAG.getNode(ISD::FABS, DL, VT, N0);
11319 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11320 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11321 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11322 N2.getOperand(0) == N3)
11323 return DAG.getNode(ISD::FABS, DL, VT, N3);
11327 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11328 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11329 // in it. This is a win when the constant is not otherwise available because
11330 // it replaces two constant pool loads with one. We only do this if the FP
11331 // type is known to be legal, because if it isn't, then we are before legalize
11332 // types an we want the other legalization to happen first (e.g. to avoid
11333 // messing with soft float) and if the ConstantFP is not legal, because if
11334 // it is legal, we may not need to store the FP constant in a constant pool.
11335 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11336 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11337 if (TLI.isTypeLegal(N2.getValueType()) &&
11338 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11339 TargetLowering::Legal &&
11340 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11341 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11342 // If both constants have multiple uses, then we won't need to do an
11343 // extra load, they are likely around in registers for other users.
11344 (TV->hasOneUse() || FV->hasOneUse())) {
11345 Constant *Elts[] = {
11346 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11347 const_cast<ConstantFP*>(TV->getConstantFPValue())
11349 Type *FPTy = Elts[0]->getType();
11350 const DataLayout &TD = *TLI.getDataLayout();
11352 // Create a ConstantArray of the two constants.
11353 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11354 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11355 TD.getPrefTypeAlignment(FPTy));
11356 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11358 // Get the offsets to the 0 and 1 element of the array so that we can
11359 // select between them.
11360 SDValue Zero = DAG.getIntPtrConstant(0);
11361 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11362 SDValue One = DAG.getIntPtrConstant(EltSize);
11364 SDValue Cond = DAG.getSetCC(DL,
11365 getSetCCResultType(N0.getValueType()),
11367 AddToWorklist(Cond.getNode());
11368 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11370 AddToWorklist(CstOffset.getNode());
11371 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11373 AddToWorklist(CPIdx.getNode());
11374 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11375 MachinePointerInfo::getConstantPool(), false,
11376 false, false, Alignment);
11381 // Check to see if we can perform the "gzip trick", transforming
11382 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11383 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11384 (N1C->isNullValue() || // (a < 0) ? b : 0
11385 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11386 EVT XType = N0.getValueType();
11387 EVT AType = N2.getValueType();
11388 if (XType.bitsGE(AType)) {
11389 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11390 // single-bit constant.
11391 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11392 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11393 ShCtV = XType.getSizeInBits()-ShCtV-1;
11394 SDValue ShCt = DAG.getConstant(ShCtV,
11395 getShiftAmountTy(N0.getValueType()));
11396 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11398 AddToWorklist(Shift.getNode());
11400 if (XType.bitsGT(AType)) {
11401 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11402 AddToWorklist(Shift.getNode());
11405 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11408 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11410 DAG.getConstant(XType.getSizeInBits()-1,
11411 getShiftAmountTy(N0.getValueType())));
11412 AddToWorklist(Shift.getNode());
11414 if (XType.bitsGT(AType)) {
11415 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11416 AddToWorklist(Shift.getNode());
11419 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11423 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11424 // where y is has a single bit set.
11425 // A plaintext description would be, we can turn the SELECT_CC into an AND
11426 // when the condition can be materialized as an all-ones register. Any
11427 // single bit-test can be materialized as an all-ones register with
11428 // shift-left and shift-right-arith.
11429 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11430 N0->getValueType(0) == VT &&
11431 N1C && N1C->isNullValue() &&
11432 N2C && N2C->isNullValue()) {
11433 SDValue AndLHS = N0->getOperand(0);
11434 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11435 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11436 // Shift the tested bit over the sign bit.
11437 APInt AndMask = ConstAndRHS->getAPIntValue();
11439 DAG.getConstant(AndMask.countLeadingZeros(),
11440 getShiftAmountTy(AndLHS.getValueType()));
11441 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11443 // Now arithmetic right shift it all the way over, so the result is either
11444 // all-ones, or zero.
11446 DAG.getConstant(AndMask.getBitWidth()-1,
11447 getShiftAmountTy(Shl.getValueType()));
11448 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11450 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11454 // fold select C, 16, 0 -> shl C, 4
11455 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11456 TLI.getBooleanContents(N0.getValueType()) ==
11457 TargetLowering::ZeroOrOneBooleanContent) {
11459 // If the caller doesn't want us to simplify this into a zext of a compare,
11461 if (NotExtCompare && N2C->getAPIntValue() == 1)
11464 // Get a SetCC of the condition
11465 // NOTE: Don't create a SETCC if it's not legal on this target.
11466 if (!LegalOperations ||
11467 TLI.isOperationLegal(ISD::SETCC,
11468 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11470 // cast from setcc result type to select result type
11472 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11474 if (N2.getValueType().bitsLT(SCC.getValueType()))
11475 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11476 N2.getValueType());
11478 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11479 N2.getValueType(), SCC);
11481 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11482 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11483 N2.getValueType(), SCC);
11486 AddToWorklist(SCC.getNode());
11487 AddToWorklist(Temp.getNode());
11489 if (N2C->getAPIntValue() == 1)
11492 // shl setcc result by log2 n2c
11493 return DAG.getNode(
11494 ISD::SHL, DL, N2.getValueType(), Temp,
11495 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11496 getShiftAmountTy(Temp.getValueType())));
11500 // Check to see if this is the equivalent of setcc
11501 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11502 // otherwise, go ahead with the folds.
11503 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11504 EVT XType = N0.getValueType();
11505 if (!LegalOperations ||
11506 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11507 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11508 if (Res.getValueType() != VT)
11509 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11513 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11514 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11515 (!LegalOperations ||
11516 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11517 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11518 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11519 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11520 getShiftAmountTy(Ctlz.getValueType())));
11522 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11523 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11524 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11525 XType, DAG.getConstant(0, XType), N0);
11526 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11527 return DAG.getNode(ISD::SRL, DL, XType,
11528 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11529 DAG.getConstant(XType.getSizeInBits()-1,
11530 getShiftAmountTy(XType)));
11532 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11533 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11534 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11535 DAG.getConstant(XType.getSizeInBits()-1,
11536 getShiftAmountTy(N0.getValueType())));
11537 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11541 // Check to see if this is an integer abs.
11542 // select_cc setg[te] X, 0, X, -X ->
11543 // select_cc setgt X, -1, X, -X ->
11544 // select_cc setl[te] X, 0, -X, X ->
11545 // select_cc setlt X, 1, -X, X ->
11546 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11548 ConstantSDNode *SubC = nullptr;
11549 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11550 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11551 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11552 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11553 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11554 (N1C->isOne() && CC == ISD::SETLT)) &&
11555 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11556 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11558 EVT XType = N0.getValueType();
11559 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11560 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11562 DAG.getConstant(XType.getSizeInBits()-1,
11563 getShiftAmountTy(N0.getValueType())));
11564 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11566 AddToWorklist(Shift.getNode());
11567 AddToWorklist(Add.getNode());
11568 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11575 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11576 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11577 SDValue N1, ISD::CondCode Cond,
11578 SDLoc DL, bool foldBooleans) {
11579 TargetLowering::DAGCombinerInfo
11580 DagCombineInfo(DAG, Level, false, this);
11581 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11584 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11585 /// a DAG expression to select that will generate the same value by multiplying
11586 /// by a magic number. See:
11587 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11588 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11589 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11593 // Avoid division by zero.
11594 if (!C->getAPIntValue())
11597 std::vector<SDNode*> Built;
11599 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11601 for (SDNode *N : Built)
11606 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11607 /// power of 2, return a DAG expression to select that will generate the same
11608 /// value by right shifting.
11609 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11610 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11614 // Avoid division by zero.
11615 if (!C->getAPIntValue())
11618 std::vector<SDNode *> Built;
11619 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11621 for (SDNode *N : Built)
11626 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11627 /// return a DAG expression to select that will generate the same value by
11628 /// multiplying by a magic number. See:
11629 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11630 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11631 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11635 // Avoid division by zero.
11636 if (!C->getAPIntValue())
11639 std::vector<SDNode*> Built;
11641 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11643 for (SDNode *N : Built)
11648 /// FindBaseOffset - Return true if base is a frame index, which is known not
11649 // to alias with anything but itself. Provides base object and offset as
11651 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11652 const GlobalValue *&GV, const void *&CV) {
11653 // Assume it is a primitive operation.
11654 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11656 // If it's an adding a simple constant then integrate the offset.
11657 if (Base.getOpcode() == ISD::ADD) {
11658 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11659 Base = Base.getOperand(0);
11660 Offset += C->getZExtValue();
11664 // Return the underlying GlobalValue, and update the Offset. Return false
11665 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11666 // by multiple nodes with different offsets.
11667 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11668 GV = G->getGlobal();
11669 Offset += G->getOffset();
11673 // Return the underlying Constant value, and update the Offset. Return false
11674 // for ConstantSDNodes since the same constant pool entry may be represented
11675 // by multiple nodes with different offsets.
11676 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11677 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11678 : (const void *)C->getConstVal();
11679 Offset += C->getOffset();
11682 // If it's any of the following then it can't alias with anything but itself.
11683 return isa<FrameIndexSDNode>(Base);
11686 /// isAlias - Return true if there is any possibility that the two addresses
11688 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11689 // If they are the same then they must be aliases.
11690 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11692 // If they are both volatile then they cannot be reordered.
11693 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11695 // Gather base node and offset information.
11696 SDValue Base1, Base2;
11697 int64_t Offset1, Offset2;
11698 const GlobalValue *GV1, *GV2;
11699 const void *CV1, *CV2;
11700 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11701 Base1, Offset1, GV1, CV1);
11702 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11703 Base2, Offset2, GV2, CV2);
11705 // If they have a same base address then check to see if they overlap.
11706 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11707 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11708 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11710 // It is possible for different frame indices to alias each other, mostly
11711 // when tail call optimization reuses return address slots for arguments.
11712 // To catch this case, look up the actual index of frame indices to compute
11713 // the real alias relationship.
11714 if (isFrameIndex1 && isFrameIndex2) {
11715 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11716 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11717 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11718 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11719 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11722 // Otherwise, if we know what the bases are, and they aren't identical, then
11723 // we know they cannot alias.
11724 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11727 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11728 // compared to the size and offset of the access, we may be able to prove they
11729 // do not alias. This check is conservative for now to catch cases created by
11730 // splitting vector types.
11731 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11732 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11733 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11734 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11735 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11736 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11737 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11739 // There is no overlap between these relatively aligned accesses of similar
11740 // size, return no alias.
11741 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11742 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11746 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11747 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11749 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11750 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11754 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11755 // Use alias analysis information.
11756 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11757 Op1->getSrcValueOffset());
11758 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11759 Op0->getSrcValueOffset() - MinOffset;
11760 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11761 Op1->getSrcValueOffset() - MinOffset;
11762 AliasAnalysis::AliasResult AAResult =
11763 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11765 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11766 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11768 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11769 if (AAResult == AliasAnalysis::NoAlias)
11773 // Otherwise we have to assume they alias.
11777 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11778 /// looking for aliasing nodes and adding them to the Aliases vector.
11779 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11780 SmallVectorImpl<SDValue> &Aliases) {
11781 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11782 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11784 // Get alias information for node.
11785 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11788 Chains.push_back(OriginalChain);
11789 unsigned Depth = 0;
11791 // Look at each chain and determine if it is an alias. If so, add it to the
11792 // aliases list. If not, then continue up the chain looking for the next
11794 while (!Chains.empty()) {
11795 SDValue Chain = Chains.back();
11798 // For TokenFactor nodes, look at each operand and only continue up the
11799 // chain until we find two aliases. If we've seen two aliases, assume we'll
11800 // find more and revert to original chain since the xform is unlikely to be
11803 // FIXME: The depth check could be made to return the last non-aliasing
11804 // chain we found before we hit a tokenfactor rather than the original
11806 if (Depth > 6 || Aliases.size() == 2) {
11808 Aliases.push_back(OriginalChain);
11812 // Don't bother if we've been before.
11813 if (!Visited.insert(Chain.getNode()))
11816 switch (Chain.getOpcode()) {
11817 case ISD::EntryToken:
11818 // Entry token is ideal chain operand, but handled in FindBetterChain.
11823 // Get alias information for Chain.
11824 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11825 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11827 // If chain is alias then stop here.
11828 if (!(IsLoad && IsOpLoad) &&
11829 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11830 Aliases.push_back(Chain);
11832 // Look further up the chain.
11833 Chains.push_back(Chain.getOperand(0));
11839 case ISD::TokenFactor:
11840 // We have to check each of the operands of the token factor for "small"
11841 // token factors, so we queue them up. Adding the operands to the queue
11842 // (stack) in reverse order maintains the original order and increases the
11843 // likelihood that getNode will find a matching token factor (CSE.)
11844 if (Chain.getNumOperands() > 16) {
11845 Aliases.push_back(Chain);
11848 for (unsigned n = Chain.getNumOperands(); n;)
11849 Chains.push_back(Chain.getOperand(--n));
11854 // For all other instructions we will just have to take what we can get.
11855 Aliases.push_back(Chain);
11860 // We need to be careful here to also search for aliases through the
11861 // value operand of a store, etc. Consider the following situation:
11863 // L1 = load Token1, %52
11864 // S1 = store Token1, L1, %51
11865 // L2 = load Token1, %52+8
11866 // S2 = store Token1, L2, %51+8
11867 // Token2 = Token(S1, S2)
11868 // L3 = load Token2, %53
11869 // S3 = store Token2, L3, %52
11870 // L4 = load Token2, %53+8
11871 // S4 = store Token2, L4, %52+8
11872 // If we search for aliases of S3 (which loads address %52), and we look
11873 // only through the chain, then we'll miss the trivial dependence on L1
11874 // (which also loads from %52). We then might change all loads and
11875 // stores to use Token1 as their chain operand, which could result in
11876 // copying %53 into %52 before copying %52 into %51 (which should
11879 // The problem is, however, that searching for such data dependencies
11880 // can become expensive, and the cost is not directly related to the
11881 // chain depth. Instead, we'll rule out such configurations here by
11882 // insisting that we've visited all chain users (except for users
11883 // of the original chain, which is not necessary). When doing this,
11884 // we need to look through nodes we don't care about (otherwise, things
11885 // like register copies will interfere with trivial cases).
11887 SmallVector<const SDNode *, 16> Worklist;
11888 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11889 IE = Visited.end(); I != IE; ++I)
11890 if (*I != OriginalChain.getNode())
11891 Worklist.push_back(*I);
11893 while (!Worklist.empty()) {
11894 const SDNode *M = Worklist.pop_back_val();
11896 // We have already visited M, and want to make sure we've visited any uses
11897 // of M that we care about. For uses that we've not visisted, and don't
11898 // care about, queue them to the worklist.
11900 for (SDNode::use_iterator UI = M->use_begin(),
11901 UIE = M->use_end(); UI != UIE; ++UI)
11902 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11903 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11904 // We've not visited this use, and we care about it (it could have an
11905 // ordering dependency with the original node).
11907 Aliases.push_back(OriginalChain);
11911 // We've not visited this use, but we don't care about it. Mark it as
11912 // visited and enqueue it to the worklist.
11913 Worklist.push_back(*UI);
11918 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11919 /// for a better chain (aliasing node.)
11920 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11921 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11923 // Accumulate all the aliases to this node.
11924 GatherAllAliases(N, OldChain, Aliases);
11926 // If no operands then chain to entry token.
11927 if (Aliases.size() == 0)
11928 return DAG.getEntryNode();
11930 // If a single operand then chain to it. We don't need to revisit it.
11931 if (Aliases.size() == 1)
11934 // Construct a custom tailored token factor.
11935 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11938 // SelectionDAG::Combine - This is the entry point for the file.
11940 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11941 CodeGenOpt::Level OptLevel) {
11942 /// run - This is the main entry point to this class.
11944 DAGCombiner(*this, AA, OptLevel).Run(Level);