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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
309 SDValue XformToShuffleWithZero(SDNode *N);
310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318 SDValue N3, ISD::CondCode CC,
319 bool NotExtCompare = false);
320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321 SDLoc DL, bool foldBooleans = true);
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
325 bool isOneUseSetCC(SDValue N) const;
327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331 SDValue BuildSDIV(SDNode *N);
332 SDValue BuildSDIVPow2(SDNode *N);
333 SDValue BuildUDIV(SDNode *N);
334 SDValue BuildReciprocalEstimate(SDValue Op);
335 SDValue BuildRsqrtEstimate(SDValue Op);
336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339 bool DemandHighBits = true);
340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342 SDValue InnerPos, SDValue InnerNeg,
343 unsigned PosOpcode, unsigned NegOpcode,
345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346 SDValue ReduceLoadWidth(SDNode *N);
347 SDValue ReduceLoadOpStoreWidth(SDNode *N);
348 SDValue TransformFPLoadStorePair(SDNode *N);
349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
352 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
354 /// Walk up chain skipping non-aliasing memory nodes,
355 /// looking for aliasing nodes and adding them to the Aliases vector.
356 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357 SmallVectorImpl<SDValue> &Aliases);
359 /// Return true if there is any possibility that the two addresses overlap.
360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363 /// chain (aliasing node.)
364 SDValue FindBetterChain(SDNode *N, SDValue Chain);
366 /// Merge consecutive store operations into a wide store.
367 /// This optimization uses wide integers or vectors when possible.
368 /// \return True if some memory operations were changed.
369 bool MergeConsecutiveStores(StoreSDNode *N);
371 /// \brief Try to transform a truncation where C is a constant:
372 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
374 /// \p N needs to be a truncation and its first operand an AND. Other
375 /// requirements are checked by the function (e.g. that trunc is
376 /// single-use) and if missed an empty SDValue is returned.
377 SDValue distributeTruncateThroughAnd(SDNode *N);
380 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383 AttributeSet FnAttrs =
384 DAG.getMachineFunction().getFunction()->getAttributes();
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387 Attribute::OptimizeForSize) ||
388 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
391 /// Runs the dag combiner on all nodes in the work list
392 void Run(CombineLevel AtLevel);
394 SelectionDAG &getDAG() const { return DAG; }
396 /// Returns a type large enough to hold any valid shift amount - before type
397 /// legalization these can be huge.
398 EVT getShiftAmountTy(EVT LHSTy) {
399 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400 if (LHSTy.isVector())
402 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403 : TLI.getPointerTy();
406 /// This method returns true if we are running before type legalization or
407 /// if the specified VT is legal.
408 bool isTypeLegal(const EVT &VT) {
409 if (!LegalTypes) return true;
410 return TLI.isTypeLegal(VT);
413 /// Convenience wrapper around TargetLowering::getSetCCResultType
414 EVT getSetCCResultType(EVT VT) const {
415 return TLI.getSetCCResultType(*DAG.getContext(), VT);
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
427 explicit WorklistRemover(DAGCombiner &dc)
428 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
430 void NodeDeleted(SDNode *N, SDNode *E) override {
431 DC.removeFromWorklist(N);
436 //===----------------------------------------------------------------------===//
437 // TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441 ((DAGCombiner*)DC)->AddToWorklist(N);
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445 ((DAGCombiner*)DC)->removeFromWorklist(N);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
469 //===----------------------------------------------------------------------===//
471 //===----------------------------------------------------------------------===//
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474 removeFromWorklist(N);
476 // If the operands of this node are only used by the node, they will now be
477 // dead. Make sure to re-visit them and recursively delete dead nodes.
478 for (const SDValue &Op : N->ops())
479 // For an operand generating multiple values, one of the values may
480 // become dead allowing further simplification (e.g. split index
481 // arithmetic from an indexed load).
482 if (Op->hasOneUse() || Op->getNumValues() > 1)
483 AddToWorklist(Op.getNode());
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492 const TargetLowering &TLI,
493 const TargetOptions *Options,
494 unsigned Depth = 0) {
495 // fneg is removable even if it has multiple uses.
496 if (Op.getOpcode() == ISD::FNEG) return 2;
498 // Don't allow anything with multiple uses.
499 if (!Op.hasOneUse()) return 0;
501 // Don't recurse exponentially.
502 if (Depth > 6) return 0;
504 switch (Op.getOpcode()) {
505 default: return false;
506 case ISD::ConstantFP:
507 // Don't invert constant FP values after legalize. The negated constant
508 // isn't necessarily legal.
509 return LegalOperations ? 0 : 1;
511 // FIXME: determine better conditions for this xform.
512 if (!Options->UnsafeFPMath) return 0;
514 // After operation legalization, it might not be legal to create new FSUBs.
515 if (LegalOperations &&
516 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
519 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
527 // We can't turn -(A-B) into B-A when we honor signed zeros.
528 if (!Options->UnsafeFPMath) return 0;
530 // fold (fneg (fsub A, B)) -> (fsub B, A)
535 if (Options->HonorSignDependentRoundingFPMath()) return 0;
537 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
542 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555 bool LegalOperations, unsigned Depth = 0) {
556 const TargetOptions &Options = DAG.getTarget().Options;
557 // fneg is removable even if it has multiple uses.
558 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
560 // Don't allow anything with multiple uses.
561 assert(Op.hasOneUse() && "Unknown reuse!");
563 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564 switch (Op.getOpcode()) {
565 default: llvm_unreachable("Unknown code");
566 case ISD::ConstantFP: {
567 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
569 return DAG.getConstantFP(V, Op.getValueType());
572 // FIXME: determine better conditions for this xform.
573 assert(Options.UnsafeFPMath);
575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577 DAG.getTargetLoweringInfo(), &Options, Depth+1))
578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(0), DAG,
580 LegalOperations, Depth+1),
582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(1), DAG,
585 LegalOperations, Depth+1),
588 // We can't turn -(A-B) into B-A when we honor signed zeros.
589 assert(Options.UnsafeFPMath);
591 // fold (fneg (fsub 0, B)) -> B
592 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593 if (N0CFP->getValueAPF().isZero())
594 return Op.getOperand(1);
596 // fold (fneg (fsub A, B)) -> (fsub B, A)
597 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598 Op.getOperand(1), Op.getOperand(0));
602 assert(!Options.HonorSignDependentRoundingFPMath());
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606 DAG.getTargetLoweringInfo(), &Options, Depth+1))
607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608 GetNegatedExpression(Op.getOperand(0), DAG,
609 LegalOperations, Depth+1),
612 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
615 GetNegatedExpression(Op.getOperand(1), DAG,
616 LegalOperations, Depth+1));
620 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621 GetNegatedExpression(Op.getOperand(0), DAG,
622 LegalOperations, Depth+1));
624 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625 GetNegatedExpression(Op.getOperand(0), DAG,
626 LegalOperations, Depth+1),
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
638 if (N.getOpcode() == ISD::SETCC) {
639 LHS = N.getOperand(0);
640 RHS = N.getOperand(1);
641 CC = N.getOperand(2);
645 if (N.getOpcode() != ISD::SELECT_CC ||
646 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
650 if (TLI.getBooleanContents(N.getValueType()) ==
651 TargetLowering::UndefinedBooleanContent)
654 LHS = N.getOperand(0);
655 RHS = N.getOperand(1);
656 CC = N.getOperand(4);
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
665 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
678 unsigned SplatBitSize;
680 EVT EltVT = N->getValueType(0).getVectorElementType();
681 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
683 EltVT.getSizeInBits() >= SplatBitSize);
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688 if (isa<ConstantSDNode>(N))
690 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691 if (BV && BV->isConstant())
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703 BitVector UndefElements;
704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
706 // BuildVectors can truncate their operands. Ignore that case here.
707 // FIXME: We blindly ignore splats which include undef which is overly
709 if (CN && UndefElements.none() &&
710 CN->getValueType(0) == N.getValueType().getScalarType())
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
723 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724 BitVector UndefElements;
725 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
727 if (CN && UndefElements.none())
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735 SDValue N0, SDValue N1) {
736 EVT VT = N0.getValueType();
737 if (N0.getOpcode() == Opc) {
738 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742 if (!OpNode.getNode())
744 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
746 if (N0.hasOneUse()) {
747 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
749 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750 if (!OpNode.getNode())
752 AddToWorklist(OpNode.getNode());
753 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
758 if (N1.getOpcode() == Opc) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763 if (!OpNode.getNode())
765 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
767 if (N1.hasOneUse()) {
768 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771 if (!OpNode.getNode())
773 AddToWorklist(OpNode.getNode());
774 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
782 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
784 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
786 DEBUG(dbgs() << "\nReplacing.1 ";
788 dbgs() << "\nWith: ";
789 To[0].getNode()->dump(&DAG);
790 dbgs() << " and " << NumTo-1 << " other values\n";
791 for (unsigned i = 0, e = NumTo; i != e; ++i)
792 assert((!To[i].getNode() ||
793 N->getValueType(i) == To[i].getValueType()) &&
794 "Cannot combine value to value of different type!"));
795 WorklistRemover DeadNodes(*this);
796 DAG.ReplaceAllUsesWith(N, To);
798 // Push the new nodes and any users onto the worklist
799 for (unsigned i = 0, e = NumTo; i != e; ++i) {
800 if (To[i].getNode()) {
801 AddToWorklist(To[i].getNode());
802 AddUsersToWorklist(To[i].getNode());
807 // Finally, if the node is now dead, remove it from the graph. The node
808 // may not be dead if the replacement process recursively simplified to
809 // something else needing this node.
811 deleteAndRecombine(N);
812 return SDValue(N, 0);
816 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
817 // Replace all uses. If any nodes become isomorphic to other nodes and
818 // are deleted, make sure to remove them from our worklist.
819 WorklistRemover DeadNodes(*this);
820 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
822 // Push the new node and any (possibly new) users onto the worklist.
823 AddToWorklist(TLO.New.getNode());
824 AddUsersToWorklist(TLO.New.getNode());
826 // Finally, if the node is now dead, remove it from the graph. The node
827 // may not be dead if the replacement process recursively simplified to
828 // something else needing this node.
829 if (TLO.Old.getNode()->use_empty())
830 deleteAndRecombine(TLO.Old.getNode());
833 /// Check the specified integer node value to see if it can be simplified or if
834 /// things it uses can be simplified by bit propagation. If so, return true.
835 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
836 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
837 APInt KnownZero, KnownOne;
838 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
842 AddToWorklist(Op.getNode());
844 // Replace the old value with the new one.
846 DEBUG(dbgs() << "\nReplacing.2 ";
847 TLO.Old.getNode()->dump(&DAG);
848 dbgs() << "\nWith: ";
849 TLO.New.getNode()->dump(&DAG);
852 CommitTargetLoweringOpt(TLO);
856 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
858 EVT VT = Load->getValueType(0);
859 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
861 DEBUG(dbgs() << "\nReplacing.9 ";
863 dbgs() << "\nWith: ";
864 Trunc.getNode()->dump(&DAG);
866 WorklistRemover DeadNodes(*this);
867 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
868 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
869 deleteAndRecombine(Load);
870 AddToWorklist(Trunc.getNode());
873 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
877 EVT MemVT = LD->getMemoryVT();
878 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
879 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
881 : LD->getExtensionType();
883 return DAG.getExtLoad(ExtType, dl, PVT,
884 LD->getChain(), LD->getBasePtr(),
885 MemVT, LD->getMemOperand());
888 unsigned Opc = Op.getOpcode();
891 case ISD::AssertSext:
892 return DAG.getNode(ISD::AssertSext, dl, PVT,
893 SExtPromoteOperand(Op.getOperand(0), PVT),
895 case ISD::AssertZext:
896 return DAG.getNode(ISD::AssertZext, dl, PVT,
897 ZExtPromoteOperand(Op.getOperand(0), PVT),
899 case ISD::Constant: {
901 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
902 return DAG.getNode(ExtOpc, dl, PVT, Op);
906 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
908 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
911 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
912 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
914 EVT OldVT = Op.getValueType();
916 bool Replace = false;
917 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
918 if (!NewOp.getNode())
920 AddToWorklist(NewOp.getNode());
923 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
924 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
925 DAG.getValueType(OldVT));
928 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
929 EVT OldVT = Op.getValueType();
931 bool Replace = false;
932 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
933 if (!NewOp.getNode())
935 AddToWorklist(NewOp.getNode());
938 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
939 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
942 /// Promote the specified integer binary operation if the target indicates it is
943 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
944 /// i32 since i16 instructions are longer.
945 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
946 if (!LegalOperations)
949 EVT VT = Op.getValueType();
950 if (VT.isVector() || !VT.isInteger())
953 // If operation type is 'undesirable', e.g. i16 on x86, consider
955 unsigned Opc = Op.getOpcode();
956 if (TLI.isTypeDesirableForOp(Opc, VT))
960 // Consult target whether it is a good idea to promote this operation and
961 // what's the right type to promote it to.
962 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
963 assert(PVT != VT && "Don't know what type to promote to!");
965 bool Replace0 = false;
966 SDValue N0 = Op.getOperand(0);
967 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
971 bool Replace1 = false;
972 SDValue N1 = Op.getOperand(1);
977 NN1 = PromoteOperand(N1, PVT, Replace1);
982 AddToWorklist(NN0.getNode());
984 AddToWorklist(NN1.getNode());
987 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
989 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
991 DEBUG(dbgs() << "\nPromoting ";
992 Op.getNode()->dump(&DAG));
994 return DAG.getNode(ISD::TRUNCATE, dl, VT,
995 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1000 /// Promote the specified integer shift operation if the target indicates it is
1001 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1002 /// i32 since i16 instructions are longer.
1003 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1004 if (!LegalOperations)
1007 EVT VT = Op.getValueType();
1008 if (VT.isVector() || !VT.isInteger())
1011 // If operation type is 'undesirable', e.g. i16 on x86, consider
1013 unsigned Opc = Op.getOpcode();
1014 if (TLI.isTypeDesirableForOp(Opc, VT))
1018 // Consult target whether it is a good idea to promote this operation and
1019 // what's the right type to promote it to.
1020 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021 assert(PVT != VT && "Don't know what type to promote to!");
1023 bool Replace = false;
1024 SDValue N0 = Op.getOperand(0);
1025 if (Opc == ISD::SRA)
1026 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1027 else if (Opc == ISD::SRL)
1028 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1030 N0 = PromoteOperand(N0, PVT, Replace);
1034 AddToWorklist(N0.getNode());
1036 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1038 DEBUG(dbgs() << "\nPromoting ";
1039 Op.getNode()->dump(&DAG));
1041 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1042 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1047 SDValue DAGCombiner::PromoteExtend(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!");
1066 // fold (aext (aext x)) -> (aext x)
1067 // fold (aext (zext x)) -> (zext x)
1068 // fold (aext (sext x)) -> (sext x)
1069 DEBUG(dbgs() << "\nPromoting ";
1070 Op.getNode()->dump(&DAG));
1071 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1076 bool DAGCombiner::PromoteLoad(SDValue Op) {
1077 if (!LegalOperations)
1080 EVT VT = Op.getValueType();
1081 if (VT.isVector() || !VT.isInteger())
1084 // If operation type is 'undesirable', e.g. i16 on x86, consider
1086 unsigned Opc = Op.getOpcode();
1087 if (TLI.isTypeDesirableForOp(Opc, VT))
1091 // Consult target whether it is a good idea to promote this operation and
1092 // what's the right type to promote it to.
1093 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1094 assert(PVT != VT && "Don't know what type to promote to!");
1097 SDNode *N = Op.getNode();
1098 LoadSDNode *LD = cast<LoadSDNode>(N);
1099 EVT MemVT = LD->getMemoryVT();
1100 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1101 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1103 : LD->getExtensionType();
1104 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1105 LD->getChain(), LD->getBasePtr(),
1106 MemVT, LD->getMemOperand());
1107 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1109 DEBUG(dbgs() << "\nPromoting ";
1112 Result.getNode()->dump(&DAG);
1114 WorklistRemover DeadNodes(*this);
1115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1116 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1117 deleteAndRecombine(N);
1118 AddToWorklist(Result.getNode());
1124 /// \brief Recursively delete a node which has no uses and any operands for
1125 /// which it is the only use.
1127 /// Note that this both deletes the nodes and removes them from the worklist.
1128 /// It also adds any nodes who have had a user deleted to the worklist as they
1129 /// may now have only one use and subject to other combines.
1130 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1131 if (!N->use_empty())
1134 SmallSetVector<SDNode *, 16> Nodes;
1137 N = Nodes.pop_back_val();
1141 if (N->use_empty()) {
1142 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1143 Nodes.insert(N->getOperand(i).getNode());
1145 removeFromWorklist(N);
1150 } while (!Nodes.empty());
1154 //===----------------------------------------------------------------------===//
1155 // Main DAG Combiner implementation
1156 //===----------------------------------------------------------------------===//
1158 void DAGCombiner::Run(CombineLevel AtLevel) {
1159 // set the instance variables, so that the various visit routines may use it.
1161 LegalOperations = Level >= AfterLegalizeVectorOps;
1162 LegalTypes = Level >= AfterLegalizeTypes;
1164 // Early exit if this basic block is in an optnone function.
1165 AttributeSet FnAttrs =
1166 DAG.getMachineFunction().getFunction()->getAttributes();
1167 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1168 Attribute::OptimizeNone))
1171 // Add all the dag nodes to the worklist.
1172 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1173 E = DAG.allnodes_end(); I != E; ++I)
1176 // Create a dummy node (which is not added to allnodes), that adds a reference
1177 // to the root node, preventing it from being deleted, and tracking any
1178 // changes of the root.
1179 HandleSDNode Dummy(DAG.getRoot());
1181 // while the worklist isn't empty, find a node and
1182 // try and combine it.
1183 while (!WorklistMap.empty()) {
1185 // The Worklist holds the SDNodes in order, but it may contain null entries.
1187 N = Worklist.pop_back_val();
1190 bool GoodWorklistEntry = WorklistMap.erase(N);
1191 (void)GoodWorklistEntry;
1192 assert(GoodWorklistEntry &&
1193 "Found a worklist entry without a corresponding map entry!");
1195 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1196 // N is deleted from the DAG, since they too may now be dead or may have a
1197 // reduced number of uses, allowing other xforms.
1198 if (recursivelyDeleteUnusedNodes(N))
1201 WorklistRemover DeadNodes(*this);
1203 // If this combine is running after legalizing the DAG, re-legalize any
1204 // nodes pulled off the worklist.
1205 if (Level == AfterLegalizeDAG) {
1206 SmallSetVector<SDNode *, 16> UpdatedNodes;
1207 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1209 for (SDNode *LN : UpdatedNodes) {
1211 AddUsersToWorklist(LN);
1217 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1219 // Add any operands of the new node which have not yet been combined to the
1220 // worklist as well. Because the worklist uniques things already, this
1221 // won't repeatedly process the same operand.
1222 CombinedNodes.insert(N);
1223 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1224 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1225 AddToWorklist(N->getOperand(i).getNode());
1227 SDValue RV = combine(N);
1234 // If we get back the same node we passed in, rather than a new node or
1235 // zero, we know that the node must have defined multiple values and
1236 // CombineTo was used. Since CombineTo takes care of the worklist
1237 // mechanics for us, we have no work to do in this case.
1238 if (RV.getNode() == N)
1241 assert(N->getOpcode() != ISD::DELETED_NODE &&
1242 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1243 "Node was deleted but visit returned new node!");
1245 DEBUG(dbgs() << " ... into: ";
1246 RV.getNode()->dump(&DAG));
1248 // Transfer debug value.
1249 DAG.TransferDbgValues(SDValue(N, 0), RV);
1250 if (N->getNumValues() == RV.getNode()->getNumValues())
1251 DAG.ReplaceAllUsesWith(N, RV.getNode());
1253 assert(N->getValueType(0) == RV.getValueType() &&
1254 N->getNumValues() == 1 && "Type mismatch");
1256 DAG.ReplaceAllUsesWith(N, &OpV);
1259 // Push the new node and any users onto the worklist
1260 AddToWorklist(RV.getNode());
1261 AddUsersToWorklist(RV.getNode());
1263 // Finally, if the node is now dead, remove it from the graph. The node
1264 // may not be dead if the replacement process recursively simplified to
1265 // something else needing this node. This will also take care of adding any
1266 // operands which have lost a user to the worklist.
1267 recursivelyDeleteUnusedNodes(N);
1270 // If the root changed (e.g. it was a dead load, update the root).
1271 DAG.setRoot(Dummy.getValue());
1272 DAG.RemoveDeadNodes();
1275 SDValue DAGCombiner::visit(SDNode *N) {
1276 switch (N->getOpcode()) {
1278 case ISD::TokenFactor: return visitTokenFactor(N);
1279 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1280 case ISD::ADD: return visitADD(N);
1281 case ISD::SUB: return visitSUB(N);
1282 case ISD::ADDC: return visitADDC(N);
1283 case ISD::SUBC: return visitSUBC(N);
1284 case ISD::ADDE: return visitADDE(N);
1285 case ISD::SUBE: return visitSUBE(N);
1286 case ISD::MUL: return visitMUL(N);
1287 case ISD::SDIV: return visitSDIV(N);
1288 case ISD::UDIV: return visitUDIV(N);
1289 case ISD::SREM: return visitSREM(N);
1290 case ISD::UREM: return visitUREM(N);
1291 case ISD::MULHU: return visitMULHU(N);
1292 case ISD::MULHS: return visitMULHS(N);
1293 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1294 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1295 case ISD::SMULO: return visitSMULO(N);
1296 case ISD::UMULO: return visitUMULO(N);
1297 case ISD::SDIVREM: return visitSDIVREM(N);
1298 case ISD::UDIVREM: return visitUDIVREM(N);
1299 case ISD::AND: return visitAND(N);
1300 case ISD::OR: return visitOR(N);
1301 case ISD::XOR: return visitXOR(N);
1302 case ISD::SHL: return visitSHL(N);
1303 case ISD::SRA: return visitSRA(N);
1304 case ISD::SRL: return visitSRL(N);
1306 case ISD::ROTL: return visitRotate(N);
1307 case ISD::CTLZ: return visitCTLZ(N);
1308 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1309 case ISD::CTTZ: return visitCTTZ(N);
1310 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1311 case ISD::CTPOP: return visitCTPOP(N);
1312 case ISD::SELECT: return visitSELECT(N);
1313 case ISD::VSELECT: return visitVSELECT(N);
1314 case ISD::SELECT_CC: return visitSELECT_CC(N);
1315 case ISD::SETCC: return visitSETCC(N);
1316 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1317 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1318 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1319 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1320 case ISD::TRUNCATE: return visitTRUNCATE(N);
1321 case ISD::BITCAST: return visitBITCAST(N);
1322 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1323 case ISD::FADD: return visitFADD(N);
1324 case ISD::FSUB: return visitFSUB(N);
1325 case ISD::FMUL: return visitFMUL(N);
1326 case ISD::FMA: return visitFMA(N);
1327 case ISD::FDIV: return visitFDIV(N);
1328 case ISD::FREM: return visitFREM(N);
1329 case ISD::FSQRT: return visitFSQRT(N);
1330 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1331 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1332 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1333 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1334 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1335 case ISD::FP_ROUND: return visitFP_ROUND(N);
1336 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1337 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1338 case ISD::FNEG: return visitFNEG(N);
1339 case ISD::FABS: return visitFABS(N);
1340 case ISD::FFLOOR: return visitFFLOOR(N);
1341 case ISD::FMINNUM: return visitFMINNUM(N);
1342 case ISD::FMAXNUM: return visitFMAXNUM(N);
1343 case ISD::FCEIL: return visitFCEIL(N);
1344 case ISD::FTRUNC: return visitFTRUNC(N);
1345 case ISD::BRCOND: return visitBRCOND(N);
1346 case ISD::BR_CC: return visitBR_CC(N);
1347 case ISD::LOAD: return visitLOAD(N);
1348 case ISD::STORE: return visitSTORE(N);
1349 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1350 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1351 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1352 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1353 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1354 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1355 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1356 case ISD::MLOAD: return visitMLOAD(N);
1357 case ISD::MSTORE: return visitMSTORE(N);
1362 SDValue DAGCombiner::combine(SDNode *N) {
1363 SDValue RV = visit(N);
1365 // If nothing happened, try a target-specific DAG combine.
1366 if (!RV.getNode()) {
1367 assert(N->getOpcode() != ISD::DELETED_NODE &&
1368 "Node was deleted but visit returned NULL!");
1370 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1371 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1373 // Expose the DAG combiner to the target combiner impls.
1374 TargetLowering::DAGCombinerInfo
1375 DagCombineInfo(DAG, Level, false, this);
1377 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1381 // If nothing happened still, try promoting the operation.
1382 if (!RV.getNode()) {
1383 switch (N->getOpcode()) {
1391 RV = PromoteIntBinOp(SDValue(N, 0));
1396 RV = PromoteIntShiftOp(SDValue(N, 0));
1398 case ISD::SIGN_EXTEND:
1399 case ISD::ZERO_EXTEND:
1400 case ISD::ANY_EXTEND:
1401 RV = PromoteExtend(SDValue(N, 0));
1404 if (PromoteLoad(SDValue(N, 0)))
1410 // If N is a commutative binary node, try commuting it to enable more
1412 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1413 N->getNumValues() == 1) {
1414 SDValue N0 = N->getOperand(0);
1415 SDValue N1 = N->getOperand(1);
1417 // Constant operands are canonicalized to RHS.
1418 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1419 SDValue Ops[] = {N1, N0};
1421 if (const BinaryWithFlagsSDNode *BinNode =
1422 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1423 CSENode = DAG.getNodeIfExists(
1424 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1425 BinNode->hasNoSignedWrap(), BinNode->isExact());
1427 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1430 return SDValue(CSENode, 0);
1437 /// Given a node, return its input chain if it has one, otherwise return a null
1439 static SDValue getInputChainForNode(SDNode *N) {
1440 if (unsigned NumOps = N->getNumOperands()) {
1441 if (N->getOperand(0).getValueType() == MVT::Other)
1442 return N->getOperand(0);
1443 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1444 return N->getOperand(NumOps-1);
1445 for (unsigned i = 1; i < NumOps-1; ++i)
1446 if (N->getOperand(i).getValueType() == MVT::Other)
1447 return N->getOperand(i);
1452 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1453 // If N has two operands, where one has an input chain equal to the other,
1454 // the 'other' chain is redundant.
1455 if (N->getNumOperands() == 2) {
1456 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1457 return N->getOperand(0);
1458 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1459 return N->getOperand(1);
1462 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1463 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1464 SmallPtrSet<SDNode*, 16> SeenOps;
1465 bool Changed = false; // If we should replace this token factor.
1467 // Start out with this token factor.
1470 // Iterate through token factors. The TFs grows when new token factors are
1472 for (unsigned i = 0; i < TFs.size(); ++i) {
1473 SDNode *TF = TFs[i];
1475 // Check each of the operands.
1476 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1477 SDValue Op = TF->getOperand(i);
1479 switch (Op.getOpcode()) {
1480 case ISD::EntryToken:
1481 // Entry tokens don't need to be added to the list. They are
1486 case ISD::TokenFactor:
1487 if (Op.hasOneUse() &&
1488 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1489 // Queue up for processing.
1490 TFs.push_back(Op.getNode());
1491 // Clean up in case the token factor is removed.
1492 AddToWorklist(Op.getNode());
1499 // Only add if it isn't already in the list.
1500 if (SeenOps.insert(Op.getNode()).second)
1511 // If we've change things around then replace token factor.
1514 // The entry token is the only possible outcome.
1515 Result = DAG.getEntryNode();
1517 // New and improved token factor.
1518 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1521 // Don't add users to work list.
1522 return CombineTo(N, Result, false);
1528 /// MERGE_VALUES can always be eliminated.
1529 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1530 WorklistRemover DeadNodes(*this);
1531 // Replacing results may cause a different MERGE_VALUES to suddenly
1532 // be CSE'd with N, and carry its uses with it. Iterate until no
1533 // uses remain, to ensure that the node can be safely deleted.
1534 // First add the users of this node to the work list so that they
1535 // can be tried again once they have new operands.
1536 AddUsersToWorklist(N);
1538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1540 } while (!N->use_empty());
1541 deleteAndRecombine(N);
1542 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1545 SDValue DAGCombiner::visitADD(SDNode *N) {
1546 SDValue N0 = N->getOperand(0);
1547 SDValue N1 = N->getOperand(1);
1548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1549 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1550 EVT VT = N0.getValueType();
1553 if (VT.isVector()) {
1554 SDValue FoldedVOp = SimplifyVBinOp(N);
1555 if (FoldedVOp.getNode()) return FoldedVOp;
1557 // fold (add x, 0) -> x, vector edition
1558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1564 // fold (add x, undef) -> undef
1565 if (N0.getOpcode() == ISD::UNDEF)
1567 if (N1.getOpcode() == ISD::UNDEF)
1569 // fold (add c1, c2) -> c1+c2
1571 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1572 // canonicalize constant to RHS
1574 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1575 // fold (add x, 0) -> x
1576 if (N1C && N1C->isNullValue())
1578 // fold (add Sym, c) -> Sym+c
1579 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1580 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1581 GA->getOpcode() == ISD::GlobalAddress)
1582 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584 (uint64_t)N1C->getSExtValue());
1585 // fold ((c1-A)+c2) -> (c1+c2)-A
1586 if (N1C && N0.getOpcode() == ISD::SUB)
1587 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1588 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1589 DAG.getConstant(N1C->getAPIntValue()+
1590 N0C->getAPIntValue(), VT),
1593 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1596 // fold ((0-A) + B) -> B-A
1597 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1598 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1600 // fold (A + (0-B)) -> A-B
1601 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1602 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1603 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1604 // fold (A+(B-A)) -> B
1605 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1606 return N1.getOperand(0);
1607 // fold ((B-A)+A) -> B
1608 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1609 return N0.getOperand(0);
1610 // fold (A+(B-(A+C))) to (B-C)
1611 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1612 N0 == N1.getOperand(1).getOperand(0))
1613 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1614 N1.getOperand(1).getOperand(1));
1615 // fold (A+(B-(C+A))) to (B-C)
1616 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1617 N0 == N1.getOperand(1).getOperand(1))
1618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1619 N1.getOperand(1).getOperand(0));
1620 // fold (A+((B-A)+or-C)) to (B+or-C)
1621 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1622 N1.getOperand(0).getOpcode() == ISD::SUB &&
1623 N0 == N1.getOperand(0).getOperand(1))
1624 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1625 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1628 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1629 SDValue N00 = N0.getOperand(0);
1630 SDValue N01 = N0.getOperand(1);
1631 SDValue N10 = N1.getOperand(0);
1632 SDValue N11 = N1.getOperand(1);
1634 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1635 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1636 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1637 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1640 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1641 return SDValue(N, 0);
1643 // fold (a+b) -> (a|b) iff a and b share no bits.
1644 if (VT.isInteger() && !VT.isVector()) {
1645 APInt LHSZero, LHSOne;
1646 APInt RHSZero, RHSOne;
1647 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649 if (LHSZero.getBoolValue()) {
1650 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1653 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1654 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1655 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1656 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1661 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1662 if (N1.getOpcode() == ISD::SHL &&
1663 N1.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
1667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669 N1.getOperand(0).getOperand(1),
1671 if (N0.getOpcode() == ISD::SHL &&
1672 N0.getOperand(0).getOpcode() == ISD::SUB)
1673 if (ConstantSDNode *C =
1674 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1675 if (C->getAPIntValue() == 0)
1676 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1677 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1678 N0.getOperand(0).getOperand(1),
1681 if (N1.getOpcode() == ISD::AND) {
1682 SDValue AndOp0 = N1.getOperand(0);
1683 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1684 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1685 unsigned DestBits = VT.getScalarType().getSizeInBits();
1687 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1688 // and similar xforms where the inner op is either ~0 or 0.
1689 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1691 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1695 // add (sext i1), X -> sub X, (zext i1)
1696 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1697 N0.getOperand(0).getValueType() == MVT::i1 &&
1698 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1700 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1701 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1704 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1705 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1706 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1707 if (TN->getVT() == MVT::i1) {
1709 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1710 DAG.getConstant(1, VT));
1711 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719 SDValue N0 = N->getOperand(0);
1720 SDValue N1 = N->getOperand(1);
1721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723 EVT VT = N0.getValueType();
1725 // If the flag result is dead, turn this into an ADD.
1726 if (!N->hasAnyUseOfValue(1))
1727 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728 DAG.getNode(ISD::CARRY_FALSE,
1729 SDLoc(N), MVT::Glue));
1731 // canonicalize constant to RHS.
1733 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735 // fold (addc x, 0) -> x + no carry out
1736 if (N1C && N1C->isNullValue())
1737 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738 SDLoc(N), MVT::Glue));
1740 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741 APInt LHSZero, LHSOne;
1742 APInt RHSZero, RHSOne;
1743 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745 if (LHSZero.getBoolValue()) {
1746 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752 DAG.getNode(ISD::CARRY_FALSE,
1753 SDLoc(N), MVT::Glue));
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 SDValue CarryIn = N->getOperand(2);
1763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766 // canonicalize constant to RHS
1768 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1771 // fold (adde x, y, false) -> (addc x, y)
1772 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782 bool LegalOperations, bool LegalTypes) {
1784 return DAG.getConstant(0, VT);
1785 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786 return DAG.getConstant(0, VT);
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
1793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797 EVT VT = N0.getValueType();
1800 if (VT.isVector()) {
1801 SDValue FoldedVOp = SimplifyVBinOp(N);
1802 if (FoldedVOp.getNode()) return FoldedVOp;
1804 // fold (sub x, 0) -> x, vector edition
1805 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1809 // fold (sub x, x) -> 0
1810 // FIXME: Refactor this and xor and other similar operations together.
1812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813 // fold (sub c1, c2) -> c1-c2
1815 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816 // fold (sub x, c) -> (add x, -c)
1818 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819 DAG.getConstant(-N1C->getAPIntValue(), VT));
1820 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821 if (N0C && N0C->isAllOnesValue())
1822 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823 // fold A-(A-B) -> B
1824 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825 return N1.getOperand(1);
1826 // fold (A+B)-A -> B
1827 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828 return N0.getOperand(1);
1829 // fold (A+B)-B -> A
1830 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831 return N0.getOperand(0);
1832 // fold C2-(A+C1) -> (C2-C1)-A
1833 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1839 // fold ((A+(B+or-C))-B) -> A+or-C
1840 if (N0.getOpcode() == ISD::ADD &&
1841 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843 N0.getOperand(1).getOperand(0) == N1)
1844 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846 // fold ((A+(C+B))-B) -> A+C
1847 if (N0.getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOperand(1) == N1)
1850 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852 // fold ((A-(B-C))-C) -> A-B
1853 if (N0.getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOperand(1) == N1)
1856 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859 // If either operand of a sub is undef, the result is undef
1860 if (N0.getOpcode() == ISD::UNDEF)
1862 if (N1.getOpcode() == ISD::UNDEF)
1865 // If the relocation model supports it, consider symbol offsets.
1866 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868 // fold (sub Sym, c) -> Sym-c
1869 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872 (uint64_t)N1C->getSExtValue());
1873 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875 if (GA->getGlobal() == GB->getGlobal())
1876 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1880 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1881 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1882 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1883 if (TN->getVT() == MVT::i1) {
1885 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1886 DAG.getConstant(1, VT));
1887 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1894 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1895 SDValue N0 = N->getOperand(0);
1896 SDValue N1 = N->getOperand(1);
1897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899 EVT VT = N0.getValueType();
1901 // If the flag result is dead, turn this into an SUB.
1902 if (!N->hasAnyUseOfValue(1))
1903 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1904 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907 // fold (subc x, x) -> 0 + no borrow
1909 return CombineTo(N, DAG.getConstant(0, VT),
1910 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1913 // fold (subc x, 0) -> x + no borrow
1914 if (N1C && N1C->isNullValue())
1915 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1918 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1919 if (N0C && N0C->isAllOnesValue())
1920 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1921 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
1930 SDValue CarryIn = N->getOperand(2);
1932 // fold (sube x, y, false) -> (subc x, y)
1933 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1934 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1939 SDValue DAGCombiner::visitMUL(SDNode *N) {
1940 SDValue N0 = N->getOperand(0);
1941 SDValue N1 = N->getOperand(1);
1942 EVT VT = N0.getValueType();
1944 // fold (mul x, undef) -> 0
1945 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1946 return DAG.getConstant(0, VT);
1948 bool N0IsConst = false;
1949 bool N1IsConst = false;
1950 APInt ConstValue0, ConstValue1;
1952 if (VT.isVector()) {
1953 SDValue FoldedVOp = SimplifyVBinOp(N);
1954 if (FoldedVOp.getNode()) return FoldedVOp;
1956 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1957 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1959 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1960 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1962 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1963 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1967 // fold (mul c1, c2) -> c1*c2
1968 if (N0IsConst && N1IsConst)
1969 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1971 // canonicalize constant to RHS
1972 if (N0IsConst && !N1IsConst)
1973 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1974 // fold (mul x, 0) -> 0
1975 if (N1IsConst && ConstValue1 == 0)
1977 // We require a splat of the entire scalar bit width for non-contiguous
1980 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1981 // fold (mul x, 1) -> x
1982 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1984 // fold (mul x, -1) -> 0-x
1985 if (N1IsConst && ConstValue1.isAllOnesValue())
1986 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1987 DAG.getConstant(0, VT), N0);
1988 // fold (mul x, (1 << c)) -> x << c
1989 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1990 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991 DAG.getConstant(ConstValue1.logBase2(),
1992 getShiftAmountTy(N0.getValueType())));
1993 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1994 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1995 unsigned Log2Val = (-ConstValue1).logBase2();
1996 // FIXME: If the input is something that is easily negated (e.g. a
1997 // single-use add), we should put the negate there.
1998 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1999 DAG.getConstant(0, VT),
2000 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2001 DAG.getConstant(Log2Val,
2002 getShiftAmountTy(N0.getValueType()))));
2006 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2007 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2008 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009 isa<ConstantSDNode>(N0.getOperand(1)))) {
2010 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2011 N1, N0.getOperand(1));
2012 AddToWorklist(C3.getNode());
2013 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2014 N0.getOperand(0), C3);
2017 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2020 SDValue Sh(nullptr,0), Y(nullptr,0);
2021 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2022 if (N0.getOpcode() == ISD::SHL &&
2023 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2024 isa<ConstantSDNode>(N0.getOperand(1))) &&
2025 N0.getNode()->hasOneUse()) {
2027 } else if (N1.getOpcode() == ISD::SHL &&
2028 isa<ConstantSDNode>(N1.getOperand(1)) &&
2029 N1.getNode()->hasOneUse()) {
2034 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2035 Sh.getOperand(0), Y);
2036 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2037 Mul, Sh.getOperand(1));
2041 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2042 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044 isa<ConstantSDNode>(N0.getOperand(1))))
2045 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2046 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2047 N0.getOperand(0), N1),
2048 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2049 N0.getOperand(1), N1));
2052 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2059 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2060 SDValue N0 = N->getOperand(0);
2061 SDValue N1 = N->getOperand(1);
2062 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2063 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2064 EVT VT = N->getValueType(0);
2067 if (VT.isVector()) {
2068 SDValue FoldedVOp = SimplifyVBinOp(N);
2069 if (FoldedVOp.getNode()) return FoldedVOp;
2072 // fold (sdiv c1, c2) -> c1/c2
2073 if (N0C && N1C && !N1C->isNullValue())
2074 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2075 // fold (sdiv X, 1) -> X
2076 if (N1C && N1C->getAPIntValue() == 1LL)
2078 // fold (sdiv X, -1) -> 0-X
2079 if (N1C && N1C->isAllOnesValue())
2080 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2081 DAG.getConstant(0, VT), N0);
2082 // If we know the sign bits of both operands are zero, strength reduce to a
2083 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2084 if (!VT.isVector()) {
2085 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2086 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2090 // fold (sdiv X, pow2) -> simple ops after legalize
2091 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2092 (-N1C->getAPIntValue()).isPowerOf2())) {
2093 // If dividing by powers of two is cheap, then don't perform the following
2095 if (TLI.isPow2SDivCheap())
2098 // Target-specific implementation of sdiv x, pow2.
2099 SDValue Res = BuildSDIVPow2(N);
2103 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2105 // Splat the sign bit into the register
2107 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2108 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2109 getShiftAmountTy(N0.getValueType())));
2110 AddToWorklist(SGN.getNode());
2112 // Add (N0 < 0) ? abs2 - 1 : 0;
2114 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2115 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2116 getShiftAmountTy(SGN.getValueType())));
2117 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2118 AddToWorklist(SRL.getNode());
2119 AddToWorklist(ADD.getNode()); // Divide by pow2
2120 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2121 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2123 // If we're dividing by a positive value, we're done. Otherwise, we must
2124 // negate the result.
2125 if (N1C->getAPIntValue().isNonNegative())
2128 AddToWorklist(SRA.getNode());
2129 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2132 // if integer divide is expensive and we satisfy the requirements, emit an
2133 // alternate sequence.
2134 if (N1C && !TLI.isIntDivCheap()) {
2135 SDValue Op = BuildSDIV(N);
2136 if (Op.getNode()) return Op;
2140 if (N0.getOpcode() == ISD::UNDEF)
2141 return DAG.getConstant(0, VT);
2142 // X / undef -> undef
2143 if (N1.getOpcode() == ISD::UNDEF)
2149 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2150 SDValue N0 = N->getOperand(0);
2151 SDValue N1 = N->getOperand(1);
2152 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2153 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2154 EVT VT = N->getValueType(0);
2157 if (VT.isVector()) {
2158 SDValue FoldedVOp = SimplifyVBinOp(N);
2159 if (FoldedVOp.getNode()) return FoldedVOp;
2162 // fold (udiv c1, c2) -> c1/c2
2163 if (N0C && N1C && !N1C->isNullValue())
2164 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2165 // fold (udiv x, (1 << c)) -> x >>u c
2166 if (N1C && N1C->getAPIntValue().isPowerOf2())
2167 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2168 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2169 getShiftAmountTy(N0.getValueType())));
2170 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2171 if (N1.getOpcode() == ISD::SHL) {
2172 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2173 if (SHC->getAPIntValue().isPowerOf2()) {
2174 EVT ADDVT = N1.getOperand(1).getValueType();
2175 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2177 DAG.getConstant(SHC->getAPIntValue()
2180 AddToWorklist(Add.getNode());
2181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2185 // fold (udiv x, c) -> alternate
2186 if (N1C && !TLI.isIntDivCheap()) {
2187 SDValue Op = BuildUDIV(N);
2188 if (Op.getNode()) return Op;
2192 if (N0.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2194 // X / undef -> undef
2195 if (N1.getOpcode() == ISD::UNDEF)
2201 SDValue DAGCombiner::visitSREM(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
2204 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2206 EVT VT = N->getValueType(0);
2208 // fold (srem c1, c2) -> c1%c2
2209 if (N0C && N1C && !N1C->isNullValue())
2210 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2211 // If we know the sign bits of both operands are zero, strength reduce to a
2212 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2213 if (!VT.isVector()) {
2214 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2215 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2218 // If X/C can be simplified by the division-by-constant logic, lower
2219 // X%C to the equivalent of X-X/C*C.
2220 if (N1C && !N1C->isNullValue()) {
2221 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2222 AddToWorklist(Div.getNode());
2223 SDValue OptimizedDiv = combine(Div.getNode());
2224 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2225 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2227 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2228 AddToWorklist(Mul.getNode());
2234 if (N0.getOpcode() == ISD::UNDEF)
2235 return DAG.getConstant(0, VT);
2236 // X % undef -> undef
2237 if (N1.getOpcode() == ISD::UNDEF)
2243 SDValue DAGCombiner::visitUREM(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
2246 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2247 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2248 EVT VT = N->getValueType(0);
2250 // fold (urem c1, c2) -> c1%c2
2251 if (N0C && N1C && !N1C->isNullValue())
2252 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2253 // fold (urem x, pow2) -> (and x, pow2-1)
2254 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2255 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2256 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2257 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2258 if (N1.getOpcode() == ISD::SHL) {
2259 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2260 if (SHC->getAPIntValue().isPowerOf2()) {
2262 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2263 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2265 AddToWorklist(Add.getNode());
2266 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2271 // If X/C can be simplified by the division-by-constant logic, lower
2272 // X%C to the equivalent of X-X/C*C.
2273 if (N1C && !N1C->isNullValue()) {
2274 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2275 AddToWorklist(Div.getNode());
2276 SDValue OptimizedDiv = combine(Div.getNode());
2277 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281 AddToWorklist(Mul.getNode());
2287 if (N0.getOpcode() == ISD::UNDEF)
2288 return DAG.getConstant(0, VT);
2289 // X % undef -> undef
2290 if (N1.getOpcode() == ISD::UNDEF)
2296 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2297 SDValue N0 = N->getOperand(0);
2298 SDValue N1 = N->getOperand(1);
2299 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2300 EVT VT = N->getValueType(0);
2303 // fold (mulhs x, 0) -> 0
2304 if (N1C && N1C->isNullValue())
2306 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2307 if (N1C && N1C->getAPIntValue() == 1)
2308 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2309 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2310 getShiftAmountTy(N0.getValueType())));
2311 // fold (mulhs x, undef) -> 0
2312 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2313 return DAG.getConstant(0, VT);
2315 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2317 if (VT.isSimple() && !VT.isVector()) {
2318 MVT Simple = VT.getSimpleVT();
2319 unsigned SimpleSize = Simple.getSizeInBits();
2320 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2323 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2324 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2325 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2326 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2327 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2334 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2335 SDValue N0 = N->getOperand(0);
2336 SDValue N1 = N->getOperand(1);
2337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2338 EVT VT = N->getValueType(0);
2341 // fold (mulhu x, 0) -> 0
2342 if (N1C && N1C->isNullValue())
2344 // fold (mulhu x, 1) -> 0
2345 if (N1C && N1C->getAPIntValue() == 1)
2346 return DAG.getConstant(0, N0.getValueType());
2347 // fold (mulhu x, undef) -> 0
2348 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2349 return DAG.getConstant(0, VT);
2351 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353 if (VT.isSimple() && !VT.isVector()) {
2354 MVT Simple = VT.getSimpleVT();
2355 unsigned SimpleSize = Simple.getSizeInBits();
2356 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2359 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2360 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2361 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2362 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2363 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2370 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2371 /// give the opcodes for the two computations that are being performed. Return
2372 /// true if a simplification was made.
2373 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2375 // If the high half is not needed, just compute the low half.
2376 bool HiExists = N->hasAnyUseOfValue(1);
2378 (!LegalOperations ||
2379 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2380 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2381 return CombineTo(N, Res, Res);
2384 // If the low half is not needed, just compute the high half.
2385 bool LoExists = N->hasAnyUseOfValue(0);
2387 (!LegalOperations ||
2388 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2389 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2390 return CombineTo(N, Res, Res);
2393 // If both halves are used, return as it is.
2394 if (LoExists && HiExists)
2397 // If the two computed results can be simplified separately, separate them.
2399 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2400 AddToWorklist(Lo.getNode());
2401 SDValue LoOpt = combine(Lo.getNode());
2402 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2403 (!LegalOperations ||
2404 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2405 return CombineTo(N, LoOpt, LoOpt);
2409 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2410 AddToWorklist(Hi.getNode());
2411 SDValue HiOpt = combine(Hi.getNode());
2412 if (HiOpt.getNode() && HiOpt != Hi &&
2413 (!LegalOperations ||
2414 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2415 return CombineTo(N, HiOpt, HiOpt);
2421 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2423 if (Res.getNode()) return Res;
2425 EVT VT = N->getValueType(0);
2428 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2430 if (VT.isSimple() && !VT.isVector()) {
2431 MVT Simple = VT.getSimpleVT();
2432 unsigned SimpleSize = Simple.getSizeInBits();
2433 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2436 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2437 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438 // Compute the high part as N1.
2439 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2440 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2441 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442 // Compute the low part as N0.
2443 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444 return CombineTo(N, Lo, Hi);
2451 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2452 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2453 if (Res.getNode()) return Res;
2455 EVT VT = N->getValueType(0);
2458 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460 if (VT.isSimple() && !VT.isVector()) {
2461 MVT Simple = VT.getSimpleVT();
2462 unsigned SimpleSize = Simple.getSizeInBits();
2463 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2466 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2467 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2468 // Compute the high part as N1.
2469 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2470 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2471 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2472 // Compute the low part as N0.
2473 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2474 return CombineTo(N, Lo, Hi);
2481 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2482 // (smulo x, 2) -> (saddo x, x)
2483 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484 if (C2->getAPIntValue() == 2)
2485 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2486 N->getOperand(0), N->getOperand(0));
2491 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2492 // (umulo x, 2) -> (uaddo x, x)
2493 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2494 if (C2->getAPIntValue() == 2)
2495 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2496 N->getOperand(0), N->getOperand(0));
2501 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2502 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2503 if (Res.getNode()) return Res;
2508 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2509 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2510 if (Res.getNode()) return Res;
2515 /// If this is a binary operator with two operands of the same opcode, try to
2517 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2518 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2519 EVT VT = N0.getValueType();
2520 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2522 // Bail early if none of these transforms apply.
2523 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2525 // For each of OP in AND/OR/XOR:
2526 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2527 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2528 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2529 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2531 // do not sink logical op inside of a vector extend, since it may combine
2533 EVT Op0VT = N0.getOperand(0).getValueType();
2534 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2535 N0.getOpcode() == ISD::SIGN_EXTEND ||
2536 // Avoid infinite looping with PromoteIntBinOp.
2537 (N0.getOpcode() == ISD::ANY_EXTEND &&
2538 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2539 (N0.getOpcode() == ISD::TRUNCATE &&
2540 (!TLI.isZExtFree(VT, Op0VT) ||
2541 !TLI.isTruncateFree(Op0VT, VT)) &&
2542 TLI.isTypeLegal(Op0VT))) &&
2544 Op0VT == N1.getOperand(0).getValueType() &&
2545 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2546 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2547 N0.getOperand(0).getValueType(),
2548 N0.getOperand(0), N1.getOperand(0));
2549 AddToWorklist(ORNode.getNode());
2550 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2553 // For each of OP in SHL/SRL/SRA/AND...
2554 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2555 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2556 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2557 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2558 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2559 N0.getOperand(1) == N1.getOperand(1)) {
2560 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2561 N0.getOperand(0).getValueType(),
2562 N0.getOperand(0), N1.getOperand(0));
2563 AddToWorklist(ORNode.getNode());
2564 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2565 ORNode, N0.getOperand(1));
2568 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2569 // Only perform this optimization after type legalization and before
2570 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2571 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2572 // we don't want to undo this promotion.
2573 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2575 if ((N0.getOpcode() == ISD::BITCAST ||
2576 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2577 Level == AfterLegalizeTypes) {
2578 SDValue In0 = N0.getOperand(0);
2579 SDValue In1 = N1.getOperand(0);
2580 EVT In0Ty = In0.getValueType();
2581 EVT In1Ty = In1.getValueType();
2583 // If both incoming values are integers, and the original types are the
2585 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2586 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2587 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2588 AddToWorklist(Op.getNode());
2593 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2594 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2595 // If both shuffles use the same mask, and both shuffle within a single
2596 // vector, then it is worthwhile to move the swizzle after the operation.
2597 // The type-legalizer generates this pattern when loading illegal
2598 // vector types from memory. In many cases this allows additional shuffle
2600 // There are other cases where moving the shuffle after the xor/and/or
2601 // is profitable even if shuffles don't perform a swizzle.
2602 // If both shuffles use the same mask, and both shuffles have the same first
2603 // or second operand, then it might still be profitable to move the shuffle
2604 // after the xor/and/or operation.
2605 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2606 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2607 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2609 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2610 "Inputs to shuffles are not the same type");
2612 // Check that both shuffles use the same mask. The masks are known to be of
2613 // the same length because the result vector type is the same.
2614 // Check also that shuffles have only one use to avoid introducing extra
2616 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2617 SVN0->getMask().equals(SVN1->getMask())) {
2618 SDValue ShOp = N0->getOperand(1);
2620 // Don't try to fold this node if it requires introducing a
2621 // build vector of all zeros that might be illegal at this stage.
2622 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2624 ShOp = DAG.getConstant(0, VT);
2629 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2630 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2631 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2632 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2633 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2634 N0->getOperand(0), N1->getOperand(0));
2635 AddToWorklist(NewNode.getNode());
2636 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2637 &SVN0->getMask()[0]);
2640 // Don't try to fold this node if it requires introducing a
2641 // build vector of all zeros that might be illegal at this stage.
2642 ShOp = N0->getOperand(0);
2643 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2645 ShOp = DAG.getConstant(0, VT);
2650 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2651 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2652 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2653 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2654 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2655 N0->getOperand(1), N1->getOperand(1));
2656 AddToWorklist(NewNode.getNode());
2657 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2658 &SVN0->getMask()[0]);
2666 SDValue DAGCombiner::visitAND(SDNode *N) {
2667 SDValue N0 = N->getOperand(0);
2668 SDValue N1 = N->getOperand(1);
2669 SDValue LL, LR, RL, RR, CC0, CC1;
2670 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2672 EVT VT = N1.getValueType();
2673 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2676 if (VT.isVector()) {
2677 SDValue FoldedVOp = SimplifyVBinOp(N);
2678 if (FoldedVOp.getNode()) return FoldedVOp;
2680 // fold (and x, 0) -> 0, vector edition
2681 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2682 // do not return N0, because undef node may exist in N0
2683 return DAG.getConstant(
2684 APInt::getNullValue(
2685 N0.getValueType().getScalarType().getSizeInBits()),
2687 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2688 // do not return N1, because undef node may exist in N1
2689 return DAG.getConstant(
2690 APInt::getNullValue(
2691 N1.getValueType().getScalarType().getSizeInBits()),
2694 // fold (and x, -1) -> x, vector edition
2695 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2697 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2701 // fold (and x, undef) -> 0
2702 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2703 return DAG.getConstant(0, VT);
2704 // fold (and c1, c2) -> c1&c2
2706 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2707 // canonicalize constant to RHS
2709 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2710 // fold (and x, -1) -> x
2711 if (N1C && N1C->isAllOnesValue())
2713 // if (and x, c) is known to be zero, return 0
2714 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2715 APInt::getAllOnesValue(BitWidth)))
2716 return DAG.getConstant(0, VT);
2718 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2721 // fold (and (or x, C), D) -> D if (C & D) == D
2722 if (N1C && N0.getOpcode() == ISD::OR)
2723 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2724 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2726 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2727 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2728 SDValue N0Op0 = N0.getOperand(0);
2729 APInt Mask = ~N1C->getAPIntValue();
2730 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2731 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2732 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2733 N0.getValueType(), N0Op0);
2735 // Replace uses of the AND with uses of the Zero extend node.
2738 // We actually want to replace all uses of the any_extend with the
2739 // zero_extend, to avoid duplicating things. This will later cause this
2740 // AND to be folded.
2741 CombineTo(N0.getNode(), Zext);
2742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2745 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2746 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2747 // already be zero by virtue of the width of the base type of the load.
2749 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2751 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2752 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2753 N0.getOpcode() == ISD::LOAD) {
2754 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2755 N0 : N0.getOperand(0) );
2757 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2758 // This can be a pure constant or a vector splat, in which case we treat the
2759 // vector as a scalar and use the splat value.
2760 APInt Constant = APInt::getNullValue(1);
2761 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2762 Constant = C->getAPIntValue();
2763 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2764 APInt SplatValue, SplatUndef;
2765 unsigned SplatBitSize;
2767 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2768 SplatBitSize, HasAnyUndefs);
2770 // Undef bits can contribute to a possible optimisation if set, so
2772 SplatValue |= SplatUndef;
2774 // The splat value may be something like "0x00FFFFFF", which means 0 for
2775 // the first vector value and FF for the rest, repeating. We need a mask
2776 // that will apply equally to all members of the vector, so AND all the
2777 // lanes of the constant together.
2778 EVT VT = Vector->getValueType(0);
2779 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2781 // If the splat value has been compressed to a bitlength lower
2782 // than the size of the vector lane, we need to re-expand it to
2784 if (BitWidth > SplatBitSize)
2785 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2786 SplatBitSize < BitWidth;
2787 SplatBitSize = SplatBitSize * 2)
2788 SplatValue |= SplatValue.shl(SplatBitSize);
2790 Constant = APInt::getAllOnesValue(BitWidth);
2791 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2792 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2796 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2797 // actually legal and isn't going to get expanded, else this is a false
2799 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2800 Load->getMemoryVT());
2802 // Resize the constant to the same size as the original memory access before
2803 // extension. If it is still the AllOnesValue then this AND is completely
2806 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2809 switch (Load->getExtensionType()) {
2810 default: B = false; break;
2811 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2813 case ISD::NON_EXTLOAD: B = true; break;
2816 if (B && Constant.isAllOnesValue()) {
2817 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2818 // preserve semantics once we get rid of the AND.
2819 SDValue NewLoad(Load, 0);
2820 if (Load->getExtensionType() == ISD::EXTLOAD) {
2821 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2822 Load->getValueType(0), SDLoc(Load),
2823 Load->getChain(), Load->getBasePtr(),
2824 Load->getOffset(), Load->getMemoryVT(),
2825 Load->getMemOperand());
2826 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2827 if (Load->getNumValues() == 3) {
2828 // PRE/POST_INC loads have 3 values.
2829 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2830 NewLoad.getValue(2) };
2831 CombineTo(Load, To, 3, true);
2833 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2837 // Fold the AND away, taking care not to fold to the old load node if we
2839 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2845 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2846 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2847 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2849 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2850 LL.getValueType().isInteger()) {
2851 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2852 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2853 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2854 LR.getValueType(), LL, RL);
2855 AddToWorklist(ORNode.getNode());
2856 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2858 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2859 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2860 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2861 LR.getValueType(), LL, RL);
2862 AddToWorklist(ANDNode.getNode());
2863 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2865 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2866 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2867 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2868 LR.getValueType(), LL, RL);
2869 AddToWorklist(ORNode.getNode());
2870 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2873 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2874 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2875 Op0 == Op1 && LL.getValueType().isInteger() &&
2876 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2877 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2878 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2879 cast<ConstantSDNode>(RR)->isNullValue()))) {
2880 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2881 LL, DAG.getConstant(1, LL.getValueType()));
2882 AddToWorklist(ADDNode.getNode());
2883 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2884 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2886 // canonicalize equivalent to ll == rl
2887 if (LL == RR && LR == RL) {
2888 Op1 = ISD::getSetCCSwappedOperands(Op1);
2891 if (LL == RL && LR == RR) {
2892 bool isInteger = LL.getValueType().isInteger();
2893 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2894 if (Result != ISD::SETCC_INVALID &&
2895 (!LegalOperations ||
2896 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2897 TLI.isOperationLegal(ISD::SETCC,
2898 getSetCCResultType(N0.getSimpleValueType())))))
2899 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2904 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2905 if (N0.getOpcode() == N1.getOpcode()) {
2906 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2907 if (Tmp.getNode()) return Tmp;
2910 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2911 // fold (and (sra)) -> (and (srl)) when possible.
2912 if (!VT.isVector() &&
2913 SimplifyDemandedBits(SDValue(N, 0)))
2914 return SDValue(N, 0);
2916 // fold (zext_inreg (extload x)) -> (zextload x)
2917 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2918 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2919 EVT MemVT = LN0->getMemoryVT();
2920 // If we zero all the possible extended bits, then we can turn this into
2921 // a zextload if we are running before legalize or the operation is legal.
2922 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2923 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2924 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2925 ((!LegalOperations && !LN0->isVolatile()) ||
2926 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2927 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2928 LN0->getChain(), LN0->getBasePtr(),
2929 MemVT, LN0->getMemOperand());
2931 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2935 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2936 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2938 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2939 EVT MemVT = LN0->getMemoryVT();
2940 // If we zero all the possible extended bits, then we can turn this into
2941 // a zextload if we are running before legalize or the operation is legal.
2942 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2943 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2944 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2945 ((!LegalOperations && !LN0->isVolatile()) ||
2946 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2947 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2948 LN0->getChain(), LN0->getBasePtr(),
2949 MemVT, LN0->getMemOperand());
2951 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2952 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2956 // fold (and (load x), 255) -> (zextload x, i8)
2957 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2958 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2959 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2960 (N0.getOpcode() == ISD::ANY_EXTEND &&
2961 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2962 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2963 LoadSDNode *LN0 = HasAnyExt
2964 ? cast<LoadSDNode>(N0.getOperand(0))
2965 : cast<LoadSDNode>(N0);
2966 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2967 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2968 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2969 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2970 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2971 EVT LoadedVT = LN0->getMemoryVT();
2973 if (ExtVT == LoadedVT &&
2974 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2975 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2979 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2980 LN0->getMemOperand());
2982 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2983 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2986 // Do not change the width of a volatile load.
2987 // Do not generate loads of non-round integer types since these can
2988 // be expensive (and would be wrong if the type is not byte sized).
2989 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2990 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2991 EVT PtrType = LN0->getOperand(1).getValueType();
2993 unsigned Alignment = LN0->getAlignment();
2994 SDValue NewPtr = LN0->getBasePtr();
2996 // For big endian targets, we need to add an offset to the pointer
2997 // to load the correct bytes. For little endian systems, we merely
2998 // need to read fewer bytes from the same pointer.
2999 if (TLI.isBigEndian()) {
3000 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3001 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3002 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3003 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3004 NewPtr, DAG.getConstant(PtrOff, PtrType));
3005 Alignment = MinAlign(Alignment, PtrOff);
3008 AddToWorklist(NewPtr.getNode());
3010 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3012 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3013 LN0->getChain(), NewPtr,
3014 LN0->getPointerInfo(),
3015 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3016 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3018 CombineTo(LN0, Load, Load.getValue(1));
3019 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3025 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3026 VT.getSizeInBits() <= 64) {
3027 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3028 APInt ADDC = ADDI->getAPIntValue();
3029 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3030 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3031 // immediate for an add, but it is legal if its top c2 bits are set,
3032 // transform the ADD so the immediate doesn't need to be materialized
3034 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3035 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3036 SRLI->getZExtValue());
3037 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3039 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3041 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3042 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3043 CombineTo(N0.getNode(), NewAdd);
3044 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3053 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3054 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3055 N0.getOperand(1), false);
3056 if (BSwap.getNode())
3063 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3064 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3065 bool DemandHighBits) {
3066 if (!LegalOperations)
3069 EVT VT = N->getValueType(0);
3070 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3072 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3075 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3076 bool LookPassAnd0 = false;
3077 bool LookPassAnd1 = false;
3078 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3080 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3082 if (N0.getOpcode() == ISD::AND) {
3083 if (!N0.getNode()->hasOneUse())
3085 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3086 if (!N01C || N01C->getZExtValue() != 0xFF00)
3088 N0 = N0.getOperand(0);
3089 LookPassAnd0 = true;
3092 if (N1.getOpcode() == ISD::AND) {
3093 if (!N1.getNode()->hasOneUse())
3095 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3096 if (!N11C || N11C->getZExtValue() != 0xFF)
3098 N1 = N1.getOperand(0);
3099 LookPassAnd1 = true;
3102 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3104 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3106 if (!N0.getNode()->hasOneUse() ||
3107 !N1.getNode()->hasOneUse())
3110 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3114 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3117 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3118 SDValue N00 = N0->getOperand(0);
3119 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3120 if (!N00.getNode()->hasOneUse())
3122 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3123 if (!N001C || N001C->getZExtValue() != 0xFF)
3125 N00 = N00.getOperand(0);
3126 LookPassAnd0 = true;
3129 SDValue N10 = N1->getOperand(0);
3130 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3131 if (!N10.getNode()->hasOneUse())
3133 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3134 if (!N101C || N101C->getZExtValue() != 0xFF00)
3136 N10 = N10.getOperand(0);
3137 LookPassAnd1 = true;
3143 // Make sure everything beyond the low halfword gets set to zero since the SRL
3144 // 16 will clear the top bits.
3145 unsigned OpSizeInBits = VT.getSizeInBits();
3146 if (DemandHighBits && OpSizeInBits > 16) {
3147 // If the left-shift isn't masked out then the only way this is a bswap is
3148 // if all bits beyond the low 8 are 0. In that case the entire pattern
3149 // reduces to a left shift anyway: leave it for other parts of the combiner.
3153 // However, if the right shift isn't masked out then it might be because
3154 // it's not needed. See if we can spot that too.
3155 if (!LookPassAnd1 &&
3156 !DAG.MaskedValueIsZero(
3157 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3161 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3162 if (OpSizeInBits > 16)
3163 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3164 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3168 /// Return true if the specified node is an element that makes up a 32-bit
3169 /// packed halfword byteswap.
3170 /// ((x & 0x000000ff) << 8) |
3171 /// ((x & 0x0000ff00) >> 8) |
3172 /// ((x & 0x00ff0000) << 8) |
3173 /// ((x & 0xff000000) >> 8)
3174 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3175 if (!N.getNode()->hasOneUse())
3178 unsigned Opc = N.getOpcode();
3179 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3182 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3187 switch (N1C->getZExtValue()) {
3190 case 0xFF: Num = 0; break;
3191 case 0xFF00: Num = 1; break;
3192 case 0xFF0000: Num = 2; break;
3193 case 0xFF000000: Num = 3; break;
3196 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3197 SDValue N0 = N.getOperand(0);
3198 if (Opc == ISD::AND) {
3199 if (Num == 0 || Num == 2) {
3201 // (x >> 8) & 0xff0000
3202 if (N0.getOpcode() != ISD::SRL)
3204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 if (!C || C->getZExtValue() != 8)
3208 // (x << 8) & 0xff00
3209 // (x << 8) & 0xff000000
3210 if (N0.getOpcode() != ISD::SHL)
3212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3213 if (!C || C->getZExtValue() != 8)
3216 } else if (Opc == ISD::SHL) {
3218 // (x & 0xff0000) << 8
3219 if (Num != 0 && Num != 2)
3221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222 if (!C || C->getZExtValue() != 8)
3224 } else { // Opc == ISD::SRL
3225 // (x & 0xff00) >> 8
3226 // (x & 0xff000000) >> 8
3227 if (Num != 1 && Num != 3)
3229 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230 if (!C || C->getZExtValue() != 8)
3237 Parts[Num] = N0.getOperand(0).getNode();
3241 /// Match a 32-bit packed halfword bswap. That is
3242 /// ((x & 0x000000ff) << 8) |
3243 /// ((x & 0x0000ff00) >> 8) |
3244 /// ((x & 0x00ff0000) << 8) |
3245 /// ((x & 0xff000000) >> 8)
3246 /// => (rotl (bswap x), 16)
3247 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3248 if (!LegalOperations)
3251 EVT VT = N->getValueType(0);
3254 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3258 // (or (or (and), (and)), (or (and), (and)))
3259 // (or (or (or (and), (and)), (and)), (and))
3260 if (N0.getOpcode() != ISD::OR)
3262 SDValue N00 = N0.getOperand(0);
3263 SDValue N01 = N0.getOperand(1);
3264 SDNode *Parts[4] = {};
3266 if (N1.getOpcode() == ISD::OR &&
3267 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3268 // (or (or (and), (and)), (or (and), (and)))
3269 SDValue N000 = N00.getOperand(0);
3270 if (!isBSwapHWordElement(N000, Parts))
3273 SDValue N001 = N00.getOperand(1);
3274 if (!isBSwapHWordElement(N001, Parts))
3276 SDValue N010 = N01.getOperand(0);
3277 if (!isBSwapHWordElement(N010, Parts))
3279 SDValue N011 = N01.getOperand(1);
3280 if (!isBSwapHWordElement(N011, Parts))
3283 // (or (or (or (and), (and)), (and)), (and))
3284 if (!isBSwapHWordElement(N1, Parts))
3286 if (!isBSwapHWordElement(N01, Parts))
3288 if (N00.getOpcode() != ISD::OR)
3290 SDValue N000 = N00.getOperand(0);
3291 if (!isBSwapHWordElement(N000, Parts))
3293 SDValue N001 = N00.getOperand(1);
3294 if (!isBSwapHWordElement(N001, Parts))
3298 // Make sure the parts are all coming from the same node.
3299 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3302 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3303 SDValue(Parts[0],0));
3305 // Result of the bswap should be rotated by 16. If it's not legal, then
3306 // do (x << 16) | (x >> 16).
3307 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3308 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3309 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3310 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3311 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3312 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3313 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3314 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3317 SDValue DAGCombiner::visitOR(SDNode *N) {
3318 SDValue N0 = N->getOperand(0);
3319 SDValue N1 = N->getOperand(1);
3320 SDValue LL, LR, RL, RR, CC0, CC1;
3321 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3323 EVT VT = N1.getValueType();
3326 if (VT.isVector()) {
3327 SDValue FoldedVOp = SimplifyVBinOp(N);
3328 if (FoldedVOp.getNode()) return FoldedVOp;
3330 // fold (or x, 0) -> x, vector edition
3331 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3333 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3336 // fold (or x, -1) -> -1, vector edition
3337 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3338 // do not return N0, because undef node may exist in N0
3339 return DAG.getConstant(
3340 APInt::getAllOnesValue(
3341 N0.getValueType().getScalarType().getSizeInBits()),
3343 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3344 // do not return N1, because undef node may exist in N1
3345 return DAG.getConstant(
3346 APInt::getAllOnesValue(
3347 N1.getValueType().getScalarType().getSizeInBits()),
3350 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3351 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3352 // Do this only if the resulting shuffle is legal.
3353 if (isa<ShuffleVectorSDNode>(N0) &&
3354 isa<ShuffleVectorSDNode>(N1) &&
3355 // Avoid folding a node with illegal type.
3356 TLI.isTypeLegal(VT) &&
3357 N0->getOperand(1) == N1->getOperand(1) &&
3358 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3359 bool CanFold = true;
3360 unsigned NumElts = VT.getVectorNumElements();
3361 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3362 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3363 // We construct two shuffle masks:
3364 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3365 // and N1 as the second operand.
3366 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3367 // and N0 as the second operand.
3368 // We do this because OR is commutable and therefore there might be
3369 // two ways to fold this node into a shuffle.
3370 SmallVector<int,4> Mask1;
3371 SmallVector<int,4> Mask2;
3373 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3374 int M0 = SV0->getMaskElt(i);
3375 int M1 = SV1->getMaskElt(i);
3377 // Both shuffle indexes are undef. Propagate Undef.
3378 if (M0 < 0 && M1 < 0) {
3379 Mask1.push_back(M0);
3380 Mask2.push_back(M0);
3384 if (M0 < 0 || M1 < 0 ||
3385 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3386 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3391 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3392 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3396 // Fold this sequence only if the resulting shuffle is 'legal'.
3397 if (TLI.isShuffleMaskLegal(Mask1, VT))
3398 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3399 N1->getOperand(0), &Mask1[0]);
3400 if (TLI.isShuffleMaskLegal(Mask2, VT))
3401 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3402 N0->getOperand(0), &Mask2[0]);
3407 // fold (or x, undef) -> -1
3408 if (!LegalOperations &&
3409 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3410 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3411 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3413 // fold (or c1, c2) -> c1|c2
3415 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3416 // canonicalize constant to RHS
3418 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3419 // fold (or x, 0) -> x
3420 if (N1C && N1C->isNullValue())
3422 // fold (or x, -1) -> -1
3423 if (N1C && N1C->isAllOnesValue())
3425 // fold (or x, c) -> c iff (x & ~c) == 0
3426 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3429 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3430 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3431 if (BSwap.getNode())
3433 BSwap = MatchBSwapHWordLow(N, N0, N1);
3434 if (BSwap.getNode())
3438 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3441 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3442 // iff (c1 & c2) == 0.
3443 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3444 isa<ConstantSDNode>(N0.getOperand(1))) {
3445 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3446 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3447 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3450 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3451 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3452 N0.getOperand(0), N1), COR);
3455 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3456 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3457 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3458 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3460 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3461 LL.getValueType().isInteger()) {
3462 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3463 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3464 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3465 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3466 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3467 LR.getValueType(), LL, RL);
3468 AddToWorklist(ORNode.getNode());
3469 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3471 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3472 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3473 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3474 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3475 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3476 LR.getValueType(), LL, RL);
3477 AddToWorklist(ANDNode.getNode());
3478 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3481 // canonicalize equivalent to ll == rl
3482 if (LL == RR && LR == RL) {
3483 Op1 = ISD::getSetCCSwappedOperands(Op1);
3486 if (LL == RL && LR == RR) {
3487 bool isInteger = LL.getValueType().isInteger();
3488 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3489 if (Result != ISD::SETCC_INVALID &&
3490 (!LegalOperations ||
3491 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3492 TLI.isOperationLegal(ISD::SETCC,
3493 getSetCCResultType(N0.getValueType())))))
3494 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3499 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3500 if (N0.getOpcode() == N1.getOpcode()) {
3501 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3502 if (Tmp.getNode()) return Tmp;
3505 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3506 if (N0.getOpcode() == ISD::AND &&
3507 N1.getOpcode() == ISD::AND &&
3508 N0.getOperand(1).getOpcode() == ISD::Constant &&
3509 N1.getOperand(1).getOpcode() == ISD::Constant &&
3510 // Don't increase # computations.
3511 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3512 // We can only do this xform if we know that bits from X that are set in C2
3513 // but not in C1 are already zero. Likewise for Y.
3514 const APInt &LHSMask =
3515 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3516 const APInt &RHSMask =
3517 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3519 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3520 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3521 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3522 N0.getOperand(0), N1.getOperand(0));
3523 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3524 DAG.getConstant(LHSMask | RHSMask, VT));
3528 // See if this is some rotate idiom.
3529 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3530 return SDValue(Rot, 0);
3532 // Simplify the operands using demanded-bits information.
3533 if (!VT.isVector() &&
3534 SimplifyDemandedBits(SDValue(N, 0)))
3535 return SDValue(N, 0);
3540 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3541 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3542 if (Op.getOpcode() == ISD::AND) {
3543 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3544 Mask = Op.getOperand(1);
3545 Op = Op.getOperand(0);
3551 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3559 // Return true if we can prove that, whenever Neg and Pos are both in the
3560 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3561 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3563 // (or (shift1 X, Neg), (shift2 X, Pos))
3565 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3566 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3567 // to consider shift amounts with defined behavior.
3568 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3569 // If OpSize is a power of 2 then:
3571 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3572 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3574 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3575 // for the stronger condition:
3577 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3579 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3580 // we can just replace Neg with Neg' for the rest of the function.
3582 // In other cases we check for the even stronger condition:
3584 // Neg == OpSize - Pos [B]
3586 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3587 // behavior if Pos == 0 (and consequently Neg == OpSize).
3589 // We could actually use [A] whenever OpSize is a power of 2, but the
3590 // only extra cases that it would match are those uninteresting ones
3591 // where Neg and Pos are never in range at the same time. E.g. for
3592 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3593 // as well as (sub 32, Pos), but:
3595 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3597 // always invokes undefined behavior for 32-bit X.
3599 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3600 unsigned MaskLoBits = 0;
3601 if (Neg.getOpcode() == ISD::AND &&
3602 isPowerOf2_64(OpSize) &&
3603 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3604 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3605 Neg = Neg.getOperand(0);
3606 MaskLoBits = Log2_64(OpSize);
3609 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3610 if (Neg.getOpcode() != ISD::SUB)
3612 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3615 SDValue NegOp1 = Neg.getOperand(1);
3617 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3618 // Pos'. The truncation is redundant for the purpose of the equality.
3620 Pos.getOpcode() == ISD::AND &&
3621 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3622 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3623 Pos = Pos.getOperand(0);
3625 // The condition we need is now:
3627 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3629 // If NegOp1 == Pos then we need:
3631 // OpSize & Mask == NegC & Mask
3633 // (because "x & Mask" is a truncation and distributes through subtraction).
3636 Width = NegC->getAPIntValue();
3637 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3638 // Then the condition we want to prove becomes:
3640 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3642 // which, again because "x & Mask" is a truncation, becomes:
3644 // NegC & Mask == (OpSize - PosC) & Mask
3645 // OpSize & Mask == (NegC + PosC) & Mask
3646 else if (Pos.getOpcode() == ISD::ADD &&
3647 Pos.getOperand(0) == NegOp1 &&
3648 Pos.getOperand(1).getOpcode() == ISD::Constant)
3649 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3650 NegC->getAPIntValue());
3654 // Now we just need to check that OpSize & Mask == Width & Mask.
3656 // Opsize & Mask is 0 since Mask is Opsize - 1.
3657 return Width.getLoBits(MaskLoBits) == 0;
3658 return Width == OpSize;
3661 // A subroutine of MatchRotate used once we have found an OR of two opposite
3662 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3663 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3664 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3665 // Neg with outer conversions stripped away.
3666 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3667 SDValue Neg, SDValue InnerPos,
3668 SDValue InnerNeg, unsigned PosOpcode,
3669 unsigned NegOpcode, SDLoc DL) {
3670 // fold (or (shl x, (*ext y)),
3671 // (srl x, (*ext (sub 32, y)))) ->
3672 // (rotl x, y) or (rotr x, (sub 32, y))
3674 // fold (or (shl x, (*ext (sub 32, y))),
3675 // (srl x, (*ext y))) ->
3676 // (rotr x, y) or (rotl x, (sub 32, y))
3677 EVT VT = Shifted.getValueType();
3678 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3679 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3680 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3681 HasPos ? Pos : Neg).getNode();
3687 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3688 // idioms for rotate, and if the target supports rotation instructions, generate
3690 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3691 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3692 EVT VT = LHS.getValueType();
3693 if (!TLI.isTypeLegal(VT)) return nullptr;
3695 // The target must have at least one rotate flavor.
3696 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3697 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3698 if (!HasROTL && !HasROTR) return nullptr;
3700 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3701 SDValue LHSShift; // The shift.
3702 SDValue LHSMask; // AND value if any.
3703 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3704 return nullptr; // Not part of a rotate.
3706 SDValue RHSShift; // The shift.
3707 SDValue RHSMask; // AND value if any.
3708 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3709 return nullptr; // Not part of a rotate.
3711 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3712 return nullptr; // Not shifting the same value.
3714 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3715 return nullptr; // Shifts must disagree.
3717 // Canonicalize shl to left side in a shl/srl pair.
3718 if (RHSShift.getOpcode() == ISD::SHL) {
3719 std::swap(LHS, RHS);
3720 std::swap(LHSShift, RHSShift);
3721 std::swap(LHSMask , RHSMask );
3724 unsigned OpSizeInBits = VT.getSizeInBits();
3725 SDValue LHSShiftArg = LHSShift.getOperand(0);
3726 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3727 SDValue RHSShiftArg = RHSShift.getOperand(0);
3728 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3730 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3731 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3732 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3733 RHSShiftAmt.getOpcode() == ISD::Constant) {
3734 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3735 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3736 if ((LShVal + RShVal) != OpSizeInBits)
3739 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3740 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3742 // If there is an AND of either shifted operand, apply it to the result.
3743 if (LHSMask.getNode() || RHSMask.getNode()) {
3744 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3746 if (LHSMask.getNode()) {
3747 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3748 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3750 if (RHSMask.getNode()) {
3751 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3752 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3755 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3758 return Rot.getNode();
3761 // If there is a mask here, and we have a variable shift, we can't be sure
3762 // that we're masking out the right stuff.
3763 if (LHSMask.getNode() || RHSMask.getNode())
3766 // If the shift amount is sign/zext/any-extended just peel it off.
3767 SDValue LExtOp0 = LHSShiftAmt;
3768 SDValue RExtOp0 = RHSShiftAmt;
3769 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3770 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3771 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3772 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3773 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3774 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3775 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3776 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3777 LExtOp0 = LHSShiftAmt.getOperand(0);
3778 RExtOp0 = RHSShiftAmt.getOperand(0);
3781 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3782 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3786 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3787 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3794 SDValue DAGCombiner::visitXOR(SDNode *N) {
3795 SDValue N0 = N->getOperand(0);
3796 SDValue N1 = N->getOperand(1);
3797 SDValue LHS, RHS, CC;
3798 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3800 EVT VT = N0.getValueType();
3803 if (VT.isVector()) {
3804 SDValue FoldedVOp = SimplifyVBinOp(N);
3805 if (FoldedVOp.getNode()) return FoldedVOp;
3807 // fold (xor x, 0) -> x, vector edition
3808 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3810 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3814 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3815 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3816 return DAG.getConstant(0, VT);
3817 // fold (xor x, undef) -> undef
3818 if (N0.getOpcode() == ISD::UNDEF)
3820 if (N1.getOpcode() == ISD::UNDEF)
3822 // fold (xor c1, c2) -> c1^c2
3824 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3825 // canonicalize constant to RHS
3827 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3828 // fold (xor x, 0) -> x
3829 if (N1C && N1C->isNullValue())
3832 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3836 // fold !(x cc y) -> (x !cc y)
3837 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3838 bool isInt = LHS.getValueType().isInteger();
3839 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3842 if (!LegalOperations ||
3843 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3844 switch (N0.getOpcode()) {
3846 llvm_unreachable("Unhandled SetCC Equivalent!");
3848 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3849 case ISD::SELECT_CC:
3850 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3851 N0.getOperand(3), NotCC);
3856 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3857 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3858 N0.getNode()->hasOneUse() &&
3859 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3860 SDValue V = N0.getOperand(0);
3861 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3862 DAG.getConstant(1, V.getValueType()));
3863 AddToWorklist(V.getNode());
3864 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3867 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3868 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3869 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3870 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3871 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3872 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3873 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3874 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3875 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3876 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3879 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3880 if (N1C && N1C->isAllOnesValue() &&
3881 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3882 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3883 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3884 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3885 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3886 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3887 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3888 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3891 // fold (xor (and x, y), y) -> (and (not x), y)
3892 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3893 N0->getOperand(1) == N1) {
3894 SDValue X = N0->getOperand(0);
3895 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3896 AddToWorklist(NotX.getNode());
3897 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3899 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3900 if (N1C && N0.getOpcode() == ISD::XOR) {
3901 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3902 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3905 DAG.getConstant(N1C->getAPIntValue() ^
3906 N00C->getAPIntValue(), VT));
3908 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3909 DAG.getConstant(N1C->getAPIntValue() ^
3910 N01C->getAPIntValue(), VT));
3912 // fold (xor x, x) -> 0
3914 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3916 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3917 if (N0.getOpcode() == N1.getOpcode()) {
3918 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3919 if (Tmp.getNode()) return Tmp;
3922 // Simplify the expression using non-local knowledge.
3923 if (!VT.isVector() &&
3924 SimplifyDemandedBits(SDValue(N, 0)))
3925 return SDValue(N, 0);
3930 /// Handle transforms common to the three shifts, when the shift amount is a
3932 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3933 // We can't and shouldn't fold opaque constants.
3934 if (Amt->isOpaque())
3937 SDNode *LHS = N->getOperand(0).getNode();
3938 if (!LHS->hasOneUse()) return SDValue();
3940 // We want to pull some binops through shifts, so that we have (and (shift))
3941 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3942 // thing happens with address calculations, so it's important to canonicalize
3944 bool HighBitSet = false; // Can we transform this if the high bit is set?
3946 switch (LHS->getOpcode()) {
3947 default: return SDValue();
3950 HighBitSet = false; // We can only transform sra if the high bit is clear.
3953 HighBitSet = true; // We can only transform sra if the high bit is set.
3956 if (N->getOpcode() != ISD::SHL)
3957 return SDValue(); // only shl(add) not sr[al](add).
3958 HighBitSet = false; // We can only transform sra if the high bit is clear.
3962 // We require the RHS of the binop to be a constant and not opaque as well.
3963 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3964 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3966 // FIXME: disable this unless the input to the binop is a shift by a constant.
3967 // If it is not a shift, it pessimizes some common cases like:
3969 // void foo(int *X, int i) { X[i & 1235] = 1; }
3970 // int bar(int *X, int i) { return X[i & 255]; }
3971 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3972 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3973 BinOpLHSVal->getOpcode() != ISD::SRA &&
3974 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3975 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3978 EVT VT = N->getValueType(0);
3980 // If this is a signed shift right, and the high bit is modified by the
3981 // logical operation, do not perform the transformation. The highBitSet
3982 // boolean indicates the value of the high bit of the constant which would
3983 // cause it to be modified for this operation.
3984 if (N->getOpcode() == ISD::SRA) {
3985 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3986 if (BinOpRHSSignSet != HighBitSet)
3990 if (!TLI.isDesirableToCommuteWithShift(LHS))
3993 // Fold the constants, shifting the binop RHS by the shift amount.
3994 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3996 LHS->getOperand(1), N->getOperand(1));
3997 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3999 // Create the new shift.
4000 SDValue NewShift = DAG.getNode(N->getOpcode(),
4001 SDLoc(LHS->getOperand(0)),
4002 VT, LHS->getOperand(0), N->getOperand(1));
4004 // Create the new binop.
4005 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4008 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4009 assert(N->getOpcode() == ISD::TRUNCATE);
4010 assert(N->getOperand(0).getOpcode() == ISD::AND);
4012 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4013 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4014 SDValue N01 = N->getOperand(0).getOperand(1);
4016 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4017 EVT TruncVT = N->getValueType(0);
4018 SDValue N00 = N->getOperand(0).getOperand(0);
4019 APInt TruncC = N01C->getAPIntValue();
4020 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4022 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4023 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4024 DAG.getConstant(TruncC, TruncVT));
4031 SDValue DAGCombiner::visitRotate(SDNode *N) {
4032 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4033 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4034 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4035 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4036 if (NewOp1.getNode())
4037 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4038 N->getOperand(0), NewOp1);
4043 SDValue DAGCombiner::visitSHL(SDNode *N) {
4044 SDValue N0 = N->getOperand(0);
4045 SDValue N1 = N->getOperand(1);
4046 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4048 EVT VT = N0.getValueType();
4049 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4052 if (VT.isVector()) {
4053 SDValue FoldedVOp = SimplifyVBinOp(N);
4054 if (FoldedVOp.getNode()) return FoldedVOp;
4056 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4057 // If setcc produces all-one true value then:
4058 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4059 if (N1CV && N1CV->isConstant()) {
4060 if (N0.getOpcode() == ISD::AND) {
4061 SDValue N00 = N0->getOperand(0);
4062 SDValue N01 = N0->getOperand(1);
4063 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4065 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4066 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4067 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4068 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4073 N1C = isConstOrConstSplat(N1);
4078 // fold (shl c1, c2) -> c1<<c2
4080 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4081 // fold (shl 0, x) -> 0
4082 if (N0C && N0C->isNullValue())
4084 // fold (shl x, c >= size(x)) -> undef
4085 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4086 return DAG.getUNDEF(VT);
4087 // fold (shl x, 0) -> x
4088 if (N1C && N1C->isNullValue())
4090 // fold (shl undef, x) -> 0
4091 if (N0.getOpcode() == ISD::UNDEF)
4092 return DAG.getConstant(0, VT);
4093 // if (shl x, c) is known to be zero, return 0
4094 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4095 APInt::getAllOnesValue(OpSizeInBits)))
4096 return DAG.getConstant(0, VT);
4097 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4098 if (N1.getOpcode() == ISD::TRUNCATE &&
4099 N1.getOperand(0).getOpcode() == ISD::AND) {
4100 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4101 if (NewOp1.getNode())
4102 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4105 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4106 return SDValue(N, 0);
4108 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4109 if (N1C && N0.getOpcode() == ISD::SHL) {
4110 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4111 uint64_t c1 = N0C1->getZExtValue();
4112 uint64_t c2 = N1C->getZExtValue();
4113 if (c1 + c2 >= OpSizeInBits)
4114 return DAG.getConstant(0, VT);
4115 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4116 DAG.getConstant(c1 + c2, N1.getValueType()));
4120 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4121 // For this to be valid, the second form must not preserve any of the bits
4122 // that are shifted out by the inner shift in the first form. This means
4123 // the outer shift size must be >= the number of bits added by the ext.
4124 // As a corollary, we don't care what kind of ext it is.
4125 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4126 N0.getOpcode() == ISD::ANY_EXTEND ||
4127 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4128 N0.getOperand(0).getOpcode() == ISD::SHL) {
4129 SDValue N0Op0 = N0.getOperand(0);
4130 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4131 uint64_t c1 = N0Op0C1->getZExtValue();
4132 uint64_t c2 = N1C->getZExtValue();
4133 EVT InnerShiftVT = N0Op0.getValueType();
4134 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4135 if (c2 >= OpSizeInBits - InnerShiftSize) {
4136 if (c1 + c2 >= OpSizeInBits)
4137 return DAG.getConstant(0, VT);
4138 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4139 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4140 N0Op0->getOperand(0)),
4141 DAG.getConstant(c1 + c2, N1.getValueType()));
4146 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4147 // Only fold this if the inner zext has no other uses to avoid increasing
4148 // the total number of instructions.
4149 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4150 N0.getOperand(0).getOpcode() == ISD::SRL) {
4151 SDValue N0Op0 = N0.getOperand(0);
4152 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4153 uint64_t c1 = N0Op0C1->getZExtValue();
4154 if (c1 < VT.getScalarSizeInBits()) {
4155 uint64_t c2 = N1C->getZExtValue();
4157 SDValue NewOp0 = N0.getOperand(0);
4158 EVT CountVT = NewOp0.getOperand(1).getValueType();
4159 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4160 NewOp0, DAG.getConstant(c2, CountVT));
4161 AddToWorklist(NewSHL.getNode());
4162 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4168 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4169 // (and (srl x, (sub c1, c2), MASK)
4170 // Only fold this if the inner shift has no other uses -- if it does, folding
4171 // this will increase the total number of instructions.
4172 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4173 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4174 uint64_t c1 = N0C1->getZExtValue();
4175 if (c1 < OpSizeInBits) {
4176 uint64_t c2 = N1C->getZExtValue();
4177 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4180 Mask = Mask.shl(c2 - c1);
4181 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4182 DAG.getConstant(c2 - c1, N1.getValueType()));
4184 Mask = Mask.lshr(c1 - c2);
4185 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4186 DAG.getConstant(c1 - c2, N1.getValueType()));
4188 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4189 DAG.getConstant(Mask, VT));
4193 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4194 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4195 unsigned BitSize = VT.getScalarSizeInBits();
4196 SDValue HiBitsMask =
4197 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4198 BitSize - N1C->getZExtValue()), VT);
4199 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4203 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4204 // Variant of version done on multiply, except mul by a power of 2 is turned
4207 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4208 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4209 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4210 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4211 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4212 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4216 SDValue NewSHL = visitShiftByConstant(N, N1C);
4217 if (NewSHL.getNode())
4224 SDValue DAGCombiner::visitSRA(SDNode *N) {
4225 SDValue N0 = N->getOperand(0);
4226 SDValue N1 = N->getOperand(1);
4227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4229 EVT VT = N0.getValueType();
4230 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4233 if (VT.isVector()) {
4234 SDValue FoldedVOp = SimplifyVBinOp(N);
4235 if (FoldedVOp.getNode()) return FoldedVOp;
4237 N1C = isConstOrConstSplat(N1);
4240 // fold (sra c1, c2) -> (sra c1, c2)
4242 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4243 // fold (sra 0, x) -> 0
4244 if (N0C && N0C->isNullValue())
4246 // fold (sra -1, x) -> -1
4247 if (N0C && N0C->isAllOnesValue())
4249 // fold (sra x, (setge c, size(x))) -> undef
4250 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4251 return DAG.getUNDEF(VT);
4252 // fold (sra x, 0) -> x
4253 if (N1C && N1C->isNullValue())
4255 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4257 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4258 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4259 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4261 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4262 ExtVT, VT.getVectorNumElements());
4263 if ((!LegalOperations ||
4264 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4265 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4266 N0.getOperand(0), DAG.getValueType(ExtVT));
4269 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4270 if (N1C && N0.getOpcode() == ISD::SRA) {
4271 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4272 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4273 if (Sum >= OpSizeInBits)
4274 Sum = OpSizeInBits - 1;
4275 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4276 DAG.getConstant(Sum, N1.getValueType()));
4280 // fold (sra (shl X, m), (sub result_size, n))
4281 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4282 // result_size - n != m.
4283 // If truncate is free for the target sext(shl) is likely to result in better
4285 if (N0.getOpcode() == ISD::SHL && N1C) {
4286 // Get the two constanst of the shifts, CN0 = m, CN = n.
4287 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4289 LLVMContext &Ctx = *DAG.getContext();
4290 // Determine what the truncate's result bitsize and type would be.
4291 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4294 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4296 // Determine the residual right-shift amount.
4297 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4299 // If the shift is not a no-op (in which case this should be just a sign
4300 // extend already), the truncated to type is legal, sign_extend is legal
4301 // on that type, and the truncate to that type is both legal and free,
4302 // perform the transform.
4303 if ((ShiftAmt > 0) &&
4304 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4305 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4306 TLI.isTruncateFree(VT, TruncVT)) {
4308 SDValue Amt = DAG.getConstant(ShiftAmt,
4309 getShiftAmountTy(N0.getOperand(0).getValueType()));
4310 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4311 N0.getOperand(0), Amt);
4312 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4314 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4315 N->getValueType(0), Trunc);
4320 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4321 if (N1.getOpcode() == ISD::TRUNCATE &&
4322 N1.getOperand(0).getOpcode() == ISD::AND) {
4323 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4324 if (NewOp1.getNode())
4325 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4328 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4329 // if c1 is equal to the number of bits the trunc removes
4330 if (N0.getOpcode() == ISD::TRUNCATE &&
4331 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4332 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4333 N0.getOperand(0).hasOneUse() &&
4334 N0.getOperand(0).getOperand(1).hasOneUse() &&
4336 SDValue N0Op0 = N0.getOperand(0);
4337 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4338 unsigned LargeShiftVal = LargeShift->getZExtValue();
4339 EVT LargeVT = N0Op0.getValueType();
4341 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4343 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4344 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4345 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4346 N0Op0.getOperand(0), Amt);
4347 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4352 // Simplify, based on bits shifted out of the LHS.
4353 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4354 return SDValue(N, 0);
4357 // If the sign bit is known to be zero, switch this to a SRL.
4358 if (DAG.SignBitIsZero(N0))
4359 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4362 SDValue NewSRA = visitShiftByConstant(N, N1C);
4363 if (NewSRA.getNode())
4370 SDValue DAGCombiner::visitSRL(SDNode *N) {
4371 SDValue N0 = N->getOperand(0);
4372 SDValue N1 = N->getOperand(1);
4373 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4374 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4375 EVT VT = N0.getValueType();
4376 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4379 if (VT.isVector()) {
4380 SDValue FoldedVOp = SimplifyVBinOp(N);
4381 if (FoldedVOp.getNode()) return FoldedVOp;
4383 N1C = isConstOrConstSplat(N1);
4386 // fold (srl c1, c2) -> c1 >>u c2
4388 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4389 // fold (srl 0, x) -> 0
4390 if (N0C && N0C->isNullValue())
4392 // fold (srl x, c >= size(x)) -> undef
4393 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4394 return DAG.getUNDEF(VT);
4395 // fold (srl x, 0) -> x
4396 if (N1C && N1C->isNullValue())
4398 // if (srl x, c) is known to be zero, return 0
4399 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4400 APInt::getAllOnesValue(OpSizeInBits)))
4401 return DAG.getConstant(0, VT);
4403 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4404 if (N1C && N0.getOpcode() == ISD::SRL) {
4405 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4406 uint64_t c1 = N01C->getZExtValue();
4407 uint64_t c2 = N1C->getZExtValue();
4408 if (c1 + c2 >= OpSizeInBits)
4409 return DAG.getConstant(0, VT);
4410 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4411 DAG.getConstant(c1 + c2, N1.getValueType()));
4415 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4416 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4417 N0.getOperand(0).getOpcode() == ISD::SRL &&
4418 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4420 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4421 uint64_t c2 = N1C->getZExtValue();
4422 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4423 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4424 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4425 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4426 if (c1 + OpSizeInBits == InnerShiftSize) {
4427 if (c1 + c2 >= InnerShiftSize)
4428 return DAG.getConstant(0, VT);
4429 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4430 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4431 N0.getOperand(0)->getOperand(0),
4432 DAG.getConstant(c1 + c2, ShiftCountVT)));
4436 // fold (srl (shl x, c), c) -> (and x, cst2)
4437 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4438 unsigned BitSize = N0.getScalarValueSizeInBits();
4439 if (BitSize <= 64) {
4440 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4441 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4442 DAG.getConstant(~0ULL >> ShAmt, VT));
4446 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4447 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4448 // Shifting in all undef bits?
4449 EVT SmallVT = N0.getOperand(0).getValueType();
4450 unsigned BitSize = SmallVT.getScalarSizeInBits();
4451 if (N1C->getZExtValue() >= BitSize)
4452 return DAG.getUNDEF(VT);
4454 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4455 uint64_t ShiftAmt = N1C->getZExtValue();
4456 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4458 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4459 AddToWorklist(SmallShift.getNode());
4460 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4461 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4462 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4463 DAG.getConstant(Mask, VT));
4467 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4468 // bit, which is unmodified by sra.
4469 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4470 if (N0.getOpcode() == ISD::SRA)
4471 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4474 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4475 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4476 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4477 APInt KnownZero, KnownOne;
4478 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4480 // If any of the input bits are KnownOne, then the input couldn't be all
4481 // zeros, thus the result of the srl will always be zero.
4482 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4484 // If all of the bits input the to ctlz node are known to be zero, then
4485 // the result of the ctlz is "32" and the result of the shift is one.
4486 APInt UnknownBits = ~KnownZero;
4487 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4489 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4490 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4491 // Okay, we know that only that the single bit specified by UnknownBits
4492 // could be set on input to the CTLZ node. If this bit is set, the SRL
4493 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4494 // to an SRL/XOR pair, which is likely to simplify more.
4495 unsigned ShAmt = UnknownBits.countTrailingZeros();
4496 SDValue Op = N0.getOperand(0);
4499 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4500 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4501 AddToWorklist(Op.getNode());
4504 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4505 Op, DAG.getConstant(1, VT));
4509 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4510 if (N1.getOpcode() == ISD::TRUNCATE &&
4511 N1.getOperand(0).getOpcode() == ISD::AND) {
4512 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4513 if (NewOp1.getNode())
4514 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4517 // fold operands of srl based on knowledge that the low bits are not
4519 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4520 return SDValue(N, 0);
4523 SDValue NewSRL = visitShiftByConstant(N, N1C);
4524 if (NewSRL.getNode())
4528 // Attempt to convert a srl of a load into a narrower zero-extending load.
4529 SDValue NarrowLoad = ReduceLoadWidth(N);
4530 if (NarrowLoad.getNode())
4533 // Here is a common situation. We want to optimize:
4536 // %b = and i32 %a, 2
4537 // %c = srl i32 %b, 1
4538 // brcond i32 %c ...
4544 // %c = setcc eq %b, 0
4547 // However when after the source operand of SRL is optimized into AND, the SRL
4548 // itself may not be optimized further. Look for it and add the BRCOND into
4550 if (N->hasOneUse()) {
4551 SDNode *Use = *N->use_begin();
4552 if (Use->getOpcode() == ISD::BRCOND)
4554 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4555 // Also look pass the truncate.
4556 Use = *Use->use_begin();
4557 if (Use->getOpcode() == ISD::BRCOND)
4565 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4566 SDValue N0 = N->getOperand(0);
4567 EVT VT = N->getValueType(0);
4569 // fold (ctlz c1) -> c2
4570 if (isa<ConstantSDNode>(N0))
4571 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4575 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4576 SDValue N0 = N->getOperand(0);
4577 EVT VT = N->getValueType(0);
4579 // fold (ctlz_zero_undef c1) -> c2
4580 if (isa<ConstantSDNode>(N0))
4581 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4585 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4586 SDValue N0 = N->getOperand(0);
4587 EVT VT = N->getValueType(0);
4589 // fold (cttz c1) -> c2
4590 if (isa<ConstantSDNode>(N0))
4591 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4595 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4596 SDValue N0 = N->getOperand(0);
4597 EVT VT = N->getValueType(0);
4599 // fold (cttz_zero_undef c1) -> c2
4600 if (isa<ConstantSDNode>(N0))
4601 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4605 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4606 SDValue N0 = N->getOperand(0);
4607 EVT VT = N->getValueType(0);
4609 // fold (ctpop c1) -> c2
4610 if (isa<ConstantSDNode>(N0))
4611 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4615 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4616 SDValue N0 = N->getOperand(0);
4617 SDValue N1 = N->getOperand(1);
4618 SDValue N2 = N->getOperand(2);
4619 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4620 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4621 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4622 EVT VT = N->getValueType(0);
4623 EVT VT0 = N0.getValueType();
4625 // fold (select C, X, X) -> X
4628 // fold (select true, X, Y) -> X
4629 if (N0C && !N0C->isNullValue())
4631 // fold (select false, X, Y) -> Y
4632 if (N0C && N0C->isNullValue())
4634 // fold (select C, 1, X) -> (or C, X)
4635 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4637 // fold (select C, 0, 1) -> (xor C, 1)
4638 // We can't do this reliably if integer based booleans have different contents
4639 // to floating point based booleans. This is because we can't tell whether we
4640 // have an integer-based boolean or a floating-point-based boolean unless we
4641 // can find the SETCC that produced it and inspect its operands. This is
4642 // fairly easy if C is the SETCC node, but it can potentially be
4643 // undiscoverable (or not reasonably discoverable). For example, it could be
4644 // in another basic block or it could require searching a complicated
4646 if (VT.isInteger() &&
4647 (VT0 == MVT::i1 || (VT0.isInteger() &&
4648 TLI.getBooleanContents(false, false) ==
4649 TLI.getBooleanContents(false, true) &&
4650 TLI.getBooleanContents(false, false) ==
4651 TargetLowering::ZeroOrOneBooleanContent)) &&
4652 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4655 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4656 N0, DAG.getConstant(1, VT0));
4657 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4658 N0, DAG.getConstant(1, VT0));
4659 AddToWorklist(XORNode.getNode());
4661 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4662 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4664 // fold (select C, 0, X) -> (and (not C), X)
4665 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4666 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4667 AddToWorklist(NOTNode.getNode());
4668 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4670 // fold (select C, X, 1) -> (or (not C), X)
4671 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4672 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4673 AddToWorklist(NOTNode.getNode());
4674 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4676 // fold (select C, X, 0) -> (and C, X)
4677 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4678 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4679 // fold (select X, X, Y) -> (or X, Y)
4680 // fold (select X, 1, Y) -> (or X, Y)
4681 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4682 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4683 // fold (select X, Y, X) -> (and X, Y)
4684 // fold (select X, Y, 0) -> (and X, Y)
4685 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4686 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4688 // If we can fold this based on the true/false value, do so.
4689 if (SimplifySelectOps(N, N1, N2))
4690 return SDValue(N, 0); // Don't revisit N.
4692 // fold selects based on a setcc into other things, such as min/max/abs
4693 if (N0.getOpcode() == ISD::SETCC) {
4694 if ((!LegalOperations &&
4695 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4696 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4697 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4698 N0.getOperand(0), N0.getOperand(1),
4699 N1, N2, N0.getOperand(2));
4700 return SimplifySelect(SDLoc(N), N0, N1, N2);
4707 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4710 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4712 // Split the inputs.
4713 SDValue Lo, Hi, LL, LH, RL, RH;
4714 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4715 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4717 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4718 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4720 return std::make_pair(Lo, Hi);
4723 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4724 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4725 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4727 SDValue Cond = N->getOperand(0);
4728 SDValue LHS = N->getOperand(1);
4729 SDValue RHS = N->getOperand(2);
4730 EVT VT = N->getValueType(0);
4731 int NumElems = VT.getVectorNumElements();
4732 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4733 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4734 Cond.getOpcode() == ISD::BUILD_VECTOR);
4736 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4737 // binary ones here.
4738 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4741 // We're sure we have an even number of elements due to the
4742 // concat_vectors we have as arguments to vselect.
4743 // Skip BV elements until we find one that's not an UNDEF
4744 // After we find an UNDEF element, keep looping until we get to half the
4745 // length of the BV and see if all the non-undef nodes are the same.
4746 ConstantSDNode *BottomHalf = nullptr;
4747 for (int i = 0; i < NumElems / 2; ++i) {
4748 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4751 if (BottomHalf == nullptr)
4752 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4753 else if (Cond->getOperand(i).getNode() != BottomHalf)
4757 // Do the same for the second half of the BuildVector
4758 ConstantSDNode *TopHalf = nullptr;
4759 for (int i = NumElems / 2; i < NumElems; ++i) {
4760 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4763 if (TopHalf == nullptr)
4764 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4765 else if (Cond->getOperand(i).getNode() != TopHalf)
4769 assert(TopHalf && BottomHalf &&
4770 "One half of the selector was all UNDEFs and the other was all the "
4771 "same value. This should have been addressed before this function.");
4773 ISD::CONCAT_VECTORS, dl, VT,
4774 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4775 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4778 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4780 if (Level >= AfterLegalizeTypes)
4783 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4784 SDValue Mask = MST->getMask();
4785 SDValue Data = MST->getData();
4788 // If the MSTORE data type requires splitting and the mask is provided by a
4789 // SETCC, then split both nodes and its operands before legalization. This
4790 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4791 // and enables future optimizations (e.g. min/max pattern matching on X86).
4792 if (Mask.getOpcode() == ISD::SETCC) {
4794 // Check if any splitting is required.
4795 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4796 TargetLowering::TypeSplitVector)
4799 SDValue MaskLo, MaskHi, Lo, Hi;
4800 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4803 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4805 SDValue Chain = MST->getChain();
4806 SDValue Ptr = MST->getBasePtr();
4808 EVT MemoryVT = MST->getMemoryVT();
4809 unsigned Alignment = MST->getOriginalAlignment();
4811 // if Alignment is equal to the vector size,
4812 // take the half of it for the second part
4813 unsigned SecondHalfAlignment =
4814 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4815 Alignment/2 : Alignment;
4817 EVT LoMemVT, HiMemVT;
4818 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4820 SDValue DataLo, DataHi;
4821 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4823 MachineMemOperand *MMO = DAG.getMachineFunction().
4824 getMachineMemOperand(MST->getPointerInfo(),
4825 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4826 Alignment, MST->getAAInfo(), MST->getRanges());
4828 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4830 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4831 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4832 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4834 MMO = DAG.getMachineFunction().
4835 getMachineMemOperand(MST->getPointerInfo(),
4836 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4837 SecondHalfAlignment, MST->getAAInfo(),
4840 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4842 AddToWorklist(Lo.getNode());
4843 AddToWorklist(Hi.getNode());
4845 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4850 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4852 if (Level >= AfterLegalizeTypes)
4855 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4856 SDValue Mask = MLD->getMask();
4859 // If the MLOAD result requires splitting and the mask is provided by a
4860 // SETCC, then split both nodes and its operands before legalization. This
4861 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4862 // and enables future optimizations (e.g. min/max pattern matching on X86).
4864 if (Mask.getOpcode() == ISD::SETCC) {
4865 EVT VT = N->getValueType(0);
4867 // Check if any splitting is required.
4868 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4869 TargetLowering::TypeSplitVector)
4872 SDValue MaskLo, MaskHi, Lo, Hi;
4873 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4875 SDValue Src0 = MLD->getSrc0();
4876 SDValue Src0Lo, Src0Hi;
4877 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4880 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4882 SDValue Chain = MLD->getChain();
4883 SDValue Ptr = MLD->getBasePtr();
4884 EVT MemoryVT = MLD->getMemoryVT();
4885 unsigned Alignment = MLD->getOriginalAlignment();
4887 // if Alignment is equal to the vector size,
4888 // take the half of it for the second part
4889 unsigned SecondHalfAlignment =
4890 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4891 Alignment/2 : Alignment;
4893 EVT LoMemVT, HiMemVT;
4894 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4896 MachineMemOperand *MMO = DAG.getMachineFunction().
4897 getMachineMemOperand(MLD->getPointerInfo(),
4898 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4899 Alignment, MLD->getAAInfo(), MLD->getRanges());
4901 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4903 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4904 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4905 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4907 MMO = DAG.getMachineFunction().
4908 getMachineMemOperand(MLD->getPointerInfo(),
4909 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4910 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4912 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4914 AddToWorklist(Lo.getNode());
4915 AddToWorklist(Hi.getNode());
4917 // Build a factor node to remember that this load is independent of the
4919 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4922 // Legalized the chain result - switch anything that used the old chain to
4924 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4926 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4928 SDValue RetOps[] = { LoadRes, Chain };
4929 return DAG.getMergeValues(RetOps, DL);
4934 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4935 SDValue N0 = N->getOperand(0);
4936 SDValue N1 = N->getOperand(1);
4937 SDValue N2 = N->getOperand(2);
4940 // Canonicalize integer abs.
4941 // vselect (setg[te] X, 0), X, -X ->
4942 // vselect (setgt X, -1), X, -X ->
4943 // vselect (setl[te] X, 0), -X, X ->
4944 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4945 if (N0.getOpcode() == ISD::SETCC) {
4946 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4947 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4949 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4951 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4952 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4953 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4954 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4955 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4956 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4957 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4960 EVT VT = LHS.getValueType();
4961 SDValue Shift = DAG.getNode(
4962 ISD::SRA, DL, VT, LHS,
4963 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4964 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4965 AddToWorklist(Shift.getNode());
4966 AddToWorklist(Add.getNode());
4967 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4971 // If the VSELECT result requires splitting and the mask is provided by a
4972 // SETCC, then split both nodes and its operands before legalization. This
4973 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4974 // and enables future optimizations (e.g. min/max pattern matching on X86).
4975 if (N0.getOpcode() == ISD::SETCC) {
4976 EVT VT = N->getValueType(0);
4978 // Check if any splitting is required.
4979 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4980 TargetLowering::TypeSplitVector)
4983 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4984 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4985 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4986 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4988 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4989 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4991 // Add the new VSELECT nodes to the work list in case they need to be split
4993 AddToWorklist(Lo.getNode());
4994 AddToWorklist(Hi.getNode());
4996 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4999 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5000 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5002 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5003 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5006 // The ConvertSelectToConcatVector function is assuming both the above
5007 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5009 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5010 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5011 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5012 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5020 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5021 SDValue N0 = N->getOperand(0);
5022 SDValue N1 = N->getOperand(1);
5023 SDValue N2 = N->getOperand(2);
5024 SDValue N3 = N->getOperand(3);
5025 SDValue N4 = N->getOperand(4);
5026 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5028 // fold select_cc lhs, rhs, x, x, cc -> x
5032 // Determine if the condition we're dealing with is constant
5033 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5034 N0, N1, CC, SDLoc(N), false);
5035 if (SCC.getNode()) {
5036 AddToWorklist(SCC.getNode());
5038 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5039 if (!SCCC->isNullValue())
5040 return N2; // cond always true -> true val
5042 return N3; // cond always false -> false val
5045 // Fold to a simpler select_cc
5046 if (SCC.getOpcode() == ISD::SETCC)
5047 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5048 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5052 // If we can fold this based on the true/false value, do so.
5053 if (SimplifySelectOps(N, N2, N3))
5054 return SDValue(N, 0); // Don't revisit N.
5056 // fold select_cc into other things, such as min/max/abs
5057 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5060 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5061 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5062 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5066 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5067 // dag node into a ConstantSDNode or a build_vector of constants.
5068 // This function is called by the DAGCombiner when visiting sext/zext/aext
5069 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5070 // Vector extends are not folded if operations are legal; this is to
5071 // avoid introducing illegal build_vector dag nodes.
5072 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5073 SelectionDAG &DAG, bool LegalTypes,
5074 bool LegalOperations) {
5075 unsigned Opcode = N->getOpcode();
5076 SDValue N0 = N->getOperand(0);
5077 EVT VT = N->getValueType(0);
5079 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5080 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5082 // fold (sext c1) -> c1
5083 // fold (zext c1) -> c1
5084 // fold (aext c1) -> c1
5085 if (isa<ConstantSDNode>(N0))
5086 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5088 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5089 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5090 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5091 EVT SVT = VT.getScalarType();
5092 if (!(VT.isVector() &&
5093 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5094 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5097 // We can fold this node into a build_vector.
5098 unsigned VTBits = SVT.getSizeInBits();
5099 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5100 unsigned ShAmt = VTBits - EVTBits;
5101 SmallVector<SDValue, 8> Elts;
5102 unsigned NumElts = N0->getNumOperands();
5105 for (unsigned i=0; i != NumElts; ++i) {
5106 SDValue Op = N0->getOperand(i);
5107 if (Op->getOpcode() == ISD::UNDEF) {
5108 Elts.push_back(DAG.getUNDEF(SVT));
5112 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5113 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5114 if (Opcode == ISD::SIGN_EXTEND)
5115 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5118 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5122 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5125 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5126 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5127 // transformation. Returns true if extension are possible and the above
5128 // mentioned transformation is profitable.
5129 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5131 SmallVectorImpl<SDNode *> &ExtendNodes,
5132 const TargetLowering &TLI) {
5133 bool HasCopyToRegUses = false;
5134 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5135 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5136 UE = N0.getNode()->use_end();
5141 if (UI.getUse().getResNo() != N0.getResNo())
5143 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5144 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5145 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5146 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5147 // Sign bits will be lost after a zext.
5150 for (unsigned i = 0; i != 2; ++i) {
5151 SDValue UseOp = User->getOperand(i);
5154 if (!isa<ConstantSDNode>(UseOp))
5159 ExtendNodes.push_back(User);
5162 // If truncates aren't free and there are users we can't
5163 // extend, it isn't worthwhile.
5166 // Remember if this value is live-out.
5167 if (User->getOpcode() == ISD::CopyToReg)
5168 HasCopyToRegUses = true;
5171 if (HasCopyToRegUses) {
5172 bool BothLiveOut = false;
5173 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5175 SDUse &Use = UI.getUse();
5176 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5182 // Both unextended and extended values are live out. There had better be
5183 // a good reason for the transformation.
5184 return ExtendNodes.size();
5189 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5190 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5191 ISD::NodeType ExtType) {
5192 // Extend SetCC uses if necessary.
5193 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5194 SDNode *SetCC = SetCCs[i];
5195 SmallVector<SDValue, 4> Ops;
5197 for (unsigned j = 0; j != 2; ++j) {
5198 SDValue SOp = SetCC->getOperand(j);
5200 Ops.push_back(ExtLoad);
5202 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5205 Ops.push_back(SetCC->getOperand(2));
5206 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5210 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5211 SDValue N0 = N->getOperand(0);
5212 EVT VT = N->getValueType(0);
5214 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5216 return SDValue(Res, 0);
5218 // fold (sext (sext x)) -> (sext x)
5219 // fold (sext (aext x)) -> (sext x)
5220 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5221 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5224 if (N0.getOpcode() == ISD::TRUNCATE) {
5225 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5226 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5227 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5228 if (NarrowLoad.getNode()) {
5229 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5230 if (NarrowLoad.getNode() != N0.getNode()) {
5231 CombineTo(N0.getNode(), NarrowLoad);
5232 // CombineTo deleted the truncate, if needed, but not what's under it.
5235 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5238 // See if the value being truncated is already sign extended. If so, just
5239 // eliminate the trunc/sext pair.
5240 SDValue Op = N0.getOperand(0);
5241 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5242 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5243 unsigned DestBits = VT.getScalarType().getSizeInBits();
5244 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5246 if (OpBits == DestBits) {
5247 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5248 // bits, it is already ready.
5249 if (NumSignBits > DestBits-MidBits)
5251 } else if (OpBits < DestBits) {
5252 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5253 // bits, just sext from i32.
5254 if (NumSignBits > OpBits-MidBits)
5255 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5257 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5258 // bits, just truncate to i32.
5259 if (NumSignBits > OpBits-MidBits)
5260 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5263 // fold (sext (truncate x)) -> (sextinreg x).
5264 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5265 N0.getValueType())) {
5266 if (OpBits < DestBits)
5267 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5268 else if (OpBits > DestBits)
5269 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5270 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5271 DAG.getValueType(N0.getValueType()));
5275 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5276 // None of the supported targets knows how to perform load and sign extend
5277 // on vectors in one instruction. We only perform this transformation on
5279 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5280 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5281 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5282 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5283 bool DoXform = true;
5284 SmallVector<SDNode*, 4> SetCCs;
5285 if (!N0.hasOneUse())
5286 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5288 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5289 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5291 LN0->getBasePtr(), N0.getValueType(),
5292 LN0->getMemOperand());
5293 CombineTo(N, ExtLoad);
5294 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5295 N0.getValueType(), ExtLoad);
5296 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5297 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5299 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5303 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5304 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5305 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5306 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5308 EVT MemVT = LN0->getMemoryVT();
5309 if ((!LegalOperations && !LN0->isVolatile()) ||
5310 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5311 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5313 LN0->getBasePtr(), MemVT,
5314 LN0->getMemOperand());
5315 CombineTo(N, ExtLoad);
5316 CombineTo(N0.getNode(),
5317 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5318 N0.getValueType(), ExtLoad),
5319 ExtLoad.getValue(1));
5320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5324 // fold (sext (and/or/xor (load x), cst)) ->
5325 // (and/or/xor (sextload x), (sext cst))
5326 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5327 N0.getOpcode() == ISD::XOR) &&
5328 isa<LoadSDNode>(N0.getOperand(0)) &&
5329 N0.getOperand(1).getOpcode() == ISD::Constant &&
5330 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5331 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5332 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5333 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5334 bool DoXform = true;
5335 SmallVector<SDNode*, 4> SetCCs;
5336 if (!N0.hasOneUse())
5337 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5340 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5341 LN0->getChain(), LN0->getBasePtr(),
5343 LN0->getMemOperand());
5344 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5345 Mask = Mask.sext(VT.getSizeInBits());
5346 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5347 ExtLoad, DAG.getConstant(Mask, VT));
5348 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5349 SDLoc(N0.getOperand(0)),
5350 N0.getOperand(0).getValueType(), ExtLoad);
5352 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5353 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5355 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5360 if (N0.getOpcode() == ISD::SETCC) {
5361 EVT N0VT = N0.getOperand(0).getValueType();
5362 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5363 // Only do this before legalize for now.
5364 if (VT.isVector() && !LegalOperations &&
5365 TLI.getBooleanContents(N0VT) ==
5366 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5367 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5368 // of the same size as the compared operands. Only optimize sext(setcc())
5369 // if this is the case.
5370 EVT SVT = getSetCCResultType(N0VT);
5372 // We know that the # elements of the results is the same as the
5373 // # elements of the compare (and the # elements of the compare result
5374 // for that matter). Check to see that they are the same size. If so,
5375 // we know that the element size of the sext'd result matches the
5376 // element size of the compare operands.
5377 if (VT.getSizeInBits() == SVT.getSizeInBits())
5378 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5380 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5382 // If the desired elements are smaller or larger than the source
5383 // elements we can use a matching integer vector type and then
5384 // truncate/sign extend
5385 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5386 if (SVT == MatchingVectorType) {
5387 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5388 N0.getOperand(0), N0.getOperand(1),
5389 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5390 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5394 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5395 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5397 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5399 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5400 NegOne, DAG.getConstant(0, VT),
5401 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5402 if (SCC.getNode()) return SCC;
5404 if (!VT.isVector()) {
5405 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5406 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5408 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5409 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5410 N0.getOperand(0), N0.getOperand(1), CC);
5411 return DAG.getSelect(DL, VT, SetCC,
5412 NegOne, DAG.getConstant(0, VT));
5417 // fold (sext x) -> (zext x) if the sign bit is known zero.
5418 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5419 DAG.SignBitIsZero(N0))
5420 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5425 // isTruncateOf - If N is a truncate of some other value, return true, record
5426 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5427 // This function computes KnownZero to avoid a duplicated call to
5428 // computeKnownBits in the caller.
5429 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5432 if (N->getOpcode() == ISD::TRUNCATE) {
5433 Op = N->getOperand(0);
5434 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5438 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5439 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5442 SDValue Op0 = N->getOperand(0);
5443 SDValue Op1 = N->getOperand(1);
5444 assert(Op0.getValueType() == Op1.getValueType());
5446 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5447 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5448 if (COp0 && COp0->isNullValue())
5450 else if (COp1 && COp1->isNullValue())
5455 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5457 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5463 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5464 SDValue N0 = N->getOperand(0);
5465 EVT VT = N->getValueType(0);
5467 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5469 return SDValue(Res, 0);
5471 // fold (zext (zext x)) -> (zext x)
5472 // fold (zext (aext x)) -> (zext x)
5473 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5474 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5477 // fold (zext (truncate x)) -> (zext x) or
5478 // (zext (truncate x)) -> (truncate x)
5479 // This is valid when the truncated bits of x are already zero.
5480 // FIXME: We should extend this to work for vectors too.
5483 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5484 APInt TruncatedBits =
5485 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5486 APInt(Op.getValueSizeInBits(), 0) :
5487 APInt::getBitsSet(Op.getValueSizeInBits(),
5488 N0.getValueSizeInBits(),
5489 std::min(Op.getValueSizeInBits(),
5490 VT.getSizeInBits()));
5491 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5492 if (VT.bitsGT(Op.getValueType()))
5493 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5494 if (VT.bitsLT(Op.getValueType()))
5495 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5501 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5502 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5503 if (N0.getOpcode() == ISD::TRUNCATE) {
5504 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5505 if (NarrowLoad.getNode()) {
5506 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5507 if (NarrowLoad.getNode() != N0.getNode()) {
5508 CombineTo(N0.getNode(), NarrowLoad);
5509 // CombineTo deleted the truncate, if needed, but not what's under it.
5512 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5516 // fold (zext (truncate x)) -> (and x, mask)
5517 if (N0.getOpcode() == ISD::TRUNCATE &&
5518 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5520 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5521 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5522 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5523 if (NarrowLoad.getNode()) {
5524 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5525 if (NarrowLoad.getNode() != N0.getNode()) {
5526 CombineTo(N0.getNode(), NarrowLoad);
5527 // CombineTo deleted the truncate, if needed, but not what's under it.
5530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5533 SDValue Op = N0.getOperand(0);
5534 if (Op.getValueType().bitsLT(VT)) {
5535 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5536 AddToWorklist(Op.getNode());
5537 } else if (Op.getValueType().bitsGT(VT)) {
5538 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5539 AddToWorklist(Op.getNode());
5541 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5542 N0.getValueType().getScalarType());
5545 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5546 // if either of the casts is not free.
5547 if (N0.getOpcode() == ISD::AND &&
5548 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5549 N0.getOperand(1).getOpcode() == ISD::Constant &&
5550 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5551 N0.getValueType()) ||
5552 !TLI.isZExtFree(N0.getValueType(), VT))) {
5553 SDValue X = N0.getOperand(0).getOperand(0);
5554 if (X.getValueType().bitsLT(VT)) {
5555 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5556 } else if (X.getValueType().bitsGT(VT)) {
5557 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5559 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5560 Mask = Mask.zext(VT.getSizeInBits());
5561 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5562 X, DAG.getConstant(Mask, VT));
5565 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5566 // None of the supported targets knows how to perform load and vector_zext
5567 // on vectors in one instruction. We only perform this transformation on
5569 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5570 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5571 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5572 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5573 bool DoXform = true;
5574 SmallVector<SDNode*, 4> SetCCs;
5575 if (!N0.hasOneUse())
5576 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5578 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5579 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5581 LN0->getBasePtr(), N0.getValueType(),
5582 LN0->getMemOperand());
5583 CombineTo(N, ExtLoad);
5584 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5585 N0.getValueType(), ExtLoad);
5586 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5588 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5590 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5594 // fold (zext (and/or/xor (load x), cst)) ->
5595 // (and/or/xor (zextload x), (zext cst))
5596 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5597 N0.getOpcode() == ISD::XOR) &&
5598 isa<LoadSDNode>(N0.getOperand(0)) &&
5599 N0.getOperand(1).getOpcode() == ISD::Constant &&
5600 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5601 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5602 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5603 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5604 bool DoXform = true;
5605 SmallVector<SDNode*, 4> SetCCs;
5606 if (!N0.hasOneUse())
5607 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5610 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5611 LN0->getChain(), LN0->getBasePtr(),
5613 LN0->getMemOperand());
5614 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5615 Mask = Mask.zext(VT.getSizeInBits());
5616 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5617 ExtLoad, DAG.getConstant(Mask, VT));
5618 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5619 SDLoc(N0.getOperand(0)),
5620 N0.getOperand(0).getValueType(), ExtLoad);
5622 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5630 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5631 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5632 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5633 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5634 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5635 EVT MemVT = LN0->getMemoryVT();
5636 if ((!LegalOperations && !LN0->isVolatile()) ||
5637 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5638 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5640 LN0->getBasePtr(), MemVT,
5641 LN0->getMemOperand());
5642 CombineTo(N, ExtLoad);
5643 CombineTo(N0.getNode(),
5644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5646 ExtLoad.getValue(1));
5647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5651 if (N0.getOpcode() == ISD::SETCC) {
5652 if (!LegalOperations && VT.isVector() &&
5653 N0.getValueType().getVectorElementType() == MVT::i1) {
5654 EVT N0VT = N0.getOperand(0).getValueType();
5655 if (getSetCCResultType(N0VT) == N0.getValueType())
5658 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5659 // Only do this before legalize for now.
5660 EVT EltVT = VT.getVectorElementType();
5661 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5662 DAG.getConstant(1, EltVT));
5663 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5664 // We know that the # elements of the results is the same as the
5665 // # elements of the compare (and the # elements of the compare result
5666 // for that matter). Check to see that they are the same size. If so,
5667 // we know that the element size of the sext'd result matches the
5668 // element size of the compare operands.
5669 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5670 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5672 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5673 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5676 // If the desired elements are smaller or larger than the source
5677 // elements we can use a matching integer vector type and then
5678 // truncate/sign extend
5679 EVT MatchingElementType =
5680 EVT::getIntegerVT(*DAG.getContext(),
5681 N0VT.getScalarType().getSizeInBits());
5682 EVT MatchingVectorType =
5683 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5684 N0VT.getVectorNumElements());
5686 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5688 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5689 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5690 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5691 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5694 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5696 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5697 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5698 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5699 if (SCC.getNode()) return SCC;
5702 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5703 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5704 isa<ConstantSDNode>(N0.getOperand(1)) &&
5705 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5707 SDValue ShAmt = N0.getOperand(1);
5708 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5709 if (N0.getOpcode() == ISD::SHL) {
5710 SDValue InnerZExt = N0.getOperand(0);
5711 // If the original shl may be shifting out bits, do not perform this
5713 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5714 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5715 if (ShAmtVal > KnownZeroBits)
5721 // Ensure that the shift amount is wide enough for the shifted value.
5722 if (VT.getSizeInBits() >= 256)
5723 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5725 return DAG.getNode(N0.getOpcode(), DL, VT,
5726 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5733 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5734 SDValue N0 = N->getOperand(0);
5735 EVT VT = N->getValueType(0);
5737 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5739 return SDValue(Res, 0);
5741 // fold (aext (aext x)) -> (aext x)
5742 // fold (aext (zext x)) -> (zext x)
5743 // fold (aext (sext x)) -> (sext x)
5744 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5745 N0.getOpcode() == ISD::ZERO_EXTEND ||
5746 N0.getOpcode() == ISD::SIGN_EXTEND)
5747 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5749 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5750 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5751 if (N0.getOpcode() == ISD::TRUNCATE) {
5752 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5753 if (NarrowLoad.getNode()) {
5754 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5755 if (NarrowLoad.getNode() != N0.getNode()) {
5756 CombineTo(N0.getNode(), NarrowLoad);
5757 // CombineTo deleted the truncate, if needed, but not what's under it.
5760 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5764 // fold (aext (truncate x))
5765 if (N0.getOpcode() == ISD::TRUNCATE) {
5766 SDValue TruncOp = N0.getOperand(0);
5767 if (TruncOp.getValueType() == VT)
5768 return TruncOp; // x iff x size == zext size.
5769 if (TruncOp.getValueType().bitsGT(VT))
5770 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5771 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5774 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5775 // if the trunc is not free.
5776 if (N0.getOpcode() == ISD::AND &&
5777 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5778 N0.getOperand(1).getOpcode() == ISD::Constant &&
5779 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5780 N0.getValueType())) {
5781 SDValue X = N0.getOperand(0).getOperand(0);
5782 if (X.getValueType().bitsLT(VT)) {
5783 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5784 } else if (X.getValueType().bitsGT(VT)) {
5785 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5787 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5788 Mask = Mask.zext(VT.getSizeInBits());
5789 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5790 X, DAG.getConstant(Mask, VT));
5793 // fold (aext (load x)) -> (aext (truncate (extload x)))
5794 // None of the supported targets knows how to perform load and any_ext
5795 // on vectors in one instruction. We only perform this transformation on
5797 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5798 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5799 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5800 bool DoXform = true;
5801 SmallVector<SDNode*, 4> SetCCs;
5802 if (!N0.hasOneUse())
5803 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5806 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5808 LN0->getBasePtr(), N0.getValueType(),
5809 LN0->getMemOperand());
5810 CombineTo(N, ExtLoad);
5811 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5812 N0.getValueType(), ExtLoad);
5813 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5814 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5820 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5821 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5822 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5823 if (N0.getOpcode() == ISD::LOAD &&
5824 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5827 ISD::LoadExtType ExtType = LN0->getExtensionType();
5828 EVT MemVT = LN0->getMemoryVT();
5829 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5830 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5831 VT, LN0->getChain(), LN0->getBasePtr(),
5832 MemVT, LN0->getMemOperand());
5833 CombineTo(N, ExtLoad);
5834 CombineTo(N0.getNode(),
5835 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5836 N0.getValueType(), ExtLoad),
5837 ExtLoad.getValue(1));
5838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5842 if (N0.getOpcode() == ISD::SETCC) {
5844 // aext(setcc) -> vsetcc
5845 // aext(setcc) -> truncate(vsetcc)
5846 // aext(setcc) -> aext(vsetcc)
5847 // Only do this before legalize for now.
5848 if (VT.isVector() && !LegalOperations) {
5849 EVT N0VT = N0.getOperand(0).getValueType();
5850 // We know that the # elements of the results is the same as the
5851 // # elements of the compare (and the # elements of the compare result
5852 // for that matter). Check to see that they are the same size. If so,
5853 // we know that the element size of the sext'd result matches the
5854 // element size of the compare operands.
5855 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5856 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5858 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5859 // If the desired elements are smaller or larger than the source
5860 // elements we can use a matching integer vector type and then
5861 // truncate/any extend
5863 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5865 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5867 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5868 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5872 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5874 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5875 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5876 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5884 /// See if the specified operand can be simplified with the knowledge that only
5885 /// the bits specified by Mask are used. If so, return the simpler operand,
5886 /// otherwise return a null SDValue.
5887 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5888 switch (V.getOpcode()) {
5890 case ISD::Constant: {
5891 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5892 assert(CV && "Const value should be ConstSDNode.");
5893 const APInt &CVal = CV->getAPIntValue();
5894 APInt NewVal = CVal & Mask;
5896 return DAG.getConstant(NewVal, V.getValueType());
5901 // If the LHS or RHS don't contribute bits to the or, drop them.
5902 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5903 return V.getOperand(1);
5904 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5905 return V.getOperand(0);
5908 // Only look at single-use SRLs.
5909 if (!V.getNode()->hasOneUse())
5911 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5912 // See if we can recursively simplify the LHS.
5913 unsigned Amt = RHSC->getZExtValue();
5915 // Watch out for shift count overflow though.
5916 if (Amt >= Mask.getBitWidth()) break;
5917 APInt NewMask = Mask << Amt;
5918 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5919 if (SimplifyLHS.getNode())
5920 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5921 SimplifyLHS, V.getOperand(1));
5927 /// If the result of a wider load is shifted to right of N bits and then
5928 /// truncated to a narrower type and where N is a multiple of number of bits of
5929 /// the narrower type, transform it to a narrower load from address + N / num of
5930 /// bits of new type. If the result is to be extended, also fold the extension
5931 /// to form a extending load.
5932 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5933 unsigned Opc = N->getOpcode();
5935 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5936 SDValue N0 = N->getOperand(0);
5937 EVT VT = N->getValueType(0);
5940 // This transformation isn't valid for vector loads.
5944 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5946 if (Opc == ISD::SIGN_EXTEND_INREG) {
5947 ExtType = ISD::SEXTLOAD;
5948 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5949 } else if (Opc == ISD::SRL) {
5950 // Another special-case: SRL is basically zero-extending a narrower value.
5951 ExtType = ISD::ZEXTLOAD;
5953 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5954 if (!N01) return SDValue();
5955 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5956 VT.getSizeInBits() - N01->getZExtValue());
5958 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5961 unsigned EVTBits = ExtVT.getSizeInBits();
5963 // Do not generate loads of non-round integer types since these can
5964 // be expensive (and would be wrong if the type is not byte sized).
5965 if (!ExtVT.isRound())
5969 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5970 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5971 ShAmt = N01->getZExtValue();
5972 // Is the shift amount a multiple of size of VT?
5973 if ((ShAmt & (EVTBits-1)) == 0) {
5974 N0 = N0.getOperand(0);
5975 // Is the load width a multiple of size of VT?
5976 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5980 // At this point, we must have a load or else we can't do the transform.
5981 if (!isa<LoadSDNode>(N0)) return SDValue();
5983 // Because a SRL must be assumed to *need* to zero-extend the high bits
5984 // (as opposed to anyext the high bits), we can't combine the zextload
5985 // lowering of SRL and an sextload.
5986 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5989 // If the shift amount is larger than the input type then we're not
5990 // accessing any of the loaded bytes. If the load was a zextload/extload
5991 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5992 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5997 // If the load is shifted left (and the result isn't shifted back right),
5998 // we can fold the truncate through the shift.
5999 unsigned ShLeftAmt = 0;
6000 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6001 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6002 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6003 ShLeftAmt = N01->getZExtValue();
6004 N0 = N0.getOperand(0);
6008 // If we haven't found a load, we can't narrow it. Don't transform one with
6009 // multiple uses, this would require adding a new load.
6010 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6013 // Don't change the width of a volatile load.
6014 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6015 if (LN0->isVolatile())
6018 // Verify that we are actually reducing a load width here.
6019 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6022 // For the transform to be legal, the load must produce only two values
6023 // (the value loaded and the chain). Don't transform a pre-increment
6024 // load, for example, which produces an extra value. Otherwise the
6025 // transformation is not equivalent, and the downstream logic to replace
6026 // uses gets things wrong.
6027 if (LN0->getNumValues() > 2)
6030 // If the load that we're shrinking is an extload and we're not just
6031 // discarding the extension we can't simply shrink the load. Bail.
6032 // TODO: It would be possible to merge the extensions in some cases.
6033 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6034 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6037 EVT PtrType = N0.getOperand(1).getValueType();
6039 if (PtrType == MVT::Untyped || PtrType.isExtended())
6040 // It's not possible to generate a constant of extended or untyped type.
6043 // For big endian targets, we need to adjust the offset to the pointer to
6044 // load the correct bytes.
6045 if (TLI.isBigEndian()) {
6046 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6047 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6048 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6051 uint64_t PtrOff = ShAmt / 8;
6052 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6053 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6054 PtrType, LN0->getBasePtr(),
6055 DAG.getConstant(PtrOff, PtrType));
6056 AddToWorklist(NewPtr.getNode());
6059 if (ExtType == ISD::NON_EXTLOAD)
6060 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6061 LN0->getPointerInfo().getWithOffset(PtrOff),
6062 LN0->isVolatile(), LN0->isNonTemporal(),
6063 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6065 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6066 LN0->getPointerInfo().getWithOffset(PtrOff),
6067 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6068 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6070 // Replace the old load's chain with the new load's chain.
6071 WorklistRemover DeadNodes(*this);
6072 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6074 // Shift the result left, if we've swallowed a left shift.
6075 SDValue Result = Load;
6076 if (ShLeftAmt != 0) {
6077 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6078 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6080 // If the shift amount is as large as the result size (but, presumably,
6081 // no larger than the source) then the useful bits of the result are
6082 // zero; we can't simply return the shortened shift, because the result
6083 // of that operation is undefined.
6084 if (ShLeftAmt >= VT.getSizeInBits())
6085 Result = DAG.getConstant(0, VT);
6087 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6088 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6091 // Return the new loaded value.
6095 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6096 SDValue N0 = N->getOperand(0);
6097 SDValue N1 = N->getOperand(1);
6098 EVT VT = N->getValueType(0);
6099 EVT EVT = cast<VTSDNode>(N1)->getVT();
6100 unsigned VTBits = VT.getScalarType().getSizeInBits();
6101 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6103 // fold (sext_in_reg c1) -> c1
6104 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6105 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6107 // If the input is already sign extended, just drop the extension.
6108 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6111 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6112 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6113 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6114 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6115 N0.getOperand(0), N1);
6117 // fold (sext_in_reg (sext x)) -> (sext x)
6118 // fold (sext_in_reg (aext x)) -> (sext x)
6119 // if x is small enough.
6120 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6121 SDValue N00 = N0.getOperand(0);
6122 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6123 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6124 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6127 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6128 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6129 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6131 // fold operands of sext_in_reg based on knowledge that the top bits are not
6133 if (SimplifyDemandedBits(SDValue(N, 0)))
6134 return SDValue(N, 0);
6136 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6137 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6138 SDValue NarrowLoad = ReduceLoadWidth(N);
6139 if (NarrowLoad.getNode())
6142 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6143 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6144 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6145 if (N0.getOpcode() == ISD::SRL) {
6146 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6147 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6148 // We can turn this into an SRA iff the input to the SRL is already sign
6150 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6151 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6152 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6153 N0.getOperand(0), N0.getOperand(1));
6157 // fold (sext_inreg (extload x)) -> (sextload x)
6158 if (ISD::isEXTLoad(N0.getNode()) &&
6159 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6160 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6161 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6162 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6164 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6166 LN0->getBasePtr(), EVT,
6167 LN0->getMemOperand());
6168 CombineTo(N, ExtLoad);
6169 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6170 AddToWorklist(ExtLoad.getNode());
6171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6173 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6174 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6176 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6177 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6178 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6179 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6180 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6182 LN0->getBasePtr(), EVT,
6183 LN0->getMemOperand());
6184 CombineTo(N, ExtLoad);
6185 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6186 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6189 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6190 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6191 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6192 N0.getOperand(1), false);
6193 if (BSwap.getNode())
6194 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6198 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6199 // into a build_vector.
6200 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6201 SmallVector<SDValue, 8> Elts;
6202 unsigned NumElts = N0->getNumOperands();
6203 unsigned ShAmt = VTBits - EVTBits;
6205 for (unsigned i = 0; i != NumElts; ++i) {
6206 SDValue Op = N0->getOperand(i);
6207 if (Op->getOpcode() == ISD::UNDEF) {
6212 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6213 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6214 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6215 Op.getValueType()));
6218 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6224 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6225 SDValue N0 = N->getOperand(0);
6226 EVT VT = N->getValueType(0);
6227 bool isLE = TLI.isLittleEndian();
6230 if (N0.getValueType() == N->getValueType(0))
6232 // fold (truncate c1) -> c1
6233 if (isa<ConstantSDNode>(N0))
6234 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6235 // fold (truncate (truncate x)) -> (truncate x)
6236 if (N0.getOpcode() == ISD::TRUNCATE)
6237 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6238 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6239 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6240 N0.getOpcode() == ISD::SIGN_EXTEND ||
6241 N0.getOpcode() == ISD::ANY_EXTEND) {
6242 if (N0.getOperand(0).getValueType().bitsLT(VT))
6243 // if the source is smaller than the dest, we still need an extend
6244 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6246 if (N0.getOperand(0).getValueType().bitsGT(VT))
6247 // if the source is larger than the dest, than we just need the truncate
6248 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6249 // if the source and dest are the same type, we can drop both the extend
6250 // and the truncate.
6251 return N0.getOperand(0);
6254 // Fold extract-and-trunc into a narrow extract. For example:
6255 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6256 // i32 y = TRUNCATE(i64 x)
6258 // v16i8 b = BITCAST (v2i64 val)
6259 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6261 // Note: We only run this optimization after type legalization (which often
6262 // creates this pattern) and before operation legalization after which
6263 // we need to be more careful about the vector instructions that we generate.
6264 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6265 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6267 EVT VecTy = N0.getOperand(0).getValueType();
6268 EVT ExTy = N0.getValueType();
6269 EVT TrTy = N->getValueType(0);
6271 unsigned NumElem = VecTy.getVectorNumElements();
6272 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6274 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6275 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6277 SDValue EltNo = N0->getOperand(1);
6278 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6279 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6280 EVT IndexTy = TLI.getVectorIdxTy();
6281 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6283 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6284 NVT, N0.getOperand(0));
6286 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6288 DAG.getConstant(Index, IndexTy));
6292 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6293 if (N0.getOpcode() == ISD::SELECT) {
6294 EVT SrcVT = N0.getValueType();
6295 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6296 TLI.isTruncateFree(SrcVT, VT)) {
6298 SDValue Cond = N0.getOperand(0);
6299 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6300 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6301 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6305 // Fold a series of buildvector, bitcast, and truncate if possible.
6307 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6308 // (2xi32 (buildvector x, y)).
6309 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6310 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6311 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6312 N0.getOperand(0).hasOneUse()) {
6314 SDValue BuildVect = N0.getOperand(0);
6315 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6316 EVT TruncVecEltTy = VT.getVectorElementType();
6318 // Check that the element types match.
6319 if (BuildVectEltTy == TruncVecEltTy) {
6320 // Now we only need to compute the offset of the truncated elements.
6321 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6322 unsigned TruncVecNumElts = VT.getVectorNumElements();
6323 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6325 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6326 "Invalid number of elements");
6328 SmallVector<SDValue, 8> Opnds;
6329 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6330 Opnds.push_back(BuildVect.getOperand(i));
6332 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6336 // See if we can simplify the input to this truncate through knowledge that
6337 // only the low bits are being used.
6338 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6339 // Currently we only perform this optimization on scalars because vectors
6340 // may have different active low bits.
6341 if (!VT.isVector()) {
6343 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6344 VT.getSizeInBits()));
6345 if (Shorter.getNode())
6346 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6348 // fold (truncate (load x)) -> (smaller load x)
6349 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6350 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6351 SDValue Reduced = ReduceLoadWidth(N);
6352 if (Reduced.getNode())
6354 // Handle the case where the load remains an extending load even
6355 // after truncation.
6356 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6357 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6358 if (!LN0->isVolatile() &&
6359 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6360 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6361 VT, LN0->getChain(), LN0->getBasePtr(),
6363 LN0->getMemOperand());
6364 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6369 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6370 // where ... are all 'undef'.
6371 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6372 SmallVector<EVT, 8> VTs;
6375 unsigned NumDefs = 0;
6377 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6378 SDValue X = N0.getOperand(i);
6379 if (X.getOpcode() != ISD::UNDEF) {
6384 // Stop if more than one members are non-undef.
6387 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6388 VT.getVectorElementType(),
6389 X.getValueType().getVectorNumElements()));
6393 return DAG.getUNDEF(VT);
6396 assert(V.getNode() && "The single defined operand is empty!");
6397 SmallVector<SDValue, 8> Opnds;
6398 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6400 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6403 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6404 AddToWorklist(NV.getNode());
6405 Opnds.push_back(NV);
6407 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6411 // Simplify the operands using demanded-bits information.
6412 if (!VT.isVector() &&
6413 SimplifyDemandedBits(SDValue(N, 0)))
6414 return SDValue(N, 0);
6419 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6420 SDValue Elt = N->getOperand(i);
6421 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6422 return Elt.getNode();
6423 return Elt.getOperand(Elt.getResNo()).getNode();
6426 /// build_pair (load, load) -> load
6427 /// if load locations are consecutive.
6428 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6429 assert(N->getOpcode() == ISD::BUILD_PAIR);
6431 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6432 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6433 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6434 LD1->getAddressSpace() != LD2->getAddressSpace())
6436 EVT LD1VT = LD1->getValueType(0);
6438 if (ISD::isNON_EXTLoad(LD2) &&
6440 // If both are volatile this would reduce the number of volatile loads.
6441 // If one is volatile it might be ok, but play conservative and bail out.
6442 !LD1->isVolatile() &&
6443 !LD2->isVolatile() &&
6444 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6445 unsigned Align = LD1->getAlignment();
6446 unsigned NewAlign = TLI.getDataLayout()->
6447 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6449 if (NewAlign <= Align &&
6450 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6451 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6452 LD1->getBasePtr(), LD1->getPointerInfo(),
6453 false, false, false, Align);
6459 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6460 SDValue N0 = N->getOperand(0);
6461 EVT VT = N->getValueType(0);
6463 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6464 // Only do this before legalize, since afterward the target may be depending
6465 // on the bitconvert.
6466 // First check to see if this is all constant.
6468 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6470 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6472 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6473 assert(!DestEltVT.isVector() &&
6474 "Element type of vector ValueType must not be vector!");
6476 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6479 // If the input is a constant, let getNode fold it.
6480 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6481 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6482 if (Res.getNode() != N) {
6483 if (!LegalOperations ||
6484 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6487 // Folding it resulted in an illegal node, and it's too late to
6488 // do that. Clean up the old node and forego the transformation.
6489 // Ideally this won't happen very often, because instcombine
6490 // and the earlier dagcombine runs (where illegal nodes are
6491 // permitted) should have folded most of them already.
6492 deleteAndRecombine(Res.getNode());
6496 // (conv (conv x, t1), t2) -> (conv x, t2)
6497 if (N0.getOpcode() == ISD::BITCAST)
6498 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6501 // fold (conv (load x)) -> (load (conv*)x)
6502 // If the resultant load doesn't need a higher alignment than the original!
6503 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6504 // Do not change the width of a volatile load.
6505 !cast<LoadSDNode>(N0)->isVolatile() &&
6506 // Do not remove the cast if the types differ in endian layout.
6507 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6508 TLI.hasBigEndianPartOrdering(VT) &&
6509 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6510 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6511 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6512 unsigned Align = TLI.getDataLayout()->
6513 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6514 unsigned OrigAlign = LN0->getAlignment();
6516 if (Align <= OrigAlign) {
6517 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6518 LN0->getBasePtr(), LN0->getPointerInfo(),
6519 LN0->isVolatile(), LN0->isNonTemporal(),
6520 LN0->isInvariant(), OrigAlign,
6522 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6527 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6528 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6529 // This often reduces constant pool loads.
6530 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6531 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6532 N0.getNode()->hasOneUse() && VT.isInteger() &&
6533 !VT.isVector() && !N0.getValueType().isVector()) {
6534 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6536 AddToWorklist(NewConv.getNode());
6538 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6539 if (N0.getOpcode() == ISD::FNEG)
6540 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6541 NewConv, DAG.getConstant(SignBit, VT));
6542 assert(N0.getOpcode() == ISD::FABS);
6543 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6544 NewConv, DAG.getConstant(~SignBit, VT));
6547 // fold (bitconvert (fcopysign cst, x)) ->
6548 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6549 // Note that we don't handle (copysign x, cst) because this can always be
6550 // folded to an fneg or fabs.
6551 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6552 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6553 VT.isInteger() && !VT.isVector()) {
6554 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6555 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6556 if (isTypeLegal(IntXVT)) {
6557 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6558 IntXVT, N0.getOperand(1));
6559 AddToWorklist(X.getNode());
6561 // If X has a different width than the result/lhs, sext it or truncate it.
6562 unsigned VTWidth = VT.getSizeInBits();
6563 if (OrigXWidth < VTWidth) {
6564 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6565 AddToWorklist(X.getNode());
6566 } else if (OrigXWidth > VTWidth) {
6567 // To get the sign bit in the right place, we have to shift it right
6568 // before truncating.
6569 X = DAG.getNode(ISD::SRL, SDLoc(X),
6570 X.getValueType(), X,
6571 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6572 AddToWorklist(X.getNode());
6573 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6574 AddToWorklist(X.getNode());
6577 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6578 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6579 X, DAG.getConstant(SignBit, VT));
6580 AddToWorklist(X.getNode());
6582 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6583 VT, N0.getOperand(0));
6584 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6585 Cst, DAG.getConstant(~SignBit, VT));
6586 AddToWorklist(Cst.getNode());
6588 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6592 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6593 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6594 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6595 if (CombineLD.getNode())
6602 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6603 EVT VT = N->getValueType(0);
6604 return CombineConsecutiveLoads(N, VT);
6607 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6608 /// operands. DstEltVT indicates the destination element value type.
6609 SDValue DAGCombiner::
6610 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6611 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6613 // If this is already the right type, we're done.
6614 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6616 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6617 unsigned DstBitSize = DstEltVT.getSizeInBits();
6619 // If this is a conversion of N elements of one type to N elements of another
6620 // type, convert each element. This handles FP<->INT cases.
6621 if (SrcBitSize == DstBitSize) {
6622 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6623 BV->getValueType(0).getVectorNumElements());
6625 // Due to the FP element handling below calling this routine recursively,
6626 // we can end up with a scalar-to-vector node here.
6627 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6628 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6629 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6630 DstEltVT, BV->getOperand(0)));
6632 SmallVector<SDValue, 8> Ops;
6633 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6634 SDValue Op = BV->getOperand(i);
6635 // If the vector element type is not legal, the BUILD_VECTOR operands
6636 // are promoted and implicitly truncated. Make that explicit here.
6637 if (Op.getValueType() != SrcEltVT)
6638 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6639 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6641 AddToWorklist(Ops.back().getNode());
6643 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6646 // Otherwise, we're growing or shrinking the elements. To avoid having to
6647 // handle annoying details of growing/shrinking FP values, we convert them to
6649 if (SrcEltVT.isFloatingPoint()) {
6650 // Convert the input float vector to a int vector where the elements are the
6652 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6653 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6654 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6658 // Now we know the input is an integer vector. If the output is a FP type,
6659 // convert to integer first, then to FP of the right size.
6660 if (DstEltVT.isFloatingPoint()) {
6661 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6662 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6663 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6665 // Next, convert to FP elements of the same size.
6666 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6669 // Okay, we know the src/dst types are both integers of differing types.
6670 // Handling growing first.
6671 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6672 if (SrcBitSize < DstBitSize) {
6673 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6675 SmallVector<SDValue, 8> Ops;
6676 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6677 i += NumInputsPerOutput) {
6678 bool isLE = TLI.isLittleEndian();
6679 APInt NewBits = APInt(DstBitSize, 0);
6680 bool EltIsUndef = true;
6681 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6682 // Shift the previously computed bits over.
6683 NewBits <<= SrcBitSize;
6684 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6685 if (Op.getOpcode() == ISD::UNDEF) continue;
6688 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6689 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6693 Ops.push_back(DAG.getUNDEF(DstEltVT));
6695 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6698 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6699 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6702 // Finally, this must be the case where we are shrinking elements: each input
6703 // turns into multiple outputs.
6704 bool isS2V = ISD::isScalarToVector(BV);
6705 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6706 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6707 NumOutputsPerInput*BV->getNumOperands());
6708 SmallVector<SDValue, 8> Ops;
6710 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6711 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6712 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6713 Ops.push_back(DAG.getUNDEF(DstEltVT));
6717 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6718 getAPIntValue().zextOrTrunc(SrcBitSize);
6720 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6721 APInt ThisVal = OpVal.trunc(DstBitSize);
6722 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6723 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6724 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6725 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6727 OpVal = OpVal.lshr(DstBitSize);
6730 // For big endian targets, swap the order of the pieces of each element.
6731 if (TLI.isBigEndian())
6732 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6735 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6738 SDValue DAGCombiner::visitFADD(SDNode *N) {
6739 SDValue N0 = N->getOperand(0);
6740 SDValue N1 = N->getOperand(1);
6741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6743 EVT VT = N->getValueType(0);
6744 const TargetOptions &Options = DAG.getTarget().Options;
6747 if (VT.isVector()) {
6748 SDValue FoldedVOp = SimplifyVBinOp(N);
6749 if (FoldedVOp.getNode()) return FoldedVOp;
6752 // fold (fadd c1, c2) -> c1 + c2
6754 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6756 // canonicalize constant to RHS
6757 if (N0CFP && !N1CFP)
6758 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6760 // fold (fadd A, (fneg B)) -> (fsub A, B)
6761 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6762 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6763 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6764 GetNegatedExpression(N1, DAG, LegalOperations));
6766 // fold (fadd (fneg A), B) -> (fsub B, A)
6767 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6768 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6769 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6770 GetNegatedExpression(N0, DAG, LegalOperations));
6772 // If 'unsafe math' is enabled, fold lots of things.
6773 if (Options.UnsafeFPMath) {
6774 // No FP constant should be created after legalization as Instruction
6775 // Selection pass has a hard time dealing with FP constants.
6776 bool AllowNewConst = (Level < AfterLegalizeDAG);
6778 // fold (fadd A, 0) -> A
6779 if (N1CFP && N1CFP->getValueAPF().isZero())
6782 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6783 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6784 isa<ConstantFPSDNode>(N0.getOperand(1)))
6785 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6786 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6787 N0.getOperand(1), N1));
6789 // If allowed, fold (fadd (fneg x), x) -> 0.0
6790 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6791 return DAG.getConstantFP(0.0, VT);
6793 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6794 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6795 return DAG.getConstantFP(0.0, VT);
6797 // We can fold chains of FADD's of the same value into multiplications.
6798 // This transform is not safe in general because we are reducing the number
6799 // of rounding steps.
6800 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6801 if (N0.getOpcode() == ISD::FMUL) {
6802 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6803 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6805 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6806 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6807 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6809 DAG.getConstantFP(1.0, VT));
6810 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6813 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6814 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6815 N1.getOperand(0) == N1.getOperand(1) &&
6816 N0.getOperand(0) == N1.getOperand(0)) {
6817 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6819 DAG.getConstantFP(2.0, VT));
6820 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821 N0.getOperand(0), NewCFP);
6825 if (N1.getOpcode() == ISD::FMUL) {
6826 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6827 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6829 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6830 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6831 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6833 DAG.getConstantFP(1.0, VT));
6834 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6837 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6838 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6839 N0.getOperand(0) == N0.getOperand(1) &&
6840 N1.getOperand(0) == N0.getOperand(0)) {
6841 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6843 DAG.getConstantFP(2.0, VT));
6844 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6848 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6849 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6850 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6851 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6852 (N0.getOperand(0) == N1))
6853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6854 N1, DAG.getConstantFP(3.0, VT));
6857 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6858 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6859 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6860 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6861 N1.getOperand(0) == N0)
6862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6863 N0, DAG.getConstantFP(3.0, VT));
6866 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6867 if (AllowNewConst &&
6868 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6869 N0.getOperand(0) == N0.getOperand(1) &&
6870 N1.getOperand(0) == N1.getOperand(1) &&
6871 N0.getOperand(0) == N1.getOperand(0))
6872 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6873 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6875 } // enable-unsafe-fp-math
6877 // FADD -> FMA combines:
6878 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6879 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6880 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6882 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6883 if (N0.getOpcode() == ISD::FMUL &&
6884 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6885 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6886 N0.getOperand(0), N0.getOperand(1), N1);
6888 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6889 // Note: Commutes FADD operands.
6890 if (N1.getOpcode() == ISD::FMUL &&
6891 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6892 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6893 N1.getOperand(0), N1.getOperand(1), N0);
6899 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6900 SDValue N0 = N->getOperand(0);
6901 SDValue N1 = N->getOperand(1);
6902 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6903 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6904 EVT VT = N->getValueType(0);
6906 const TargetOptions &Options = DAG.getTarget().Options;
6909 if (VT.isVector()) {
6910 SDValue FoldedVOp = SimplifyVBinOp(N);
6911 if (FoldedVOp.getNode()) return FoldedVOp;
6914 // fold (fsub c1, c2) -> c1-c2
6916 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6918 // fold (fsub A, (fneg B)) -> (fadd A, B)
6919 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6920 return DAG.getNode(ISD::FADD, dl, VT, N0,
6921 GetNegatedExpression(N1, DAG, LegalOperations));
6923 // If 'unsafe math' is enabled, fold lots of things.
6924 if (Options.UnsafeFPMath) {
6926 if (N1CFP && N1CFP->getValueAPF().isZero())
6929 // (fsub 0, B) -> -B
6930 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6931 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6932 return GetNegatedExpression(N1, DAG, LegalOperations);
6933 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6934 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6937 // (fsub x, x) -> 0.0
6939 return DAG.getConstantFP(0.0f, VT);
6941 // (fsub x, (fadd x, y)) -> (fneg y)
6942 // (fsub x, (fadd y, x)) -> (fneg y)
6943 if (N1.getOpcode() == ISD::FADD) {
6944 SDValue N10 = N1->getOperand(0);
6945 SDValue N11 = N1->getOperand(1);
6947 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6948 return GetNegatedExpression(N11, DAG, LegalOperations);
6950 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6951 return GetNegatedExpression(N10, DAG, LegalOperations);
6955 // FSUB -> FMA combines:
6956 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6957 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6958 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6960 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6961 if (N0.getOpcode() == ISD::FMUL &&
6962 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6963 return DAG.getNode(ISD::FMA, dl, VT,
6964 N0.getOperand(0), N0.getOperand(1),
6965 DAG.getNode(ISD::FNEG, dl, VT, N1));
6967 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6968 // Note: Commutes FSUB operands.
6969 if (N1.getOpcode() == ISD::FMUL &&
6970 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6971 return DAG.getNode(ISD::FMA, dl, VT,
6972 DAG.getNode(ISD::FNEG, dl, VT,
6974 N1.getOperand(1), N0);
6976 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6977 if (N0.getOpcode() == ISD::FNEG &&
6978 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6979 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6980 TLI.enableAggressiveFMAFusion(VT))) {
6981 SDValue N00 = N0.getOperand(0).getOperand(0);
6982 SDValue N01 = N0.getOperand(0).getOperand(1);
6983 return DAG.getNode(ISD::FMA, dl, VT,
6984 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6985 DAG.getNode(ISD::FNEG, dl, VT, N1));
6992 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6993 SDValue N0 = N->getOperand(0);
6994 SDValue N1 = N->getOperand(1);
6995 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6996 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6997 EVT VT = N->getValueType(0);
6998 const TargetOptions &Options = DAG.getTarget().Options;
7001 if (VT.isVector()) {
7002 // This just handles C1 * C2 for vectors. Other vector folds are below.
7003 SDValue FoldedVOp = SimplifyVBinOp(N);
7004 if (FoldedVOp.getNode())
7006 // Canonicalize vector constant to RHS.
7007 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7008 N1.getOpcode() != ISD::BUILD_VECTOR)
7009 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7010 if (BV0->isConstant())
7011 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7014 // fold (fmul c1, c2) -> c1*c2
7016 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7018 // canonicalize constant to RHS
7019 if (N0CFP && !N1CFP)
7020 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7022 // fold (fmul A, 1.0) -> A
7023 if (N1CFP && N1CFP->isExactlyValue(1.0))
7026 if (Options.UnsafeFPMath) {
7027 // fold (fmul A, 0) -> 0
7028 if (N1CFP && N1CFP->getValueAPF().isZero())
7031 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7032 if (N0.getOpcode() == ISD::FMUL) {
7033 // Fold scalars or any vector constants (not just splats).
7034 // This fold is done in general by InstCombine, but extra fmul insts
7035 // may have been generated during lowering.
7036 SDValue N01 = N0.getOperand(1);
7037 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7038 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7039 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7040 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7042 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7043 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7047 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7048 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7049 // during an early run of DAGCombiner can prevent folding with fmuls
7050 // inserted during lowering.
7051 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7053 const SDValue Two = DAG.getConstantFP(2.0, VT);
7054 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7055 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7059 // fold (fmul X, 2.0) -> (fadd X, X)
7060 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7061 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7063 // fold (fmul X, -1.0) -> (fneg X)
7064 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7065 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7066 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7068 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7069 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7070 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7071 // Both can be negated for free, check to see if at least one is cheaper
7073 if (LHSNeg == 2 || RHSNeg == 2)
7074 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7075 GetNegatedExpression(N0, DAG, LegalOperations),
7076 GetNegatedExpression(N1, DAG, LegalOperations));
7083 SDValue DAGCombiner::visitFMA(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
7085 SDValue N1 = N->getOperand(1);
7086 SDValue N2 = N->getOperand(2);
7087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7088 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7089 EVT VT = N->getValueType(0);
7091 const TargetOptions &Options = DAG.getTarget().Options;
7093 // Constant fold FMA.
7094 if (isa<ConstantFPSDNode>(N0) &&
7095 isa<ConstantFPSDNode>(N1) &&
7096 isa<ConstantFPSDNode>(N2)) {
7097 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7100 if (Options.UnsafeFPMath) {
7101 if (N0CFP && N0CFP->isZero())
7103 if (N1CFP && N1CFP->isZero())
7106 if (N0CFP && N0CFP->isExactlyValue(1.0))
7107 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7108 if (N1CFP && N1CFP->isExactlyValue(1.0))
7109 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7111 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7112 if (N0CFP && !N1CFP)
7113 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7115 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7116 if (Options.UnsafeFPMath && N1CFP &&
7117 N2.getOpcode() == ISD::FMUL &&
7118 N0 == N2.getOperand(0) &&
7119 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7120 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7121 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7125 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7126 if (Options.UnsafeFPMath &&
7127 N0.getOpcode() == ISD::FMUL && N1CFP &&
7128 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7129 return DAG.getNode(ISD::FMA, dl, VT,
7131 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7135 // (fma x, 1, y) -> (fadd x, y)
7136 // (fma x, -1, y) -> (fadd (fneg x), y)
7138 if (N1CFP->isExactlyValue(1.0))
7139 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7141 if (N1CFP->isExactlyValue(-1.0) &&
7142 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7143 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7144 AddToWorklist(RHSNeg.getNode());
7145 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7149 // (fma x, c, x) -> (fmul x, (c+1))
7150 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7151 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7152 DAG.getNode(ISD::FADD, dl, VT,
7153 N1, DAG.getConstantFP(1.0, VT)));
7155 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7156 if (Options.UnsafeFPMath && N1CFP &&
7157 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7158 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7159 DAG.getNode(ISD::FADD, dl, VT,
7160 N1, DAG.getConstantFP(-1.0, VT)));
7166 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7167 SDValue N0 = N->getOperand(0);
7168 SDValue N1 = N->getOperand(1);
7169 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7170 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7171 EVT VT = N->getValueType(0);
7173 const TargetOptions &Options = DAG.getTarget().Options;
7176 if (VT.isVector()) {
7177 SDValue FoldedVOp = SimplifyVBinOp(N);
7178 if (FoldedVOp.getNode()) return FoldedVOp;
7181 // fold (fdiv c1, c2) -> c1/c2
7183 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7185 if (Options.UnsafeFPMath) {
7186 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7188 // Compute the reciprocal 1.0 / c2.
7189 APFloat N1APF = N1CFP->getValueAPF();
7190 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7191 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7192 // Only do the transform if the reciprocal is a legal fp immediate that
7193 // isn't too nasty (eg NaN, denormal, ...).
7194 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7195 (!LegalOperations ||
7196 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7197 // backend)... we should handle this gracefully after Legalize.
7198 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7199 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7200 TLI.isFPImmLegal(Recip, VT)))
7201 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7202 DAG.getConstantFP(Recip, VT));
7205 // If this FDIV is part of a reciprocal square root, it may be folded
7206 // into a target-specific square root estimate instruction.
7207 if (N1.getOpcode() == ISD::FSQRT) {
7208 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7209 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7211 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7212 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7213 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7214 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7215 AddToWorklist(RV.getNode());
7216 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7218 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7219 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7220 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7221 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7222 AddToWorklist(RV.getNode());
7223 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7225 } else if (N1.getOpcode() == ISD::FMUL) {
7226 // Look through an FMUL. Even though this won't remove the FDIV directly,
7227 // it's still worthwhile to get rid of the FSQRT if possible.
7230 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7231 SqrtOp = N1.getOperand(0);
7232 OtherOp = N1.getOperand(1);
7233 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7234 SqrtOp = N1.getOperand(1);
7235 OtherOp = N1.getOperand(0);
7237 if (SqrtOp.getNode()) {
7238 // We found a FSQRT, so try to make this fold:
7239 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7240 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7241 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7242 AddToWorklist(RV.getNode());
7243 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7248 // Fold into a reciprocal estimate and multiply instead of a real divide.
7249 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7250 AddToWorklist(RV.getNode());
7251 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7255 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7256 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7257 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7258 // Both can be negated for free, check to see if at least one is cheaper
7260 if (LHSNeg == 2 || RHSNeg == 2)
7261 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7262 GetNegatedExpression(N0, DAG, LegalOperations),
7263 GetNegatedExpression(N1, DAG, LegalOperations));
7267 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7269 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7270 // Notice that this is not always beneficial. One reason is different target
7271 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7272 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7273 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7274 if (Options.UnsafeFPMath) {
7275 // Skip if current node is a reciprocal.
7276 if (N0CFP && N0CFP->isExactlyValue(1.0))
7279 SmallVector<SDNode *, 4> Users;
7280 // Find all FDIV users of the same divisor.
7281 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7282 UE = N1.getNode()->use_end();
7284 SDNode *User = UI.getUse().getUser();
7285 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7286 Users.push_back(User);
7289 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7290 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7291 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7293 // Dividend / Divisor -> Dividend * Reciprocal
7294 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7295 if ((*I)->getOperand(0) != FPOne) {
7296 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7297 (*I)->getOperand(0), Reciprocal);
7298 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7308 SDValue DAGCombiner::visitFREM(SDNode *N) {
7309 SDValue N0 = N->getOperand(0);
7310 SDValue N1 = N->getOperand(1);
7311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7313 EVT VT = N->getValueType(0);
7315 // fold (frem c1, c2) -> fmod(c1,c2)
7317 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7322 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7323 if (DAG.getTarget().Options.UnsafeFPMath) {
7324 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7325 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7326 EVT VT = RV.getValueType();
7327 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7328 AddToWorklist(RV.getNode());
7330 // Unfortunately, RV is now NaN if the input was exactly 0.
7331 // Select out this case and force the answer to 0.
7332 SDValue Zero = DAG.getConstantFP(0.0, VT);
7334 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7335 N->getOperand(0), Zero, ISD::SETEQ);
7336 AddToWorklist(ZeroCmp.getNode());
7337 AddToWorklist(RV.getNode());
7339 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7340 SDLoc(N), VT, ZeroCmp, Zero, RV);
7347 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7348 SDValue N0 = N->getOperand(0);
7349 SDValue N1 = N->getOperand(1);
7350 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7351 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7352 EVT VT = N->getValueType(0);
7354 if (N0CFP && N1CFP) // Constant fold
7355 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7358 const APFloat& V = N1CFP->getValueAPF();
7359 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7360 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7361 if (!V.isNegative()) {
7362 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7363 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7365 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7366 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7367 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7371 // copysign(fabs(x), y) -> copysign(x, y)
7372 // copysign(fneg(x), y) -> copysign(x, y)
7373 // copysign(copysign(x,z), y) -> copysign(x, y)
7374 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7375 N0.getOpcode() == ISD::FCOPYSIGN)
7376 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7377 N0.getOperand(0), N1);
7379 // copysign(x, abs(y)) -> abs(x)
7380 if (N1.getOpcode() == ISD::FABS)
7381 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7383 // copysign(x, copysign(y,z)) -> copysign(x, z)
7384 if (N1.getOpcode() == ISD::FCOPYSIGN)
7385 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7386 N0, N1.getOperand(1));
7388 // copysign(x, fp_extend(y)) -> copysign(x, y)
7389 // copysign(x, fp_round(y)) -> copysign(x, y)
7390 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7391 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7392 N0, N1.getOperand(0));
7397 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7398 SDValue N0 = N->getOperand(0);
7399 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7400 EVT VT = N->getValueType(0);
7401 EVT OpVT = N0.getValueType();
7403 // fold (sint_to_fp c1) -> c1fp
7405 // ...but only if the target supports immediate floating-point values
7406 (!LegalOperations ||
7407 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7408 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7410 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7411 // but UINT_TO_FP is legal on this target, try to convert.
7412 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7413 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7414 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7415 if (DAG.SignBitIsZero(N0))
7416 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7419 // The next optimizations are desirable only if SELECT_CC can be lowered.
7420 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7421 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7422 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7424 (!LegalOperations ||
7425 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7427 { N0.getOperand(0), N0.getOperand(1),
7428 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7430 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7433 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7434 // (select_cc x, y, 1.0, 0.0,, cc)
7435 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7436 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7437 (!LegalOperations ||
7438 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7440 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7441 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7442 N0.getOperand(0).getOperand(2) };
7443 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7450 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7451 SDValue N0 = N->getOperand(0);
7452 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7453 EVT VT = N->getValueType(0);
7454 EVT OpVT = N0.getValueType();
7456 // fold (uint_to_fp c1) -> c1fp
7458 // ...but only if the target supports immediate floating-point values
7459 (!LegalOperations ||
7460 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7461 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7463 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7464 // but SINT_TO_FP is legal on this target, try to convert.
7465 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7466 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7467 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7468 if (DAG.SignBitIsZero(N0))
7469 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7472 // The next optimizations are desirable only if SELECT_CC can be lowered.
7473 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7474 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7476 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7477 (!LegalOperations ||
7478 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7480 { N0.getOperand(0), N0.getOperand(1),
7481 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7483 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7490 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7491 SDValue N0 = N->getOperand(0);
7492 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7493 EVT VT = N->getValueType(0);
7495 // fold (fp_to_sint c1fp) -> c1
7497 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7502 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7503 SDValue N0 = N->getOperand(0);
7504 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7505 EVT VT = N->getValueType(0);
7507 // fold (fp_to_uint c1fp) -> c1
7509 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7514 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7515 SDValue N0 = N->getOperand(0);
7516 SDValue N1 = N->getOperand(1);
7517 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7518 EVT VT = N->getValueType(0);
7520 // fold (fp_round c1fp) -> c1fp
7522 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7524 // fold (fp_round (fp_extend x)) -> x
7525 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7526 return N0.getOperand(0);
7528 // fold (fp_round (fp_round x)) -> (fp_round x)
7529 if (N0.getOpcode() == ISD::FP_ROUND) {
7530 // This is a value preserving truncation if both round's are.
7531 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7532 N0.getNode()->getConstantOperandVal(1) == 1;
7533 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7534 DAG.getIntPtrConstant(IsTrunc));
7537 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7538 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7539 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7540 N0.getOperand(0), N1);
7541 AddToWorklist(Tmp.getNode());
7542 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7543 Tmp, N0.getOperand(1));
7549 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7550 SDValue N0 = N->getOperand(0);
7551 EVT VT = N->getValueType(0);
7552 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7553 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7555 // fold (fp_round_inreg c1fp) -> c1fp
7556 if (N0CFP && isTypeLegal(EVT)) {
7557 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7558 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7564 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7565 SDValue N0 = N->getOperand(0);
7566 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7567 EVT VT = N->getValueType(0);
7569 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7570 if (N->hasOneUse() &&
7571 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7574 // fold (fp_extend c1fp) -> c1fp
7576 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7578 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7580 if (N0.getOpcode() == ISD::FP_ROUND
7581 && N0.getNode()->getConstantOperandVal(1) == 1) {
7582 SDValue In = N0.getOperand(0);
7583 if (In.getValueType() == VT) return In;
7584 if (VT.bitsLT(In.getValueType()))
7585 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7586 In, N0.getOperand(1));
7587 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7590 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7591 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7592 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7594 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7596 LN0->getBasePtr(), N0.getValueType(),
7597 LN0->getMemOperand());
7598 CombineTo(N, ExtLoad);
7599 CombineTo(N0.getNode(),
7600 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7601 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7602 ExtLoad.getValue(1));
7603 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7609 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7610 SDValue N0 = N->getOperand(0);
7611 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7612 EVT VT = N->getValueType(0);
7614 // fold (fceil c1) -> fceil(c1)
7616 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7621 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7622 SDValue N0 = N->getOperand(0);
7623 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7624 EVT VT = N->getValueType(0);
7626 // fold (ftrunc c1) -> ftrunc(c1)
7628 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7633 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7634 SDValue N0 = N->getOperand(0);
7635 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7636 EVT VT = N->getValueType(0);
7638 // fold (ffloor c1) -> ffloor(c1)
7640 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7645 // FIXME: FNEG and FABS have a lot in common; refactor.
7646 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7647 SDValue N0 = N->getOperand(0);
7648 EVT VT = N->getValueType(0);
7650 if (VT.isVector()) {
7651 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7652 if (FoldedVOp.getNode()) return FoldedVOp;
7655 // Constant fold FNEG.
7656 if (isa<ConstantFPSDNode>(N0))
7657 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7659 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7660 &DAG.getTarget().Options))
7661 return GetNegatedExpression(N0, DAG, LegalOperations);
7663 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7664 // constant pool values.
7665 if (!TLI.isFNegFree(VT) &&
7666 N0.getOpcode() == ISD::BITCAST &&
7667 N0.getNode()->hasOneUse()) {
7668 SDValue Int = N0.getOperand(0);
7669 EVT IntVT = Int.getValueType();
7670 if (IntVT.isInteger() && !IntVT.isVector()) {
7672 if (N0.getValueType().isVector()) {
7673 // For a vector, get a mask such as 0x80... per scalar element
7675 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7676 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7678 // For a scalar, just generate 0x80...
7679 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7681 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7682 DAG.getConstant(SignMask, IntVT));
7683 AddToWorklist(Int.getNode());
7684 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7688 // (fneg (fmul c, x)) -> (fmul -c, x)
7689 if (N0.getOpcode() == ISD::FMUL) {
7690 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7692 APFloat CVal = CFP1->getValueAPF();
7694 if (Level >= AfterLegalizeDAG &&
7695 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7696 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7698 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7699 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7706 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7707 SDValue N0 = N->getOperand(0);
7708 SDValue N1 = N->getOperand(1);
7709 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7710 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7712 if (N0CFP && N1CFP) {
7713 const APFloat &C0 = N0CFP->getValueAPF();
7714 const APFloat &C1 = N1CFP->getValueAPF();
7715 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7719 EVT VT = N->getValueType(0);
7720 // Canonicalize to constant on RHS.
7721 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7727 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7728 SDValue N0 = N->getOperand(0);
7729 SDValue N1 = N->getOperand(1);
7730 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7731 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7733 if (N0CFP && N1CFP) {
7734 const APFloat &C0 = N0CFP->getValueAPF();
7735 const APFloat &C1 = N1CFP->getValueAPF();
7736 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7740 EVT VT = N->getValueType(0);
7741 // Canonicalize to constant on RHS.
7742 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7748 SDValue DAGCombiner::visitFABS(SDNode *N) {
7749 SDValue N0 = N->getOperand(0);
7750 EVT VT = N->getValueType(0);
7752 if (VT.isVector()) {
7753 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7754 if (FoldedVOp.getNode()) return FoldedVOp;
7757 // fold (fabs c1) -> fabs(c1)
7758 if (isa<ConstantFPSDNode>(N0))
7759 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7761 // fold (fabs (fabs x)) -> (fabs x)
7762 if (N0.getOpcode() == ISD::FABS)
7763 return N->getOperand(0);
7765 // fold (fabs (fneg x)) -> (fabs x)
7766 // fold (fabs (fcopysign x, y)) -> (fabs x)
7767 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7768 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7770 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7771 // constant pool values.
7772 if (!TLI.isFAbsFree(VT) &&
7773 N0.getOpcode() == ISD::BITCAST &&
7774 N0.getNode()->hasOneUse()) {
7775 SDValue Int = N0.getOperand(0);
7776 EVT IntVT = Int.getValueType();
7777 if (IntVT.isInteger() && !IntVT.isVector()) {
7779 if (N0.getValueType().isVector()) {
7780 // For a vector, get a mask such as 0x7f... per scalar element
7782 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7783 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7785 // For a scalar, just generate 0x7f...
7786 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7788 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7789 DAG.getConstant(SignMask, IntVT));
7790 AddToWorklist(Int.getNode());
7791 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7798 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7799 SDValue Chain = N->getOperand(0);
7800 SDValue N1 = N->getOperand(1);
7801 SDValue N2 = N->getOperand(2);
7803 // If N is a constant we could fold this into a fallthrough or unconditional
7804 // branch. However that doesn't happen very often in normal code, because
7805 // Instcombine/SimplifyCFG should have handled the available opportunities.
7806 // If we did this folding here, it would be necessary to update the
7807 // MachineBasicBlock CFG, which is awkward.
7809 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7811 if (N1.getOpcode() == ISD::SETCC &&
7812 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7813 N1.getOperand(0).getValueType())) {
7814 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7815 Chain, N1.getOperand(2),
7816 N1.getOperand(0), N1.getOperand(1), N2);
7819 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7820 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7821 (N1.getOperand(0).hasOneUse() &&
7822 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7823 SDNode *Trunc = nullptr;
7824 if (N1.getOpcode() == ISD::TRUNCATE) {
7825 // Look pass the truncate.
7826 Trunc = N1.getNode();
7827 N1 = N1.getOperand(0);
7830 // Match this pattern so that we can generate simpler code:
7833 // %b = and i32 %a, 2
7834 // %c = srl i32 %b, 1
7835 // brcond i32 %c ...
7840 // %b = and i32 %a, 2
7841 // %c = setcc eq %b, 0
7844 // This applies only when the AND constant value has one bit set and the
7845 // SRL constant is equal to the log2 of the AND constant. The back-end is
7846 // smart enough to convert the result into a TEST/JMP sequence.
7847 SDValue Op0 = N1.getOperand(0);
7848 SDValue Op1 = N1.getOperand(1);
7850 if (Op0.getOpcode() == ISD::AND &&
7851 Op1.getOpcode() == ISD::Constant) {
7852 SDValue AndOp1 = Op0.getOperand(1);
7854 if (AndOp1.getOpcode() == ISD::Constant) {
7855 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7857 if (AndConst.isPowerOf2() &&
7858 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7860 DAG.getSetCC(SDLoc(N),
7861 getSetCCResultType(Op0.getValueType()),
7862 Op0, DAG.getConstant(0, Op0.getValueType()),
7865 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7866 MVT::Other, Chain, SetCC, N2);
7867 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7868 // will convert it back to (X & C1) >> C2.
7869 CombineTo(N, NewBRCond, false);
7870 // Truncate is dead.
7872 deleteAndRecombine(Trunc);
7873 // Replace the uses of SRL with SETCC
7874 WorklistRemover DeadNodes(*this);
7875 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7876 deleteAndRecombine(N1.getNode());
7877 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7883 // Restore N1 if the above transformation doesn't match.
7884 N1 = N->getOperand(1);
7887 // Transform br(xor(x, y)) -> br(x != y)
7888 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7889 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7890 SDNode *TheXor = N1.getNode();
7891 SDValue Op0 = TheXor->getOperand(0);
7892 SDValue Op1 = TheXor->getOperand(1);
7893 if (Op0.getOpcode() == Op1.getOpcode()) {
7894 // Avoid missing important xor optimizations.
7895 SDValue Tmp = visitXOR(TheXor);
7896 if (Tmp.getNode()) {
7897 if (Tmp.getNode() != TheXor) {
7898 DEBUG(dbgs() << "\nReplacing.8 ";
7900 dbgs() << "\nWith: ";
7901 Tmp.getNode()->dump(&DAG);
7903 WorklistRemover DeadNodes(*this);
7904 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7905 deleteAndRecombine(TheXor);
7906 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7907 MVT::Other, Chain, Tmp, N2);
7910 // visitXOR has changed XOR's operands or replaced the XOR completely,
7912 return SDValue(N, 0);
7916 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7918 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7919 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7920 Op0.getOpcode() == ISD::XOR) {
7921 TheXor = Op0.getNode();
7925 EVT SetCCVT = N1.getValueType();
7927 SetCCVT = getSetCCResultType(SetCCVT);
7928 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7931 Equal ? ISD::SETEQ : ISD::SETNE);
7932 // Replace the uses of XOR with SETCC
7933 WorklistRemover DeadNodes(*this);
7934 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7935 deleteAndRecombine(N1.getNode());
7936 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7937 MVT::Other, Chain, SetCC, N2);
7944 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7946 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7947 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7948 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7950 // If N is a constant we could fold this into a fallthrough or unconditional
7951 // branch. However that doesn't happen very often in normal code, because
7952 // Instcombine/SimplifyCFG should have handled the available opportunities.
7953 // If we did this folding here, it would be necessary to update the
7954 // MachineBasicBlock CFG, which is awkward.
7956 // Use SimplifySetCC to simplify SETCC's.
7957 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7958 CondLHS, CondRHS, CC->get(), SDLoc(N),
7960 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7962 // fold to a simpler setcc
7963 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7964 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7965 N->getOperand(0), Simp.getOperand(2),
7966 Simp.getOperand(0), Simp.getOperand(1),
7972 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7973 /// and that N may be folded in the load / store addressing mode.
7974 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7976 const TargetLowering &TLI) {
7978 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7979 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7981 VT = Use->getValueType(0);
7982 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7983 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7985 VT = ST->getValue().getValueType();
7989 TargetLowering::AddrMode AM;
7990 if (N->getOpcode() == ISD::ADD) {
7991 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7994 AM.BaseOffs = Offset->getSExtValue();
7998 } else if (N->getOpcode() == ISD::SUB) {
7999 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8002 AM.BaseOffs = -Offset->getSExtValue();
8009 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8012 /// Try turning a load/store into a pre-indexed load/store when the base
8013 /// pointer is an add or subtract and it has other uses besides the load/store.
8014 /// After the transformation, the new indexed load/store has effectively folded
8015 /// the add/subtract in and all of its other uses are redirected to the
8017 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8018 if (Level < AfterLegalizeDAG)
8024 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8025 if (LD->isIndexed())
8027 VT = LD->getMemoryVT();
8028 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8029 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8031 Ptr = LD->getBasePtr();
8032 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8033 if (ST->isIndexed())
8035 VT = ST->getMemoryVT();
8036 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8037 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8039 Ptr = ST->getBasePtr();
8045 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8046 // out. There is no reason to make this a preinc/predec.
8047 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8048 Ptr.getNode()->hasOneUse())
8051 // Ask the target to do addressing mode selection.
8054 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8055 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8058 // Backends without true r+i pre-indexed forms may need to pass a
8059 // constant base with a variable offset so that constant coercion
8060 // will work with the patterns in canonical form.
8061 bool Swapped = false;
8062 if (isa<ConstantSDNode>(BasePtr)) {
8063 std::swap(BasePtr, Offset);
8067 // Don't create a indexed load / store with zero offset.
8068 if (isa<ConstantSDNode>(Offset) &&
8069 cast<ConstantSDNode>(Offset)->isNullValue())
8072 // Try turning it into a pre-indexed load / store except when:
8073 // 1) The new base ptr is a frame index.
8074 // 2) If N is a store and the new base ptr is either the same as or is a
8075 // predecessor of the value being stored.
8076 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8077 // that would create a cycle.
8078 // 4) All uses are load / store ops that use it as old base ptr.
8080 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8081 // (plus the implicit offset) to a register to preinc anyway.
8082 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8087 SDValue Val = cast<StoreSDNode>(N)->getValue();
8088 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8092 // If the offset is a constant, there may be other adds of constants that
8093 // can be folded with this one. We should do this to avoid having to keep
8094 // a copy of the original base pointer.
8095 SmallVector<SDNode *, 16> OtherUses;
8096 if (isa<ConstantSDNode>(Offset))
8097 for (SDNode *Use : BasePtr.getNode()->uses()) {
8098 if (Use == Ptr.getNode())
8101 if (Use->isPredecessorOf(N))
8104 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8109 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8110 if (Op1.getNode() == BasePtr.getNode())
8111 std::swap(Op0, Op1);
8112 assert(Op0.getNode() == BasePtr.getNode() &&
8113 "Use of ADD/SUB but not an operand");
8115 if (!isa<ConstantSDNode>(Op1)) {
8120 // FIXME: In some cases, we can be smarter about this.
8121 if (Op1.getValueType() != Offset.getValueType()) {
8126 OtherUses.push_back(Use);
8130 std::swap(BasePtr, Offset);
8132 // Now check for #3 and #4.
8133 bool RealUse = false;
8135 // Caches for hasPredecessorHelper
8136 SmallPtrSet<const SDNode *, 32> Visited;
8137 SmallVector<const SDNode *, 16> Worklist;
8139 for (SDNode *Use : Ptr.getNode()->uses()) {
8142 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8145 // If Ptr may be folded in addressing mode of other use, then it's
8146 // not profitable to do this transformation.
8147 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8156 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8157 BasePtr, Offset, AM);
8159 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8160 BasePtr, Offset, AM);
8163 DEBUG(dbgs() << "\nReplacing.4 ";
8165 dbgs() << "\nWith: ";
8166 Result.getNode()->dump(&DAG);
8168 WorklistRemover DeadNodes(*this);
8170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8171 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8173 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8176 // Finally, since the node is now dead, remove it from the graph.
8177 deleteAndRecombine(N);
8180 std::swap(BasePtr, Offset);
8182 // Replace other uses of BasePtr that can be updated to use Ptr
8183 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8184 unsigned OffsetIdx = 1;
8185 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8187 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8188 BasePtr.getNode() && "Expected BasePtr operand");
8190 // We need to replace ptr0 in the following expression:
8191 // x0 * offset0 + y0 * ptr0 = t0
8193 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8195 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8196 // indexed load/store and the expresion that needs to be re-written.
8198 // Therefore, we have:
8199 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8201 ConstantSDNode *CN =
8202 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8204 APInt Offset0 = CN->getAPIntValue();
8205 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8207 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8208 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8209 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8210 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8212 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8214 APInt CNV = Offset0;
8215 if (X0 < 0) CNV = -CNV;
8216 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8217 else CNV = CNV - Offset1;
8219 // We can now generate the new expression.
8220 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8221 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8223 SDValue NewUse = DAG.getNode(Opcode,
8224 SDLoc(OtherUses[i]),
8225 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8226 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8227 deleteAndRecombine(OtherUses[i]);
8230 // Replace the uses of Ptr with uses of the updated base value.
8231 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8232 deleteAndRecombine(Ptr.getNode());
8237 /// Try to combine a load/store with a add/sub of the base pointer node into a
8238 /// post-indexed load/store. The transformation folded the add/subtract into the
8239 /// new indexed load/store effectively and all of its uses are redirected to the
8241 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8242 if (Level < AfterLegalizeDAG)
8248 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8249 if (LD->isIndexed())
8251 VT = LD->getMemoryVT();
8252 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8253 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8255 Ptr = LD->getBasePtr();
8256 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8257 if (ST->isIndexed())
8259 VT = ST->getMemoryVT();
8260 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8261 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8263 Ptr = ST->getBasePtr();
8269 if (Ptr.getNode()->hasOneUse())
8272 for (SDNode *Op : Ptr.getNode()->uses()) {
8274 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8279 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8280 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8281 // Don't create a indexed load / store with zero offset.
8282 if (isa<ConstantSDNode>(Offset) &&
8283 cast<ConstantSDNode>(Offset)->isNullValue())
8286 // Try turning it into a post-indexed load / store except when
8287 // 1) All uses are load / store ops that use it as base ptr (and
8288 // it may be folded as addressing mmode).
8289 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8290 // nor a successor of N. Otherwise, if Op is folded that would
8293 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8297 bool TryNext = false;
8298 for (SDNode *Use : BasePtr.getNode()->uses()) {
8299 if (Use == Ptr.getNode())
8302 // If all the uses are load / store addresses, then don't do the
8304 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8305 bool RealUse = false;
8306 for (SDNode *UseUse : Use->uses()) {
8307 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8322 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8323 SDValue Result = isLoad
8324 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8325 BasePtr, Offset, AM)
8326 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8327 BasePtr, Offset, AM);
8330 DEBUG(dbgs() << "\nReplacing.5 ";
8332 dbgs() << "\nWith: ";
8333 Result.getNode()->dump(&DAG);
8335 WorklistRemover DeadNodes(*this);
8337 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8338 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8340 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8343 // Finally, since the node is now dead, remove it from the graph.
8344 deleteAndRecombine(N);
8346 // Replace the uses of Use with uses of the updated base value.
8347 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8348 Result.getValue(isLoad ? 1 : 0));
8349 deleteAndRecombine(Op);
8358 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8359 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8360 ISD::MemIndexedMode AM = LD->getAddressingMode();
8361 assert(AM != ISD::UNINDEXED);
8362 SDValue BP = LD->getOperand(1);
8363 SDValue Inc = LD->getOperand(2);
8365 // Some backends use TargetConstants for load offsets, but don't expect
8366 // TargetConstants in general ADD nodes. We can convert these constants into
8367 // regular Constants (if the constant is not opaque).
8368 assert((Inc.getOpcode() != ISD::TargetConstant ||
8369 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8370 "Cannot split out indexing using opaque target constants");
8371 if (Inc.getOpcode() == ISD::TargetConstant) {
8372 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8373 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8374 ConstInc->getValueType(0));
8378 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8379 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8382 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8383 LoadSDNode *LD = cast<LoadSDNode>(N);
8384 SDValue Chain = LD->getChain();
8385 SDValue Ptr = LD->getBasePtr();
8387 // If load is not volatile and there are no uses of the loaded value (and
8388 // the updated indexed value in case of indexed loads), change uses of the
8389 // chain value into uses of the chain input (i.e. delete the dead load).
8390 if (!LD->isVolatile()) {
8391 if (N->getValueType(1) == MVT::Other) {
8393 if (!N->hasAnyUseOfValue(0)) {
8394 // It's not safe to use the two value CombineTo variant here. e.g.
8395 // v1, chain2 = load chain1, loc
8396 // v2, chain3 = load chain2, loc
8398 // Now we replace use of chain2 with chain1. This makes the second load
8399 // isomorphic to the one we are deleting, and thus makes this load live.
8400 DEBUG(dbgs() << "\nReplacing.6 ";
8402 dbgs() << "\nWith chain: ";
8403 Chain.getNode()->dump(&DAG);
8405 WorklistRemover DeadNodes(*this);
8406 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8409 deleteAndRecombine(N);
8411 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8415 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8417 // If this load has an opaque TargetConstant offset, then we cannot split
8418 // the indexing into an add/sub directly (that TargetConstant may not be
8419 // valid for a different type of node, and we cannot convert an opaque
8420 // target constant into a regular constant).
8421 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8422 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8424 if (!N->hasAnyUseOfValue(0) &&
8425 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8426 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8428 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8429 Index = SplitIndexingFromLoad(LD);
8430 // Try to fold the base pointer arithmetic into subsequent loads and
8432 AddUsersToWorklist(N);
8434 Index = DAG.getUNDEF(N->getValueType(1));
8435 DEBUG(dbgs() << "\nReplacing.7 ";
8437 dbgs() << "\nWith: ";
8438 Undef.getNode()->dump(&DAG);
8439 dbgs() << " and 2 other values\n");
8440 WorklistRemover DeadNodes(*this);
8441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8444 deleteAndRecombine(N);
8445 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8450 // If this load is directly stored, replace the load value with the stored
8452 // TODO: Handle store large -> read small portion.
8453 // TODO: Handle TRUNCSTORE/LOADEXT
8454 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8455 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8456 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8457 if (PrevST->getBasePtr() == Ptr &&
8458 PrevST->getValue().getValueType() == N->getValueType(0))
8459 return CombineTo(N, Chain.getOperand(1), Chain);
8463 // Try to infer better alignment information than the load already has.
8464 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8465 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8466 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8468 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8469 LD->getValueType(0),
8470 Chain, Ptr, LD->getPointerInfo(),
8472 LD->isVolatile(), LD->isNonTemporal(),
8473 LD->isInvariant(), Align, LD->getAAInfo());
8474 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8479 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8480 : DAG.getSubtarget().useAA();
8482 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8483 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8486 if (UseAA && LD->isUnindexed()) {
8487 // Walk up chain skipping non-aliasing memory nodes.
8488 SDValue BetterChain = FindBetterChain(N, Chain);
8490 // If there is a better chain.
8491 if (Chain != BetterChain) {
8494 // Replace the chain to void dependency.
8495 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8496 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8497 BetterChain, Ptr, LD->getMemOperand());
8499 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8500 LD->getValueType(0),
8501 BetterChain, Ptr, LD->getMemoryVT(),
8502 LD->getMemOperand());
8505 // Create token factor to keep old chain connected.
8506 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8507 MVT::Other, Chain, ReplLoad.getValue(1));
8509 // Make sure the new and old chains are cleaned up.
8510 AddToWorklist(Token.getNode());
8512 // Replace uses with load result and token factor. Don't add users
8514 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8518 // Try transforming N to an indexed load.
8519 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8520 return SDValue(N, 0);
8522 // Try to slice up N to more direct loads if the slices are mapped to
8523 // different register banks or pairing can take place.
8525 return SDValue(N, 0);
8531 /// \brief Helper structure used to slice a load in smaller loads.
8532 /// Basically a slice is obtained from the following sequence:
8533 /// Origin = load Ty1, Base
8534 /// Shift = srl Ty1 Origin, CstTy Amount
8535 /// Inst = trunc Shift to Ty2
8537 /// Then, it will be rewriten into:
8538 /// Slice = load SliceTy, Base + SliceOffset
8539 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8541 /// SliceTy is deduced from the number of bits that are actually used to
8543 struct LoadedSlice {
8544 /// \brief Helper structure used to compute the cost of a slice.
8546 /// Are we optimizing for code size.
8551 unsigned CrossRegisterBanksCopies;
8555 Cost(bool ForCodeSize = false)
8556 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8557 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8559 /// \brief Get the cost of one isolated slice.
8560 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8561 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8562 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8563 EVT TruncType = LS.Inst->getValueType(0);
8564 EVT LoadedType = LS.getLoadedType();
8565 if (TruncType != LoadedType &&
8566 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8570 /// \brief Account for slicing gain in the current cost.
8571 /// Slicing provide a few gains like removing a shift or a
8572 /// truncate. This method allows to grow the cost of the original
8573 /// load with the gain from this slice.
8574 void addSliceGain(const LoadedSlice &LS) {
8575 // Each slice saves a truncate.
8576 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8577 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8578 LS.Inst->getOperand(0).getValueType()))
8580 // If there is a shift amount, this slice gets rid of it.
8583 // If this slice can merge a cross register bank copy, account for it.
8584 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8585 ++CrossRegisterBanksCopies;
8588 Cost &operator+=(const Cost &RHS) {
8590 Truncates += RHS.Truncates;
8591 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8597 bool operator==(const Cost &RHS) const {
8598 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8599 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8600 ZExts == RHS.ZExts && Shift == RHS.Shift;
8603 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8605 bool operator<(const Cost &RHS) const {
8606 // Assume cross register banks copies are as expensive as loads.
8607 // FIXME: Do we want some more target hooks?
8608 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8609 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8610 // Unless we are optimizing for code size, consider the
8611 // expensive operation first.
8612 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8613 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8614 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8615 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8618 bool operator>(const Cost &RHS) const { return RHS < *this; }
8620 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8622 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8624 // The last instruction that represent the slice. This should be a
8625 // truncate instruction.
8627 // The original load instruction.
8629 // The right shift amount in bits from the original load.
8631 // The DAG from which Origin came from.
8632 // This is used to get some contextual information about legal types, etc.
8635 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8636 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8637 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8639 LoadedSlice(const LoadedSlice &LS)
8640 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8642 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8643 /// \return Result is \p BitWidth and has used bits set to 1 and
8644 /// not used bits set to 0.
8645 APInt getUsedBits() const {
8646 // Reproduce the trunc(lshr) sequence:
8647 // - Start from the truncated value.
8648 // - Zero extend to the desired bit width.
8650 assert(Origin && "No original load to compare against.");
8651 unsigned BitWidth = Origin->getValueSizeInBits(0);
8652 assert(Inst && "This slice is not bound to an instruction");
8653 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8654 "Extracted slice is bigger than the whole type!");
8655 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8656 UsedBits.setAllBits();
8657 UsedBits = UsedBits.zext(BitWidth);
8662 /// \brief Get the size of the slice to be loaded in bytes.
8663 unsigned getLoadedSize() const {
8664 unsigned SliceSize = getUsedBits().countPopulation();
8665 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8666 return SliceSize / 8;
8669 /// \brief Get the type that will be loaded for this slice.
8670 /// Note: This may not be the final type for the slice.
8671 EVT getLoadedType() const {
8672 assert(DAG && "Missing context");
8673 LLVMContext &Ctxt = *DAG->getContext();
8674 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8677 /// \brief Get the alignment of the load used for this slice.
8678 unsigned getAlignment() const {
8679 unsigned Alignment = Origin->getAlignment();
8680 unsigned Offset = getOffsetFromBase();
8682 Alignment = MinAlign(Alignment, Alignment + Offset);
8686 /// \brief Check if this slice can be rewritten with legal operations.
8687 bool isLegal() const {
8688 // An invalid slice is not legal.
8689 if (!Origin || !Inst || !DAG)
8692 // Offsets are for indexed load only, we do not handle that.
8693 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8696 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8698 // Check that the type is legal.
8699 EVT SliceType = getLoadedType();
8700 if (!TLI.isTypeLegal(SliceType))
8703 // Check that the load is legal for this type.
8704 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8707 // Check that the offset can be computed.
8708 // 1. Check its type.
8709 EVT PtrType = Origin->getBasePtr().getValueType();
8710 if (PtrType == MVT::Untyped || PtrType.isExtended())
8713 // 2. Check that it fits in the immediate.
8714 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8717 // 3. Check that the computation is legal.
8718 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8721 // Check that the zext is legal if it needs one.
8722 EVT TruncateType = Inst->getValueType(0);
8723 if (TruncateType != SliceType &&
8724 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8730 /// \brief Get the offset in bytes of this slice in the original chunk of
8732 /// \pre DAG != nullptr.
8733 uint64_t getOffsetFromBase() const {
8734 assert(DAG && "Missing context.");
8736 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8737 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8738 uint64_t Offset = Shift / 8;
8739 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8740 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8741 "The size of the original loaded type is not a multiple of a"
8743 // If Offset is bigger than TySizeInBytes, it means we are loading all
8744 // zeros. This should have been optimized before in the process.
8745 assert(TySizeInBytes > Offset &&
8746 "Invalid shift amount for given loaded size");
8748 Offset = TySizeInBytes - Offset - getLoadedSize();
8752 /// \brief Generate the sequence of instructions to load the slice
8753 /// represented by this object and redirect the uses of this slice to
8754 /// this new sequence of instructions.
8755 /// \pre this->Inst && this->Origin are valid Instructions and this
8756 /// object passed the legal check: LoadedSlice::isLegal returned true.
8757 /// \return The last instruction of the sequence used to load the slice.
8758 SDValue loadSlice() const {
8759 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8760 const SDValue &OldBaseAddr = Origin->getBasePtr();
8761 SDValue BaseAddr = OldBaseAddr;
8762 // Get the offset in that chunk of bytes w.r.t. the endianess.
8763 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8764 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8766 // BaseAddr = BaseAddr + Offset.
8767 EVT ArithType = BaseAddr.getValueType();
8768 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8769 DAG->getConstant(Offset, ArithType));
8772 // Create the type of the loaded slice according to its size.
8773 EVT SliceType = getLoadedType();
8775 // Create the load for the slice.
8776 SDValue LastInst = DAG->getLoad(
8777 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8778 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8779 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8780 // If the final type is not the same as the loaded type, this means that
8781 // we have to pad with zero. Create a zero extend for that.
8782 EVT FinalType = Inst->getValueType(0);
8783 if (SliceType != FinalType)
8785 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8789 /// \brief Check if this slice can be merged with an expensive cross register
8790 /// bank copy. E.g.,
8792 /// f = bitcast i32 i to float
8793 bool canMergeExpensiveCrossRegisterBankCopy() const {
8794 if (!Inst || !Inst->hasOneUse())
8796 SDNode *Use = *Inst->use_begin();
8797 if (Use->getOpcode() != ISD::BITCAST)
8799 assert(DAG && "Missing context");
8800 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8801 EVT ResVT = Use->getValueType(0);
8802 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8803 const TargetRegisterClass *ArgRC =
8804 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8805 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8808 // At this point, we know that we perform a cross-register-bank copy.
8809 // Check if it is expensive.
8810 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8811 // Assume bitcasts are cheap, unless both register classes do not
8812 // explicitly share a common sub class.
8813 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8816 // Check if it will be merged with the load.
8817 // 1. Check the alignment constraint.
8818 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8819 ResVT.getTypeForEVT(*DAG->getContext()));
8821 if (RequiredAlignment > getAlignment())
8824 // 2. Check that the load is a legal operation for that type.
8825 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8828 // 3. Check that we do not have a zext in the way.
8829 if (Inst->getValueType(0) != getLoadedType())
8837 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8838 /// \p UsedBits looks like 0..0 1..1 0..0.
8839 static bool areUsedBitsDense(const APInt &UsedBits) {
8840 // If all the bits are one, this is dense!
8841 if (UsedBits.isAllOnesValue())
8844 // Get rid of the unused bits on the right.
8845 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8846 // Get rid of the unused bits on the left.
8847 if (NarrowedUsedBits.countLeadingZeros())
8848 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8849 // Check that the chunk of bits is completely used.
8850 return NarrowedUsedBits.isAllOnesValue();
8853 /// \brief Check whether or not \p First and \p Second are next to each other
8854 /// in memory. This means that there is no hole between the bits loaded
8855 /// by \p First and the bits loaded by \p Second.
8856 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8857 const LoadedSlice &Second) {
8858 assert(First.Origin == Second.Origin && First.Origin &&
8859 "Unable to match different memory origins.");
8860 APInt UsedBits = First.getUsedBits();
8861 assert((UsedBits & Second.getUsedBits()) == 0 &&
8862 "Slices are not supposed to overlap.");
8863 UsedBits |= Second.getUsedBits();
8864 return areUsedBitsDense(UsedBits);
8867 /// \brief Adjust the \p GlobalLSCost according to the target
8868 /// paring capabilities and the layout of the slices.
8869 /// \pre \p GlobalLSCost should account for at least as many loads as
8870 /// there is in the slices in \p LoadedSlices.
8871 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8872 LoadedSlice::Cost &GlobalLSCost) {
8873 unsigned NumberOfSlices = LoadedSlices.size();
8874 // If there is less than 2 elements, no pairing is possible.
8875 if (NumberOfSlices < 2)
8878 // Sort the slices so that elements that are likely to be next to each
8879 // other in memory are next to each other in the list.
8880 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8881 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8882 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8883 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8885 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8886 // First (resp. Second) is the first (resp. Second) potentially candidate
8887 // to be placed in a paired load.
8888 const LoadedSlice *First = nullptr;
8889 const LoadedSlice *Second = nullptr;
8890 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8891 // Set the beginning of the pair.
8894 Second = &LoadedSlices[CurrSlice];
8896 // If First is NULL, it means we start a new pair.
8897 // Get to the next slice.
8901 EVT LoadedType = First->getLoadedType();
8903 // If the types of the slices are different, we cannot pair them.
8904 if (LoadedType != Second->getLoadedType())
8907 // Check if the target supplies paired loads for this type.
8908 unsigned RequiredAlignment = 0;
8909 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8910 // move to the next pair, this type is hopeless.
8914 // Check if we meet the alignment requirement.
8915 if (RequiredAlignment > First->getAlignment())
8918 // Check that both loads are next to each other in memory.
8919 if (!areSlicesNextToEachOther(*First, *Second))
8922 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8923 --GlobalLSCost.Loads;
8924 // Move to the next pair.
8929 /// \brief Check the profitability of all involved LoadedSlice.
8930 /// Currently, it is considered profitable if there is exactly two
8931 /// involved slices (1) which are (2) next to each other in memory, and
8932 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8934 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8935 /// the elements themselves.
8937 /// FIXME: When the cost model will be mature enough, we can relax
8938 /// constraints (1) and (2).
8939 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8940 const APInt &UsedBits, bool ForCodeSize) {
8941 unsigned NumberOfSlices = LoadedSlices.size();
8942 if (StressLoadSlicing)
8943 return NumberOfSlices > 1;
8946 if (NumberOfSlices != 2)
8950 if (!areUsedBitsDense(UsedBits))
8954 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8955 // The original code has one big load.
8957 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8958 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8959 // Accumulate the cost of all the slices.
8960 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8961 GlobalSlicingCost += SliceCost;
8963 // Account as cost in the original configuration the gain obtained
8964 // with the current slices.
8965 OrigCost.addSliceGain(LS);
8968 // If the target supports paired load, adjust the cost accordingly.
8969 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8970 return OrigCost > GlobalSlicingCost;
8973 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8974 /// operations, split it in the various pieces being extracted.
8976 /// This sort of thing is introduced by SROA.
8977 /// This slicing takes care not to insert overlapping loads.
8978 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8979 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8980 if (Level < AfterLegalizeDAG)
8983 LoadSDNode *LD = cast<LoadSDNode>(N);
8984 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8985 !LD->getValueType(0).isInteger())
8988 // Keep track of already used bits to detect overlapping values.
8989 // In that case, we will just abort the transformation.
8990 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8992 SmallVector<LoadedSlice, 4> LoadedSlices;
8994 // Check if this load is used as several smaller chunks of bits.
8995 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8996 // of computation for each trunc.
8997 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8998 UI != UIEnd; ++UI) {
8999 // Skip the uses of the chain.
9000 if (UI.getUse().getResNo() != 0)
9006 // Check if this is a trunc(lshr).
9007 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9008 isa<ConstantSDNode>(User->getOperand(1))) {
9009 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9010 User = *User->use_begin();
9013 // At this point, User is a Truncate, iff we encountered, trunc or
9015 if (User->getOpcode() != ISD::TRUNCATE)
9018 // The width of the type must be a power of 2 and greater than 8-bits.
9019 // Otherwise the load cannot be represented in LLVM IR.
9020 // Moreover, if we shifted with a non-8-bits multiple, the slice
9021 // will be across several bytes. We do not support that.
9022 unsigned Width = User->getValueSizeInBits(0);
9023 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9026 // Build the slice for this chain of computations.
9027 LoadedSlice LS(User, LD, Shift, &DAG);
9028 APInt CurrentUsedBits = LS.getUsedBits();
9030 // Check if this slice overlaps with another.
9031 if ((CurrentUsedBits & UsedBits) != 0)
9033 // Update the bits used globally.
9034 UsedBits |= CurrentUsedBits;
9036 // Check if the new slice would be legal.
9040 // Record the slice.
9041 LoadedSlices.push_back(LS);
9044 // Abort slicing if it does not seem to be profitable.
9045 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9050 // Rewrite each chain to use an independent load.
9051 // By construction, each chain can be represented by a unique load.
9053 // Prepare the argument for the new token factor for all the slices.
9054 SmallVector<SDValue, 8> ArgChains;
9055 for (SmallVectorImpl<LoadedSlice>::const_iterator
9056 LSIt = LoadedSlices.begin(),
9057 LSItEnd = LoadedSlices.end();
9058 LSIt != LSItEnd; ++LSIt) {
9059 SDValue SliceInst = LSIt->loadSlice();
9060 CombineTo(LSIt->Inst, SliceInst, true);
9061 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9062 SliceInst = SliceInst.getOperand(0);
9063 assert(SliceInst->getOpcode() == ISD::LOAD &&
9064 "It takes more than a zext to get to the loaded slice!!");
9065 ArgChains.push_back(SliceInst.getValue(1));
9068 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9074 /// Check to see if V is (and load (ptr), imm), where the load is having
9075 /// specific bytes cleared out. If so, return the byte size being masked out
9076 /// and the shift amount.
9077 static std::pair<unsigned, unsigned>
9078 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9079 std::pair<unsigned, unsigned> Result(0, 0);
9081 // Check for the structure we're looking for.
9082 if (V->getOpcode() != ISD::AND ||
9083 !isa<ConstantSDNode>(V->getOperand(1)) ||
9084 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9087 // Check the chain and pointer.
9088 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9089 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9091 // The store should be chained directly to the load or be an operand of a
9093 if (LD == Chain.getNode())
9095 else if (Chain->getOpcode() != ISD::TokenFactor)
9096 return Result; // Fail.
9099 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9100 if (Chain->getOperand(i).getNode() == LD) {
9104 if (!isOk) return Result;
9107 // This only handles simple types.
9108 if (V.getValueType() != MVT::i16 &&
9109 V.getValueType() != MVT::i32 &&
9110 V.getValueType() != MVT::i64)
9113 // Check the constant mask. Invert it so that the bits being masked out are
9114 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9115 // follow the sign bit for uniformity.
9116 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9117 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9118 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9119 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9120 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9121 if (NotMaskLZ == 64) return Result; // All zero mask.
9123 // See if we have a continuous run of bits. If so, we have 0*1+0*
9124 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9127 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9128 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9129 NotMaskLZ -= 64-V.getValueSizeInBits();
9131 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9132 switch (MaskedBytes) {
9136 default: return Result; // All one mask, or 5-byte mask.
9139 // Verify that the first bit starts at a multiple of mask so that the access
9140 // is aligned the same as the access width.
9141 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9143 Result.first = MaskedBytes;
9144 Result.second = NotMaskTZ/8;
9149 /// Check to see if IVal is something that provides a value as specified by
9150 /// MaskInfo. If so, replace the specified store with a narrower store of
9153 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9154 SDValue IVal, StoreSDNode *St,
9156 unsigned NumBytes = MaskInfo.first;
9157 unsigned ByteShift = MaskInfo.second;
9158 SelectionDAG &DAG = DC->getDAG();
9160 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9161 // that uses this. If not, this is not a replacement.
9162 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9163 ByteShift*8, (ByteShift+NumBytes)*8);
9164 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9166 // Check that it is legal on the target to do this. It is legal if the new
9167 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9169 MVT VT = MVT::getIntegerVT(NumBytes*8);
9170 if (!DC->isTypeLegal(VT))
9173 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9174 // shifted by ByteShift and truncated down to NumBytes.
9176 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9177 DAG.getConstant(ByteShift*8,
9178 DC->getShiftAmountTy(IVal.getValueType())));
9180 // Figure out the offset for the store and the alignment of the access.
9182 unsigned NewAlign = St->getAlignment();
9184 if (DAG.getTargetLoweringInfo().isLittleEndian())
9185 StOffset = ByteShift;
9187 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9189 SDValue Ptr = St->getBasePtr();
9191 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9192 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9193 NewAlign = MinAlign(NewAlign, StOffset);
9196 // Truncate down to the new size.
9197 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9200 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9201 St->getPointerInfo().getWithOffset(StOffset),
9202 false, false, NewAlign).getNode();
9206 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9207 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9208 /// narrowing the load and store if it would end up being a win for performance
9210 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9211 StoreSDNode *ST = cast<StoreSDNode>(N);
9212 if (ST->isVolatile())
9215 SDValue Chain = ST->getChain();
9216 SDValue Value = ST->getValue();
9217 SDValue Ptr = ST->getBasePtr();
9218 EVT VT = Value.getValueType();
9220 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9223 unsigned Opc = Value.getOpcode();
9225 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9226 // is a byte mask indicating a consecutive number of bytes, check to see if
9227 // Y is known to provide just those bytes. If so, we try to replace the
9228 // load + replace + store sequence with a single (narrower) store, which makes
9230 if (Opc == ISD::OR) {
9231 std::pair<unsigned, unsigned> MaskedLoad;
9232 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9233 if (MaskedLoad.first)
9234 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9235 Value.getOperand(1), ST,this))
9236 return SDValue(NewST, 0);
9238 // Or is commutative, so try swapping X and Y.
9239 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9240 if (MaskedLoad.first)
9241 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9242 Value.getOperand(0), ST,this))
9243 return SDValue(NewST, 0);
9246 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9247 Value.getOperand(1).getOpcode() != ISD::Constant)
9250 SDValue N0 = Value.getOperand(0);
9251 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9252 Chain == SDValue(N0.getNode(), 1)) {
9253 LoadSDNode *LD = cast<LoadSDNode>(N0);
9254 if (LD->getBasePtr() != Ptr ||
9255 LD->getPointerInfo().getAddrSpace() !=
9256 ST->getPointerInfo().getAddrSpace())
9259 // Find the type to narrow it the load / op / store to.
9260 SDValue N1 = Value.getOperand(1);
9261 unsigned BitWidth = N1.getValueSizeInBits();
9262 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9263 if (Opc == ISD::AND)
9264 Imm ^= APInt::getAllOnesValue(BitWidth);
9265 if (Imm == 0 || Imm.isAllOnesValue())
9267 unsigned ShAmt = Imm.countTrailingZeros();
9268 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9269 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9271 while (NewBW < BitWidth &&
9272 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9273 TLI.isNarrowingProfitable(VT, NewVT))) {
9274 NewBW = NextPowerOf2(NewBW);
9275 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9277 if (NewBW >= BitWidth)
9280 // If the lsb changed does not start at the type bitwidth boundary,
9281 // start at the previous one.
9283 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9284 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9285 std::min(BitWidth, ShAmt + NewBW));
9286 if ((Imm & Mask) == Imm) {
9287 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9288 if (Opc == ISD::AND)
9289 NewImm ^= APInt::getAllOnesValue(NewBW);
9290 uint64_t PtrOff = ShAmt / 8;
9291 // For big endian targets, we need to adjust the offset to the pointer to
9292 // load the correct bytes.
9293 if (TLI.isBigEndian())
9294 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9296 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9297 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9298 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9301 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9302 Ptr.getValueType(), Ptr,
9303 DAG.getConstant(PtrOff, Ptr.getValueType()));
9304 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9305 LD->getChain(), NewPtr,
9306 LD->getPointerInfo().getWithOffset(PtrOff),
9307 LD->isVolatile(), LD->isNonTemporal(),
9308 LD->isInvariant(), NewAlign,
9310 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9311 DAG.getConstant(NewImm, NewVT));
9312 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9314 ST->getPointerInfo().getWithOffset(PtrOff),
9315 false, false, NewAlign);
9317 AddToWorklist(NewPtr.getNode());
9318 AddToWorklist(NewLD.getNode());
9319 AddToWorklist(NewVal.getNode());
9320 WorklistRemover DeadNodes(*this);
9321 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9330 /// For a given floating point load / store pair, if the load value isn't used
9331 /// by any other operations, then consider transforming the pair to integer
9332 /// load / store operations if the target deems the transformation profitable.
9333 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9334 StoreSDNode *ST = cast<StoreSDNode>(N);
9335 SDValue Chain = ST->getChain();
9336 SDValue Value = ST->getValue();
9337 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9338 Value.hasOneUse() &&
9339 Chain == SDValue(Value.getNode(), 1)) {
9340 LoadSDNode *LD = cast<LoadSDNode>(Value);
9341 EVT VT = LD->getMemoryVT();
9342 if (!VT.isFloatingPoint() ||
9343 VT != ST->getMemoryVT() ||
9344 LD->isNonTemporal() ||
9345 ST->isNonTemporal() ||
9346 LD->getPointerInfo().getAddrSpace() != 0 ||
9347 ST->getPointerInfo().getAddrSpace() != 0)
9350 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9351 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9352 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9353 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9354 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9357 unsigned LDAlign = LD->getAlignment();
9358 unsigned STAlign = ST->getAlignment();
9359 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9360 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9361 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9364 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9365 LD->getChain(), LD->getBasePtr(),
9366 LD->getPointerInfo(),
9367 false, false, false, LDAlign);
9369 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9370 NewLD, ST->getBasePtr(),
9371 ST->getPointerInfo(),
9372 false, false, STAlign);
9374 AddToWorklist(NewLD.getNode());
9375 AddToWorklist(NewST.getNode());
9376 WorklistRemover DeadNodes(*this);
9377 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9385 /// Helper struct to parse and store a memory address as base + index + offset.
9386 /// We ignore sign extensions when it is safe to do so.
9387 /// The following two expressions are not equivalent. To differentiate we need
9388 /// to store whether there was a sign extension involved in the index
9390 /// (load (i64 add (i64 copyfromreg %c)
9391 /// (i64 signextend (add (i8 load %index)
9395 /// (load (i64 add (i64 copyfromreg %c)
9396 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9398 struct BaseIndexOffset {
9402 bool IsIndexSignExt;
9404 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9406 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9407 bool IsIndexSignExt) :
9408 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9410 bool equalBaseIndex(const BaseIndexOffset &Other) {
9411 return Other.Base == Base && Other.Index == Index &&
9412 Other.IsIndexSignExt == IsIndexSignExt;
9415 /// Parses tree in Ptr for base, index, offset addresses.
9416 static BaseIndexOffset match(SDValue Ptr) {
9417 bool IsIndexSignExt = false;
9419 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9420 // instruction, then it could be just the BASE or everything else we don't
9421 // know how to handle. Just use Ptr as BASE and give up.
9422 if (Ptr->getOpcode() != ISD::ADD)
9423 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9425 // We know that we have at least an ADD instruction. Try to pattern match
9426 // the simple case of BASE + OFFSET.
9427 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9428 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9429 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9433 // Inside a loop the current BASE pointer is calculated using an ADD and a
9434 // MUL instruction. In this case Ptr is the actual BASE pointer.
9435 // (i64 add (i64 %array_ptr)
9436 // (i64 mul (i64 %induction_var)
9437 // (i64 %element_size)))
9438 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9439 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9441 // Look at Base + Index + Offset cases.
9442 SDValue Base = Ptr->getOperand(0);
9443 SDValue IndexOffset = Ptr->getOperand(1);
9445 // Skip signextends.
9446 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9447 IndexOffset = IndexOffset->getOperand(0);
9448 IsIndexSignExt = true;
9451 // Either the case of Base + Index (no offset) or something else.
9452 if (IndexOffset->getOpcode() != ISD::ADD)
9453 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9455 // Now we have the case of Base + Index + offset.
9456 SDValue Index = IndexOffset->getOperand(0);
9457 SDValue Offset = IndexOffset->getOperand(1);
9459 if (!isa<ConstantSDNode>(Offset))
9460 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9462 // Ignore signextends.
9463 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9464 Index = Index->getOperand(0);
9465 IsIndexSignExt = true;
9466 } else IsIndexSignExt = false;
9468 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9469 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9473 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9474 /// is located in a sequence of memory operations connected by a chain.
9476 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9477 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9478 // Ptr to the mem node.
9479 LSBaseSDNode *MemNode;
9480 // Offset from the base ptr.
9481 int64_t OffsetFromBase;
9482 // What is the sequence number of this mem node.
9483 // Lowest mem operand in the DAG starts at zero.
9484 unsigned SequenceNum;
9487 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9488 EVT MemVT = St->getMemoryVT();
9489 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9490 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9491 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9493 // Don't merge vectors into wider inputs.
9494 if (MemVT.isVector() || !MemVT.isSimple())
9497 // Perform an early exit check. Do not bother looking at stored values that
9498 // are not constants or loads.
9499 SDValue StoredVal = St->getValue();
9500 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9501 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9505 // Only look at ends of store sequences.
9506 SDValue Chain = SDValue(St, 0);
9507 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9510 // This holds the base pointer, index, and the offset in bytes from the base
9512 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9514 // We must have a base and an offset.
9515 if (!BasePtr.Base.getNode())
9518 // Do not handle stores to undef base pointers.
9519 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9522 // Save the LoadSDNodes that we find in the chain.
9523 // We need to make sure that these nodes do not interfere with
9524 // any of the store nodes.
9525 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9527 // Save the StoreSDNodes that we find in the chain.
9528 SmallVector<MemOpLink, 8> StoreNodes;
9530 // Walk up the chain and look for nodes with offsets from the same
9531 // base pointer. Stop when reaching an instruction with a different kind
9532 // or instruction which has a different base pointer.
9534 StoreSDNode *Index = St;
9536 // If the chain has more than one use, then we can't reorder the mem ops.
9537 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9540 // Find the base pointer and offset for this memory node.
9541 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9543 // Check that the base pointer is the same as the original one.
9544 if (!Ptr.equalBaseIndex(BasePtr))
9547 // Check that the alignment is the same.
9548 if (Index->getAlignment() != St->getAlignment())
9551 // The memory operands must not be volatile.
9552 if (Index->isVolatile() || Index->isIndexed())
9556 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9557 if (St->isTruncatingStore())
9560 // The stored memory type must be the same.
9561 if (Index->getMemoryVT() != MemVT)
9564 // We do not allow unaligned stores because we want to prevent overriding
9566 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9569 // We found a potential memory operand to merge.
9570 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9572 // Find the next memory operand in the chain. If the next operand in the
9573 // chain is a store then move up and continue the scan with the next
9574 // memory operand. If the next operand is a load save it and use alias
9575 // information to check if it interferes with anything.
9576 SDNode *NextInChain = Index->getChain().getNode();
9578 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9579 // We found a store node. Use it for the next iteration.
9582 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9583 if (Ldn->isVolatile()) {
9588 // Save the load node for later. Continue the scan.
9589 AliasLoadNodes.push_back(Ldn);
9590 NextInChain = Ldn->getChain().getNode();
9599 // Check if there is anything to merge.
9600 if (StoreNodes.size() < 2)
9603 // Sort the memory operands according to their distance from the base pointer.
9604 std::sort(StoreNodes.begin(), StoreNodes.end(),
9605 [](MemOpLink LHS, MemOpLink RHS) {
9606 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9607 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9608 LHS.SequenceNum > RHS.SequenceNum);
9611 // Scan the memory operations on the chain and find the first non-consecutive
9612 // store memory address.
9613 unsigned LastConsecutiveStore = 0;
9614 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9615 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9617 // Check that the addresses are consecutive starting from the second
9618 // element in the list of stores.
9620 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9621 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9626 // Check if this store interferes with any of the loads that we found.
9627 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9628 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9632 // We found a load that alias with this store. Stop the sequence.
9636 // Mark this node as useful.
9637 LastConsecutiveStore = i;
9640 // The node with the lowest store address.
9641 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9643 // Store the constants into memory as one consecutive store.
9645 unsigned LastLegalType = 0;
9646 unsigned LastLegalVectorType = 0;
9647 bool NonZero = false;
9648 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9649 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9650 SDValue StoredVal = St->getValue();
9652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9653 NonZero |= !C->isNullValue();
9654 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9655 NonZero |= !C->getConstantFPValue()->isNullValue();
9661 // Find a legal type for the constant store.
9662 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9663 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9664 if (TLI.isTypeLegal(StoreTy))
9665 LastLegalType = i+1;
9666 // Or check whether a truncstore is legal.
9667 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9668 TargetLowering::TypePromoteInteger) {
9669 EVT LegalizedStoredValueTy =
9670 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9671 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9672 LastLegalType = i+1;
9675 // Find a legal type for the vector store.
9676 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9677 if (TLI.isTypeLegal(Ty))
9678 LastLegalVectorType = i + 1;
9681 // We only use vectors if the constant is known to be zero and the
9682 // function is not marked with the noimplicitfloat attribute.
9683 if (NonZero || NoVectors)
9684 LastLegalVectorType = 0;
9686 // Check if we found a legal integer type to store.
9687 if (LastLegalType == 0 && LastLegalVectorType == 0)
9690 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9691 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9693 // Make sure we have something to merge.
9697 unsigned EarliestNodeUsed = 0;
9698 for (unsigned i=0; i < NumElem; ++i) {
9699 // Find a chain for the new wide-store operand. Notice that some
9700 // of the store nodes that we found may not be selected for inclusion
9701 // in the wide store. The chain we use needs to be the chain of the
9702 // earliest store node which is *used* and replaced by the wide store.
9703 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9704 EarliestNodeUsed = i;
9707 // The earliest Node in the DAG.
9708 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9709 SDLoc DL(StoreNodes[0].MemNode);
9713 // Find a legal type for the vector store.
9714 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9715 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9716 StoredVal = DAG.getConstant(0, Ty);
9718 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9719 APInt StoreInt(StoreBW, 0);
9721 // Construct a single integer constant which is made of the smaller
9723 bool IsLE = TLI.isLittleEndian();
9724 for (unsigned i = 0; i < NumElem ; ++i) {
9725 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9726 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9727 SDValue Val = St->getValue();
9728 StoreInt<<=ElementSizeBytes*8;
9729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9730 StoreInt|=C->getAPIntValue().zext(StoreBW);
9731 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9732 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9734 assert(false && "Invalid constant element type");
9738 // Create the new Load and Store operations.
9739 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9740 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9743 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9744 FirstInChain->getBasePtr(),
9745 FirstInChain->getPointerInfo(),
9747 FirstInChain->getAlignment());
9749 // Replace the first store with the new store
9750 CombineTo(EarliestOp, NewStore);
9751 // Erase all other stores.
9752 for (unsigned i = 0; i < NumElem ; ++i) {
9753 if (StoreNodes[i].MemNode == EarliestOp)
9755 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9756 // ReplaceAllUsesWith will replace all uses that existed when it was
9757 // called, but graph optimizations may cause new ones to appear. For
9758 // example, the case in pr14333 looks like
9760 // St's chain -> St -> another store -> X
9762 // And the only difference from St to the other store is the chain.
9763 // When we change it's chain to be St's chain they become identical,
9764 // get CSEed and the net result is that X is now a use of St.
9765 // Since we know that St is redundant, just iterate.
9766 while (!St->use_empty())
9767 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9768 deleteAndRecombine(St);
9774 // Below we handle the case of multiple consecutive stores that
9775 // come from multiple consecutive loads. We merge them into a single
9776 // wide load and a single wide store.
9778 // Look for load nodes which are used by the stored values.
9779 SmallVector<MemOpLink, 8> LoadNodes;
9781 // Find acceptable loads. Loads need to have the same chain (token factor),
9782 // must not be zext, volatile, indexed, and they must be consecutive.
9783 BaseIndexOffset LdBasePtr;
9784 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9785 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9786 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9789 // Loads must only have one use.
9790 if (!Ld->hasNUsesOfValue(1, 0))
9793 // Check that the alignment is the same as the stores.
9794 if (Ld->getAlignment() != St->getAlignment())
9797 // The memory operands must not be volatile.
9798 if (Ld->isVolatile() || Ld->isIndexed())
9801 // We do not accept ext loads.
9802 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9805 // The stored memory type must be the same.
9806 if (Ld->getMemoryVT() != MemVT)
9809 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9810 // If this is not the first ptr that we check.
9811 if (LdBasePtr.Base.getNode()) {
9812 // The base ptr must be the same.
9813 if (!LdPtr.equalBaseIndex(LdBasePtr))
9816 // Check that all other base pointers are the same as this one.
9820 // We found a potential memory operand to merge.
9821 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9824 if (LoadNodes.size() < 2)
9827 // If we have load/store pair instructions and we only have two values,
9829 unsigned RequiredAlignment;
9830 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9831 St->getAlignment() >= RequiredAlignment)
9834 // Scan the memory operations on the chain and find the first non-consecutive
9835 // load memory address. These variables hold the index in the store node
9837 unsigned LastConsecutiveLoad = 0;
9838 // This variable refers to the size and not index in the array.
9839 unsigned LastLegalVectorType = 0;
9840 unsigned LastLegalIntegerType = 0;
9841 StartAddress = LoadNodes[0].OffsetFromBase;
9842 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9843 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9844 // All loads much share the same chain.
9845 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9848 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9849 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9851 LastConsecutiveLoad = i;
9853 // Find a legal type for the vector store.
9854 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9855 if (TLI.isTypeLegal(StoreTy))
9856 LastLegalVectorType = i + 1;
9858 // Find a legal type for the integer store.
9859 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9860 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9861 if (TLI.isTypeLegal(StoreTy))
9862 LastLegalIntegerType = i + 1;
9863 // Or check whether a truncstore and extload is legal.
9864 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9865 TargetLowering::TypePromoteInteger) {
9866 EVT LegalizedStoredValueTy =
9867 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9868 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9869 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9870 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9871 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9872 LastLegalIntegerType = i+1;
9876 // Only use vector types if the vector type is larger than the integer type.
9877 // If they are the same, use integers.
9878 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9879 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9881 // We add +1 here because the LastXXX variables refer to location while
9882 // the NumElem refers to array/index size.
9883 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9884 NumElem = std::min(LastLegalType, NumElem);
9889 // The earliest Node in the DAG.
9890 unsigned EarliestNodeUsed = 0;
9891 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9892 for (unsigned i=1; i<NumElem; ++i) {
9893 // Find a chain for the new wide-store operand. Notice that some
9894 // of the store nodes that we found may not be selected for inclusion
9895 // in the wide store. The chain we use needs to be the chain of the
9896 // earliest store node which is *used* and replaced by the wide store.
9897 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9898 EarliestNodeUsed = i;
9901 // Find if it is better to use vectors or integers to load and store
9905 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9907 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9908 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9911 SDLoc LoadDL(LoadNodes[0].MemNode);
9912 SDLoc StoreDL(StoreNodes[0].MemNode);
9914 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9915 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9916 FirstLoad->getChain(),
9917 FirstLoad->getBasePtr(),
9918 FirstLoad->getPointerInfo(),
9919 false, false, false,
9920 FirstLoad->getAlignment());
9922 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9923 FirstInChain->getBasePtr(),
9924 FirstInChain->getPointerInfo(), false, false,
9925 FirstInChain->getAlignment());
9927 // Replace one of the loads with the new load.
9928 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9929 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9930 SDValue(NewLoad.getNode(), 1));
9932 // Remove the rest of the load chains.
9933 for (unsigned i = 1; i < NumElem ; ++i) {
9934 // Replace all chain users of the old load nodes with the chain of the new
9936 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9937 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9940 // Replace the first store with the new store.
9941 CombineTo(EarliestOp, NewStore);
9942 // Erase all other stores.
9943 for (unsigned i = 0; i < NumElem ; ++i) {
9944 // Remove all Store nodes.
9945 if (StoreNodes[i].MemNode == EarliestOp)
9947 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9948 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9949 deleteAndRecombine(St);
9955 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9956 StoreSDNode *ST = cast<StoreSDNode>(N);
9957 SDValue Chain = ST->getChain();
9958 SDValue Value = ST->getValue();
9959 SDValue Ptr = ST->getBasePtr();
9961 // If this is a store of a bit convert, store the input value if the
9962 // resultant store does not need a higher alignment than the original.
9963 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9964 ST->isUnindexed()) {
9965 unsigned OrigAlign = ST->getAlignment();
9966 EVT SVT = Value.getOperand(0).getValueType();
9967 unsigned Align = TLI.getDataLayout()->
9968 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9969 if (Align <= OrigAlign &&
9970 ((!LegalOperations && !ST->isVolatile()) ||
9971 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9972 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9973 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9974 ST->isNonTemporal(), OrigAlign,
9978 // Turn 'store undef, Ptr' -> nothing.
9979 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9982 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9983 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9984 // NOTE: If the original store is volatile, this transform must not increase
9985 // the number of stores. For example, on x86-32 an f64 can be stored in one
9986 // processor operation but an i64 (which is not legal) requires two. So the
9987 // transform should not be done in this case.
9988 if (Value.getOpcode() != ISD::TargetConstantFP) {
9990 switch (CFP->getSimpleValueType(0).SimpleTy) {
9991 default: llvm_unreachable("Unknown FP type");
9992 case MVT::f16: // We don't do this for these yet.
9998 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9999 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10000 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10001 bitcastToAPInt().getZExtValue(), MVT::i32);
10002 return DAG.getStore(Chain, SDLoc(N), Tmp,
10003 Ptr, ST->getMemOperand());
10007 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10008 !ST->isVolatile()) ||
10009 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10010 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10011 getZExtValue(), MVT::i64);
10012 return DAG.getStore(Chain, SDLoc(N), Tmp,
10013 Ptr, ST->getMemOperand());
10016 if (!ST->isVolatile() &&
10017 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10018 // Many FP stores are not made apparent until after legalize, e.g. for
10019 // argument passing. Since this is so common, custom legalize the
10020 // 64-bit integer store into two 32-bit stores.
10021 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10022 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10023 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10024 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10026 unsigned Alignment = ST->getAlignment();
10027 bool isVolatile = ST->isVolatile();
10028 bool isNonTemporal = ST->isNonTemporal();
10029 AAMDNodes AAInfo = ST->getAAInfo();
10031 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10032 Ptr, ST->getPointerInfo(),
10033 isVolatile, isNonTemporal,
10034 ST->getAlignment(), AAInfo);
10035 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10036 DAG.getConstant(4, Ptr.getValueType()));
10037 Alignment = MinAlign(Alignment, 4U);
10038 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10039 Ptr, ST->getPointerInfo().getWithOffset(4),
10040 isVolatile, isNonTemporal,
10041 Alignment, AAInfo);
10042 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10051 // Try to infer better alignment information than the store already has.
10052 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10053 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10054 if (Align > ST->getAlignment())
10055 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10056 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10057 ST->isVolatile(), ST->isNonTemporal(), Align,
10062 // Try transforming a pair floating point load / store ops to integer
10063 // load / store ops.
10064 SDValue NewST = TransformFPLoadStorePair(N);
10065 if (NewST.getNode())
10068 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10069 : DAG.getSubtarget().useAA();
10071 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10072 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10075 if (UseAA && ST->isUnindexed()) {
10076 // Walk up chain skipping non-aliasing memory nodes.
10077 SDValue BetterChain = FindBetterChain(N, Chain);
10079 // If there is a better chain.
10080 if (Chain != BetterChain) {
10083 // Replace the chain to avoid dependency.
10084 if (ST->isTruncatingStore()) {
10085 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10086 ST->getMemoryVT(), ST->getMemOperand());
10088 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10089 ST->getMemOperand());
10092 // Create token to keep both nodes around.
10093 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10094 MVT::Other, Chain, ReplStore);
10096 // Make sure the new and old chains are cleaned up.
10097 AddToWorklist(Token.getNode());
10099 // Don't add users to work list.
10100 return CombineTo(N, Token, false);
10104 // Try transforming N to an indexed store.
10105 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10106 return SDValue(N, 0);
10108 // FIXME: is there such a thing as a truncating indexed store?
10109 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10110 Value.getValueType().isInteger()) {
10111 // See if we can simplify the input to this truncstore with knowledge that
10112 // only the low bits are being used. For example:
10113 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10115 GetDemandedBits(Value,
10116 APInt::getLowBitsSet(
10117 Value.getValueType().getScalarType().getSizeInBits(),
10118 ST->getMemoryVT().getScalarType().getSizeInBits()));
10119 AddToWorklist(Value.getNode());
10120 if (Shorter.getNode())
10121 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10122 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10124 // Otherwise, see if we can simplify the operation with
10125 // SimplifyDemandedBits, which only works if the value has a single use.
10126 if (SimplifyDemandedBits(Value,
10127 APInt::getLowBitsSet(
10128 Value.getValueType().getScalarType().getSizeInBits(),
10129 ST->getMemoryVT().getScalarType().getSizeInBits())))
10130 return SDValue(N, 0);
10133 // If this is a load followed by a store to the same location, then the store
10135 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10136 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10137 ST->isUnindexed() && !ST->isVolatile() &&
10138 // There can't be any side effects between the load and store, such as
10139 // a call or store.
10140 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10141 // The store is dead, remove it.
10146 // If this is a store followed by a store with the same value to the same
10147 // location, then the store is dead/noop.
10148 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10149 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10150 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10151 ST1->isUnindexed() && !ST1->isVolatile()) {
10152 // The store is dead, remove it.
10157 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10158 // truncating store. We can do this even if this is already a truncstore.
10159 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10160 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10161 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10162 ST->getMemoryVT())) {
10163 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10164 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10167 // Only perform this optimization before the types are legal, because we
10168 // don't want to perform this optimization on every DAGCombine invocation.
10170 bool EverChanged = false;
10173 // There can be multiple store sequences on the same chain.
10174 // Keep trying to merge store sequences until we are unable to do so
10175 // or until we merge the last store on the chain.
10176 bool Changed = MergeConsecutiveStores(ST);
10177 EverChanged |= Changed;
10178 if (!Changed) break;
10179 } while (ST->getOpcode() != ISD::DELETED_NODE);
10182 return SDValue(N, 0);
10185 return ReduceLoadOpStoreWidth(N);
10188 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10189 SDValue InVec = N->getOperand(0);
10190 SDValue InVal = N->getOperand(1);
10191 SDValue EltNo = N->getOperand(2);
10194 // If the inserted element is an UNDEF, just use the input vector.
10195 if (InVal.getOpcode() == ISD::UNDEF)
10198 EVT VT = InVec.getValueType();
10200 // If we can't generate a legal BUILD_VECTOR, exit
10201 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10204 // Check that we know which element is being inserted
10205 if (!isa<ConstantSDNode>(EltNo))
10207 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10209 // Canonicalize insert_vector_elt dag nodes.
10211 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10212 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10214 // Do this only if the child insert_vector node has one use; also
10215 // do this only if indices are both constants and Idx1 < Idx0.
10216 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10217 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10218 unsigned OtherElt =
10219 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10220 if (Elt < OtherElt) {
10222 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10223 InVec.getOperand(0), InVal, EltNo);
10224 AddToWorklist(NewOp.getNode());
10225 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10226 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10230 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10231 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10232 // vector elements.
10233 SmallVector<SDValue, 8> Ops;
10234 // Do not combine these two vectors if the output vector will not replace
10235 // the input vector.
10236 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10237 Ops.append(InVec.getNode()->op_begin(),
10238 InVec.getNode()->op_end());
10239 } else if (InVec.getOpcode() == ISD::UNDEF) {
10240 unsigned NElts = VT.getVectorNumElements();
10241 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10246 // Insert the element
10247 if (Elt < Ops.size()) {
10248 // All the operands of BUILD_VECTOR must have the same type;
10249 // we enforce that here.
10250 EVT OpVT = Ops[0].getValueType();
10251 if (InVal.getValueType() != OpVT)
10252 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10253 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10254 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10258 // Return the new vector
10259 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10262 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10263 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10264 EVT ResultVT = EVE->getValueType(0);
10265 EVT VecEltVT = InVecVT.getVectorElementType();
10266 unsigned Align = OriginalLoad->getAlignment();
10267 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10268 VecEltVT.getTypeForEVT(*DAG.getContext()));
10270 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10275 SDValue NewPtr = OriginalLoad->getBasePtr();
10277 EVT PtrType = NewPtr.getValueType();
10278 MachinePointerInfo MPI;
10279 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10280 int Elt = ConstEltNo->getZExtValue();
10281 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10282 if (TLI.isBigEndian())
10283 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10284 Offset = DAG.getConstant(PtrOff, PtrType);
10285 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10287 Offset = DAG.getNode(
10288 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10289 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10290 if (TLI.isBigEndian())
10291 Offset = DAG.getNode(
10292 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10293 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10294 MPI = OriginalLoad->getPointerInfo();
10296 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10298 // The replacement we need to do here is a little tricky: we need to
10299 // replace an extractelement of a load with a load.
10300 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10301 // Note that this replacement assumes that the extractvalue is the only
10302 // use of the load; that's okay because we don't want to perform this
10303 // transformation in other cases anyway.
10306 if (ResultVT.bitsGT(VecEltVT)) {
10307 // If the result type of vextract is wider than the load, then issue an
10308 // extending load instead.
10309 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10312 Load = DAG.getExtLoad(
10313 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10314 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10315 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10316 Chain = Load.getValue(1);
10318 Load = DAG.getLoad(
10319 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10320 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10321 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10322 Chain = Load.getValue(1);
10323 if (ResultVT.bitsLT(VecEltVT))
10324 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10326 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10328 WorklistRemover DeadNodes(*this);
10329 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10330 SDValue To[] = { Load, Chain };
10331 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10332 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10333 // worklist explicitly as well.
10334 AddToWorklist(Load.getNode());
10335 AddUsersToWorklist(Load.getNode()); // Add users too
10336 // Make sure to revisit this node to clean it up; it will usually be dead.
10337 AddToWorklist(EVE);
10339 return SDValue(EVE, 0);
10342 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10343 // (vextract (scalar_to_vector val, 0) -> val
10344 SDValue InVec = N->getOperand(0);
10345 EVT VT = InVec.getValueType();
10346 EVT NVT = N->getValueType(0);
10348 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10349 // Check if the result type doesn't match the inserted element type. A
10350 // SCALAR_TO_VECTOR may truncate the inserted element and the
10351 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10352 SDValue InOp = InVec.getOperand(0);
10353 if (InOp.getValueType() != NVT) {
10354 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10355 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10360 SDValue EltNo = N->getOperand(1);
10361 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10363 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10364 // We only perform this optimization before the op legalization phase because
10365 // we may introduce new vector instructions which are not backed by TD
10366 // patterns. For example on AVX, extracting elements from a wide vector
10367 // without using extract_subvector. However, if we can find an underlying
10368 // scalar value, then we can always use that.
10369 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10371 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10372 int NumElem = VT.getVectorNumElements();
10373 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10374 // Find the new index to extract from.
10375 int OrigElt = SVOp->getMaskElt(Elt);
10377 // Extracting an undef index is undef.
10379 return DAG.getUNDEF(NVT);
10381 // Select the right vector half to extract from.
10383 if (OrigElt < NumElem) {
10384 SVInVec = InVec->getOperand(0);
10386 SVInVec = InVec->getOperand(1);
10387 OrigElt -= NumElem;
10390 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10391 SDValue InOp = SVInVec.getOperand(OrigElt);
10392 if (InOp.getValueType() != NVT) {
10393 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10394 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10400 // FIXME: We should handle recursing on other vector shuffles and
10401 // scalar_to_vector here as well.
10403 if (!LegalOperations) {
10404 EVT IndexTy = TLI.getVectorIdxTy();
10405 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10406 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10410 bool BCNumEltsChanged = false;
10411 EVT ExtVT = VT.getVectorElementType();
10414 // If the result of load has to be truncated, then it's not necessarily
10416 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10419 if (InVec.getOpcode() == ISD::BITCAST) {
10420 // Don't duplicate a load with other uses.
10421 if (!InVec.hasOneUse())
10424 EVT BCVT = InVec.getOperand(0).getValueType();
10425 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10427 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10428 BCNumEltsChanged = true;
10429 InVec = InVec.getOperand(0);
10430 ExtVT = BCVT.getVectorElementType();
10433 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10434 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10435 ISD::isNormalLoad(InVec.getNode()) &&
10436 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10437 SDValue Index = N->getOperand(1);
10438 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10439 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10443 // Perform only after legalization to ensure build_vector / vector_shuffle
10444 // optimizations have already been done.
10445 if (!LegalOperations) return SDValue();
10447 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10448 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10449 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10452 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10454 LoadSDNode *LN0 = nullptr;
10455 const ShuffleVectorSDNode *SVN = nullptr;
10456 if (ISD::isNormalLoad(InVec.getNode())) {
10457 LN0 = cast<LoadSDNode>(InVec);
10458 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10459 InVec.getOperand(0).getValueType() == ExtVT &&
10460 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10461 // Don't duplicate a load with other uses.
10462 if (!InVec.hasOneUse())
10465 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10466 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10467 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10469 // (load $addr+1*size)
10471 // Don't duplicate a load with other uses.
10472 if (!InVec.hasOneUse())
10475 // If the bit convert changed the number of elements, it is unsafe
10476 // to examine the mask.
10477 if (BCNumEltsChanged)
10480 // Select the input vector, guarding against out of range extract vector.
10481 unsigned NumElems = VT.getVectorNumElements();
10482 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10483 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10485 if (InVec.getOpcode() == ISD::BITCAST) {
10486 // Don't duplicate a load with other uses.
10487 if (!InVec.hasOneUse())
10490 InVec = InVec.getOperand(0);
10492 if (ISD::isNormalLoad(InVec.getNode())) {
10493 LN0 = cast<LoadSDNode>(InVec);
10494 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10495 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10499 // Make sure we found a non-volatile load and the extractelement is
10501 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10504 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10506 return DAG.getUNDEF(LVT);
10508 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10514 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10515 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10516 // We perform this optimization post type-legalization because
10517 // the type-legalizer often scalarizes integer-promoted vectors.
10518 // Performing this optimization before may create bit-casts which
10519 // will be type-legalized to complex code sequences.
10520 // We perform this optimization only before the operation legalizer because we
10521 // may introduce illegal operations.
10522 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10525 unsigned NumInScalars = N->getNumOperands();
10527 EVT VT = N->getValueType(0);
10529 // Check to see if this is a BUILD_VECTOR of a bunch of values
10530 // which come from any_extend or zero_extend nodes. If so, we can create
10531 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10532 // optimizations. We do not handle sign-extend because we can't fill the sign
10534 EVT SourceType = MVT::Other;
10535 bool AllAnyExt = true;
10537 for (unsigned i = 0; i != NumInScalars; ++i) {
10538 SDValue In = N->getOperand(i);
10539 // Ignore undef inputs.
10540 if (In.getOpcode() == ISD::UNDEF) continue;
10542 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10543 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10545 // Abort if the element is not an extension.
10546 if (!ZeroExt && !AnyExt) {
10547 SourceType = MVT::Other;
10551 // The input is a ZeroExt or AnyExt. Check the original type.
10552 EVT InTy = In.getOperand(0).getValueType();
10554 // Check that all of the widened source types are the same.
10555 if (SourceType == MVT::Other)
10558 else if (InTy != SourceType) {
10559 // Multiple income types. Abort.
10560 SourceType = MVT::Other;
10564 // Check if all of the extends are ANY_EXTENDs.
10565 AllAnyExt &= AnyExt;
10568 // In order to have valid types, all of the inputs must be extended from the
10569 // same source type and all of the inputs must be any or zero extend.
10570 // Scalar sizes must be a power of two.
10571 EVT OutScalarTy = VT.getScalarType();
10572 bool ValidTypes = SourceType != MVT::Other &&
10573 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10574 isPowerOf2_32(SourceType.getSizeInBits());
10576 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10577 // turn into a single shuffle instruction.
10581 bool isLE = TLI.isLittleEndian();
10582 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10583 assert(ElemRatio > 1 && "Invalid element size ratio");
10584 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10585 DAG.getConstant(0, SourceType);
10587 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10588 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10590 // Populate the new build_vector
10591 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10592 SDValue Cast = N->getOperand(i);
10593 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10594 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10595 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10597 if (Cast.getOpcode() == ISD::UNDEF)
10598 In = DAG.getUNDEF(SourceType);
10600 In = Cast->getOperand(0);
10601 unsigned Index = isLE ? (i * ElemRatio) :
10602 (i * ElemRatio + (ElemRatio - 1));
10604 assert(Index < Ops.size() && "Invalid index");
10608 // The type of the new BUILD_VECTOR node.
10609 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10610 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10611 "Invalid vector size");
10612 // Check if the new vector type is legal.
10613 if (!isTypeLegal(VecVT)) return SDValue();
10615 // Make the new BUILD_VECTOR.
10616 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10618 // The new BUILD_VECTOR node has the potential to be further optimized.
10619 AddToWorklist(BV.getNode());
10620 // Bitcast to the desired type.
10621 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10624 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10625 EVT VT = N->getValueType(0);
10627 unsigned NumInScalars = N->getNumOperands();
10630 EVT SrcVT = MVT::Other;
10631 unsigned Opcode = ISD::DELETED_NODE;
10632 unsigned NumDefs = 0;
10634 for (unsigned i = 0; i != NumInScalars; ++i) {
10635 SDValue In = N->getOperand(i);
10636 unsigned Opc = In.getOpcode();
10638 if (Opc == ISD::UNDEF)
10641 // If all scalar values are floats and converted from integers.
10642 if (Opcode == ISD::DELETED_NODE &&
10643 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10650 EVT InVT = In.getOperand(0).getValueType();
10652 // If all scalar values are typed differently, bail out. It's chosen to
10653 // simplify BUILD_VECTOR of integer types.
10654 if (SrcVT == MVT::Other)
10661 // If the vector has just one element defined, it's not worth to fold it into
10662 // a vectorized one.
10666 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10667 && "Should only handle conversion from integer to float.");
10668 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10670 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10672 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10675 SmallVector<SDValue, 8> Opnds;
10676 for (unsigned i = 0; i != NumInScalars; ++i) {
10677 SDValue In = N->getOperand(i);
10679 if (In.getOpcode() == ISD::UNDEF)
10680 Opnds.push_back(DAG.getUNDEF(SrcVT));
10682 Opnds.push_back(In.getOperand(0));
10684 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10685 AddToWorklist(BV.getNode());
10687 return DAG.getNode(Opcode, dl, VT, BV);
10690 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10691 unsigned NumInScalars = N->getNumOperands();
10693 EVT VT = N->getValueType(0);
10695 // A vector built entirely of undefs is undef.
10696 if (ISD::allOperandsUndef(N))
10697 return DAG.getUNDEF(VT);
10699 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10703 V = reduceBuildVecConvertToConvertBuildVec(N);
10707 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10708 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10709 // at most two distinct vectors, turn this into a shuffle node.
10711 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10712 if (!isTypeLegal(VT))
10715 // May only combine to shuffle after legalize if shuffle is legal.
10716 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10719 SDValue VecIn1, VecIn2;
10720 bool UsesZeroVector = false;
10721 for (unsigned i = 0; i != NumInScalars; ++i) {
10722 SDValue Op = N->getOperand(i);
10723 // Ignore undef inputs.
10724 if (Op.getOpcode() == ISD::UNDEF) continue;
10726 // See if we can combine this build_vector into a blend with a zero vector.
10727 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10728 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10729 (Op.getOpcode() == ISD::ConstantFP &&
10730 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10731 UsesZeroVector = true;
10735 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10736 // constant index, bail out.
10737 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10738 !isa<ConstantSDNode>(Op.getOperand(1))) {
10739 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10743 // We allow up to two distinct input vectors.
10744 SDValue ExtractedFromVec = Op.getOperand(0);
10745 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10748 if (!VecIn1.getNode()) {
10749 VecIn1 = ExtractedFromVec;
10750 } else if (!VecIn2.getNode() && !UsesZeroVector) {
10751 VecIn2 = ExtractedFromVec;
10753 // Too many inputs.
10754 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10759 // If everything is good, we can make a shuffle operation.
10760 if (VecIn1.getNode()) {
10761 SmallVector<int, 8> Mask;
10762 for (unsigned i = 0; i != NumInScalars; ++i) {
10763 unsigned Opcode = N->getOperand(i).getOpcode();
10764 if (Opcode == ISD::UNDEF) {
10765 Mask.push_back(-1);
10769 // Operands can also be zero.
10770 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10771 assert(UsesZeroVector &&
10772 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10773 "Unexpected node found!");
10774 Mask.push_back(NumInScalars+i);
10778 // If extracting from the first vector, just use the index directly.
10779 SDValue Extract = N->getOperand(i);
10780 SDValue ExtVal = Extract.getOperand(1);
10781 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10782 if (Extract.getOperand(0) == VecIn1) {
10783 if (ExtIndex > VT.getVectorNumElements())
10786 Mask.push_back(ExtIndex);
10790 // Otherwise, use InIdx + VecSize
10791 Mask.push_back(NumInScalars+ExtIndex);
10794 // Avoid introducing illegal shuffles with zero.
10795 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10798 // We can't generate a shuffle node with mismatched input and output types.
10799 // Attempt to transform a single input vector to the correct type.
10800 if ((VT != VecIn1.getValueType())) {
10801 // We don't support shuffeling between TWO values of different types.
10802 if (VecIn2.getNode())
10805 // We only support widening of vectors which are half the size of the
10806 // output registers. For example XMM->YMM widening on X86 with AVX.
10807 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10810 // If the input vector type has a different base type to the output
10811 // vector type, bail out.
10812 if (VecIn1.getValueType().getVectorElementType() !=
10813 VT.getVectorElementType())
10816 // Widen the input vector by adding undef values.
10817 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10818 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10821 if (UsesZeroVector)
10822 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10823 DAG.getConstantFP(0.0, VT);
10825 // If VecIn2 is unused then change it to undef.
10826 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10828 // Check that we were able to transform all incoming values to the same
10830 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10831 VecIn1.getValueType() != VT)
10834 // Return the new VECTOR_SHUFFLE node.
10838 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10844 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10845 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10846 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10847 // inputs come from at most two distinct vectors, turn this into a shuffle
10850 // If we only have one input vector, we don't need to do any concatenation.
10851 if (N->getNumOperands() == 1)
10852 return N->getOperand(0);
10854 // Check if all of the operands are undefs.
10855 EVT VT = N->getValueType(0);
10856 if (ISD::allOperandsUndef(N))
10857 return DAG.getUNDEF(VT);
10859 // Optimize concat_vectors where one of the vectors is undef.
10860 if (N->getNumOperands() == 2 &&
10861 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10862 SDValue In = N->getOperand(0);
10863 assert(In.getValueType().isVector() && "Must concat vectors");
10865 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10866 if (In->getOpcode() == ISD::BITCAST &&
10867 !In->getOperand(0)->getValueType(0).isVector()) {
10868 SDValue Scalar = In->getOperand(0);
10869 EVT SclTy = Scalar->getValueType(0);
10871 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10874 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10875 VT.getSizeInBits() / SclTy.getSizeInBits());
10876 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10879 SDLoc dl = SDLoc(N);
10880 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10881 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10885 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10886 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10887 if (N->getNumOperands() == 2 &&
10888 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10889 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10890 EVT VT = N->getValueType(0);
10891 SDValue N0 = N->getOperand(0);
10892 SDValue N1 = N->getOperand(1);
10893 SmallVector<SDValue, 8> Opnds;
10894 unsigned BuildVecNumElts = N0.getNumOperands();
10896 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10897 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10898 if (SclTy0.isFloatingPoint()) {
10899 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10900 Opnds.push_back(N0.getOperand(i));
10901 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10902 Opnds.push_back(N1.getOperand(i));
10904 // If BUILD_VECTOR are from built from integer, they may have different
10905 // operand types. Get the smaller type and truncate all operands to it.
10906 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10907 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10908 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10909 N0.getOperand(i)));
10910 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10911 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10912 N1.getOperand(i)));
10915 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10918 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10919 // nodes often generate nop CONCAT_VECTOR nodes.
10920 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10921 // place the incoming vectors at the exact same location.
10922 SDValue SingleSource = SDValue();
10923 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10925 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10926 SDValue Op = N->getOperand(i);
10928 if (Op.getOpcode() == ISD::UNDEF)
10931 // Check if this is the identity extract:
10932 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10935 // Find the single incoming vector for the extract_subvector.
10936 if (SingleSource.getNode()) {
10937 if (Op.getOperand(0) != SingleSource)
10940 SingleSource = Op.getOperand(0);
10942 // Check the source type is the same as the type of the result.
10943 // If not, this concat may extend the vector, so we can not
10944 // optimize it away.
10945 if (SingleSource.getValueType() != N->getValueType(0))
10949 unsigned IdentityIndex = i * PartNumElem;
10950 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10951 // The extract index must be constant.
10955 // Check that we are reading from the identity index.
10956 if (CS->getZExtValue() != IdentityIndex)
10960 if (SingleSource.getNode())
10961 return SingleSource;
10966 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10967 EVT NVT = N->getValueType(0);
10968 SDValue V = N->getOperand(0);
10970 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10972 // (extract_subvec (concat V1, V2, ...), i)
10975 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10977 if (V->getOperand(0).getValueType() != NVT)
10979 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10980 unsigned NumElems = NVT.getVectorNumElements();
10981 assert((Idx % NumElems) == 0 &&
10982 "IDX in concat is not a multiple of the result vector length.");
10983 return V->getOperand(Idx / NumElems);
10987 if (V->getOpcode() == ISD::BITCAST)
10988 V = V.getOperand(0);
10990 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10992 // Handle only simple case where vector being inserted and vector
10993 // being extracted are of same type, and are half size of larger vectors.
10994 EVT BigVT = V->getOperand(0).getValueType();
10995 EVT SmallVT = V->getOperand(1).getValueType();
10996 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10999 // Only handle cases where both indexes are constants with the same type.
11000 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11001 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11003 if (InsIdx && ExtIdx &&
11004 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11005 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11007 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11009 // indices are equal or bit offsets are equal => V1
11010 // otherwise => (extract_subvec V1, ExtIdx)
11011 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11012 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11013 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11014 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11015 DAG.getNode(ISD::BITCAST, dl,
11016 N->getOperand(0).getValueType(),
11017 V->getOperand(0)), N->getOperand(1));
11024 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11025 SDValue V, SelectionDAG &DAG) {
11027 EVT VT = V.getValueType();
11029 switch (V.getOpcode()) {
11033 case ISD::CONCAT_VECTORS: {
11034 EVT OpVT = V->getOperand(0).getValueType();
11035 int OpSize = OpVT.getVectorNumElements();
11036 SmallBitVector OpUsedElements(OpSize, false);
11037 bool FoundSimplification = false;
11038 SmallVector<SDValue, 4> NewOps;
11039 NewOps.reserve(V->getNumOperands());
11040 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11041 SDValue Op = V->getOperand(i);
11042 bool OpUsed = false;
11043 for (int j = 0; j < OpSize; ++j)
11044 if (UsedElements[i * OpSize + j]) {
11045 OpUsedElements[j] = true;
11049 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11050 : DAG.getUNDEF(OpVT));
11051 FoundSimplification |= Op == NewOps.back();
11052 OpUsedElements.reset();
11054 if (FoundSimplification)
11055 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11059 case ISD::INSERT_SUBVECTOR: {
11060 SDValue BaseV = V->getOperand(0);
11061 SDValue SubV = V->getOperand(1);
11062 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11066 int SubSize = SubV.getValueType().getVectorNumElements();
11067 int Idx = IdxN->getZExtValue();
11068 bool SubVectorUsed = false;
11069 SmallBitVector SubUsedElements(SubSize, false);
11070 for (int i = 0; i < SubSize; ++i)
11071 if (UsedElements[i + Idx]) {
11072 SubVectorUsed = true;
11073 SubUsedElements[i] = true;
11074 UsedElements[i + Idx] = false;
11077 // Now recurse on both the base and sub vectors.
11078 SDValue SimplifiedSubV =
11080 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11081 : DAG.getUNDEF(SubV.getValueType());
11082 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11083 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11084 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11085 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11091 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11092 SDValue N1, SelectionDAG &DAG) {
11093 EVT VT = SVN->getValueType(0);
11094 int NumElts = VT.getVectorNumElements();
11095 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11096 for (int M : SVN->getMask())
11097 if (M >= 0 && M < NumElts)
11098 N0UsedElements[M] = true;
11099 else if (M >= NumElts)
11100 N1UsedElements[M - NumElts] = true;
11102 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11103 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11104 if (S0 == N0 && S1 == N1)
11107 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11110 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11111 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11112 EVT VT = N->getValueType(0);
11113 unsigned NumElts = VT.getVectorNumElements();
11115 SDValue N0 = N->getOperand(0);
11116 SDValue N1 = N->getOperand(1);
11117 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11119 SmallVector<SDValue, 4> Ops;
11120 EVT ConcatVT = N0.getOperand(0).getValueType();
11121 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11122 unsigned NumConcats = NumElts / NumElemsPerConcat;
11124 // Look at every vector that's inserted. We're looking for exact
11125 // subvector-sized copies from a concatenated vector
11126 for (unsigned I = 0; I != NumConcats; ++I) {
11127 // Make sure we're dealing with a copy.
11128 unsigned Begin = I * NumElemsPerConcat;
11129 bool AllUndef = true, NoUndef = true;
11130 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11131 if (SVN->getMaskElt(J) >= 0)
11138 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11141 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11142 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11145 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11146 if (FirstElt < N0.getNumOperands())
11147 Ops.push_back(N0.getOperand(FirstElt));
11149 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11151 } else if (AllUndef) {
11152 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11153 } else { // Mixed with general masks and undefs, can't do optimization.
11158 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11161 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11162 EVT VT = N->getValueType(0);
11163 unsigned NumElts = VT.getVectorNumElements();
11165 SDValue N0 = N->getOperand(0);
11166 SDValue N1 = N->getOperand(1);
11168 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11170 // Canonicalize shuffle undef, undef -> undef
11171 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11172 return DAG.getUNDEF(VT);
11174 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11176 // Canonicalize shuffle v, v -> v, undef
11178 SmallVector<int, 8> NewMask;
11179 for (unsigned i = 0; i != NumElts; ++i) {
11180 int Idx = SVN->getMaskElt(i);
11181 if (Idx >= (int)NumElts) Idx -= NumElts;
11182 NewMask.push_back(Idx);
11184 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11188 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11189 if (N0.getOpcode() == ISD::UNDEF) {
11190 SmallVector<int, 8> NewMask;
11191 for (unsigned i = 0; i != NumElts; ++i) {
11192 int Idx = SVN->getMaskElt(i);
11194 if (Idx >= (int)NumElts)
11197 Idx = -1; // remove reference to lhs
11199 NewMask.push_back(Idx);
11201 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11205 // Remove references to rhs if it is undef
11206 if (N1.getOpcode() == ISD::UNDEF) {
11207 bool Changed = false;
11208 SmallVector<int, 8> NewMask;
11209 for (unsigned i = 0; i != NumElts; ++i) {
11210 int Idx = SVN->getMaskElt(i);
11211 if (Idx >= (int)NumElts) {
11215 NewMask.push_back(Idx);
11218 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11221 // If it is a splat, check if the argument vector is another splat or a
11222 // build_vector with all scalar elements the same.
11223 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11224 SDNode *V = N0.getNode();
11226 // If this is a bit convert that changes the element type of the vector but
11227 // not the number of vector elements, look through it. Be careful not to
11228 // look though conversions that change things like v4f32 to v2f64.
11229 if (V->getOpcode() == ISD::BITCAST) {
11230 SDValue ConvInput = V->getOperand(0);
11231 if (ConvInput.getValueType().isVector() &&
11232 ConvInput.getValueType().getVectorNumElements() == NumElts)
11233 V = ConvInput.getNode();
11236 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11237 assert(V->getNumOperands() == NumElts &&
11238 "BUILD_VECTOR has wrong number of operands");
11240 bool AllSame = true;
11241 for (unsigned i = 0; i != NumElts; ++i) {
11242 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11243 Base = V->getOperand(i);
11247 // Splat of <u, u, u, u>, return <u, u, u, u>
11248 if (!Base.getNode())
11250 for (unsigned i = 0; i != NumElts; ++i) {
11251 if (V->getOperand(i) != Base) {
11256 // Splat of <x, x, x, x>, return <x, x, x, x>
11262 // There are various patterns used to build up a vector from smaller vectors,
11263 // subvectors, or elements. Scan chains of these and replace unused insertions
11264 // or components with undef.
11265 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11268 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11269 Level < AfterLegalizeVectorOps &&
11270 (N1.getOpcode() == ISD::UNDEF ||
11271 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11272 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11273 SDValue V = partitionShuffleOfConcats(N, DAG);
11279 // Canonicalize shuffles according to rules:
11280 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11281 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11282 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11283 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11284 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11285 TLI.isTypeLegal(VT)) {
11286 // The incoming shuffle must be of the same type as the result of the
11287 // current shuffle.
11288 assert(N1->getOperand(0).getValueType() == VT &&
11289 "Shuffle types don't match");
11291 SDValue SV0 = N1->getOperand(0);
11292 SDValue SV1 = N1->getOperand(1);
11293 bool HasSameOp0 = N0 == SV0;
11294 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11295 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11296 // Commute the operands of this shuffle so that next rule
11298 return DAG.getCommutedVectorShuffle(*SVN);
11301 // Try to fold according to rules:
11302 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11303 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11304 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11305 // Don't try to fold shuffles with illegal type.
11306 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11307 TLI.isTypeLegal(VT)) {
11308 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11310 // The incoming shuffle must be of the same type as the result of the
11311 // current shuffle.
11312 assert(OtherSV->getOperand(0).getValueType() == VT &&
11313 "Shuffle types don't match");
11316 SmallVector<int, 4> Mask;
11317 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11318 // operand, and SV1 as the second operand.
11319 for (unsigned i = 0; i != NumElts; ++i) {
11320 int Idx = SVN->getMaskElt(i);
11322 // Propagate Undef.
11323 Mask.push_back(Idx);
11327 SDValue CurrentVec;
11328 if (Idx < (int)NumElts) {
11329 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11330 // shuffle mask to identify which vector is actually referenced.
11331 Idx = OtherSV->getMaskElt(Idx);
11333 // Propagate Undef.
11334 Mask.push_back(Idx);
11338 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11339 : OtherSV->getOperand(1);
11341 // This shuffle index references an element within N1.
11345 // Simple case where 'CurrentVec' is UNDEF.
11346 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11347 Mask.push_back(-1);
11351 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11352 // will be the first or second operand of the combined shuffle.
11353 Idx = Idx % NumElts;
11354 if (!SV0.getNode() || SV0 == CurrentVec) {
11355 // Ok. CurrentVec is the left hand side.
11356 // Update the mask accordingly.
11358 Mask.push_back(Idx);
11362 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11363 if (SV1.getNode() && SV1 != CurrentVec)
11366 // Ok. CurrentVec is the right hand side.
11367 // Update the mask accordingly.
11369 Mask.push_back(Idx + NumElts);
11372 // Check if all indices in Mask are Undef. In case, propagate Undef.
11373 bool isUndefMask = true;
11374 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11375 isUndefMask &= Mask[i] < 0;
11378 return DAG.getUNDEF(VT);
11380 if (!SV0.getNode())
11381 SV0 = DAG.getUNDEF(VT);
11382 if (!SV1.getNode())
11383 SV1 = DAG.getUNDEF(VT);
11385 // Avoid introducing shuffles with illegal mask.
11386 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11387 // Compute the commuted shuffle mask and test again.
11388 for (unsigned i = 0; i != NumElts; ++i) {
11392 else if (idx < (int)NumElts)
11393 Mask[i] = idx + NumElts;
11395 Mask[i] = idx - NumElts;
11398 if (!TLI.isShuffleMaskLegal(Mask, VT))
11401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11402 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11403 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11404 std::swap(SV0, SV1);
11407 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11408 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11409 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11410 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11416 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11417 SDValue N0 = N->getOperand(0);
11418 SDValue N2 = N->getOperand(2);
11420 // If the input vector is a concatenation, and the insert replaces
11421 // one of the halves, we can optimize into a single concat_vectors.
11422 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11423 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11424 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11425 EVT VT = N->getValueType(0);
11427 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11428 // (concat_vectors Z, Y)
11430 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11431 N->getOperand(1), N0.getOperand(1));
11433 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11434 // (concat_vectors X, Z)
11435 if (InsIdx == VT.getVectorNumElements()/2)
11436 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11437 N0.getOperand(0), N->getOperand(1));
11443 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11444 /// with the destination vector and a zero vector.
11445 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11446 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11447 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11448 EVT VT = N->getValueType(0);
11450 SDValue LHS = N->getOperand(0);
11451 SDValue RHS = N->getOperand(1);
11452 if (N->getOpcode() == ISD::AND) {
11453 if (RHS.getOpcode() == ISD::BITCAST)
11454 RHS = RHS.getOperand(0);
11455 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11456 SmallVector<int, 8> Indices;
11457 unsigned NumElts = RHS.getNumOperands();
11458 for (unsigned i = 0; i != NumElts; ++i) {
11459 SDValue Elt = RHS.getOperand(i);
11460 if (!isa<ConstantSDNode>(Elt))
11463 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11464 Indices.push_back(i);
11465 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11466 Indices.push_back(NumElts+i);
11471 // Let's see if the target supports this vector_shuffle.
11472 EVT RVT = RHS.getValueType();
11473 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11476 // Return the new VECTOR_SHUFFLE node.
11477 EVT EltVT = RVT.getVectorElementType();
11478 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11479 DAG.getConstant(0, EltVT));
11480 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11481 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11482 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11483 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11490 /// Visit a binary vector operation, like ADD.
11491 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11492 assert(N->getValueType(0).isVector() &&
11493 "SimplifyVBinOp only works on vectors!");
11495 SDValue LHS = N->getOperand(0);
11496 SDValue RHS = N->getOperand(1);
11497 SDValue Shuffle = XformToShuffleWithZero(N);
11498 if (Shuffle.getNode()) return Shuffle;
11500 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11502 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11503 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11504 // Check if both vectors are constants. If not bail out.
11505 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11506 cast<BuildVectorSDNode>(RHS)->isConstant()))
11509 SmallVector<SDValue, 8> Ops;
11510 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11511 SDValue LHSOp = LHS.getOperand(i);
11512 SDValue RHSOp = RHS.getOperand(i);
11514 // Can't fold divide by zero.
11515 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11516 N->getOpcode() == ISD::FDIV) {
11517 if ((RHSOp.getOpcode() == ISD::Constant &&
11518 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11519 (RHSOp.getOpcode() == ISD::ConstantFP &&
11520 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11524 EVT VT = LHSOp.getValueType();
11525 EVT RVT = RHSOp.getValueType();
11527 // Integer BUILD_VECTOR operands may have types larger than the element
11528 // size (e.g., when the element type is not legal). Prior to type
11529 // legalization, the types may not match between the two BUILD_VECTORS.
11530 // Truncate one of the operands to make them match.
11531 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11532 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11534 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11538 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11540 if (FoldOp.getOpcode() != ISD::UNDEF &&
11541 FoldOp.getOpcode() != ISD::Constant &&
11542 FoldOp.getOpcode() != ISD::ConstantFP)
11544 Ops.push_back(FoldOp);
11545 AddToWorklist(FoldOp.getNode());
11548 if (Ops.size() == LHS.getNumOperands())
11549 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11552 // Type legalization might introduce new shuffles in the DAG.
11553 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11554 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11555 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11556 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11557 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11558 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11559 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11560 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11562 if (SVN0->getMask().equals(SVN1->getMask())) {
11563 EVT VT = N->getValueType(0);
11564 SDValue UndefVector = LHS.getOperand(1);
11565 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11566 LHS.getOperand(0), RHS.getOperand(0));
11567 AddUsersToWorklist(N);
11568 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11569 &SVN0->getMask()[0]);
11576 /// Visit a binary vector operation, like FABS/FNEG.
11577 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11578 assert(N->getValueType(0).isVector() &&
11579 "SimplifyVUnaryOp only works on vectors!");
11581 SDValue N0 = N->getOperand(0);
11583 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11586 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11587 SmallVector<SDValue, 8> Ops;
11588 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11589 SDValue Op = N0.getOperand(i);
11590 if (Op.getOpcode() != ISD::UNDEF &&
11591 Op.getOpcode() != ISD::ConstantFP)
11593 EVT EltVT = Op.getValueType();
11594 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11595 if (FoldOp.getOpcode() != ISD::UNDEF &&
11596 FoldOp.getOpcode() != ISD::ConstantFP)
11598 Ops.push_back(FoldOp);
11599 AddToWorklist(FoldOp.getNode());
11602 if (Ops.size() != N0.getNumOperands())
11605 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11608 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11609 SDValue N1, SDValue N2){
11610 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11612 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11613 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11615 // If we got a simplified select_cc node back from SimplifySelectCC, then
11616 // break it down into a new SETCC node, and a new SELECT node, and then return
11617 // the SELECT node, since we were called with a SELECT node.
11618 if (SCC.getNode()) {
11619 // Check to see if we got a select_cc back (to turn into setcc/select).
11620 // Otherwise, just return whatever node we got back, like fabs.
11621 if (SCC.getOpcode() == ISD::SELECT_CC) {
11622 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11624 SCC.getOperand(0), SCC.getOperand(1),
11625 SCC.getOperand(4));
11626 AddToWorklist(SETCC.getNode());
11627 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11628 SCC.getOperand(2), SCC.getOperand(3));
11636 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11637 /// being selected between, see if we can simplify the select. Callers of this
11638 /// should assume that TheSelect is deleted if this returns true. As such, they
11639 /// should return the appropriate thing (e.g. the node) back to the top-level of
11640 /// the DAG combiner loop to avoid it being looked at.
11641 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11644 // Cannot simplify select with vector condition
11645 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11647 // If this is a select from two identical things, try to pull the operation
11648 // through the select.
11649 if (LHS.getOpcode() != RHS.getOpcode() ||
11650 !LHS.hasOneUse() || !RHS.hasOneUse())
11653 // If this is a load and the token chain is identical, replace the select
11654 // of two loads with a load through a select of the address to load from.
11655 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11656 // constants have been dropped into the constant pool.
11657 if (LHS.getOpcode() == ISD::LOAD) {
11658 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11659 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11661 // Token chains must be identical.
11662 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11663 // Do not let this transformation reduce the number of volatile loads.
11664 LLD->isVolatile() || RLD->isVolatile() ||
11665 // If this is an EXTLOAD, the VT's must match.
11666 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11667 // If this is an EXTLOAD, the kind of extension must match.
11668 (LLD->getExtensionType() != RLD->getExtensionType() &&
11669 // The only exception is if one of the extensions is anyext.
11670 LLD->getExtensionType() != ISD::EXTLOAD &&
11671 RLD->getExtensionType() != ISD::EXTLOAD) ||
11672 // FIXME: this discards src value information. This is
11673 // over-conservative. It would be beneficial to be able to remember
11674 // both potential memory locations. Since we are discarding
11675 // src value info, don't do the transformation if the memory
11676 // locations are not in the default address space.
11677 LLD->getPointerInfo().getAddrSpace() != 0 ||
11678 RLD->getPointerInfo().getAddrSpace() != 0 ||
11679 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11680 LLD->getBasePtr().getValueType()))
11683 // Check that the select condition doesn't reach either load. If so,
11684 // folding this will induce a cycle into the DAG. If not, this is safe to
11685 // xform, so create a select of the addresses.
11687 if (TheSelect->getOpcode() == ISD::SELECT) {
11688 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11689 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11690 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11692 // The loads must not depend on one another.
11693 if (LLD->isPredecessorOf(RLD) ||
11694 RLD->isPredecessorOf(LLD))
11696 Addr = DAG.getSelect(SDLoc(TheSelect),
11697 LLD->getBasePtr().getValueType(),
11698 TheSelect->getOperand(0), LLD->getBasePtr(),
11699 RLD->getBasePtr());
11700 } else { // Otherwise SELECT_CC
11701 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11702 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11704 if ((LLD->hasAnyUseOfValue(1) &&
11705 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11706 (RLD->hasAnyUseOfValue(1) &&
11707 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11710 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11711 LLD->getBasePtr().getValueType(),
11712 TheSelect->getOperand(0),
11713 TheSelect->getOperand(1),
11714 LLD->getBasePtr(), RLD->getBasePtr(),
11715 TheSelect->getOperand(4));
11719 // It is safe to replace the two loads if they have different alignments,
11720 // but the new load must be the minimum (most restrictive) alignment of the
11722 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11723 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11724 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11725 Load = DAG.getLoad(TheSelect->getValueType(0),
11727 // FIXME: Discards pointer and AA info.
11728 LLD->getChain(), Addr, MachinePointerInfo(),
11729 LLD->isVolatile(), LLD->isNonTemporal(),
11730 isInvariant, Alignment);
11732 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11733 RLD->getExtensionType() : LLD->getExtensionType(),
11735 TheSelect->getValueType(0),
11736 // FIXME: Discards pointer and AA info.
11737 LLD->getChain(), Addr, MachinePointerInfo(),
11738 LLD->getMemoryVT(), LLD->isVolatile(),
11739 LLD->isNonTemporal(), isInvariant, Alignment);
11742 // Users of the select now use the result of the load.
11743 CombineTo(TheSelect, Load);
11745 // Users of the old loads now use the new load's chain. We know the
11746 // old-load value is dead now.
11747 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11748 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11755 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11756 /// where 'cond' is the comparison specified by CC.
11757 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11758 SDValue N2, SDValue N3,
11759 ISD::CondCode CC, bool NotExtCompare) {
11760 // (x ? y : y) -> y.
11761 if (N2 == N3) return N2;
11763 EVT VT = N2.getValueType();
11764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11765 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11766 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11768 // Determine if the condition we're dealing with is constant
11769 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11770 N0, N1, CC, DL, false);
11771 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11772 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11774 // fold select_cc true, x, y -> x
11775 if (SCCC && !SCCC->isNullValue())
11777 // fold select_cc false, x, y -> y
11778 if (SCCC && SCCC->isNullValue())
11781 // Check to see if we can simplify the select into an fabs node
11782 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11783 // Allow either -0.0 or 0.0
11784 if (CFP->getValueAPF().isZero()) {
11785 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11786 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11787 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11788 N2 == N3.getOperand(0))
11789 return DAG.getNode(ISD::FABS, DL, VT, N0);
11791 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11792 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11793 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11794 N2.getOperand(0) == N3)
11795 return DAG.getNode(ISD::FABS, DL, VT, N3);
11799 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11800 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11801 // in it. This is a win when the constant is not otherwise available because
11802 // it replaces two constant pool loads with one. We only do this if the FP
11803 // type is known to be legal, because if it isn't, then we are before legalize
11804 // types an we want the other legalization to happen first (e.g. to avoid
11805 // messing with soft float) and if the ConstantFP is not legal, because if
11806 // it is legal, we may not need to store the FP constant in a constant pool.
11807 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11808 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11809 if (TLI.isTypeLegal(N2.getValueType()) &&
11810 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11811 TargetLowering::Legal &&
11812 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11813 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11814 // If both constants have multiple uses, then we won't need to do an
11815 // extra load, they are likely around in registers for other users.
11816 (TV->hasOneUse() || FV->hasOneUse())) {
11817 Constant *Elts[] = {
11818 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11819 const_cast<ConstantFP*>(TV->getConstantFPValue())
11821 Type *FPTy = Elts[0]->getType();
11822 const DataLayout &TD = *TLI.getDataLayout();
11824 // Create a ConstantArray of the two constants.
11825 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11826 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11827 TD.getPrefTypeAlignment(FPTy));
11828 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11830 // Get the offsets to the 0 and 1 element of the array so that we can
11831 // select between them.
11832 SDValue Zero = DAG.getIntPtrConstant(0);
11833 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11834 SDValue One = DAG.getIntPtrConstant(EltSize);
11836 SDValue Cond = DAG.getSetCC(DL,
11837 getSetCCResultType(N0.getValueType()),
11839 AddToWorklist(Cond.getNode());
11840 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11842 AddToWorklist(CstOffset.getNode());
11843 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11845 AddToWorklist(CPIdx.getNode());
11846 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11847 MachinePointerInfo::getConstantPool(), false,
11848 false, false, Alignment);
11853 // Check to see if we can perform the "gzip trick", transforming
11854 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11855 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11856 (N1C->isNullValue() || // (a < 0) ? b : 0
11857 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11858 EVT XType = N0.getValueType();
11859 EVT AType = N2.getValueType();
11860 if (XType.bitsGE(AType)) {
11861 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11862 // single-bit constant.
11863 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11864 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11865 ShCtV = XType.getSizeInBits()-ShCtV-1;
11866 SDValue ShCt = DAG.getConstant(ShCtV,
11867 getShiftAmountTy(N0.getValueType()));
11868 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11870 AddToWorklist(Shift.getNode());
11872 if (XType.bitsGT(AType)) {
11873 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11874 AddToWorklist(Shift.getNode());
11877 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11880 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11882 DAG.getConstant(XType.getSizeInBits()-1,
11883 getShiftAmountTy(N0.getValueType())));
11884 AddToWorklist(Shift.getNode());
11886 if (XType.bitsGT(AType)) {
11887 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11888 AddToWorklist(Shift.getNode());
11891 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11895 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11896 // where y is has a single bit set.
11897 // A plaintext description would be, we can turn the SELECT_CC into an AND
11898 // when the condition can be materialized as an all-ones register. Any
11899 // single bit-test can be materialized as an all-ones register with
11900 // shift-left and shift-right-arith.
11901 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11902 N0->getValueType(0) == VT &&
11903 N1C && N1C->isNullValue() &&
11904 N2C && N2C->isNullValue()) {
11905 SDValue AndLHS = N0->getOperand(0);
11906 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11907 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11908 // Shift the tested bit over the sign bit.
11909 APInt AndMask = ConstAndRHS->getAPIntValue();
11911 DAG.getConstant(AndMask.countLeadingZeros(),
11912 getShiftAmountTy(AndLHS.getValueType()));
11913 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11915 // Now arithmetic right shift it all the way over, so the result is either
11916 // all-ones, or zero.
11918 DAG.getConstant(AndMask.getBitWidth()-1,
11919 getShiftAmountTy(Shl.getValueType()));
11920 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11922 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11926 // fold select C, 16, 0 -> shl C, 4
11927 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11928 TLI.getBooleanContents(N0.getValueType()) ==
11929 TargetLowering::ZeroOrOneBooleanContent) {
11931 // If the caller doesn't want us to simplify this into a zext of a compare,
11933 if (NotExtCompare && N2C->getAPIntValue() == 1)
11936 // Get a SetCC of the condition
11937 // NOTE: Don't create a SETCC if it's not legal on this target.
11938 if (!LegalOperations ||
11939 TLI.isOperationLegal(ISD::SETCC,
11940 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11942 // cast from setcc result type to select result type
11944 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11946 if (N2.getValueType().bitsLT(SCC.getValueType()))
11947 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11948 N2.getValueType());
11950 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11951 N2.getValueType(), SCC);
11953 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11954 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11955 N2.getValueType(), SCC);
11958 AddToWorklist(SCC.getNode());
11959 AddToWorklist(Temp.getNode());
11961 if (N2C->getAPIntValue() == 1)
11964 // shl setcc result by log2 n2c
11965 return DAG.getNode(
11966 ISD::SHL, DL, N2.getValueType(), Temp,
11967 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11968 getShiftAmountTy(Temp.getValueType())));
11972 // Check to see if this is the equivalent of setcc
11973 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11974 // otherwise, go ahead with the folds.
11975 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11976 EVT XType = N0.getValueType();
11977 if (!LegalOperations ||
11978 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11979 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11980 if (Res.getValueType() != VT)
11981 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11985 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11986 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11987 (!LegalOperations ||
11988 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11989 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11990 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11991 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11992 getShiftAmountTy(Ctlz.getValueType())));
11994 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11995 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11996 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11997 XType, DAG.getConstant(0, XType), N0);
11998 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11999 return DAG.getNode(ISD::SRL, DL, XType,
12000 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12001 DAG.getConstant(XType.getSizeInBits()-1,
12002 getShiftAmountTy(XType)));
12004 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12005 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12006 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12007 DAG.getConstant(XType.getSizeInBits()-1,
12008 getShiftAmountTy(N0.getValueType())));
12009 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12013 // Check to see if this is an integer abs.
12014 // select_cc setg[te] X, 0, X, -X ->
12015 // select_cc setgt X, -1, X, -X ->
12016 // select_cc setl[te] X, 0, -X, X ->
12017 // select_cc setlt X, 1, -X, X ->
12018 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12020 ConstantSDNode *SubC = nullptr;
12021 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12022 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12023 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12024 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12025 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12026 (N1C->isOne() && CC == ISD::SETLT)) &&
12027 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12028 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12030 EVT XType = N0.getValueType();
12031 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12032 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12034 DAG.getConstant(XType.getSizeInBits()-1,
12035 getShiftAmountTy(N0.getValueType())));
12036 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12038 AddToWorklist(Shift.getNode());
12039 AddToWorklist(Add.getNode());
12040 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12047 /// This is a stub for TargetLowering::SimplifySetCC.
12048 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12049 SDValue N1, ISD::CondCode Cond,
12050 SDLoc DL, bool foldBooleans) {
12051 TargetLowering::DAGCombinerInfo
12052 DagCombineInfo(DAG, Level, false, this);
12053 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12056 /// Given an ISD::SDIV node expressing a divide by constant, return
12057 /// a DAG expression to select that will generate the same value by multiplying
12058 /// by a magic number.
12059 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12060 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12061 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12065 // Avoid division by zero.
12066 if (!C->getAPIntValue())
12069 std::vector<SDNode*> Built;
12071 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12073 for (SDNode *N : Built)
12078 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12079 /// DAG expression that will generate the same value by right shifting.
12080 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12081 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12085 // Avoid division by zero.
12086 if (!C->getAPIntValue())
12089 std::vector<SDNode *> Built;
12090 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12092 for (SDNode *N : Built)
12097 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12098 /// expression that will generate the same value by multiplying by a magic
12100 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12101 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12102 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12106 // Avoid division by zero.
12107 if (!C->getAPIntValue())
12110 std::vector<SDNode*> Built;
12112 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12114 for (SDNode *N : Built)
12119 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12120 if (Level >= AfterLegalizeDAG)
12123 // Expose the DAG combiner to the target combiner implementations.
12124 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12126 unsigned Iterations = 0;
12127 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12129 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12130 // For the reciprocal, we need to find the zero of the function:
12131 // F(X) = A X - 1 [which has a zero at X = 1/A]
12133 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12134 // does not require additional intermediate precision]
12135 EVT VT = Op.getValueType();
12137 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12139 AddToWorklist(Est.getNode());
12141 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12142 for (unsigned i = 0; i < Iterations; ++i) {
12143 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12144 AddToWorklist(NewEst.getNode());
12146 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12147 AddToWorklist(NewEst.getNode());
12149 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12150 AddToWorklist(NewEst.getNode());
12152 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12153 AddToWorklist(Est.getNode());
12162 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12163 /// For the reciprocal sqrt, we need to find the zero of the function:
12164 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12166 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12167 /// As a result, we precompute A/2 prior to the iteration loop.
12168 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12169 unsigned Iterations) {
12170 EVT VT = Arg.getValueType();
12172 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12174 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12175 // this entire sequence requires only one FP constant.
12176 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12177 AddToWorklist(HalfArg.getNode());
12179 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12180 AddToWorklist(HalfArg.getNode());
12182 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12183 for (unsigned i = 0; i < Iterations; ++i) {
12184 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12185 AddToWorklist(NewEst.getNode());
12187 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12188 AddToWorklist(NewEst.getNode());
12190 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12191 AddToWorklist(NewEst.getNode());
12193 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12194 AddToWorklist(Est.getNode());
12199 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12200 /// For the reciprocal sqrt, we need to find the zero of the function:
12201 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12203 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12204 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12205 unsigned Iterations) {
12206 EVT VT = Arg.getValueType();
12208 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12209 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12211 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12212 for (unsigned i = 0; i < Iterations; ++i) {
12213 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12214 AddToWorklist(HalfEst.getNode());
12216 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12217 AddToWorklist(Est.getNode());
12219 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12220 AddToWorklist(Est.getNode());
12222 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12223 AddToWorklist(Est.getNode());
12225 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12226 AddToWorklist(Est.getNode());
12231 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12232 if (Level >= AfterLegalizeDAG)
12235 // Expose the DAG combiner to the target combiner implementations.
12236 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12237 unsigned Iterations = 0;
12238 bool UseOneConstNR = false;
12239 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12240 AddToWorklist(Est.getNode());
12242 Est = UseOneConstNR ?
12243 BuildRsqrtNROneConst(Op, Est, Iterations) :
12244 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12252 /// Return true if base is a frame index, which is known not to alias with
12253 /// anything but itself. Provides base object and offset as results.
12254 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12255 const GlobalValue *&GV, const void *&CV) {
12256 // Assume it is a primitive operation.
12257 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12259 // If it's an adding a simple constant then integrate the offset.
12260 if (Base.getOpcode() == ISD::ADD) {
12261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12262 Base = Base.getOperand(0);
12263 Offset += C->getZExtValue();
12267 // Return the underlying GlobalValue, and update the Offset. Return false
12268 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12269 // by multiple nodes with different offsets.
12270 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12271 GV = G->getGlobal();
12272 Offset += G->getOffset();
12276 // Return the underlying Constant value, and update the Offset. Return false
12277 // for ConstantSDNodes since the same constant pool entry may be represented
12278 // by multiple nodes with different offsets.
12279 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12280 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12281 : (const void *)C->getConstVal();
12282 Offset += C->getOffset();
12285 // If it's any of the following then it can't alias with anything but itself.
12286 return isa<FrameIndexSDNode>(Base);
12289 /// Return true if there is any possibility that the two addresses overlap.
12290 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12291 // If they are the same then they must be aliases.
12292 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12294 // If they are both volatile then they cannot be reordered.
12295 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12297 // Gather base node and offset information.
12298 SDValue Base1, Base2;
12299 int64_t Offset1, Offset2;
12300 const GlobalValue *GV1, *GV2;
12301 const void *CV1, *CV2;
12302 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12303 Base1, Offset1, GV1, CV1);
12304 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12305 Base2, Offset2, GV2, CV2);
12307 // If they have a same base address then check to see if they overlap.
12308 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12309 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12310 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12312 // It is possible for different frame indices to alias each other, mostly
12313 // when tail call optimization reuses return address slots for arguments.
12314 // To catch this case, look up the actual index of frame indices to compute
12315 // the real alias relationship.
12316 if (isFrameIndex1 && isFrameIndex2) {
12317 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12318 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12319 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12320 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12321 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12324 // Otherwise, if we know what the bases are, and they aren't identical, then
12325 // we know they cannot alias.
12326 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12329 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12330 // compared to the size and offset of the access, we may be able to prove they
12331 // do not alias. This check is conservative for now to catch cases created by
12332 // splitting vector types.
12333 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12334 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12335 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12336 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12337 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12338 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12339 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12341 // There is no overlap between these relatively aligned accesses of similar
12342 // size, return no alias.
12343 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12344 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12348 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12350 : DAG.getSubtarget().useAA();
12352 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12353 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12357 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12358 // Use alias analysis information.
12359 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12360 Op1->getSrcValueOffset());
12361 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12362 Op0->getSrcValueOffset() - MinOffset;
12363 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12364 Op1->getSrcValueOffset() - MinOffset;
12365 AliasAnalysis::AliasResult AAResult =
12366 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12368 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12369 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12371 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12372 if (AAResult == AliasAnalysis::NoAlias)
12376 // Otherwise we have to assume they alias.
12380 /// Walk up chain skipping non-aliasing memory nodes,
12381 /// looking for aliasing nodes and adding them to the Aliases vector.
12382 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12383 SmallVectorImpl<SDValue> &Aliases) {
12384 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12385 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12387 // Get alias information for node.
12388 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12391 Chains.push_back(OriginalChain);
12392 unsigned Depth = 0;
12394 // Look at each chain and determine if it is an alias. If so, add it to the
12395 // aliases list. If not, then continue up the chain looking for the next
12397 while (!Chains.empty()) {
12398 SDValue Chain = Chains.back();
12401 // For TokenFactor nodes, look at each operand and only continue up the
12402 // chain until we find two aliases. If we've seen two aliases, assume we'll
12403 // find more and revert to original chain since the xform is unlikely to be
12406 // FIXME: The depth check could be made to return the last non-aliasing
12407 // chain we found before we hit a tokenfactor rather than the original
12409 if (Depth > 6 || Aliases.size() == 2) {
12411 Aliases.push_back(OriginalChain);
12415 // Don't bother if we've been before.
12416 if (!Visited.insert(Chain.getNode()).second)
12419 switch (Chain.getOpcode()) {
12420 case ISD::EntryToken:
12421 // Entry token is ideal chain operand, but handled in FindBetterChain.
12426 // Get alias information for Chain.
12427 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12428 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12430 // If chain is alias then stop here.
12431 if (!(IsLoad && IsOpLoad) &&
12432 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12433 Aliases.push_back(Chain);
12435 // Look further up the chain.
12436 Chains.push_back(Chain.getOperand(0));
12442 case ISD::TokenFactor:
12443 // We have to check each of the operands of the token factor for "small"
12444 // token factors, so we queue them up. Adding the operands to the queue
12445 // (stack) in reverse order maintains the original order and increases the
12446 // likelihood that getNode will find a matching token factor (CSE.)
12447 if (Chain.getNumOperands() > 16) {
12448 Aliases.push_back(Chain);
12451 for (unsigned n = Chain.getNumOperands(); n;)
12452 Chains.push_back(Chain.getOperand(--n));
12457 // For all other instructions we will just have to take what we can get.
12458 Aliases.push_back(Chain);
12463 // We need to be careful here to also search for aliases through the
12464 // value operand of a store, etc. Consider the following situation:
12466 // L1 = load Token1, %52
12467 // S1 = store Token1, L1, %51
12468 // L2 = load Token1, %52+8
12469 // S2 = store Token1, L2, %51+8
12470 // Token2 = Token(S1, S2)
12471 // L3 = load Token2, %53
12472 // S3 = store Token2, L3, %52
12473 // L4 = load Token2, %53+8
12474 // S4 = store Token2, L4, %52+8
12475 // If we search for aliases of S3 (which loads address %52), and we look
12476 // only through the chain, then we'll miss the trivial dependence on L1
12477 // (which also loads from %52). We then might change all loads and
12478 // stores to use Token1 as their chain operand, which could result in
12479 // copying %53 into %52 before copying %52 into %51 (which should
12482 // The problem is, however, that searching for such data dependencies
12483 // can become expensive, and the cost is not directly related to the
12484 // chain depth. Instead, we'll rule out such configurations here by
12485 // insisting that we've visited all chain users (except for users
12486 // of the original chain, which is not necessary). When doing this,
12487 // we need to look through nodes we don't care about (otherwise, things
12488 // like register copies will interfere with trivial cases).
12490 SmallVector<const SDNode *, 16> Worklist;
12491 for (const SDNode *N : Visited)
12492 if (N != OriginalChain.getNode())
12493 Worklist.push_back(N);
12495 while (!Worklist.empty()) {
12496 const SDNode *M = Worklist.pop_back_val();
12498 // We have already visited M, and want to make sure we've visited any uses
12499 // of M that we care about. For uses that we've not visisted, and don't
12500 // care about, queue them to the worklist.
12502 for (SDNode::use_iterator UI = M->use_begin(),
12503 UIE = M->use_end(); UI != UIE; ++UI)
12504 if (UI.getUse().getValueType() == MVT::Other &&
12505 Visited.insert(*UI).second) {
12506 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12507 // We've not visited this use, and we care about it (it could have an
12508 // ordering dependency with the original node).
12510 Aliases.push_back(OriginalChain);
12514 // We've not visited this use, but we don't care about it. Mark it as
12515 // visited and enqueue it to the worklist.
12516 Worklist.push_back(*UI);
12521 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12522 /// (aliasing node.)
12523 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12524 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12526 // Accumulate all the aliases to this node.
12527 GatherAllAliases(N, OldChain, Aliases);
12529 // If no operands then chain to entry token.
12530 if (Aliases.size() == 0)
12531 return DAG.getEntryNode();
12533 // If a single operand then chain to it. We don't need to revisit it.
12534 if (Aliases.size() == 1)
12537 // Construct a custom tailored token factor.
12538 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12541 /// This is the entry point for the file.
12542 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12543 CodeGenOpt::Level OptLevel) {
12544 /// This is the main entry point to this class.
12545 DAGCombiner(*this, AA, OptLevel).Run(Level);