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/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "dagcombine"
46 STATISTIC(NodesCombined , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Enable DAG combiner alias-analysis heuristics"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Enable DAG combiner's use of IR alias analysis"));
63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64 cl::desc("Enable DAG combiner's use of TBAA"));
67 static cl::opt<std::string>
68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69 cl::desc("Only use DAG-combiner alias analysis in this"
73 /// Hidden option to stress test load slicing, i.e., when this option
74 /// is enabled, load slicing bypasses most of its profitability guards.
76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77 cl::desc("Bypass the profitability model of load "
82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83 cl::desc("DAG combiner may split indexing from loads"));
85 //------------------------------ DAGCombiner ---------------------------------//
89 const TargetLowering &TLI;
91 CodeGenOpt::Level OptLevel;
96 /// \brief Worklist of all of the nodes that need to be simplified.
98 /// This must behave as a stack -- new nodes to process are pushed onto the
99 /// back and when processing we pop off of the back.
101 /// The worklist will not contain duplicates but may contain null entries
102 /// due to nodes being deleted from the underlying DAG.
103 SmallVector<SDNode *, 64> Worklist;
105 /// \brief Mapping from an SDNode to its position on the worklist.
107 /// This is used to find and remove nodes from the worklist (by nulling
108 /// them) when they are deleted from the underlying DAG. It relies on
109 /// stable indices of nodes within the worklist.
110 DenseMap<SDNode *, unsigned> WorklistMap;
112 /// \brief Set of nodes which have been combined (at least once).
114 /// This is used to allow us to reliably add any operands of a DAG node
115 /// which have not yet been combined to the worklist.
116 SmallPtrSet<SDNode *, 64> CombinedNodes;
118 // AA - Used for DAG load/store alias analysis.
121 /// When an instruction is simplified, add all users of the instruction to
122 /// the work lists because they might get more simplified now.
123 void AddUsersToWorklist(SDNode *N) {
124 for (SDNode *Node : N->uses())
128 /// Call the node-specific routine that folds each particular type of node.
129 SDValue visit(SDNode *N);
132 /// Add to the worklist making sure its instance is at the back (next to be
134 void AddToWorklist(SDNode *N) {
135 // Skip handle nodes as they can't usefully be combined and confuse the
136 // zero-use deletion strategy.
137 if (N->getOpcode() == ISD::HANDLENODE)
140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141 Worklist.push_back(N);
144 /// Remove all instances of N from the worklist.
145 void removeFromWorklist(SDNode *N) {
146 CombinedNodes.erase(N);
148 auto It = WorklistMap.find(N);
149 if (It == WorklistMap.end())
150 return; // Not in the worklist.
152 // Null out the entry rather than erasing it to avoid a linear operation.
153 Worklist[It->second] = nullptr;
154 WorklistMap.erase(It);
157 void deleteAndRecombine(SDNode *N);
158 bool recursivelyDeleteUnusedNodes(SDNode *N);
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
164 return CombineTo(N, &Res, 1, AddTo);
167 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
169 SDValue To[] = { Res0, Res1 };
170 return CombineTo(N, To, 2, AddTo);
173 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 /// Check the specified integer node value to see if it can be simplified or
178 /// if things it uses can be simplified by bit propagation.
179 /// If so, return true.
180 bool SimplifyDemandedBits(SDValue Op) {
181 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
182 APInt Demanded = APInt::getAllOnesValue(BitWidth);
183 return SimplifyDemandedBits(Op, Demanded);
186 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
188 bool CombineToPreIndexedLoadStore(SDNode *N);
189 bool CombineToPostIndexedLoadStore(SDNode *N);
190 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
191 bool SliceUpLoad(SDNode *N);
193 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
197 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
198 /// \param EltNo index of the vector element to load.
199 /// \param OriginalLoad load that EVE came from to be replaced.
200 /// \returns EVE on success SDValue() on failure.
201 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
202 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
203 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
204 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
205 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
207 SDValue PromoteIntBinOp(SDValue Op);
208 SDValue PromoteIntShiftOp(SDValue Op);
209 SDValue PromoteExtend(SDValue Op);
210 bool PromoteLoad(SDValue Op);
212 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
213 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
214 ISD::NodeType ExtType);
216 /// Call the node-specific routine that knows how to fold each
217 /// particular type of node. If that doesn't do anything, try the
218 /// target-specific DAG combines.
219 SDValue combine(SDNode *N);
221 // Visitation implementation - Implement dag node combining for different
222 // node types. The semantics are as follows:
224 // SDValue.getNode() == 0 - No change was made
225 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
226 // otherwise - N should be replaced by the returned Operand.
228 SDValue visitTokenFactor(SDNode *N);
229 SDValue visitMERGE_VALUES(SDNode *N);
230 SDValue visitADD(SDNode *N);
231 SDValue visitSUB(SDNode *N);
232 SDValue visitADDC(SDNode *N);
233 SDValue visitSUBC(SDNode *N);
234 SDValue visitADDE(SDNode *N);
235 SDValue visitSUBE(SDNode *N);
236 SDValue visitMUL(SDNode *N);
237 SDValue visitSDIV(SDNode *N);
238 SDValue visitUDIV(SDNode *N);
239 SDValue visitSREM(SDNode *N);
240 SDValue visitUREM(SDNode *N);
241 SDValue visitMULHU(SDNode *N);
242 SDValue visitMULHS(SDNode *N);
243 SDValue visitSMUL_LOHI(SDNode *N);
244 SDValue visitUMUL_LOHI(SDNode *N);
245 SDValue visitSMULO(SDNode *N);
246 SDValue visitUMULO(SDNode *N);
247 SDValue visitSDIVREM(SDNode *N);
248 SDValue visitUDIVREM(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitOR(SDNode *N);
251 SDValue visitXOR(SDNode *N);
252 SDValue SimplifyVBinOp(SDNode *N);
253 SDValue SimplifyVUnaryOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitCTLZ(SDNode *N);
259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTTZ(SDNode *N);
261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
264 SDValue visitVSELECT(SDNode *N);
265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
272 SDValue visitBITCAST(SDNode *N);
273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
277 SDValue visitFMA(SDNode *N);
278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
280 SDValue visitFSQRT(SDNode *N);
281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
294 SDValue visitBRCOND(SDNode *N);
295 SDValue visitBR_CC(SDNode *N);
296 SDValue visitLOAD(SDNode *N);
297 SDValue visitSTORE(SDNode *N);
298 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
299 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
300 SDValue visitBUILD_VECTOR(SDNode *N);
301 SDValue visitCONCAT_VECTORS(SDNode *N);
302 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
303 SDValue visitVECTOR_SHUFFLE(SDNode *N);
304 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue XformToShuffleWithZero(SDNode *N);
307 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
312 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
313 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
314 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
315 SDValue N3, ISD::CondCode CC,
316 bool NotExtCompare = false);
317 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
318 SDLoc DL, bool foldBooleans = true);
320 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322 bool isOneUseSetCC(SDValue N) const;
324 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
327 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
328 SDValue BuildSDIV(SDNode *N);
329 SDValue BuildSDIVPow2(SDNode *N);
330 SDValue BuildUDIV(SDNode *N);
331 SDValue BuildReciprocalEstimate(SDValue Op);
332 SDValue BuildRsqrtEstimate(SDValue Op);
333 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
334 bool DemandHighBits = true);
335 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
336 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
337 SDValue InnerPos, SDValue InnerNeg,
338 unsigned PosOpcode, unsigned NegOpcode,
340 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
341 SDValue ReduceLoadWidth(SDNode *N);
342 SDValue ReduceLoadOpStoreWidth(SDNode *N);
343 SDValue TransformFPLoadStorePair(SDNode *N);
344 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
345 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
347 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
349 /// Walk up chain skipping non-aliasing memory nodes,
350 /// looking for aliasing nodes and adding them to the Aliases vector.
351 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
352 SmallVectorImpl<SDValue> &Aliases);
354 /// Return true if there is any possibility that the two addresses overlap.
355 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
357 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
358 /// chain (aliasing node.)
359 SDValue FindBetterChain(SDNode *N, SDValue Chain);
361 /// Merge consecutive store operations into a wide store.
362 /// This optimization uses wide integers or vectors when possible.
363 /// \return True if some memory operations were changed.
364 bool MergeConsecutiveStores(StoreSDNode *N);
366 /// \brief Try to transform a truncation where C is a constant:
367 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
369 /// \p N needs to be a truncation and its first operand an AND. Other
370 /// requirements are checked by the function (e.g. that trunc is
371 /// single-use) and if missed an empty SDValue is returned.
372 SDValue distributeTruncateThroughAnd(SDNode *N);
375 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
376 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
377 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
378 AttributeSet FnAttrs =
379 DAG.getMachineFunction().getFunction()->getAttributes();
381 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
382 Attribute::OptimizeForSize) ||
383 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
386 /// Runs the dag combiner on all nodes in the work list
387 void Run(CombineLevel AtLevel);
389 SelectionDAG &getDAG() const { return DAG; }
391 /// Returns a type large enough to hold any valid shift amount - before type
392 /// legalization these can be huge.
393 EVT getShiftAmountTy(EVT LHSTy) {
394 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
395 if (LHSTy.isVector())
397 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
398 : TLI.getPointerTy();
401 /// This method returns true if we are running before type legalization or
402 /// if the specified VT is legal.
403 bool isTypeLegal(const EVT &VT) {
404 if (!LegalTypes) return true;
405 return TLI.isTypeLegal(VT);
408 /// Convenience wrapper around TargetLowering::getSetCCResultType
409 EVT getSetCCResultType(EVT VT) const {
410 return TLI.getSetCCResultType(*DAG.getContext(), VT);
417 /// This class is a DAGUpdateListener that removes any deleted
418 /// nodes from the worklist.
419 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
422 explicit WorklistRemover(DAGCombiner &dc)
423 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
425 void NodeDeleted(SDNode *N, SDNode *E) override {
426 DC.removeFromWorklist(N);
431 //===----------------------------------------------------------------------===//
432 // TargetLowering::DAGCombinerInfo implementation
433 //===----------------------------------------------------------------------===//
435 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
436 ((DAGCombiner*)DC)->AddToWorklist(N);
439 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
440 ((DAGCombiner*)DC)->removeFromWorklist(N);
443 SDValue TargetLowering::DAGCombinerInfo::
444 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
445 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
454 SDValue TargetLowering::DAGCombinerInfo::
455 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
456 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
459 void TargetLowering::DAGCombinerInfo::
460 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
461 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
464 //===----------------------------------------------------------------------===//
466 //===----------------------------------------------------------------------===//
468 void DAGCombiner::deleteAndRecombine(SDNode *N) {
469 removeFromWorklist(N);
471 // If the operands of this node are only used by the node, they will now be
472 // dead. Make sure to re-visit them and recursively delete dead nodes.
473 for (const SDValue &Op : N->ops())
474 // For an operand generating multiple values, one of the values may
475 // become dead allowing further simplification (e.g. split index
476 // arithmetic from an indexed load).
477 if (Op->hasOneUse() || Op->getNumValues() > 1)
478 AddToWorklist(Op.getNode());
483 /// Return 1 if we can compute the negated form of the specified expression for
484 /// the same cost as the expression itself, or 2 if we can compute the negated
485 /// form more cheaply than the expression itself.
486 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
487 const TargetLowering &TLI,
488 const TargetOptions *Options,
489 unsigned Depth = 0) {
490 // fneg is removable even if it has multiple uses.
491 if (Op.getOpcode() == ISD::FNEG) return 2;
493 // Don't allow anything with multiple uses.
494 if (!Op.hasOneUse()) return 0;
496 // Don't recurse exponentially.
497 if (Depth > 6) return 0;
499 switch (Op.getOpcode()) {
500 default: return false;
501 case ISD::ConstantFP:
502 // Don't invert constant FP values after legalize. The negated constant
503 // isn't necessarily legal.
504 return LegalOperations ? 0 : 1;
506 // FIXME: determine better conditions for this xform.
507 if (!Options->UnsafeFPMath) return 0;
509 // After operation legalization, it might not be legal to create new FSUBs.
510 if (LegalOperations &&
511 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
514 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
515 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
518 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
519 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
522 // We can't turn -(A-B) into B-A when we honor signed zeros.
523 if (!Options->UnsafeFPMath) return 0;
525 // fold (fneg (fsub A, B)) -> (fsub B, A)
530 if (Options->HonorSignDependentRoundingFPMath()) return 0;
532 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
533 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
537 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
548 /// If isNegatibleForFree returns true, return the newly negated expression.
549 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
550 bool LegalOperations, unsigned Depth = 0) {
551 const TargetOptions &Options = DAG.getTarget().Options;
552 // fneg is removable even if it has multiple uses.
553 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
555 // Don't allow anything with multiple uses.
556 assert(Op.hasOneUse() && "Unknown reuse!");
558 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
559 switch (Op.getOpcode()) {
560 default: llvm_unreachable("Unknown code");
561 case ISD::ConstantFP: {
562 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
564 return DAG.getConstantFP(V, Op.getValueType());
567 // FIXME: determine better conditions for this xform.
568 assert(Options.UnsafeFPMath);
570 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
571 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
572 DAG.getTargetLoweringInfo(), &Options, Depth+1))
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(0), DAG,
575 LegalOperations, Depth+1),
577 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(1), DAG,
580 LegalOperations, Depth+1),
583 // We can't turn -(A-B) into B-A when we honor signed zeros.
584 assert(Options.UnsafeFPMath);
586 // fold (fneg (fsub 0, B)) -> B
587 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
588 if (N0CFP->getValueAPF().isZero())
589 return Op.getOperand(1);
591 // fold (fneg (fsub A, B)) -> (fsub B, A)
592 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
593 Op.getOperand(1), Op.getOperand(0));
597 assert(!Options.HonorSignDependentRoundingFPMath());
599 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
600 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
601 DAG.getTargetLoweringInfo(), &Options, Depth+1))
602 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
603 GetNegatedExpression(Op.getOperand(0), DAG,
604 LegalOperations, Depth+1),
607 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
608 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
610 GetNegatedExpression(Op.getOperand(1), DAG,
611 LegalOperations, Depth+1));
615 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1));
619 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
620 GetNegatedExpression(Op.getOperand(0), DAG,
621 LegalOperations, Depth+1),
626 // Return true if this node is a setcc, or is a select_cc
627 // that selects between the target values used for true and false, making it
628 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
629 // the appropriate nodes based on the type of node we are checking. This
630 // simplifies life a bit for the callers.
631 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
633 if (N.getOpcode() == ISD::SETCC) {
634 LHS = N.getOperand(0);
635 RHS = N.getOperand(1);
636 CC = N.getOperand(2);
640 if (N.getOpcode() != ISD::SELECT_CC ||
641 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
642 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
645 LHS = N.getOperand(0);
646 RHS = N.getOperand(1);
647 CC = N.getOperand(4);
651 /// Return true if this is a SetCC-equivalent operation with only one use.
652 /// If this is true, it allows the users to invert the operation for free when
653 /// it is profitable to do so.
654 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
656 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
661 /// Returns true if N is a BUILD_VECTOR node whose
662 /// elements are all the same constant or undefined.
663 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
664 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
669 unsigned SplatBitSize;
671 EVT EltVT = N->getValueType(0).getVectorElementType();
672 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
674 EltVT.getSizeInBits() >= SplatBitSize);
677 // \brief Returns the SDNode if it is a constant BuildVector or constant.
678 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
679 if (isa<ConstantSDNode>(N))
681 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
682 if (BV && BV->isConstant())
687 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
689 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
690 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
693 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
694 BitVector UndefElements;
695 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
697 // BuildVectors can truncate their operands. Ignore that case here.
698 // FIXME: We blindly ignore splats which include undef which is overly
700 if (CN && UndefElements.none() &&
701 CN->getValueType(0) == N.getValueType().getScalarType())
708 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
710 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
711 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
714 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
715 BitVector UndefElements;
716 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
718 if (CN && UndefElements.none())
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726 SDValue N0, SDValue N1) {
727 EVT VT = N0.getValueType();
728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
764 AddToWorklist(OpNode.getNode());
765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777 DEBUG(dbgs() << "\nReplacing.1 ";
779 dbgs() << "\nWith: ";
780 To[0].getNode()->dump(&DAG);
781 dbgs() << " and " << NumTo-1 << " other values\n";
782 for (unsigned i = 0, e = NumTo; i != e; ++i)
783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
785 "Cannot combine value to value of different type!"));
786 WorklistRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesWith(N, To);
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
791 if (To[i].getNode()) {
792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
802 deleteAndRecombine(N);
803 return SDValue(N, 0);
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808 // Replace all uses. If any nodes become isomorphic to other nodes and
809 // are deleted, make sure to remove them from our worklist.
810 WorklistRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813 // Push the new node and any (possibly new) users onto the worklist.
814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
824 /// Check the specified integer node value to see if it can be simplified or if
825 /// things it uses can be simplified by bit propagation. If so, return true.
826 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
827 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
828 APInt KnownZero, KnownOne;
829 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
833 AddToWorklist(Op.getNode());
835 // Replace the old value with the new one.
837 DEBUG(dbgs() << "\nReplacing.2 ";
838 TLO.Old.getNode()->dump(&DAG);
839 dbgs() << "\nWith: ";
840 TLO.New.getNode()->dump(&DAG);
843 CommitTargetLoweringOpt(TLO);
847 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849 EVT VT = Load->getValueType(0);
850 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852 DEBUG(dbgs() << "\nReplacing.9 ";
854 dbgs() << "\nWith: ";
855 Trunc.getNode()->dump(&DAG);
857 WorklistRemover DeadNodes(*this);
858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
860 deleteAndRecombine(Load);
861 AddToWorklist(Trunc.getNode());
864 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
868 EVT MemVT = LD->getMemoryVT();
869 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
870 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872 : LD->getExtensionType();
874 return DAG.getExtLoad(ExtType, dl, PVT,
875 LD->getChain(), LD->getBasePtr(),
876 MemVT, LD->getMemOperand());
879 unsigned Opc = Op.getOpcode();
882 case ISD::AssertSext:
883 return DAG.getNode(ISD::AssertSext, dl, PVT,
884 SExtPromoteOperand(Op.getOperand(0), PVT),
886 case ISD::AssertZext:
887 return DAG.getNode(ISD::AssertZext, dl, PVT,
888 ZExtPromoteOperand(Op.getOperand(0), PVT),
890 case ISD::Constant: {
892 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
893 return DAG.getNode(ExtOpc, dl, PVT, Op);
897 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
902 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
903 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905 EVT OldVT = Op.getValueType();
907 bool Replace = false;
908 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
909 if (!NewOp.getNode())
911 AddToWorklist(NewOp.getNode());
914 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
916 DAG.getValueType(OldVT));
919 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
920 EVT OldVT = Op.getValueType();
922 bool Replace = false;
923 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
924 if (!NewOp.getNode())
926 AddToWorklist(NewOp.getNode());
929 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
933 /// Promote the specified integer binary operation if the target indicates it is
934 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935 /// i32 since i16 instructions are longer.
936 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937 if (!LegalOperations)
940 EVT VT = Op.getValueType();
941 if (VT.isVector() || !VT.isInteger())
944 // If operation type is 'undesirable', e.g. i16 on x86, consider
946 unsigned Opc = Op.getOpcode();
947 if (TLI.isTypeDesirableForOp(Opc, VT))
951 // Consult target whether it is a good idea to promote this operation and
952 // what's the right type to promote it to.
953 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
954 assert(PVT != VT && "Don't know what type to promote to!");
956 bool Replace0 = false;
957 SDValue N0 = Op.getOperand(0);
958 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
962 bool Replace1 = false;
963 SDValue N1 = Op.getOperand(1);
968 NN1 = PromoteOperand(N1, PVT, Replace1);
973 AddToWorklist(NN0.getNode());
975 AddToWorklist(NN1.getNode());
978 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982 DEBUG(dbgs() << "\nPromoting ";
983 Op.getNode()->dump(&DAG));
985 return DAG.getNode(ISD::TRUNCATE, dl, VT,
986 DAG.getNode(Opc, dl, PVT, NN0, NN1));
991 /// Promote the specified integer shift operation if the target indicates it is
992 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993 /// i32 since i16 instructions are longer.
994 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995 if (!LegalOperations)
998 EVT VT = Op.getValueType();
999 if (VT.isVector() || !VT.isInteger())
1002 // If operation type is 'undesirable', e.g. i16 on x86, consider
1004 unsigned Opc = Op.getOpcode();
1005 if (TLI.isTypeDesirableForOp(Opc, VT))
1009 // Consult target whether it is a good idea to promote this operation and
1010 // what's the right type to promote it to.
1011 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012 assert(PVT != VT && "Don't know what type to promote to!");
1014 bool Replace = false;
1015 SDValue N0 = Op.getOperand(0);
1016 if (Opc == ISD::SRA)
1017 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1018 else if (Opc == ISD::SRL)
1019 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021 N0 = PromoteOperand(N0, PVT, Replace);
1025 AddToWorklist(N0.getNode());
1027 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029 DEBUG(dbgs() << "\nPromoting ";
1030 Op.getNode()->dump(&DAG));
1032 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1038 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039 if (!LegalOperations)
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1057 // fold (aext (aext x)) -> (aext x)
1058 // fold (aext (zext x)) -> (zext x)
1059 // fold (aext (sext x)) -> (sext x)
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1067 bool DAGCombiner::PromoteLoad(SDValue Op) {
1068 if (!LegalOperations)
1071 EVT VT = Op.getValueType();
1072 if (VT.isVector() || !VT.isInteger())
1075 // If operation type is 'undesirable', e.g. i16 on x86, consider
1077 unsigned Opc = Op.getOpcode();
1078 if (TLI.isTypeDesirableForOp(Opc, VT))
1082 // Consult target whether it is a good idea to promote this operation and
1083 // what's the right type to promote it to.
1084 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085 assert(PVT != VT && "Don't know what type to promote to!");
1088 SDNode *N = Op.getNode();
1089 LoadSDNode *LD = cast<LoadSDNode>(N);
1090 EVT MemVT = LD->getMemoryVT();
1091 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094 : LD->getExtensionType();
1095 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1096 LD->getChain(), LD->getBasePtr(),
1097 MemVT, LD->getMemOperand());
1098 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100 DEBUG(dbgs() << "\nPromoting ";
1103 Result.getNode()->dump(&DAG);
1105 WorklistRemover DeadNodes(*this);
1106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1108 deleteAndRecombine(N);
1109 AddToWorklist(Result.getNode());
1115 /// \brief Recursively delete a node which has no uses and any operands for
1116 /// which it is the only use.
1118 /// Note that this both deletes the nodes and removes them from the worklist.
1119 /// It also adds any nodes who have had a user deleted to the worklist as they
1120 /// may now have only one use and subject to other combines.
1121 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122 if (!N->use_empty())
1125 SmallSetVector<SDNode *, 16> Nodes;
1128 N = Nodes.pop_back_val();
1132 if (N->use_empty()) {
1133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134 Nodes.insert(N->getOperand(i).getNode());
1136 removeFromWorklist(N);
1141 } while (!Nodes.empty());
1145 //===----------------------------------------------------------------------===//
1146 // Main DAG Combiner implementation
1147 //===----------------------------------------------------------------------===//
1149 void DAGCombiner::Run(CombineLevel AtLevel) {
1150 // set the instance variables, so that the various visit routines may use it.
1152 LegalOperations = Level >= AfterLegalizeVectorOps;
1153 LegalTypes = Level >= AfterLegalizeTypes;
1155 // Add all the dag nodes to the worklist.
1156 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157 E = DAG.allnodes_end(); I != E; ++I)
1160 // Create a dummy node (which is not added to allnodes), that adds a reference
1161 // to the root node, preventing it from being deleted, and tracking any
1162 // changes of the root.
1163 HandleSDNode Dummy(DAG.getRoot());
1165 // while the worklist isn't empty, find a node and
1166 // try and combine it.
1167 while (!WorklistMap.empty()) {
1169 // The Worklist holds the SDNodes in order, but it may contain null entries.
1171 N = Worklist.pop_back_val();
1174 bool GoodWorklistEntry = WorklistMap.erase(N);
1175 (void)GoodWorklistEntry;
1176 assert(GoodWorklistEntry &&
1177 "Found a worklist entry without a corresponding map entry!");
1179 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1180 // N is deleted from the DAG, since they too may now be dead or may have a
1181 // reduced number of uses, allowing other xforms.
1182 if (recursivelyDeleteUnusedNodes(N))
1185 WorklistRemover DeadNodes(*this);
1187 // If this combine is running after legalizing the DAG, re-legalize any
1188 // nodes pulled off the worklist.
1189 if (Level == AfterLegalizeDAG) {
1190 SmallSetVector<SDNode *, 16> UpdatedNodes;
1191 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193 for (SDNode *LN : UpdatedNodes) {
1195 AddUsersToWorklist(LN);
1201 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203 // Add any operands of the new node which have not yet been combined to the
1204 // worklist as well. Because the worklist uniques things already, this
1205 // won't repeatedly process the same operand.
1206 CombinedNodes.insert(N);
1207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209 AddToWorklist(N->getOperand(i).getNode());
1211 SDValue RV = combine(N);
1218 // If we get back the same node we passed in, rather than a new node or
1219 // zero, we know that the node must have defined multiple values and
1220 // CombineTo was used. Since CombineTo takes care of the worklist
1221 // mechanics for us, we have no work to do in this case.
1222 if (RV.getNode() == N)
1225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227 "Node was deleted but visit returned new node!");
1229 DEBUG(dbgs() << " ... into: ";
1230 RV.getNode()->dump(&DAG));
1232 // Transfer debug value.
1233 DAG.TransferDbgValues(SDValue(N, 0), RV);
1234 if (N->getNumValues() == RV.getNode()->getNumValues())
1235 DAG.ReplaceAllUsesWith(N, RV.getNode());
1237 assert(N->getValueType(0) == RV.getValueType() &&
1238 N->getNumValues() == 1 && "Type mismatch");
1240 DAG.ReplaceAllUsesWith(N, &OpV);
1243 // Push the new node and any users onto the worklist
1244 AddToWorklist(RV.getNode());
1245 AddUsersToWorklist(RV.getNode());
1247 // Finally, if the node is now dead, remove it from the graph. The node
1248 // may not be dead if the replacement process recursively simplified to
1249 // something else needing this node. This will also take care of adding any
1250 // operands which have lost a user to the worklist.
1251 recursivelyDeleteUnusedNodes(N);
1254 // If the root changed (e.g. it was a dead load, update the root).
1255 DAG.setRoot(Dummy.getValue());
1256 DAG.RemoveDeadNodes();
1259 SDValue DAGCombiner::visit(SDNode *N) {
1260 switch (N->getOpcode()) {
1262 case ISD::TokenFactor: return visitTokenFactor(N);
1263 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1264 case ISD::ADD: return visitADD(N);
1265 case ISD::SUB: return visitSUB(N);
1266 case ISD::ADDC: return visitADDC(N);
1267 case ISD::SUBC: return visitSUBC(N);
1268 case ISD::ADDE: return visitADDE(N);
1269 case ISD::SUBE: return visitSUBE(N);
1270 case ISD::MUL: return visitMUL(N);
1271 case ISD::SDIV: return visitSDIV(N);
1272 case ISD::UDIV: return visitUDIV(N);
1273 case ISD::SREM: return visitSREM(N);
1274 case ISD::UREM: return visitUREM(N);
1275 case ISD::MULHU: return visitMULHU(N);
1276 case ISD::MULHS: return visitMULHS(N);
1277 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1278 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1279 case ISD::SMULO: return visitSMULO(N);
1280 case ISD::UMULO: return visitUMULO(N);
1281 case ISD::SDIVREM: return visitSDIVREM(N);
1282 case ISD::UDIVREM: return visitUDIVREM(N);
1283 case ISD::AND: return visitAND(N);
1284 case ISD::OR: return visitOR(N);
1285 case ISD::XOR: return visitXOR(N);
1286 case ISD::SHL: return visitSHL(N);
1287 case ISD::SRA: return visitSRA(N);
1288 case ISD::SRL: return visitSRL(N);
1290 case ISD::ROTL: return visitRotate(N);
1291 case ISD::CTLZ: return visitCTLZ(N);
1292 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1293 case ISD::CTTZ: return visitCTTZ(N);
1294 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1295 case ISD::CTPOP: return visitCTPOP(N);
1296 case ISD::SELECT: return visitSELECT(N);
1297 case ISD::VSELECT: return visitVSELECT(N);
1298 case ISD::SELECT_CC: return visitSELECT_CC(N);
1299 case ISD::SETCC: return visitSETCC(N);
1300 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1301 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1302 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1303 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1304 case ISD::TRUNCATE: return visitTRUNCATE(N);
1305 case ISD::BITCAST: return visitBITCAST(N);
1306 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1307 case ISD::FADD: return visitFADD(N);
1308 case ISD::FSUB: return visitFSUB(N);
1309 case ISD::FMUL: return visitFMUL(N);
1310 case ISD::FMA: return visitFMA(N);
1311 case ISD::FDIV: return visitFDIV(N);
1312 case ISD::FREM: return visitFREM(N);
1313 case ISD::FSQRT: return visitFSQRT(N);
1314 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1315 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1316 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1317 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1318 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1319 case ISD::FP_ROUND: return visitFP_ROUND(N);
1320 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1321 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1322 case ISD::FNEG: return visitFNEG(N);
1323 case ISD::FABS: return visitFABS(N);
1324 case ISD::FFLOOR: return visitFFLOOR(N);
1325 case ISD::FCEIL: return visitFCEIL(N);
1326 case ISD::FTRUNC: return visitFTRUNC(N);
1327 case ISD::BRCOND: return visitBRCOND(N);
1328 case ISD::BR_CC: return visitBR_CC(N);
1329 case ISD::LOAD: return visitLOAD(N);
1330 case ISD::STORE: return visitSTORE(N);
1331 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1332 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1334 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1335 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1336 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1337 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343 SDValue RV = visit(N);
1345 // If nothing happened, try a target-specific DAG combine.
1346 if (!RV.getNode()) {
1347 assert(N->getOpcode() != ISD::DELETED_NODE &&
1348 "Node was deleted but visit returned NULL!");
1350 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1353 // Expose the DAG combiner to the target combiner impls.
1354 TargetLowering::DAGCombinerInfo
1355 DagCombineInfo(DAG, Level, false, this);
1357 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1361 // If nothing happened still, try promoting the operation.
1362 if (!RV.getNode()) {
1363 switch (N->getOpcode()) {
1371 RV = PromoteIntBinOp(SDValue(N, 0));
1376 RV = PromoteIntShiftOp(SDValue(N, 0));
1378 case ISD::SIGN_EXTEND:
1379 case ISD::ZERO_EXTEND:
1380 case ISD::ANY_EXTEND:
1381 RV = PromoteExtend(SDValue(N, 0));
1384 if (PromoteLoad(SDValue(N, 0)))
1390 // If N is a commutative binary node, try commuting it to enable more
1392 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393 N->getNumValues() == 1) {
1394 SDValue N0 = N->getOperand(0);
1395 SDValue N1 = N->getOperand(1);
1397 // Constant operands are canonicalized to RHS.
1398 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399 SDValue Ops[] = {N1, N0};
1401 if (const BinaryWithFlagsSDNode *BinNode =
1402 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403 CSENode = DAG.getNodeIfExists(
1404 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405 BinNode->hasNoSignedWrap(), BinNode->isExact());
1407 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1410 return SDValue(CSENode, 0);
1417 /// Given a node, return its input chain if it has one, otherwise return a null
1419 static SDValue getInputChainForNode(SDNode *N) {
1420 if (unsigned NumOps = N->getNumOperands()) {
1421 if (N->getOperand(0).getValueType() == MVT::Other)
1422 return N->getOperand(0);
1423 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424 return N->getOperand(NumOps-1);
1425 for (unsigned i = 1; i < NumOps-1; ++i)
1426 if (N->getOperand(i).getValueType() == MVT::Other)
1427 return N->getOperand(i);
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433 // If N has two operands, where one has an input chain equal to the other,
1434 // the 'other' chain is redundant.
1435 if (N->getNumOperands() == 2) {
1436 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437 return N->getOperand(0);
1438 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439 return N->getOperand(1);
1442 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1443 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1444 SmallPtrSet<SDNode*, 16> SeenOps;
1445 bool Changed = false; // If we should replace this token factor.
1447 // Start out with this token factor.
1450 // Iterate through token factors. The TFs grows when new token factors are
1452 for (unsigned i = 0; i < TFs.size(); ++i) {
1453 SDNode *TF = TFs[i];
1455 // Check each of the operands.
1456 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457 SDValue Op = TF->getOperand(i);
1459 switch (Op.getOpcode()) {
1460 case ISD::EntryToken:
1461 // Entry tokens don't need to be added to the list. They are
1466 case ISD::TokenFactor:
1467 if (Op.hasOneUse() &&
1468 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469 // Queue up for processing.
1470 TFs.push_back(Op.getNode());
1471 // Clean up in case the token factor is removed.
1472 AddToWorklist(Op.getNode());
1479 // Only add if it isn't already in the list.
1480 if (SeenOps.insert(Op.getNode()))
1491 // If we've change things around then replace token factor.
1494 // The entry token is the only possible outcome.
1495 Result = DAG.getEntryNode();
1497 // New and improved token factor.
1498 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1501 // Don't add users to work list.
1502 return CombineTo(N, Result, false);
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510 WorklistRemover DeadNodes(*this);
1511 // Replacing results may cause a different MERGE_VALUES to suddenly
1512 // be CSE'd with N, and carry its uses with it. Iterate until no
1513 // uses remain, to ensure that the node can be safely deleted.
1514 // First add the users of this node to the work list so that they
1515 // can be tried again once they have new operands.
1516 AddUsersToWorklist(N);
1518 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520 } while (!N->use_empty());
1521 deleteAndRecombine(N);
1522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1525 SDValue DAGCombiner::visitADD(SDNode *N) {
1526 SDValue N0 = N->getOperand(0);
1527 SDValue N1 = N->getOperand(1);
1528 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1529 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1530 EVT VT = N0.getValueType();
1533 if (VT.isVector()) {
1534 SDValue FoldedVOp = SimplifyVBinOp(N);
1535 if (FoldedVOp.getNode()) return FoldedVOp;
1537 // fold (add x, 0) -> x, vector edition
1538 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1540 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1544 // fold (add x, undef) -> undef
1545 if (N0.getOpcode() == ISD::UNDEF)
1547 if (N1.getOpcode() == ISD::UNDEF)
1549 // fold (add c1, c2) -> c1+c2
1551 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1552 // canonicalize constant to RHS
1554 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1555 // fold (add x, 0) -> x
1556 if (N1C && N1C->isNullValue())
1558 // fold (add Sym, c) -> Sym+c
1559 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1560 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1561 GA->getOpcode() == ISD::GlobalAddress)
1562 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1564 (uint64_t)N1C->getSExtValue());
1565 // fold ((c1-A)+c2) -> (c1+c2)-A
1566 if (N1C && N0.getOpcode() == ISD::SUB)
1567 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1568 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1569 DAG.getConstant(N1C->getAPIntValue()+
1570 N0C->getAPIntValue(), VT),
1573 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1576 // fold ((0-A) + B) -> B-A
1577 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1578 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1579 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1580 // fold (A + (0-B)) -> A-B
1581 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1582 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1583 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1584 // fold (A+(B-A)) -> B
1585 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1586 return N1.getOperand(0);
1587 // fold ((B-A)+A) -> B
1588 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1589 return N0.getOperand(0);
1590 // fold (A+(B-(A+C))) to (B-C)
1591 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1592 N0 == N1.getOperand(1).getOperand(0))
1593 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1594 N1.getOperand(1).getOperand(1));
1595 // fold (A+(B-(C+A))) to (B-C)
1596 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1597 N0 == N1.getOperand(1).getOperand(1))
1598 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1599 N1.getOperand(1).getOperand(0));
1600 // fold (A+((B-A)+or-C)) to (B+or-C)
1601 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1602 N1.getOperand(0).getOpcode() == ISD::SUB &&
1603 N0 == N1.getOperand(0).getOperand(1))
1604 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1605 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1607 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1608 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1609 SDValue N00 = N0.getOperand(0);
1610 SDValue N01 = N0.getOperand(1);
1611 SDValue N10 = N1.getOperand(0);
1612 SDValue N11 = N1.getOperand(1);
1614 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1615 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1616 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1617 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1620 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1621 return SDValue(N, 0);
1623 // fold (a+b) -> (a|b) iff a and b share no bits.
1624 if (VT.isInteger() && !VT.isVector()) {
1625 APInt LHSZero, LHSOne;
1626 APInt RHSZero, RHSOne;
1627 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1629 if (LHSZero.getBoolValue()) {
1630 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1632 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1633 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1634 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1635 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1641 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1642 if (N1.getOpcode() == ISD::SHL &&
1643 N1.getOperand(0).getOpcode() == ISD::SUB)
1644 if (ConstantSDNode *C =
1645 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1646 if (C->getAPIntValue() == 0)
1647 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1648 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1649 N1.getOperand(0).getOperand(1),
1651 if (N0.getOpcode() == ISD::SHL &&
1652 N0.getOperand(0).getOpcode() == ISD::SUB)
1653 if (ConstantSDNode *C =
1654 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1655 if (C->getAPIntValue() == 0)
1656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1657 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1658 N0.getOperand(0).getOperand(1),
1661 if (N1.getOpcode() == ISD::AND) {
1662 SDValue AndOp0 = N1.getOperand(0);
1663 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1664 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1665 unsigned DestBits = VT.getScalarType().getSizeInBits();
1667 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1668 // and similar xforms where the inner op is either ~0 or 0.
1669 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1671 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1675 // add (sext i1), X -> sub X, (zext i1)
1676 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1677 N0.getOperand(0).getValueType() == MVT::i1 &&
1678 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1680 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1681 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1687 SDValue DAGCombiner::visitADDC(SDNode *N) {
1688 SDValue N0 = N->getOperand(0);
1689 SDValue N1 = N->getOperand(1);
1690 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1692 EVT VT = N0.getValueType();
1694 // If the flag result is dead, turn this into an ADD.
1695 if (!N->hasAnyUseOfValue(1))
1696 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1697 DAG.getNode(ISD::CARRY_FALSE,
1698 SDLoc(N), MVT::Glue));
1700 // canonicalize constant to RHS.
1702 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1704 // fold (addc x, 0) -> x + no carry out
1705 if (N1C && N1C->isNullValue())
1706 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1707 SDLoc(N), MVT::Glue));
1709 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1710 APInt LHSZero, LHSOne;
1711 APInt RHSZero, RHSOne;
1712 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1714 if (LHSZero.getBoolValue()) {
1715 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1717 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1718 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1719 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1720 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1721 DAG.getNode(ISD::CARRY_FALSE,
1722 SDLoc(N), MVT::Glue));
1728 SDValue DAGCombiner::visitADDE(SDNode *N) {
1729 SDValue N0 = N->getOperand(0);
1730 SDValue N1 = N->getOperand(1);
1731 SDValue CarryIn = N->getOperand(2);
1732 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1733 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735 // canonicalize constant to RHS
1737 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1740 // fold (adde x, y, false) -> (addc x, y)
1741 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1742 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1747 // Since it may not be valid to emit a fold to zero for vector initializers
1748 // check if we can before folding.
1749 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1751 bool LegalOperations, bool LegalTypes) {
1753 return DAG.getConstant(0, VT);
1754 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1755 return DAG.getConstant(0, VT);
1759 SDValue DAGCombiner::visitSUB(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1764 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1765 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1766 EVT VT = N0.getValueType();
1769 if (VT.isVector()) {
1770 SDValue FoldedVOp = SimplifyVBinOp(N);
1771 if (FoldedVOp.getNode()) return FoldedVOp;
1773 // fold (sub x, 0) -> x, vector edition
1774 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1778 // fold (sub x, x) -> 0
1779 // FIXME: Refactor this and xor and other similar operations together.
1781 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1782 // fold (sub c1, c2) -> c1-c2
1784 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1785 // fold (sub x, c) -> (add x, -c)
1787 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1788 DAG.getConstant(-N1C->getAPIntValue(), VT));
1789 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1790 if (N0C && N0C->isAllOnesValue())
1791 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1792 // fold A-(A-B) -> B
1793 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1794 return N1.getOperand(1);
1795 // fold (A+B)-A -> B
1796 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1797 return N0.getOperand(1);
1798 // fold (A+B)-B -> A
1799 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1800 return N0.getOperand(0);
1801 // fold C2-(A+C1) -> (C2-C1)-A
1802 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1803 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1805 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1808 // fold ((A+(B+or-C))-B) -> A+or-C
1809 if (N0.getOpcode() == ISD::ADD &&
1810 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1811 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1812 N0.getOperand(1).getOperand(0) == N1)
1813 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1814 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1815 // fold ((A+(C+B))-B) -> A+C
1816 if (N0.getOpcode() == ISD::ADD &&
1817 N0.getOperand(1).getOpcode() == ISD::ADD &&
1818 N0.getOperand(1).getOperand(1) == N1)
1819 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1820 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1821 // fold ((A-(B-C))-C) -> A-B
1822 if (N0.getOpcode() == ISD::SUB &&
1823 N0.getOperand(1).getOpcode() == ISD::SUB &&
1824 N0.getOperand(1).getOperand(1) == N1)
1825 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1826 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1828 // If either operand of a sub is undef, the result is undef
1829 if (N0.getOpcode() == ISD::UNDEF)
1831 if (N1.getOpcode() == ISD::UNDEF)
1834 // If the relocation model supports it, consider symbol offsets.
1835 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1836 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1837 // fold (sub Sym, c) -> Sym-c
1838 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1839 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1841 (uint64_t)N1C->getSExtValue());
1842 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1843 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1844 if (GA->getGlobal() == GB->getGlobal())
1845 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1852 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1857 EVT VT = N0.getValueType();
1859 // If the flag result is dead, turn this into an SUB.
1860 if (!N->hasAnyUseOfValue(1))
1861 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1862 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1865 // fold (subc x, x) -> 0 + no borrow
1867 return CombineTo(N, DAG.getConstant(0, VT),
1868 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1871 // fold (subc x, 0) -> x + no borrow
1872 if (N1C && N1C->isNullValue())
1873 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1876 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1877 if (N0C && N0C->isAllOnesValue())
1878 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1885 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 SDValue CarryIn = N->getOperand(2);
1890 // fold (sube x, y, false) -> (subc x, y)
1891 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1892 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1897 SDValue DAGCombiner::visitMUL(SDNode *N) {
1898 SDValue N0 = N->getOperand(0);
1899 SDValue N1 = N->getOperand(1);
1900 EVT VT = N0.getValueType();
1902 // fold (mul x, undef) -> 0
1903 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1904 return DAG.getConstant(0, VT);
1906 bool N0IsConst = false;
1907 bool N1IsConst = false;
1908 APInt ConstValue0, ConstValue1;
1910 if (VT.isVector()) {
1911 SDValue FoldedVOp = SimplifyVBinOp(N);
1912 if (FoldedVOp.getNode()) return FoldedVOp;
1914 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1915 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1917 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1918 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1920 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1921 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1925 // fold (mul c1, c2) -> c1*c2
1926 if (N0IsConst && N1IsConst)
1927 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1929 // canonicalize constant to RHS
1930 if (N0IsConst && !N1IsConst)
1931 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1932 // fold (mul x, 0) -> 0
1933 if (N1IsConst && ConstValue1 == 0)
1935 // We require a splat of the entire scalar bit width for non-contiguous
1938 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1939 // fold (mul x, 1) -> x
1940 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1942 // fold (mul x, -1) -> 0-x
1943 if (N1IsConst && ConstValue1.isAllOnesValue())
1944 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945 DAG.getConstant(0, VT), N0);
1946 // fold (mul x, (1 << c)) -> x << c
1947 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1948 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1949 DAG.getConstant(ConstValue1.logBase2(),
1950 getShiftAmountTy(N0.getValueType())));
1951 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1952 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1953 unsigned Log2Val = (-ConstValue1).logBase2();
1954 // FIXME: If the input is something that is easily negated (e.g. a
1955 // single-use add), we should put the negate there.
1956 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1957 DAG.getConstant(0, VT),
1958 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1959 DAG.getConstant(Log2Val,
1960 getShiftAmountTy(N0.getValueType()))));
1964 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1965 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1966 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1967 isa<ConstantSDNode>(N0.getOperand(1)))) {
1968 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1969 N1, N0.getOperand(1));
1970 AddToWorklist(C3.getNode());
1971 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1972 N0.getOperand(0), C3);
1975 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1978 SDValue Sh(nullptr,0), Y(nullptr,0);
1979 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1980 if (N0.getOpcode() == ISD::SHL &&
1981 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1982 isa<ConstantSDNode>(N0.getOperand(1))) &&
1983 N0.getNode()->hasOneUse()) {
1985 } else if (N1.getOpcode() == ISD::SHL &&
1986 isa<ConstantSDNode>(N1.getOperand(1)) &&
1987 N1.getNode()->hasOneUse()) {
1992 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1993 Sh.getOperand(0), Y);
1994 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1995 Mul, Sh.getOperand(1));
1999 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2000 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2001 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2002 isa<ConstantSDNode>(N0.getOperand(1))))
2003 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2004 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2005 N0.getOperand(0), N1),
2006 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2007 N0.getOperand(1), N1));
2010 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2017 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2018 SDValue N0 = N->getOperand(0);
2019 SDValue N1 = N->getOperand(1);
2020 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2021 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2022 EVT VT = N->getValueType(0);
2025 if (VT.isVector()) {
2026 SDValue FoldedVOp = SimplifyVBinOp(N);
2027 if (FoldedVOp.getNode()) return FoldedVOp;
2030 // fold (sdiv c1, c2) -> c1/c2
2031 if (N0C && N1C && !N1C->isNullValue())
2032 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2033 // fold (sdiv X, 1) -> X
2034 if (N1C && N1C->getAPIntValue() == 1LL)
2036 // fold (sdiv X, -1) -> 0-X
2037 if (N1C && N1C->isAllOnesValue())
2038 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2039 DAG.getConstant(0, VT), N0);
2040 // If we know the sign bits of both operands are zero, strength reduce to a
2041 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2042 if (!VT.isVector()) {
2043 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2044 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2048 // fold (sdiv X, pow2) -> simple ops after legalize
2049 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2050 (-N1C->getAPIntValue()).isPowerOf2())) {
2051 // If dividing by powers of two is cheap, then don't perform the following
2053 if (TLI.isPow2SDivCheap())
2056 // Target-specific implementation of sdiv x, pow2.
2057 SDValue Res = BuildSDIVPow2(N);
2061 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2063 // Splat the sign bit into the register
2065 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2066 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2067 getShiftAmountTy(N0.getValueType())));
2068 AddToWorklist(SGN.getNode());
2070 // Add (N0 < 0) ? abs2 - 1 : 0;
2072 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2073 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2074 getShiftAmountTy(SGN.getValueType())));
2075 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2076 AddToWorklist(SRL.getNode());
2077 AddToWorklist(ADD.getNode()); // Divide by pow2
2078 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2079 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2081 // If we're dividing by a positive value, we're done. Otherwise, we must
2082 // negate the result.
2083 if (N1C->getAPIntValue().isNonNegative())
2086 AddToWorklist(SRA.getNode());
2087 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2090 // if integer divide is expensive and we satisfy the requirements, emit an
2091 // alternate sequence.
2092 if (N1C && !TLI.isIntDivCheap()) {
2093 SDValue Op = BuildSDIV(N);
2094 if (Op.getNode()) return Op;
2098 if (N0.getOpcode() == ISD::UNDEF)
2099 return DAG.getConstant(0, VT);
2100 // X / undef -> undef
2101 if (N1.getOpcode() == ISD::UNDEF)
2107 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2108 SDValue N0 = N->getOperand(0);
2109 SDValue N1 = N->getOperand(1);
2110 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2111 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2112 EVT VT = N->getValueType(0);
2115 if (VT.isVector()) {
2116 SDValue FoldedVOp = SimplifyVBinOp(N);
2117 if (FoldedVOp.getNode()) return FoldedVOp;
2120 // fold (udiv c1, c2) -> c1/c2
2121 if (N0C && N1C && !N1C->isNullValue())
2122 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2123 // fold (udiv x, (1 << c)) -> x >>u c
2124 if (N1C && N1C->getAPIntValue().isPowerOf2())
2125 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2126 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2127 getShiftAmountTy(N0.getValueType())));
2128 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2129 if (N1.getOpcode() == ISD::SHL) {
2130 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2131 if (SHC->getAPIntValue().isPowerOf2()) {
2132 EVT ADDVT = N1.getOperand(1).getValueType();
2133 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2135 DAG.getConstant(SHC->getAPIntValue()
2138 AddToWorklist(Add.getNode());
2139 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2143 // fold (udiv x, c) -> alternate
2144 if (N1C && !TLI.isIntDivCheap()) {
2145 SDValue Op = BuildUDIV(N);
2146 if (Op.getNode()) return Op;
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X / undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2159 SDValue DAGCombiner::visitSREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
2162 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2163 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2164 EVT VT = N->getValueType(0);
2166 // fold (srem c1, c2) -> c1%c2
2167 if (N0C && N1C && !N1C->isNullValue())
2168 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2169 // If we know the sign bits of both operands are zero, strength reduce to a
2170 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2171 if (!VT.isVector()) {
2172 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2173 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2176 // If X/C can be simplified by the division-by-constant logic, lower
2177 // X%C to the equivalent of X-X/C*C.
2178 if (N1C && !N1C->isNullValue()) {
2179 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2180 AddToWorklist(Div.getNode());
2181 SDValue OptimizedDiv = combine(Div.getNode());
2182 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2183 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2185 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2186 AddToWorklist(Mul.getNode());
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::visitUREM(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 (urem c1, c2) -> c1%c2
2209 if (N0C && N1C && !N1C->isNullValue())
2210 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2211 // fold (urem x, pow2) -> (and x, pow2-1)
2212 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2213 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2214 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2215 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2216 if (N1.getOpcode() == ISD::SHL) {
2217 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2218 if (SHC->getAPIntValue().isPowerOf2()) {
2220 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2221 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2223 AddToWorklist(Add.getNode());
2224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2229 // If X/C can be simplified by the division-by-constant logic, lower
2230 // X%C to the equivalent of X-X/C*C.
2231 if (N1C && !N1C->isNullValue()) {
2232 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2233 AddToWorklist(Div.getNode());
2234 SDValue OptimizedDiv = combine(Div.getNode());
2235 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2236 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2238 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2239 AddToWorklist(Mul.getNode());
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, VT);
2247 // X % undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2254 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2258 EVT VT = N->getValueType(0);
2261 // fold (mulhs x, 0) -> 0
2262 if (N1C && N1C->isNullValue())
2264 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2265 if (N1C && N1C->getAPIntValue() == 1)
2266 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2267 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2268 getShiftAmountTy(N0.getValueType())));
2269 // fold (mulhs x, undef) -> 0
2270 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2271 return DAG.getConstant(0, VT);
2273 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2275 if (VT.isSimple() && !VT.isVector()) {
2276 MVT Simple = VT.getSimpleVT();
2277 unsigned SimpleSize = Simple.getSizeInBits();
2278 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2279 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2280 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2281 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2282 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2283 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2284 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2285 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2292 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2293 SDValue N0 = N->getOperand(0);
2294 SDValue N1 = N->getOperand(1);
2295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2296 EVT VT = N->getValueType(0);
2299 // fold (mulhu x, 0) -> 0
2300 if (N1C && N1C->isNullValue())
2302 // fold (mulhu x, 1) -> 0
2303 if (N1C && N1C->getAPIntValue() == 1)
2304 return DAG.getConstant(0, N0.getValueType());
2305 // fold (mulhu x, undef) -> 0
2306 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2307 return DAG.getConstant(0, VT);
2309 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2311 if (VT.isSimple() && !VT.isVector()) {
2312 MVT Simple = VT.getSimpleVT();
2313 unsigned SimpleSize = Simple.getSizeInBits();
2314 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2315 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2316 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2317 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2318 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2319 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2320 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2321 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2329 /// give the opcodes for the two computations that are being performed. Return
2330 /// true if a simplification was made.
2331 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2333 // If the high half is not needed, just compute the low half.
2334 bool HiExists = N->hasAnyUseOfValue(1);
2336 (!LegalOperations ||
2337 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2338 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2339 return CombineTo(N, Res, Res);
2342 // If the low half is not needed, just compute the high half.
2343 bool LoExists = N->hasAnyUseOfValue(0);
2345 (!LegalOperations ||
2346 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2347 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2348 return CombineTo(N, Res, Res);
2351 // If both halves are used, return as it is.
2352 if (LoExists && HiExists)
2355 // If the two computed results can be simplified separately, separate them.
2357 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2358 AddToWorklist(Lo.getNode());
2359 SDValue LoOpt = combine(Lo.getNode());
2360 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2361 (!LegalOperations ||
2362 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2363 return CombineTo(N, LoOpt, LoOpt);
2367 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2368 AddToWorklist(Hi.getNode());
2369 SDValue HiOpt = combine(Hi.getNode());
2370 if (HiOpt.getNode() && HiOpt != Hi &&
2371 (!LegalOperations ||
2372 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2373 return CombineTo(N, HiOpt, HiOpt);
2379 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2380 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2381 if (Res.getNode()) return Res;
2383 EVT VT = N->getValueType(0);
2386 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2388 if (VT.isSimple() && !VT.isVector()) {
2389 MVT Simple = VT.getSimpleVT();
2390 unsigned SimpleSize = Simple.getSizeInBits();
2391 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2392 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2393 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2394 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2395 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2396 // Compute the high part as N1.
2397 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2398 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2399 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2400 // Compute the low part as N0.
2401 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2402 return CombineTo(N, Lo, Hi);
2409 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2411 if (Res.getNode()) return Res;
2413 EVT VT = N->getValueType(0);
2416 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2418 if (VT.isSimple() && !VT.isVector()) {
2419 MVT Simple = VT.getSimpleVT();
2420 unsigned SimpleSize = Simple.getSizeInBits();
2421 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2424 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2425 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2426 // Compute the high part as N1.
2427 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2428 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2429 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2430 // Compute the low part as N0.
2431 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2432 return CombineTo(N, Lo, Hi);
2439 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2440 // (smulo x, 2) -> (saddo x, x)
2441 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2442 if (C2->getAPIntValue() == 2)
2443 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2444 N->getOperand(0), N->getOperand(0));
2449 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2450 // (umulo x, 2) -> (uaddo x, x)
2451 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2452 if (C2->getAPIntValue() == 2)
2453 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2454 N->getOperand(0), N->getOperand(0));
2459 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2460 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2461 if (Res.getNode()) return Res;
2466 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2467 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2468 if (Res.getNode()) return Res;
2473 /// If this is a binary operator with two operands of the same opcode, try to
2475 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2476 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2477 EVT VT = N0.getValueType();
2478 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2480 // Bail early if none of these transforms apply.
2481 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2483 // For each of OP in AND/OR/XOR:
2484 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2485 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2486 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2487 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2489 // do not sink logical op inside of a vector extend, since it may combine
2491 EVT Op0VT = N0.getOperand(0).getValueType();
2492 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2493 N0.getOpcode() == ISD::SIGN_EXTEND ||
2494 // Avoid infinite looping with PromoteIntBinOp.
2495 (N0.getOpcode() == ISD::ANY_EXTEND &&
2496 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2497 (N0.getOpcode() == ISD::TRUNCATE &&
2498 (!TLI.isZExtFree(VT, Op0VT) ||
2499 !TLI.isTruncateFree(Op0VT, VT)) &&
2500 TLI.isTypeLegal(Op0VT))) &&
2502 Op0VT == N1.getOperand(0).getValueType() &&
2503 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2504 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2505 N0.getOperand(0).getValueType(),
2506 N0.getOperand(0), N1.getOperand(0));
2507 AddToWorklist(ORNode.getNode());
2508 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2511 // For each of OP in SHL/SRL/SRA/AND...
2512 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2513 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2514 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2515 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2516 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2517 N0.getOperand(1) == N1.getOperand(1)) {
2518 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2519 N0.getOperand(0).getValueType(),
2520 N0.getOperand(0), N1.getOperand(0));
2521 AddToWorklist(ORNode.getNode());
2522 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2523 ORNode, N0.getOperand(1));
2526 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2527 // Only perform this optimization after type legalization and before
2528 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2529 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2530 // we don't want to undo this promotion.
2531 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2533 if ((N0.getOpcode() == ISD::BITCAST ||
2534 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2535 Level == AfterLegalizeTypes) {
2536 SDValue In0 = N0.getOperand(0);
2537 SDValue In1 = N1.getOperand(0);
2538 EVT In0Ty = In0.getValueType();
2539 EVT In1Ty = In1.getValueType();
2541 // If both incoming values are integers, and the original types are the
2543 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2544 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2545 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2546 AddToWorklist(Op.getNode());
2551 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2552 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2553 // If both shuffles use the same mask, and both shuffle within a single
2554 // vector, then it is worthwhile to move the swizzle after the operation.
2555 // The type-legalizer generates this pattern when loading illegal
2556 // vector types from memory. In many cases this allows additional shuffle
2558 // There are other cases where moving the shuffle after the xor/and/or
2559 // is profitable even if shuffles don't perform a swizzle.
2560 // If both shuffles use the same mask, and both shuffles have the same first
2561 // or second operand, then it might still be profitable to move the shuffle
2562 // after the xor/and/or operation.
2563 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2564 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2565 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2567 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2568 "Inputs to shuffles are not the same type");
2570 // Check that both shuffles use the same mask. The masks are known to be of
2571 // the same length because the result vector type is the same.
2572 // Check also that shuffles have only one use to avoid introducing extra
2574 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2575 SVN0->getMask().equals(SVN1->getMask())) {
2576 SDValue ShOp = N0->getOperand(1);
2578 // Don't try to fold this node if it requires introducing a
2579 // build vector of all zeros that might be illegal at this stage.
2580 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2582 ShOp = DAG.getConstant(0, VT);
2587 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2588 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2589 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2590 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2591 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2592 N0->getOperand(0), N1->getOperand(0));
2593 AddToWorklist(NewNode.getNode());
2594 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2595 &SVN0->getMask()[0]);
2598 // Don't try to fold this node if it requires introducing a
2599 // build vector of all zeros that might be illegal at this stage.
2600 ShOp = N0->getOperand(0);
2601 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2603 ShOp = DAG.getConstant(0, VT);
2608 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2609 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2610 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2611 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2612 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2613 N0->getOperand(1), N1->getOperand(1));
2614 AddToWorklist(NewNode.getNode());
2615 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2616 &SVN0->getMask()[0]);
2624 SDValue DAGCombiner::visitAND(SDNode *N) {
2625 SDValue N0 = N->getOperand(0);
2626 SDValue N1 = N->getOperand(1);
2627 SDValue LL, LR, RL, RR, CC0, CC1;
2628 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2629 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2630 EVT VT = N1.getValueType();
2631 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2634 if (VT.isVector()) {
2635 SDValue FoldedVOp = SimplifyVBinOp(N);
2636 if (FoldedVOp.getNode()) return FoldedVOp;
2638 // fold (and x, 0) -> 0, vector edition
2639 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2640 // do not return N0, because undef node may exist in N0
2641 return DAG.getConstant(
2642 APInt::getNullValue(
2643 N0.getValueType().getScalarType().getSizeInBits()),
2645 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2646 // do not return N1, because undef node may exist in N1
2647 return DAG.getConstant(
2648 APInt::getNullValue(
2649 N1.getValueType().getScalarType().getSizeInBits()),
2652 // fold (and x, -1) -> x, vector edition
2653 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2655 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2659 // fold (and x, undef) -> 0
2660 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2661 return DAG.getConstant(0, VT);
2662 // fold (and c1, c2) -> c1&c2
2664 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2665 // canonicalize constant to RHS
2667 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2668 // fold (and x, -1) -> x
2669 if (N1C && N1C->isAllOnesValue())
2671 // if (and x, c) is known to be zero, return 0
2672 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2673 APInt::getAllOnesValue(BitWidth)))
2674 return DAG.getConstant(0, VT);
2676 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2679 // fold (and (or x, C), D) -> D if (C & D) == D
2680 if (N1C && N0.getOpcode() == ISD::OR)
2681 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2682 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2684 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2685 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2686 SDValue N0Op0 = N0.getOperand(0);
2687 APInt Mask = ~N1C->getAPIntValue();
2688 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2689 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2690 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2691 N0.getValueType(), N0Op0);
2693 // Replace uses of the AND with uses of the Zero extend node.
2696 // We actually want to replace all uses of the any_extend with the
2697 // zero_extend, to avoid duplicating things. This will later cause this
2698 // AND to be folded.
2699 CombineTo(N0.getNode(), Zext);
2700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2703 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2704 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2705 // already be zero by virtue of the width of the base type of the load.
2707 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2709 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2710 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2711 N0.getOpcode() == ISD::LOAD) {
2712 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2713 N0 : N0.getOperand(0) );
2715 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2716 // This can be a pure constant or a vector splat, in which case we treat the
2717 // vector as a scalar and use the splat value.
2718 APInt Constant = APInt::getNullValue(1);
2719 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2720 Constant = C->getAPIntValue();
2721 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2722 APInt SplatValue, SplatUndef;
2723 unsigned SplatBitSize;
2725 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2726 SplatBitSize, HasAnyUndefs);
2728 // Undef bits can contribute to a possible optimisation if set, so
2730 SplatValue |= SplatUndef;
2732 // The splat value may be something like "0x00FFFFFF", which means 0 for
2733 // the first vector value and FF for the rest, repeating. We need a mask
2734 // that will apply equally to all members of the vector, so AND all the
2735 // lanes of the constant together.
2736 EVT VT = Vector->getValueType(0);
2737 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2739 // If the splat value has been compressed to a bitlength lower
2740 // than the size of the vector lane, we need to re-expand it to
2742 if (BitWidth > SplatBitSize)
2743 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2744 SplatBitSize < BitWidth;
2745 SplatBitSize = SplatBitSize * 2)
2746 SplatValue |= SplatValue.shl(SplatBitSize);
2748 Constant = APInt::getAllOnesValue(BitWidth);
2749 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2750 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2754 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2755 // actually legal and isn't going to get expanded, else this is a false
2757 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2758 Load->getMemoryVT());
2760 // Resize the constant to the same size as the original memory access before
2761 // extension. If it is still the AllOnesValue then this AND is completely
2764 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2767 switch (Load->getExtensionType()) {
2768 default: B = false; break;
2769 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2771 case ISD::NON_EXTLOAD: B = true; break;
2774 if (B && Constant.isAllOnesValue()) {
2775 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2776 // preserve semantics once we get rid of the AND.
2777 SDValue NewLoad(Load, 0);
2778 if (Load->getExtensionType() == ISD::EXTLOAD) {
2779 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2780 Load->getValueType(0), SDLoc(Load),
2781 Load->getChain(), Load->getBasePtr(),
2782 Load->getOffset(), Load->getMemoryVT(),
2783 Load->getMemOperand());
2784 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2785 if (Load->getNumValues() == 3) {
2786 // PRE/POST_INC loads have 3 values.
2787 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2788 NewLoad.getValue(2) };
2789 CombineTo(Load, To, 3, true);
2791 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2795 // Fold the AND away, taking care not to fold to the old load node if we
2797 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2802 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2803 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2804 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2805 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2807 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2808 LL.getValueType().isInteger()) {
2809 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2810 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2811 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2812 LR.getValueType(), LL, RL);
2813 AddToWorklist(ORNode.getNode());
2814 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2816 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2817 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2818 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2819 LR.getValueType(), LL, RL);
2820 AddToWorklist(ANDNode.getNode());
2821 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2823 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2824 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2825 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2826 LR.getValueType(), LL, RL);
2827 AddToWorklist(ORNode.getNode());
2828 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2831 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2832 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2833 Op0 == Op1 && LL.getValueType().isInteger() &&
2834 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2835 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2836 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2837 cast<ConstantSDNode>(RR)->isNullValue()))) {
2838 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2839 LL, DAG.getConstant(1, LL.getValueType()));
2840 AddToWorklist(ADDNode.getNode());
2841 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2842 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2844 // canonicalize equivalent to ll == rl
2845 if (LL == RR && LR == RL) {
2846 Op1 = ISD::getSetCCSwappedOperands(Op1);
2849 if (LL == RL && LR == RR) {
2850 bool isInteger = LL.getValueType().isInteger();
2851 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2852 if (Result != ISD::SETCC_INVALID &&
2853 (!LegalOperations ||
2854 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2855 TLI.isOperationLegal(ISD::SETCC,
2856 getSetCCResultType(N0.getSimpleValueType())))))
2857 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2862 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2863 if (N0.getOpcode() == N1.getOpcode()) {
2864 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2865 if (Tmp.getNode()) return Tmp;
2868 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2869 // fold (and (sra)) -> (and (srl)) when possible.
2870 if (!VT.isVector() &&
2871 SimplifyDemandedBits(SDValue(N, 0)))
2872 return SDValue(N, 0);
2874 // fold (zext_inreg (extload x)) -> (zextload x)
2875 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2876 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2877 EVT MemVT = LN0->getMemoryVT();
2878 // If we zero all the possible extended bits, then we can turn this into
2879 // a zextload if we are running before legalize or the operation is legal.
2880 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2881 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2882 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2883 ((!LegalOperations && !LN0->isVolatile()) ||
2884 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2885 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2886 LN0->getChain(), LN0->getBasePtr(),
2887 MemVT, LN0->getMemOperand());
2889 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2893 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2894 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2897 EVT MemVT = LN0->getMemoryVT();
2898 // If we zero all the possible extended bits, then we can turn this into
2899 // a zextload if we are running before legalize or the operation is legal.
2900 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2901 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2902 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2903 ((!LegalOperations && !LN0->isVolatile()) ||
2904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2905 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2906 LN0->getChain(), LN0->getBasePtr(),
2907 MemVT, LN0->getMemOperand());
2909 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2914 // fold (and (load x), 255) -> (zextload x, i8)
2915 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2916 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2917 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2918 (N0.getOpcode() == ISD::ANY_EXTEND &&
2919 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2920 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2921 LoadSDNode *LN0 = HasAnyExt
2922 ? cast<LoadSDNode>(N0.getOperand(0))
2923 : cast<LoadSDNode>(N0);
2924 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2925 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2926 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2927 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2928 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2929 EVT LoadedVT = LN0->getMemoryVT();
2931 if (ExtVT == LoadedVT &&
2932 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2933 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2936 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2937 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2938 LN0->getMemOperand());
2940 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2944 // Do not change the width of a volatile load.
2945 // Do not generate loads of non-round integer types since these can
2946 // be expensive (and would be wrong if the type is not byte sized).
2947 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2948 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2949 EVT PtrType = LN0->getOperand(1).getValueType();
2951 unsigned Alignment = LN0->getAlignment();
2952 SDValue NewPtr = LN0->getBasePtr();
2954 // For big endian targets, we need to add an offset to the pointer
2955 // to load the correct bytes. For little endian systems, we merely
2956 // need to read fewer bytes from the same pointer.
2957 if (TLI.isBigEndian()) {
2958 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2959 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2960 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2961 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2962 NewPtr, DAG.getConstant(PtrOff, PtrType));
2963 Alignment = MinAlign(Alignment, PtrOff);
2966 AddToWorklist(NewPtr.getNode());
2968 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2970 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971 LN0->getChain(), NewPtr,
2972 LN0->getPointerInfo(),
2973 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2974 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2976 CombineTo(LN0, Load, Load.getValue(1));
2977 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2983 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2984 VT.getSizeInBits() <= 64) {
2985 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2986 APInt ADDC = ADDI->getAPIntValue();
2987 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2988 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2989 // immediate for an add, but it is legal if its top c2 bits are set,
2990 // transform the ADD so the immediate doesn't need to be materialized
2992 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2993 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2994 SRLI->getZExtValue());
2995 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2997 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2999 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3000 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3001 CombineTo(N0.getNode(), NewAdd);
3002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3010 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3011 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3012 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3013 N0.getOperand(1), false);
3014 if (BSwap.getNode())
3021 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3022 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3023 bool DemandHighBits) {
3024 if (!LegalOperations)
3027 EVT VT = N->getValueType(0);
3028 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3030 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3033 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3034 bool LookPassAnd0 = false;
3035 bool LookPassAnd1 = false;
3036 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3038 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3040 if (N0.getOpcode() == ISD::AND) {
3041 if (!N0.getNode()->hasOneUse())
3043 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3044 if (!N01C || N01C->getZExtValue() != 0xFF00)
3046 N0 = N0.getOperand(0);
3047 LookPassAnd0 = true;
3050 if (N1.getOpcode() == ISD::AND) {
3051 if (!N1.getNode()->hasOneUse())
3053 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3054 if (!N11C || N11C->getZExtValue() != 0xFF)
3056 N1 = N1.getOperand(0);
3057 LookPassAnd1 = true;
3060 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3062 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3064 if (!N0.getNode()->hasOneUse() ||
3065 !N1.getNode()->hasOneUse())
3068 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3069 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3072 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3075 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3076 SDValue N00 = N0->getOperand(0);
3077 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3078 if (!N00.getNode()->hasOneUse())
3080 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3081 if (!N001C || N001C->getZExtValue() != 0xFF)
3083 N00 = N00.getOperand(0);
3084 LookPassAnd0 = true;
3087 SDValue N10 = N1->getOperand(0);
3088 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3089 if (!N10.getNode()->hasOneUse())
3091 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3092 if (!N101C || N101C->getZExtValue() != 0xFF00)
3094 N10 = N10.getOperand(0);
3095 LookPassAnd1 = true;
3101 // Make sure everything beyond the low halfword gets set to zero since the SRL
3102 // 16 will clear the top bits.
3103 unsigned OpSizeInBits = VT.getSizeInBits();
3104 if (DemandHighBits && OpSizeInBits > 16) {
3105 // If the left-shift isn't masked out then the only way this is a bswap is
3106 // if all bits beyond the low 8 are 0. In that case the entire pattern
3107 // reduces to a left shift anyway: leave it for other parts of the combiner.
3111 // However, if the right shift isn't masked out then it might be because
3112 // it's not needed. See if we can spot that too.
3113 if (!LookPassAnd1 &&
3114 !DAG.MaskedValueIsZero(
3115 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3119 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3120 if (OpSizeInBits > 16)
3121 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3122 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3126 /// Return true if the specified node is an element that makes up a 32-bit
3127 /// packed halfword byteswap.
3128 /// ((x & 0x000000ff) << 8) |
3129 /// ((x & 0x0000ff00) >> 8) |
3130 /// ((x & 0x00ff0000) << 8) |
3131 /// ((x & 0xff000000) >> 8)
3132 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3133 if (!N.getNode()->hasOneUse())
3136 unsigned Opc = N.getOpcode();
3137 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3145 switch (N1C->getZExtValue()) {
3148 case 0xFF: Num = 0; break;
3149 case 0xFF00: Num = 1; break;
3150 case 0xFF0000: Num = 2; break;
3151 case 0xFF000000: Num = 3; break;
3154 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3155 SDValue N0 = N.getOperand(0);
3156 if (Opc == ISD::AND) {
3157 if (Num == 0 || Num == 2) {
3159 // (x >> 8) & 0xff0000
3160 if (N0.getOpcode() != ISD::SRL)
3162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163 if (!C || C->getZExtValue() != 8)
3166 // (x << 8) & 0xff00
3167 // (x << 8) & 0xff000000
3168 if (N0.getOpcode() != ISD::SHL)
3170 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3171 if (!C || C->getZExtValue() != 8)
3174 } else if (Opc == ISD::SHL) {
3176 // (x & 0xff0000) << 8
3177 if (Num != 0 && Num != 2)
3179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3180 if (!C || C->getZExtValue() != 8)
3182 } else { // Opc == ISD::SRL
3183 // (x & 0xff00) >> 8
3184 // (x & 0xff000000) >> 8
3185 if (Num != 1 && Num != 3)
3187 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3188 if (!C || C->getZExtValue() != 8)
3195 Parts[Num] = N0.getOperand(0).getNode();
3199 /// Match a 32-bit packed halfword bswap. That is
3200 /// ((x & 0x000000ff) << 8) |
3201 /// ((x & 0x0000ff00) >> 8) |
3202 /// ((x & 0x00ff0000) << 8) |
3203 /// ((x & 0xff000000) >> 8)
3204 /// => (rotl (bswap x), 16)
3205 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3206 if (!LegalOperations)
3209 EVT VT = N->getValueType(0);
3212 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3215 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3217 // (or (or (and), (and)), (or (and), (and)))
3218 // (or (or (or (and), (and)), (and)), (and))
3219 if (N0.getOpcode() != ISD::OR)
3221 SDValue N00 = N0.getOperand(0);
3222 SDValue N01 = N0.getOperand(1);
3224 if (N1.getOpcode() == ISD::OR &&
3225 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3226 // (or (or (and), (and)), (or (and), (and)))
3227 SDValue N000 = N00.getOperand(0);
3228 if (!isBSwapHWordElement(N000, Parts))
3231 SDValue N001 = N00.getOperand(1);
3232 if (!isBSwapHWordElement(N001, Parts))
3234 SDValue N010 = N01.getOperand(0);
3235 if (!isBSwapHWordElement(N010, Parts))
3237 SDValue N011 = N01.getOperand(1);
3238 if (!isBSwapHWordElement(N011, Parts))
3241 // (or (or (or (and), (and)), (and)), (and))
3242 if (!isBSwapHWordElement(N1, Parts))
3244 if (!isBSwapHWordElement(N01, Parts))
3246 if (N00.getOpcode() != ISD::OR)
3248 SDValue N000 = N00.getOperand(0);
3249 if (!isBSwapHWordElement(N000, Parts))
3251 SDValue N001 = N00.getOperand(1);
3252 if (!isBSwapHWordElement(N001, Parts))
3256 // Make sure the parts are all coming from the same node.
3257 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3260 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3261 SDValue(Parts[0],0));
3263 // Result of the bswap should be rotated by 16. If it's not legal, then
3264 // do (x << 16) | (x >> 16).
3265 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3266 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3267 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3268 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3269 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3270 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3271 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3272 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3275 SDValue DAGCombiner::visitOR(SDNode *N) {
3276 SDValue N0 = N->getOperand(0);
3277 SDValue N1 = N->getOperand(1);
3278 SDValue LL, LR, RL, RR, CC0, CC1;
3279 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3280 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3281 EVT VT = N1.getValueType();
3284 if (VT.isVector()) {
3285 SDValue FoldedVOp = SimplifyVBinOp(N);
3286 if (FoldedVOp.getNode()) return FoldedVOp;
3288 // fold (or x, 0) -> x, vector edition
3289 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3291 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3294 // fold (or x, -1) -> -1, vector edition
3295 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3296 // do not return N0, because undef node may exist in N0
3297 return DAG.getConstant(
3298 APInt::getAllOnesValue(
3299 N0.getValueType().getScalarType().getSizeInBits()),
3301 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3302 // do not return N1, because undef node may exist in N1
3303 return DAG.getConstant(
3304 APInt::getAllOnesValue(
3305 N1.getValueType().getScalarType().getSizeInBits()),
3308 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3309 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3310 // Do this only if the resulting shuffle is legal.
3311 if (isa<ShuffleVectorSDNode>(N0) &&
3312 isa<ShuffleVectorSDNode>(N1) &&
3313 // Avoid folding a node with illegal type.
3314 TLI.isTypeLegal(VT) &&
3315 N0->getOperand(1) == N1->getOperand(1) &&
3316 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3317 bool CanFold = true;
3318 unsigned NumElts = VT.getVectorNumElements();
3319 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3320 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3321 // We construct two shuffle masks:
3322 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3323 // and N1 as the second operand.
3324 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3325 // and N0 as the second operand.
3326 // We do this because OR is commutable and therefore there might be
3327 // two ways to fold this node into a shuffle.
3328 SmallVector<int,4> Mask1;
3329 SmallVector<int,4> Mask2;
3331 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3332 int M0 = SV0->getMaskElt(i);
3333 int M1 = SV1->getMaskElt(i);
3335 // Both shuffle indexes are undef. Propagate Undef.
3336 if (M0 < 0 && M1 < 0) {
3337 Mask1.push_back(M0);
3338 Mask2.push_back(M0);
3342 if (M0 < 0 || M1 < 0 ||
3343 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3344 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3349 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3350 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3354 // Fold this sequence only if the resulting shuffle is 'legal'.
3355 if (TLI.isShuffleMaskLegal(Mask1, VT))
3356 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3357 N1->getOperand(0), &Mask1[0]);
3358 if (TLI.isShuffleMaskLegal(Mask2, VT))
3359 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3360 N0->getOperand(0), &Mask2[0]);
3365 // fold (or x, undef) -> -1
3366 if (!LegalOperations &&
3367 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3368 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3369 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3371 // fold (or c1, c2) -> c1|c2
3373 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3374 // canonicalize constant to RHS
3376 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3377 // fold (or x, 0) -> x
3378 if (N1C && N1C->isNullValue())
3380 // fold (or x, -1) -> -1
3381 if (N1C && N1C->isAllOnesValue())
3383 // fold (or x, c) -> c iff (x & ~c) == 0
3384 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3387 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3388 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3389 if (BSwap.getNode())
3391 BSwap = MatchBSwapHWordLow(N, N0, N1);
3392 if (BSwap.getNode())
3396 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3399 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3400 // iff (c1 & c2) == 0.
3401 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3402 isa<ConstantSDNode>(N0.getOperand(1))) {
3403 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3404 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3405 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3408 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3409 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3410 N0.getOperand(0), N1), COR);
3413 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3414 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3415 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3416 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3418 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3419 LL.getValueType().isInteger()) {
3420 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3421 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3422 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3423 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3424 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3425 LR.getValueType(), LL, RL);
3426 AddToWorklist(ORNode.getNode());
3427 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3429 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3430 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3431 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3432 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3433 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3434 LR.getValueType(), LL, RL);
3435 AddToWorklist(ANDNode.getNode());
3436 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3439 // canonicalize equivalent to ll == rl
3440 if (LL == RR && LR == RL) {
3441 Op1 = ISD::getSetCCSwappedOperands(Op1);
3444 if (LL == RL && LR == RR) {
3445 bool isInteger = LL.getValueType().isInteger();
3446 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3447 if (Result != ISD::SETCC_INVALID &&
3448 (!LegalOperations ||
3449 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3450 TLI.isOperationLegal(ISD::SETCC,
3451 getSetCCResultType(N0.getValueType())))))
3452 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3457 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3458 if (N0.getOpcode() == N1.getOpcode()) {
3459 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3460 if (Tmp.getNode()) return Tmp;
3463 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3464 if (N0.getOpcode() == ISD::AND &&
3465 N1.getOpcode() == ISD::AND &&
3466 N0.getOperand(1).getOpcode() == ISD::Constant &&
3467 N1.getOperand(1).getOpcode() == ISD::Constant &&
3468 // Don't increase # computations.
3469 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3470 // We can only do this xform if we know that bits from X that are set in C2
3471 // but not in C1 are already zero. Likewise for Y.
3472 const APInt &LHSMask =
3473 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3474 const APInt &RHSMask =
3475 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3477 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3478 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3479 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3480 N0.getOperand(0), N1.getOperand(0));
3481 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3482 DAG.getConstant(LHSMask | RHSMask, VT));
3486 // See if this is some rotate idiom.
3487 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3488 return SDValue(Rot, 0);
3490 // Simplify the operands using demanded-bits information.
3491 if (!VT.isVector() &&
3492 SimplifyDemandedBits(SDValue(N, 0)))
3493 return SDValue(N, 0);
3498 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3499 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3500 if (Op.getOpcode() == ISD::AND) {
3501 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3502 Mask = Op.getOperand(1);
3503 Op = Op.getOperand(0);
3509 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3517 // Return true if we can prove that, whenever Neg and Pos are both in the
3518 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3519 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3521 // (or (shift1 X, Neg), (shift2 X, Pos))
3523 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3524 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3525 // to consider shift amounts with defined behavior.
3526 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3527 // If OpSize is a power of 2 then:
3529 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3530 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3532 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3533 // for the stronger condition:
3535 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3537 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3538 // we can just replace Neg with Neg' for the rest of the function.
3540 // In other cases we check for the even stronger condition:
3542 // Neg == OpSize - Pos [B]
3544 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3545 // behavior if Pos == 0 (and consequently Neg == OpSize).
3547 // We could actually use [A] whenever OpSize is a power of 2, but the
3548 // only extra cases that it would match are those uninteresting ones
3549 // where Neg and Pos are never in range at the same time. E.g. for
3550 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3551 // as well as (sub 32, Pos), but:
3553 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3555 // always invokes undefined behavior for 32-bit X.
3557 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3558 unsigned MaskLoBits = 0;
3559 if (Neg.getOpcode() == ISD::AND &&
3560 isPowerOf2_64(OpSize) &&
3561 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3562 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3563 Neg = Neg.getOperand(0);
3564 MaskLoBits = Log2_64(OpSize);
3567 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3568 if (Neg.getOpcode() != ISD::SUB)
3570 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3573 SDValue NegOp1 = Neg.getOperand(1);
3575 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3576 // Pos'. The truncation is redundant for the purpose of the equality.
3578 Pos.getOpcode() == ISD::AND &&
3579 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3580 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3581 Pos = Pos.getOperand(0);
3583 // The condition we need is now:
3585 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3587 // If NegOp1 == Pos then we need:
3589 // OpSize & Mask == NegC & Mask
3591 // (because "x & Mask" is a truncation and distributes through subtraction).
3594 Width = NegC->getAPIntValue();
3595 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3596 // Then the condition we want to prove becomes:
3598 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3600 // which, again because "x & Mask" is a truncation, becomes:
3602 // NegC & Mask == (OpSize - PosC) & Mask
3603 // OpSize & Mask == (NegC + PosC) & Mask
3604 else if (Pos.getOpcode() == ISD::ADD &&
3605 Pos.getOperand(0) == NegOp1 &&
3606 Pos.getOperand(1).getOpcode() == ISD::Constant)
3607 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3608 NegC->getAPIntValue());
3612 // Now we just need to check that OpSize & Mask == Width & Mask.
3614 // Opsize & Mask is 0 since Mask is Opsize - 1.
3615 return Width.getLoBits(MaskLoBits) == 0;
3616 return Width == OpSize;
3619 // A subroutine of MatchRotate used once we have found an OR of two opposite
3620 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3621 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3622 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3623 // Neg with outer conversions stripped away.
3624 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3625 SDValue Neg, SDValue InnerPos,
3626 SDValue InnerNeg, unsigned PosOpcode,
3627 unsigned NegOpcode, SDLoc DL) {
3628 // fold (or (shl x, (*ext y)),
3629 // (srl x, (*ext (sub 32, y)))) ->
3630 // (rotl x, y) or (rotr x, (sub 32, y))
3632 // fold (or (shl x, (*ext (sub 32, y))),
3633 // (srl x, (*ext y))) ->
3634 // (rotr x, y) or (rotl x, (sub 32, y))
3635 EVT VT = Shifted.getValueType();
3636 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3637 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3638 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3639 HasPos ? Pos : Neg).getNode();
3645 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3646 // idioms for rotate, and if the target supports rotation instructions, generate
3648 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3649 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3650 EVT VT = LHS.getValueType();
3651 if (!TLI.isTypeLegal(VT)) return nullptr;
3653 // The target must have at least one rotate flavor.
3654 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3655 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3656 if (!HasROTL && !HasROTR) return nullptr;
3658 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3659 SDValue LHSShift; // The shift.
3660 SDValue LHSMask; // AND value if any.
3661 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3662 return nullptr; // Not part of a rotate.
3664 SDValue RHSShift; // The shift.
3665 SDValue RHSMask; // AND value if any.
3666 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3667 return nullptr; // Not part of a rotate.
3669 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3670 return nullptr; // Not shifting the same value.
3672 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3673 return nullptr; // Shifts must disagree.
3675 // Canonicalize shl to left side in a shl/srl pair.
3676 if (RHSShift.getOpcode() == ISD::SHL) {
3677 std::swap(LHS, RHS);
3678 std::swap(LHSShift, RHSShift);
3679 std::swap(LHSMask , RHSMask );
3682 unsigned OpSizeInBits = VT.getSizeInBits();
3683 SDValue LHSShiftArg = LHSShift.getOperand(0);
3684 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3685 SDValue RHSShiftArg = RHSShift.getOperand(0);
3686 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3688 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3689 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3690 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3691 RHSShiftAmt.getOpcode() == ISD::Constant) {
3692 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3693 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3694 if ((LShVal + RShVal) != OpSizeInBits)
3697 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3698 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3700 // If there is an AND of either shifted operand, apply it to the result.
3701 if (LHSMask.getNode() || RHSMask.getNode()) {
3702 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3704 if (LHSMask.getNode()) {
3705 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3706 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3708 if (RHSMask.getNode()) {
3709 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3710 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3713 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3716 return Rot.getNode();
3719 // If there is a mask here, and we have a variable shift, we can't be sure
3720 // that we're masking out the right stuff.
3721 if (LHSMask.getNode() || RHSMask.getNode())
3724 // If the shift amount is sign/zext/any-extended just peel it off.
3725 SDValue LExtOp0 = LHSShiftAmt;
3726 SDValue RExtOp0 = RHSShiftAmt;
3727 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3728 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3729 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3730 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3731 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3732 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3733 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3734 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3735 LExtOp0 = LHSShiftAmt.getOperand(0);
3736 RExtOp0 = RHSShiftAmt.getOperand(0);
3739 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3740 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3744 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3745 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3752 SDValue DAGCombiner::visitXOR(SDNode *N) {
3753 SDValue N0 = N->getOperand(0);
3754 SDValue N1 = N->getOperand(1);
3755 SDValue LHS, RHS, CC;
3756 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3757 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3758 EVT VT = N0.getValueType();
3761 if (VT.isVector()) {
3762 SDValue FoldedVOp = SimplifyVBinOp(N);
3763 if (FoldedVOp.getNode()) return FoldedVOp;
3765 // fold (xor x, 0) -> x, vector edition
3766 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3768 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3772 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3773 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3774 return DAG.getConstant(0, VT);
3775 // fold (xor x, undef) -> undef
3776 if (N0.getOpcode() == ISD::UNDEF)
3778 if (N1.getOpcode() == ISD::UNDEF)
3780 // fold (xor c1, c2) -> c1^c2
3782 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3783 // canonicalize constant to RHS
3785 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3786 // fold (xor x, 0) -> x
3787 if (N1C && N1C->isNullValue())
3790 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3794 // fold !(x cc y) -> (x !cc y)
3795 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3796 bool isInt = LHS.getValueType().isInteger();
3797 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3800 if (!LegalOperations ||
3801 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3802 switch (N0.getOpcode()) {
3804 llvm_unreachable("Unhandled SetCC Equivalent!");
3806 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3807 case ISD::SELECT_CC:
3808 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3809 N0.getOperand(3), NotCC);
3814 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3815 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3816 N0.getNode()->hasOneUse() &&
3817 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3818 SDValue V = N0.getOperand(0);
3819 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3820 DAG.getConstant(1, V.getValueType()));
3821 AddToWorklist(V.getNode());
3822 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3825 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3826 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3827 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3828 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3829 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3830 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3831 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3832 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3833 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3834 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3837 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3838 if (N1C && N1C->isAllOnesValue() &&
3839 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3840 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3841 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3842 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3843 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3844 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3845 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3846 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3849 // fold (xor (and x, y), y) -> (and (not x), y)
3850 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3851 N0->getOperand(1) == N1) {
3852 SDValue X = N0->getOperand(0);
3853 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3854 AddToWorklist(NotX.getNode());
3855 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3857 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3858 if (N1C && N0.getOpcode() == ISD::XOR) {
3859 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3860 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3863 DAG.getConstant(N1C->getAPIntValue() ^
3864 N00C->getAPIntValue(), VT));
3866 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3867 DAG.getConstant(N1C->getAPIntValue() ^
3868 N01C->getAPIntValue(), VT));
3870 // fold (xor x, x) -> 0
3872 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3874 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3875 if (N0.getOpcode() == N1.getOpcode()) {
3876 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3877 if (Tmp.getNode()) return Tmp;
3880 // Simplify the expression using non-local knowledge.
3881 if (!VT.isVector() &&
3882 SimplifyDemandedBits(SDValue(N, 0)))
3883 return SDValue(N, 0);
3888 /// Handle transforms common to the three shifts, when the shift amount is a
3890 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3891 // We can't and shouldn't fold opaque constants.
3892 if (Amt->isOpaque())
3895 SDNode *LHS = N->getOperand(0).getNode();
3896 if (!LHS->hasOneUse()) return SDValue();
3898 // We want to pull some binops through shifts, so that we have (and (shift))
3899 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3900 // thing happens with address calculations, so it's important to canonicalize
3902 bool HighBitSet = false; // Can we transform this if the high bit is set?
3904 switch (LHS->getOpcode()) {
3905 default: return SDValue();
3908 HighBitSet = false; // We can only transform sra if the high bit is clear.
3911 HighBitSet = true; // We can only transform sra if the high bit is set.
3914 if (N->getOpcode() != ISD::SHL)
3915 return SDValue(); // only shl(add) not sr[al](add).
3916 HighBitSet = false; // We can only transform sra if the high bit is clear.
3920 // We require the RHS of the binop to be a constant and not opaque as well.
3921 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3922 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3924 // FIXME: disable this unless the input to the binop is a shift by a constant.
3925 // If it is not a shift, it pessimizes some common cases like:
3927 // void foo(int *X, int i) { X[i & 1235] = 1; }
3928 // int bar(int *X, int i) { return X[i & 255]; }
3929 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3930 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3931 BinOpLHSVal->getOpcode() != ISD::SRA &&
3932 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3933 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3936 EVT VT = N->getValueType(0);
3938 // If this is a signed shift right, and the high bit is modified by the
3939 // logical operation, do not perform the transformation. The highBitSet
3940 // boolean indicates the value of the high bit of the constant which would
3941 // cause it to be modified for this operation.
3942 if (N->getOpcode() == ISD::SRA) {
3943 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3944 if (BinOpRHSSignSet != HighBitSet)
3948 if (!TLI.isDesirableToCommuteWithShift(LHS))
3951 // Fold the constants, shifting the binop RHS by the shift amount.
3952 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3954 LHS->getOperand(1), N->getOperand(1));
3955 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3957 // Create the new shift.
3958 SDValue NewShift = DAG.getNode(N->getOpcode(),
3959 SDLoc(LHS->getOperand(0)),
3960 VT, LHS->getOperand(0), N->getOperand(1));
3962 // Create the new binop.
3963 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3966 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3967 assert(N->getOpcode() == ISD::TRUNCATE);
3968 assert(N->getOperand(0).getOpcode() == ISD::AND);
3970 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3971 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3972 SDValue N01 = N->getOperand(0).getOperand(1);
3974 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3975 EVT TruncVT = N->getValueType(0);
3976 SDValue N00 = N->getOperand(0).getOperand(0);
3977 APInt TruncC = N01C->getAPIntValue();
3978 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3980 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3981 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3982 DAG.getConstant(TruncC, TruncVT));
3989 SDValue DAGCombiner::visitRotate(SDNode *N) {
3990 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3991 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3992 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3993 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3994 if (NewOp1.getNode())
3995 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3996 N->getOperand(0), NewOp1);
4001 SDValue DAGCombiner::visitSHL(SDNode *N) {
4002 SDValue N0 = N->getOperand(0);
4003 SDValue N1 = N->getOperand(1);
4004 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4005 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4006 EVT VT = N0.getValueType();
4007 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4010 if (VT.isVector()) {
4011 SDValue FoldedVOp = SimplifyVBinOp(N);
4012 if (FoldedVOp.getNode()) return FoldedVOp;
4014 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4015 // If setcc produces all-one true value then:
4016 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4017 if (N1CV && N1CV->isConstant()) {
4018 if (N0.getOpcode() == ISD::AND) {
4019 SDValue N00 = N0->getOperand(0);
4020 SDValue N01 = N0->getOperand(1);
4021 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4023 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4024 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4025 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4026 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4028 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4031 N1C = isConstOrConstSplat(N1);
4036 // fold (shl c1, c2) -> c1<<c2
4038 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4039 // fold (shl 0, x) -> 0
4040 if (N0C && N0C->isNullValue())
4042 // fold (shl x, c >= size(x)) -> undef
4043 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4044 return DAG.getUNDEF(VT);
4045 // fold (shl x, 0) -> x
4046 if (N1C && N1C->isNullValue())
4048 // fold (shl undef, x) -> 0
4049 if (N0.getOpcode() == ISD::UNDEF)
4050 return DAG.getConstant(0, VT);
4051 // if (shl x, c) is known to be zero, return 0
4052 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4053 APInt::getAllOnesValue(OpSizeInBits)))
4054 return DAG.getConstant(0, VT);
4055 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4056 if (N1.getOpcode() == ISD::TRUNCATE &&
4057 N1.getOperand(0).getOpcode() == ISD::AND) {
4058 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4059 if (NewOp1.getNode())
4060 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4063 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4064 return SDValue(N, 0);
4066 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4067 if (N1C && N0.getOpcode() == ISD::SHL) {
4068 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4069 uint64_t c1 = N0C1->getZExtValue();
4070 uint64_t c2 = N1C->getZExtValue();
4071 if (c1 + c2 >= OpSizeInBits)
4072 return DAG.getConstant(0, VT);
4073 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4074 DAG.getConstant(c1 + c2, N1.getValueType()));
4078 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4079 // For this to be valid, the second form must not preserve any of the bits
4080 // that are shifted out by the inner shift in the first form. This means
4081 // the outer shift size must be >= the number of bits added by the ext.
4082 // As a corollary, we don't care what kind of ext it is.
4083 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4084 N0.getOpcode() == ISD::ANY_EXTEND ||
4085 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4086 N0.getOperand(0).getOpcode() == ISD::SHL) {
4087 SDValue N0Op0 = N0.getOperand(0);
4088 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4089 uint64_t c1 = N0Op0C1->getZExtValue();
4090 uint64_t c2 = N1C->getZExtValue();
4091 EVT InnerShiftVT = N0Op0.getValueType();
4092 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4093 if (c2 >= OpSizeInBits - InnerShiftSize) {
4094 if (c1 + c2 >= OpSizeInBits)
4095 return DAG.getConstant(0, VT);
4096 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4097 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4098 N0Op0->getOperand(0)),
4099 DAG.getConstant(c1 + c2, N1.getValueType()));
4104 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4105 // Only fold this if the inner zext has no other uses to avoid increasing
4106 // the total number of instructions.
4107 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4108 N0.getOperand(0).getOpcode() == ISD::SRL) {
4109 SDValue N0Op0 = N0.getOperand(0);
4110 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4111 uint64_t c1 = N0Op0C1->getZExtValue();
4112 if (c1 < VT.getScalarSizeInBits()) {
4113 uint64_t c2 = N1C->getZExtValue();
4115 SDValue NewOp0 = N0.getOperand(0);
4116 EVT CountVT = NewOp0.getOperand(1).getValueType();
4117 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4118 NewOp0, DAG.getConstant(c2, CountVT));
4119 AddToWorklist(NewSHL.getNode());
4120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4126 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4127 // (and (srl x, (sub c1, c2), MASK)
4128 // Only fold this if the inner shift has no other uses -- if it does, folding
4129 // this will increase the total number of instructions.
4130 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4131 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4132 uint64_t c1 = N0C1->getZExtValue();
4133 if (c1 < OpSizeInBits) {
4134 uint64_t c2 = N1C->getZExtValue();
4135 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4138 Mask = Mask.shl(c2 - c1);
4139 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4140 DAG.getConstant(c2 - c1, N1.getValueType()));
4142 Mask = Mask.lshr(c1 - c2);
4143 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4144 DAG.getConstant(c1 - c2, N1.getValueType()));
4146 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4147 DAG.getConstant(Mask, VT));
4151 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4152 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4153 unsigned BitSize = VT.getScalarSizeInBits();
4154 SDValue HiBitsMask =
4155 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4156 BitSize - N1C->getZExtValue()), VT);
4157 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4161 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4162 // Variant of version done on multiply, except mul by a power of 2 is turned
4165 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4166 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4167 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4168 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4169 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4170 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4174 SDValue NewSHL = visitShiftByConstant(N, N1C);
4175 if (NewSHL.getNode())
4182 SDValue DAGCombiner::visitSRA(SDNode *N) {
4183 SDValue N0 = N->getOperand(0);
4184 SDValue N1 = N->getOperand(1);
4185 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4186 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4187 EVT VT = N0.getValueType();
4188 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4191 if (VT.isVector()) {
4192 SDValue FoldedVOp = SimplifyVBinOp(N);
4193 if (FoldedVOp.getNode()) return FoldedVOp;
4195 N1C = isConstOrConstSplat(N1);
4198 // fold (sra c1, c2) -> (sra c1, c2)
4200 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4201 // fold (sra 0, x) -> 0
4202 if (N0C && N0C->isNullValue())
4204 // fold (sra -1, x) -> -1
4205 if (N0C && N0C->isAllOnesValue())
4207 // fold (sra x, (setge c, size(x))) -> undef
4208 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4209 return DAG.getUNDEF(VT);
4210 // fold (sra x, 0) -> x
4211 if (N1C && N1C->isNullValue())
4213 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4215 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4216 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4217 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4219 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4220 ExtVT, VT.getVectorNumElements());
4221 if ((!LegalOperations ||
4222 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4223 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4224 N0.getOperand(0), DAG.getValueType(ExtVT));
4227 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4228 if (N1C && N0.getOpcode() == ISD::SRA) {
4229 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4230 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4231 if (Sum >= OpSizeInBits)
4232 Sum = OpSizeInBits - 1;
4233 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4234 DAG.getConstant(Sum, N1.getValueType()));
4238 // fold (sra (shl X, m), (sub result_size, n))
4239 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4240 // result_size - n != m.
4241 // If truncate is free for the target sext(shl) is likely to result in better
4243 if (N0.getOpcode() == ISD::SHL && N1C) {
4244 // Get the two constanst of the shifts, CN0 = m, CN = n.
4245 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4247 LLVMContext &Ctx = *DAG.getContext();
4248 // Determine what the truncate's result bitsize and type would be.
4249 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4252 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4254 // Determine the residual right-shift amount.
4255 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4257 // If the shift is not a no-op (in which case this should be just a sign
4258 // extend already), the truncated to type is legal, sign_extend is legal
4259 // on that type, and the truncate to that type is both legal and free,
4260 // perform the transform.
4261 if ((ShiftAmt > 0) &&
4262 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4263 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4264 TLI.isTruncateFree(VT, TruncVT)) {
4266 SDValue Amt = DAG.getConstant(ShiftAmt,
4267 getShiftAmountTy(N0.getOperand(0).getValueType()));
4268 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4269 N0.getOperand(0), Amt);
4270 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4272 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4273 N->getValueType(0), Trunc);
4278 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4279 if (N1.getOpcode() == ISD::TRUNCATE &&
4280 N1.getOperand(0).getOpcode() == ISD::AND) {
4281 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4282 if (NewOp1.getNode())
4283 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4286 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4287 // if c1 is equal to the number of bits the trunc removes
4288 if (N0.getOpcode() == ISD::TRUNCATE &&
4289 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4290 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4291 N0.getOperand(0).hasOneUse() &&
4292 N0.getOperand(0).getOperand(1).hasOneUse() &&
4294 SDValue N0Op0 = N0.getOperand(0);
4295 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4296 unsigned LargeShiftVal = LargeShift->getZExtValue();
4297 EVT LargeVT = N0Op0.getValueType();
4299 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4301 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4302 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4303 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4304 N0Op0.getOperand(0), Amt);
4305 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4310 // Simplify, based on bits shifted out of the LHS.
4311 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4312 return SDValue(N, 0);
4315 // If the sign bit is known to be zero, switch this to a SRL.
4316 if (DAG.SignBitIsZero(N0))
4317 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4320 SDValue NewSRA = visitShiftByConstant(N, N1C);
4321 if (NewSRA.getNode())
4328 SDValue DAGCombiner::visitSRL(SDNode *N) {
4329 SDValue N0 = N->getOperand(0);
4330 SDValue N1 = N->getOperand(1);
4331 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4333 EVT VT = N0.getValueType();
4334 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4337 if (VT.isVector()) {
4338 SDValue FoldedVOp = SimplifyVBinOp(N);
4339 if (FoldedVOp.getNode()) return FoldedVOp;
4341 N1C = isConstOrConstSplat(N1);
4344 // fold (srl c1, c2) -> c1 >>u c2
4346 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4347 // fold (srl 0, x) -> 0
4348 if (N0C && N0C->isNullValue())
4350 // fold (srl x, c >= size(x)) -> undef
4351 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4352 return DAG.getUNDEF(VT);
4353 // fold (srl x, 0) -> x
4354 if (N1C && N1C->isNullValue())
4356 // if (srl x, c) is known to be zero, return 0
4357 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4358 APInt::getAllOnesValue(OpSizeInBits)))
4359 return DAG.getConstant(0, VT);
4361 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4362 if (N1C && N0.getOpcode() == ISD::SRL) {
4363 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4364 uint64_t c1 = N01C->getZExtValue();
4365 uint64_t c2 = N1C->getZExtValue();
4366 if (c1 + c2 >= OpSizeInBits)
4367 return DAG.getConstant(0, VT);
4368 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4369 DAG.getConstant(c1 + c2, N1.getValueType()));
4373 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4374 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4375 N0.getOperand(0).getOpcode() == ISD::SRL &&
4376 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4378 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4379 uint64_t c2 = N1C->getZExtValue();
4380 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4381 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4382 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4383 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4384 if (c1 + OpSizeInBits == InnerShiftSize) {
4385 if (c1 + c2 >= InnerShiftSize)
4386 return DAG.getConstant(0, VT);
4387 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4388 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4389 N0.getOperand(0)->getOperand(0),
4390 DAG.getConstant(c1 + c2, ShiftCountVT)));
4394 // fold (srl (shl x, c), c) -> (and x, cst2)
4395 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4396 unsigned BitSize = N0.getScalarValueSizeInBits();
4397 if (BitSize <= 64) {
4398 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4400 DAG.getConstant(~0ULL >> ShAmt, VT));
4404 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4405 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4406 // Shifting in all undef bits?
4407 EVT SmallVT = N0.getOperand(0).getValueType();
4408 unsigned BitSize = SmallVT.getScalarSizeInBits();
4409 if (N1C->getZExtValue() >= BitSize)
4410 return DAG.getUNDEF(VT);
4412 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4413 uint64_t ShiftAmt = N1C->getZExtValue();
4414 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4416 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4417 AddToWorklist(SmallShift.getNode());
4418 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4419 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4420 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4421 DAG.getConstant(Mask, VT));
4425 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4426 // bit, which is unmodified by sra.
4427 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4428 if (N0.getOpcode() == ISD::SRA)
4429 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4432 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4433 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4434 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4435 APInt KnownZero, KnownOne;
4436 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4438 // If any of the input bits are KnownOne, then the input couldn't be all
4439 // zeros, thus the result of the srl will always be zero.
4440 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4442 // If all of the bits input the to ctlz node are known to be zero, then
4443 // the result of the ctlz is "32" and the result of the shift is one.
4444 APInt UnknownBits = ~KnownZero;
4445 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4447 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4448 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4449 // Okay, we know that only that the single bit specified by UnknownBits
4450 // could be set on input to the CTLZ node. If this bit is set, the SRL
4451 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4452 // to an SRL/XOR pair, which is likely to simplify more.
4453 unsigned ShAmt = UnknownBits.countTrailingZeros();
4454 SDValue Op = N0.getOperand(0);
4457 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4458 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4459 AddToWorklist(Op.getNode());
4462 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4463 Op, DAG.getConstant(1, VT));
4467 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4468 if (N1.getOpcode() == ISD::TRUNCATE &&
4469 N1.getOperand(0).getOpcode() == ISD::AND) {
4470 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4471 if (NewOp1.getNode())
4472 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4475 // fold operands of srl based on knowledge that the low bits are not
4477 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4478 return SDValue(N, 0);
4481 SDValue NewSRL = visitShiftByConstant(N, N1C);
4482 if (NewSRL.getNode())
4486 // Attempt to convert a srl of a load into a narrower zero-extending load.
4487 SDValue NarrowLoad = ReduceLoadWidth(N);
4488 if (NarrowLoad.getNode())
4491 // Here is a common situation. We want to optimize:
4494 // %b = and i32 %a, 2
4495 // %c = srl i32 %b, 1
4496 // brcond i32 %c ...
4502 // %c = setcc eq %b, 0
4505 // However when after the source operand of SRL is optimized into AND, the SRL
4506 // itself may not be optimized further. Look for it and add the BRCOND into
4508 if (N->hasOneUse()) {
4509 SDNode *Use = *N->use_begin();
4510 if (Use->getOpcode() == ISD::BRCOND)
4512 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4513 // Also look pass the truncate.
4514 Use = *Use->use_begin();
4515 if (Use->getOpcode() == ISD::BRCOND)
4523 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4524 SDValue N0 = N->getOperand(0);
4525 EVT VT = N->getValueType(0);
4527 // fold (ctlz c1) -> c2
4528 if (isa<ConstantSDNode>(N0))
4529 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4533 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4534 SDValue N0 = N->getOperand(0);
4535 EVT VT = N->getValueType(0);
4537 // fold (ctlz_zero_undef c1) -> c2
4538 if (isa<ConstantSDNode>(N0))
4539 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4543 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4544 SDValue N0 = N->getOperand(0);
4545 EVT VT = N->getValueType(0);
4547 // fold (cttz c1) -> c2
4548 if (isa<ConstantSDNode>(N0))
4549 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4553 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4554 SDValue N0 = N->getOperand(0);
4555 EVT VT = N->getValueType(0);
4557 // fold (cttz_zero_undef c1) -> c2
4558 if (isa<ConstantSDNode>(N0))
4559 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4563 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4564 SDValue N0 = N->getOperand(0);
4565 EVT VT = N->getValueType(0);
4567 // fold (ctpop c1) -> c2
4568 if (isa<ConstantSDNode>(N0))
4569 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4573 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4574 SDValue N0 = N->getOperand(0);
4575 SDValue N1 = N->getOperand(1);
4576 SDValue N2 = N->getOperand(2);
4577 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4580 EVT VT = N->getValueType(0);
4581 EVT VT0 = N0.getValueType();
4583 // fold (select C, X, X) -> X
4586 // fold (select true, X, Y) -> X
4587 if (N0C && !N0C->isNullValue())
4589 // fold (select false, X, Y) -> Y
4590 if (N0C && N0C->isNullValue())
4592 // fold (select C, 1, X) -> (or C, X)
4593 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4594 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4595 // fold (select C, 0, 1) -> (xor C, 1)
4596 // We can't do this reliably if integer based booleans have different contents
4597 // to floating point based booleans. This is because we can't tell whether we
4598 // have an integer-based boolean or a floating-point-based boolean unless we
4599 // can find the SETCC that produced it and inspect its operands. This is
4600 // fairly easy if C is the SETCC node, but it can potentially be
4601 // undiscoverable (or not reasonably discoverable). For example, it could be
4602 // in another basic block or it could require searching a complicated
4604 if (VT.isInteger() &&
4605 (VT0 == MVT::i1 || (VT0.isInteger() &&
4606 TLI.getBooleanContents(false, false) ==
4607 TLI.getBooleanContents(false, true) &&
4608 TLI.getBooleanContents(false, false) ==
4609 TargetLowering::ZeroOrOneBooleanContent)) &&
4610 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4613 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4614 N0, DAG.getConstant(1, VT0));
4615 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4616 N0, DAG.getConstant(1, VT0));
4617 AddToWorklist(XORNode.getNode());
4619 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4620 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4622 // fold (select C, 0, X) -> (and (not C), X)
4623 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4624 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4625 AddToWorklist(NOTNode.getNode());
4626 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4628 // fold (select C, X, 1) -> (or (not C), X)
4629 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4630 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4631 AddToWorklist(NOTNode.getNode());
4632 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4634 // fold (select C, X, 0) -> (and C, X)
4635 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4636 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4637 // fold (select X, X, Y) -> (or X, Y)
4638 // fold (select X, 1, Y) -> (or X, Y)
4639 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4640 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4641 // fold (select X, Y, X) -> (and X, Y)
4642 // fold (select X, Y, 0) -> (and X, Y)
4643 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4644 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4646 // If we can fold this based on the true/false value, do so.
4647 if (SimplifySelectOps(N, N1, N2))
4648 return SDValue(N, 0); // Don't revisit N.
4650 // fold selects based on a setcc into other things, such as min/max/abs
4651 if (N0.getOpcode() == ISD::SETCC) {
4652 if ((!LegalOperations &&
4653 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4654 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4655 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4656 N0.getOperand(0), N0.getOperand(1),
4657 N1, N2, N0.getOperand(2));
4658 return SimplifySelect(SDLoc(N), N0, N1, N2);
4665 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4668 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4670 // Split the inputs.
4671 SDValue Lo, Hi, LL, LH, RL, RH;
4672 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4673 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4675 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4676 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4678 return std::make_pair(Lo, Hi);
4681 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4682 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4683 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4685 SDValue Cond = N->getOperand(0);
4686 SDValue LHS = N->getOperand(1);
4687 SDValue RHS = N->getOperand(2);
4688 EVT VT = N->getValueType(0);
4689 int NumElems = VT.getVectorNumElements();
4690 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4692 Cond.getOpcode() == ISD::BUILD_VECTOR);
4694 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4695 // binary ones here.
4696 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4699 // We're sure we have an even number of elements due to the
4700 // concat_vectors we have as arguments to vselect.
4701 // Skip BV elements until we find one that's not an UNDEF
4702 // After we find an UNDEF element, keep looping until we get to half the
4703 // length of the BV and see if all the non-undef nodes are the same.
4704 ConstantSDNode *BottomHalf = nullptr;
4705 for (int i = 0; i < NumElems / 2; ++i) {
4706 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4709 if (BottomHalf == nullptr)
4710 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4711 else if (Cond->getOperand(i).getNode() != BottomHalf)
4715 // Do the same for the second half of the BuildVector
4716 ConstantSDNode *TopHalf = nullptr;
4717 for (int i = NumElems / 2; i < NumElems; ++i) {
4718 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4721 if (TopHalf == nullptr)
4722 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4723 else if (Cond->getOperand(i).getNode() != TopHalf)
4727 assert(TopHalf && BottomHalf &&
4728 "One half of the selector was all UNDEFs and the other was all the "
4729 "same value. This should have been addressed before this function.");
4731 ISD::CONCAT_VECTORS, dl, VT,
4732 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4733 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4736 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4737 SDValue N0 = N->getOperand(0);
4738 SDValue N1 = N->getOperand(1);
4739 SDValue N2 = N->getOperand(2);
4742 // Canonicalize integer abs.
4743 // vselect (setg[te] X, 0), X, -X ->
4744 // vselect (setgt X, -1), X, -X ->
4745 // vselect (setl[te] X, 0), -X, X ->
4746 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4747 if (N0.getOpcode() == ISD::SETCC) {
4748 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4749 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4751 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4753 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4754 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4755 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4756 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4757 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4758 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4759 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4762 EVT VT = LHS.getValueType();
4763 SDValue Shift = DAG.getNode(
4764 ISD::SRA, DL, VT, LHS,
4765 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4766 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4767 AddToWorklist(Shift.getNode());
4768 AddToWorklist(Add.getNode());
4769 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4773 // If the VSELECT result requires splitting and the mask is provided by a
4774 // SETCC, then split both nodes and its operands before legalization. This
4775 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4776 // and enables future optimizations (e.g. min/max pattern matching on X86).
4777 if (N0.getOpcode() == ISD::SETCC) {
4778 EVT VT = N->getValueType(0);
4780 // Check if any splitting is required.
4781 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4782 TargetLowering::TypeSplitVector)
4785 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4786 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4787 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4788 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4790 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4791 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4793 // Add the new VSELECT nodes to the work list in case they need to be split
4795 AddToWorklist(Lo.getNode());
4796 AddToWorklist(Hi.getNode());
4798 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4801 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4802 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4804 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4805 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4808 // The ConvertSelectToConcatVector function is assuming both the above
4809 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4811 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4812 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4813 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4814 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4822 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4823 SDValue N0 = N->getOperand(0);
4824 SDValue N1 = N->getOperand(1);
4825 SDValue N2 = N->getOperand(2);
4826 SDValue N3 = N->getOperand(3);
4827 SDValue N4 = N->getOperand(4);
4828 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4830 // fold select_cc lhs, rhs, x, x, cc -> x
4834 // Determine if the condition we're dealing with is constant
4835 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4836 N0, N1, CC, SDLoc(N), false);
4837 if (SCC.getNode()) {
4838 AddToWorklist(SCC.getNode());
4840 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4841 if (!SCCC->isNullValue())
4842 return N2; // cond always true -> true val
4844 return N3; // cond always false -> false val
4847 // Fold to a simpler select_cc
4848 if (SCC.getOpcode() == ISD::SETCC)
4849 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4850 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4854 // If we can fold this based on the true/false value, do so.
4855 if (SimplifySelectOps(N, N2, N3))
4856 return SDValue(N, 0); // Don't revisit N.
4858 // fold select_cc into other things, such as min/max/abs
4859 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4862 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4863 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4864 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4868 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4869 // dag node into a ConstantSDNode or a build_vector of constants.
4870 // This function is called by the DAGCombiner when visiting sext/zext/aext
4871 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4872 // Vector extends are not folded if operations are legal; this is to
4873 // avoid introducing illegal build_vector dag nodes.
4874 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4875 SelectionDAG &DAG, bool LegalTypes,
4876 bool LegalOperations) {
4877 unsigned Opcode = N->getOpcode();
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4881 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4882 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4884 // fold (sext c1) -> c1
4885 // fold (zext c1) -> c1
4886 // fold (aext c1) -> c1
4887 if (isa<ConstantSDNode>(N0))
4888 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4890 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4892 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4893 EVT SVT = VT.getScalarType();
4894 if (!(VT.isVector() &&
4895 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4896 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4899 // We can fold this node into a build_vector.
4900 unsigned VTBits = SVT.getSizeInBits();
4901 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4902 unsigned ShAmt = VTBits - EVTBits;
4903 SmallVector<SDValue, 8> Elts;
4904 unsigned NumElts = N0->getNumOperands();
4907 for (unsigned i=0; i != NumElts; ++i) {
4908 SDValue Op = N0->getOperand(i);
4909 if (Op->getOpcode() == ISD::UNDEF) {
4910 Elts.push_back(DAG.getUNDEF(SVT));
4914 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4915 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4916 if (Opcode == ISD::SIGN_EXTEND)
4917 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4920 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4924 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4927 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4928 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4929 // transformation. Returns true if extension are possible and the above
4930 // mentioned transformation is profitable.
4931 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4933 SmallVectorImpl<SDNode *> &ExtendNodes,
4934 const TargetLowering &TLI) {
4935 bool HasCopyToRegUses = false;
4936 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4937 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4938 UE = N0.getNode()->use_end();
4943 if (UI.getUse().getResNo() != N0.getResNo())
4945 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4946 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4947 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4948 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4949 // Sign bits will be lost after a zext.
4952 for (unsigned i = 0; i != 2; ++i) {
4953 SDValue UseOp = User->getOperand(i);
4956 if (!isa<ConstantSDNode>(UseOp))
4961 ExtendNodes.push_back(User);
4964 // If truncates aren't free and there are users we can't
4965 // extend, it isn't worthwhile.
4968 // Remember if this value is live-out.
4969 if (User->getOpcode() == ISD::CopyToReg)
4970 HasCopyToRegUses = true;
4973 if (HasCopyToRegUses) {
4974 bool BothLiveOut = false;
4975 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4977 SDUse &Use = UI.getUse();
4978 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4984 // Both unextended and extended values are live out. There had better be
4985 // a good reason for the transformation.
4986 return ExtendNodes.size();
4991 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4992 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4993 ISD::NodeType ExtType) {
4994 // Extend SetCC uses if necessary.
4995 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4996 SDNode *SetCC = SetCCs[i];
4997 SmallVector<SDValue, 4> Ops;
4999 for (unsigned j = 0; j != 2; ++j) {
5000 SDValue SOp = SetCC->getOperand(j);
5002 Ops.push_back(ExtLoad);
5004 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5007 Ops.push_back(SetCC->getOperand(2));
5008 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5012 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5013 SDValue N0 = N->getOperand(0);
5014 EVT VT = N->getValueType(0);
5016 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5018 return SDValue(Res, 0);
5020 // fold (sext (sext x)) -> (sext x)
5021 // fold (sext (aext x)) -> (sext x)
5022 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5023 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5026 if (N0.getOpcode() == ISD::TRUNCATE) {
5027 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5028 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5029 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5030 if (NarrowLoad.getNode()) {
5031 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5032 if (NarrowLoad.getNode() != N0.getNode()) {
5033 CombineTo(N0.getNode(), NarrowLoad);
5034 // CombineTo deleted the truncate, if needed, but not what's under it.
5037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5040 // See if the value being truncated is already sign extended. If so, just
5041 // eliminate the trunc/sext pair.
5042 SDValue Op = N0.getOperand(0);
5043 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5044 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5045 unsigned DestBits = VT.getScalarType().getSizeInBits();
5046 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5048 if (OpBits == DestBits) {
5049 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5050 // bits, it is already ready.
5051 if (NumSignBits > DestBits-MidBits)
5053 } else if (OpBits < DestBits) {
5054 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5055 // bits, just sext from i32.
5056 if (NumSignBits > OpBits-MidBits)
5057 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5059 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5060 // bits, just truncate to i32.
5061 if (NumSignBits > OpBits-MidBits)
5062 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5065 // fold (sext (truncate x)) -> (sextinreg x).
5066 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5067 N0.getValueType())) {
5068 if (OpBits < DestBits)
5069 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5070 else if (OpBits > DestBits)
5071 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5072 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5073 DAG.getValueType(N0.getValueType()));
5077 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5078 // None of the supported targets knows how to perform load and sign extend
5079 // on vectors in one instruction. We only perform this transformation on
5081 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5082 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5083 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5084 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5085 bool DoXform = true;
5086 SmallVector<SDNode*, 4> SetCCs;
5087 if (!N0.hasOneUse())
5088 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5093 LN0->getBasePtr(), N0.getValueType(),
5094 LN0->getMemOperand());
5095 CombineTo(N, ExtLoad);
5096 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5097 N0.getValueType(), ExtLoad);
5098 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5099 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5105 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5106 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5107 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5108 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5110 EVT MemVT = LN0->getMemoryVT();
5111 if ((!LegalOperations && !LN0->isVolatile()) ||
5112 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5113 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5115 LN0->getBasePtr(), MemVT,
5116 LN0->getMemOperand());
5117 CombineTo(N, ExtLoad);
5118 CombineTo(N0.getNode(),
5119 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5120 N0.getValueType(), ExtLoad),
5121 ExtLoad.getValue(1));
5122 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5126 // fold (sext (and/or/xor (load x), cst)) ->
5127 // (and/or/xor (sextload x), (sext cst))
5128 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5129 N0.getOpcode() == ISD::XOR) &&
5130 isa<LoadSDNode>(N0.getOperand(0)) &&
5131 N0.getOperand(1).getOpcode() == ISD::Constant &&
5132 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5133 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5134 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5135 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5136 bool DoXform = true;
5137 SmallVector<SDNode*, 4> SetCCs;
5138 if (!N0.hasOneUse())
5139 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5142 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5143 LN0->getChain(), LN0->getBasePtr(),
5145 LN0->getMemOperand());
5146 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5147 Mask = Mask.sext(VT.getSizeInBits());
5148 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5149 ExtLoad, DAG.getConstant(Mask, VT));
5150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5151 SDLoc(N0.getOperand(0)),
5152 N0.getOperand(0).getValueType(), ExtLoad);
5154 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5155 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5162 if (N0.getOpcode() == ISD::SETCC) {
5163 EVT N0VT = N0.getOperand(0).getValueType();
5164 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5165 // Only do this before legalize for now.
5166 if (VT.isVector() && !LegalOperations &&
5167 TLI.getBooleanContents(N0VT) ==
5168 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5169 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5170 // of the same size as the compared operands. Only optimize sext(setcc())
5171 // if this is the case.
5172 EVT SVT = getSetCCResultType(N0VT);
5174 // We know that the # elements of the results is the same as the
5175 // # elements of the compare (and the # elements of the compare result
5176 // for that matter). Check to see that they are the same size. If so,
5177 // we know that the element size of the sext'd result matches the
5178 // element size of the compare operands.
5179 if (VT.getSizeInBits() == SVT.getSizeInBits())
5180 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5182 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5184 // If the desired elements are smaller or larger than the source
5185 // elements we can use a matching integer vector type and then
5186 // truncate/sign extend
5187 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5188 if (SVT == MatchingVectorType) {
5189 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5190 N0.getOperand(0), N0.getOperand(1),
5191 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5192 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5196 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5197 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5199 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5201 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5202 NegOne, DAG.getConstant(0, VT),
5203 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5204 if (SCC.getNode()) return SCC;
5206 if (!VT.isVector()) {
5207 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5208 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5210 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5211 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5212 N0.getOperand(0), N0.getOperand(1), CC);
5213 return DAG.getSelect(DL, VT, SetCC,
5214 NegOne, DAG.getConstant(0, VT));
5219 // fold (sext x) -> (zext x) if the sign bit is known zero.
5220 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5221 DAG.SignBitIsZero(N0))
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5227 // isTruncateOf - If N is a truncate of some other value, return true, record
5228 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5229 // This function computes KnownZero to avoid a duplicated call to
5230 // computeKnownBits in the caller.
5231 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5234 if (N->getOpcode() == ISD::TRUNCATE) {
5235 Op = N->getOperand(0);
5236 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5241 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5244 SDValue Op0 = N->getOperand(0);
5245 SDValue Op1 = N->getOperand(1);
5246 assert(Op0.getValueType() == Op1.getValueType());
5248 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5249 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5250 if (COp0 && COp0->isNullValue())
5252 else if (COp1 && COp1->isNullValue())
5257 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5259 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5265 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5266 SDValue N0 = N->getOperand(0);
5267 EVT VT = N->getValueType(0);
5269 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5271 return SDValue(Res, 0);
5273 // fold (zext (zext x)) -> (zext x)
5274 // fold (zext (aext x)) -> (zext x)
5275 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5276 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5279 // fold (zext (truncate x)) -> (zext x) or
5280 // (zext (truncate x)) -> (truncate x)
5281 // This is valid when the truncated bits of x are already zero.
5282 // FIXME: We should extend this to work for vectors too.
5285 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5286 APInt TruncatedBits =
5287 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5288 APInt(Op.getValueSizeInBits(), 0) :
5289 APInt::getBitsSet(Op.getValueSizeInBits(),
5290 N0.getValueSizeInBits(),
5291 std::min(Op.getValueSizeInBits(),
5292 VT.getSizeInBits()));
5293 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5294 if (VT.bitsGT(Op.getValueType()))
5295 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5296 if (VT.bitsLT(Op.getValueType()))
5297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5303 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5304 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5305 if (N0.getOpcode() == ISD::TRUNCATE) {
5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5307 if (NarrowLoad.getNode()) {
5308 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5309 if (NarrowLoad.getNode() != N0.getNode()) {
5310 CombineTo(N0.getNode(), NarrowLoad);
5311 // CombineTo deleted the truncate, if needed, but not what's under it.
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5318 // fold (zext (truncate x)) -> (and x, mask)
5319 if (N0.getOpcode() == ISD::TRUNCATE &&
5320 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5322 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5323 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5324 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5325 if (NarrowLoad.getNode()) {
5326 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5327 if (NarrowLoad.getNode() != N0.getNode()) {
5328 CombineTo(N0.getNode(), NarrowLoad);
5329 // CombineTo deleted the truncate, if needed, but not what's under it.
5332 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5335 SDValue Op = N0.getOperand(0);
5336 if (Op.getValueType().bitsLT(VT)) {
5337 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5338 AddToWorklist(Op.getNode());
5339 } else if (Op.getValueType().bitsGT(VT)) {
5340 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5341 AddToWorklist(Op.getNode());
5343 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5344 N0.getValueType().getScalarType());
5347 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5348 // if either of the casts is not free.
5349 if (N0.getOpcode() == ISD::AND &&
5350 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5351 N0.getOperand(1).getOpcode() == ISD::Constant &&
5352 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5353 N0.getValueType()) ||
5354 !TLI.isZExtFree(N0.getValueType(), VT))) {
5355 SDValue X = N0.getOperand(0).getOperand(0);
5356 if (X.getValueType().bitsLT(VT)) {
5357 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5358 } else if (X.getValueType().bitsGT(VT)) {
5359 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5361 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5362 Mask = Mask.zext(VT.getSizeInBits());
5363 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5364 X, DAG.getConstant(Mask, VT));
5367 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5368 // None of the supported targets knows how to perform load and vector_zext
5369 // on vectors in one instruction. We only perform this transformation on
5371 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5372 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5373 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5375 bool DoXform = true;
5376 SmallVector<SDNode*, 4> SetCCs;
5377 if (!N0.hasOneUse())
5378 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5380 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5381 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5383 LN0->getBasePtr(), N0.getValueType(),
5384 LN0->getMemOperand());
5385 CombineTo(N, ExtLoad);
5386 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5387 N0.getValueType(), ExtLoad);
5388 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5390 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5392 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5396 // fold (zext (and/or/xor (load x), cst)) ->
5397 // (and/or/xor (zextload x), (zext cst))
5398 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5399 N0.getOpcode() == ISD::XOR) &&
5400 isa<LoadSDNode>(N0.getOperand(0)) &&
5401 N0.getOperand(1).getOpcode() == ISD::Constant &&
5402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5403 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5404 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5405 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5406 bool DoXform = true;
5407 SmallVector<SDNode*, 4> SetCCs;
5408 if (!N0.hasOneUse())
5409 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5413 LN0->getChain(), LN0->getBasePtr(),
5415 LN0->getMemOperand());
5416 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5417 Mask = Mask.zext(VT.getSizeInBits());
5418 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5419 ExtLoad, DAG.getConstant(Mask, VT));
5420 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5421 SDLoc(N0.getOperand(0)),
5422 N0.getOperand(0).getValueType(), ExtLoad);
5424 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5432 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5433 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5434 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5435 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5436 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5437 EVT MemVT = LN0->getMemoryVT();
5438 if ((!LegalOperations && !LN0->isVolatile()) ||
5439 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5440 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5442 LN0->getBasePtr(), MemVT,
5443 LN0->getMemOperand());
5444 CombineTo(N, ExtLoad);
5445 CombineTo(N0.getNode(),
5446 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5448 ExtLoad.getValue(1));
5449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5453 if (N0.getOpcode() == ISD::SETCC) {
5454 if (!LegalOperations && VT.isVector() &&
5455 N0.getValueType().getVectorElementType() == MVT::i1) {
5456 EVT N0VT = N0.getOperand(0).getValueType();
5457 if (getSetCCResultType(N0VT) == N0.getValueType())
5460 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5461 // Only do this before legalize for now.
5462 EVT EltVT = VT.getVectorElementType();
5463 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5464 DAG.getConstant(1, EltVT));
5465 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5466 // We know that the # elements of the results is the same as the
5467 // # elements of the compare (and the # elements of the compare result
5468 // for that matter). Check to see that they are the same size. If so,
5469 // we know that the element size of the sext'd result matches the
5470 // element size of the compare operands.
5471 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5472 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5474 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5478 // If the desired elements are smaller or larger than the source
5479 // elements we can use a matching integer vector type and then
5480 // truncate/sign extend
5481 EVT MatchingElementType =
5482 EVT::getIntegerVT(*DAG.getContext(),
5483 N0VT.getScalarType().getSizeInBits());
5484 EVT MatchingVectorType =
5485 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5486 N0VT.getVectorNumElements());
5488 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5490 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5491 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5492 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5493 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5496 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5498 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5499 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5500 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5501 if (SCC.getNode()) return SCC;
5504 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5505 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5506 isa<ConstantSDNode>(N0.getOperand(1)) &&
5507 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5509 SDValue ShAmt = N0.getOperand(1);
5510 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5511 if (N0.getOpcode() == ISD::SHL) {
5512 SDValue InnerZExt = N0.getOperand(0);
5513 // If the original shl may be shifting out bits, do not perform this
5515 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5516 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5517 if (ShAmtVal > KnownZeroBits)
5523 // Ensure that the shift amount is wide enough for the shifted value.
5524 if (VT.getSizeInBits() >= 256)
5525 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5527 return DAG.getNode(N0.getOpcode(), DL, VT,
5528 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5535 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5536 SDValue N0 = N->getOperand(0);
5537 EVT VT = N->getValueType(0);
5539 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5541 return SDValue(Res, 0);
5543 // fold (aext (aext x)) -> (aext x)
5544 // fold (aext (zext x)) -> (zext x)
5545 // fold (aext (sext x)) -> (sext x)
5546 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5547 N0.getOpcode() == ISD::ZERO_EXTEND ||
5548 N0.getOpcode() == ISD::SIGN_EXTEND)
5549 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5551 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5552 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5553 if (N0.getOpcode() == ISD::TRUNCATE) {
5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
5556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
5558 CombineTo(N0.getNode(), NarrowLoad);
5559 // CombineTo deleted the truncate, if needed, but not what's under it.
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5566 // fold (aext (truncate x))
5567 if (N0.getOpcode() == ISD::TRUNCATE) {
5568 SDValue TruncOp = N0.getOperand(0);
5569 if (TruncOp.getValueType() == VT)
5570 return TruncOp; // x iff x size == zext size.
5571 if (TruncOp.getValueType().bitsGT(VT))
5572 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5573 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5576 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5577 // if the trunc is not free.
5578 if (N0.getOpcode() == ISD::AND &&
5579 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5580 N0.getOperand(1).getOpcode() == ISD::Constant &&
5581 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5582 N0.getValueType())) {
5583 SDValue X = N0.getOperand(0).getOperand(0);
5584 if (X.getValueType().bitsLT(VT)) {
5585 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5586 } else if (X.getValueType().bitsGT(VT)) {
5587 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5589 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5590 Mask = Mask.zext(VT.getSizeInBits());
5591 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5592 X, DAG.getConstant(Mask, VT));
5595 // fold (aext (load x)) -> (aext (truncate (extload x)))
5596 // None of the supported targets knows how to perform load and any_ext
5597 // on vectors in one instruction. We only perform this transformation on
5599 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5600 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5601 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5602 bool DoXform = true;
5603 SmallVector<SDNode*, 4> SetCCs;
5604 if (!N0.hasOneUse())
5605 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5607 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5608 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5610 LN0->getBasePtr(), N0.getValueType(),
5611 LN0->getMemOperand());
5612 CombineTo(N, ExtLoad);
5613 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5614 N0.getValueType(), ExtLoad);
5615 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5616 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5618 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5623 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5624 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5625 if (N0.getOpcode() == ISD::LOAD &&
5626 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5628 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5629 ISD::LoadExtType ExtType = LN0->getExtensionType();
5630 EVT MemVT = LN0->getMemoryVT();
5631 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5632 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5633 VT, LN0->getChain(), LN0->getBasePtr(),
5634 MemVT, LN0->getMemOperand());
5635 CombineTo(N, ExtLoad);
5636 CombineTo(N0.getNode(),
5637 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5638 N0.getValueType(), ExtLoad),
5639 ExtLoad.getValue(1));
5640 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5644 if (N0.getOpcode() == ISD::SETCC) {
5646 // aext(setcc) -> vsetcc
5647 // aext(setcc) -> truncate(vsetcc)
5648 // aext(setcc) -> aext(vsetcc)
5649 // Only do this before legalize for now.
5650 if (VT.isVector() && !LegalOperations) {
5651 EVT N0VT = N0.getOperand(0).getValueType();
5652 // We know that the # elements of the results is the same as the
5653 // # elements of the compare (and the # elements of the compare result
5654 // for that matter). Check to see that they are the same size. If so,
5655 // we know that the element size of the sext'd result matches the
5656 // element size of the compare operands.
5657 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5658 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5660 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5661 // If the desired elements are smaller or larger than the source
5662 // elements we can use a matching integer vector type and then
5663 // truncate/any extend
5665 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5667 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5669 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5670 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5676 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5677 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5678 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5686 /// See if the specified operand can be simplified with the knowledge that only
5687 /// the bits specified by Mask are used. If so, return the simpler operand,
5688 /// otherwise return a null SDValue.
5689 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5690 switch (V.getOpcode()) {
5692 case ISD::Constant: {
5693 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5694 assert(CV && "Const value should be ConstSDNode.");
5695 const APInt &CVal = CV->getAPIntValue();
5696 APInt NewVal = CVal & Mask;
5698 return DAG.getConstant(NewVal, V.getValueType());
5703 // If the LHS or RHS don't contribute bits to the or, drop them.
5704 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5705 return V.getOperand(1);
5706 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5707 return V.getOperand(0);
5710 // Only look at single-use SRLs.
5711 if (!V.getNode()->hasOneUse())
5713 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5714 // See if we can recursively simplify the LHS.
5715 unsigned Amt = RHSC->getZExtValue();
5717 // Watch out for shift count overflow though.
5718 if (Amt >= Mask.getBitWidth()) break;
5719 APInt NewMask = Mask << Amt;
5720 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5721 if (SimplifyLHS.getNode())
5722 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5723 SimplifyLHS, V.getOperand(1));
5729 /// If the result of a wider load is shifted to right of N bits and then
5730 /// truncated to a narrower type and where N is a multiple of number of bits of
5731 /// the narrower type, transform it to a narrower load from address + N / num of
5732 /// bits of new type. If the result is to be extended, also fold the extension
5733 /// to form a extending load.
5734 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5735 unsigned Opc = N->getOpcode();
5737 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5738 SDValue N0 = N->getOperand(0);
5739 EVT VT = N->getValueType(0);
5742 // This transformation isn't valid for vector loads.
5746 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5748 if (Opc == ISD::SIGN_EXTEND_INREG) {
5749 ExtType = ISD::SEXTLOAD;
5750 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5751 } else if (Opc == ISD::SRL) {
5752 // Another special-case: SRL is basically zero-extending a narrower value.
5753 ExtType = ISD::ZEXTLOAD;
5755 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5756 if (!N01) return SDValue();
5757 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5758 VT.getSizeInBits() - N01->getZExtValue());
5760 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5763 unsigned EVTBits = ExtVT.getSizeInBits();
5765 // Do not generate loads of non-round integer types since these can
5766 // be expensive (and would be wrong if the type is not byte sized).
5767 if (!ExtVT.isRound())
5771 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5772 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5773 ShAmt = N01->getZExtValue();
5774 // Is the shift amount a multiple of size of VT?
5775 if ((ShAmt & (EVTBits-1)) == 0) {
5776 N0 = N0.getOperand(0);
5777 // Is the load width a multiple of size of VT?
5778 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782 // At this point, we must have a load or else we can't do the transform.
5783 if (!isa<LoadSDNode>(N0)) return SDValue();
5785 // Because a SRL must be assumed to *need* to zero-extend the high bits
5786 // (as opposed to anyext the high bits), we can't combine the zextload
5787 // lowering of SRL and an sextload.
5788 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5791 // If the shift amount is larger than the input type then we're not
5792 // accessing any of the loaded bytes. If the load was a zextload/extload
5793 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5794 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5799 // If the load is shifted left (and the result isn't shifted back right),
5800 // we can fold the truncate through the shift.
5801 unsigned ShLeftAmt = 0;
5802 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5803 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5804 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5805 ShLeftAmt = N01->getZExtValue();
5806 N0 = N0.getOperand(0);
5810 // If we haven't found a load, we can't narrow it. Don't transform one with
5811 // multiple uses, this would require adding a new load.
5812 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5815 // Don't change the width of a volatile load.
5816 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5817 if (LN0->isVolatile())
5820 // Verify that we are actually reducing a load width here.
5821 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5824 // For the transform to be legal, the load must produce only two values
5825 // (the value loaded and the chain). Don't transform a pre-increment
5826 // load, for example, which produces an extra value. Otherwise the
5827 // transformation is not equivalent, and the downstream logic to replace
5828 // uses gets things wrong.
5829 if (LN0->getNumValues() > 2)
5832 // If the load that we're shrinking is an extload and we're not just
5833 // discarding the extension we can't simply shrink the load. Bail.
5834 // TODO: It would be possible to merge the extensions in some cases.
5835 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5836 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5839 EVT PtrType = N0.getOperand(1).getValueType();
5841 if (PtrType == MVT::Untyped || PtrType.isExtended())
5842 // It's not possible to generate a constant of extended or untyped type.
5845 // For big endian targets, we need to adjust the offset to the pointer to
5846 // load the correct bytes.
5847 if (TLI.isBigEndian()) {
5848 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5849 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5850 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5853 uint64_t PtrOff = ShAmt / 8;
5854 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5855 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5856 PtrType, LN0->getBasePtr(),
5857 DAG.getConstant(PtrOff, PtrType));
5858 AddToWorklist(NewPtr.getNode());
5861 if (ExtType == ISD::NON_EXTLOAD)
5862 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5863 LN0->getPointerInfo().getWithOffset(PtrOff),
5864 LN0->isVolatile(), LN0->isNonTemporal(),
5865 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5867 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5868 LN0->getPointerInfo().getWithOffset(PtrOff),
5869 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5870 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5872 // Replace the old load's chain with the new load's chain.
5873 WorklistRemover DeadNodes(*this);
5874 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5876 // Shift the result left, if we've swallowed a left shift.
5877 SDValue Result = Load;
5878 if (ShLeftAmt != 0) {
5879 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5880 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5882 // If the shift amount is as large as the result size (but, presumably,
5883 // no larger than the source) then the useful bits of the result are
5884 // zero; we can't simply return the shortened shift, because the result
5885 // of that operation is undefined.
5886 if (ShLeftAmt >= VT.getSizeInBits())
5887 Result = DAG.getConstant(0, VT);
5889 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5890 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5893 // Return the new loaded value.
5897 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5898 SDValue N0 = N->getOperand(0);
5899 SDValue N1 = N->getOperand(1);
5900 EVT VT = N->getValueType(0);
5901 EVT EVT = cast<VTSDNode>(N1)->getVT();
5902 unsigned VTBits = VT.getScalarType().getSizeInBits();
5903 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5905 // fold (sext_in_reg c1) -> c1
5906 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5907 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5909 // If the input is already sign extended, just drop the extension.
5910 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5913 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5914 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5915 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5917 N0.getOperand(0), N1);
5919 // fold (sext_in_reg (sext x)) -> (sext x)
5920 // fold (sext_in_reg (aext x)) -> (sext x)
5921 // if x is small enough.
5922 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5923 SDValue N00 = N0.getOperand(0);
5924 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5925 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5926 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5929 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5930 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5931 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5933 // fold operands of sext_in_reg based on knowledge that the top bits are not
5935 if (SimplifyDemandedBits(SDValue(N, 0)))
5936 return SDValue(N, 0);
5938 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5939 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5940 SDValue NarrowLoad = ReduceLoadWidth(N);
5941 if (NarrowLoad.getNode())
5944 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5945 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5946 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5947 if (N0.getOpcode() == ISD::SRL) {
5948 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5949 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5950 // We can turn this into an SRA iff the input to the SRL is already sign
5952 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5953 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5954 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5955 N0.getOperand(0), N0.getOperand(1));
5959 // fold (sext_inreg (extload x)) -> (sextload x)
5960 if (ISD::isEXTLoad(N0.getNode()) &&
5961 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5962 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5963 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5964 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5966 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5968 LN0->getBasePtr(), EVT,
5969 LN0->getMemOperand());
5970 CombineTo(N, ExtLoad);
5971 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5972 AddToWorklist(ExtLoad.getNode());
5973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5975 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5976 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5978 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5979 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5980 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5981 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5982 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5984 LN0->getBasePtr(), EVT,
5985 LN0->getMemOperand());
5986 CombineTo(N, ExtLoad);
5987 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5991 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5992 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5993 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5994 N0.getOperand(1), false);
5995 if (BSwap.getNode())
5996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6001 // into a build_vector.
6002 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6003 SmallVector<SDValue, 8> Elts;
6004 unsigned NumElts = N0->getNumOperands();
6005 unsigned ShAmt = VTBits - EVTBits;
6007 for (unsigned i = 0; i != NumElts; ++i) {
6008 SDValue Op = N0->getOperand(i);
6009 if (Op->getOpcode() == ISD::UNDEF) {
6014 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6015 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6016 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6017 Op.getValueType()));
6020 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6026 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6027 SDValue N0 = N->getOperand(0);
6028 EVT VT = N->getValueType(0);
6029 bool isLE = TLI.isLittleEndian();
6032 if (N0.getValueType() == N->getValueType(0))
6034 // fold (truncate c1) -> c1
6035 if (isa<ConstantSDNode>(N0))
6036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6037 // fold (truncate (truncate x)) -> (truncate x)
6038 if (N0.getOpcode() == ISD::TRUNCATE)
6039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6040 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6041 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6042 N0.getOpcode() == ISD::SIGN_EXTEND ||
6043 N0.getOpcode() == ISD::ANY_EXTEND) {
6044 if (N0.getOperand(0).getValueType().bitsLT(VT))
6045 // if the source is smaller than the dest, we still need an extend
6046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6048 if (N0.getOperand(0).getValueType().bitsGT(VT))
6049 // if the source is larger than the dest, than we just need the truncate
6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6051 // if the source and dest are the same type, we can drop both the extend
6052 // and the truncate.
6053 return N0.getOperand(0);
6056 // Fold extract-and-trunc into a narrow extract. For example:
6057 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6058 // i32 y = TRUNCATE(i64 x)
6060 // v16i8 b = BITCAST (v2i64 val)
6061 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6063 // Note: We only run this optimization after type legalization (which often
6064 // creates this pattern) and before operation legalization after which
6065 // we need to be more careful about the vector instructions that we generate.
6066 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6067 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6069 EVT VecTy = N0.getOperand(0).getValueType();
6070 EVT ExTy = N0.getValueType();
6071 EVT TrTy = N->getValueType(0);
6073 unsigned NumElem = VecTy.getVectorNumElements();
6074 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6076 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6077 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6079 SDValue EltNo = N0->getOperand(1);
6080 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6081 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6082 EVT IndexTy = TLI.getVectorIdxTy();
6083 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6085 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6086 NVT, N0.getOperand(0));
6088 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6090 DAG.getConstant(Index, IndexTy));
6094 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6095 if (N0.getOpcode() == ISD::SELECT) {
6096 EVT SrcVT = N0.getValueType();
6097 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6098 TLI.isTruncateFree(SrcVT, VT)) {
6100 SDValue Cond = N0.getOperand(0);
6101 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6102 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6103 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107 // Fold a series of buildvector, bitcast, and truncate if possible.
6109 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6110 // (2xi32 (buildvector x, y)).
6111 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6112 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6113 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6114 N0.getOperand(0).hasOneUse()) {
6116 SDValue BuildVect = N0.getOperand(0);
6117 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6118 EVT TruncVecEltTy = VT.getVectorElementType();
6120 // Check that the element types match.
6121 if (BuildVectEltTy == TruncVecEltTy) {
6122 // Now we only need to compute the offset of the truncated elements.
6123 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6124 unsigned TruncVecNumElts = VT.getVectorNumElements();
6125 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6127 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6128 "Invalid number of elements");
6130 SmallVector<SDValue, 8> Opnds;
6131 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6132 Opnds.push_back(BuildVect.getOperand(i));
6134 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138 // See if we can simplify the input to this truncate through knowledge that
6139 // only the low bits are being used.
6140 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6141 // Currently we only perform this optimization on scalars because vectors
6142 // may have different active low bits.
6143 if (!VT.isVector()) {
6145 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6146 VT.getSizeInBits()));
6147 if (Shorter.getNode())
6148 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6150 // fold (truncate (load x)) -> (smaller load x)
6151 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6152 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6153 SDValue Reduced = ReduceLoadWidth(N);
6154 if (Reduced.getNode())
6156 // Handle the case where the load remains an extending load even
6157 // after truncation.
6158 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6159 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6160 if (!LN0->isVolatile() &&
6161 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6162 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6163 VT, LN0->getChain(), LN0->getBasePtr(),
6165 LN0->getMemOperand());
6166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6171 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6172 // where ... are all 'undef'.
6173 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6174 SmallVector<EVT, 8> VTs;
6177 unsigned NumDefs = 0;
6179 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6180 SDValue X = N0.getOperand(i);
6181 if (X.getOpcode() != ISD::UNDEF) {
6186 // Stop if more than one members are non-undef.
6189 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6190 VT.getVectorElementType(),
6191 X.getValueType().getVectorNumElements()));
6195 return DAG.getUNDEF(VT);
6198 assert(V.getNode() && "The single defined operand is empty!");
6199 SmallVector<SDValue, 8> Opnds;
6200 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6202 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6205 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6206 AddToWorklist(NV.getNode());
6207 Opnds.push_back(NV);
6209 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213 // Simplify the operands using demanded-bits information.
6214 if (!VT.isVector() &&
6215 SimplifyDemandedBits(SDValue(N, 0)))
6216 return SDValue(N, 0);
6221 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6222 SDValue Elt = N->getOperand(i);
6223 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6224 return Elt.getNode();
6225 return Elt.getOperand(Elt.getResNo()).getNode();
6228 /// build_pair (load, load) -> load
6229 /// if load locations are consecutive.
6230 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6231 assert(N->getOpcode() == ISD::BUILD_PAIR);
6233 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6234 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6235 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6236 LD1->getAddressSpace() != LD2->getAddressSpace())
6238 EVT LD1VT = LD1->getValueType(0);
6240 if (ISD::isNON_EXTLoad(LD2) &&
6242 // If both are volatile this would reduce the number of volatile loads.
6243 // If one is volatile it might be ok, but play conservative and bail out.
6244 !LD1->isVolatile() &&
6245 !LD2->isVolatile() &&
6246 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6247 unsigned Align = LD1->getAlignment();
6248 unsigned NewAlign = TLI.getDataLayout()->
6249 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6251 if (NewAlign <= Align &&
6252 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6253 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6254 LD1->getBasePtr(), LD1->getPointerInfo(),
6255 false, false, false, Align);
6261 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6262 SDValue N0 = N->getOperand(0);
6263 EVT VT = N->getValueType(0);
6265 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6266 // Only do this before legalize, since afterward the target may be depending
6267 // on the bitconvert.
6268 // First check to see if this is all constant.
6270 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6272 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6274 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6275 assert(!DestEltVT.isVector() &&
6276 "Element type of vector ValueType must not be vector!");
6278 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6281 // If the input is a constant, let getNode fold it.
6282 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6283 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6284 if (Res.getNode() != N) {
6285 if (!LegalOperations ||
6286 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6289 // Folding it resulted in an illegal node, and it's too late to
6290 // do that. Clean up the old node and forego the transformation.
6291 // Ideally this won't happen very often, because instcombine
6292 // and the earlier dagcombine runs (where illegal nodes are
6293 // permitted) should have folded most of them already.
6294 deleteAndRecombine(Res.getNode());
6298 // (conv (conv x, t1), t2) -> (conv x, t2)
6299 if (N0.getOpcode() == ISD::BITCAST)
6300 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6303 // fold (conv (load x)) -> (load (conv*)x)
6304 // If the resultant load doesn't need a higher alignment than the original!
6305 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6306 // Do not change the width of a volatile load.
6307 !cast<LoadSDNode>(N0)->isVolatile() &&
6308 // Do not remove the cast if the types differ in endian layout.
6309 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6310 TLI.hasBigEndianPartOrdering(VT) &&
6311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6312 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6314 unsigned Align = TLI.getDataLayout()->
6315 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6316 unsigned OrigAlign = LN0->getAlignment();
6318 if (Align <= OrigAlign) {
6319 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6320 LN0->getBasePtr(), LN0->getPointerInfo(),
6321 LN0->isVolatile(), LN0->isNonTemporal(),
6322 LN0->isInvariant(), OrigAlign,
6324 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6329 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6330 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6331 // This often reduces constant pool loads.
6332 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6333 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6334 N0.getNode()->hasOneUse() && VT.isInteger() &&
6335 !VT.isVector() && !N0.getValueType().isVector()) {
6336 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6338 AddToWorklist(NewConv.getNode());
6340 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6341 if (N0.getOpcode() == ISD::FNEG)
6342 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6343 NewConv, DAG.getConstant(SignBit, VT));
6344 assert(N0.getOpcode() == ISD::FABS);
6345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6346 NewConv, DAG.getConstant(~SignBit, VT));
6349 // fold (bitconvert (fcopysign cst, x)) ->
6350 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6351 // Note that we don't handle (copysign x, cst) because this can always be
6352 // folded to an fneg or fabs.
6353 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6354 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6355 VT.isInteger() && !VT.isVector()) {
6356 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6357 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6358 if (isTypeLegal(IntXVT)) {
6359 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6360 IntXVT, N0.getOperand(1));
6361 AddToWorklist(X.getNode());
6363 // If X has a different width than the result/lhs, sext it or truncate it.
6364 unsigned VTWidth = VT.getSizeInBits();
6365 if (OrigXWidth < VTWidth) {
6366 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6367 AddToWorklist(X.getNode());
6368 } else if (OrigXWidth > VTWidth) {
6369 // To get the sign bit in the right place, we have to shift it right
6370 // before truncating.
6371 X = DAG.getNode(ISD::SRL, SDLoc(X),
6372 X.getValueType(), X,
6373 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6374 AddToWorklist(X.getNode());
6375 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6376 AddToWorklist(X.getNode());
6379 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6380 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6381 X, DAG.getConstant(SignBit, VT));
6382 AddToWorklist(X.getNode());
6384 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6385 VT, N0.getOperand(0));
6386 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6387 Cst, DAG.getConstant(~SignBit, VT));
6388 AddToWorklist(Cst.getNode());
6390 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6395 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6396 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6397 if (CombineLD.getNode())
6404 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6405 EVT VT = N->getValueType(0);
6406 return CombineConsecutiveLoads(N, VT);
6409 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6410 /// operands. DstEltVT indicates the destination element value type.
6411 SDValue DAGCombiner::
6412 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6413 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6415 // If this is already the right type, we're done.
6416 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6418 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6419 unsigned DstBitSize = DstEltVT.getSizeInBits();
6421 // If this is a conversion of N elements of one type to N elements of another
6422 // type, convert each element. This handles FP<->INT cases.
6423 if (SrcBitSize == DstBitSize) {
6424 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6425 BV->getValueType(0).getVectorNumElements());
6427 // Due to the FP element handling below calling this routine recursively,
6428 // we can end up with a scalar-to-vector node here.
6429 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6430 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6431 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6432 DstEltVT, BV->getOperand(0)));
6434 SmallVector<SDValue, 8> Ops;
6435 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6436 SDValue Op = BV->getOperand(i);
6437 // If the vector element type is not legal, the BUILD_VECTOR operands
6438 // are promoted and implicitly truncated. Make that explicit here.
6439 if (Op.getValueType() != SrcEltVT)
6440 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6441 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6443 AddToWorklist(Ops.back().getNode());
6445 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6448 // Otherwise, we're growing or shrinking the elements. To avoid having to
6449 // handle annoying details of growing/shrinking FP values, we convert them to
6451 if (SrcEltVT.isFloatingPoint()) {
6452 // Convert the input float vector to a int vector where the elements are the
6454 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6455 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6456 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6460 // Now we know the input is an integer vector. If the output is a FP type,
6461 // convert to integer first, then to FP of the right size.
6462 if (DstEltVT.isFloatingPoint()) {
6463 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6464 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6465 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6467 // Next, convert to FP elements of the same size.
6468 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6471 // Okay, we know the src/dst types are both integers of differing types.
6472 // Handling growing first.
6473 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6474 if (SrcBitSize < DstBitSize) {
6475 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6477 SmallVector<SDValue, 8> Ops;
6478 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6479 i += NumInputsPerOutput) {
6480 bool isLE = TLI.isLittleEndian();
6481 APInt NewBits = APInt(DstBitSize, 0);
6482 bool EltIsUndef = true;
6483 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6484 // Shift the previously computed bits over.
6485 NewBits <<= SrcBitSize;
6486 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6487 if (Op.getOpcode() == ISD::UNDEF) continue;
6490 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6491 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6495 Ops.push_back(DAG.getUNDEF(DstEltVT));
6497 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6500 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6501 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6504 // Finally, this must be the case where we are shrinking elements: each input
6505 // turns into multiple outputs.
6506 bool isS2V = ISD::isScalarToVector(BV);
6507 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6508 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6509 NumOutputsPerInput*BV->getNumOperands());
6510 SmallVector<SDValue, 8> Ops;
6512 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6513 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6514 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6515 Ops.push_back(DAG.getUNDEF(DstEltVT));
6519 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6520 getAPIntValue().zextOrTrunc(SrcBitSize);
6522 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6523 APInt ThisVal = OpVal.trunc(DstBitSize);
6524 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6525 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6526 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6527 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6529 OpVal = OpVal.lshr(DstBitSize);
6532 // For big endian targets, swap the order of the pieces of each element.
6533 if (TLI.isBigEndian())
6534 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6537 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6540 SDValue DAGCombiner::visitFADD(SDNode *N) {
6541 SDValue N0 = N->getOperand(0);
6542 SDValue N1 = N->getOperand(1);
6543 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6544 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6545 EVT VT = N->getValueType(0);
6546 const TargetOptions &Options = DAG.getTarget().Options;
6549 if (VT.isVector()) {
6550 SDValue FoldedVOp = SimplifyVBinOp(N);
6551 if (FoldedVOp.getNode()) return FoldedVOp;
6554 // fold (fadd c1, c2) -> c1 + c2
6556 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6558 // canonicalize constant to RHS
6559 if (N0CFP && !N1CFP)
6560 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6562 // fold (fadd A, (fneg B)) -> (fsub A, B)
6563 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6564 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6565 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6566 GetNegatedExpression(N1, DAG, LegalOperations));
6568 // fold (fadd (fneg A), B) -> (fsub B, A)
6569 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6570 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6571 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6572 GetNegatedExpression(N0, DAG, LegalOperations));
6574 // If 'unsafe math' is enabled, fold lots of things.
6575 if (Options.UnsafeFPMath) {
6576 // No FP constant should be created after legalization as Instruction
6577 // Selection pass has a hard time dealing with FP constants.
6578 bool AllowNewConst = (Level < AfterLegalizeDAG);
6580 // fold (fadd A, 0) -> A
6581 if (N1CFP && N1CFP->getValueAPF().isZero())
6584 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6585 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6586 isa<ConstantFPSDNode>(N0.getOperand(1)))
6587 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6588 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589 N0.getOperand(1), N1));
6591 // If allowed, fold (fadd (fneg x), x) -> 0.0
6592 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6593 return DAG.getConstantFP(0.0, VT);
6595 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6596 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6597 return DAG.getConstantFP(0.0, VT);
6599 // We can fold chains of FADD's of the same value into multiplications.
6600 // This transform is not safe in general because we are reducing the number
6601 // of rounding steps.
6602 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6603 if (N0.getOpcode() == ISD::FMUL) {
6604 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6605 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6607 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6608 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6609 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6611 DAG.getConstantFP(1.0, VT));
6612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6617 N1.getOperand(0) == N1.getOperand(1) &&
6618 N0.getOperand(0) == N1.getOperand(0)) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(2.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623 N0.getOperand(0), NewCFP);
6627 if (N1.getOpcode() == ISD::FMUL) {
6628 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6629 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6631 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6632 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635 DAG.getConstantFP(1.0, VT));
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6639 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6640 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6641 N0.getOperand(0) == N0.getOperand(1) &&
6642 N1.getOperand(0) == N0.getOperand(0)) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(2.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6650 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6651 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6652 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6653 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6654 (N0.getOperand(0) == N1))
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656 N1, DAG.getConstantFP(3.0, VT));
6659 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6660 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6661 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6662 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6663 N1.getOperand(0) == N0)
6664 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6665 N0, DAG.getConstantFP(3.0, VT));
6668 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6669 if (AllowNewConst &&
6670 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6671 N0.getOperand(0) == N0.getOperand(1) &&
6672 N1.getOperand(0) == N1.getOperand(1) &&
6673 N0.getOperand(0) == N1.getOperand(0))
6674 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6675 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6677 } // enable-unsafe-fp-math
6679 // FADD -> FMA combines:
6680 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6683 ->getTargetLowering()
6684 ->isFMAFasterThanFMulAndFAdd(VT) &&
6685 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6687 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6688 if (N0.getOpcode() == ISD::FMUL &&
6689 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6690 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6691 N0.getOperand(0), N0.getOperand(1), N1);
6693 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6694 // Note: Commutes FADD operands.
6695 if (N1.getOpcode() == ISD::FMUL &&
6696 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6697 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6698 N1.getOperand(0), N1.getOperand(1), N0);
6704 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6705 SDValue N0 = N->getOperand(0);
6706 SDValue N1 = N->getOperand(1);
6707 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6708 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6709 EVT VT = N->getValueType(0);
6711 const TargetOptions &Options = DAG.getTarget().Options;
6714 if (VT.isVector()) {
6715 SDValue FoldedVOp = SimplifyVBinOp(N);
6716 if (FoldedVOp.getNode()) return FoldedVOp;
6719 // fold (fsub c1, c2) -> c1-c2
6721 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6723 // fold (fsub A, (fneg B)) -> (fadd A, B)
6724 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6725 return DAG.getNode(ISD::FADD, dl, VT, N0,
6726 GetNegatedExpression(N1, DAG, LegalOperations));
6728 // If 'unsafe math' is enabled, fold lots of things.
6729 if (Options.UnsafeFPMath) {
6731 if (N1CFP && N1CFP->getValueAPF().isZero())
6734 // (fsub 0, B) -> -B
6735 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6736 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6737 return GetNegatedExpression(N1, DAG, LegalOperations);
6738 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6739 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6742 // (fsub x, x) -> 0.0
6744 return DAG.getConstantFP(0.0f, VT);
6746 // (fsub x, (fadd x, y)) -> (fneg y)
6747 // (fsub x, (fadd y, x)) -> (fneg y)
6748 if (N1.getOpcode() == ISD::FADD) {
6749 SDValue N10 = N1->getOperand(0);
6750 SDValue N11 = N1->getOperand(1);
6752 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6753 return GetNegatedExpression(N11, DAG, LegalOperations);
6755 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6756 return GetNegatedExpression(N10, DAG, LegalOperations);
6760 // FSUB -> FMA combines:
6761 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6762 DAG.getTarget().getSubtargetImpl()
6763 ->getTargetLowering()
6764 ->isFMAFasterThanFMulAndFAdd(VT) &&
6765 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6767 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6768 if (N0.getOpcode() == ISD::FMUL &&
6769 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6770 return DAG.getNode(ISD::FMA, dl, VT,
6771 N0.getOperand(0), N0.getOperand(1),
6772 DAG.getNode(ISD::FNEG, dl, VT, N1));
6774 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6775 // Note: Commutes FSUB operands.
6776 if (N1.getOpcode() == ISD::FMUL &&
6777 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6778 return DAG.getNode(ISD::FMA, dl, VT,
6779 DAG.getNode(ISD::FNEG, dl, VT,
6781 N1.getOperand(1), N0);
6783 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6784 if (N0.getOpcode() == ISD::FNEG &&
6785 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6786 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6787 TLI.enableAggressiveFMAFusion(VT))) {
6788 SDValue N00 = N0.getOperand(0).getOperand(0);
6789 SDValue N01 = N0.getOperand(0).getOperand(1);
6790 return DAG.getNode(ISD::FMA, dl, VT,
6791 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6792 DAG.getNode(ISD::FNEG, dl, VT, N1));
6799 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6800 SDValue N0 = N->getOperand(0);
6801 SDValue N1 = N->getOperand(1);
6802 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6803 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6804 EVT VT = N->getValueType(0);
6805 const TargetOptions &Options = DAG.getTarget().Options;
6808 if (VT.isVector()) {
6809 // This just handles C1 * C2 for vectors. Other vector folds are below.
6810 SDValue FoldedVOp = SimplifyVBinOp(N);
6811 if (FoldedVOp.getNode())
6813 // Canonicalize vector constant to RHS.
6814 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6815 N1.getOpcode() != ISD::BUILD_VECTOR)
6816 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6817 if (BV0->isConstant())
6818 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6821 // fold (fmul c1, c2) -> c1*c2
6823 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6825 // canonicalize constant to RHS
6826 if (N0CFP && !N1CFP)
6827 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6829 // fold (fmul A, 1.0) -> A
6830 if (N1CFP && N1CFP->isExactlyValue(1.0))
6833 if (Options.UnsafeFPMath) {
6834 // fold (fmul A, 0) -> 0
6835 if (N1CFP && N1CFP->getValueAPF().isZero())
6838 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6839 if (N0.getOpcode() == ISD::FMUL) {
6840 // Fold scalars or any vector constants (not just splats).
6841 // This fold is done in general by InstCombine, but extra fmul insts
6842 // may have been generated during lowering.
6843 SDValue N01 = N0.getOperand(1);
6844 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6845 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6846 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6847 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6849 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6850 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6854 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6855 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6856 // during an early run of DAGCombiner can prevent folding with fmuls
6857 // inserted during lowering.
6858 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6860 const SDValue Two = DAG.getConstantFP(2.0, VT);
6861 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6866 // fold (fmul X, 2.0) -> (fadd X, X)
6867 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6868 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6870 // fold (fmul X, -1.0) -> (fneg X)
6871 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6872 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6873 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6875 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6876 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6877 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6878 // Both can be negated for free, check to see if at least one is cheaper
6880 if (LHSNeg == 2 || RHSNeg == 2)
6881 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6882 GetNegatedExpression(N0, DAG, LegalOperations),
6883 GetNegatedExpression(N1, DAG, LegalOperations));
6890 SDValue DAGCombiner::visitFMA(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
6893 SDValue N2 = N->getOperand(2);
6894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6895 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6896 EVT VT = N->getValueType(0);
6898 const TargetOptions &Options = DAG.getTarget().Options;
6900 // Constant fold FMA.
6901 if (isa<ConstantFPSDNode>(N0) &&
6902 isa<ConstantFPSDNode>(N1) &&
6903 isa<ConstantFPSDNode>(N2)) {
6904 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6907 if (Options.UnsafeFPMath) {
6908 if (N0CFP && N0CFP->isZero())
6910 if (N1CFP && N1CFP->isZero())
6913 if (N0CFP && N0CFP->isExactlyValue(1.0))
6914 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6915 if (N1CFP && N1CFP->isExactlyValue(1.0))
6916 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6918 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6919 if (N0CFP && !N1CFP)
6920 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6922 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6923 if (Options.UnsafeFPMath && N1CFP &&
6924 N2.getOpcode() == ISD::FMUL &&
6925 N0 == N2.getOperand(0) &&
6926 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6927 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6928 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6932 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6933 if (Options.UnsafeFPMath &&
6934 N0.getOpcode() == ISD::FMUL && N1CFP &&
6935 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6936 return DAG.getNode(ISD::FMA, dl, VT,
6938 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6942 // (fma x, 1, y) -> (fadd x, y)
6943 // (fma x, -1, y) -> (fadd (fneg x), y)
6945 if (N1CFP->isExactlyValue(1.0))
6946 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6948 if (N1CFP->isExactlyValue(-1.0) &&
6949 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6950 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6951 AddToWorklist(RHSNeg.getNode());
6952 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6956 // (fma x, c, x) -> (fmul x, (c+1))
6957 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6958 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6959 DAG.getNode(ISD::FADD, dl, VT,
6960 N1, DAG.getConstantFP(1.0, VT)));
6962 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6963 if (Options.UnsafeFPMath && N1CFP &&
6964 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6965 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6966 DAG.getNode(ISD::FADD, dl, VT,
6967 N1, DAG.getConstantFP(-1.0, VT)));
6973 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6974 SDValue N0 = N->getOperand(0);
6975 SDValue N1 = N->getOperand(1);
6976 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6977 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6978 EVT VT = N->getValueType(0);
6980 const TargetOptions &Options = DAG.getTarget().Options;
6983 if (VT.isVector()) {
6984 SDValue FoldedVOp = SimplifyVBinOp(N);
6985 if (FoldedVOp.getNode()) return FoldedVOp;
6988 // fold (fdiv c1, c2) -> c1/c2
6990 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6992 if (Options.UnsafeFPMath) {
6993 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6995 // Compute the reciprocal 1.0 / c2.
6996 APFloat N1APF = N1CFP->getValueAPF();
6997 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6998 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6999 // Only do the transform if the reciprocal is a legal fp immediate that
7000 // isn't too nasty (eg NaN, denormal, ...).
7001 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7002 (!LegalOperations ||
7003 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7004 // backend)... we should handle this gracefully after Legalize.
7005 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7006 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7007 TLI.isFPImmLegal(Recip, VT)))
7008 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7009 DAG.getConstantFP(Recip, VT));
7012 // If this FDIV is part of a reciprocal square root, it may be folded
7013 // into a target-specific square root estimate instruction.
7014 if (N1.getOpcode() == ISD::FSQRT) {
7015 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7016 AddToWorklist(RV.getNode());
7017 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7019 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7020 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7021 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7022 AddToWorklist(RV.getNode());
7023 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7024 AddToWorklist(RV.getNode());
7025 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7027 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7028 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7029 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7030 AddToWorklist(RV.getNode());
7031 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7032 AddToWorklist(RV.getNode());
7033 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7035 } else if (N1.getOpcode() == ISD::FMUL) {
7036 // Look through an FMUL. Even though this won't remove the FDIV directly,
7037 // it's still worthwhile to get rid of the FSQRT if possible.
7040 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7041 SqrtOp = N1.getOperand(0);
7042 OtherOp = N1.getOperand(1);
7043 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7044 SqrtOp = N1.getOperand(1);
7045 OtherOp = N1.getOperand(0);
7047 if (SqrtOp.getNode()) {
7048 // We found a FSQRT, so try to make this fold:
7049 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7050 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7051 AddToWorklist(RV.getNode());
7052 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7053 AddToWorklist(RV.getNode());
7054 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7059 // Fold into a reciprocal estimate and multiply instead of a real divide.
7060 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7061 AddToWorklist(RV.getNode());
7062 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7066 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7067 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7068 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7069 // Both can be negated for free, check to see if at least one is cheaper
7071 if (LHSNeg == 2 || RHSNeg == 2)
7072 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7073 GetNegatedExpression(N0, DAG, LegalOperations),
7074 GetNegatedExpression(N1, DAG, LegalOperations));
7081 SDValue DAGCombiner::visitFREM(SDNode *N) {
7082 SDValue N0 = N->getOperand(0);
7083 SDValue N1 = N->getOperand(1);
7084 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7085 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7086 EVT VT = N->getValueType(0);
7088 // fold (frem c1, c2) -> fmod(c1,c2)
7090 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7095 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7096 if (DAG.getTarget().Options.UnsafeFPMath) {
7097 // Compute this as 1/(1/sqrt(X)): the reciprocal of the reciprocal sqrt.
7098 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7099 AddToWorklist(RV.getNode());
7100 RV = BuildReciprocalEstimate(RV);
7102 // Unfortunately, RV is now NaN if the input was exactly 0.
7103 // Select out this case and force the answer to 0.
7104 EVT VT = RV.getValueType();
7106 SDValue Zero = DAG.getConstantFP(0.0, VT);
7108 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7109 N->getOperand(0), Zero, ISD::SETEQ);
7110 AddToWorklist(ZeroCmp.getNode());
7111 AddToWorklist(RV.getNode());
7113 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7114 SDLoc(N), VT, ZeroCmp, Zero, RV);
7122 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7123 SDValue N0 = N->getOperand(0);
7124 SDValue N1 = N->getOperand(1);
7125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7126 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7127 EVT VT = N->getValueType(0);
7129 if (N0CFP && N1CFP) // Constant fold
7130 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7133 const APFloat& V = N1CFP->getValueAPF();
7134 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7135 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7136 if (!V.isNegative()) {
7137 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7138 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7140 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7141 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7142 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7146 // copysign(fabs(x), y) -> copysign(x, y)
7147 // copysign(fneg(x), y) -> copysign(x, y)
7148 // copysign(copysign(x,z), y) -> copysign(x, y)
7149 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7150 N0.getOpcode() == ISD::FCOPYSIGN)
7151 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7152 N0.getOperand(0), N1);
7154 // copysign(x, abs(y)) -> abs(x)
7155 if (N1.getOpcode() == ISD::FABS)
7156 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7158 // copysign(x, copysign(y,z)) -> copysign(x, z)
7159 if (N1.getOpcode() == ISD::FCOPYSIGN)
7160 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7161 N0, N1.getOperand(1));
7163 // copysign(x, fp_extend(y)) -> copysign(x, y)
7164 // copysign(x, fp_round(y)) -> copysign(x, y)
7165 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7166 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7167 N0, N1.getOperand(0));
7172 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7173 SDValue N0 = N->getOperand(0);
7174 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7175 EVT VT = N->getValueType(0);
7176 EVT OpVT = N0.getValueType();
7178 // fold (sint_to_fp c1) -> c1fp
7180 // ...but only if the target supports immediate floating-point values
7181 (!LegalOperations ||
7182 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7183 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7185 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7186 // but UINT_TO_FP is legal on this target, try to convert.
7187 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7188 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7189 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7190 if (DAG.SignBitIsZero(N0))
7191 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7194 // The next optimizations are desirable only if SELECT_CC can be lowered.
7195 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7196 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7197 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7199 (!LegalOperations ||
7200 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7202 { N0.getOperand(0), N0.getOperand(1),
7203 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7205 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7208 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7209 // (select_cc x, y, 1.0, 0.0,, cc)
7210 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7211 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7212 (!LegalOperations ||
7213 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7215 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7216 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7217 N0.getOperand(0).getOperand(2) };
7218 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7225 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7226 SDValue N0 = N->getOperand(0);
7227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7228 EVT VT = N->getValueType(0);
7229 EVT OpVT = N0.getValueType();
7231 // fold (uint_to_fp c1) -> c1fp
7233 // ...but only if the target supports immediate floating-point values
7234 (!LegalOperations ||
7235 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7236 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7238 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7239 // but SINT_TO_FP is legal on this target, try to convert.
7240 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7241 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7242 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7243 if (DAG.SignBitIsZero(N0))
7244 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7247 // The next optimizations are desirable only if SELECT_CC can be lowered.
7248 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7249 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7251 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7252 (!LegalOperations ||
7253 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7255 { N0.getOperand(0), N0.getOperand(1),
7256 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7258 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7265 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7266 SDValue N0 = N->getOperand(0);
7267 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7268 EVT VT = N->getValueType(0);
7270 // fold (fp_to_sint c1fp) -> c1
7272 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7277 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7278 SDValue N0 = N->getOperand(0);
7279 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7280 EVT VT = N->getValueType(0);
7282 // fold (fp_to_uint c1fp) -> c1
7284 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7289 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7290 SDValue N0 = N->getOperand(0);
7291 SDValue N1 = N->getOperand(1);
7292 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7293 EVT VT = N->getValueType(0);
7295 // fold (fp_round c1fp) -> c1fp
7297 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7299 // fold (fp_round (fp_extend x)) -> x
7300 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7301 return N0.getOperand(0);
7303 // fold (fp_round (fp_round x)) -> (fp_round x)
7304 if (N0.getOpcode() == ISD::FP_ROUND) {
7305 // This is a value preserving truncation if both round's are.
7306 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7307 N0.getNode()->getConstantOperandVal(1) == 1;
7308 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7309 DAG.getIntPtrConstant(IsTrunc));
7312 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7313 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7314 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7315 N0.getOperand(0), N1);
7316 AddToWorklist(Tmp.getNode());
7317 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7318 Tmp, N0.getOperand(1));
7324 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7325 SDValue N0 = N->getOperand(0);
7326 EVT VT = N->getValueType(0);
7327 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7328 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7330 // fold (fp_round_inreg c1fp) -> c1fp
7331 if (N0CFP && isTypeLegal(EVT)) {
7332 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7333 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7339 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7340 SDValue N0 = N->getOperand(0);
7341 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7342 EVT VT = N->getValueType(0);
7344 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7345 if (N->hasOneUse() &&
7346 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7349 // fold (fp_extend c1fp) -> c1fp
7351 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7353 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7355 if (N0.getOpcode() == ISD::FP_ROUND
7356 && N0.getNode()->getConstantOperandVal(1) == 1) {
7357 SDValue In = N0.getOperand(0);
7358 if (In.getValueType() == VT) return In;
7359 if (VT.bitsLT(In.getValueType()))
7360 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7361 In, N0.getOperand(1));
7362 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7365 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7366 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7367 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7368 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7369 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7371 LN0->getBasePtr(), N0.getValueType(),
7372 LN0->getMemOperand());
7373 CombineTo(N, ExtLoad);
7374 CombineTo(N0.getNode(),
7375 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7376 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7377 ExtLoad.getValue(1));
7378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7384 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7385 SDValue N0 = N->getOperand(0);
7386 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7387 EVT VT = N->getValueType(0);
7389 // fold (fceil c1) -> fceil(c1)
7391 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7396 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7397 SDValue N0 = N->getOperand(0);
7398 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7399 EVT VT = N->getValueType(0);
7401 // fold (ftrunc c1) -> ftrunc(c1)
7403 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7408 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7409 SDValue N0 = N->getOperand(0);
7410 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7411 EVT VT = N->getValueType(0);
7413 // fold (ffloor c1) -> ffloor(c1)
7415 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7420 // FIXME: FNEG and FABS have a lot in common; refactor.
7421 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7422 SDValue N0 = N->getOperand(0);
7423 EVT VT = N->getValueType(0);
7425 if (VT.isVector()) {
7426 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7427 if (FoldedVOp.getNode()) return FoldedVOp;
7430 // Constant fold FNEG.
7431 if (isa<ConstantFPSDNode>(N0))
7432 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7434 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7435 &DAG.getTarget().Options))
7436 return GetNegatedExpression(N0, DAG, LegalOperations);
7438 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7439 // constant pool values.
7440 if (!TLI.isFNegFree(VT) &&
7441 N0.getOpcode() == ISD::BITCAST &&
7442 N0.getNode()->hasOneUse()) {
7443 SDValue Int = N0.getOperand(0);
7444 EVT IntVT = Int.getValueType();
7445 if (IntVT.isInteger() && !IntVT.isVector()) {
7447 if (N0.getValueType().isVector()) {
7448 // For a vector, get a mask such as 0x80... per scalar element
7450 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7451 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7453 // For a scalar, just generate 0x80...
7454 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7456 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7457 DAG.getConstant(SignMask, IntVT));
7458 AddToWorklist(Int.getNode());
7459 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7463 // (fneg (fmul c, x)) -> (fmul -c, x)
7464 if (N0.getOpcode() == ISD::FMUL) {
7465 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7467 APFloat CVal = CFP1->getValueAPF();
7469 if (Level >= AfterLegalizeDAG &&
7470 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7471 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7473 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7474 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7481 SDValue DAGCombiner::visitFABS(SDNode *N) {
7482 SDValue N0 = N->getOperand(0);
7483 EVT VT = N->getValueType(0);
7485 if (VT.isVector()) {
7486 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7487 if (FoldedVOp.getNode()) return FoldedVOp;
7490 // fold (fabs c1) -> fabs(c1)
7491 if (isa<ConstantFPSDNode>(N0))
7492 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7494 // fold (fabs (fabs x)) -> (fabs x)
7495 if (N0.getOpcode() == ISD::FABS)
7496 return N->getOperand(0);
7498 // fold (fabs (fneg x)) -> (fabs x)
7499 // fold (fabs (fcopysign x, y)) -> (fabs x)
7500 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7501 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7503 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7504 // constant pool values.
7505 if (!TLI.isFAbsFree(VT) &&
7506 N0.getOpcode() == ISD::BITCAST &&
7507 N0.getNode()->hasOneUse()) {
7508 SDValue Int = N0.getOperand(0);
7509 EVT IntVT = Int.getValueType();
7510 if (IntVT.isInteger() && !IntVT.isVector()) {
7512 if (N0.getValueType().isVector()) {
7513 // For a vector, get a mask such as 0x7f... per scalar element
7515 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7516 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7518 // For a scalar, just generate 0x7f...
7519 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7521 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7522 DAG.getConstant(SignMask, IntVT));
7523 AddToWorklist(Int.getNode());
7524 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7531 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7532 SDValue Chain = N->getOperand(0);
7533 SDValue N1 = N->getOperand(1);
7534 SDValue N2 = N->getOperand(2);
7536 // If N is a constant we could fold this into a fallthrough or unconditional
7537 // branch. However that doesn't happen very often in normal code, because
7538 // Instcombine/SimplifyCFG should have handled the available opportunities.
7539 // If we did this folding here, it would be necessary to update the
7540 // MachineBasicBlock CFG, which is awkward.
7542 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7544 if (N1.getOpcode() == ISD::SETCC &&
7545 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7546 N1.getOperand(0).getValueType())) {
7547 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7548 Chain, N1.getOperand(2),
7549 N1.getOperand(0), N1.getOperand(1), N2);
7552 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7553 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7554 (N1.getOperand(0).hasOneUse() &&
7555 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7556 SDNode *Trunc = nullptr;
7557 if (N1.getOpcode() == ISD::TRUNCATE) {
7558 // Look pass the truncate.
7559 Trunc = N1.getNode();
7560 N1 = N1.getOperand(0);
7563 // Match this pattern so that we can generate simpler code:
7566 // %b = and i32 %a, 2
7567 // %c = srl i32 %b, 1
7568 // brcond i32 %c ...
7573 // %b = and i32 %a, 2
7574 // %c = setcc eq %b, 0
7577 // This applies only when the AND constant value has one bit set and the
7578 // SRL constant is equal to the log2 of the AND constant. The back-end is
7579 // smart enough to convert the result into a TEST/JMP sequence.
7580 SDValue Op0 = N1.getOperand(0);
7581 SDValue Op1 = N1.getOperand(1);
7583 if (Op0.getOpcode() == ISD::AND &&
7584 Op1.getOpcode() == ISD::Constant) {
7585 SDValue AndOp1 = Op0.getOperand(1);
7587 if (AndOp1.getOpcode() == ISD::Constant) {
7588 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7590 if (AndConst.isPowerOf2() &&
7591 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7593 DAG.getSetCC(SDLoc(N),
7594 getSetCCResultType(Op0.getValueType()),
7595 Op0, DAG.getConstant(0, Op0.getValueType()),
7598 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7599 MVT::Other, Chain, SetCC, N2);
7600 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7601 // will convert it back to (X & C1) >> C2.
7602 CombineTo(N, NewBRCond, false);
7603 // Truncate is dead.
7605 deleteAndRecombine(Trunc);
7606 // Replace the uses of SRL with SETCC
7607 WorklistRemover DeadNodes(*this);
7608 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7609 deleteAndRecombine(N1.getNode());
7610 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7616 // Restore N1 if the above transformation doesn't match.
7617 N1 = N->getOperand(1);
7620 // Transform br(xor(x, y)) -> br(x != y)
7621 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7622 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7623 SDNode *TheXor = N1.getNode();
7624 SDValue Op0 = TheXor->getOperand(0);
7625 SDValue Op1 = TheXor->getOperand(1);
7626 if (Op0.getOpcode() == Op1.getOpcode()) {
7627 // Avoid missing important xor optimizations.
7628 SDValue Tmp = visitXOR(TheXor);
7629 if (Tmp.getNode()) {
7630 if (Tmp.getNode() != TheXor) {
7631 DEBUG(dbgs() << "\nReplacing.8 ";
7633 dbgs() << "\nWith: ";
7634 Tmp.getNode()->dump(&DAG);
7636 WorklistRemover DeadNodes(*this);
7637 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7638 deleteAndRecombine(TheXor);
7639 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7640 MVT::Other, Chain, Tmp, N2);
7643 // visitXOR has changed XOR's operands or replaced the XOR completely,
7645 return SDValue(N, 0);
7649 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7651 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7652 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7653 Op0.getOpcode() == ISD::XOR) {
7654 TheXor = Op0.getNode();
7658 EVT SetCCVT = N1.getValueType();
7660 SetCCVT = getSetCCResultType(SetCCVT);
7661 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7664 Equal ? ISD::SETEQ : ISD::SETNE);
7665 // Replace the uses of XOR with SETCC
7666 WorklistRemover DeadNodes(*this);
7667 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7668 deleteAndRecombine(N1.getNode());
7669 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7670 MVT::Other, Chain, SetCC, N2);
7677 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7679 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7680 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7681 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7683 // If N is a constant we could fold this into a fallthrough or unconditional
7684 // branch. However that doesn't happen very often in normal code, because
7685 // Instcombine/SimplifyCFG should have handled the available opportunities.
7686 // If we did this folding here, it would be necessary to update the
7687 // MachineBasicBlock CFG, which is awkward.
7689 // Use SimplifySetCC to simplify SETCC's.
7690 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7691 CondLHS, CondRHS, CC->get(), SDLoc(N),
7693 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7695 // fold to a simpler setcc
7696 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7697 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7698 N->getOperand(0), Simp.getOperand(2),
7699 Simp.getOperand(0), Simp.getOperand(1),
7705 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7706 /// and that N may be folded in the load / store addressing mode.
7707 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7709 const TargetLowering &TLI) {
7711 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7712 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7714 VT = Use->getValueType(0);
7715 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7716 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7718 VT = ST->getValue().getValueType();
7722 TargetLowering::AddrMode AM;
7723 if (N->getOpcode() == ISD::ADD) {
7724 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7727 AM.BaseOffs = Offset->getSExtValue();
7731 } else if (N->getOpcode() == ISD::SUB) {
7732 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7735 AM.BaseOffs = -Offset->getSExtValue();
7742 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7745 /// Try turning a load/store into a pre-indexed load/store when the base
7746 /// pointer is an add or subtract and it has other uses besides the load/store.
7747 /// After the transformation, the new indexed load/store has effectively folded
7748 /// the add/subtract in and all of its other uses are redirected to the
7750 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7751 if (Level < AfterLegalizeDAG)
7757 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7758 if (LD->isIndexed())
7760 VT = LD->getMemoryVT();
7761 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7762 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7764 Ptr = LD->getBasePtr();
7765 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7766 if (ST->isIndexed())
7768 VT = ST->getMemoryVT();
7769 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7770 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7772 Ptr = ST->getBasePtr();
7778 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7779 // out. There is no reason to make this a preinc/predec.
7780 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7781 Ptr.getNode()->hasOneUse())
7784 // Ask the target to do addressing mode selection.
7787 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7788 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7791 // Backends without true r+i pre-indexed forms may need to pass a
7792 // constant base with a variable offset so that constant coercion
7793 // will work with the patterns in canonical form.
7794 bool Swapped = false;
7795 if (isa<ConstantSDNode>(BasePtr)) {
7796 std::swap(BasePtr, Offset);
7800 // Don't create a indexed load / store with zero offset.
7801 if (isa<ConstantSDNode>(Offset) &&
7802 cast<ConstantSDNode>(Offset)->isNullValue())
7805 // Try turning it into a pre-indexed load / store except when:
7806 // 1) The new base ptr is a frame index.
7807 // 2) If N is a store and the new base ptr is either the same as or is a
7808 // predecessor of the value being stored.
7809 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7810 // that would create a cycle.
7811 // 4) All uses are load / store ops that use it as old base ptr.
7813 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7814 // (plus the implicit offset) to a register to preinc anyway.
7815 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7820 SDValue Val = cast<StoreSDNode>(N)->getValue();
7821 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7825 // If the offset is a constant, there may be other adds of constants that
7826 // can be folded with this one. We should do this to avoid having to keep
7827 // a copy of the original base pointer.
7828 SmallVector<SDNode *, 16> OtherUses;
7829 if (isa<ConstantSDNode>(Offset))
7830 for (SDNode *Use : BasePtr.getNode()->uses()) {
7831 if (Use == Ptr.getNode())
7834 if (Use->isPredecessorOf(N))
7837 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7842 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7843 if (Op1.getNode() == BasePtr.getNode())
7844 std::swap(Op0, Op1);
7845 assert(Op0.getNode() == BasePtr.getNode() &&
7846 "Use of ADD/SUB but not an operand");
7848 if (!isa<ConstantSDNode>(Op1)) {
7853 // FIXME: In some cases, we can be smarter about this.
7854 if (Op1.getValueType() != Offset.getValueType()) {
7859 OtherUses.push_back(Use);
7863 std::swap(BasePtr, Offset);
7865 // Now check for #3 and #4.
7866 bool RealUse = false;
7868 // Caches for hasPredecessorHelper
7869 SmallPtrSet<const SDNode *, 32> Visited;
7870 SmallVector<const SDNode *, 16> Worklist;
7872 for (SDNode *Use : Ptr.getNode()->uses()) {
7875 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7878 // If Ptr may be folded in addressing mode of other use, then it's
7879 // not profitable to do this transformation.
7880 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7889 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7890 BasePtr, Offset, AM);
7892 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7893 BasePtr, Offset, AM);
7896 DEBUG(dbgs() << "\nReplacing.4 ";
7898 dbgs() << "\nWith: ";
7899 Result.getNode()->dump(&DAG);
7901 WorklistRemover DeadNodes(*this);
7903 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7906 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7909 // Finally, since the node is now dead, remove it from the graph.
7910 deleteAndRecombine(N);
7913 std::swap(BasePtr, Offset);
7915 // Replace other uses of BasePtr that can be updated to use Ptr
7916 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7917 unsigned OffsetIdx = 1;
7918 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7920 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7921 BasePtr.getNode() && "Expected BasePtr operand");
7923 // We need to replace ptr0 in the following expression:
7924 // x0 * offset0 + y0 * ptr0 = t0
7926 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7928 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7929 // indexed load/store and the expresion that needs to be re-written.
7931 // Therefore, we have:
7932 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7934 ConstantSDNode *CN =
7935 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7937 APInt Offset0 = CN->getAPIntValue();
7938 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7940 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7941 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7942 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7943 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7945 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7947 APInt CNV = Offset0;
7948 if (X0 < 0) CNV = -CNV;
7949 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7950 else CNV = CNV - Offset1;
7952 // We can now generate the new expression.
7953 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7954 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7956 SDValue NewUse = DAG.getNode(Opcode,
7957 SDLoc(OtherUses[i]),
7958 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7959 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7960 deleteAndRecombine(OtherUses[i]);
7963 // Replace the uses of Ptr with uses of the updated base value.
7964 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7965 deleteAndRecombine(Ptr.getNode());
7970 /// Try to combine a load/store with a add/sub of the base pointer node into a
7971 /// post-indexed load/store. The transformation folded the add/subtract into the
7972 /// new indexed load/store effectively and all of its uses are redirected to the
7974 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7975 if (Level < AfterLegalizeDAG)
7981 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7982 if (LD->isIndexed())
7984 VT = LD->getMemoryVT();
7985 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7986 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7988 Ptr = LD->getBasePtr();
7989 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7990 if (ST->isIndexed())
7992 VT = ST->getMemoryVT();
7993 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7994 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7996 Ptr = ST->getBasePtr();
8002 if (Ptr.getNode()->hasOneUse())
8005 for (SDNode *Op : Ptr.getNode()->uses()) {
8007 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8012 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8013 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8014 // Don't create a indexed load / store with zero offset.
8015 if (isa<ConstantSDNode>(Offset) &&
8016 cast<ConstantSDNode>(Offset)->isNullValue())
8019 // Try turning it into a post-indexed load / store except when
8020 // 1) All uses are load / store ops that use it as base ptr (and
8021 // it may be folded as addressing mmode).
8022 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8023 // nor a successor of N. Otherwise, if Op is folded that would
8026 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8030 bool TryNext = false;
8031 for (SDNode *Use : BasePtr.getNode()->uses()) {
8032 if (Use == Ptr.getNode())
8035 // If all the uses are load / store addresses, then don't do the
8037 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8038 bool RealUse = false;
8039 for (SDNode *UseUse : Use->uses()) {
8040 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8055 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8056 SDValue Result = isLoad
8057 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8058 BasePtr, Offset, AM)
8059 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8060 BasePtr, Offset, AM);
8063 DEBUG(dbgs() << "\nReplacing.5 ";
8065 dbgs() << "\nWith: ";
8066 Result.getNode()->dump(&DAG);
8068 WorklistRemover DeadNodes(*this);
8070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8076 // Finally, since the node is now dead, remove it from the graph.
8077 deleteAndRecombine(N);
8079 // Replace the uses of Use with uses of the updated base value.
8080 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8081 Result.getValue(isLoad ? 1 : 0));
8082 deleteAndRecombine(Op);
8091 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8092 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8093 ISD::MemIndexedMode AM = LD->getAddressingMode();
8094 assert(AM != ISD::UNINDEXED);
8095 SDValue BP = LD->getOperand(1);
8096 SDValue Inc = LD->getOperand(2);
8098 // Some backends use TargetConstants for load offsets, but don't expect
8099 // TargetConstants in general ADD nodes. We can convert these constants into
8100 // regular Constants (if the constant is not opaque).
8101 assert((Inc.getOpcode() != ISD::TargetConstant ||
8102 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8103 "Cannot split out indexing using opaque target constants");
8104 if (Inc.getOpcode() == ISD::TargetConstant) {
8105 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8106 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8107 ConstInc->getValueType(0));
8111 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8112 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8115 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8116 LoadSDNode *LD = cast<LoadSDNode>(N);
8117 SDValue Chain = LD->getChain();
8118 SDValue Ptr = LD->getBasePtr();
8120 // If load is not volatile and there are no uses of the loaded value (and
8121 // the updated indexed value in case of indexed loads), change uses of the
8122 // chain value into uses of the chain input (i.e. delete the dead load).
8123 if (!LD->isVolatile()) {
8124 if (N->getValueType(1) == MVT::Other) {
8126 if (!N->hasAnyUseOfValue(0)) {
8127 // It's not safe to use the two value CombineTo variant here. e.g.
8128 // v1, chain2 = load chain1, loc
8129 // v2, chain3 = load chain2, loc
8131 // Now we replace use of chain2 with chain1. This makes the second load
8132 // isomorphic to the one we are deleting, and thus makes this load live.
8133 DEBUG(dbgs() << "\nReplacing.6 ";
8135 dbgs() << "\nWith chain: ";
8136 Chain.getNode()->dump(&DAG);
8138 WorklistRemover DeadNodes(*this);
8139 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8142 deleteAndRecombine(N);
8144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8148 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8150 // If this load has an opaque TargetConstant offset, then we cannot split
8151 // the indexing into an add/sub directly (that TargetConstant may not be
8152 // valid for a different type of node, and we cannot convert an opaque
8153 // target constant into a regular constant).
8154 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8155 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8157 if (!N->hasAnyUseOfValue(0) &&
8158 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8159 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8161 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8162 Index = SplitIndexingFromLoad(LD);
8163 // Try to fold the base pointer arithmetic into subsequent loads and
8165 AddUsersToWorklist(N);
8167 Index = DAG.getUNDEF(N->getValueType(1));
8168 DEBUG(dbgs() << "\nReplacing.7 ";
8170 dbgs() << "\nWith: ";
8171 Undef.getNode()->dump(&DAG);
8172 dbgs() << " and 2 other values\n");
8173 WorklistRemover DeadNodes(*this);
8174 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8175 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8176 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8177 deleteAndRecombine(N);
8178 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8183 // If this load is directly stored, replace the load value with the stored
8185 // TODO: Handle store large -> read small portion.
8186 // TODO: Handle TRUNCSTORE/LOADEXT
8187 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8188 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8189 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8190 if (PrevST->getBasePtr() == Ptr &&
8191 PrevST->getValue().getValueType() == N->getValueType(0))
8192 return CombineTo(N, Chain.getOperand(1), Chain);
8196 // Try to infer better alignment information than the load already has.
8197 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8198 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8199 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8201 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8202 LD->getValueType(0),
8203 Chain, Ptr, LD->getPointerInfo(),
8205 LD->isVolatile(), LD->isNonTemporal(),
8206 LD->isInvariant(), Align, LD->getAAInfo());
8207 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8212 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8213 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8215 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8216 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8219 if (UseAA && LD->isUnindexed()) {
8220 // Walk up chain skipping non-aliasing memory nodes.
8221 SDValue BetterChain = FindBetterChain(N, Chain);
8223 // If there is a better chain.
8224 if (Chain != BetterChain) {
8227 // Replace the chain to void dependency.
8228 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8229 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8230 BetterChain, Ptr, LD->getMemOperand());
8232 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8233 LD->getValueType(0),
8234 BetterChain, Ptr, LD->getMemoryVT(),
8235 LD->getMemOperand());
8238 // Create token factor to keep old chain connected.
8239 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8240 MVT::Other, Chain, ReplLoad.getValue(1));
8242 // Make sure the new and old chains are cleaned up.
8243 AddToWorklist(Token.getNode());
8245 // Replace uses with load result and token factor. Don't add users
8247 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8251 // Try transforming N to an indexed load.
8252 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8253 return SDValue(N, 0);
8255 // Try to slice up N to more direct loads if the slices are mapped to
8256 // different register banks or pairing can take place.
8258 return SDValue(N, 0);
8264 /// \brief Helper structure used to slice a load in smaller loads.
8265 /// Basically a slice is obtained from the following sequence:
8266 /// Origin = load Ty1, Base
8267 /// Shift = srl Ty1 Origin, CstTy Amount
8268 /// Inst = trunc Shift to Ty2
8270 /// Then, it will be rewriten into:
8271 /// Slice = load SliceTy, Base + SliceOffset
8272 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8274 /// SliceTy is deduced from the number of bits that are actually used to
8276 struct LoadedSlice {
8277 /// \brief Helper structure used to compute the cost of a slice.
8279 /// Are we optimizing for code size.
8284 unsigned CrossRegisterBanksCopies;
8288 Cost(bool ForCodeSize = false)
8289 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8290 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8292 /// \brief Get the cost of one isolated slice.
8293 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8294 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8295 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8296 EVT TruncType = LS.Inst->getValueType(0);
8297 EVT LoadedType = LS.getLoadedType();
8298 if (TruncType != LoadedType &&
8299 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8303 /// \brief Account for slicing gain in the current cost.
8304 /// Slicing provide a few gains like removing a shift or a
8305 /// truncate. This method allows to grow the cost of the original
8306 /// load with the gain from this slice.
8307 void addSliceGain(const LoadedSlice &LS) {
8308 // Each slice saves a truncate.
8309 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8310 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8311 LS.Inst->getOperand(0).getValueType()))
8313 // If there is a shift amount, this slice gets rid of it.
8316 // If this slice can merge a cross register bank copy, account for it.
8317 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8318 ++CrossRegisterBanksCopies;
8321 Cost &operator+=(const Cost &RHS) {
8323 Truncates += RHS.Truncates;
8324 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8330 bool operator==(const Cost &RHS) const {
8331 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8332 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8333 ZExts == RHS.ZExts && Shift == RHS.Shift;
8336 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8338 bool operator<(const Cost &RHS) const {
8339 // Assume cross register banks copies are as expensive as loads.
8340 // FIXME: Do we want some more target hooks?
8341 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8342 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8343 // Unless we are optimizing for code size, consider the
8344 // expensive operation first.
8345 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8346 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8347 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8348 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8351 bool operator>(const Cost &RHS) const { return RHS < *this; }
8353 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8355 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8357 // The last instruction that represent the slice. This should be a
8358 // truncate instruction.
8360 // The original load instruction.
8362 // The right shift amount in bits from the original load.
8364 // The DAG from which Origin came from.
8365 // This is used to get some contextual information about legal types, etc.
8368 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8369 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8370 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8372 LoadedSlice(const LoadedSlice &LS)
8373 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8375 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8376 /// \return Result is \p BitWidth and has used bits set to 1 and
8377 /// not used bits set to 0.
8378 APInt getUsedBits() const {
8379 // Reproduce the trunc(lshr) sequence:
8380 // - Start from the truncated value.
8381 // - Zero extend to the desired bit width.
8383 assert(Origin && "No original load to compare against.");
8384 unsigned BitWidth = Origin->getValueSizeInBits(0);
8385 assert(Inst && "This slice is not bound to an instruction");
8386 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8387 "Extracted slice is bigger than the whole type!");
8388 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8389 UsedBits.setAllBits();
8390 UsedBits = UsedBits.zext(BitWidth);
8395 /// \brief Get the size of the slice to be loaded in bytes.
8396 unsigned getLoadedSize() const {
8397 unsigned SliceSize = getUsedBits().countPopulation();
8398 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8399 return SliceSize / 8;
8402 /// \brief Get the type that will be loaded for this slice.
8403 /// Note: This may not be the final type for the slice.
8404 EVT getLoadedType() const {
8405 assert(DAG && "Missing context");
8406 LLVMContext &Ctxt = *DAG->getContext();
8407 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8410 /// \brief Get the alignment of the load used for this slice.
8411 unsigned getAlignment() const {
8412 unsigned Alignment = Origin->getAlignment();
8413 unsigned Offset = getOffsetFromBase();
8415 Alignment = MinAlign(Alignment, Alignment + Offset);
8419 /// \brief Check if this slice can be rewritten with legal operations.
8420 bool isLegal() const {
8421 // An invalid slice is not legal.
8422 if (!Origin || !Inst || !DAG)
8425 // Offsets are for indexed load only, we do not handle that.
8426 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8429 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8431 // Check that the type is legal.
8432 EVT SliceType = getLoadedType();
8433 if (!TLI.isTypeLegal(SliceType))
8436 // Check that the load is legal for this type.
8437 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8440 // Check that the offset can be computed.
8441 // 1. Check its type.
8442 EVT PtrType = Origin->getBasePtr().getValueType();
8443 if (PtrType == MVT::Untyped || PtrType.isExtended())
8446 // 2. Check that it fits in the immediate.
8447 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8450 // 3. Check that the computation is legal.
8451 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8454 // Check that the zext is legal if it needs one.
8455 EVT TruncateType = Inst->getValueType(0);
8456 if (TruncateType != SliceType &&
8457 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8463 /// \brief Get the offset in bytes of this slice in the original chunk of
8465 /// \pre DAG != nullptr.
8466 uint64_t getOffsetFromBase() const {
8467 assert(DAG && "Missing context.");
8469 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8470 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8471 uint64_t Offset = Shift / 8;
8472 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8473 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8474 "The size of the original loaded type is not a multiple of a"
8476 // If Offset is bigger than TySizeInBytes, it means we are loading all
8477 // zeros. This should have been optimized before in the process.
8478 assert(TySizeInBytes > Offset &&
8479 "Invalid shift amount for given loaded size");
8481 Offset = TySizeInBytes - Offset - getLoadedSize();
8485 /// \brief Generate the sequence of instructions to load the slice
8486 /// represented by this object and redirect the uses of this slice to
8487 /// this new sequence of instructions.
8488 /// \pre this->Inst && this->Origin are valid Instructions and this
8489 /// object passed the legal check: LoadedSlice::isLegal returned true.
8490 /// \return The last instruction of the sequence used to load the slice.
8491 SDValue loadSlice() const {
8492 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8493 const SDValue &OldBaseAddr = Origin->getBasePtr();
8494 SDValue BaseAddr = OldBaseAddr;
8495 // Get the offset in that chunk of bytes w.r.t. the endianess.
8496 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8497 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8499 // BaseAddr = BaseAddr + Offset.
8500 EVT ArithType = BaseAddr.getValueType();
8501 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8502 DAG->getConstant(Offset, ArithType));
8505 // Create the type of the loaded slice according to its size.
8506 EVT SliceType = getLoadedType();
8508 // Create the load for the slice.
8509 SDValue LastInst = DAG->getLoad(
8510 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8511 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8512 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8513 // If the final type is not the same as the loaded type, this means that
8514 // we have to pad with zero. Create a zero extend for that.
8515 EVT FinalType = Inst->getValueType(0);
8516 if (SliceType != FinalType)
8518 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8522 /// \brief Check if this slice can be merged with an expensive cross register
8523 /// bank copy. E.g.,
8525 /// f = bitcast i32 i to float
8526 bool canMergeExpensiveCrossRegisterBankCopy() const {
8527 if (!Inst || !Inst->hasOneUse())
8529 SDNode *Use = *Inst->use_begin();
8530 if (Use->getOpcode() != ISD::BITCAST)
8532 assert(DAG && "Missing context");
8533 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8534 EVT ResVT = Use->getValueType(0);
8535 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8536 const TargetRegisterClass *ArgRC =
8537 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8538 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8541 // At this point, we know that we perform a cross-register-bank copy.
8542 // Check if it is expensive.
8543 const TargetRegisterInfo *TRI =
8544 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8545 // Assume bitcasts are cheap, unless both register classes do not
8546 // explicitly share a common sub class.
8547 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8550 // Check if it will be merged with the load.
8551 // 1. Check the alignment constraint.
8552 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8553 ResVT.getTypeForEVT(*DAG->getContext()));
8555 if (RequiredAlignment > getAlignment())
8558 // 2. Check that the load is a legal operation for that type.
8559 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8562 // 3. Check that we do not have a zext in the way.
8563 if (Inst->getValueType(0) != getLoadedType())
8571 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8572 /// \p UsedBits looks like 0..0 1..1 0..0.
8573 static bool areUsedBitsDense(const APInt &UsedBits) {
8574 // If all the bits are one, this is dense!
8575 if (UsedBits.isAllOnesValue())
8578 // Get rid of the unused bits on the right.
8579 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8580 // Get rid of the unused bits on the left.
8581 if (NarrowedUsedBits.countLeadingZeros())
8582 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8583 // Check that the chunk of bits is completely used.
8584 return NarrowedUsedBits.isAllOnesValue();
8587 /// \brief Check whether or not \p First and \p Second are next to each other
8588 /// in memory. This means that there is no hole between the bits loaded
8589 /// by \p First and the bits loaded by \p Second.
8590 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8591 const LoadedSlice &Second) {
8592 assert(First.Origin == Second.Origin && First.Origin &&
8593 "Unable to match different memory origins.");
8594 APInt UsedBits = First.getUsedBits();
8595 assert((UsedBits & Second.getUsedBits()) == 0 &&
8596 "Slices are not supposed to overlap.");
8597 UsedBits |= Second.getUsedBits();
8598 return areUsedBitsDense(UsedBits);
8601 /// \brief Adjust the \p GlobalLSCost according to the target
8602 /// paring capabilities and the layout of the slices.
8603 /// \pre \p GlobalLSCost should account for at least as many loads as
8604 /// there is in the slices in \p LoadedSlices.
8605 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8606 LoadedSlice::Cost &GlobalLSCost) {
8607 unsigned NumberOfSlices = LoadedSlices.size();
8608 // If there is less than 2 elements, no pairing is possible.
8609 if (NumberOfSlices < 2)
8612 // Sort the slices so that elements that are likely to be next to each
8613 // other in memory are next to each other in the list.
8614 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8615 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8616 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8617 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8619 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8620 // First (resp. Second) is the first (resp. Second) potentially candidate
8621 // to be placed in a paired load.
8622 const LoadedSlice *First = nullptr;
8623 const LoadedSlice *Second = nullptr;
8624 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8625 // Set the beginning of the pair.
8628 Second = &LoadedSlices[CurrSlice];
8630 // If First is NULL, it means we start a new pair.
8631 // Get to the next slice.
8635 EVT LoadedType = First->getLoadedType();
8637 // If the types of the slices are different, we cannot pair them.
8638 if (LoadedType != Second->getLoadedType())
8641 // Check if the target supplies paired loads for this type.
8642 unsigned RequiredAlignment = 0;
8643 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8644 // move to the next pair, this type is hopeless.
8648 // Check if we meet the alignment requirement.
8649 if (RequiredAlignment > First->getAlignment())
8652 // Check that both loads are next to each other in memory.
8653 if (!areSlicesNextToEachOther(*First, *Second))
8656 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8657 --GlobalLSCost.Loads;
8658 // Move to the next pair.
8663 /// \brief Check the profitability of all involved LoadedSlice.
8664 /// Currently, it is considered profitable if there is exactly two
8665 /// involved slices (1) which are (2) next to each other in memory, and
8666 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8668 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8669 /// the elements themselves.
8671 /// FIXME: When the cost model will be mature enough, we can relax
8672 /// constraints (1) and (2).
8673 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8674 const APInt &UsedBits, bool ForCodeSize) {
8675 unsigned NumberOfSlices = LoadedSlices.size();
8676 if (StressLoadSlicing)
8677 return NumberOfSlices > 1;
8680 if (NumberOfSlices != 2)
8684 if (!areUsedBitsDense(UsedBits))
8688 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8689 // The original code has one big load.
8691 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8692 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8693 // Accumulate the cost of all the slices.
8694 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8695 GlobalSlicingCost += SliceCost;
8697 // Account as cost in the original configuration the gain obtained
8698 // with the current slices.
8699 OrigCost.addSliceGain(LS);
8702 // If the target supports paired load, adjust the cost accordingly.
8703 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8704 return OrigCost > GlobalSlicingCost;
8707 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8708 /// operations, split it in the various pieces being extracted.
8710 /// This sort of thing is introduced by SROA.
8711 /// This slicing takes care not to insert overlapping loads.
8712 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8713 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8714 if (Level < AfterLegalizeDAG)
8717 LoadSDNode *LD = cast<LoadSDNode>(N);
8718 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8719 !LD->getValueType(0).isInteger())
8722 // Keep track of already used bits to detect overlapping values.
8723 // In that case, we will just abort the transformation.
8724 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8726 SmallVector<LoadedSlice, 4> LoadedSlices;
8728 // Check if this load is used as several smaller chunks of bits.
8729 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8730 // of computation for each trunc.
8731 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8732 UI != UIEnd; ++UI) {
8733 // Skip the uses of the chain.
8734 if (UI.getUse().getResNo() != 0)
8740 // Check if this is a trunc(lshr).
8741 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8742 isa<ConstantSDNode>(User->getOperand(1))) {
8743 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8744 User = *User->use_begin();
8747 // At this point, User is a Truncate, iff we encountered, trunc or
8749 if (User->getOpcode() != ISD::TRUNCATE)
8752 // The width of the type must be a power of 2 and greater than 8-bits.
8753 // Otherwise the load cannot be represented in LLVM IR.
8754 // Moreover, if we shifted with a non-8-bits multiple, the slice
8755 // will be across several bytes. We do not support that.
8756 unsigned Width = User->getValueSizeInBits(0);
8757 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8760 // Build the slice for this chain of computations.
8761 LoadedSlice LS(User, LD, Shift, &DAG);
8762 APInt CurrentUsedBits = LS.getUsedBits();
8764 // Check if this slice overlaps with another.
8765 if ((CurrentUsedBits & UsedBits) != 0)
8767 // Update the bits used globally.
8768 UsedBits |= CurrentUsedBits;
8770 // Check if the new slice would be legal.
8774 // Record the slice.
8775 LoadedSlices.push_back(LS);
8778 // Abort slicing if it does not seem to be profitable.
8779 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8784 // Rewrite each chain to use an independent load.
8785 // By construction, each chain can be represented by a unique load.
8787 // Prepare the argument for the new token factor for all the slices.
8788 SmallVector<SDValue, 8> ArgChains;
8789 for (SmallVectorImpl<LoadedSlice>::const_iterator
8790 LSIt = LoadedSlices.begin(),
8791 LSItEnd = LoadedSlices.end();
8792 LSIt != LSItEnd; ++LSIt) {
8793 SDValue SliceInst = LSIt->loadSlice();
8794 CombineTo(LSIt->Inst, SliceInst, true);
8795 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8796 SliceInst = SliceInst.getOperand(0);
8797 assert(SliceInst->getOpcode() == ISD::LOAD &&
8798 "It takes more than a zext to get to the loaded slice!!");
8799 ArgChains.push_back(SliceInst.getValue(1));
8802 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8804 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8808 /// Check to see if V is (and load (ptr), imm), where the load is having
8809 /// specific bytes cleared out. If so, return the byte size being masked out
8810 /// and the shift amount.
8811 static std::pair<unsigned, unsigned>
8812 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8813 std::pair<unsigned, unsigned> Result(0, 0);
8815 // Check for the structure we're looking for.
8816 if (V->getOpcode() != ISD::AND ||
8817 !isa<ConstantSDNode>(V->getOperand(1)) ||
8818 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8821 // Check the chain and pointer.
8822 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8823 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8825 // The store should be chained directly to the load or be an operand of a
8827 if (LD == Chain.getNode())
8829 else if (Chain->getOpcode() != ISD::TokenFactor)
8830 return Result; // Fail.
8833 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8834 if (Chain->getOperand(i).getNode() == LD) {
8838 if (!isOk) return Result;
8841 // This only handles simple types.
8842 if (V.getValueType() != MVT::i16 &&
8843 V.getValueType() != MVT::i32 &&
8844 V.getValueType() != MVT::i64)
8847 // Check the constant mask. Invert it so that the bits being masked out are
8848 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8849 // follow the sign bit for uniformity.
8850 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8851 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8852 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8853 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8854 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8855 if (NotMaskLZ == 64) return Result; // All zero mask.
8857 // See if we have a continuous run of bits. If so, we have 0*1+0*
8858 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8861 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8862 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8863 NotMaskLZ -= 64-V.getValueSizeInBits();
8865 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8866 switch (MaskedBytes) {
8870 default: return Result; // All one mask, or 5-byte mask.
8873 // Verify that the first bit starts at a multiple of mask so that the access
8874 // is aligned the same as the access width.
8875 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8877 Result.first = MaskedBytes;
8878 Result.second = NotMaskTZ/8;
8883 /// Check to see if IVal is something that provides a value as specified by
8884 /// MaskInfo. If so, replace the specified store with a narrower store of
8887 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8888 SDValue IVal, StoreSDNode *St,
8890 unsigned NumBytes = MaskInfo.first;
8891 unsigned ByteShift = MaskInfo.second;
8892 SelectionDAG &DAG = DC->getDAG();
8894 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8895 // that uses this. If not, this is not a replacement.
8896 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8897 ByteShift*8, (ByteShift+NumBytes)*8);
8898 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8900 // Check that it is legal on the target to do this. It is legal if the new
8901 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8903 MVT VT = MVT::getIntegerVT(NumBytes*8);
8904 if (!DC->isTypeLegal(VT))
8907 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8908 // shifted by ByteShift and truncated down to NumBytes.
8910 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8911 DAG.getConstant(ByteShift*8,
8912 DC->getShiftAmountTy(IVal.getValueType())));
8914 // Figure out the offset for the store and the alignment of the access.
8916 unsigned NewAlign = St->getAlignment();
8918 if (DAG.getTargetLoweringInfo().isLittleEndian())
8919 StOffset = ByteShift;
8921 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8923 SDValue Ptr = St->getBasePtr();
8925 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8926 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8927 NewAlign = MinAlign(NewAlign, StOffset);
8930 // Truncate down to the new size.
8931 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8934 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8935 St->getPointerInfo().getWithOffset(StOffset),
8936 false, false, NewAlign).getNode();
8940 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8941 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8942 /// narrowing the load and store if it would end up being a win for performance
8944 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8945 StoreSDNode *ST = cast<StoreSDNode>(N);
8946 if (ST->isVolatile())
8949 SDValue Chain = ST->getChain();
8950 SDValue Value = ST->getValue();
8951 SDValue Ptr = ST->getBasePtr();
8952 EVT VT = Value.getValueType();
8954 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8957 unsigned Opc = Value.getOpcode();
8959 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8960 // is a byte mask indicating a consecutive number of bytes, check to see if
8961 // Y is known to provide just those bytes. If so, we try to replace the
8962 // load + replace + store sequence with a single (narrower) store, which makes
8964 if (Opc == ISD::OR) {
8965 std::pair<unsigned, unsigned> MaskedLoad;
8966 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8967 if (MaskedLoad.first)
8968 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8969 Value.getOperand(1), ST,this))
8970 return SDValue(NewST, 0);
8972 // Or is commutative, so try swapping X and Y.
8973 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8974 if (MaskedLoad.first)
8975 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8976 Value.getOperand(0), ST,this))
8977 return SDValue(NewST, 0);
8980 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8981 Value.getOperand(1).getOpcode() != ISD::Constant)
8984 SDValue N0 = Value.getOperand(0);
8985 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8986 Chain == SDValue(N0.getNode(), 1)) {
8987 LoadSDNode *LD = cast<LoadSDNode>(N0);
8988 if (LD->getBasePtr() != Ptr ||
8989 LD->getPointerInfo().getAddrSpace() !=
8990 ST->getPointerInfo().getAddrSpace())
8993 // Find the type to narrow it the load / op / store to.
8994 SDValue N1 = Value.getOperand(1);
8995 unsigned BitWidth = N1.getValueSizeInBits();
8996 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8997 if (Opc == ISD::AND)
8998 Imm ^= APInt::getAllOnesValue(BitWidth);
8999 if (Imm == 0 || Imm.isAllOnesValue())
9001 unsigned ShAmt = Imm.countTrailingZeros();
9002 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9003 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9004 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9005 while (NewBW < BitWidth &&
9006 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9007 TLI.isNarrowingProfitable(VT, NewVT))) {
9008 NewBW = NextPowerOf2(NewBW);
9009 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9011 if (NewBW >= BitWidth)
9014 // If the lsb changed does not start at the type bitwidth boundary,
9015 // start at the previous one.
9017 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9018 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9019 std::min(BitWidth, ShAmt + NewBW));
9020 if ((Imm & Mask) == Imm) {
9021 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9022 if (Opc == ISD::AND)
9023 NewImm ^= APInt::getAllOnesValue(NewBW);
9024 uint64_t PtrOff = ShAmt / 8;
9025 // For big endian targets, we need to adjust the offset to the pointer to
9026 // load the correct bytes.
9027 if (TLI.isBigEndian())
9028 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9030 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9031 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9032 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9035 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9036 Ptr.getValueType(), Ptr,
9037 DAG.getConstant(PtrOff, Ptr.getValueType()));
9038 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9039 LD->getChain(), NewPtr,
9040 LD->getPointerInfo().getWithOffset(PtrOff),
9041 LD->isVolatile(), LD->isNonTemporal(),
9042 LD->isInvariant(), NewAlign,
9044 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9045 DAG.getConstant(NewImm, NewVT));
9046 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9048 ST->getPointerInfo().getWithOffset(PtrOff),
9049 false, false, NewAlign);
9051 AddToWorklist(NewPtr.getNode());
9052 AddToWorklist(NewLD.getNode());
9053 AddToWorklist(NewVal.getNode());
9054 WorklistRemover DeadNodes(*this);
9055 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9064 /// For a given floating point load / store pair, if the load value isn't used
9065 /// by any other operations, then consider transforming the pair to integer
9066 /// load / store operations if the target deems the transformation profitable.
9067 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9068 StoreSDNode *ST = cast<StoreSDNode>(N);
9069 SDValue Chain = ST->getChain();
9070 SDValue Value = ST->getValue();
9071 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9072 Value.hasOneUse() &&
9073 Chain == SDValue(Value.getNode(), 1)) {
9074 LoadSDNode *LD = cast<LoadSDNode>(Value);
9075 EVT VT = LD->getMemoryVT();
9076 if (!VT.isFloatingPoint() ||
9077 VT != ST->getMemoryVT() ||
9078 LD->isNonTemporal() ||
9079 ST->isNonTemporal() ||
9080 LD->getPointerInfo().getAddrSpace() != 0 ||
9081 ST->getPointerInfo().getAddrSpace() != 0)
9084 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9085 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9086 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9087 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9088 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9091 unsigned LDAlign = LD->getAlignment();
9092 unsigned STAlign = ST->getAlignment();
9093 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9094 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9095 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9098 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9099 LD->getChain(), LD->getBasePtr(),
9100 LD->getPointerInfo(),
9101 false, false, false, LDAlign);
9103 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9104 NewLD, ST->getBasePtr(),
9105 ST->getPointerInfo(),
9106 false, false, STAlign);
9108 AddToWorklist(NewLD.getNode());
9109 AddToWorklist(NewST.getNode());
9110 WorklistRemover DeadNodes(*this);
9111 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9119 /// Helper struct to parse and store a memory address as base + index + offset.
9120 /// We ignore sign extensions when it is safe to do so.
9121 /// The following two expressions are not equivalent. To differentiate we need
9122 /// to store whether there was a sign extension involved in the index
9124 /// (load (i64 add (i64 copyfromreg %c)
9125 /// (i64 signextend (add (i8 load %index)
9129 /// (load (i64 add (i64 copyfromreg %c)
9130 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9132 struct BaseIndexOffset {
9136 bool IsIndexSignExt;
9138 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9140 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9141 bool IsIndexSignExt) :
9142 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9144 bool equalBaseIndex(const BaseIndexOffset &Other) {
9145 return Other.Base == Base && Other.Index == Index &&
9146 Other.IsIndexSignExt == IsIndexSignExt;
9149 /// Parses tree in Ptr for base, index, offset addresses.
9150 static BaseIndexOffset match(SDValue Ptr) {
9151 bool IsIndexSignExt = false;
9153 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9154 // instruction, then it could be just the BASE or everything else we don't
9155 // know how to handle. Just use Ptr as BASE and give up.
9156 if (Ptr->getOpcode() != ISD::ADD)
9157 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9159 // We know that we have at least an ADD instruction. Try to pattern match
9160 // the simple case of BASE + OFFSET.
9161 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9162 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9163 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9167 // Inside a loop the current BASE pointer is calculated using an ADD and a
9168 // MUL instruction. In this case Ptr is the actual BASE pointer.
9169 // (i64 add (i64 %array_ptr)
9170 // (i64 mul (i64 %induction_var)
9171 // (i64 %element_size)))
9172 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9173 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9175 // Look at Base + Index + Offset cases.
9176 SDValue Base = Ptr->getOperand(0);
9177 SDValue IndexOffset = Ptr->getOperand(1);
9179 // Skip signextends.
9180 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9181 IndexOffset = IndexOffset->getOperand(0);
9182 IsIndexSignExt = true;
9185 // Either the case of Base + Index (no offset) or something else.
9186 if (IndexOffset->getOpcode() != ISD::ADD)
9187 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9189 // Now we have the case of Base + Index + offset.
9190 SDValue Index = IndexOffset->getOperand(0);
9191 SDValue Offset = IndexOffset->getOperand(1);
9193 if (!isa<ConstantSDNode>(Offset))
9194 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9196 // Ignore signextends.
9197 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9198 Index = Index->getOperand(0);
9199 IsIndexSignExt = true;
9200 } else IsIndexSignExt = false;
9202 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9203 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9207 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9208 /// is located in a sequence of memory operations connected by a chain.
9210 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9211 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9212 // Ptr to the mem node.
9213 LSBaseSDNode *MemNode;
9214 // Offset from the base ptr.
9215 int64_t OffsetFromBase;
9216 // What is the sequence number of this mem node.
9217 // Lowest mem operand in the DAG starts at zero.
9218 unsigned SequenceNum;
9221 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9222 EVT MemVT = St->getMemoryVT();
9223 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9224 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9225 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9227 // Don't merge vectors into wider inputs.
9228 if (MemVT.isVector() || !MemVT.isSimple())
9231 // Perform an early exit check. Do not bother looking at stored values that
9232 // are not constants or loads.
9233 SDValue StoredVal = St->getValue();
9234 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9235 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9239 // Only look at ends of store sequences.
9240 SDValue Chain = SDValue(St, 0);
9241 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9244 // This holds the base pointer, index, and the offset in bytes from the base
9246 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9248 // We must have a base and an offset.
9249 if (!BasePtr.Base.getNode())
9252 // Do not handle stores to undef base pointers.
9253 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9256 // Save the LoadSDNodes that we find in the chain.
9257 // We need to make sure that these nodes do not interfere with
9258 // any of the store nodes.
9259 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9261 // Save the StoreSDNodes that we find in the chain.
9262 SmallVector<MemOpLink, 8> StoreNodes;
9264 // Walk up the chain and look for nodes with offsets from the same
9265 // base pointer. Stop when reaching an instruction with a different kind
9266 // or instruction which has a different base pointer.
9268 StoreSDNode *Index = St;
9270 // If the chain has more than one use, then we can't reorder the mem ops.
9271 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9274 // Find the base pointer and offset for this memory node.
9275 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9277 // Check that the base pointer is the same as the original one.
9278 if (!Ptr.equalBaseIndex(BasePtr))
9281 // Check that the alignment is the same.
9282 if (Index->getAlignment() != St->getAlignment())
9285 // The memory operands must not be volatile.
9286 if (Index->isVolatile() || Index->isIndexed())
9290 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9291 if (St->isTruncatingStore())
9294 // The stored memory type must be the same.
9295 if (Index->getMemoryVT() != MemVT)
9298 // We do not allow unaligned stores because we want to prevent overriding
9300 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9303 // We found a potential memory operand to merge.
9304 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9306 // Find the next memory operand in the chain. If the next operand in the
9307 // chain is a store then move up and continue the scan with the next
9308 // memory operand. If the next operand is a load save it and use alias
9309 // information to check if it interferes with anything.
9310 SDNode *NextInChain = Index->getChain().getNode();
9312 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9313 // We found a store node. Use it for the next iteration.
9316 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9317 if (Ldn->isVolatile()) {
9322 // Save the load node for later. Continue the scan.
9323 AliasLoadNodes.push_back(Ldn);
9324 NextInChain = Ldn->getChain().getNode();
9333 // Check if there is anything to merge.
9334 if (StoreNodes.size() < 2)
9337 // Sort the memory operands according to their distance from the base pointer.
9338 std::sort(StoreNodes.begin(), StoreNodes.end(),
9339 [](MemOpLink LHS, MemOpLink RHS) {
9340 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9341 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9342 LHS.SequenceNum > RHS.SequenceNum);
9345 // Scan the memory operations on the chain and find the first non-consecutive
9346 // store memory address.
9347 unsigned LastConsecutiveStore = 0;
9348 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9349 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9351 // Check that the addresses are consecutive starting from the second
9352 // element in the list of stores.
9354 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9355 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9360 // Check if this store interferes with any of the loads that we found.
9361 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9362 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9366 // We found a load that alias with this store. Stop the sequence.
9370 // Mark this node as useful.
9371 LastConsecutiveStore = i;
9374 // The node with the lowest store address.
9375 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9377 // Store the constants into memory as one consecutive store.
9379 unsigned LastLegalType = 0;
9380 unsigned LastLegalVectorType = 0;
9381 bool NonZero = false;
9382 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9383 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9384 SDValue StoredVal = St->getValue();
9386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9387 NonZero |= !C->isNullValue();
9388 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9389 NonZero |= !C->getConstantFPValue()->isNullValue();
9395 // Find a legal type for the constant store.
9396 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9397 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9398 if (TLI.isTypeLegal(StoreTy))
9399 LastLegalType = i+1;
9400 // Or check whether a truncstore is legal.
9401 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9402 TargetLowering::TypePromoteInteger) {
9403 EVT LegalizedStoredValueTy =
9404 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9405 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9406 LastLegalType = i+1;
9409 // Find a legal type for the vector store.
9410 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9411 if (TLI.isTypeLegal(Ty))
9412 LastLegalVectorType = i + 1;
9415 // We only use vectors if the constant is known to be zero and the
9416 // function is not marked with the noimplicitfloat attribute.
9417 if (NonZero || NoVectors)
9418 LastLegalVectorType = 0;
9420 // Check if we found a legal integer type to store.
9421 if (LastLegalType == 0 && LastLegalVectorType == 0)
9424 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9425 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9427 // Make sure we have something to merge.
9431 unsigned EarliestNodeUsed = 0;
9432 for (unsigned i=0; i < NumElem; ++i) {
9433 // Find a chain for the new wide-store operand. Notice that some
9434 // of the store nodes that we found may not be selected for inclusion
9435 // in the wide store. The chain we use needs to be the chain of the
9436 // earliest store node which is *used* and replaced by the wide store.
9437 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9438 EarliestNodeUsed = i;
9441 // The earliest Node in the DAG.
9442 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9443 SDLoc DL(StoreNodes[0].MemNode);
9447 // Find a legal type for the vector store.
9448 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9449 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9450 StoredVal = DAG.getConstant(0, Ty);
9452 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9453 APInt StoreInt(StoreBW, 0);
9455 // Construct a single integer constant which is made of the smaller
9457 bool IsLE = TLI.isLittleEndian();
9458 for (unsigned i = 0; i < NumElem ; ++i) {
9459 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9460 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9461 SDValue Val = St->getValue();
9462 StoreInt<<=ElementSizeBytes*8;
9463 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9464 StoreInt|=C->getAPIntValue().zext(StoreBW);
9465 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9466 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9468 assert(false && "Invalid constant element type");
9472 // Create the new Load and Store operations.
9473 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9474 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9477 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9478 FirstInChain->getBasePtr(),
9479 FirstInChain->getPointerInfo(),
9481 FirstInChain->getAlignment());
9483 // Replace the first store with the new store
9484 CombineTo(EarliestOp, NewStore);
9485 // Erase all other stores.
9486 for (unsigned i = 0; i < NumElem ; ++i) {
9487 if (StoreNodes[i].MemNode == EarliestOp)
9489 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9490 // ReplaceAllUsesWith will replace all uses that existed when it was
9491 // called, but graph optimizations may cause new ones to appear. For
9492 // example, the case in pr14333 looks like
9494 // St's chain -> St -> another store -> X
9496 // And the only difference from St to the other store is the chain.
9497 // When we change it's chain to be St's chain they become identical,
9498 // get CSEed and the net result is that X is now a use of St.
9499 // Since we know that St is redundant, just iterate.
9500 while (!St->use_empty())
9501 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9502 deleteAndRecombine(St);
9508 // Below we handle the case of multiple consecutive stores that
9509 // come from multiple consecutive loads. We merge them into a single
9510 // wide load and a single wide store.
9512 // Look for load nodes which are used by the stored values.
9513 SmallVector<MemOpLink, 8> LoadNodes;
9515 // Find acceptable loads. Loads need to have the same chain (token factor),
9516 // must not be zext, volatile, indexed, and they must be consecutive.
9517 BaseIndexOffset LdBasePtr;
9518 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9519 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9520 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9523 // Loads must only have one use.
9524 if (!Ld->hasNUsesOfValue(1, 0))
9527 // Check that the alignment is the same as the stores.
9528 if (Ld->getAlignment() != St->getAlignment())
9531 // The memory operands must not be volatile.
9532 if (Ld->isVolatile() || Ld->isIndexed())
9535 // We do not accept ext loads.
9536 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9539 // The stored memory type must be the same.
9540 if (Ld->getMemoryVT() != MemVT)
9543 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9544 // If this is not the first ptr that we check.
9545 if (LdBasePtr.Base.getNode()) {
9546 // The base ptr must be the same.
9547 if (!LdPtr.equalBaseIndex(LdBasePtr))
9550 // Check that all other base pointers are the same as this one.
9554 // We found a potential memory operand to merge.
9555 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9558 if (LoadNodes.size() < 2)
9561 // If we have load/store pair instructions and we only have two values,
9563 unsigned RequiredAlignment;
9564 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9565 St->getAlignment() >= RequiredAlignment)
9568 // Scan the memory operations on the chain and find the first non-consecutive
9569 // load memory address. These variables hold the index in the store node
9571 unsigned LastConsecutiveLoad = 0;
9572 // This variable refers to the size and not index in the array.
9573 unsigned LastLegalVectorType = 0;
9574 unsigned LastLegalIntegerType = 0;
9575 StartAddress = LoadNodes[0].OffsetFromBase;
9576 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9577 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9578 // All loads much share the same chain.
9579 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9582 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9583 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9585 LastConsecutiveLoad = i;
9587 // Find a legal type for the vector store.
9588 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9589 if (TLI.isTypeLegal(StoreTy))
9590 LastLegalVectorType = i + 1;
9592 // Find a legal type for the integer store.
9593 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9594 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9595 if (TLI.isTypeLegal(StoreTy))
9596 LastLegalIntegerType = i + 1;
9597 // Or check whether a truncstore and extload is legal.
9598 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9599 TargetLowering::TypePromoteInteger) {
9600 EVT LegalizedStoredValueTy =
9601 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9602 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9603 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9604 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9605 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9606 LastLegalIntegerType = i+1;
9610 // Only use vector types if the vector type is larger than the integer type.
9611 // If they are the same, use integers.
9612 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9613 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9615 // We add +1 here because the LastXXX variables refer to location while
9616 // the NumElem refers to array/index size.
9617 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9618 NumElem = std::min(LastLegalType, NumElem);
9623 // The earliest Node in the DAG.
9624 unsigned EarliestNodeUsed = 0;
9625 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9626 for (unsigned i=1; i<NumElem; ++i) {
9627 // Find a chain for the new wide-store operand. Notice that some
9628 // of the store nodes that we found may not be selected for inclusion
9629 // in the wide store. The chain we use needs to be the chain of the
9630 // earliest store node which is *used* and replaced by the wide store.
9631 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9632 EarliestNodeUsed = i;
9635 // Find if it is better to use vectors or integers to load and store
9639 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9641 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9642 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9645 SDLoc LoadDL(LoadNodes[0].MemNode);
9646 SDLoc StoreDL(StoreNodes[0].MemNode);
9648 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9649 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9650 FirstLoad->getChain(),
9651 FirstLoad->getBasePtr(),
9652 FirstLoad->getPointerInfo(),
9653 false, false, false,
9654 FirstLoad->getAlignment());
9656 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9657 FirstInChain->getBasePtr(),
9658 FirstInChain->getPointerInfo(), false, false,
9659 FirstInChain->getAlignment());
9661 // Replace one of the loads with the new load.
9662 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9663 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9664 SDValue(NewLoad.getNode(), 1));
9666 // Remove the rest of the load chains.
9667 for (unsigned i = 1; i < NumElem ; ++i) {
9668 // Replace all chain users of the old load nodes with the chain of the new
9670 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9671 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9674 // Replace the first store with the new store.
9675 CombineTo(EarliestOp, NewStore);
9676 // Erase all other stores.
9677 for (unsigned i = 0; i < NumElem ; ++i) {
9678 // Remove all Store nodes.
9679 if (StoreNodes[i].MemNode == EarliestOp)
9681 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9682 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9683 deleteAndRecombine(St);
9689 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9690 StoreSDNode *ST = cast<StoreSDNode>(N);
9691 SDValue Chain = ST->getChain();
9692 SDValue Value = ST->getValue();
9693 SDValue Ptr = ST->getBasePtr();
9695 // If this is a store of a bit convert, store the input value if the
9696 // resultant store does not need a higher alignment than the original.
9697 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9698 ST->isUnindexed()) {
9699 unsigned OrigAlign = ST->getAlignment();
9700 EVT SVT = Value.getOperand(0).getValueType();
9701 unsigned Align = TLI.getDataLayout()->
9702 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9703 if (Align <= OrigAlign &&
9704 ((!LegalOperations && !ST->isVolatile()) ||
9705 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9706 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9707 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9708 ST->isNonTemporal(), OrigAlign,
9712 // Turn 'store undef, Ptr' -> nothing.
9713 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9716 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9717 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9718 // NOTE: If the original store is volatile, this transform must not increase
9719 // the number of stores. For example, on x86-32 an f64 can be stored in one
9720 // processor operation but an i64 (which is not legal) requires two. So the
9721 // transform should not be done in this case.
9722 if (Value.getOpcode() != ISD::TargetConstantFP) {
9724 switch (CFP->getSimpleValueType(0).SimpleTy) {
9725 default: llvm_unreachable("Unknown FP type");
9726 case MVT::f16: // We don't do this for these yet.
9732 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9733 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9734 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9735 bitcastToAPInt().getZExtValue(), MVT::i32);
9736 return DAG.getStore(Chain, SDLoc(N), Tmp,
9737 Ptr, ST->getMemOperand());
9741 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9742 !ST->isVolatile()) ||
9743 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9744 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9745 getZExtValue(), MVT::i64);
9746 return DAG.getStore(Chain, SDLoc(N), Tmp,
9747 Ptr, ST->getMemOperand());
9750 if (!ST->isVolatile() &&
9751 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9752 // Many FP stores are not made apparent until after legalize, e.g. for
9753 // argument passing. Since this is so common, custom legalize the
9754 // 64-bit integer store into two 32-bit stores.
9755 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9756 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9757 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9758 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9760 unsigned Alignment = ST->getAlignment();
9761 bool isVolatile = ST->isVolatile();
9762 bool isNonTemporal = ST->isNonTemporal();
9763 AAMDNodes AAInfo = ST->getAAInfo();
9765 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9766 Ptr, ST->getPointerInfo(),
9767 isVolatile, isNonTemporal,
9768 ST->getAlignment(), AAInfo);
9769 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9770 DAG.getConstant(4, Ptr.getValueType()));
9771 Alignment = MinAlign(Alignment, 4U);
9772 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9773 Ptr, ST->getPointerInfo().getWithOffset(4),
9774 isVolatile, isNonTemporal,
9776 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9785 // Try to infer better alignment information than the store already has.
9786 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9787 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9788 if (Align > ST->getAlignment())
9789 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9790 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9791 ST->isVolatile(), ST->isNonTemporal(), Align,
9796 // Try transforming a pair floating point load / store ops to integer
9797 // load / store ops.
9798 SDValue NewST = TransformFPLoadStorePair(N);
9799 if (NewST.getNode())
9802 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9803 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9805 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9806 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9809 if (UseAA && ST->isUnindexed()) {
9810 // Walk up chain skipping non-aliasing memory nodes.
9811 SDValue BetterChain = FindBetterChain(N, Chain);
9813 // If there is a better chain.
9814 if (Chain != BetterChain) {
9817 // Replace the chain to avoid dependency.
9818 if (ST->isTruncatingStore()) {
9819 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9820 ST->getMemoryVT(), ST->getMemOperand());
9822 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9823 ST->getMemOperand());
9826 // Create token to keep both nodes around.
9827 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9828 MVT::Other, Chain, ReplStore);
9830 // Make sure the new and old chains are cleaned up.
9831 AddToWorklist(Token.getNode());
9833 // Don't add users to work list.
9834 return CombineTo(N, Token, false);
9838 // Try transforming N to an indexed store.
9839 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9840 return SDValue(N, 0);
9842 // FIXME: is there such a thing as a truncating indexed store?
9843 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9844 Value.getValueType().isInteger()) {
9845 // See if we can simplify the input to this truncstore with knowledge that
9846 // only the low bits are being used. For example:
9847 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9849 GetDemandedBits(Value,
9850 APInt::getLowBitsSet(
9851 Value.getValueType().getScalarType().getSizeInBits(),
9852 ST->getMemoryVT().getScalarType().getSizeInBits()));
9853 AddToWorklist(Value.getNode());
9854 if (Shorter.getNode())
9855 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9856 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9858 // Otherwise, see if we can simplify the operation with
9859 // SimplifyDemandedBits, which only works if the value has a single use.
9860 if (SimplifyDemandedBits(Value,
9861 APInt::getLowBitsSet(
9862 Value.getValueType().getScalarType().getSizeInBits(),
9863 ST->getMemoryVT().getScalarType().getSizeInBits())))
9864 return SDValue(N, 0);
9867 // If this is a load followed by a store to the same location, then the store
9869 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9870 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9871 ST->isUnindexed() && !ST->isVolatile() &&
9872 // There can't be any side effects between the load and store, such as
9874 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9875 // The store is dead, remove it.
9880 // If this is a store followed by a store with the same value to the same
9881 // location, then the store is dead/noop.
9882 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9883 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9884 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9885 ST1->isUnindexed() && !ST1->isVolatile()) {
9886 // The store is dead, remove it.
9891 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9892 // truncating store. We can do this even if this is already a truncstore.
9893 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9894 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9895 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9896 ST->getMemoryVT())) {
9897 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9898 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9901 // Only perform this optimization before the types are legal, because we
9902 // don't want to perform this optimization on every DAGCombine invocation.
9904 bool EverChanged = false;
9907 // There can be multiple store sequences on the same chain.
9908 // Keep trying to merge store sequences until we are unable to do so
9909 // or until we merge the last store on the chain.
9910 bool Changed = MergeConsecutiveStores(ST);
9911 EverChanged |= Changed;
9912 if (!Changed) break;
9913 } while (ST->getOpcode() != ISD::DELETED_NODE);
9916 return SDValue(N, 0);
9919 return ReduceLoadOpStoreWidth(N);
9922 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9923 SDValue InVec = N->getOperand(0);
9924 SDValue InVal = N->getOperand(1);
9925 SDValue EltNo = N->getOperand(2);
9928 // If the inserted element is an UNDEF, just use the input vector.
9929 if (InVal.getOpcode() == ISD::UNDEF)
9932 EVT VT = InVec.getValueType();
9934 // If we can't generate a legal BUILD_VECTOR, exit
9935 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9938 // Check that we know which element is being inserted
9939 if (!isa<ConstantSDNode>(EltNo))
9941 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9943 // Canonicalize insert_vector_elt dag nodes.
9945 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9946 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9948 // Do this only if the child insert_vector node has one use; also
9949 // do this only if indices are both constants and Idx1 < Idx0.
9950 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9951 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9953 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9954 if (Elt < OtherElt) {
9956 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9957 InVec.getOperand(0), InVal, EltNo);
9958 AddToWorklist(NewOp.getNode());
9959 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9960 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9964 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9965 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9967 SmallVector<SDValue, 8> Ops;
9968 // Do not combine these two vectors if the output vector will not replace
9969 // the input vector.
9970 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9971 Ops.append(InVec.getNode()->op_begin(),
9972 InVec.getNode()->op_end());
9973 } else if (InVec.getOpcode() == ISD::UNDEF) {
9974 unsigned NElts = VT.getVectorNumElements();
9975 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9980 // Insert the element
9981 if (Elt < Ops.size()) {
9982 // All the operands of BUILD_VECTOR must have the same type;
9983 // we enforce that here.
9984 EVT OpVT = Ops[0].getValueType();
9985 if (InVal.getValueType() != OpVT)
9986 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9987 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9988 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9992 // Return the new vector
9993 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9996 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9997 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9998 EVT ResultVT = EVE->getValueType(0);
9999 EVT VecEltVT = InVecVT.getVectorElementType();
10000 unsigned Align = OriginalLoad->getAlignment();
10001 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10002 VecEltVT.getTypeForEVT(*DAG.getContext()));
10004 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10009 SDValue NewPtr = OriginalLoad->getBasePtr();
10011 EVT PtrType = NewPtr.getValueType();
10012 MachinePointerInfo MPI;
10013 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10014 int Elt = ConstEltNo->getZExtValue();
10015 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10016 if (TLI.isBigEndian())
10017 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10018 Offset = DAG.getConstant(PtrOff, PtrType);
10019 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10021 Offset = DAG.getNode(
10022 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10023 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10024 if (TLI.isBigEndian())
10025 Offset = DAG.getNode(
10026 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10027 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10028 MPI = OriginalLoad->getPointerInfo();
10030 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10032 // The replacement we need to do here is a little tricky: we need to
10033 // replace an extractelement of a load with a load.
10034 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10035 // Note that this replacement assumes that the extractvalue is the only
10036 // use of the load; that's okay because we don't want to perform this
10037 // transformation in other cases anyway.
10040 if (ResultVT.bitsGT(VecEltVT)) {
10041 // If the result type of vextract is wider than the load, then issue an
10042 // extending load instead.
10043 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10046 Load = DAG.getExtLoad(
10047 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10048 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10049 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10050 Chain = Load.getValue(1);
10052 Load = DAG.getLoad(
10053 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10054 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10055 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10056 Chain = Load.getValue(1);
10057 if (ResultVT.bitsLT(VecEltVT))
10058 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10060 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10062 WorklistRemover DeadNodes(*this);
10063 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10064 SDValue To[] = { Load, Chain };
10065 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10066 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10067 // worklist explicitly as well.
10068 AddToWorklist(Load.getNode());
10069 AddUsersToWorklist(Load.getNode()); // Add users too
10070 // Make sure to revisit this node to clean it up; it will usually be dead.
10071 AddToWorklist(EVE);
10073 return SDValue(EVE, 0);
10076 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10077 // (vextract (scalar_to_vector val, 0) -> val
10078 SDValue InVec = N->getOperand(0);
10079 EVT VT = InVec.getValueType();
10080 EVT NVT = N->getValueType(0);
10082 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10083 // Check if the result type doesn't match the inserted element type. A
10084 // SCALAR_TO_VECTOR may truncate the inserted element and the
10085 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10086 SDValue InOp = InVec.getOperand(0);
10087 if (InOp.getValueType() != NVT) {
10088 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10089 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10094 SDValue EltNo = N->getOperand(1);
10095 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10097 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10098 // We only perform this optimization before the op legalization phase because
10099 // we may introduce new vector instructions which are not backed by TD
10100 // patterns. For example on AVX, extracting elements from a wide vector
10101 // without using extract_subvector. However, if we can find an underlying
10102 // scalar value, then we can always use that.
10103 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10105 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10106 int NumElem = VT.getVectorNumElements();
10107 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10108 // Find the new index to extract from.
10109 int OrigElt = SVOp->getMaskElt(Elt);
10111 // Extracting an undef index is undef.
10113 return DAG.getUNDEF(NVT);
10115 // Select the right vector half to extract from.
10117 if (OrigElt < NumElem) {
10118 SVInVec = InVec->getOperand(0);
10120 SVInVec = InVec->getOperand(1);
10121 OrigElt -= NumElem;
10124 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10125 SDValue InOp = SVInVec.getOperand(OrigElt);
10126 if (InOp.getValueType() != NVT) {
10127 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10128 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10134 // FIXME: We should handle recursing on other vector shuffles and
10135 // scalar_to_vector here as well.
10137 if (!LegalOperations) {
10138 EVT IndexTy = TLI.getVectorIdxTy();
10139 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10140 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10144 bool BCNumEltsChanged = false;
10145 EVT ExtVT = VT.getVectorElementType();
10148 // If the result of load has to be truncated, then it's not necessarily
10150 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10153 if (InVec.getOpcode() == ISD::BITCAST) {
10154 // Don't duplicate a load with other uses.
10155 if (!InVec.hasOneUse())
10158 EVT BCVT = InVec.getOperand(0).getValueType();
10159 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10161 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10162 BCNumEltsChanged = true;
10163 InVec = InVec.getOperand(0);
10164 ExtVT = BCVT.getVectorElementType();
10167 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10168 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10169 ISD::isNormalLoad(InVec.getNode()) &&
10170 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10171 SDValue Index = N->getOperand(1);
10172 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10173 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10177 // Perform only after legalization to ensure build_vector / vector_shuffle
10178 // optimizations have already been done.
10179 if (!LegalOperations) return SDValue();
10181 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10182 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10183 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10186 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10188 LoadSDNode *LN0 = nullptr;
10189 const ShuffleVectorSDNode *SVN = nullptr;
10190 if (ISD::isNormalLoad(InVec.getNode())) {
10191 LN0 = cast<LoadSDNode>(InVec);
10192 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10193 InVec.getOperand(0).getValueType() == ExtVT &&
10194 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10195 // Don't duplicate a load with other uses.
10196 if (!InVec.hasOneUse())
10199 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10200 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10201 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10203 // (load $addr+1*size)
10205 // Don't duplicate a load with other uses.
10206 if (!InVec.hasOneUse())
10209 // If the bit convert changed the number of elements, it is unsafe
10210 // to examine the mask.
10211 if (BCNumEltsChanged)
10214 // Select the input vector, guarding against out of range extract vector.
10215 unsigned NumElems = VT.getVectorNumElements();
10216 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10217 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10219 if (InVec.getOpcode() == ISD::BITCAST) {
10220 // Don't duplicate a load with other uses.
10221 if (!InVec.hasOneUse())
10224 InVec = InVec.getOperand(0);
10226 if (ISD::isNormalLoad(InVec.getNode())) {
10227 LN0 = cast<LoadSDNode>(InVec);
10228 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10229 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10233 // Make sure we found a non-volatile load and the extractelement is
10235 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10238 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10240 return DAG.getUNDEF(LVT);
10242 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10248 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10249 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10250 // We perform this optimization post type-legalization because
10251 // the type-legalizer often scalarizes integer-promoted vectors.
10252 // Performing this optimization before may create bit-casts which
10253 // will be type-legalized to complex code sequences.
10254 // We perform this optimization only before the operation legalizer because we
10255 // may introduce illegal operations.
10256 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10259 unsigned NumInScalars = N->getNumOperands();
10261 EVT VT = N->getValueType(0);
10263 // Check to see if this is a BUILD_VECTOR of a bunch of values
10264 // which come from any_extend or zero_extend nodes. If so, we can create
10265 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10266 // optimizations. We do not handle sign-extend because we can't fill the sign
10268 EVT SourceType = MVT::Other;
10269 bool AllAnyExt = true;
10271 for (unsigned i = 0; i != NumInScalars; ++i) {
10272 SDValue In = N->getOperand(i);
10273 // Ignore undef inputs.
10274 if (In.getOpcode() == ISD::UNDEF) continue;
10276 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10277 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10279 // Abort if the element is not an extension.
10280 if (!ZeroExt && !AnyExt) {
10281 SourceType = MVT::Other;
10285 // The input is a ZeroExt or AnyExt. Check the original type.
10286 EVT InTy = In.getOperand(0).getValueType();
10288 // Check that all of the widened source types are the same.
10289 if (SourceType == MVT::Other)
10292 else if (InTy != SourceType) {
10293 // Multiple income types. Abort.
10294 SourceType = MVT::Other;
10298 // Check if all of the extends are ANY_EXTENDs.
10299 AllAnyExt &= AnyExt;
10302 // In order to have valid types, all of the inputs must be extended from the
10303 // same source type and all of the inputs must be any or zero extend.
10304 // Scalar sizes must be a power of two.
10305 EVT OutScalarTy = VT.getScalarType();
10306 bool ValidTypes = SourceType != MVT::Other &&
10307 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10308 isPowerOf2_32(SourceType.getSizeInBits());
10310 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10311 // turn into a single shuffle instruction.
10315 bool isLE = TLI.isLittleEndian();
10316 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10317 assert(ElemRatio > 1 && "Invalid element size ratio");
10318 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10319 DAG.getConstant(0, SourceType);
10321 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10322 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10324 // Populate the new build_vector
10325 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10326 SDValue Cast = N->getOperand(i);
10327 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10328 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10329 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10331 if (Cast.getOpcode() == ISD::UNDEF)
10332 In = DAG.getUNDEF(SourceType);
10334 In = Cast->getOperand(0);
10335 unsigned Index = isLE ? (i * ElemRatio) :
10336 (i * ElemRatio + (ElemRatio - 1));
10338 assert(Index < Ops.size() && "Invalid index");
10342 // The type of the new BUILD_VECTOR node.
10343 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10344 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10345 "Invalid vector size");
10346 // Check if the new vector type is legal.
10347 if (!isTypeLegal(VecVT)) return SDValue();
10349 // Make the new BUILD_VECTOR.
10350 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10352 // The new BUILD_VECTOR node has the potential to be further optimized.
10353 AddToWorklist(BV.getNode());
10354 // Bitcast to the desired type.
10355 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10358 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10359 EVT VT = N->getValueType(0);
10361 unsigned NumInScalars = N->getNumOperands();
10364 EVT SrcVT = MVT::Other;
10365 unsigned Opcode = ISD::DELETED_NODE;
10366 unsigned NumDefs = 0;
10368 for (unsigned i = 0; i != NumInScalars; ++i) {
10369 SDValue In = N->getOperand(i);
10370 unsigned Opc = In.getOpcode();
10372 if (Opc == ISD::UNDEF)
10375 // If all scalar values are floats and converted from integers.
10376 if (Opcode == ISD::DELETED_NODE &&
10377 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10384 EVT InVT = In.getOperand(0).getValueType();
10386 // If all scalar values are typed differently, bail out. It's chosen to
10387 // simplify BUILD_VECTOR of integer types.
10388 if (SrcVT == MVT::Other)
10395 // If the vector has just one element defined, it's not worth to fold it into
10396 // a vectorized one.
10400 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10401 && "Should only handle conversion from integer to float.");
10402 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10404 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10406 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10409 SmallVector<SDValue, 8> Opnds;
10410 for (unsigned i = 0; i != NumInScalars; ++i) {
10411 SDValue In = N->getOperand(i);
10413 if (In.getOpcode() == ISD::UNDEF)
10414 Opnds.push_back(DAG.getUNDEF(SrcVT));
10416 Opnds.push_back(In.getOperand(0));
10418 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10419 AddToWorklist(BV.getNode());
10421 return DAG.getNode(Opcode, dl, VT, BV);
10424 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10425 unsigned NumInScalars = N->getNumOperands();
10427 EVT VT = N->getValueType(0);
10429 // A vector built entirely of undefs is undef.
10430 if (ISD::allOperandsUndef(N))
10431 return DAG.getUNDEF(VT);
10433 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10437 V = reduceBuildVecConvertToConvertBuildVec(N);
10441 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10442 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10443 // at most two distinct vectors, turn this into a shuffle node.
10445 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10446 if (!isTypeLegal(VT))
10449 // May only combine to shuffle after legalize if shuffle is legal.
10450 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10453 SDValue VecIn1, VecIn2;
10454 for (unsigned i = 0; i != NumInScalars; ++i) {
10455 // Ignore undef inputs.
10456 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10458 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10459 // constant index, bail out.
10460 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10461 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10462 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10466 // We allow up to two distinct input vectors.
10467 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10468 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10471 if (!VecIn1.getNode()) {
10472 VecIn1 = ExtractedFromVec;
10473 } else if (!VecIn2.getNode()) {
10474 VecIn2 = ExtractedFromVec;
10476 // Too many inputs.
10477 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10482 // If everything is good, we can make a shuffle operation.
10483 if (VecIn1.getNode()) {
10484 SmallVector<int, 8> Mask;
10485 for (unsigned i = 0; i != NumInScalars; ++i) {
10486 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10487 Mask.push_back(-1);
10491 // If extracting from the first vector, just use the index directly.
10492 SDValue Extract = N->getOperand(i);
10493 SDValue ExtVal = Extract.getOperand(1);
10494 if (Extract.getOperand(0) == VecIn1) {
10495 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10496 if (ExtIndex > VT.getVectorNumElements())
10499 Mask.push_back(ExtIndex);
10503 // Otherwise, use InIdx + VecSize
10504 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10505 Mask.push_back(Idx+NumInScalars);
10508 // We can't generate a shuffle node with mismatched input and output types.
10509 // Attempt to transform a single input vector to the correct type.
10510 if ((VT != VecIn1.getValueType())) {
10511 // We don't support shuffeling between TWO values of different types.
10512 if (VecIn2.getNode())
10515 // We only support widening of vectors which are half the size of the
10516 // output registers. For example XMM->YMM widening on X86 with AVX.
10517 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10520 // If the input vector type has a different base type to the output
10521 // vector type, bail out.
10522 if (VecIn1.getValueType().getVectorElementType() !=
10523 VT.getVectorElementType())
10526 // Widen the input vector by adding undef values.
10527 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10528 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10531 // If VecIn2 is unused then change it to undef.
10532 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10534 // Check that we were able to transform all incoming values to the same
10536 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10537 VecIn1.getValueType() != VT)
10540 // Return the new VECTOR_SHUFFLE node.
10544 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10550 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10551 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10552 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10553 // inputs come from at most two distinct vectors, turn this into a shuffle
10556 // If we only have one input vector, we don't need to do any concatenation.
10557 if (N->getNumOperands() == 1)
10558 return N->getOperand(0);
10560 // Check if all of the operands are undefs.
10561 EVT VT = N->getValueType(0);
10562 if (ISD::allOperandsUndef(N))
10563 return DAG.getUNDEF(VT);
10565 // Optimize concat_vectors where one of the vectors is undef.
10566 if (N->getNumOperands() == 2 &&
10567 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10568 SDValue In = N->getOperand(0);
10569 assert(In.getValueType().isVector() && "Must concat vectors");
10571 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10572 if (In->getOpcode() == ISD::BITCAST &&
10573 !In->getOperand(0)->getValueType(0).isVector()) {
10574 SDValue Scalar = In->getOperand(0);
10575 EVT SclTy = Scalar->getValueType(0);
10577 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10580 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10581 VT.getSizeInBits() / SclTy.getSizeInBits());
10582 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10585 SDLoc dl = SDLoc(N);
10586 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10587 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10591 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10592 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10593 if (N->getNumOperands() == 2 &&
10594 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10595 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10596 EVT VT = N->getValueType(0);
10597 SDValue N0 = N->getOperand(0);
10598 SDValue N1 = N->getOperand(1);
10599 SmallVector<SDValue, 8> Opnds;
10600 unsigned BuildVecNumElts = N0.getNumOperands();
10602 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10603 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10604 if (SclTy0.isFloatingPoint()) {
10605 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10606 Opnds.push_back(N0.getOperand(i));
10607 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10608 Opnds.push_back(N1.getOperand(i));
10610 // If BUILD_VECTOR are from built from integer, they may have different
10611 // operand types. Get the smaller type and truncate all operands to it.
10612 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10613 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10614 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10615 N0.getOperand(i)));
10616 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10617 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10618 N1.getOperand(i)));
10621 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10624 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10625 // nodes often generate nop CONCAT_VECTOR nodes.
10626 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10627 // place the incoming vectors at the exact same location.
10628 SDValue SingleSource = SDValue();
10629 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10631 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10632 SDValue Op = N->getOperand(i);
10634 if (Op.getOpcode() == ISD::UNDEF)
10637 // Check if this is the identity extract:
10638 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10641 // Find the single incoming vector for the extract_subvector.
10642 if (SingleSource.getNode()) {
10643 if (Op.getOperand(0) != SingleSource)
10646 SingleSource = Op.getOperand(0);
10648 // Check the source type is the same as the type of the result.
10649 // If not, this concat may extend the vector, so we can not
10650 // optimize it away.
10651 if (SingleSource.getValueType() != N->getValueType(0))
10655 unsigned IdentityIndex = i * PartNumElem;
10656 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10657 // The extract index must be constant.
10661 // Check that we are reading from the identity index.
10662 if (CS->getZExtValue() != IdentityIndex)
10666 if (SingleSource.getNode())
10667 return SingleSource;
10672 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10673 EVT NVT = N->getValueType(0);
10674 SDValue V = N->getOperand(0);
10676 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10678 // (extract_subvec (concat V1, V2, ...), i)
10681 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10683 if (V->getOperand(0).getValueType() != NVT)
10685 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10686 unsigned NumElems = NVT.getVectorNumElements();
10687 assert((Idx % NumElems) == 0 &&
10688 "IDX in concat is not a multiple of the result vector length.");
10689 return V->getOperand(Idx / NumElems);
10693 if (V->getOpcode() == ISD::BITCAST)
10694 V = V.getOperand(0);
10696 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10698 // Handle only simple case where vector being inserted and vector
10699 // being extracted are of same type, and are half size of larger vectors.
10700 EVT BigVT = V->getOperand(0).getValueType();
10701 EVT SmallVT = V->getOperand(1).getValueType();
10702 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10705 // Only handle cases where both indexes are constants with the same type.
10706 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10707 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10709 if (InsIdx && ExtIdx &&
10710 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10711 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10713 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10715 // indices are equal or bit offsets are equal => V1
10716 // otherwise => (extract_subvec V1, ExtIdx)
10717 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10718 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10719 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10720 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10721 DAG.getNode(ISD::BITCAST, dl,
10722 N->getOperand(0).getValueType(),
10723 V->getOperand(0)), N->getOperand(1));
10730 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10731 SDValue V, SelectionDAG &DAG) {
10733 EVT VT = V.getValueType();
10735 switch (V.getOpcode()) {
10739 case ISD::CONCAT_VECTORS: {
10740 EVT OpVT = V->getOperand(0).getValueType();
10741 int OpSize = OpVT.getVectorNumElements();
10742 SmallBitVector OpUsedElements(OpSize, false);
10743 bool FoundSimplification = false;
10744 SmallVector<SDValue, 4> NewOps;
10745 NewOps.reserve(V->getNumOperands());
10746 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10747 SDValue Op = V->getOperand(i);
10748 bool OpUsed = false;
10749 for (int j = 0; j < OpSize; ++j)
10750 if (UsedElements[i * OpSize + j]) {
10751 OpUsedElements[j] = true;
10755 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10756 : DAG.getUNDEF(OpVT));
10757 FoundSimplification |= Op == NewOps.back();
10758 OpUsedElements.reset();
10760 if (FoundSimplification)
10761 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10765 case ISD::INSERT_SUBVECTOR: {
10766 SDValue BaseV = V->getOperand(0);
10767 SDValue SubV = V->getOperand(1);
10768 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10772 int SubSize = SubV.getValueType().getVectorNumElements();
10773 int Idx = IdxN->getZExtValue();
10774 bool SubVectorUsed = false;
10775 SmallBitVector SubUsedElements(SubSize, false);
10776 for (int i = 0; i < SubSize; ++i)
10777 if (UsedElements[i + Idx]) {
10778 SubVectorUsed = true;
10779 SubUsedElements[i] = true;
10780 UsedElements[i + Idx] = false;
10783 // Now recurse on both the base and sub vectors.
10784 SDValue SimplifiedSubV =
10786 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10787 : DAG.getUNDEF(SubV.getValueType());
10788 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10789 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10790 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10791 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10797 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10798 SDValue N1, SelectionDAG &DAG) {
10799 EVT VT = SVN->getValueType(0);
10800 int NumElts = VT.getVectorNumElements();
10801 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10802 for (int M : SVN->getMask())
10803 if (M >= 0 && M < NumElts)
10804 N0UsedElements[M] = true;
10805 else if (M >= NumElts)
10806 N1UsedElements[M - NumElts] = true;
10808 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10809 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10810 if (S0 == N0 && S1 == N1)
10813 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10816 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10817 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10818 EVT VT = N->getValueType(0);
10819 unsigned NumElts = VT.getVectorNumElements();
10821 SDValue N0 = N->getOperand(0);
10822 SDValue N1 = N->getOperand(1);
10823 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10825 SmallVector<SDValue, 4> Ops;
10826 EVT ConcatVT = N0.getOperand(0).getValueType();
10827 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10828 unsigned NumConcats = NumElts / NumElemsPerConcat;
10830 // Look at every vector that's inserted. We're looking for exact
10831 // subvector-sized copies from a concatenated vector
10832 for (unsigned I = 0; I != NumConcats; ++I) {
10833 // Make sure we're dealing with a copy.
10834 unsigned Begin = I * NumElemsPerConcat;
10835 bool AllUndef = true, NoUndef = true;
10836 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10837 if (SVN->getMaskElt(J) >= 0)
10844 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10847 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10848 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10851 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10852 if (FirstElt < N0.getNumOperands())
10853 Ops.push_back(N0.getOperand(FirstElt));
10855 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10857 } else if (AllUndef) {
10858 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10859 } else { // Mixed with general masks and undefs, can't do optimization.
10864 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10867 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10868 EVT VT = N->getValueType(0);
10869 unsigned NumElts = VT.getVectorNumElements();
10871 SDValue N0 = N->getOperand(0);
10872 SDValue N1 = N->getOperand(1);
10874 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10876 // Canonicalize shuffle undef, undef -> undef
10877 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10878 return DAG.getUNDEF(VT);
10880 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10882 // Canonicalize shuffle v, v -> v, undef
10884 SmallVector<int, 8> NewMask;
10885 for (unsigned i = 0; i != NumElts; ++i) {
10886 int Idx = SVN->getMaskElt(i);
10887 if (Idx >= (int)NumElts) Idx -= NumElts;
10888 NewMask.push_back(Idx);
10890 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10894 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10895 if (N0.getOpcode() == ISD::UNDEF) {
10896 SmallVector<int, 8> NewMask;
10897 for (unsigned i = 0; i != NumElts; ++i) {
10898 int Idx = SVN->getMaskElt(i);
10900 if (Idx >= (int)NumElts)
10903 Idx = -1; // remove reference to lhs
10905 NewMask.push_back(Idx);
10907 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10911 // Remove references to rhs if it is undef
10912 if (N1.getOpcode() == ISD::UNDEF) {
10913 bool Changed = false;
10914 SmallVector<int, 8> NewMask;
10915 for (unsigned i = 0; i != NumElts; ++i) {
10916 int Idx = SVN->getMaskElt(i);
10917 if (Idx >= (int)NumElts) {
10921 NewMask.push_back(Idx);
10924 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10927 // If it is a splat, check if the argument vector is another splat or a
10928 // build_vector with all scalar elements the same.
10929 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10930 SDNode *V = N0.getNode();
10932 // If this is a bit convert that changes the element type of the vector but
10933 // not the number of vector elements, look through it. Be careful not to
10934 // look though conversions that change things like v4f32 to v2f64.
10935 if (V->getOpcode() == ISD::BITCAST) {
10936 SDValue ConvInput = V->getOperand(0);
10937 if (ConvInput.getValueType().isVector() &&
10938 ConvInput.getValueType().getVectorNumElements() == NumElts)
10939 V = ConvInput.getNode();
10942 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10943 assert(V->getNumOperands() == NumElts &&
10944 "BUILD_VECTOR has wrong number of operands");
10946 bool AllSame = true;
10947 for (unsigned i = 0; i != NumElts; ++i) {
10948 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10949 Base = V->getOperand(i);
10953 // Splat of <u, u, u, u>, return <u, u, u, u>
10954 if (!Base.getNode())
10956 for (unsigned i = 0; i != NumElts; ++i) {
10957 if (V->getOperand(i) != Base) {
10962 // Splat of <x, x, x, x>, return <x, x, x, x>
10968 // There are various patterns used to build up a vector from smaller vectors,
10969 // subvectors, or elements. Scan chains of these and replace unused insertions
10970 // or components with undef.
10971 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
10974 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10975 Level < AfterLegalizeVectorOps &&
10976 (N1.getOpcode() == ISD::UNDEF ||
10977 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10978 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10979 SDValue V = partitionShuffleOfConcats(N, DAG);
10985 // If this shuffle node is simply a swizzle of another shuffle node,
10986 // then try to simplify it.
10987 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10988 N1.getOpcode() == ISD::UNDEF) {
10990 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10992 // The incoming shuffle must be of the same type as the result of the
10993 // current shuffle.
10994 assert(OtherSV->getOperand(0).getValueType() == VT &&
10995 "Shuffle types don't match");
10997 SmallVector<int, 4> Mask;
10998 // Compute the combined shuffle mask.
10999 for (unsigned i = 0; i != NumElts; ++i) {
11000 int Idx = SVN->getMaskElt(i);
11001 assert(Idx < (int)NumElts && "Index references undef operand");
11002 // Next, this index comes from the first value, which is the incoming
11003 // shuffle. Adopt the incoming index.
11005 Idx = OtherSV->getMaskElt(Idx);
11006 Mask.push_back(Idx);
11009 // Check if all indices in Mask are Undef. In case, propagate Undef.
11010 bool isUndefMask = true;
11011 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11012 isUndefMask &= Mask[i] < 0;
11015 return DAG.getUNDEF(VT);
11017 bool CommuteOperands = false;
11018 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11019 // To be valid, the combine shuffle mask should only reference elements
11020 // from one of the two vectors in input to the inner shufflevector.
11021 bool IsValidMask = true;
11022 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11023 // See if the combined mask only reference undefs or elements coming
11024 // from the first shufflevector operand.
11025 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11027 if (!IsValidMask) {
11028 IsValidMask = true;
11029 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11030 // Check that all the elements come from the second shuffle operand.
11031 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11032 CommuteOperands = IsValidMask;
11035 // Early exit if the combined shuffle mask is not valid.
11040 // See if this pair of shuffles can be safely folded according to either
11041 // of the following rules:
11042 // shuffle(shuffle(x, y), undef) -> x
11043 // shuffle(shuffle(x, undef), undef) -> x
11044 // shuffle(shuffle(x, y), undef) -> y
11045 bool IsIdentityMask = true;
11046 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11047 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11052 // The combined shuffle must map each index to itself.
11053 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11056 if (IsIdentityMask) {
11057 if (CommuteOperands)
11058 // optimize shuffle(shuffle(x, y), undef) -> y.
11059 return OtherSV->getOperand(1);
11061 // optimize shuffle(shuffle(x, undef), undef) -> x
11062 // optimize shuffle(shuffle(x, y), undef) -> x
11063 return OtherSV->getOperand(0);
11066 // It may still be beneficial to combine the two shuffles if the
11067 // resulting shuffle is legal.
11068 if (TLI.isTypeLegal(VT)) {
11069 if (!CommuteOperands) {
11070 if (TLI.isShuffleMaskLegal(Mask, VT))
11071 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11072 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11073 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11076 // Compute the commuted shuffle mask.
11077 for (unsigned i = 0; i != NumElts; ++i) {
11081 else if (idx < (int)NumElts)
11082 Mask[i] = idx + NumElts;
11084 Mask[i] = idx - NumElts;
11087 if (TLI.isShuffleMaskLegal(Mask, VT))
11088 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11089 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11095 // Canonicalize shuffles according to rules:
11096 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11097 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11098 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11099 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11100 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11101 TLI.isTypeLegal(VT)) {
11102 // The incoming shuffle must be of the same type as the result of the
11103 // current shuffle.
11104 assert(N1->getOperand(0).getValueType() == VT &&
11105 "Shuffle types don't match");
11107 SDValue SV0 = N1->getOperand(0);
11108 SDValue SV1 = N1->getOperand(1);
11109 bool HasSameOp0 = N0 == SV0;
11110 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11111 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11112 // Commute the operands of this shuffle so that next rule
11114 return DAG.getCommutedVectorShuffle(*SVN);
11117 // Try to fold according to rules:
11118 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11119 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11120 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11121 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11122 // Don't try to fold shuffles with illegal type.
11123 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11124 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11125 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11127 // The incoming shuffle must be of the same type as the result of the
11128 // current shuffle.
11129 assert(OtherSV->getOperand(0).getValueType() == VT &&
11130 "Shuffle types don't match");
11132 SDValue SV0 = OtherSV->getOperand(0);
11133 SDValue SV1 = OtherSV->getOperand(1);
11134 bool HasSameOp0 = N1 == SV0;
11135 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11136 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11140 SmallVector<int, 4> Mask;
11141 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11142 // operand, and SV1 as the second operand.
11143 for (unsigned i = 0; i != NumElts; ++i) {
11144 int Idx = SVN->getMaskElt(i);
11146 // Propagate Undef.
11147 Mask.push_back(Idx);
11151 if (Idx < (int)NumElts) {
11152 Idx = OtherSV->getMaskElt(Idx);
11153 if (IsSV1Undef && Idx >= (int) NumElts)
11154 Idx = -1; // Propagate Undef.
11156 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11158 Mask.push_back(Idx);
11161 // Check if all indices in Mask are Undef. In case, propagate Undef.
11162 bool isUndefMask = true;
11163 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11164 isUndefMask &= Mask[i] < 0;
11167 return DAG.getUNDEF(VT);
11169 // Avoid introducing shuffles with illegal mask.
11170 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11172 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11173 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11174 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11175 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11182 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11183 SDValue N0 = N->getOperand(0);
11184 SDValue N2 = N->getOperand(2);
11186 // If the input vector is a concatenation, and the insert replaces
11187 // one of the halves, we can optimize into a single concat_vectors.
11188 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11189 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11190 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11191 EVT VT = N->getValueType(0);
11193 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11194 // (concat_vectors Z, Y)
11196 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11197 N->getOperand(1), N0.getOperand(1));
11199 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11200 // (concat_vectors X, Z)
11201 if (InsIdx == VT.getVectorNumElements()/2)
11202 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11203 N0.getOperand(0), N->getOperand(1));
11209 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11210 /// with the destination vector and a zero vector.
11211 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11212 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11213 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11214 EVT VT = N->getValueType(0);
11216 SDValue LHS = N->getOperand(0);
11217 SDValue RHS = N->getOperand(1);
11218 if (N->getOpcode() == ISD::AND) {
11219 if (RHS.getOpcode() == ISD::BITCAST)
11220 RHS = RHS.getOperand(0);
11221 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11222 SmallVector<int, 8> Indices;
11223 unsigned NumElts = RHS.getNumOperands();
11224 for (unsigned i = 0; i != NumElts; ++i) {
11225 SDValue Elt = RHS.getOperand(i);
11226 if (!isa<ConstantSDNode>(Elt))
11229 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11230 Indices.push_back(i);
11231 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11232 Indices.push_back(NumElts);
11237 // Let's see if the target supports this vector_shuffle.
11238 EVT RVT = RHS.getValueType();
11239 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11242 // Return the new VECTOR_SHUFFLE node.
11243 EVT EltVT = RVT.getVectorElementType();
11244 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11245 DAG.getConstant(0, EltVT));
11246 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11247 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11248 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11249 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11256 /// Visit a binary vector operation, like ADD.
11257 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11258 assert(N->getValueType(0).isVector() &&
11259 "SimplifyVBinOp only works on vectors!");
11261 SDValue LHS = N->getOperand(0);
11262 SDValue RHS = N->getOperand(1);
11263 SDValue Shuffle = XformToShuffleWithZero(N);
11264 if (Shuffle.getNode()) return Shuffle;
11266 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11268 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11269 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11270 // Check if both vectors are constants. If not bail out.
11271 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11272 cast<BuildVectorSDNode>(RHS)->isConstant()))
11275 SmallVector<SDValue, 8> Ops;
11276 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11277 SDValue LHSOp = LHS.getOperand(i);
11278 SDValue RHSOp = RHS.getOperand(i);
11280 // Can't fold divide by zero.
11281 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11282 N->getOpcode() == ISD::FDIV) {
11283 if ((RHSOp.getOpcode() == ISD::Constant &&
11284 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11285 (RHSOp.getOpcode() == ISD::ConstantFP &&
11286 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11290 EVT VT = LHSOp.getValueType();
11291 EVT RVT = RHSOp.getValueType();
11293 // Integer BUILD_VECTOR operands may have types larger than the element
11294 // size (e.g., when the element type is not legal). Prior to type
11295 // legalization, the types may not match between the two BUILD_VECTORS.
11296 // Truncate one of the operands to make them match.
11297 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11298 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11300 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11304 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11306 if (FoldOp.getOpcode() != ISD::UNDEF &&
11307 FoldOp.getOpcode() != ISD::Constant &&
11308 FoldOp.getOpcode() != ISD::ConstantFP)
11310 Ops.push_back(FoldOp);
11311 AddToWorklist(FoldOp.getNode());
11314 if (Ops.size() == LHS.getNumOperands())
11315 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11318 // Type legalization might introduce new shuffles in the DAG.
11319 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11320 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11321 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11322 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11323 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11324 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11325 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11326 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11328 if (SVN0->getMask().equals(SVN1->getMask())) {
11329 EVT VT = N->getValueType(0);
11330 SDValue UndefVector = LHS.getOperand(1);
11331 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11332 LHS.getOperand(0), RHS.getOperand(0));
11333 AddUsersToWorklist(N);
11334 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11335 &SVN0->getMask()[0]);
11342 /// Visit a binary vector operation, like FABS/FNEG.
11343 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11344 assert(N->getValueType(0).isVector() &&
11345 "SimplifyVUnaryOp only works on vectors!");
11347 SDValue N0 = N->getOperand(0);
11349 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11352 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11353 SmallVector<SDValue, 8> Ops;
11354 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11355 SDValue Op = N0.getOperand(i);
11356 if (Op.getOpcode() != ISD::UNDEF &&
11357 Op.getOpcode() != ISD::ConstantFP)
11359 EVT EltVT = Op.getValueType();
11360 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11361 if (FoldOp.getOpcode() != ISD::UNDEF &&
11362 FoldOp.getOpcode() != ISD::ConstantFP)
11364 Ops.push_back(FoldOp);
11365 AddToWorklist(FoldOp.getNode());
11368 if (Ops.size() != N0.getNumOperands())
11371 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11374 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11375 SDValue N1, SDValue N2){
11376 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11378 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11379 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11381 // If we got a simplified select_cc node back from SimplifySelectCC, then
11382 // break it down into a new SETCC node, and a new SELECT node, and then return
11383 // the SELECT node, since we were called with a SELECT node.
11384 if (SCC.getNode()) {
11385 // Check to see if we got a select_cc back (to turn into setcc/select).
11386 // Otherwise, just return whatever node we got back, like fabs.
11387 if (SCC.getOpcode() == ISD::SELECT_CC) {
11388 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11390 SCC.getOperand(0), SCC.getOperand(1),
11391 SCC.getOperand(4));
11392 AddToWorklist(SETCC.getNode());
11393 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11394 SCC.getOperand(2), SCC.getOperand(3));
11402 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11403 /// being selected between, see if we can simplify the select. Callers of this
11404 /// should assume that TheSelect is deleted if this returns true. As such, they
11405 /// should return the appropriate thing (e.g. the node) back to the top-level of
11406 /// the DAG combiner loop to avoid it being looked at.
11407 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11410 // Cannot simplify select with vector condition
11411 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11413 // If this is a select from two identical things, try to pull the operation
11414 // through the select.
11415 if (LHS.getOpcode() != RHS.getOpcode() ||
11416 !LHS.hasOneUse() || !RHS.hasOneUse())
11419 // If this is a load and the token chain is identical, replace the select
11420 // of two loads with a load through a select of the address to load from.
11421 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11422 // constants have been dropped into the constant pool.
11423 if (LHS.getOpcode() == ISD::LOAD) {
11424 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11425 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11427 // Token chains must be identical.
11428 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11429 // Do not let this transformation reduce the number of volatile loads.
11430 LLD->isVolatile() || RLD->isVolatile() ||
11431 // If this is an EXTLOAD, the VT's must match.
11432 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11433 // If this is an EXTLOAD, the kind of extension must match.
11434 (LLD->getExtensionType() != RLD->getExtensionType() &&
11435 // The only exception is if one of the extensions is anyext.
11436 LLD->getExtensionType() != ISD::EXTLOAD &&
11437 RLD->getExtensionType() != ISD::EXTLOAD) ||
11438 // FIXME: this discards src value information. This is
11439 // over-conservative. It would be beneficial to be able to remember
11440 // both potential memory locations. Since we are discarding
11441 // src value info, don't do the transformation if the memory
11442 // locations are not in the default address space.
11443 LLD->getPointerInfo().getAddrSpace() != 0 ||
11444 RLD->getPointerInfo().getAddrSpace() != 0 ||
11445 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11446 LLD->getBasePtr().getValueType()))
11449 // Check that the select condition doesn't reach either load. If so,
11450 // folding this will induce a cycle into the DAG. If not, this is safe to
11451 // xform, so create a select of the addresses.
11453 if (TheSelect->getOpcode() == ISD::SELECT) {
11454 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11455 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11456 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11458 // The loads must not depend on one another.
11459 if (LLD->isPredecessorOf(RLD) ||
11460 RLD->isPredecessorOf(LLD))
11462 Addr = DAG.getSelect(SDLoc(TheSelect),
11463 LLD->getBasePtr().getValueType(),
11464 TheSelect->getOperand(0), LLD->getBasePtr(),
11465 RLD->getBasePtr());
11466 } else { // Otherwise SELECT_CC
11467 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11468 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11470 if ((LLD->hasAnyUseOfValue(1) &&
11471 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11472 (RLD->hasAnyUseOfValue(1) &&
11473 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11476 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11477 LLD->getBasePtr().getValueType(),
11478 TheSelect->getOperand(0),
11479 TheSelect->getOperand(1),
11480 LLD->getBasePtr(), RLD->getBasePtr(),
11481 TheSelect->getOperand(4));
11485 // It is safe to replace the two loads if they have different alignments,
11486 // but the new load must be the minimum (most restrictive) alignment of the
11488 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11489 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11490 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11491 Load = DAG.getLoad(TheSelect->getValueType(0),
11493 // FIXME: Discards pointer and AA info.
11494 LLD->getChain(), Addr, MachinePointerInfo(),
11495 LLD->isVolatile(), LLD->isNonTemporal(),
11496 isInvariant, Alignment);
11498 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11499 RLD->getExtensionType() : LLD->getExtensionType(),
11501 TheSelect->getValueType(0),
11502 // FIXME: Discards pointer and AA info.
11503 LLD->getChain(), Addr, MachinePointerInfo(),
11504 LLD->getMemoryVT(), LLD->isVolatile(),
11505 LLD->isNonTemporal(), isInvariant, Alignment);
11508 // Users of the select now use the result of the load.
11509 CombineTo(TheSelect, Load);
11511 // Users of the old loads now use the new load's chain. We know the
11512 // old-load value is dead now.
11513 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11514 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11521 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11522 /// where 'cond' is the comparison specified by CC.
11523 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11524 SDValue N2, SDValue N3,
11525 ISD::CondCode CC, bool NotExtCompare) {
11526 // (x ? y : y) -> y.
11527 if (N2 == N3) return N2;
11529 EVT VT = N2.getValueType();
11530 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11531 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11532 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11534 // Determine if the condition we're dealing with is constant
11535 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11536 N0, N1, CC, DL, false);
11537 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11538 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11540 // fold select_cc true, x, y -> x
11541 if (SCCC && !SCCC->isNullValue())
11543 // fold select_cc false, x, y -> y
11544 if (SCCC && SCCC->isNullValue())
11547 // Check to see if we can simplify the select into an fabs node
11548 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11549 // Allow either -0.0 or 0.0
11550 if (CFP->getValueAPF().isZero()) {
11551 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11552 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11553 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11554 N2 == N3.getOperand(0))
11555 return DAG.getNode(ISD::FABS, DL, VT, N0);
11557 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11558 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11559 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11560 N2.getOperand(0) == N3)
11561 return DAG.getNode(ISD::FABS, DL, VT, N3);
11565 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11566 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11567 // in it. This is a win when the constant is not otherwise available because
11568 // it replaces two constant pool loads with one. We only do this if the FP
11569 // type is known to be legal, because if it isn't, then we are before legalize
11570 // types an we want the other legalization to happen first (e.g. to avoid
11571 // messing with soft float) and if the ConstantFP is not legal, because if
11572 // it is legal, we may not need to store the FP constant in a constant pool.
11573 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11574 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11575 if (TLI.isTypeLegal(N2.getValueType()) &&
11576 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11577 TargetLowering::Legal &&
11578 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11579 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11580 // If both constants have multiple uses, then we won't need to do an
11581 // extra load, they are likely around in registers for other users.
11582 (TV->hasOneUse() || FV->hasOneUse())) {
11583 Constant *Elts[] = {
11584 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11585 const_cast<ConstantFP*>(TV->getConstantFPValue())
11587 Type *FPTy = Elts[0]->getType();
11588 const DataLayout &TD = *TLI.getDataLayout();
11590 // Create a ConstantArray of the two constants.
11591 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11592 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11593 TD.getPrefTypeAlignment(FPTy));
11594 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11596 // Get the offsets to the 0 and 1 element of the array so that we can
11597 // select between them.
11598 SDValue Zero = DAG.getIntPtrConstant(0);
11599 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11600 SDValue One = DAG.getIntPtrConstant(EltSize);
11602 SDValue Cond = DAG.getSetCC(DL,
11603 getSetCCResultType(N0.getValueType()),
11605 AddToWorklist(Cond.getNode());
11606 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11608 AddToWorklist(CstOffset.getNode());
11609 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11611 AddToWorklist(CPIdx.getNode());
11612 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11613 MachinePointerInfo::getConstantPool(), false,
11614 false, false, Alignment);
11619 // Check to see if we can perform the "gzip trick", transforming
11620 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11621 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11622 (N1C->isNullValue() || // (a < 0) ? b : 0
11623 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11624 EVT XType = N0.getValueType();
11625 EVT AType = N2.getValueType();
11626 if (XType.bitsGE(AType)) {
11627 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11628 // single-bit constant.
11629 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11630 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11631 ShCtV = XType.getSizeInBits()-ShCtV-1;
11632 SDValue ShCt = DAG.getConstant(ShCtV,
11633 getShiftAmountTy(N0.getValueType()));
11634 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11636 AddToWorklist(Shift.getNode());
11638 if (XType.bitsGT(AType)) {
11639 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11640 AddToWorklist(Shift.getNode());
11643 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11646 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11648 DAG.getConstant(XType.getSizeInBits()-1,
11649 getShiftAmountTy(N0.getValueType())));
11650 AddToWorklist(Shift.getNode());
11652 if (XType.bitsGT(AType)) {
11653 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11654 AddToWorklist(Shift.getNode());
11657 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11661 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11662 // where y is has a single bit set.
11663 // A plaintext description would be, we can turn the SELECT_CC into an AND
11664 // when the condition can be materialized as an all-ones register. Any
11665 // single bit-test can be materialized as an all-ones register with
11666 // shift-left and shift-right-arith.
11667 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11668 N0->getValueType(0) == VT &&
11669 N1C && N1C->isNullValue() &&
11670 N2C && N2C->isNullValue()) {
11671 SDValue AndLHS = N0->getOperand(0);
11672 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11673 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11674 // Shift the tested bit over the sign bit.
11675 APInt AndMask = ConstAndRHS->getAPIntValue();
11677 DAG.getConstant(AndMask.countLeadingZeros(),
11678 getShiftAmountTy(AndLHS.getValueType()));
11679 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11681 // Now arithmetic right shift it all the way over, so the result is either
11682 // all-ones, or zero.
11684 DAG.getConstant(AndMask.getBitWidth()-1,
11685 getShiftAmountTy(Shl.getValueType()));
11686 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11688 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11692 // fold select C, 16, 0 -> shl C, 4
11693 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11694 TLI.getBooleanContents(N0.getValueType()) ==
11695 TargetLowering::ZeroOrOneBooleanContent) {
11697 // If the caller doesn't want us to simplify this into a zext of a compare,
11699 if (NotExtCompare && N2C->getAPIntValue() == 1)
11702 // Get a SetCC of the condition
11703 // NOTE: Don't create a SETCC if it's not legal on this target.
11704 if (!LegalOperations ||
11705 TLI.isOperationLegal(ISD::SETCC,
11706 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11708 // cast from setcc result type to select result type
11710 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11712 if (N2.getValueType().bitsLT(SCC.getValueType()))
11713 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11714 N2.getValueType());
11716 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11717 N2.getValueType(), SCC);
11719 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11720 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11721 N2.getValueType(), SCC);
11724 AddToWorklist(SCC.getNode());
11725 AddToWorklist(Temp.getNode());
11727 if (N2C->getAPIntValue() == 1)
11730 // shl setcc result by log2 n2c
11731 return DAG.getNode(
11732 ISD::SHL, DL, N2.getValueType(), Temp,
11733 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11734 getShiftAmountTy(Temp.getValueType())));
11738 // Check to see if this is the equivalent of setcc
11739 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11740 // otherwise, go ahead with the folds.
11741 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11742 EVT XType = N0.getValueType();
11743 if (!LegalOperations ||
11744 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11745 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11746 if (Res.getValueType() != VT)
11747 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11751 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11752 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11753 (!LegalOperations ||
11754 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11755 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11756 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11757 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11758 getShiftAmountTy(Ctlz.getValueType())));
11760 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11761 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11762 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11763 XType, DAG.getConstant(0, XType), N0);
11764 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11765 return DAG.getNode(ISD::SRL, DL, XType,
11766 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11767 DAG.getConstant(XType.getSizeInBits()-1,
11768 getShiftAmountTy(XType)));
11770 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11771 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11772 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11773 DAG.getConstant(XType.getSizeInBits()-1,
11774 getShiftAmountTy(N0.getValueType())));
11775 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11779 // Check to see if this is an integer abs.
11780 // select_cc setg[te] X, 0, X, -X ->
11781 // select_cc setgt X, -1, X, -X ->
11782 // select_cc setl[te] X, 0, -X, X ->
11783 // select_cc setlt X, 1, -X, X ->
11784 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11786 ConstantSDNode *SubC = nullptr;
11787 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11788 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11789 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11790 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11791 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11792 (N1C->isOne() && CC == ISD::SETLT)) &&
11793 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11794 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11796 EVT XType = N0.getValueType();
11797 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11798 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11800 DAG.getConstant(XType.getSizeInBits()-1,
11801 getShiftAmountTy(N0.getValueType())));
11802 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11804 AddToWorklist(Shift.getNode());
11805 AddToWorklist(Add.getNode());
11806 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11813 /// This is a stub for TargetLowering::SimplifySetCC.
11814 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11815 SDValue N1, ISD::CondCode Cond,
11816 SDLoc DL, bool foldBooleans) {
11817 TargetLowering::DAGCombinerInfo
11818 DagCombineInfo(DAG, Level, false, this);
11819 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11822 /// Given an ISD::SDIV node expressing a divide by constant, return
11823 /// a DAG expression to select that will generate the same value by multiplying
11824 /// by a magic number.
11825 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11826 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11827 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11831 // Avoid division by zero.
11832 if (!C->getAPIntValue())
11835 std::vector<SDNode*> Built;
11837 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11839 for (SDNode *N : Built)
11844 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11845 /// DAG expression that will generate the same value by right shifting.
11846 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11847 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11851 // Avoid division by zero.
11852 if (!C->getAPIntValue())
11855 std::vector<SDNode *> Built;
11856 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11858 for (SDNode *N : Built)
11863 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11864 /// expression that will generate the same value by multiplying by a magic
11866 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11867 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11868 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11872 // Avoid division by zero.
11873 if (!C->getAPIntValue())
11876 std::vector<SDNode*> Built;
11878 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11880 for (SDNode *N : Built)
11885 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11886 if (Level >= AfterLegalizeDAG)
11889 // Expose the DAG combiner to the target combiner implementations.
11890 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11892 unsigned Iterations = 0;
11893 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11895 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11896 // For the reciprocal, we need to find the zero of the function:
11897 // F(X) = A X - 1 [which has a zero at X = 1/A]
11899 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11900 // does not require additional intermediate precision]
11901 EVT VT = Op.getValueType();
11903 SDValue FPOne = DAG.getConstantFP(1.0, VT);
11905 AddToWorklist(Est.getNode());
11907 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11908 for (unsigned i = 0; i < Iterations; ++i) {
11909 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11910 AddToWorklist(NewEst.getNode());
11912 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11913 AddToWorklist(NewEst.getNode());
11915 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11916 AddToWorklist(NewEst.getNode());
11918 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11919 AddToWorklist(Est.getNode());
11928 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11929 if (Level >= AfterLegalizeDAG)
11932 // Expose the DAG combiner to the target combiner implementations.
11933 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11934 unsigned Iterations = 0;
11935 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations)) {
11937 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11938 // For the reciprocal sqrt, we need to find the zero of the function:
11939 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11941 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11942 // As a result, we precompute A/2 prior to the iteration loop.
11943 EVT VT = Op.getValueType();
11945 SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
11947 AddToWorklist(Est.getNode());
11949 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11950 // this entire sequence requires only one FP constant.
11951 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
11952 AddToWorklist(HalfArg.getNode());
11954 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
11955 AddToWorklist(HalfArg.getNode());
11957 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
11958 for (unsigned i = 0; i < Iterations; ++i) {
11959 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
11960 AddToWorklist(NewEst.getNode());
11962 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
11963 AddToWorklist(NewEst.getNode());
11965 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
11966 AddToWorklist(NewEst.getNode());
11968 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11969 AddToWorklist(Est.getNode());
11978 /// Return true if base is a frame index, which is known not to alias with
11979 /// anything but itself. Provides base object and offset as results.
11980 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11981 const GlobalValue *&GV, const void *&CV) {
11982 // Assume it is a primitive operation.
11983 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11985 // If it's an adding a simple constant then integrate the offset.
11986 if (Base.getOpcode() == ISD::ADD) {
11987 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11988 Base = Base.getOperand(0);
11989 Offset += C->getZExtValue();
11993 // Return the underlying GlobalValue, and update the Offset. Return false
11994 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11995 // by multiple nodes with different offsets.
11996 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11997 GV = G->getGlobal();
11998 Offset += G->getOffset();
12002 // Return the underlying Constant value, and update the Offset. Return false
12003 // for ConstantSDNodes since the same constant pool entry may be represented
12004 // by multiple nodes with different offsets.
12005 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12006 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12007 : (const void *)C->getConstVal();
12008 Offset += C->getOffset();
12011 // If it's any of the following then it can't alias with anything but itself.
12012 return isa<FrameIndexSDNode>(Base);
12015 /// Return true if there is any possibility that the two addresses overlap.
12016 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12017 // If they are the same then they must be aliases.
12018 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12020 // If they are both volatile then they cannot be reordered.
12021 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12023 // Gather base node and offset information.
12024 SDValue Base1, Base2;
12025 int64_t Offset1, Offset2;
12026 const GlobalValue *GV1, *GV2;
12027 const void *CV1, *CV2;
12028 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12029 Base1, Offset1, GV1, CV1);
12030 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12031 Base2, Offset2, GV2, CV2);
12033 // If they have a same base address then check to see if they overlap.
12034 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12035 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12036 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12038 // It is possible for different frame indices to alias each other, mostly
12039 // when tail call optimization reuses return address slots for arguments.
12040 // To catch this case, look up the actual index of frame indices to compute
12041 // the real alias relationship.
12042 if (isFrameIndex1 && isFrameIndex2) {
12043 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12044 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12045 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12046 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12047 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12050 // Otherwise, if we know what the bases are, and they aren't identical, then
12051 // we know they cannot alias.
12052 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12055 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12056 // compared to the size and offset of the access, we may be able to prove they
12057 // do not alias. This check is conservative for now to catch cases created by
12058 // splitting vector types.
12059 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12060 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12061 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12062 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12063 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12064 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12065 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12067 // There is no overlap between these relatively aligned accesses of similar
12068 // size, return no alias.
12069 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12070 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12074 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
12075 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
12077 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12078 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12082 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12083 // Use alias analysis information.
12084 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12085 Op1->getSrcValueOffset());
12086 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12087 Op0->getSrcValueOffset() - MinOffset;
12088 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12089 Op1->getSrcValueOffset() - MinOffset;
12090 AliasAnalysis::AliasResult AAResult =
12091 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12093 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12094 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12096 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12097 if (AAResult == AliasAnalysis::NoAlias)
12101 // Otherwise we have to assume they alias.
12105 /// Walk up chain skipping non-aliasing memory nodes,
12106 /// looking for aliasing nodes and adding them to the Aliases vector.
12107 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12108 SmallVectorImpl<SDValue> &Aliases) {
12109 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12110 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12112 // Get alias information for node.
12113 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12116 Chains.push_back(OriginalChain);
12117 unsigned Depth = 0;
12119 // Look at each chain and determine if it is an alias. If so, add it to the
12120 // aliases list. If not, then continue up the chain looking for the next
12122 while (!Chains.empty()) {
12123 SDValue Chain = Chains.back();
12126 // For TokenFactor nodes, look at each operand and only continue up the
12127 // chain until we find two aliases. If we've seen two aliases, assume we'll
12128 // find more and revert to original chain since the xform is unlikely to be
12131 // FIXME: The depth check could be made to return the last non-aliasing
12132 // chain we found before we hit a tokenfactor rather than the original
12134 if (Depth > 6 || Aliases.size() == 2) {
12136 Aliases.push_back(OriginalChain);
12140 // Don't bother if we've been before.
12141 if (!Visited.insert(Chain.getNode()))
12144 switch (Chain.getOpcode()) {
12145 case ISD::EntryToken:
12146 // Entry token is ideal chain operand, but handled in FindBetterChain.
12151 // Get alias information for Chain.
12152 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12153 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12155 // If chain is alias then stop here.
12156 if (!(IsLoad && IsOpLoad) &&
12157 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12158 Aliases.push_back(Chain);
12160 // Look further up the chain.
12161 Chains.push_back(Chain.getOperand(0));
12167 case ISD::TokenFactor:
12168 // We have to check each of the operands of the token factor for "small"
12169 // token factors, so we queue them up. Adding the operands to the queue
12170 // (stack) in reverse order maintains the original order and increases the
12171 // likelihood that getNode will find a matching token factor (CSE.)
12172 if (Chain.getNumOperands() > 16) {
12173 Aliases.push_back(Chain);
12176 for (unsigned n = Chain.getNumOperands(); n;)
12177 Chains.push_back(Chain.getOperand(--n));
12182 // For all other instructions we will just have to take what we can get.
12183 Aliases.push_back(Chain);
12188 // We need to be careful here to also search for aliases through the
12189 // value operand of a store, etc. Consider the following situation:
12191 // L1 = load Token1, %52
12192 // S1 = store Token1, L1, %51
12193 // L2 = load Token1, %52+8
12194 // S2 = store Token1, L2, %51+8
12195 // Token2 = Token(S1, S2)
12196 // L3 = load Token2, %53
12197 // S3 = store Token2, L3, %52
12198 // L4 = load Token2, %53+8
12199 // S4 = store Token2, L4, %52+8
12200 // If we search for aliases of S3 (which loads address %52), and we look
12201 // only through the chain, then we'll miss the trivial dependence on L1
12202 // (which also loads from %52). We then might change all loads and
12203 // stores to use Token1 as their chain operand, which could result in
12204 // copying %53 into %52 before copying %52 into %51 (which should
12207 // The problem is, however, that searching for such data dependencies
12208 // can become expensive, and the cost is not directly related to the
12209 // chain depth. Instead, we'll rule out such configurations here by
12210 // insisting that we've visited all chain users (except for users
12211 // of the original chain, which is not necessary). When doing this,
12212 // we need to look through nodes we don't care about (otherwise, things
12213 // like register copies will interfere with trivial cases).
12215 SmallVector<const SDNode *, 16> Worklist;
12216 for (const SDNode *N : Visited)
12217 if (N != OriginalChain.getNode())
12218 Worklist.push_back(N);
12220 while (!Worklist.empty()) {
12221 const SDNode *M = Worklist.pop_back_val();
12223 // We have already visited M, and want to make sure we've visited any uses
12224 // of M that we care about. For uses that we've not visisted, and don't
12225 // care about, queue them to the worklist.
12227 for (SDNode::use_iterator UI = M->use_begin(),
12228 UIE = M->use_end(); UI != UIE; ++UI)
12229 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12230 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12231 // We've not visited this use, and we care about it (it could have an
12232 // ordering dependency with the original node).
12234 Aliases.push_back(OriginalChain);
12238 // We've not visited this use, but we don't care about it. Mark it as
12239 // visited and enqueue it to the worklist.
12240 Worklist.push_back(*UI);
12245 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12246 /// (aliasing node.)
12247 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12248 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12250 // Accumulate all the aliases to this node.
12251 GatherAllAliases(N, OldChain, Aliases);
12253 // If no operands then chain to entry token.
12254 if (Aliases.size() == 0)
12255 return DAG.getEntryNode();
12257 // If a single operand then chain to it. We don't need to revisit it.
12258 if (Aliases.size() == 1)
12261 // Construct a custom tailored token factor.
12262 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12265 /// This is the entry point for the file.
12266 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12267 CodeGenOpt::Level OptLevel) {
12268 /// This is the main entry point to this class.
12269 DAGCombiner(*this, AA, OptLevel).Run(Level);