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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue SimplifyVUnaryOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitTRUNCATE(SDNode *N);
273 SDValue visitBITCAST(SDNode *N);
274 SDValue visitBUILD_PAIR(SDNode *N);
275 SDValue visitFADD(SDNode *N);
276 SDValue visitFSUB(SDNode *N);
277 SDValue visitFMUL(SDNode *N);
278 SDValue visitFMA(SDNode *N);
279 SDValue visitFDIV(SDNode *N);
280 SDValue visitFREM(SDNode *N);
281 SDValue visitFSQRT(SDNode *N);
282 SDValue visitFCOPYSIGN(SDNode *N);
283 SDValue visitSINT_TO_FP(SDNode *N);
284 SDValue visitUINT_TO_FP(SDNode *N);
285 SDValue visitFP_TO_SINT(SDNode *N);
286 SDValue visitFP_TO_UINT(SDNode *N);
287 SDValue visitFP_ROUND(SDNode *N);
288 SDValue visitFP_ROUND_INREG(SDNode *N);
289 SDValue visitFP_EXTEND(SDNode *N);
290 SDValue visitFNEG(SDNode *N);
291 SDValue visitFABS(SDNode *N);
292 SDValue visitFCEIL(SDNode *N);
293 SDValue visitFTRUNC(SDNode *N);
294 SDValue visitFFLOOR(SDNode *N);
295 SDValue visitFMINNUM(SDNode *N);
296 SDValue visitFMAXNUM(SDNode *N);
297 SDValue visitBRCOND(SDNode *N);
298 SDValue visitBR_CC(SDNode *N);
299 SDValue visitLOAD(SDNode *N);
300 SDValue visitSTORE(SDNode *N);
301 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303 SDValue visitBUILD_VECTOR(SDNode *N);
304 SDValue visitCONCAT_VECTORS(SDNode *N);
305 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306 SDValue visitVECTOR_SHUFFLE(SDNode *N);
307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
311 SDValue XformToShuffleWithZero(SDNode *N);
312 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
314 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
316 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
318 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
320 SDValue N3, ISD::CondCode CC,
321 bool NotExtCompare = false);
322 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
323 SDLoc DL, bool foldBooleans = true);
325 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327 bool isOneUseSetCC(SDValue N) const;
329 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
331 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
332 SDValue CombineExtLoad(SDNode *N);
333 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
334 SDValue BuildSDIV(SDNode *N);
335 SDValue BuildSDIVPow2(SDNode *N);
336 SDValue BuildUDIV(SDNode *N);
337 SDValue BuildReciprocalEstimate(SDValue Op);
338 SDValue BuildRsqrtEstimate(SDValue Op);
339 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
341 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342 bool DemandHighBits = true);
343 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
344 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345 SDValue InnerPos, SDValue InnerNeg,
346 unsigned PosOpcode, unsigned NegOpcode,
348 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
349 SDValue ReduceLoadWidth(SDNode *N);
350 SDValue ReduceLoadOpStoreWidth(SDNode *N);
351 SDValue TransformFPLoadStorePair(SDNode *N);
352 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
353 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
355 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
357 /// Walk up chain skipping non-aliasing memory nodes,
358 /// looking for aliasing nodes and adding them to the Aliases vector.
359 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
360 SmallVectorImpl<SDValue> &Aliases);
362 /// Return true if there is any possibility that the two addresses overlap.
363 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
365 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366 /// chain (aliasing node.)
367 SDValue FindBetterChain(SDNode *N, SDValue Chain);
369 /// Holds a pointer to an LSBaseSDNode as well as information on where it
370 /// is located in a sequence of memory operations connected by a chain.
372 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374 // Ptr to the mem node.
375 LSBaseSDNode *MemNode;
376 // Offset from the base ptr.
377 int64_t OffsetFromBase;
378 // What is the sequence number of this mem node.
379 // Lowest mem operand in the DAG starts at zero.
380 unsigned SequenceNum;
383 /// This is a helper function for MergeConsecutiveStores. When the source
384 /// elements of the consecutive stores are all constants or all extracted
385 /// vector elements, try to merge them into one larger store.
386 /// \return True if a merged store was created.
387 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
388 EVT MemVT, unsigned NumElem,
389 bool IsConstantSrc, bool UseVector);
391 /// Merge consecutive store operations into a wide store.
392 /// This optimization uses wide integers or vectors when possible.
393 /// \return True if some memory operations were changed.
394 bool MergeConsecutiveStores(StoreSDNode *N);
396 /// \brief Try to transform a truncation where C is a constant:
397 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
399 /// \p N needs to be a truncation and its first operand an AND. Other
400 /// requirements are checked by the function (e.g. that trunc is
401 /// single-use) and if missed an empty SDValue is returned.
402 SDValue distributeTruncateThroughAnd(SDNode *N);
405 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
406 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
408 auto *F = DAG.getMachineFunction().getFunction();
409 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410 F->hasFnAttribute(Attribute::MinSize);
413 /// Runs the dag combiner on all nodes in the work list
414 void Run(CombineLevel AtLevel);
416 SelectionDAG &getDAG() const { return DAG; }
418 /// Returns a type large enough to hold any valid shift amount - before type
419 /// legalization these can be huge.
420 EVT getShiftAmountTy(EVT LHSTy) {
421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422 if (LHSTy.isVector())
424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425 : TLI.getPointerTy();
428 /// This method returns true if we are running before type legalization or
429 /// if the specified VT is legal.
430 bool isTypeLegal(const EVT &VT) {
431 if (!LegalTypes) return true;
432 return TLI.isTypeLegal(VT);
435 /// Convenience wrapper around TargetLowering::getSetCCResultType
436 EVT getSetCCResultType(EVT VT) const {
437 return TLI.getSetCCResultType(*DAG.getContext(), VT);
444 /// This class is a DAGUpdateListener that removes any deleted
445 /// nodes from the worklist.
446 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
449 explicit WorklistRemover(DAGCombiner &dc)
450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452 void NodeDeleted(SDNode *N, SDNode *E) override {
453 DC.removeFromWorklist(N);
458 //===----------------------------------------------------------------------===//
459 // TargetLowering::DAGCombinerInfo implementation
460 //===----------------------------------------------------------------------===//
462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
463 ((DAGCombiner*)DC)->AddToWorklist(N);
466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
467 ((DAGCombiner*)DC)->removeFromWorklist(N);
470 SDValue TargetLowering::DAGCombinerInfo::
471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
475 SDValue TargetLowering::DAGCombinerInfo::
476 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
486 void TargetLowering::DAGCombinerInfo::
487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 void DAGCombiner::deleteAndRecombine(SDNode *N) {
496 removeFromWorklist(N);
498 // If the operands of this node are only used by the node, they will now be
499 // dead. Make sure to re-visit them and recursively delete dead nodes.
500 for (const SDValue &Op : N->ops())
501 // For an operand generating multiple values, one of the values may
502 // become dead allowing further simplification (e.g. split index
503 // arithmetic from an indexed load).
504 if (Op->hasOneUse() || Op->getNumValues() > 1)
505 AddToWorklist(Op.getNode());
510 /// Return 1 if we can compute the negated form of the specified expression for
511 /// the same cost as the expression itself, or 2 if we can compute the negated
512 /// form more cheaply than the expression itself.
513 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
514 const TargetLowering &TLI,
515 const TargetOptions *Options,
516 unsigned Depth = 0) {
517 // fneg is removable even if it has multiple uses.
518 if (Op.getOpcode() == ISD::FNEG) return 2;
520 // Don't allow anything with multiple uses.
521 if (!Op.hasOneUse()) return 0;
523 // Don't recurse exponentially.
524 if (Depth > 6) return 0;
526 switch (Op.getOpcode()) {
527 default: return false;
528 case ISD::ConstantFP:
529 // Don't invert constant FP values after legalize. The negated constant
530 // isn't necessarily legal.
531 return LegalOperations ? 0 : 1;
533 // FIXME: determine better conditions for this xform.
534 if (!Options->UnsafeFPMath) return 0;
536 // After operation legalization, it might not be legal to create new FSUBs.
537 if (LegalOperations &&
538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
549 // We can't turn -(A-B) into B-A when we honor signed zeros.
550 if (!Options->UnsafeFPMath) return 0;
552 // fold (fneg (fsub A, B)) -> (fsub B, A)
557 if (Options->HonorSignDependentRoundingFPMath()) return 0;
559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575 /// If isNegatibleForFree returns true, return the newly negated expression.
576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
577 bool LegalOperations, unsigned Depth = 0) {
578 const TargetOptions &Options = DAG.getTarget().Options;
579 // fneg is removable even if it has multiple uses.
580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582 // Don't allow anything with multiple uses.
583 assert(Op.hasOneUse() && "Unknown reuse!");
585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
586 switch (Op.getOpcode()) {
587 default: llvm_unreachable("Unknown code");
588 case ISD::ConstantFP: {
589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591 return DAG.getConstantFP(V, Op.getValueType());
594 // FIXME: determine better conditions for this xform.
595 assert(Options.UnsafeFPMath);
597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
599 DAG.getTargetLoweringInfo(), &Options, Depth+1))
600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
601 GetNegatedExpression(Op.getOperand(0), DAG,
602 LegalOperations, Depth+1),
604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1),
610 // We can't turn -(A-B) into B-A when we honor signed zeros.
611 assert(Options.UnsafeFPMath);
613 // fold (fneg (fsub 0, B)) -> B
614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
615 if (N0CFP->getValueAPF().isZero())
616 return Op.getOperand(1);
618 // fold (fneg (fsub A, B)) -> (fsub B, A)
619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620 Op.getOperand(1), Op.getOperand(0));
624 assert(!Options.HonorSignDependentRoundingFPMath());
626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
628 DAG.getTargetLoweringInfo(), &Options, Depth+1))
629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
630 GetNegatedExpression(Op.getOperand(0), DAG,
631 LegalOperations, Depth+1),
634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637 GetNegatedExpression(Op.getOperand(1), DAG,
638 LegalOperations, Depth+1));
642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(0), DAG,
644 LegalOperations, Depth+1));
646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(0), DAG,
648 LegalOperations, Depth+1),
653 // Return true if this node is a setcc, or is a select_cc
654 // that selects between the target values used for true and false, making it
655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656 // the appropriate nodes based on the type of node we are checking. This
657 // simplifies life a bit for the callers.
658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660 if (N.getOpcode() == ISD::SETCC) {
661 LHS = N.getOperand(0);
662 RHS = N.getOperand(1);
663 CC = N.getOperand(2);
667 if (N.getOpcode() != ISD::SELECT_CC ||
668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
672 if (TLI.getBooleanContents(N.getValueType()) ==
673 TargetLowering::UndefinedBooleanContent)
676 LHS = N.getOperand(0);
677 RHS = N.getOperand(1);
678 CC = N.getOperand(4);
682 /// Return true if this is a SetCC-equivalent operation with only one use.
683 /// If this is true, it allows the users to invert the operation for free when
684 /// it is profitable to do so.
685 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692 /// Returns true if N is a BUILD_VECTOR node whose
693 /// elements are all the same constant or undefined.
694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700 unsigned SplatBitSize;
702 EVT EltVT = N->getValueType(0).getVectorElementType();
703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705 EltVT.getSizeInBits() >= SplatBitSize);
708 // \brief Returns the SDNode if it is a constant BuildVector or constant.
709 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
710 if (isa<ConstantSDNode>(N))
712 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
713 if (BV && BV->isConstant())
718 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
720 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
721 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
724 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
725 BitVector UndefElements;
726 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
728 // BuildVectors can truncate their operands. Ignore that case here.
729 // FIXME: We blindly ignore splats which include undef which is overly
731 if (CN && UndefElements.none() &&
732 CN->getValueType(0) == N.getValueType().getScalarType())
739 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
741 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
742 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
745 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
746 BitVector UndefElements;
747 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
749 if (CN && UndefElements.none())
756 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
757 SDValue N0, SDValue N1) {
758 EVT VT = N0.getValueType();
759 if (N0.getOpcode() == Opc) {
760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
761 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
762 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
763 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
764 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
767 if (N0.hasOneUse()) {
768 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
771 if (!OpNode.getNode())
773 AddToWorklist(OpNode.getNode());
774 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
779 if (N1.getOpcode() == Opc) {
780 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
781 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
782 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
783 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
784 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
787 if (N1.hasOneUse()) {
788 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
790 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
791 if (!OpNode.getNode())
793 AddToWorklist(OpNode.getNode());
794 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
802 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
804 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
806 DEBUG(dbgs() << "\nReplacing.1 ";
808 dbgs() << "\nWith: ";
809 To[0].getNode()->dump(&DAG);
810 dbgs() << " and " << NumTo-1 << " other values\n");
811 for (unsigned i = 0, e = NumTo; i != e; ++i)
812 assert((!To[i].getNode() ||
813 N->getValueType(i) == To[i].getValueType()) &&
814 "Cannot combine value to value of different type!");
816 WorklistRemover DeadNodes(*this);
817 DAG.ReplaceAllUsesWith(N, To);
819 // Push the new nodes and any users onto the worklist
820 for (unsigned i = 0, e = NumTo; i != e; ++i) {
821 if (To[i].getNode()) {
822 AddToWorklist(To[i].getNode());
823 AddUsersToWorklist(To[i].getNode());
828 // Finally, if the node is now dead, remove it from the graph. The node
829 // may not be dead if the replacement process recursively simplified to
830 // something else needing this node.
832 deleteAndRecombine(N);
833 return SDValue(N, 0);
837 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
838 // Replace all uses. If any nodes become isomorphic to other nodes and
839 // are deleted, make sure to remove them from our worklist.
840 WorklistRemover DeadNodes(*this);
841 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
843 // Push the new node and any (possibly new) users onto the worklist.
844 AddToWorklist(TLO.New.getNode());
845 AddUsersToWorklist(TLO.New.getNode());
847 // Finally, if the node is now dead, remove it from the graph. The node
848 // may not be dead if the replacement process recursively simplified to
849 // something else needing this node.
850 if (TLO.Old.getNode()->use_empty())
851 deleteAndRecombine(TLO.Old.getNode());
854 /// Check the specified integer node value to see if it can be simplified or if
855 /// things it uses can be simplified by bit propagation. If so, return true.
856 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
857 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
858 APInt KnownZero, KnownOne;
859 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
863 AddToWorklist(Op.getNode());
865 // Replace the old value with the new one.
867 DEBUG(dbgs() << "\nReplacing.2 ";
868 TLO.Old.getNode()->dump(&DAG);
869 dbgs() << "\nWith: ";
870 TLO.New.getNode()->dump(&DAG);
873 CommitTargetLoweringOpt(TLO);
877 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
879 EVT VT = Load->getValueType(0);
880 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
882 DEBUG(dbgs() << "\nReplacing.9 ";
884 dbgs() << "\nWith: ";
885 Trunc.getNode()->dump(&DAG);
887 WorklistRemover DeadNodes(*this);
888 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
889 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
890 deleteAndRecombine(Load);
891 AddToWorklist(Trunc.getNode());
894 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
897 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
898 EVT MemVT = LD->getMemoryVT();
899 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
900 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
902 : LD->getExtensionType();
904 return DAG.getExtLoad(ExtType, dl, PVT,
905 LD->getChain(), LD->getBasePtr(),
906 MemVT, LD->getMemOperand());
909 unsigned Opc = Op.getOpcode();
912 case ISD::AssertSext:
913 return DAG.getNode(ISD::AssertSext, dl, PVT,
914 SExtPromoteOperand(Op.getOperand(0), PVT),
916 case ISD::AssertZext:
917 return DAG.getNode(ISD::AssertZext, dl, PVT,
918 ZExtPromoteOperand(Op.getOperand(0), PVT),
920 case ISD::Constant: {
922 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
923 return DAG.getNode(ExtOpc, dl, PVT, Op);
927 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
929 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
932 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
933 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
935 EVT OldVT = Op.getValueType();
937 bool Replace = false;
938 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
939 if (!NewOp.getNode())
941 AddToWorklist(NewOp.getNode());
944 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
945 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
946 DAG.getValueType(OldVT));
949 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
950 EVT OldVT = Op.getValueType();
952 bool Replace = false;
953 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
954 if (!NewOp.getNode())
956 AddToWorklist(NewOp.getNode());
959 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
960 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
963 /// Promote the specified integer binary operation if the target indicates it is
964 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
965 /// i32 since i16 instructions are longer.
966 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
967 if (!LegalOperations)
970 EVT VT = Op.getValueType();
971 if (VT.isVector() || !VT.isInteger())
974 // If operation type is 'undesirable', e.g. i16 on x86, consider
976 unsigned Opc = Op.getOpcode();
977 if (TLI.isTypeDesirableForOp(Opc, VT))
981 // Consult target whether it is a good idea to promote this operation and
982 // what's the right type to promote it to.
983 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
984 assert(PVT != VT && "Don't know what type to promote to!");
986 bool Replace0 = false;
987 SDValue N0 = Op.getOperand(0);
988 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
992 bool Replace1 = false;
993 SDValue N1 = Op.getOperand(1);
998 NN1 = PromoteOperand(N1, PVT, Replace1);
1003 AddToWorklist(NN0.getNode());
1005 AddToWorklist(NN1.getNode());
1008 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1010 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1012 DEBUG(dbgs() << "\nPromoting ";
1013 Op.getNode()->dump(&DAG));
1015 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1016 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1021 /// Promote the specified integer shift operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1025 if (!LegalOperations)
1028 EVT VT = Op.getValueType();
1029 if (VT.isVector() || !VT.isInteger())
1032 // If operation type is 'undesirable', e.g. i16 on x86, consider
1034 unsigned Opc = Op.getOpcode();
1035 if (TLI.isTypeDesirableForOp(Opc, VT))
1039 // Consult target whether it is a good idea to promote this operation and
1040 // what's the right type to promote it to.
1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042 assert(PVT != VT && "Don't know what type to promote to!");
1044 bool Replace = false;
1045 SDValue N0 = Op.getOperand(0);
1046 if (Opc == ISD::SRA)
1047 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1048 else if (Opc == ISD::SRL)
1049 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1051 N0 = PromoteOperand(N0, PVT, Replace);
1055 AddToWorklist(N0.getNode());
1057 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1059 DEBUG(dbgs() << "\nPromoting ";
1060 Op.getNode()->dump(&DAG));
1062 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1063 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1068 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1069 if (!LegalOperations)
1072 EVT VT = Op.getValueType();
1073 if (VT.isVector() || !VT.isInteger())
1076 // If operation type is 'undesirable', e.g. i16 on x86, consider
1078 unsigned Opc = Op.getOpcode();
1079 if (TLI.isTypeDesirableForOp(Opc, VT))
1083 // Consult target whether it is a good idea to promote this operation and
1084 // what's the right type to promote it to.
1085 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086 assert(PVT != VT && "Don't know what type to promote to!");
1087 // fold (aext (aext x)) -> (aext x)
1088 // fold (aext (zext x)) -> (zext x)
1089 // fold (aext (sext x)) -> (sext x)
1090 DEBUG(dbgs() << "\nPromoting ";
1091 Op.getNode()->dump(&DAG));
1092 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1097 bool DAGCombiner::PromoteLoad(SDValue Op) {
1098 if (!LegalOperations)
1101 EVT VT = Op.getValueType();
1102 if (VT.isVector() || !VT.isInteger())
1105 // If operation type is 'undesirable', e.g. i16 on x86, consider
1107 unsigned Opc = Op.getOpcode();
1108 if (TLI.isTypeDesirableForOp(Opc, VT))
1112 // Consult target whether it is a good idea to promote this operation and
1113 // what's the right type to promote it to.
1114 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1115 assert(PVT != VT && "Don't know what type to promote to!");
1118 SDNode *N = Op.getNode();
1119 LoadSDNode *LD = cast<LoadSDNode>(N);
1120 EVT MemVT = LD->getMemoryVT();
1121 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1122 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1124 : LD->getExtensionType();
1125 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1126 LD->getChain(), LD->getBasePtr(),
1127 MemVT, LD->getMemOperand());
1128 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1130 DEBUG(dbgs() << "\nPromoting ";
1133 Result.getNode()->dump(&DAG);
1135 WorklistRemover DeadNodes(*this);
1136 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1138 deleteAndRecombine(N);
1139 AddToWorklist(Result.getNode());
1145 /// \brief Recursively delete a node which has no uses and any operands for
1146 /// which it is the only use.
1148 /// Note that this both deletes the nodes and removes them from the worklist.
1149 /// It also adds any nodes who have had a user deleted to the worklist as they
1150 /// may now have only one use and subject to other combines.
1151 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1152 if (!N->use_empty())
1155 SmallSetVector<SDNode *, 16> Nodes;
1158 N = Nodes.pop_back_val();
1162 if (N->use_empty()) {
1163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1164 Nodes.insert(N->getOperand(i).getNode());
1166 removeFromWorklist(N);
1171 } while (!Nodes.empty());
1175 //===----------------------------------------------------------------------===//
1176 // Main DAG Combiner implementation
1177 //===----------------------------------------------------------------------===//
1179 void DAGCombiner::Run(CombineLevel AtLevel) {
1180 // set the instance variables, so that the various visit routines may use it.
1182 LegalOperations = Level >= AfterLegalizeVectorOps;
1183 LegalTypes = Level >= AfterLegalizeTypes;
1185 // Early exit if this basic block is in an optnone function.
1186 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1187 Attribute::OptimizeNone))
1190 // Add all the dag nodes to the worklist.
1191 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1192 E = DAG.allnodes_end(); I != E; ++I)
1195 // Create a dummy node (which is not added to allnodes), that adds a reference
1196 // to the root node, preventing it from being deleted, and tracking any
1197 // changes of the root.
1198 HandleSDNode Dummy(DAG.getRoot());
1200 // while the worklist isn't empty, find a node and
1201 // try and combine it.
1202 while (!WorklistMap.empty()) {
1204 // The Worklist holds the SDNodes in order, but it may contain null entries.
1206 N = Worklist.pop_back_val();
1209 bool GoodWorklistEntry = WorklistMap.erase(N);
1210 (void)GoodWorklistEntry;
1211 assert(GoodWorklistEntry &&
1212 "Found a worklist entry without a corresponding map entry!");
1214 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1215 // N is deleted from the DAG, since they too may now be dead or may have a
1216 // reduced number of uses, allowing other xforms.
1217 if (recursivelyDeleteUnusedNodes(N))
1220 WorklistRemover DeadNodes(*this);
1222 // If this combine is running after legalizing the DAG, re-legalize any
1223 // nodes pulled off the worklist.
1224 if (Level == AfterLegalizeDAG) {
1225 SmallSetVector<SDNode *, 16> UpdatedNodes;
1226 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1228 for (SDNode *LN : UpdatedNodes) {
1230 AddUsersToWorklist(LN);
1236 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1238 // Add any operands of the new node which have not yet been combined to the
1239 // worklist as well. Because the worklist uniques things already, this
1240 // won't repeatedly process the same operand.
1241 CombinedNodes.insert(N);
1242 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1243 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1244 AddToWorklist(N->getOperand(i).getNode());
1246 SDValue RV = combine(N);
1253 // If we get back the same node we passed in, rather than a new node or
1254 // zero, we know that the node must have defined multiple values and
1255 // CombineTo was used. Since CombineTo takes care of the worklist
1256 // mechanics for us, we have no work to do in this case.
1257 if (RV.getNode() == N)
1260 assert(N->getOpcode() != ISD::DELETED_NODE &&
1261 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1262 "Node was deleted but visit returned new node!");
1264 DEBUG(dbgs() << " ... into: ";
1265 RV.getNode()->dump(&DAG));
1267 // Transfer debug value.
1268 DAG.TransferDbgValues(SDValue(N, 0), RV);
1269 if (N->getNumValues() == RV.getNode()->getNumValues())
1270 DAG.ReplaceAllUsesWith(N, RV.getNode());
1272 assert(N->getValueType(0) == RV.getValueType() &&
1273 N->getNumValues() == 1 && "Type mismatch");
1275 DAG.ReplaceAllUsesWith(N, &OpV);
1278 // Push the new node and any users onto the worklist
1279 AddToWorklist(RV.getNode());
1280 AddUsersToWorklist(RV.getNode());
1282 // Finally, if the node is now dead, remove it from the graph. The node
1283 // may not be dead if the replacement process recursively simplified to
1284 // something else needing this node. This will also take care of adding any
1285 // operands which have lost a user to the worklist.
1286 recursivelyDeleteUnusedNodes(N);
1289 // If the root changed (e.g. it was a dead load, update the root).
1290 DAG.setRoot(Dummy.getValue());
1291 DAG.RemoveDeadNodes();
1294 SDValue DAGCombiner::visit(SDNode *N) {
1295 switch (N->getOpcode()) {
1297 case ISD::TokenFactor: return visitTokenFactor(N);
1298 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1299 case ISD::ADD: return visitADD(N);
1300 case ISD::SUB: return visitSUB(N);
1301 case ISD::ADDC: return visitADDC(N);
1302 case ISD::SUBC: return visitSUBC(N);
1303 case ISD::ADDE: return visitADDE(N);
1304 case ISD::SUBE: return visitSUBE(N);
1305 case ISD::MUL: return visitMUL(N);
1306 case ISD::SDIV: return visitSDIV(N);
1307 case ISD::UDIV: return visitUDIV(N);
1308 case ISD::SREM: return visitSREM(N);
1309 case ISD::UREM: return visitUREM(N);
1310 case ISD::MULHU: return visitMULHU(N);
1311 case ISD::MULHS: return visitMULHS(N);
1312 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1313 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1314 case ISD::SMULO: return visitSMULO(N);
1315 case ISD::UMULO: return visitUMULO(N);
1316 case ISD::SDIVREM: return visitSDIVREM(N);
1317 case ISD::UDIVREM: return visitUDIVREM(N);
1318 case ISD::AND: return visitAND(N);
1319 case ISD::OR: return visitOR(N);
1320 case ISD::XOR: return visitXOR(N);
1321 case ISD::SHL: return visitSHL(N);
1322 case ISD::SRA: return visitSRA(N);
1323 case ISD::SRL: return visitSRL(N);
1325 case ISD::ROTL: return visitRotate(N);
1326 case ISD::CTLZ: return visitCTLZ(N);
1327 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1328 case ISD::CTTZ: return visitCTTZ(N);
1329 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1330 case ISD::CTPOP: return visitCTPOP(N);
1331 case ISD::SELECT: return visitSELECT(N);
1332 case ISD::VSELECT: return visitVSELECT(N);
1333 case ISD::SELECT_CC: return visitSELECT_CC(N);
1334 case ISD::SETCC: return visitSETCC(N);
1335 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1336 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1337 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1338 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1339 case ISD::TRUNCATE: return visitTRUNCATE(N);
1340 case ISD::BITCAST: return visitBITCAST(N);
1341 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1342 case ISD::FADD: return visitFADD(N);
1343 case ISD::FSUB: return visitFSUB(N);
1344 case ISD::FMUL: return visitFMUL(N);
1345 case ISD::FMA: return visitFMA(N);
1346 case ISD::FDIV: return visitFDIV(N);
1347 case ISD::FREM: return visitFREM(N);
1348 case ISD::FSQRT: return visitFSQRT(N);
1349 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1350 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1351 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1352 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1353 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1354 case ISD::FP_ROUND: return visitFP_ROUND(N);
1355 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1356 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1357 case ISD::FNEG: return visitFNEG(N);
1358 case ISD::FABS: return visitFABS(N);
1359 case ISD::FFLOOR: return visitFFLOOR(N);
1360 case ISD::FMINNUM: return visitFMINNUM(N);
1361 case ISD::FMAXNUM: return visitFMAXNUM(N);
1362 case ISD::FCEIL: return visitFCEIL(N);
1363 case ISD::FTRUNC: return visitFTRUNC(N);
1364 case ISD::BRCOND: return visitBRCOND(N);
1365 case ISD::BR_CC: return visitBR_CC(N);
1366 case ISD::LOAD: return visitLOAD(N);
1367 case ISD::STORE: return visitSTORE(N);
1368 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1369 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1370 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1371 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1372 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1373 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1374 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1375 case ISD::MLOAD: return visitMLOAD(N);
1376 case ISD::MSTORE: return visitMSTORE(N);
1381 SDValue DAGCombiner::combine(SDNode *N) {
1382 SDValue RV = visit(N);
1384 // If nothing happened, try a target-specific DAG combine.
1385 if (!RV.getNode()) {
1386 assert(N->getOpcode() != ISD::DELETED_NODE &&
1387 "Node was deleted but visit returned NULL!");
1389 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1390 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1392 // Expose the DAG combiner to the target combiner impls.
1393 TargetLowering::DAGCombinerInfo
1394 DagCombineInfo(DAG, Level, false, this);
1396 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1400 // If nothing happened still, try promoting the operation.
1401 if (!RV.getNode()) {
1402 switch (N->getOpcode()) {
1410 RV = PromoteIntBinOp(SDValue(N, 0));
1415 RV = PromoteIntShiftOp(SDValue(N, 0));
1417 case ISD::SIGN_EXTEND:
1418 case ISD::ZERO_EXTEND:
1419 case ISD::ANY_EXTEND:
1420 RV = PromoteExtend(SDValue(N, 0));
1423 if (PromoteLoad(SDValue(N, 0)))
1429 // If N is a commutative binary node, try commuting it to enable more
1431 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1432 N->getNumValues() == 1) {
1433 SDValue N0 = N->getOperand(0);
1434 SDValue N1 = N->getOperand(1);
1436 // Constant operands are canonicalized to RHS.
1437 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1438 SDValue Ops[] = {N1, N0};
1440 if (const BinaryWithFlagsSDNode *BinNode =
1441 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1442 CSENode = DAG.getNodeIfExists(
1443 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1444 BinNode->hasNoSignedWrap(), BinNode->isExact());
1446 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1449 return SDValue(CSENode, 0);
1456 /// Given a node, return its input chain if it has one, otherwise return a null
1458 static SDValue getInputChainForNode(SDNode *N) {
1459 if (unsigned NumOps = N->getNumOperands()) {
1460 if (N->getOperand(0).getValueType() == MVT::Other)
1461 return N->getOperand(0);
1462 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1463 return N->getOperand(NumOps-1);
1464 for (unsigned i = 1; i < NumOps-1; ++i)
1465 if (N->getOperand(i).getValueType() == MVT::Other)
1466 return N->getOperand(i);
1471 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1472 // If N has two operands, where one has an input chain equal to the other,
1473 // the 'other' chain is redundant.
1474 if (N->getNumOperands() == 2) {
1475 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1476 return N->getOperand(0);
1477 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1478 return N->getOperand(1);
1481 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1482 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1483 SmallPtrSet<SDNode*, 16> SeenOps;
1484 bool Changed = false; // If we should replace this token factor.
1486 // Start out with this token factor.
1489 // Iterate through token factors. The TFs grows when new token factors are
1491 for (unsigned i = 0; i < TFs.size(); ++i) {
1492 SDNode *TF = TFs[i];
1494 // Check each of the operands.
1495 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1496 SDValue Op = TF->getOperand(i);
1498 switch (Op.getOpcode()) {
1499 case ISD::EntryToken:
1500 // Entry tokens don't need to be added to the list. They are
1505 case ISD::TokenFactor:
1506 if (Op.hasOneUse() &&
1507 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1508 // Queue up for processing.
1509 TFs.push_back(Op.getNode());
1510 // Clean up in case the token factor is removed.
1511 AddToWorklist(Op.getNode());
1518 // Only add if it isn't already in the list.
1519 if (SeenOps.insert(Op.getNode()).second)
1530 // If we've changed things around then replace token factor.
1533 // The entry token is the only possible outcome.
1534 Result = DAG.getEntryNode();
1536 // New and improved token factor.
1537 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1540 // Add users to worklist if AA is enabled, since it may introduce
1541 // a lot of new chained token factors while removing memory deps.
1542 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1543 : DAG.getSubtarget().useAA();
1544 return CombineTo(N, Result, UseAA /*add to worklist*/);
1550 /// MERGE_VALUES can always be eliminated.
1551 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1552 WorklistRemover DeadNodes(*this);
1553 // Replacing results may cause a different MERGE_VALUES to suddenly
1554 // be CSE'd with N, and carry its uses with it. Iterate until no
1555 // uses remain, to ensure that the node can be safely deleted.
1556 // First add the users of this node to the work list so that they
1557 // can be tried again once they have new operands.
1558 AddUsersToWorklist(N);
1560 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1562 } while (!N->use_empty());
1563 deleteAndRecombine(N);
1564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1567 SDValue DAGCombiner::visitADD(SDNode *N) {
1568 SDValue N0 = N->getOperand(0);
1569 SDValue N1 = N->getOperand(1);
1570 EVT VT = N0.getValueType();
1573 if (VT.isVector()) {
1574 SDValue FoldedVOp = SimplifyVBinOp(N);
1575 if (FoldedVOp.getNode()) return FoldedVOp;
1577 // fold (add x, 0) -> x, vector edition
1578 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1580 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1584 // fold (add x, undef) -> undef
1585 if (N0.getOpcode() == ISD::UNDEF)
1587 if (N1.getOpcode() == ISD::UNDEF)
1589 // fold (add c1, c2) -> c1+c2
1590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1591 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1593 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1594 // canonicalize constant to RHS
1596 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1597 // fold (add x, 0) -> x
1598 if (N1C && N1C->isNullValue())
1600 // fold (add Sym, c) -> Sym+c
1601 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1602 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1603 GA->getOpcode() == ISD::GlobalAddress)
1604 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1606 (uint64_t)N1C->getSExtValue());
1607 // fold ((c1-A)+c2) -> (c1+c2)-A
1608 if (N1C && N0.getOpcode() == ISD::SUB)
1609 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1610 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1611 DAG.getConstant(N1C->getAPIntValue()+
1612 N0C->getAPIntValue(), VT),
1615 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1618 // fold ((0-A) + B) -> B-A
1619 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1620 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1621 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1622 // fold (A + (0-B)) -> A-B
1623 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1624 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1625 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1626 // fold (A+(B-A)) -> B
1627 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1628 return N1.getOperand(0);
1629 // fold ((B-A)+A) -> B
1630 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1631 return N0.getOperand(0);
1632 // fold (A+(B-(A+C))) to (B-C)
1633 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1634 N0 == N1.getOperand(1).getOperand(0))
1635 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1636 N1.getOperand(1).getOperand(1));
1637 // fold (A+(B-(C+A))) to (B-C)
1638 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1639 N0 == N1.getOperand(1).getOperand(1))
1640 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1641 N1.getOperand(1).getOperand(0));
1642 // fold (A+((B-A)+or-C)) to (B+or-C)
1643 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1644 N1.getOperand(0).getOpcode() == ISD::SUB &&
1645 N0 == N1.getOperand(0).getOperand(1))
1646 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1647 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1649 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1650 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1651 SDValue N00 = N0.getOperand(0);
1652 SDValue N01 = N0.getOperand(1);
1653 SDValue N10 = N1.getOperand(0);
1654 SDValue N11 = N1.getOperand(1);
1656 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1657 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1658 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1659 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1662 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1663 return SDValue(N, 0);
1665 // fold (a+b) -> (a|b) iff a and b share no bits.
1666 if (VT.isInteger() && !VT.isVector()) {
1667 APInt LHSZero, LHSOne;
1668 APInt RHSZero, RHSOne;
1669 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1671 if (LHSZero.getBoolValue()) {
1672 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1674 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1675 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1676 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1677 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1678 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1683 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1684 if (N1.getOpcode() == ISD::SHL &&
1685 N1.getOperand(0).getOpcode() == ISD::SUB)
1686 if (ConstantSDNode *C =
1687 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1688 if (C->getAPIntValue() == 0)
1689 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1690 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1691 N1.getOperand(0).getOperand(1),
1693 if (N0.getOpcode() == ISD::SHL &&
1694 N0.getOperand(0).getOpcode() == ISD::SUB)
1695 if (ConstantSDNode *C =
1696 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1697 if (C->getAPIntValue() == 0)
1698 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1699 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1700 N0.getOperand(0).getOperand(1),
1703 if (N1.getOpcode() == ISD::AND) {
1704 SDValue AndOp0 = N1.getOperand(0);
1705 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1706 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1707 unsigned DestBits = VT.getScalarType().getSizeInBits();
1709 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1710 // and similar xforms where the inner op is either ~0 or 0.
1711 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1713 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1717 // add (sext i1), X -> sub X, (zext i1)
1718 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1719 N0.getOperand(0).getValueType() == MVT::i1 &&
1720 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1722 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1723 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1726 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1727 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1728 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1729 if (TN->getVT() == MVT::i1) {
1731 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1732 DAG.getConstant(1, VT));
1733 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1740 SDValue DAGCombiner::visitADDC(SDNode *N) {
1741 SDValue N0 = N->getOperand(0);
1742 SDValue N1 = N->getOperand(1);
1743 EVT VT = N0.getValueType();
1745 // If the flag result is dead, turn this into an ADD.
1746 if (!N->hasAnyUseOfValue(1))
1747 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1748 DAG.getNode(ISD::CARRY_FALSE,
1749 SDLoc(N), MVT::Glue));
1751 // canonicalize constant to RHS.
1752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1755 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1757 // fold (addc x, 0) -> x + no carry out
1758 if (N1C && N1C->isNullValue())
1759 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1760 SDLoc(N), MVT::Glue));
1762 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1763 APInt LHSZero, LHSOne;
1764 APInt RHSZero, RHSOne;
1765 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1767 if (LHSZero.getBoolValue()) {
1768 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1770 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1771 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1772 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1773 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1774 DAG.getNode(ISD::CARRY_FALSE,
1775 SDLoc(N), MVT::Glue));
1781 SDValue DAGCombiner::visitADDE(SDNode *N) {
1782 SDValue N0 = N->getOperand(0);
1783 SDValue N1 = N->getOperand(1);
1784 SDValue CarryIn = N->getOperand(2);
1786 // canonicalize constant to RHS
1787 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1788 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1793 // fold (adde x, y, false) -> (addc x, y)
1794 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1795 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1800 // Since it may not be valid to emit a fold to zero for vector initializers
1801 // check if we can before folding.
1802 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1804 bool LegalOperations, bool LegalTypes) {
1806 return DAG.getConstant(0, VT);
1807 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1808 return DAG.getConstant(0, VT);
1812 SDValue DAGCombiner::visitSUB(SDNode *N) {
1813 SDValue N0 = N->getOperand(0);
1814 SDValue N1 = N->getOperand(1);
1815 EVT VT = N0.getValueType();
1818 if (VT.isVector()) {
1819 SDValue FoldedVOp = SimplifyVBinOp(N);
1820 if (FoldedVOp.getNode()) return FoldedVOp;
1822 // fold (sub x, 0) -> x, vector edition
1823 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1827 // fold (sub x, x) -> 0
1828 // FIXME: Refactor this and xor and other similar operations together.
1830 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1831 // fold (sub c1, c2) -> c1-c2
1832 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1833 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1835 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1836 // fold (sub x, c) -> (add x, -c)
1838 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1839 DAG.getConstant(-N1C->getAPIntValue(), VT));
1840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1841 if (N0C && N0C->isAllOnesValue())
1842 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1843 // fold A-(A-B) -> B
1844 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1845 return N1.getOperand(1);
1846 // fold (A+B)-A -> B
1847 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1848 return N0.getOperand(1);
1849 // fold (A+B)-B -> A
1850 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1851 return N0.getOperand(0);
1852 // fold C2-(A+C1) -> (C2-C1)-A
1853 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1854 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1855 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1856 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1858 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1861 // fold ((A+(B+or-C))-B) -> A+or-C
1862 if (N0.getOpcode() == ISD::ADD &&
1863 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1864 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1865 N0.getOperand(1).getOperand(0) == N1)
1866 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1867 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1868 // fold ((A+(C+B))-B) -> A+C
1869 if (N0.getOpcode() == ISD::ADD &&
1870 N0.getOperand(1).getOpcode() == ISD::ADD &&
1871 N0.getOperand(1).getOperand(1) == N1)
1872 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1873 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1874 // fold ((A-(B-C))-C) -> A-B
1875 if (N0.getOpcode() == ISD::SUB &&
1876 N0.getOperand(1).getOpcode() == ISD::SUB &&
1877 N0.getOperand(1).getOperand(1) == N1)
1878 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1879 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1881 // If either operand of a sub is undef, the result is undef
1882 if (N0.getOpcode() == ISD::UNDEF)
1884 if (N1.getOpcode() == ISD::UNDEF)
1887 // If the relocation model supports it, consider symbol offsets.
1888 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1889 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1890 // fold (sub Sym, c) -> Sym-c
1891 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1892 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1894 (uint64_t)N1C->getSExtValue());
1895 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1896 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1897 if (GA->getGlobal() == GB->getGlobal())
1898 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1902 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1903 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1904 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1905 if (TN->getVT() == MVT::i1) {
1907 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1908 DAG.getConstant(1, VT));
1909 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1916 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1917 SDValue N0 = N->getOperand(0);
1918 SDValue N1 = N->getOperand(1);
1919 EVT VT = N0.getValueType();
1921 // If the flag result is dead, turn this into an SUB.
1922 if (!N->hasAnyUseOfValue(1))
1923 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1924 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927 // fold (subc x, x) -> 0 + no borrow
1929 return CombineTo(N, DAG.getConstant(0, VT),
1930 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1933 // fold (subc x, 0) -> x + no borrow
1934 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1935 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1936 if (N1C && N1C->isNullValue())
1937 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1940 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1941 if (N0C && N0C->isAllOnesValue())
1942 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1943 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1949 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1950 SDValue N0 = N->getOperand(0);
1951 SDValue N1 = N->getOperand(1);
1952 SDValue CarryIn = N->getOperand(2);
1954 // fold (sube x, y, false) -> (subc x, y)
1955 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1956 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1961 SDValue DAGCombiner::visitMUL(SDNode *N) {
1962 SDValue N0 = N->getOperand(0);
1963 SDValue N1 = N->getOperand(1);
1964 EVT VT = N0.getValueType();
1966 // fold (mul x, undef) -> 0
1967 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1968 return DAG.getConstant(0, VT);
1970 bool N0IsConst = false;
1971 bool N1IsConst = false;
1972 APInt ConstValue0, ConstValue1;
1974 if (VT.isVector()) {
1975 SDValue FoldedVOp = SimplifyVBinOp(N);
1976 if (FoldedVOp.getNode()) return FoldedVOp;
1978 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1979 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1981 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1982 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1984 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1985 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1989 // fold (mul c1, c2) -> c1*c2
1990 if (N0IsConst && N1IsConst)
1991 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1993 // canonicalize constant to RHS
1994 if (N0IsConst && !N1IsConst)
1995 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1996 // fold (mul x, 0) -> 0
1997 if (N1IsConst && ConstValue1 == 0)
1999 // We require a splat of the entire scalar bit width for non-contiguous
2002 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2003 // fold (mul x, 1) -> x
2004 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2006 // fold (mul x, -1) -> 0-x
2007 if (N1IsConst && ConstValue1.isAllOnesValue())
2008 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2009 DAG.getConstant(0, VT), N0);
2010 // fold (mul x, (1 << c)) -> x << c
2011 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2012 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2013 DAG.getConstant(ConstValue1.logBase2(),
2014 getShiftAmountTy(N0.getValueType())));
2015 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2016 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2017 unsigned Log2Val = (-ConstValue1).logBase2();
2018 // FIXME: If the input is something that is easily negated (e.g. a
2019 // single-use add), we should put the negate there.
2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021 DAG.getConstant(0, VT),
2022 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2023 DAG.getConstant(Log2Val,
2024 getShiftAmountTy(N0.getValueType()))));
2028 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2029 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2030 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2031 isa<ConstantSDNode>(N0.getOperand(1)))) {
2032 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2033 N1, N0.getOperand(1));
2034 AddToWorklist(C3.getNode());
2035 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036 N0.getOperand(0), C3);
2039 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2042 SDValue Sh(nullptr,0), Y(nullptr,0);
2043 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2044 if (N0.getOpcode() == ISD::SHL &&
2045 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2046 isa<ConstantSDNode>(N0.getOperand(1))) &&
2047 N0.getNode()->hasOneUse()) {
2049 } else if (N1.getOpcode() == ISD::SHL &&
2050 isa<ConstantSDNode>(N1.getOperand(1)) &&
2051 N1.getNode()->hasOneUse()) {
2056 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2057 Sh.getOperand(0), Y);
2058 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059 Mul, Sh.getOperand(1));
2063 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2064 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2065 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2066 isa<ConstantSDNode>(N0.getOperand(1))))
2067 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2068 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2069 N0.getOperand(0), N1),
2070 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2071 N0.getOperand(1), N1));
2074 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2081 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2082 SDValue N0 = N->getOperand(0);
2083 SDValue N1 = N->getOperand(1);
2084 EVT VT = N->getValueType(0);
2087 if (VT.isVector()) {
2088 SDValue FoldedVOp = SimplifyVBinOp(N);
2089 if (FoldedVOp.getNode()) return FoldedVOp;
2092 // fold (sdiv c1, c2) -> c1/c2
2093 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2094 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2095 if (N0C && N1C && !N1C->isNullValue())
2096 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2097 // fold (sdiv X, 1) -> X
2098 if (N1C && N1C->getAPIntValue() == 1LL)
2100 // fold (sdiv X, -1) -> 0-X
2101 if (N1C && N1C->isAllOnesValue())
2102 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2103 DAG.getConstant(0, VT), N0);
2104 // If we know the sign bits of both operands are zero, strength reduce to a
2105 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2106 if (!VT.isVector()) {
2107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2112 // fold (sdiv X, pow2) -> simple ops after legalize
2113 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2114 (-N1C->getAPIntValue()).isPowerOf2())) {
2115 // If dividing by powers of two is cheap, then don't perform the following
2117 if (TLI.isPow2SDivCheap())
2120 // Target-specific implementation of sdiv x, pow2.
2121 SDValue Res = BuildSDIVPow2(N);
2125 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2127 // Splat the sign bit into the register
2129 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2130 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2131 getShiftAmountTy(N0.getValueType())));
2132 AddToWorklist(SGN.getNode());
2134 // Add (N0 < 0) ? abs2 - 1 : 0;
2136 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2137 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2138 getShiftAmountTy(SGN.getValueType())));
2139 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2140 AddToWorklist(SRL.getNode());
2141 AddToWorklist(ADD.getNode()); // Divide by pow2
2142 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2143 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2145 // If we're dividing by a positive value, we're done. Otherwise, we must
2146 // negate the result.
2147 if (N1C->getAPIntValue().isNonNegative())
2150 AddToWorklist(SRA.getNode());
2151 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2154 // if integer divide is expensive and we satisfy the requirements, emit an
2155 // alternate sequence.
2156 if (N1C && !TLI.isIntDivCheap()) {
2157 SDValue Op = BuildSDIV(N);
2158 if (Op.getNode()) return Op;
2162 if (N0.getOpcode() == ISD::UNDEF)
2163 return DAG.getConstant(0, VT);
2164 // X / undef -> undef
2165 if (N1.getOpcode() == ISD::UNDEF)
2171 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2172 SDValue N0 = N->getOperand(0);
2173 SDValue N1 = N->getOperand(1);
2174 EVT VT = N->getValueType(0);
2177 if (VT.isVector()) {
2178 SDValue FoldedVOp = SimplifyVBinOp(N);
2179 if (FoldedVOp.getNode()) return FoldedVOp;
2182 // fold (udiv c1, c2) -> c1/c2
2183 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2184 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2185 if (N0C && N1C && !N1C->isNullValue())
2186 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2187 // fold (udiv x, (1 << c)) -> x >>u c
2188 if (N1C && N1C->getAPIntValue().isPowerOf2())
2189 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2190 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2191 getShiftAmountTy(N0.getValueType())));
2192 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2193 if (N1.getOpcode() == ISD::SHL) {
2194 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2195 if (SHC->getAPIntValue().isPowerOf2()) {
2196 EVT ADDVT = N1.getOperand(1).getValueType();
2197 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2199 DAG.getConstant(SHC->getAPIntValue()
2202 AddToWorklist(Add.getNode());
2203 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2207 // fold (udiv x, c) -> alternate
2208 if (N1C && !TLI.isIntDivCheap()) {
2209 SDValue Op = BuildUDIV(N);
2210 if (Op.getNode()) return Op;
2214 if (N0.getOpcode() == ISD::UNDEF)
2215 return DAG.getConstant(0, VT);
2216 // X / undef -> undef
2217 if (N1.getOpcode() == ISD::UNDEF)
2223 SDValue DAGCombiner::visitSREM(SDNode *N) {
2224 SDValue N0 = N->getOperand(0);
2225 SDValue N1 = N->getOperand(1);
2226 EVT VT = N->getValueType(0);
2228 // fold (srem c1, c2) -> c1%c2
2229 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2230 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2231 if (N0C && N1C && !N1C->isNullValue())
2232 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2233 // If we know the sign bits of both operands are zero, strength reduce to a
2234 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2235 if (!VT.isVector()) {
2236 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2237 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2240 // If X/C can be simplified by the division-by-constant logic, lower
2241 // X%C to the equivalent of X-X/C*C.
2242 if (N1C && !N1C->isNullValue()) {
2243 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2244 AddToWorklist(Div.getNode());
2245 SDValue OptimizedDiv = combine(Div.getNode());
2246 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2247 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2249 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2250 AddToWorklist(Mul.getNode());
2256 if (N0.getOpcode() == ISD::UNDEF)
2257 return DAG.getConstant(0, VT);
2258 // X % undef -> undef
2259 if (N1.getOpcode() == ISD::UNDEF)
2265 SDValue DAGCombiner::visitUREM(SDNode *N) {
2266 SDValue N0 = N->getOperand(0);
2267 SDValue N1 = N->getOperand(1);
2268 EVT VT = N->getValueType(0);
2270 // fold (urem c1, c2) -> c1%c2
2271 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2272 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2273 if (N0C && N1C && !N1C->isNullValue())
2274 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2275 // fold (urem x, pow2) -> (and x, pow2-1)
2276 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2277 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2278 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2279 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2280 if (N1.getOpcode() == ISD::SHL) {
2281 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2282 if (SHC->getAPIntValue().isPowerOf2()) {
2284 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2285 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2287 AddToWorklist(Add.getNode());
2288 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2293 // If X/C can be simplified by the division-by-constant logic, lower
2294 // X%C to the equivalent of X-X/C*C.
2295 if (N1C && !N1C->isNullValue()) {
2296 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2297 AddToWorklist(Div.getNode());
2298 SDValue OptimizedDiv = combine(Div.getNode());
2299 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2300 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2302 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2303 AddToWorklist(Mul.getNode());
2309 if (N0.getOpcode() == ISD::UNDEF)
2310 return DAG.getConstant(0, VT);
2311 // X % undef -> undef
2312 if (N1.getOpcode() == ISD::UNDEF)
2318 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2319 SDValue N0 = N->getOperand(0);
2320 SDValue N1 = N->getOperand(1);
2321 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2322 EVT VT = N->getValueType(0);
2325 // fold (mulhs x, 0) -> 0
2326 if (N1C && N1C->isNullValue())
2328 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2329 if (N1C && N1C->getAPIntValue() == 1)
2330 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2331 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2332 getShiftAmountTy(N0.getValueType())));
2333 // fold (mulhs x, undef) -> 0
2334 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2335 return DAG.getConstant(0, VT);
2337 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2339 if (VT.isSimple() && !VT.isVector()) {
2340 MVT Simple = VT.getSimpleVT();
2341 unsigned SimpleSize = Simple.getSizeInBits();
2342 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2343 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2344 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2345 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2346 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2347 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2348 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2349 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2356 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2357 SDValue N0 = N->getOperand(0);
2358 SDValue N1 = N->getOperand(1);
2359 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2360 EVT VT = N->getValueType(0);
2363 // fold (mulhu x, 0) -> 0
2364 if (N1C && N1C->isNullValue())
2366 // fold (mulhu x, 1) -> 0
2367 if (N1C && N1C->getAPIntValue() == 1)
2368 return DAG.getConstant(0, N0.getValueType());
2369 // fold (mulhu x, undef) -> 0
2370 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371 return DAG.getConstant(0, VT);
2373 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2375 if (VT.isSimple() && !VT.isVector()) {
2376 MVT Simple = VT.getSimpleVT();
2377 unsigned SimpleSize = Simple.getSizeInBits();
2378 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2381 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2382 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2385 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2392 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2393 /// give the opcodes for the two computations that are being performed. Return
2394 /// true if a simplification was made.
2395 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2397 // If the high half is not needed, just compute the low half.
2398 bool HiExists = N->hasAnyUseOfValue(1);
2400 (!LegalOperations ||
2401 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2402 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2403 return CombineTo(N, Res, Res);
2406 // If the low half is not needed, just compute the high half.
2407 bool LoExists = N->hasAnyUseOfValue(0);
2409 (!LegalOperations ||
2410 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2411 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2412 return CombineTo(N, Res, Res);
2415 // If both halves are used, return as it is.
2416 if (LoExists && HiExists)
2419 // If the two computed results can be simplified separately, separate them.
2421 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2422 AddToWorklist(Lo.getNode());
2423 SDValue LoOpt = combine(Lo.getNode());
2424 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2425 (!LegalOperations ||
2426 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2427 return CombineTo(N, LoOpt, LoOpt);
2431 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2432 AddToWorklist(Hi.getNode());
2433 SDValue HiOpt = combine(Hi.getNode());
2434 if (HiOpt.getNode() && HiOpt != Hi &&
2435 (!LegalOperations ||
2436 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2437 return CombineTo(N, HiOpt, HiOpt);
2443 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2444 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2445 if (Res.getNode()) return Res;
2447 EVT VT = N->getValueType(0);
2450 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2452 if (VT.isSimple() && !VT.isVector()) {
2453 MVT Simple = VT.getSimpleVT();
2454 unsigned SimpleSize = Simple.getSizeInBits();
2455 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2458 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2459 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460 // Compute the high part as N1.
2461 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464 // Compute the low part as N0.
2465 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466 return CombineTo(N, Lo, Hi);
2473 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2474 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2475 if (Res.getNode()) return Res;
2477 EVT VT = N->getValueType(0);
2480 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2482 if (VT.isSimple() && !VT.isVector()) {
2483 MVT Simple = VT.getSimpleVT();
2484 unsigned SimpleSize = Simple.getSizeInBits();
2485 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2486 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2487 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2488 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2489 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2490 // Compute the high part as N1.
2491 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2492 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2493 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2494 // Compute the low part as N0.
2495 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2496 return CombineTo(N, Lo, Hi);
2503 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2504 // (smulo x, 2) -> (saddo x, x)
2505 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2506 if (C2->getAPIntValue() == 2)
2507 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2508 N->getOperand(0), N->getOperand(0));
2513 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2514 // (umulo x, 2) -> (uaddo x, x)
2515 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2516 if (C2->getAPIntValue() == 2)
2517 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2518 N->getOperand(0), N->getOperand(0));
2523 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2524 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2525 if (Res.getNode()) return Res;
2530 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2531 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2532 if (Res.getNode()) return Res;
2537 /// If this is a binary operator with two operands of the same opcode, try to
2539 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2540 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2541 EVT VT = N0.getValueType();
2542 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2544 // Bail early if none of these transforms apply.
2545 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2547 // For each of OP in AND/OR/XOR:
2548 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2549 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2550 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2551 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2552 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2554 // do not sink logical op inside of a vector extend, since it may combine
2556 EVT Op0VT = N0.getOperand(0).getValueType();
2557 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2558 N0.getOpcode() == ISD::SIGN_EXTEND ||
2559 N0.getOpcode() == ISD::BSWAP ||
2560 // Avoid infinite looping with PromoteIntBinOp.
2561 (N0.getOpcode() == ISD::ANY_EXTEND &&
2562 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2563 (N0.getOpcode() == ISD::TRUNCATE &&
2564 (!TLI.isZExtFree(VT, Op0VT) ||
2565 !TLI.isTruncateFree(Op0VT, VT)) &&
2566 TLI.isTypeLegal(Op0VT))) &&
2568 Op0VT == N1.getOperand(0).getValueType() &&
2569 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2570 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2571 N0.getOperand(0).getValueType(),
2572 N0.getOperand(0), N1.getOperand(0));
2573 AddToWorklist(ORNode.getNode());
2574 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2577 // For each of OP in SHL/SRL/SRA/AND...
2578 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2579 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2580 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2581 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2582 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2583 N0.getOperand(1) == N1.getOperand(1)) {
2584 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2585 N0.getOperand(0).getValueType(),
2586 N0.getOperand(0), N1.getOperand(0));
2587 AddToWorklist(ORNode.getNode());
2588 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2589 ORNode, N0.getOperand(1));
2592 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2593 // Only perform this optimization after type legalization and before
2594 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2595 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2596 // we don't want to undo this promotion.
2597 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2599 if ((N0.getOpcode() == ISD::BITCAST ||
2600 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2601 Level == AfterLegalizeTypes) {
2602 SDValue In0 = N0.getOperand(0);
2603 SDValue In1 = N1.getOperand(0);
2604 EVT In0Ty = In0.getValueType();
2605 EVT In1Ty = In1.getValueType();
2607 // If both incoming values are integers, and the original types are the
2609 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2610 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2611 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2612 AddToWorklist(Op.getNode());
2617 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2618 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2619 // If both shuffles use the same mask, and both shuffle within a single
2620 // vector, then it is worthwhile to move the swizzle after the operation.
2621 // The type-legalizer generates this pattern when loading illegal
2622 // vector types from memory. In many cases this allows additional shuffle
2624 // There are other cases where moving the shuffle after the xor/and/or
2625 // is profitable even if shuffles don't perform a swizzle.
2626 // If both shuffles use the same mask, and both shuffles have the same first
2627 // or second operand, then it might still be profitable to move the shuffle
2628 // after the xor/and/or operation.
2629 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2630 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2631 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2633 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2634 "Inputs to shuffles are not the same type");
2636 // Check that both shuffles use the same mask. The masks are known to be of
2637 // the same length because the result vector type is the same.
2638 // Check also that shuffles have only one use to avoid introducing extra
2640 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2641 SVN0->getMask().equals(SVN1->getMask())) {
2642 SDValue ShOp = N0->getOperand(1);
2644 // Don't try to fold this node if it requires introducing a
2645 // build vector of all zeros that might be illegal at this stage.
2646 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2648 ShOp = DAG.getConstant(0, VT);
2653 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2654 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2655 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2656 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2657 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658 N0->getOperand(0), N1->getOperand(0));
2659 AddToWorklist(NewNode.getNode());
2660 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2661 &SVN0->getMask()[0]);
2664 // Don't try to fold this node if it requires introducing a
2665 // build vector of all zeros that might be illegal at this stage.
2666 ShOp = N0->getOperand(0);
2667 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2669 ShOp = DAG.getConstant(0, VT);
2674 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2675 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2676 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2677 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2678 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2679 N0->getOperand(1), N1->getOperand(1));
2680 AddToWorklist(NewNode.getNode());
2681 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2682 &SVN0->getMask()[0]);
2690 /// This contains all DAGCombine rules which reduce two values combined by
2691 /// an And operation to a single value. This makes them reusable in the context
2692 /// of visitSELECT(). Rules involving constants are not included as
2693 /// visitSELECT() already handles those cases.
2694 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2695 SDNode *LocReference) {
2696 EVT VT = N1.getValueType();
2698 // fold (and x, undef) -> 0
2699 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2700 return DAG.getConstant(0, VT);
2701 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2702 SDValue LL, LR, RL, RR, CC0, CC1;
2703 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2704 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2705 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2707 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2708 LL.getValueType().isInteger()) {
2709 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2710 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2711 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2712 LR.getValueType(), LL, RL);
2713 AddToWorklist(ORNode.getNode());
2714 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2716 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2717 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2718 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2719 LR.getValueType(), LL, RL);
2720 AddToWorklist(ANDNode.getNode());
2721 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2723 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2724 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2725 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2726 LR.getValueType(), LL, RL);
2727 AddToWorklist(ORNode.getNode());
2728 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2731 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2732 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2733 Op0 == Op1 && LL.getValueType().isInteger() &&
2734 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2735 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2736 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2737 cast<ConstantSDNode>(RR)->isNullValue()))) {
2738 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2739 LL, DAG.getConstant(1, LL.getValueType()));
2740 AddToWorklist(ADDNode.getNode());
2741 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2742 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2744 // canonicalize equivalent to ll == rl
2745 if (LL == RR && LR == RL) {
2746 Op1 = ISD::getSetCCSwappedOperands(Op1);
2749 if (LL == RL && LR == RR) {
2750 bool isInteger = LL.getValueType().isInteger();
2751 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2752 if (Result != ISD::SETCC_INVALID &&
2753 (!LegalOperations ||
2754 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2755 TLI.isOperationLegal(ISD::SETCC,
2756 getSetCCResultType(N0.getSimpleValueType())))))
2757 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2762 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2763 VT.getSizeInBits() <= 64) {
2764 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2765 APInt ADDC = ADDI->getAPIntValue();
2766 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2767 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2768 // immediate for an add, but it is legal if its top c2 bits are set,
2769 // transform the ADD so the immediate doesn't need to be materialized
2771 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2772 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2773 SRLI->getZExtValue());
2774 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2776 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2778 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2779 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2780 CombineTo(N0.getNode(), NewAdd);
2781 // Return N so it doesn't get rechecked!
2782 return SDValue(LocReference, 0);
2793 SDValue DAGCombiner::visitAND(SDNode *N) {
2794 SDValue N0 = N->getOperand(0);
2795 SDValue N1 = N->getOperand(1);
2796 EVT VT = N1.getValueType();
2799 if (VT.isVector()) {
2800 SDValue FoldedVOp = SimplifyVBinOp(N);
2801 if (FoldedVOp.getNode()) return FoldedVOp;
2803 // fold (and x, 0) -> 0, vector edition
2804 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2805 // do not return N0, because undef node may exist in N0
2806 return DAG.getConstant(
2807 APInt::getNullValue(
2808 N0.getValueType().getScalarType().getSizeInBits()),
2810 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2811 // do not return N1, because undef node may exist in N1
2812 return DAG.getConstant(
2813 APInt::getNullValue(
2814 N1.getValueType().getScalarType().getSizeInBits()),
2817 // fold (and x, -1) -> x, vector edition
2818 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2820 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2824 // fold (and c1, c2) -> c1&c2
2825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2828 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2829 // canonicalize constant to RHS
2831 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2832 // fold (and x, -1) -> x
2833 if (N1C && N1C->isAllOnesValue())
2835 // if (and x, c) is known to be zero, return 0
2836 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2837 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2838 APInt::getAllOnesValue(BitWidth)))
2839 return DAG.getConstant(0, VT);
2841 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2844 // fold (and (or x, C), D) -> D if (C & D) == D
2845 if (N1C && N0.getOpcode() == ISD::OR)
2846 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2847 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2849 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2850 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2851 SDValue N0Op0 = N0.getOperand(0);
2852 APInt Mask = ~N1C->getAPIntValue();
2853 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2854 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2855 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2856 N0.getValueType(), N0Op0);
2858 // Replace uses of the AND with uses of the Zero extend node.
2861 // We actually want to replace all uses of the any_extend with the
2862 // zero_extend, to avoid duplicating things. This will later cause this
2863 // AND to be folded.
2864 CombineTo(N0.getNode(), Zext);
2865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2868 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2869 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2870 // already be zero by virtue of the width of the base type of the load.
2872 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2874 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2875 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2876 N0.getOpcode() == ISD::LOAD) {
2877 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2878 N0 : N0.getOperand(0) );
2880 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2881 // This can be a pure constant or a vector splat, in which case we treat the
2882 // vector as a scalar and use the splat value.
2883 APInt Constant = APInt::getNullValue(1);
2884 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2885 Constant = C->getAPIntValue();
2886 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2887 APInt SplatValue, SplatUndef;
2888 unsigned SplatBitSize;
2890 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2891 SplatBitSize, HasAnyUndefs);
2893 // Undef bits can contribute to a possible optimisation if set, so
2895 SplatValue |= SplatUndef;
2897 // The splat value may be something like "0x00FFFFFF", which means 0 for
2898 // the first vector value and FF for the rest, repeating. We need a mask
2899 // that will apply equally to all members of the vector, so AND all the
2900 // lanes of the constant together.
2901 EVT VT = Vector->getValueType(0);
2902 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2904 // If the splat value has been compressed to a bitlength lower
2905 // than the size of the vector lane, we need to re-expand it to
2907 if (BitWidth > SplatBitSize)
2908 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2909 SplatBitSize < BitWidth;
2910 SplatBitSize = SplatBitSize * 2)
2911 SplatValue |= SplatValue.shl(SplatBitSize);
2913 Constant = APInt::getAllOnesValue(BitWidth);
2914 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2915 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2919 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2920 // actually legal and isn't going to get expanded, else this is a false
2922 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2923 Load->getValueType(0),
2924 Load->getMemoryVT());
2926 // Resize the constant to the same size as the original memory access before
2927 // extension. If it is still the AllOnesValue then this AND is completely
2930 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2933 switch (Load->getExtensionType()) {
2934 default: B = false; break;
2935 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2937 case ISD::NON_EXTLOAD: B = true; break;
2940 if (B && Constant.isAllOnesValue()) {
2941 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2942 // preserve semantics once we get rid of the AND.
2943 SDValue NewLoad(Load, 0);
2944 if (Load->getExtensionType() == ISD::EXTLOAD) {
2945 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2946 Load->getValueType(0), SDLoc(Load),
2947 Load->getChain(), Load->getBasePtr(),
2948 Load->getOffset(), Load->getMemoryVT(),
2949 Load->getMemOperand());
2950 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2951 if (Load->getNumValues() == 3) {
2952 // PRE/POST_INC loads have 3 values.
2953 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2954 NewLoad.getValue(2) };
2955 CombineTo(Load, To, 3, true);
2957 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2961 // Fold the AND away, taking care not to fold to the old load node if we
2963 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2969 // fold (and (load x), 255) -> (zextload x, i8)
2970 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2971 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2972 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2973 (N0.getOpcode() == ISD::ANY_EXTEND &&
2974 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2975 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2976 LoadSDNode *LN0 = HasAnyExt
2977 ? cast<LoadSDNode>(N0.getOperand(0))
2978 : cast<LoadSDNode>(N0);
2979 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2980 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2981 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2982 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2983 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2984 EVT LoadedVT = LN0->getMemoryVT();
2985 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2987 if (ExtVT == LoadedVT &&
2988 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2992 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2993 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2994 LN0->getMemOperand());
2996 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2997 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3000 // Do not change the width of a volatile load.
3001 // Do not generate loads of non-round integer types since these can
3002 // be expensive (and would be wrong if the type is not byte sized).
3003 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3004 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3006 EVT PtrType = LN0->getOperand(1).getValueType();
3008 unsigned Alignment = LN0->getAlignment();
3009 SDValue NewPtr = LN0->getBasePtr();
3011 // For big endian targets, we need to add an offset to the pointer
3012 // to load the correct bytes. For little endian systems, we merely
3013 // need to read fewer bytes from the same pointer.
3014 if (TLI.isBigEndian()) {
3015 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3016 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3017 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3018 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3019 NewPtr, DAG.getConstant(PtrOff, PtrType));
3020 Alignment = MinAlign(Alignment, PtrOff);
3023 AddToWorklist(NewPtr.getNode());
3026 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3027 LN0->getChain(), NewPtr,
3028 LN0->getPointerInfo(),
3029 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3030 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3032 CombineTo(LN0, Load, Load.getValue(1));
3033 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3039 if (SDValue Combined = visitANDLike(N0, N1, N))
3042 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3043 if (N0.getOpcode() == N1.getOpcode()) {
3044 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3045 if (Tmp.getNode()) return Tmp;
3048 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3049 // fold (and (sra)) -> (and (srl)) when possible.
3050 if (!VT.isVector() &&
3051 SimplifyDemandedBits(SDValue(N, 0)))
3052 return SDValue(N, 0);
3054 // fold (zext_inreg (extload x)) -> (zextload x)
3055 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3056 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3057 EVT MemVT = LN0->getMemoryVT();
3058 // If we zero all the possible extended bits, then we can turn this into
3059 // a zextload if we are running before legalize or the operation is legal.
3060 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3061 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3062 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3063 ((!LegalOperations && !LN0->isVolatile()) ||
3064 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3065 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3066 LN0->getChain(), LN0->getBasePtr(),
3067 MemVT, LN0->getMemOperand());
3069 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3070 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3073 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3074 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3076 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3077 EVT MemVT = LN0->getMemoryVT();
3078 // If we zero all the possible extended bits, then we can turn this into
3079 // a zextload if we are running before legalize or the operation is legal.
3080 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3081 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3082 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3083 ((!LegalOperations && !LN0->isVolatile()) ||
3084 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3085 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3086 LN0->getChain(), LN0->getBasePtr(),
3087 MemVT, LN0->getMemOperand());
3089 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3090 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3093 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3094 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3095 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3096 N0.getOperand(1), false);
3097 if (BSwap.getNode())
3104 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3105 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3106 bool DemandHighBits) {
3107 if (!LegalOperations)
3110 EVT VT = N->getValueType(0);
3111 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3113 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3116 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3117 bool LookPassAnd0 = false;
3118 bool LookPassAnd1 = false;
3119 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3121 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3123 if (N0.getOpcode() == ISD::AND) {
3124 if (!N0.getNode()->hasOneUse())
3126 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127 if (!N01C || N01C->getZExtValue() != 0xFF00)
3129 N0 = N0.getOperand(0);
3130 LookPassAnd0 = true;
3133 if (N1.getOpcode() == ISD::AND) {
3134 if (!N1.getNode()->hasOneUse())
3136 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3137 if (!N11C || N11C->getZExtValue() != 0xFF)
3139 N1 = N1.getOperand(0);
3140 LookPassAnd1 = true;
3143 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3145 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3147 if (!N0.getNode()->hasOneUse() ||
3148 !N1.getNode()->hasOneUse())
3151 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3152 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3155 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3158 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3159 SDValue N00 = N0->getOperand(0);
3160 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3161 if (!N00.getNode()->hasOneUse())
3163 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3164 if (!N001C || N001C->getZExtValue() != 0xFF)
3166 N00 = N00.getOperand(0);
3167 LookPassAnd0 = true;
3170 SDValue N10 = N1->getOperand(0);
3171 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3172 if (!N10.getNode()->hasOneUse())
3174 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3175 if (!N101C || N101C->getZExtValue() != 0xFF00)
3177 N10 = N10.getOperand(0);
3178 LookPassAnd1 = true;
3184 // Make sure everything beyond the low halfword gets set to zero since the SRL
3185 // 16 will clear the top bits.
3186 unsigned OpSizeInBits = VT.getSizeInBits();
3187 if (DemandHighBits && OpSizeInBits > 16) {
3188 // If the left-shift isn't masked out then the only way this is a bswap is
3189 // if all bits beyond the low 8 are 0. In that case the entire pattern
3190 // reduces to a left shift anyway: leave it for other parts of the combiner.
3194 // However, if the right shift isn't masked out then it might be because
3195 // it's not needed. See if we can spot that too.
3196 if (!LookPassAnd1 &&
3197 !DAG.MaskedValueIsZero(
3198 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3202 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3203 if (OpSizeInBits > 16)
3204 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3205 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3209 /// Return true if the specified node is an element that makes up a 32-bit
3210 /// packed halfword byteswap.
3211 /// ((x & 0x000000ff) << 8) |
3212 /// ((x & 0x0000ff00) >> 8) |
3213 /// ((x & 0x00ff0000) << 8) |
3214 /// ((x & 0xff000000) >> 8)
3215 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3216 if (!N.getNode()->hasOneUse())
3219 unsigned Opc = N.getOpcode();
3220 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3223 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3228 switch (N1C->getZExtValue()) {
3231 case 0xFF: Num = 0; break;
3232 case 0xFF00: Num = 1; break;
3233 case 0xFF0000: Num = 2; break;
3234 case 0xFF000000: Num = 3; break;
3237 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3238 SDValue N0 = N.getOperand(0);
3239 if (Opc == ISD::AND) {
3240 if (Num == 0 || Num == 2) {
3242 // (x >> 8) & 0xff0000
3243 if (N0.getOpcode() != ISD::SRL)
3245 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3246 if (!C || C->getZExtValue() != 8)
3249 // (x << 8) & 0xff00
3250 // (x << 8) & 0xff000000
3251 if (N0.getOpcode() != ISD::SHL)
3253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3254 if (!C || C->getZExtValue() != 8)
3257 } else if (Opc == ISD::SHL) {
3259 // (x & 0xff0000) << 8
3260 if (Num != 0 && Num != 2)
3262 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3263 if (!C || C->getZExtValue() != 8)
3265 } else { // Opc == ISD::SRL
3266 // (x & 0xff00) >> 8
3267 // (x & 0xff000000) >> 8
3268 if (Num != 1 && Num != 3)
3270 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3271 if (!C || C->getZExtValue() != 8)
3278 Parts[Num] = N0.getOperand(0).getNode();
3282 /// Match a 32-bit packed halfword bswap. That is
3283 /// ((x & 0x000000ff) << 8) |
3284 /// ((x & 0x0000ff00) >> 8) |
3285 /// ((x & 0x00ff0000) << 8) |
3286 /// ((x & 0xff000000) >> 8)
3287 /// => (rotl (bswap x), 16)
3288 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3289 if (!LegalOperations)
3292 EVT VT = N->getValueType(0);
3295 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3299 // (or (or (and), (and)), (or (and), (and)))
3300 // (or (or (or (and), (and)), (and)), (and))
3301 if (N0.getOpcode() != ISD::OR)
3303 SDValue N00 = N0.getOperand(0);
3304 SDValue N01 = N0.getOperand(1);
3305 SDNode *Parts[4] = {};
3307 if (N1.getOpcode() == ISD::OR &&
3308 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3309 // (or (or (and), (and)), (or (and), (and)))
3310 SDValue N000 = N00.getOperand(0);
3311 if (!isBSwapHWordElement(N000, Parts))
3314 SDValue N001 = N00.getOperand(1);
3315 if (!isBSwapHWordElement(N001, Parts))
3317 SDValue N010 = N01.getOperand(0);
3318 if (!isBSwapHWordElement(N010, Parts))
3320 SDValue N011 = N01.getOperand(1);
3321 if (!isBSwapHWordElement(N011, Parts))
3324 // (or (or (or (and), (and)), (and)), (and))
3325 if (!isBSwapHWordElement(N1, Parts))
3327 if (!isBSwapHWordElement(N01, Parts))
3329 if (N00.getOpcode() != ISD::OR)
3331 SDValue N000 = N00.getOperand(0);
3332 if (!isBSwapHWordElement(N000, Parts))
3334 SDValue N001 = N00.getOperand(1);
3335 if (!isBSwapHWordElement(N001, Parts))
3339 // Make sure the parts are all coming from the same node.
3340 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3343 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3344 SDValue(Parts[0],0));
3346 // Result of the bswap should be rotated by 16. If it's not legal, then
3347 // do (x << 16) | (x >> 16).
3348 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3349 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3350 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3351 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3352 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3353 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3354 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3355 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3358 /// This contains all DAGCombine rules which reduce two values combined by
3359 /// an Or operation to a single value \see visitANDLike().
3360 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3361 EVT VT = N1.getValueType();
3362 // fold (or x, undef) -> -1
3363 if (!LegalOperations &&
3364 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3365 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3366 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3368 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3369 SDValue LL, LR, RL, RR, CC0, CC1;
3370 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3371 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3372 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3374 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3375 LL.getValueType().isInteger()) {
3376 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3377 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3378 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3379 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3380 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3381 LR.getValueType(), LL, RL);
3382 AddToWorklist(ORNode.getNode());
3383 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3385 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3386 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3387 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3388 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3389 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3390 LR.getValueType(), LL, RL);
3391 AddToWorklist(ANDNode.getNode());
3392 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3395 // canonicalize equivalent to ll == rl
3396 if (LL == RR && LR == RL) {
3397 Op1 = ISD::getSetCCSwappedOperands(Op1);
3400 if (LL == RL && LR == RR) {
3401 bool isInteger = LL.getValueType().isInteger();
3402 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3403 if (Result != ISD::SETCC_INVALID &&
3404 (!LegalOperations ||
3405 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3406 TLI.isOperationLegal(ISD::SETCC,
3407 getSetCCResultType(N0.getValueType())))))
3408 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3413 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3414 if (N0.getOpcode() == ISD::AND &&
3415 N1.getOpcode() == ISD::AND &&
3416 N0.getOperand(1).getOpcode() == ISD::Constant &&
3417 N1.getOperand(1).getOpcode() == ISD::Constant &&
3418 // Don't increase # computations.
3419 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3420 // We can only do this xform if we know that bits from X that are set in C2
3421 // but not in C1 are already zero. Likewise for Y.
3422 const APInt &LHSMask =
3423 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3424 const APInt &RHSMask =
3425 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3427 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3428 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3429 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3430 N0.getOperand(0), N1.getOperand(0));
3431 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3432 DAG.getConstant(LHSMask | RHSMask, VT));
3436 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3437 if (N0.getOpcode() == ISD::AND &&
3438 N1.getOpcode() == ISD::AND &&
3439 N0.getOperand(0) == N1.getOperand(0) &&
3440 // Don't increase # computations.
3441 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3442 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3443 N0.getOperand(1), N1.getOperand(1));
3444 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3450 SDValue DAGCombiner::visitOR(SDNode *N) {
3451 SDValue N0 = N->getOperand(0);
3452 SDValue N1 = N->getOperand(1);
3453 EVT VT = N1.getValueType();
3456 if (VT.isVector()) {
3457 SDValue FoldedVOp = SimplifyVBinOp(N);
3458 if (FoldedVOp.getNode()) return FoldedVOp;
3460 // fold (or x, 0) -> x, vector edition
3461 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3463 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3466 // fold (or x, -1) -> -1, vector edition
3467 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3468 // do not return N0, because undef node may exist in N0
3469 return DAG.getConstant(
3470 APInt::getAllOnesValue(
3471 N0.getValueType().getScalarType().getSizeInBits()),
3473 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3474 // do not return N1, because undef node may exist in N1
3475 return DAG.getConstant(
3476 APInt::getAllOnesValue(
3477 N1.getValueType().getScalarType().getSizeInBits()),
3480 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3481 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3482 // Do this only if the resulting shuffle is legal.
3483 if (isa<ShuffleVectorSDNode>(N0) &&
3484 isa<ShuffleVectorSDNode>(N1) &&
3485 // Avoid folding a node with illegal type.
3486 TLI.isTypeLegal(VT) &&
3487 N0->getOperand(1) == N1->getOperand(1) &&
3488 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3489 bool CanFold = true;
3490 unsigned NumElts = VT.getVectorNumElements();
3491 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3492 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3493 // We construct two shuffle masks:
3494 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3495 // and N1 as the second operand.
3496 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3497 // and N0 as the second operand.
3498 // We do this because OR is commutable and therefore there might be
3499 // two ways to fold this node into a shuffle.
3500 SmallVector<int,4> Mask1;
3501 SmallVector<int,4> Mask2;
3503 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3504 int M0 = SV0->getMaskElt(i);
3505 int M1 = SV1->getMaskElt(i);
3507 // Both shuffle indexes are undef. Propagate Undef.
3508 if (M0 < 0 && M1 < 0) {
3509 Mask1.push_back(M0);
3510 Mask2.push_back(M0);
3514 if (M0 < 0 || M1 < 0 ||
3515 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3516 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3521 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3522 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3526 // Fold this sequence only if the resulting shuffle is 'legal'.
3527 if (TLI.isShuffleMaskLegal(Mask1, VT))
3528 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3529 N1->getOperand(0), &Mask1[0]);
3530 if (TLI.isShuffleMaskLegal(Mask2, VT))
3531 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3532 N0->getOperand(0), &Mask2[0]);
3537 // fold (or c1, c2) -> c1|c2
3538 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3539 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3541 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3542 // canonicalize constant to RHS
3544 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3545 // fold (or x, 0) -> x
3546 if (N1C && N1C->isNullValue())
3548 // fold (or x, -1) -> -1
3549 if (N1C && N1C->isAllOnesValue())
3551 // fold (or x, c) -> c iff (x & ~c) == 0
3552 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3555 if (SDValue Combined = visitORLike(N0, N1, N))
3558 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3559 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3560 if (BSwap.getNode())
3562 BSwap = MatchBSwapHWordLow(N, N0, N1);
3563 if (BSwap.getNode())
3567 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3570 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3571 // iff (c1 & c2) == 0.
3572 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3573 isa<ConstantSDNode>(N0.getOperand(1))) {
3574 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3575 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3576 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3578 ISD::AND, SDLoc(N), VT,
3579 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3583 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3584 if (N0.getOpcode() == N1.getOpcode()) {
3585 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3586 if (Tmp.getNode()) return Tmp;
3589 // See if this is some rotate idiom.
3590 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3591 return SDValue(Rot, 0);
3593 // Simplify the operands using demanded-bits information.
3594 if (!VT.isVector() &&
3595 SimplifyDemandedBits(SDValue(N, 0)))
3596 return SDValue(N, 0);
3601 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3602 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3603 if (Op.getOpcode() == ISD::AND) {
3604 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3605 Mask = Op.getOperand(1);
3606 Op = Op.getOperand(0);
3612 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3620 // Return true if we can prove that, whenever Neg and Pos are both in the
3621 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3622 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3624 // (or (shift1 X, Neg), (shift2 X, Pos))
3626 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3627 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3628 // to consider shift amounts with defined behavior.
3629 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3630 // If OpSize is a power of 2 then:
3632 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3633 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3635 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3636 // for the stronger condition:
3638 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3640 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3641 // we can just replace Neg with Neg' for the rest of the function.
3643 // In other cases we check for the even stronger condition:
3645 // Neg == OpSize - Pos [B]
3647 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3648 // behavior if Pos == 0 (and consequently Neg == OpSize).
3650 // We could actually use [A] whenever OpSize is a power of 2, but the
3651 // only extra cases that it would match are those uninteresting ones
3652 // where Neg and Pos are never in range at the same time. E.g. for
3653 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3654 // as well as (sub 32, Pos), but:
3656 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3658 // always invokes undefined behavior for 32-bit X.
3660 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3661 unsigned MaskLoBits = 0;
3662 if (Neg.getOpcode() == ISD::AND &&
3663 isPowerOf2_64(OpSize) &&
3664 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3665 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3666 Neg = Neg.getOperand(0);
3667 MaskLoBits = Log2_64(OpSize);
3670 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3671 if (Neg.getOpcode() != ISD::SUB)
3673 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3676 SDValue NegOp1 = Neg.getOperand(1);
3678 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3679 // Pos'. The truncation is redundant for the purpose of the equality.
3681 Pos.getOpcode() == ISD::AND &&
3682 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3683 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3684 Pos = Pos.getOperand(0);
3686 // The condition we need is now:
3688 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3690 // If NegOp1 == Pos then we need:
3692 // OpSize & Mask == NegC & Mask
3694 // (because "x & Mask" is a truncation and distributes through subtraction).
3697 Width = NegC->getAPIntValue();
3698 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3699 // Then the condition we want to prove becomes:
3701 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3703 // which, again because "x & Mask" is a truncation, becomes:
3705 // NegC & Mask == (OpSize - PosC) & Mask
3706 // OpSize & Mask == (NegC + PosC) & Mask
3707 else if (Pos.getOpcode() == ISD::ADD &&
3708 Pos.getOperand(0) == NegOp1 &&
3709 Pos.getOperand(1).getOpcode() == ISD::Constant)
3710 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3711 NegC->getAPIntValue());
3715 // Now we just need to check that OpSize & Mask == Width & Mask.
3717 // Opsize & Mask is 0 since Mask is Opsize - 1.
3718 return Width.getLoBits(MaskLoBits) == 0;
3719 return Width == OpSize;
3722 // A subroutine of MatchRotate used once we have found an OR of two opposite
3723 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3724 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3725 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3726 // Neg with outer conversions stripped away.
3727 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3728 SDValue Neg, SDValue InnerPos,
3729 SDValue InnerNeg, unsigned PosOpcode,
3730 unsigned NegOpcode, SDLoc DL) {
3731 // fold (or (shl x, (*ext y)),
3732 // (srl x, (*ext (sub 32, y)))) ->
3733 // (rotl x, y) or (rotr x, (sub 32, y))
3735 // fold (or (shl x, (*ext (sub 32, y))),
3736 // (srl x, (*ext y))) ->
3737 // (rotr x, y) or (rotl x, (sub 32, y))
3738 EVT VT = Shifted.getValueType();
3739 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3740 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3741 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3742 HasPos ? Pos : Neg).getNode();
3748 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3749 // idioms for rotate, and if the target supports rotation instructions, generate
3751 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3752 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3753 EVT VT = LHS.getValueType();
3754 if (!TLI.isTypeLegal(VT)) return nullptr;
3756 // The target must have at least one rotate flavor.
3757 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3758 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3759 if (!HasROTL && !HasROTR) return nullptr;
3761 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3762 SDValue LHSShift; // The shift.
3763 SDValue LHSMask; // AND value if any.
3764 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3765 return nullptr; // Not part of a rotate.
3767 SDValue RHSShift; // The shift.
3768 SDValue RHSMask; // AND value if any.
3769 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3770 return nullptr; // Not part of a rotate.
3772 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3773 return nullptr; // Not shifting the same value.
3775 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3776 return nullptr; // Shifts must disagree.
3778 // Canonicalize shl to left side in a shl/srl pair.
3779 if (RHSShift.getOpcode() == ISD::SHL) {
3780 std::swap(LHS, RHS);
3781 std::swap(LHSShift, RHSShift);
3782 std::swap(LHSMask , RHSMask );
3785 unsigned OpSizeInBits = VT.getSizeInBits();
3786 SDValue LHSShiftArg = LHSShift.getOperand(0);
3787 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3788 SDValue RHSShiftArg = RHSShift.getOperand(0);
3789 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3791 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3792 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3793 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3794 RHSShiftAmt.getOpcode() == ISD::Constant) {
3795 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3796 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3797 if ((LShVal + RShVal) != OpSizeInBits)
3800 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3801 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3803 // If there is an AND of either shifted operand, apply it to the result.
3804 if (LHSMask.getNode() || RHSMask.getNode()) {
3805 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3807 if (LHSMask.getNode()) {
3808 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3809 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3811 if (RHSMask.getNode()) {
3812 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3813 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3816 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3819 return Rot.getNode();
3822 // If there is a mask here, and we have a variable shift, we can't be sure
3823 // that we're masking out the right stuff.
3824 if (LHSMask.getNode() || RHSMask.getNode())
3827 // If the shift amount is sign/zext/any-extended just peel it off.
3828 SDValue LExtOp0 = LHSShiftAmt;
3829 SDValue RExtOp0 = RHSShiftAmt;
3830 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3831 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3832 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3833 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3834 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3835 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3836 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3837 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3838 LExtOp0 = LHSShiftAmt.getOperand(0);
3839 RExtOp0 = RHSShiftAmt.getOperand(0);
3842 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3843 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3847 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3848 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3855 SDValue DAGCombiner::visitXOR(SDNode *N) {
3856 SDValue N0 = N->getOperand(0);
3857 SDValue N1 = N->getOperand(1);
3858 EVT VT = N0.getValueType();
3861 if (VT.isVector()) {
3862 SDValue FoldedVOp = SimplifyVBinOp(N);
3863 if (FoldedVOp.getNode()) return FoldedVOp;
3865 // fold (xor x, 0) -> x, vector edition
3866 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3868 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3872 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3873 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3874 return DAG.getConstant(0, VT);
3875 // fold (xor x, undef) -> undef
3876 if (N0.getOpcode() == ISD::UNDEF)
3878 if (N1.getOpcode() == ISD::UNDEF)
3880 // fold (xor c1, c2) -> c1^c2
3881 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3882 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3884 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3885 // canonicalize constant to RHS
3887 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3888 // fold (xor x, 0) -> x
3889 if (N1C && N1C->isNullValue())
3892 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3896 // fold !(x cc y) -> (x !cc y)
3897 SDValue LHS, RHS, CC;
3898 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3899 bool isInt = LHS.getValueType().isInteger();
3900 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3903 if (!LegalOperations ||
3904 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3905 switch (N0.getOpcode()) {
3907 llvm_unreachable("Unhandled SetCC Equivalent!");
3909 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3910 case ISD::SELECT_CC:
3911 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3912 N0.getOperand(3), NotCC);
3917 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3918 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3919 N0.getNode()->hasOneUse() &&
3920 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3921 SDValue V = N0.getOperand(0);
3922 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3923 DAG.getConstant(1, V.getValueType()));
3924 AddToWorklist(V.getNode());
3925 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3928 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3929 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3930 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3931 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3932 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3933 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3934 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3935 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3936 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3937 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3940 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3941 if (N1C && N1C->isAllOnesValue() &&
3942 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3943 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3944 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3945 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3946 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3947 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3948 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3949 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3952 // fold (xor (and x, y), y) -> (and (not x), y)
3953 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3954 N0->getOperand(1) == N1) {
3955 SDValue X = N0->getOperand(0);
3956 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3957 AddToWorklist(NotX.getNode());
3958 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3960 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3961 if (N1C && N0.getOpcode() == ISD::XOR) {
3962 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3963 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3965 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3966 DAG.getConstant(N1C->getAPIntValue() ^
3967 N00C->getAPIntValue(), VT));
3969 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3970 DAG.getConstant(N1C->getAPIntValue() ^
3971 N01C->getAPIntValue(), VT));
3973 // fold (xor x, x) -> 0
3975 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3977 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3978 if (N0.getOpcode() == N1.getOpcode()) {
3979 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3980 if (Tmp.getNode()) return Tmp;
3983 // Simplify the expression using non-local knowledge.
3984 if (!VT.isVector() &&
3985 SimplifyDemandedBits(SDValue(N, 0)))
3986 return SDValue(N, 0);
3991 /// Handle transforms common to the three shifts, when the shift amount is a
3993 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3994 // We can't and shouldn't fold opaque constants.
3995 if (Amt->isOpaque())
3998 SDNode *LHS = N->getOperand(0).getNode();
3999 if (!LHS->hasOneUse()) return SDValue();
4001 // We want to pull some binops through shifts, so that we have (and (shift))
4002 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4003 // thing happens with address calculations, so it's important to canonicalize
4005 bool HighBitSet = false; // Can we transform this if the high bit is set?
4007 switch (LHS->getOpcode()) {
4008 default: return SDValue();
4011 HighBitSet = false; // We can only transform sra if the high bit is clear.
4014 HighBitSet = true; // We can only transform sra if the high bit is set.
4017 if (N->getOpcode() != ISD::SHL)
4018 return SDValue(); // only shl(add) not sr[al](add).
4019 HighBitSet = false; // We can only transform sra if the high bit is clear.
4023 // We require the RHS of the binop to be a constant and not opaque as well.
4024 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4025 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4027 // FIXME: disable this unless the input to the binop is a shift by a constant.
4028 // If it is not a shift, it pessimizes some common cases like:
4030 // void foo(int *X, int i) { X[i & 1235] = 1; }
4031 // int bar(int *X, int i) { return X[i & 255]; }
4032 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4033 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4034 BinOpLHSVal->getOpcode() != ISD::SRA &&
4035 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4036 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4039 EVT VT = N->getValueType(0);
4041 // If this is a signed shift right, and the high bit is modified by the
4042 // logical operation, do not perform the transformation. The highBitSet
4043 // boolean indicates the value of the high bit of the constant which would
4044 // cause it to be modified for this operation.
4045 if (N->getOpcode() == ISD::SRA) {
4046 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4047 if (BinOpRHSSignSet != HighBitSet)
4051 if (!TLI.isDesirableToCommuteWithShift(LHS))
4054 // Fold the constants, shifting the binop RHS by the shift amount.
4055 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4057 LHS->getOperand(1), N->getOperand(1));
4058 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4060 // Create the new shift.
4061 SDValue NewShift = DAG.getNode(N->getOpcode(),
4062 SDLoc(LHS->getOperand(0)),
4063 VT, LHS->getOperand(0), N->getOperand(1));
4065 // Create the new binop.
4066 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4069 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4070 assert(N->getOpcode() == ISD::TRUNCATE);
4071 assert(N->getOperand(0).getOpcode() == ISD::AND);
4073 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4074 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4075 SDValue N01 = N->getOperand(0).getOperand(1);
4077 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4078 EVT TruncVT = N->getValueType(0);
4079 SDValue N00 = N->getOperand(0).getOperand(0);
4080 APInt TruncC = N01C->getAPIntValue();
4081 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4083 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4084 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4085 DAG.getConstant(TruncC, TruncVT));
4092 SDValue DAGCombiner::visitRotate(SDNode *N) {
4093 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4094 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4095 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4096 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4097 if (NewOp1.getNode())
4098 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4099 N->getOperand(0), NewOp1);
4104 SDValue DAGCombiner::visitSHL(SDNode *N) {
4105 SDValue N0 = N->getOperand(0);
4106 SDValue N1 = N->getOperand(1);
4107 EVT VT = N0.getValueType();
4108 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4111 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4112 if (VT.isVector()) {
4113 SDValue FoldedVOp = SimplifyVBinOp(N);
4114 if (FoldedVOp.getNode()) return FoldedVOp;
4116 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4117 // If setcc produces all-one true value then:
4118 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4119 if (N1CV && N1CV->isConstant()) {
4120 if (N0.getOpcode() == ISD::AND) {
4121 SDValue N00 = N0->getOperand(0);
4122 SDValue N01 = N0->getOperand(1);
4123 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4125 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4126 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4127 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4128 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4129 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4132 N1C = isConstOrConstSplat(N1);
4137 // fold (shl c1, c2) -> c1<<c2
4138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4140 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4141 // fold (shl 0, x) -> 0
4142 if (N0C && N0C->isNullValue())
4144 // fold (shl x, c >= size(x)) -> undef
4145 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4146 return DAG.getUNDEF(VT);
4147 // fold (shl x, 0) -> x
4148 if (N1C && N1C->isNullValue())
4150 // fold (shl undef, x) -> 0
4151 if (N0.getOpcode() == ISD::UNDEF)
4152 return DAG.getConstant(0, VT);
4153 // if (shl x, c) is known to be zero, return 0
4154 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4155 APInt::getAllOnesValue(OpSizeInBits)))
4156 return DAG.getConstant(0, VT);
4157 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4158 if (N1.getOpcode() == ISD::TRUNCATE &&
4159 N1.getOperand(0).getOpcode() == ISD::AND) {
4160 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4161 if (NewOp1.getNode())
4162 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4165 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4166 return SDValue(N, 0);
4168 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4169 if (N1C && N0.getOpcode() == ISD::SHL) {
4170 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4171 uint64_t c1 = N0C1->getZExtValue();
4172 uint64_t c2 = N1C->getZExtValue();
4173 if (c1 + c2 >= OpSizeInBits)
4174 return DAG.getConstant(0, VT);
4175 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4176 DAG.getConstant(c1 + c2, N1.getValueType()));
4180 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4181 // For this to be valid, the second form must not preserve any of the bits
4182 // that are shifted out by the inner shift in the first form. This means
4183 // the outer shift size must be >= the number of bits added by the ext.
4184 // As a corollary, we don't care what kind of ext it is.
4185 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4186 N0.getOpcode() == ISD::ANY_EXTEND ||
4187 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4188 N0.getOperand(0).getOpcode() == ISD::SHL) {
4189 SDValue N0Op0 = N0.getOperand(0);
4190 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4191 uint64_t c1 = N0Op0C1->getZExtValue();
4192 uint64_t c2 = N1C->getZExtValue();
4193 EVT InnerShiftVT = N0Op0.getValueType();
4194 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4195 if (c2 >= OpSizeInBits - InnerShiftSize) {
4196 if (c1 + c2 >= OpSizeInBits)
4197 return DAG.getConstant(0, VT);
4198 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4199 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4200 N0Op0->getOperand(0)),
4201 DAG.getConstant(c1 + c2, N1.getValueType()));
4206 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4207 // Only fold this if the inner zext has no other uses to avoid increasing
4208 // the total number of instructions.
4209 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4210 N0.getOperand(0).getOpcode() == ISD::SRL) {
4211 SDValue N0Op0 = N0.getOperand(0);
4212 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4213 uint64_t c1 = N0Op0C1->getZExtValue();
4214 if (c1 < VT.getScalarSizeInBits()) {
4215 uint64_t c2 = N1C->getZExtValue();
4217 SDValue NewOp0 = N0.getOperand(0);
4218 EVT CountVT = NewOp0.getOperand(1).getValueType();
4219 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4220 NewOp0, DAG.getConstant(c2, CountVT));
4221 AddToWorklist(NewSHL.getNode());
4222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4228 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4229 // (and (srl x, (sub c1, c2), MASK)
4230 // Only fold this if the inner shift has no other uses -- if it does, folding
4231 // this will increase the total number of instructions.
4232 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4233 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4234 uint64_t c1 = N0C1->getZExtValue();
4235 if (c1 < OpSizeInBits) {
4236 uint64_t c2 = N1C->getZExtValue();
4237 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4240 Mask = Mask.shl(c2 - c1);
4241 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4242 DAG.getConstant(c2 - c1, N1.getValueType()));
4244 Mask = Mask.lshr(c1 - c2);
4245 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4246 DAG.getConstant(c1 - c2, N1.getValueType()));
4248 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4249 DAG.getConstant(Mask, VT));
4253 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4254 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4255 unsigned BitSize = VT.getScalarSizeInBits();
4256 SDValue HiBitsMask =
4257 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4258 BitSize - N1C->getZExtValue()), VT);
4259 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4263 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4264 // Variant of version done on multiply, except mul by a power of 2 is turned
4267 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4268 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4269 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4270 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4271 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4272 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4276 SDValue NewSHL = visitShiftByConstant(N, N1C);
4277 if (NewSHL.getNode())
4284 SDValue DAGCombiner::visitSRA(SDNode *N) {
4285 SDValue N0 = N->getOperand(0);
4286 SDValue N1 = N->getOperand(1);
4287 EVT VT = N0.getValueType();
4288 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4292 if (VT.isVector()) {
4293 SDValue FoldedVOp = SimplifyVBinOp(N);
4294 if (FoldedVOp.getNode()) return FoldedVOp;
4296 N1C = isConstOrConstSplat(N1);
4299 // fold (sra c1, c2) -> (sra c1, c2)
4300 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4302 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4303 // fold (sra 0, x) -> 0
4304 if (N0C && N0C->isNullValue())
4306 // fold (sra -1, x) -> -1
4307 if (N0C && N0C->isAllOnesValue())
4309 // fold (sra x, (setge c, size(x))) -> undef
4310 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4311 return DAG.getUNDEF(VT);
4312 // fold (sra x, 0) -> x
4313 if (N1C && N1C->isNullValue())
4315 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4317 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4318 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4319 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4321 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4322 ExtVT, VT.getVectorNumElements());
4323 if ((!LegalOperations ||
4324 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4325 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4326 N0.getOperand(0), DAG.getValueType(ExtVT));
4329 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4330 if (N1C && N0.getOpcode() == ISD::SRA) {
4331 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4332 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4333 if (Sum >= OpSizeInBits)
4334 Sum = OpSizeInBits - 1;
4335 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4336 DAG.getConstant(Sum, N1.getValueType()));
4340 // fold (sra (shl X, m), (sub result_size, n))
4341 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4342 // result_size - n != m.
4343 // If truncate is free for the target sext(shl) is likely to result in better
4345 if (N0.getOpcode() == ISD::SHL && N1C) {
4346 // Get the two constanst of the shifts, CN0 = m, CN = n.
4347 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4349 LLVMContext &Ctx = *DAG.getContext();
4350 // Determine what the truncate's result bitsize and type would be.
4351 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4354 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4356 // Determine the residual right-shift amount.
4357 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4359 // If the shift is not a no-op (in which case this should be just a sign
4360 // extend already), the truncated to type is legal, sign_extend is legal
4361 // on that type, and the truncate to that type is both legal and free,
4362 // perform the transform.
4363 if ((ShiftAmt > 0) &&
4364 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4365 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4366 TLI.isTruncateFree(VT, TruncVT)) {
4368 SDValue Amt = DAG.getConstant(ShiftAmt,
4369 getShiftAmountTy(N0.getOperand(0).getValueType()));
4370 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4371 N0.getOperand(0), Amt);
4372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4374 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4375 N->getValueType(0), Trunc);
4380 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4381 if (N1.getOpcode() == ISD::TRUNCATE &&
4382 N1.getOperand(0).getOpcode() == ISD::AND) {
4383 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4384 if (NewOp1.getNode())
4385 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4388 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4389 // if c1 is equal to the number of bits the trunc removes
4390 if (N0.getOpcode() == ISD::TRUNCATE &&
4391 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4392 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4393 N0.getOperand(0).hasOneUse() &&
4394 N0.getOperand(0).getOperand(1).hasOneUse() &&
4396 SDValue N0Op0 = N0.getOperand(0);
4397 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4398 unsigned LargeShiftVal = LargeShift->getZExtValue();
4399 EVT LargeVT = N0Op0.getValueType();
4401 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4403 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4404 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4405 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4406 N0Op0.getOperand(0), Amt);
4407 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4412 // Simplify, based on bits shifted out of the LHS.
4413 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4414 return SDValue(N, 0);
4417 // If the sign bit is known to be zero, switch this to a SRL.
4418 if (DAG.SignBitIsZero(N0))
4419 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4422 SDValue NewSRA = visitShiftByConstant(N, N1C);
4423 if (NewSRA.getNode())
4430 SDValue DAGCombiner::visitSRL(SDNode *N) {
4431 SDValue N0 = N->getOperand(0);
4432 SDValue N1 = N->getOperand(1);
4433 EVT VT = N0.getValueType();
4434 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4437 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4438 if (VT.isVector()) {
4439 SDValue FoldedVOp = SimplifyVBinOp(N);
4440 if (FoldedVOp.getNode()) return FoldedVOp;
4442 N1C = isConstOrConstSplat(N1);
4445 // fold (srl c1, c2) -> c1 >>u c2
4446 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4448 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4449 // fold (srl 0, x) -> 0
4450 if (N0C && N0C->isNullValue())
4452 // fold (srl x, c >= size(x)) -> undef
4453 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4454 return DAG.getUNDEF(VT);
4455 // fold (srl x, 0) -> x
4456 if (N1C && N1C->isNullValue())
4458 // if (srl x, c) is known to be zero, return 0
4459 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4460 APInt::getAllOnesValue(OpSizeInBits)))
4461 return DAG.getConstant(0, VT);
4463 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4464 if (N1C && N0.getOpcode() == ISD::SRL) {
4465 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4466 uint64_t c1 = N01C->getZExtValue();
4467 uint64_t c2 = N1C->getZExtValue();
4468 if (c1 + c2 >= OpSizeInBits)
4469 return DAG.getConstant(0, VT);
4470 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4471 DAG.getConstant(c1 + c2, N1.getValueType()));
4475 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4476 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4477 N0.getOperand(0).getOpcode() == ISD::SRL &&
4478 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4480 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4481 uint64_t c2 = N1C->getZExtValue();
4482 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4483 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4484 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4485 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4486 if (c1 + OpSizeInBits == InnerShiftSize) {
4487 if (c1 + c2 >= InnerShiftSize)
4488 return DAG.getConstant(0, VT);
4489 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4490 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4491 N0.getOperand(0)->getOperand(0),
4492 DAG.getConstant(c1 + c2, ShiftCountVT)));
4496 // fold (srl (shl x, c), c) -> (and x, cst2)
4497 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4498 unsigned BitSize = N0.getScalarValueSizeInBits();
4499 if (BitSize <= 64) {
4500 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4501 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4502 DAG.getConstant(~0ULL >> ShAmt, VT));
4506 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4507 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4508 // Shifting in all undef bits?
4509 EVT SmallVT = N0.getOperand(0).getValueType();
4510 unsigned BitSize = SmallVT.getScalarSizeInBits();
4511 if (N1C->getZExtValue() >= BitSize)
4512 return DAG.getUNDEF(VT);
4514 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4515 uint64_t ShiftAmt = N1C->getZExtValue();
4516 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4518 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4519 AddToWorklist(SmallShift.getNode());
4520 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4521 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4522 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4523 DAG.getConstant(Mask, VT));
4527 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4528 // bit, which is unmodified by sra.
4529 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4530 if (N0.getOpcode() == ISD::SRA)
4531 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4534 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4535 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4536 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4537 APInt KnownZero, KnownOne;
4538 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4540 // If any of the input bits are KnownOne, then the input couldn't be all
4541 // zeros, thus the result of the srl will always be zero.
4542 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4544 // If all of the bits input the to ctlz node are known to be zero, then
4545 // the result of the ctlz is "32" and the result of the shift is one.
4546 APInt UnknownBits = ~KnownZero;
4547 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4549 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4550 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4551 // Okay, we know that only that the single bit specified by UnknownBits
4552 // could be set on input to the CTLZ node. If this bit is set, the SRL
4553 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4554 // to an SRL/XOR pair, which is likely to simplify more.
4555 unsigned ShAmt = UnknownBits.countTrailingZeros();
4556 SDValue Op = N0.getOperand(0);
4559 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4560 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4561 AddToWorklist(Op.getNode());
4564 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4565 Op, DAG.getConstant(1, VT));
4569 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4570 if (N1.getOpcode() == ISD::TRUNCATE &&
4571 N1.getOperand(0).getOpcode() == ISD::AND) {
4572 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4573 if (NewOp1.getNode())
4574 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4577 // fold operands of srl based on knowledge that the low bits are not
4579 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4580 return SDValue(N, 0);
4583 SDValue NewSRL = visitShiftByConstant(N, N1C);
4584 if (NewSRL.getNode())
4588 // Attempt to convert a srl of a load into a narrower zero-extending load.
4589 SDValue NarrowLoad = ReduceLoadWidth(N);
4590 if (NarrowLoad.getNode())
4593 // Here is a common situation. We want to optimize:
4596 // %b = and i32 %a, 2
4597 // %c = srl i32 %b, 1
4598 // brcond i32 %c ...
4604 // %c = setcc eq %b, 0
4607 // However when after the source operand of SRL is optimized into AND, the SRL
4608 // itself may not be optimized further. Look for it and add the BRCOND into
4610 if (N->hasOneUse()) {
4611 SDNode *Use = *N->use_begin();
4612 if (Use->getOpcode() == ISD::BRCOND)
4614 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4615 // Also look pass the truncate.
4616 Use = *Use->use_begin();
4617 if (Use->getOpcode() == ISD::BRCOND)
4625 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4626 SDValue N0 = N->getOperand(0);
4627 EVT VT = N->getValueType(0);
4629 // fold (ctlz c1) -> c2
4630 if (isa<ConstantSDNode>(N0))
4631 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4635 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4636 SDValue N0 = N->getOperand(0);
4637 EVT VT = N->getValueType(0);
4639 // fold (ctlz_zero_undef c1) -> c2
4640 if (isa<ConstantSDNode>(N0))
4641 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4645 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4646 SDValue N0 = N->getOperand(0);
4647 EVT VT = N->getValueType(0);
4649 // fold (cttz c1) -> c2
4650 if (isa<ConstantSDNode>(N0))
4651 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4655 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4656 SDValue N0 = N->getOperand(0);
4657 EVT VT = N->getValueType(0);
4659 // fold (cttz_zero_undef c1) -> c2
4660 if (isa<ConstantSDNode>(N0))
4661 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4665 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4666 SDValue N0 = N->getOperand(0);
4667 EVT VT = N->getValueType(0);
4669 // fold (ctpop c1) -> c2
4670 if (isa<ConstantSDNode>(N0))
4671 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4676 /// \brief Generate Min/Max node
4677 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4678 SDValue True, SDValue False,
4679 ISD::CondCode CC, const TargetLowering &TLI,
4680 SelectionDAG &DAG) {
4681 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4691 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4692 if (TLI.isOperationLegal(Opcode, VT))
4693 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4702 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4703 if (TLI.isOperationLegal(Opcode, VT))
4704 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4712 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4713 SDValue N0 = N->getOperand(0);
4714 SDValue N1 = N->getOperand(1);
4715 SDValue N2 = N->getOperand(2);
4716 EVT VT = N->getValueType(0);
4717 EVT VT0 = N0.getValueType();
4719 // fold (select C, X, X) -> X
4722 // fold (select true, X, Y) -> X
4723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4724 if (N0C && !N0C->isNullValue())
4726 // fold (select false, X, Y) -> Y
4727 if (N0C && N0C->isNullValue())
4729 // fold (select C, 1, X) -> (or C, X)
4730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4731 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4732 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4733 // fold (select C, 0, 1) -> (xor C, 1)
4734 // We can't do this reliably if integer based booleans have different contents
4735 // to floating point based booleans. This is because we can't tell whether we
4736 // have an integer-based boolean or a floating-point-based boolean unless we
4737 // can find the SETCC that produced it and inspect its operands. This is
4738 // fairly easy if C is the SETCC node, but it can potentially be
4739 // undiscoverable (or not reasonably discoverable). For example, it could be
4740 // in another basic block or it could require searching a complicated
4742 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4743 if (VT.isInteger() &&
4744 (VT0 == MVT::i1 || (VT0.isInteger() &&
4745 TLI.getBooleanContents(false, false) ==
4746 TLI.getBooleanContents(false, true) &&
4747 TLI.getBooleanContents(false, false) ==
4748 TargetLowering::ZeroOrOneBooleanContent)) &&
4749 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4752 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4753 N0, DAG.getConstant(1, VT0));
4754 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4755 N0, DAG.getConstant(1, VT0));
4756 AddToWorklist(XORNode.getNode());
4758 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4759 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4761 // fold (select C, 0, X) -> (and (not C), X)
4762 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4763 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4764 AddToWorklist(NOTNode.getNode());
4765 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4767 // fold (select C, X, 1) -> (or (not C), X)
4768 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4769 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4770 AddToWorklist(NOTNode.getNode());
4771 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4773 // fold (select C, X, 0) -> (and C, X)
4774 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4775 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4776 // fold (select X, X, Y) -> (or X, Y)
4777 // fold (select X, 1, Y) -> (or X, Y)
4778 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4779 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4780 // fold (select X, Y, X) -> (and X, Y)
4781 // fold (select X, Y, 0) -> (and X, Y)
4782 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4783 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4785 // If we can fold this based on the true/false value, do so.
4786 if (SimplifySelectOps(N, N1, N2))
4787 return SDValue(N, 0); // Don't revisit N.
4789 // fold selects based on a setcc into other things, such as min/max/abs
4790 if (N0.getOpcode() == ISD::SETCC) {
4791 // select x, y (fcmp lt x, y) -> fminnum x, y
4792 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4794 // This is OK if we don't care about what happens if either operand is a
4798 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4799 // no signed zeros as well as no nans.
4800 const TargetOptions &Options = DAG.getTarget().Options;
4801 if (Options.UnsafeFPMath &&
4802 VT.isFloatingPoint() && N0.hasOneUse() &&
4803 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4804 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4807 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4808 N1, N2, CC, TLI, DAG);
4813 if ((!LegalOperations &&
4814 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4815 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4816 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4817 N0.getOperand(0), N0.getOperand(1),
4818 N1, N2, N0.getOperand(2));
4819 return SimplifySelect(SDLoc(N), N0, N1, N2);
4822 if (VT0 == MVT::i1) {
4823 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4824 // select (and Cond0, Cond1), X, Y
4825 // -> select Cond0, (select Cond1, X, Y), Y
4826 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4827 SDValue Cond0 = N0->getOperand(0);
4828 SDValue Cond1 = N0->getOperand(1);
4829 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4830 N1.getValueType(), Cond1, N1, N2);
4831 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4834 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4835 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4836 SDValue Cond0 = N0->getOperand(0);
4837 SDValue Cond1 = N0->getOperand(1);
4838 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4839 N1.getValueType(), Cond1, N1, N2);
4840 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4845 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4846 if (N1->getOpcode() == ISD::SELECT) {
4847 SDValue N1_0 = N1->getOperand(0);
4848 SDValue N1_1 = N1->getOperand(1);
4849 SDValue N1_2 = N1->getOperand(2);
4851 // Create the actual and node if we can generate good code for it.
4852 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4853 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4855 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4858 // Otherwise see if we can optimize the "and" to a better pattern.
4859 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4860 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4864 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4865 if (N2->getOpcode() == ISD::SELECT) {
4866 SDValue N2_0 = N2->getOperand(0);
4867 SDValue N2_1 = N2->getOperand(1);
4868 SDValue N2_2 = N2->getOperand(2);
4870 // Create the actual or node if we can generate good code for it.
4871 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4872 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4874 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4877 // Otherwise see if we can optimize to a better pattern.
4878 if (SDValue Combined = visitORLike(N0, N2_0, N))
4879 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4889 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4892 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4894 // Split the inputs.
4895 SDValue Lo, Hi, LL, LH, RL, RH;
4896 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4897 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4899 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4900 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4902 return std::make_pair(Lo, Hi);
4905 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4906 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4907 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4909 SDValue Cond = N->getOperand(0);
4910 SDValue LHS = N->getOperand(1);
4911 SDValue RHS = N->getOperand(2);
4912 EVT VT = N->getValueType(0);
4913 int NumElems = VT.getVectorNumElements();
4914 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4915 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4916 Cond.getOpcode() == ISD::BUILD_VECTOR);
4918 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4919 // binary ones here.
4920 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4923 // We're sure we have an even number of elements due to the
4924 // concat_vectors we have as arguments to vselect.
4925 // Skip BV elements until we find one that's not an UNDEF
4926 // After we find an UNDEF element, keep looping until we get to half the
4927 // length of the BV and see if all the non-undef nodes are the same.
4928 ConstantSDNode *BottomHalf = nullptr;
4929 for (int i = 0; i < NumElems / 2; ++i) {
4930 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4933 if (BottomHalf == nullptr)
4934 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4935 else if (Cond->getOperand(i).getNode() != BottomHalf)
4939 // Do the same for the second half of the BuildVector
4940 ConstantSDNode *TopHalf = nullptr;
4941 for (int i = NumElems / 2; i < NumElems; ++i) {
4942 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4945 if (TopHalf == nullptr)
4946 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4947 else if (Cond->getOperand(i).getNode() != TopHalf)
4951 assert(TopHalf && BottomHalf &&
4952 "One half of the selector was all UNDEFs and the other was all the "
4953 "same value. This should have been addressed before this function.");
4955 ISD::CONCAT_VECTORS, dl, VT,
4956 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4957 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4960 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4962 if (Level >= AfterLegalizeTypes)
4965 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4966 SDValue Mask = MST->getMask();
4967 SDValue Data = MST->getValue();
4970 // If the MSTORE data type requires splitting and the mask is provided by a
4971 // SETCC, then split both nodes and its operands before legalization. This
4972 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4973 // and enables future optimizations (e.g. min/max pattern matching on X86).
4974 if (Mask.getOpcode() == ISD::SETCC) {
4976 // Check if any splitting is required.
4977 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4978 TargetLowering::TypeSplitVector)
4981 SDValue MaskLo, MaskHi, Lo, Hi;
4982 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4985 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4987 SDValue Chain = MST->getChain();
4988 SDValue Ptr = MST->getBasePtr();
4990 EVT MemoryVT = MST->getMemoryVT();
4991 unsigned Alignment = MST->getOriginalAlignment();
4993 // if Alignment is equal to the vector size,
4994 // take the half of it for the second part
4995 unsigned SecondHalfAlignment =
4996 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4997 Alignment/2 : Alignment;
4999 EVT LoMemVT, HiMemVT;
5000 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5002 SDValue DataLo, DataHi;
5003 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5005 MachineMemOperand *MMO = DAG.getMachineFunction().
5006 getMachineMemOperand(MST->getPointerInfo(),
5007 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5008 Alignment, MST->getAAInfo(), MST->getRanges());
5010 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5011 MST->isTruncatingStore());
5013 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5014 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5015 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5017 MMO = DAG.getMachineFunction().
5018 getMachineMemOperand(MST->getPointerInfo(),
5019 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5020 SecondHalfAlignment, MST->getAAInfo(),
5023 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5024 MST->isTruncatingStore());
5026 AddToWorklist(Lo.getNode());
5027 AddToWorklist(Hi.getNode());
5029 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5034 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5036 if (Level >= AfterLegalizeTypes)
5039 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5040 SDValue Mask = MLD->getMask();
5043 // If the MLOAD result requires splitting and the mask is provided by a
5044 // SETCC, then split both nodes and its operands before legalization. This
5045 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5046 // and enables future optimizations (e.g. min/max pattern matching on X86).
5048 if (Mask.getOpcode() == ISD::SETCC) {
5049 EVT VT = N->getValueType(0);
5051 // Check if any splitting is required.
5052 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5053 TargetLowering::TypeSplitVector)
5056 SDValue MaskLo, MaskHi, Lo, Hi;
5057 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5059 SDValue Src0 = MLD->getSrc0();
5060 SDValue Src0Lo, Src0Hi;
5061 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5064 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5066 SDValue Chain = MLD->getChain();
5067 SDValue Ptr = MLD->getBasePtr();
5068 EVT MemoryVT = MLD->getMemoryVT();
5069 unsigned Alignment = MLD->getOriginalAlignment();
5071 // if Alignment is equal to the vector size,
5072 // take the half of it for the second part
5073 unsigned SecondHalfAlignment =
5074 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5075 Alignment/2 : Alignment;
5077 EVT LoMemVT, HiMemVT;
5078 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5080 MachineMemOperand *MMO = DAG.getMachineFunction().
5081 getMachineMemOperand(MLD->getPointerInfo(),
5082 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5083 Alignment, MLD->getAAInfo(), MLD->getRanges());
5085 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5088 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5089 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5090 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5092 MMO = DAG.getMachineFunction().
5093 getMachineMemOperand(MLD->getPointerInfo(),
5094 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5095 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5097 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5100 AddToWorklist(Lo.getNode());
5101 AddToWorklist(Hi.getNode());
5103 // Build a factor node to remember that this load is independent of the
5105 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5108 // Legalized the chain result - switch anything that used the old chain to
5110 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5112 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5114 SDValue RetOps[] = { LoadRes, Chain };
5115 return DAG.getMergeValues(RetOps, DL);
5120 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5121 SDValue N0 = N->getOperand(0);
5122 SDValue N1 = N->getOperand(1);
5123 SDValue N2 = N->getOperand(2);
5126 // Canonicalize integer abs.
5127 // vselect (setg[te] X, 0), X, -X ->
5128 // vselect (setgt X, -1), X, -X ->
5129 // vselect (setl[te] X, 0), -X, X ->
5130 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5131 if (N0.getOpcode() == ISD::SETCC) {
5132 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5133 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5135 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5137 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5138 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5139 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5140 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5141 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5142 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5143 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5146 EVT VT = LHS.getValueType();
5147 SDValue Shift = DAG.getNode(
5148 ISD::SRA, DL, VT, LHS,
5149 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5150 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5151 AddToWorklist(Shift.getNode());
5152 AddToWorklist(Add.getNode());
5153 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5157 // If the VSELECT result requires splitting and the mask is provided by a
5158 // SETCC, then split both nodes and its operands before legalization. This
5159 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5160 // and enables future optimizations (e.g. min/max pattern matching on X86).
5161 if (N0.getOpcode() == ISD::SETCC) {
5162 EVT VT = N->getValueType(0);
5164 // Check if any splitting is required.
5165 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5166 TargetLowering::TypeSplitVector)
5169 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5170 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5171 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5172 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5174 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5175 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5177 // Add the new VSELECT nodes to the work list in case they need to be split
5179 AddToWorklist(Lo.getNode());
5180 AddToWorklist(Hi.getNode());
5182 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5185 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5186 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5188 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5189 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5192 // The ConvertSelectToConcatVector function is assuming both the above
5193 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5195 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5196 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5197 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5198 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5206 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5207 SDValue N0 = N->getOperand(0);
5208 SDValue N1 = N->getOperand(1);
5209 SDValue N2 = N->getOperand(2);
5210 SDValue N3 = N->getOperand(3);
5211 SDValue N4 = N->getOperand(4);
5212 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5214 // fold select_cc lhs, rhs, x, x, cc -> x
5218 // Determine if the condition we're dealing with is constant
5219 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5220 N0, N1, CC, SDLoc(N), false);
5221 if (SCC.getNode()) {
5222 AddToWorklist(SCC.getNode());
5224 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5225 if (!SCCC->isNullValue())
5226 return N2; // cond always true -> true val
5228 return N3; // cond always false -> false val
5229 } else if (SCC->getOpcode() == ISD::UNDEF) {
5230 // When the condition is UNDEF, just return the first operand. This is
5231 // coherent the DAG creation, no setcc node is created in this case
5233 } else if (SCC.getOpcode() == ISD::SETCC) {
5234 // Fold to a simpler select_cc
5235 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5236 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5241 // If we can fold this based on the true/false value, do so.
5242 if (SimplifySelectOps(N, N2, N3))
5243 return SDValue(N, 0); // Don't revisit N.
5245 // fold select_cc into other things, such as min/max/abs
5246 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5249 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5250 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5251 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5255 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5256 // dag node into a ConstantSDNode or a build_vector of constants.
5257 // This function is called by the DAGCombiner when visiting sext/zext/aext
5258 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5259 // Vector extends are not folded if operations are legal; this is to
5260 // avoid introducing illegal build_vector dag nodes.
5261 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5262 SelectionDAG &DAG, bool LegalTypes,
5263 bool LegalOperations) {
5264 unsigned Opcode = N->getOpcode();
5265 SDValue N0 = N->getOperand(0);
5266 EVT VT = N->getValueType(0);
5268 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5269 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5271 // fold (sext c1) -> c1
5272 // fold (zext c1) -> c1
5273 // fold (aext c1) -> c1
5274 if (isa<ConstantSDNode>(N0))
5275 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5277 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5278 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5279 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5280 EVT SVT = VT.getScalarType();
5281 if (!(VT.isVector() &&
5282 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5283 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5286 // We can fold this node into a build_vector.
5287 unsigned VTBits = SVT.getSizeInBits();
5288 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5289 unsigned ShAmt = VTBits - EVTBits;
5290 SmallVector<SDValue, 8> Elts;
5291 unsigned NumElts = N0->getNumOperands();
5294 for (unsigned i=0; i != NumElts; ++i) {
5295 SDValue Op = N0->getOperand(i);
5296 if (Op->getOpcode() == ISD::UNDEF) {
5297 Elts.push_back(DAG.getUNDEF(SVT));
5301 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5302 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5303 if (Opcode == ISD::SIGN_EXTEND)
5304 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5307 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5311 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5314 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5315 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5316 // transformation. Returns true if extension are possible and the above
5317 // mentioned transformation is profitable.
5318 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5320 SmallVectorImpl<SDNode *> &ExtendNodes,
5321 const TargetLowering &TLI) {
5322 bool HasCopyToRegUses = false;
5323 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5324 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5325 UE = N0.getNode()->use_end();
5330 if (UI.getUse().getResNo() != N0.getResNo())
5332 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5333 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5334 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5335 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5336 // Sign bits will be lost after a zext.
5339 for (unsigned i = 0; i != 2; ++i) {
5340 SDValue UseOp = User->getOperand(i);
5343 if (!isa<ConstantSDNode>(UseOp))
5348 ExtendNodes.push_back(User);
5351 // If truncates aren't free and there are users we can't
5352 // extend, it isn't worthwhile.
5355 // Remember if this value is live-out.
5356 if (User->getOpcode() == ISD::CopyToReg)
5357 HasCopyToRegUses = true;
5360 if (HasCopyToRegUses) {
5361 bool BothLiveOut = false;
5362 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5364 SDUse &Use = UI.getUse();
5365 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5371 // Both unextended and extended values are live out. There had better be
5372 // a good reason for the transformation.
5373 return ExtendNodes.size();
5378 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5379 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5380 ISD::NodeType ExtType) {
5381 // Extend SetCC uses if necessary.
5382 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5383 SDNode *SetCC = SetCCs[i];
5384 SmallVector<SDValue, 4> Ops;
5386 for (unsigned j = 0; j != 2; ++j) {
5387 SDValue SOp = SetCC->getOperand(j);
5389 Ops.push_back(ExtLoad);
5391 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5394 Ops.push_back(SetCC->getOperand(2));
5395 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5399 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5400 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5401 SDValue N0 = N->getOperand(0);
5402 EVT DstVT = N->getValueType(0);
5403 EVT SrcVT = N0.getValueType();
5405 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5406 N->getOpcode() == ISD::ZERO_EXTEND) &&
5407 "Unexpected node type (not an extend)!");
5409 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5410 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5411 // (v8i32 (sext (v8i16 (load x))))
5413 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5414 // (v4i32 (sextload (x + 16)))))
5415 // Where uses of the original load, i.e.:
5417 // are replaced with:
5419 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5420 // (v4i32 (sextload (x + 16)))))))
5422 // This combine is only applicable to illegal, but splittable, vectors.
5423 // All legal types, and illegal non-vector types, are handled elsewhere.
5424 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5426 if (N0->getOpcode() != ISD::LOAD)
5429 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5431 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5432 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5433 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5436 SmallVector<SDNode *, 4> SetCCs;
5437 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5440 ISD::LoadExtType ExtType =
5441 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5443 // Try to split the vector types to get down to legal types.
5444 EVT SplitSrcVT = SrcVT;
5445 EVT SplitDstVT = DstVT;
5446 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5447 SplitSrcVT.getVectorNumElements() > 1) {
5448 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5449 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5452 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5456 const unsigned NumSplits =
5457 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5458 const unsigned Stride = SplitSrcVT.getStoreSize();
5459 SmallVector<SDValue, 4> Loads;
5460 SmallVector<SDValue, 4> Chains;
5462 SDValue BasePtr = LN0->getBasePtr();
5463 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5464 const unsigned Offset = Idx * Stride;
5465 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5467 SDValue SplitLoad = DAG.getExtLoad(
5468 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5469 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5470 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5471 Align, LN0->getAAInfo());
5473 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5474 DAG.getConstant(Stride, BasePtr.getValueType()));
5476 Loads.push_back(SplitLoad.getValue(0));
5477 Chains.push_back(SplitLoad.getValue(1));
5480 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5481 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5483 CombineTo(N, NewValue);
5485 // Replace uses of the original load (before extension)
5486 // with a truncate of the concatenated sextloaded vectors.
5488 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5489 CombineTo(N0.getNode(), Trunc, NewChain);
5490 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5491 (ISD::NodeType)N->getOpcode());
5492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5495 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5496 SDValue N0 = N->getOperand(0);
5497 EVT VT = N->getValueType(0);
5499 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5501 return SDValue(Res, 0);
5503 // fold (sext (sext x)) -> (sext x)
5504 // fold (sext (aext x)) -> (sext x)
5505 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5506 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5509 if (N0.getOpcode() == ISD::TRUNCATE) {
5510 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5511 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5512 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5513 if (NarrowLoad.getNode()) {
5514 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5515 if (NarrowLoad.getNode() != N0.getNode()) {
5516 CombineTo(N0.getNode(), NarrowLoad);
5517 // CombineTo deleted the truncate, if needed, but not what's under it.
5520 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5523 // See if the value being truncated is already sign extended. If so, just
5524 // eliminate the trunc/sext pair.
5525 SDValue Op = N0.getOperand(0);
5526 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5527 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5528 unsigned DestBits = VT.getScalarType().getSizeInBits();
5529 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5531 if (OpBits == DestBits) {
5532 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5533 // bits, it is already ready.
5534 if (NumSignBits > DestBits-MidBits)
5536 } else if (OpBits < DestBits) {
5537 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5538 // bits, just sext from i32.
5539 if (NumSignBits > OpBits-MidBits)
5540 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5542 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5543 // bits, just truncate to i32.
5544 if (NumSignBits > OpBits-MidBits)
5545 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5548 // fold (sext (truncate x)) -> (sextinreg x).
5549 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5550 N0.getValueType())) {
5551 if (OpBits < DestBits)
5552 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5553 else if (OpBits > DestBits)
5554 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5555 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5556 DAG.getValueType(N0.getValueType()));
5560 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5561 // Only generate vector extloads when 1) they're legal, and 2) they are
5562 // deemed desirable by the target.
5563 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5564 ((!LegalOperations && !VT.isVector() &&
5565 !cast<LoadSDNode>(N0)->isVolatile()) ||
5566 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5567 bool DoXform = true;
5568 SmallVector<SDNode*, 4> SetCCs;
5569 if (!N0.hasOneUse())
5570 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5572 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5574 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5575 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5577 LN0->getBasePtr(), N0.getValueType(),
5578 LN0->getMemOperand());
5579 CombineTo(N, ExtLoad);
5580 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5581 N0.getValueType(), ExtLoad);
5582 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5583 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5585 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5589 // fold (sext (load x)) to multiple smaller sextloads.
5590 // Only on illegal but splittable vectors.
5591 if (SDValue ExtLoad = CombineExtLoad(N))
5594 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5595 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5596 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5597 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5598 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5599 EVT MemVT = LN0->getMemoryVT();
5600 if ((!LegalOperations && !LN0->isVolatile()) ||
5601 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5602 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5604 LN0->getBasePtr(), MemVT,
5605 LN0->getMemOperand());
5606 CombineTo(N, ExtLoad);
5607 CombineTo(N0.getNode(),
5608 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5609 N0.getValueType(), ExtLoad),
5610 ExtLoad.getValue(1));
5611 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5615 // fold (sext (and/or/xor (load x), cst)) ->
5616 // (and/or/xor (sextload x), (sext cst))
5617 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5618 N0.getOpcode() == ISD::XOR) &&
5619 isa<LoadSDNode>(N0.getOperand(0)) &&
5620 N0.getOperand(1).getOpcode() == ISD::Constant &&
5621 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5622 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5623 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5624 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5625 bool DoXform = true;
5626 SmallVector<SDNode*, 4> SetCCs;
5627 if (!N0.hasOneUse())
5628 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5631 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5632 LN0->getChain(), LN0->getBasePtr(),
5634 LN0->getMemOperand());
5635 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5636 Mask = Mask.sext(VT.getSizeInBits());
5637 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5638 ExtLoad, DAG.getConstant(Mask, VT));
5639 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5640 SDLoc(N0.getOperand(0)),
5641 N0.getOperand(0).getValueType(), ExtLoad);
5643 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5644 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5646 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5651 if (N0.getOpcode() == ISD::SETCC) {
5652 EVT N0VT = N0.getOperand(0).getValueType();
5653 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5654 // Only do this before legalize for now.
5655 if (VT.isVector() && !LegalOperations &&
5656 TLI.getBooleanContents(N0VT) ==
5657 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5658 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5659 // of the same size as the compared operands. Only optimize sext(setcc())
5660 // if this is the case.
5661 EVT SVT = getSetCCResultType(N0VT);
5663 // We know that the # elements of the results is the same as the
5664 // # elements of the compare (and the # elements of the compare result
5665 // for that matter). Check to see that they are the same size. If so,
5666 // we know that the element size of the sext'd result matches the
5667 // element size of the compare operands.
5668 if (VT.getSizeInBits() == SVT.getSizeInBits())
5669 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5671 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5673 // If the desired elements are smaller or larger than the source
5674 // elements we can use a matching integer vector type and then
5675 // truncate/sign extend
5676 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5677 if (SVT == MatchingVectorType) {
5678 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5679 N0.getOperand(0), N0.getOperand(1),
5680 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5681 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5685 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5686 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5688 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5690 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5691 NegOne, DAG.getConstant(0, VT),
5692 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5693 if (SCC.getNode()) return SCC;
5695 if (!VT.isVector()) {
5696 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5697 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5699 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5700 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5701 N0.getOperand(0), N0.getOperand(1), CC);
5702 return DAG.getSelect(DL, VT, SetCC,
5703 NegOne, DAG.getConstant(0, VT));
5708 // fold (sext x) -> (zext x) if the sign bit is known zero.
5709 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5710 DAG.SignBitIsZero(N0))
5711 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5716 // isTruncateOf - If N is a truncate of some other value, return true, record
5717 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5718 // This function computes KnownZero to avoid a duplicated call to
5719 // computeKnownBits in the caller.
5720 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5723 if (N->getOpcode() == ISD::TRUNCATE) {
5724 Op = N->getOperand(0);
5725 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5729 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5730 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5733 SDValue Op0 = N->getOperand(0);
5734 SDValue Op1 = N->getOperand(1);
5735 assert(Op0.getValueType() == Op1.getValueType());
5737 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5738 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5739 if (COp0 && COp0->isNullValue())
5741 else if (COp1 && COp1->isNullValue())
5746 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5748 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5754 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5755 SDValue N0 = N->getOperand(0);
5756 EVT VT = N->getValueType(0);
5758 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5760 return SDValue(Res, 0);
5762 // fold (zext (zext x)) -> (zext x)
5763 // fold (zext (aext x)) -> (zext x)
5764 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5765 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5768 // fold (zext (truncate x)) -> (zext x) or
5769 // (zext (truncate x)) -> (truncate x)
5770 // This is valid when the truncated bits of x are already zero.
5771 // FIXME: We should extend this to work for vectors too.
5774 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5775 APInt TruncatedBits =
5776 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5777 APInt(Op.getValueSizeInBits(), 0) :
5778 APInt::getBitsSet(Op.getValueSizeInBits(),
5779 N0.getValueSizeInBits(),
5780 std::min(Op.getValueSizeInBits(),
5781 VT.getSizeInBits()));
5782 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5783 if (VT.bitsGT(Op.getValueType()))
5784 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5785 if (VT.bitsLT(Op.getValueType()))
5786 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5792 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5793 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5794 if (N0.getOpcode() == ISD::TRUNCATE) {
5795 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5796 if (NarrowLoad.getNode()) {
5797 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5798 if (NarrowLoad.getNode() != N0.getNode()) {
5799 CombineTo(N0.getNode(), NarrowLoad);
5800 // CombineTo deleted the truncate, if needed, but not what's under it.
5803 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5807 // fold (zext (truncate x)) -> (and x, mask)
5808 if (N0.getOpcode() == ISD::TRUNCATE &&
5809 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5811 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5812 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5813 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5814 if (NarrowLoad.getNode()) {
5815 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5816 if (NarrowLoad.getNode() != N0.getNode()) {
5817 CombineTo(N0.getNode(), NarrowLoad);
5818 // CombineTo deleted the truncate, if needed, but not what's under it.
5821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5824 SDValue Op = N0.getOperand(0);
5825 if (Op.getValueType().bitsLT(VT)) {
5826 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5827 AddToWorklist(Op.getNode());
5828 } else if (Op.getValueType().bitsGT(VT)) {
5829 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5830 AddToWorklist(Op.getNode());
5832 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5833 N0.getValueType().getScalarType());
5836 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5837 // if either of the casts is not free.
5838 if (N0.getOpcode() == ISD::AND &&
5839 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5840 N0.getOperand(1).getOpcode() == ISD::Constant &&
5841 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5842 N0.getValueType()) ||
5843 !TLI.isZExtFree(N0.getValueType(), VT))) {
5844 SDValue X = N0.getOperand(0).getOperand(0);
5845 if (X.getValueType().bitsLT(VT)) {
5846 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5847 } else if (X.getValueType().bitsGT(VT)) {
5848 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5850 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5851 Mask = Mask.zext(VT.getSizeInBits());
5852 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5853 X, DAG.getConstant(Mask, VT));
5856 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5857 // Only generate vector extloads when 1) they're legal, and 2) they are
5858 // deemed desirable by the target.
5859 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5860 ((!LegalOperations && !VT.isVector() &&
5861 !cast<LoadSDNode>(N0)->isVolatile()) ||
5862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5863 bool DoXform = true;
5864 SmallVector<SDNode*, 4> SetCCs;
5865 if (!N0.hasOneUse())
5866 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5868 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5870 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5871 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5873 LN0->getBasePtr(), N0.getValueType(),
5874 LN0->getMemOperand());
5875 CombineTo(N, ExtLoad);
5876 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5877 N0.getValueType(), ExtLoad);
5878 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5880 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5886 // fold (zext (load x)) to multiple smaller zextloads.
5887 // Only on illegal but splittable vectors.
5888 if (SDValue ExtLoad = CombineExtLoad(N))
5891 // fold (zext (and/or/xor (load x), cst)) ->
5892 // (and/or/xor (zextload x), (zext cst))
5893 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5894 N0.getOpcode() == ISD::XOR) &&
5895 isa<LoadSDNode>(N0.getOperand(0)) &&
5896 N0.getOperand(1).getOpcode() == ISD::Constant &&
5897 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5898 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5900 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5901 bool DoXform = true;
5902 SmallVector<SDNode*, 4> SetCCs;
5903 if (!N0.hasOneUse())
5904 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5907 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5908 LN0->getChain(), LN0->getBasePtr(),
5910 LN0->getMemOperand());
5911 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5912 Mask = Mask.zext(VT.getSizeInBits());
5913 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5914 ExtLoad, DAG.getConstant(Mask, VT));
5915 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5916 SDLoc(N0.getOperand(0)),
5917 N0.getOperand(0).getValueType(), ExtLoad);
5919 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5920 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5922 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5927 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5928 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5929 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5930 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5931 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5932 EVT MemVT = LN0->getMemoryVT();
5933 if ((!LegalOperations && !LN0->isVolatile()) ||
5934 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5935 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5937 LN0->getBasePtr(), MemVT,
5938 LN0->getMemOperand());
5939 CombineTo(N, ExtLoad);
5940 CombineTo(N0.getNode(),
5941 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5943 ExtLoad.getValue(1));
5944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5948 if (N0.getOpcode() == ISD::SETCC) {
5949 if (!LegalOperations && VT.isVector() &&
5950 N0.getValueType().getVectorElementType() == MVT::i1) {
5951 EVT N0VT = N0.getOperand(0).getValueType();
5952 if (getSetCCResultType(N0VT) == N0.getValueType())
5955 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5956 // Only do this before legalize for now.
5957 EVT EltVT = VT.getVectorElementType();
5958 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5959 DAG.getConstant(1, EltVT));
5960 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5961 // We know that the # elements of the results is the same as the
5962 // # elements of the compare (and the # elements of the compare result
5963 // for that matter). Check to see that they are the same size. If so,
5964 // we know that the element size of the sext'd result matches the
5965 // element size of the compare operands.
5966 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5967 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5969 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5970 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5973 // If the desired elements are smaller or larger than the source
5974 // elements we can use a matching integer vector type and then
5975 // truncate/sign extend
5976 EVT MatchingElementType =
5977 EVT::getIntegerVT(*DAG.getContext(),
5978 N0VT.getScalarType().getSizeInBits());
5979 EVT MatchingVectorType =
5980 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5981 N0VT.getVectorNumElements());
5983 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5985 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5986 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5987 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5988 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5991 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5993 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5994 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5995 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5996 if (SCC.getNode()) return SCC;
5999 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6000 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6001 isa<ConstantSDNode>(N0.getOperand(1)) &&
6002 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6004 SDValue ShAmt = N0.getOperand(1);
6005 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6006 if (N0.getOpcode() == ISD::SHL) {
6007 SDValue InnerZExt = N0.getOperand(0);
6008 // If the original shl may be shifting out bits, do not perform this
6010 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6011 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6012 if (ShAmtVal > KnownZeroBits)
6018 // Ensure that the shift amount is wide enough for the shifted value.
6019 if (VT.getSizeInBits() >= 256)
6020 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6022 return DAG.getNode(N0.getOpcode(), DL, VT,
6023 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6030 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6031 SDValue N0 = N->getOperand(0);
6032 EVT VT = N->getValueType(0);
6034 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6036 return SDValue(Res, 0);
6038 // fold (aext (aext x)) -> (aext x)
6039 // fold (aext (zext x)) -> (zext x)
6040 // fold (aext (sext x)) -> (sext x)
6041 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6042 N0.getOpcode() == ISD::ZERO_EXTEND ||
6043 N0.getOpcode() == ISD::SIGN_EXTEND)
6044 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6046 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6047 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6048 if (N0.getOpcode() == ISD::TRUNCATE) {
6049 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6050 if (NarrowLoad.getNode()) {
6051 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6052 if (NarrowLoad.getNode() != N0.getNode()) {
6053 CombineTo(N0.getNode(), NarrowLoad);
6054 // CombineTo deleted the truncate, if needed, but not what's under it.
6057 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6061 // fold (aext (truncate x))
6062 if (N0.getOpcode() == ISD::TRUNCATE) {
6063 SDValue TruncOp = N0.getOperand(0);
6064 if (TruncOp.getValueType() == VT)
6065 return TruncOp; // x iff x size == zext size.
6066 if (TruncOp.getValueType().bitsGT(VT))
6067 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6068 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6071 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6072 // if the trunc is not free.
6073 if (N0.getOpcode() == ISD::AND &&
6074 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6075 N0.getOperand(1).getOpcode() == ISD::Constant &&
6076 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6077 N0.getValueType())) {
6078 SDValue X = N0.getOperand(0).getOperand(0);
6079 if (X.getValueType().bitsLT(VT)) {
6080 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6081 } else if (X.getValueType().bitsGT(VT)) {
6082 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6084 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6085 Mask = Mask.zext(VT.getSizeInBits());
6086 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6087 X, DAG.getConstant(Mask, VT));
6090 // fold (aext (load x)) -> (aext (truncate (extload x)))
6091 // None of the supported targets knows how to perform load and any_ext
6092 // on vectors in one instruction. We only perform this transformation on
6094 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6095 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6096 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6097 bool DoXform = true;
6098 SmallVector<SDNode*, 4> SetCCs;
6099 if (!N0.hasOneUse())
6100 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6102 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6103 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6105 LN0->getBasePtr(), N0.getValueType(),
6106 LN0->getMemOperand());
6107 CombineTo(N, ExtLoad);
6108 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6109 N0.getValueType(), ExtLoad);
6110 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6111 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6117 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6118 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6119 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6120 if (N0.getOpcode() == ISD::LOAD &&
6121 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6123 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6124 ISD::LoadExtType ExtType = LN0->getExtensionType();
6125 EVT MemVT = LN0->getMemoryVT();
6126 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6127 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6128 VT, LN0->getChain(), LN0->getBasePtr(),
6129 MemVT, LN0->getMemOperand());
6130 CombineTo(N, ExtLoad);
6131 CombineTo(N0.getNode(),
6132 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6133 N0.getValueType(), ExtLoad),
6134 ExtLoad.getValue(1));
6135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6139 if (N0.getOpcode() == ISD::SETCC) {
6141 // aext(setcc) -> vsetcc
6142 // aext(setcc) -> truncate(vsetcc)
6143 // aext(setcc) -> aext(vsetcc)
6144 // Only do this before legalize for now.
6145 if (VT.isVector() && !LegalOperations) {
6146 EVT N0VT = N0.getOperand(0).getValueType();
6147 // We know that the # elements of the results is the same as the
6148 // # elements of the compare (and the # elements of the compare result
6149 // for that matter). Check to see that they are the same size. If so,
6150 // we know that the element size of the sext'd result matches the
6151 // element size of the compare operands.
6152 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6153 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6155 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6156 // If the desired elements are smaller or larger than the source
6157 // elements we can use a matching integer vector type and then
6158 // truncate/any extend
6160 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6162 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6164 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6165 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6169 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6171 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6172 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6173 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6181 /// See if the specified operand can be simplified with the knowledge that only
6182 /// the bits specified by Mask are used. If so, return the simpler operand,
6183 /// otherwise return a null SDValue.
6184 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6185 switch (V.getOpcode()) {
6187 case ISD::Constant: {
6188 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6189 assert(CV && "Const value should be ConstSDNode.");
6190 const APInt &CVal = CV->getAPIntValue();
6191 APInt NewVal = CVal & Mask;
6193 return DAG.getConstant(NewVal, V.getValueType());
6198 // If the LHS or RHS don't contribute bits to the or, drop them.
6199 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6200 return V.getOperand(1);
6201 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6202 return V.getOperand(0);
6205 // Only look at single-use SRLs.
6206 if (!V.getNode()->hasOneUse())
6208 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6209 // See if we can recursively simplify the LHS.
6210 unsigned Amt = RHSC->getZExtValue();
6212 // Watch out for shift count overflow though.
6213 if (Amt >= Mask.getBitWidth()) break;
6214 APInt NewMask = Mask << Amt;
6215 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6216 if (SimplifyLHS.getNode())
6217 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6218 SimplifyLHS, V.getOperand(1));
6224 /// If the result of a wider load is shifted to right of N bits and then
6225 /// truncated to a narrower type and where N is a multiple of number of bits of
6226 /// the narrower type, transform it to a narrower load from address + N / num of
6227 /// bits of new type. If the result is to be extended, also fold the extension
6228 /// to form a extending load.
6229 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6230 unsigned Opc = N->getOpcode();
6232 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6233 SDValue N0 = N->getOperand(0);
6234 EVT VT = N->getValueType(0);
6237 // This transformation isn't valid for vector loads.
6241 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6243 if (Opc == ISD::SIGN_EXTEND_INREG) {
6244 ExtType = ISD::SEXTLOAD;
6245 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6246 } else if (Opc == ISD::SRL) {
6247 // Another special-case: SRL is basically zero-extending a narrower value.
6248 ExtType = ISD::ZEXTLOAD;
6250 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6251 if (!N01) return SDValue();
6252 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6253 VT.getSizeInBits() - N01->getZExtValue());
6255 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6258 unsigned EVTBits = ExtVT.getSizeInBits();
6260 // Do not generate loads of non-round integer types since these can
6261 // be expensive (and would be wrong if the type is not byte sized).
6262 if (!ExtVT.isRound())
6266 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6267 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6268 ShAmt = N01->getZExtValue();
6269 // Is the shift amount a multiple of size of VT?
6270 if ((ShAmt & (EVTBits-1)) == 0) {
6271 N0 = N0.getOperand(0);
6272 // Is the load width a multiple of size of VT?
6273 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6277 // At this point, we must have a load or else we can't do the transform.
6278 if (!isa<LoadSDNode>(N0)) return SDValue();
6280 // Because a SRL must be assumed to *need* to zero-extend the high bits
6281 // (as opposed to anyext the high bits), we can't combine the zextload
6282 // lowering of SRL and an sextload.
6283 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6286 // If the shift amount is larger than the input type then we're not
6287 // accessing any of the loaded bytes. If the load was a zextload/extload
6288 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6289 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6294 // If the load is shifted left (and the result isn't shifted back right),
6295 // we can fold the truncate through the shift.
6296 unsigned ShLeftAmt = 0;
6297 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6298 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6299 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6300 ShLeftAmt = N01->getZExtValue();
6301 N0 = N0.getOperand(0);
6305 // If we haven't found a load, we can't narrow it. Don't transform one with
6306 // multiple uses, this would require adding a new load.
6307 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6310 // Don't change the width of a volatile load.
6311 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6312 if (LN0->isVolatile())
6315 // Verify that we are actually reducing a load width here.
6316 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6319 // For the transform to be legal, the load must produce only two values
6320 // (the value loaded and the chain). Don't transform a pre-increment
6321 // load, for example, which produces an extra value. Otherwise the
6322 // transformation is not equivalent, and the downstream logic to replace
6323 // uses gets things wrong.
6324 if (LN0->getNumValues() > 2)
6327 // If the load that we're shrinking is an extload and we're not just
6328 // discarding the extension we can't simply shrink the load. Bail.
6329 // TODO: It would be possible to merge the extensions in some cases.
6330 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6331 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6334 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6337 EVT PtrType = N0.getOperand(1).getValueType();
6339 if (PtrType == MVT::Untyped || PtrType.isExtended())
6340 // It's not possible to generate a constant of extended or untyped type.
6343 // For big endian targets, we need to adjust the offset to the pointer to
6344 // load the correct bytes.
6345 if (TLI.isBigEndian()) {
6346 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6347 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6348 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6351 uint64_t PtrOff = ShAmt / 8;
6352 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6353 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6354 PtrType, LN0->getBasePtr(),
6355 DAG.getConstant(PtrOff, PtrType));
6356 AddToWorklist(NewPtr.getNode());
6359 if (ExtType == ISD::NON_EXTLOAD)
6360 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6361 LN0->getPointerInfo().getWithOffset(PtrOff),
6362 LN0->isVolatile(), LN0->isNonTemporal(),
6363 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6365 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6366 LN0->getPointerInfo().getWithOffset(PtrOff),
6367 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6368 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6370 // Replace the old load's chain with the new load's chain.
6371 WorklistRemover DeadNodes(*this);
6372 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6374 // Shift the result left, if we've swallowed a left shift.
6375 SDValue Result = Load;
6376 if (ShLeftAmt != 0) {
6377 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6378 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6380 // If the shift amount is as large as the result size (but, presumably,
6381 // no larger than the source) then the useful bits of the result are
6382 // zero; we can't simply return the shortened shift, because the result
6383 // of that operation is undefined.
6384 if (ShLeftAmt >= VT.getSizeInBits())
6385 Result = DAG.getConstant(0, VT);
6387 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6388 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6391 // Return the new loaded value.
6395 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6396 SDValue N0 = N->getOperand(0);
6397 SDValue N1 = N->getOperand(1);
6398 EVT VT = N->getValueType(0);
6399 EVT EVT = cast<VTSDNode>(N1)->getVT();
6400 unsigned VTBits = VT.getScalarType().getSizeInBits();
6401 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6403 // fold (sext_in_reg c1) -> c1
6404 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6405 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6407 // If the input is already sign extended, just drop the extension.
6408 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6411 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6412 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6413 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6414 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6415 N0.getOperand(0), N1);
6417 // fold (sext_in_reg (sext x)) -> (sext x)
6418 // fold (sext_in_reg (aext x)) -> (sext x)
6419 // if x is small enough.
6420 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6421 SDValue N00 = N0.getOperand(0);
6422 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6423 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6424 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6427 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6428 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6429 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6431 // fold operands of sext_in_reg based on knowledge that the top bits are not
6433 if (SimplifyDemandedBits(SDValue(N, 0)))
6434 return SDValue(N, 0);
6436 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6437 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6438 SDValue NarrowLoad = ReduceLoadWidth(N);
6439 if (NarrowLoad.getNode())
6442 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6443 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6444 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6445 if (N0.getOpcode() == ISD::SRL) {
6446 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6447 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6448 // We can turn this into an SRA iff the input to the SRL is already sign
6450 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6451 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6452 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6453 N0.getOperand(0), N0.getOperand(1));
6457 // fold (sext_inreg (extload x)) -> (sextload x)
6458 if (ISD::isEXTLoad(N0.getNode()) &&
6459 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6460 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6461 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6462 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6463 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6464 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6466 LN0->getBasePtr(), EVT,
6467 LN0->getMemOperand());
6468 CombineTo(N, ExtLoad);
6469 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6470 AddToWorklist(ExtLoad.getNode());
6471 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6473 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6474 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6476 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6477 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6478 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6479 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6480 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6482 LN0->getBasePtr(), EVT,
6483 LN0->getMemOperand());
6484 CombineTo(N, ExtLoad);
6485 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6486 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6489 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6490 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6491 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6492 N0.getOperand(1), false);
6493 if (BSwap.getNode())
6494 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6498 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6499 // into a build_vector.
6500 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6501 SmallVector<SDValue, 8> Elts;
6502 unsigned NumElts = N0->getNumOperands();
6503 unsigned ShAmt = VTBits - EVTBits;
6505 for (unsigned i = 0; i != NumElts; ++i) {
6506 SDValue Op = N0->getOperand(i);
6507 if (Op->getOpcode() == ISD::UNDEF) {
6512 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6513 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6514 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6515 Op.getValueType()));
6518 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6524 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6525 SDValue N0 = N->getOperand(0);
6526 EVT VT = N->getValueType(0);
6527 bool isLE = TLI.isLittleEndian();
6530 if (N0.getValueType() == N->getValueType(0))
6532 // fold (truncate c1) -> c1
6533 if (isa<ConstantSDNode>(N0))
6534 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6535 // fold (truncate (truncate x)) -> (truncate x)
6536 if (N0.getOpcode() == ISD::TRUNCATE)
6537 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6538 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6539 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6540 N0.getOpcode() == ISD::SIGN_EXTEND ||
6541 N0.getOpcode() == ISD::ANY_EXTEND) {
6542 if (N0.getOperand(0).getValueType().bitsLT(VT))
6543 // if the source is smaller than the dest, we still need an extend
6544 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6546 if (N0.getOperand(0).getValueType().bitsGT(VT))
6547 // if the source is larger than the dest, than we just need the truncate
6548 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6549 // if the source and dest are the same type, we can drop both the extend
6550 // and the truncate.
6551 return N0.getOperand(0);
6554 // Fold extract-and-trunc into a narrow extract. For example:
6555 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6556 // i32 y = TRUNCATE(i64 x)
6558 // v16i8 b = BITCAST (v2i64 val)
6559 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6561 // Note: We only run this optimization after type legalization (which often
6562 // creates this pattern) and before operation legalization after which
6563 // we need to be more careful about the vector instructions that we generate.
6564 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6565 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6567 EVT VecTy = N0.getOperand(0).getValueType();
6568 EVT ExTy = N0.getValueType();
6569 EVT TrTy = N->getValueType(0);
6571 unsigned NumElem = VecTy.getVectorNumElements();
6572 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6574 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6575 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6577 SDValue EltNo = N0->getOperand(1);
6578 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6579 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6580 EVT IndexTy = TLI.getVectorIdxTy();
6581 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6583 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6584 NVT, N0.getOperand(0));
6586 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6588 DAG.getConstant(Index, IndexTy));
6592 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6593 if (N0.getOpcode() == ISD::SELECT) {
6594 EVT SrcVT = N0.getValueType();
6595 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6596 TLI.isTruncateFree(SrcVT, VT)) {
6598 SDValue Cond = N0.getOperand(0);
6599 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6600 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6601 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6605 // Fold a series of buildvector, bitcast, and truncate if possible.
6607 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6608 // (2xi32 (buildvector x, y)).
6609 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6610 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6611 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6612 N0.getOperand(0).hasOneUse()) {
6614 SDValue BuildVect = N0.getOperand(0);
6615 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6616 EVT TruncVecEltTy = VT.getVectorElementType();
6618 // Check that the element types match.
6619 if (BuildVectEltTy == TruncVecEltTy) {
6620 // Now we only need to compute the offset of the truncated elements.
6621 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6622 unsigned TruncVecNumElts = VT.getVectorNumElements();
6623 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6625 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6626 "Invalid number of elements");
6628 SmallVector<SDValue, 8> Opnds;
6629 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6630 Opnds.push_back(BuildVect.getOperand(i));
6632 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6636 // See if we can simplify the input to this truncate through knowledge that
6637 // only the low bits are being used.
6638 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6639 // Currently we only perform this optimization on scalars because vectors
6640 // may have different active low bits.
6641 if (!VT.isVector()) {
6643 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6644 VT.getSizeInBits()));
6645 if (Shorter.getNode())
6646 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6648 // fold (truncate (load x)) -> (smaller load x)
6649 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6650 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6651 SDValue Reduced = ReduceLoadWidth(N);
6652 if (Reduced.getNode())
6654 // Handle the case where the load remains an extending load even
6655 // after truncation.
6656 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6657 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6658 if (!LN0->isVolatile() &&
6659 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6660 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6661 VT, LN0->getChain(), LN0->getBasePtr(),
6663 LN0->getMemOperand());
6664 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6669 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6670 // where ... are all 'undef'.
6671 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6672 SmallVector<EVT, 8> VTs;
6675 unsigned NumDefs = 0;
6677 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6678 SDValue X = N0.getOperand(i);
6679 if (X.getOpcode() != ISD::UNDEF) {
6684 // Stop if more than one members are non-undef.
6687 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6688 VT.getVectorElementType(),
6689 X.getValueType().getVectorNumElements()));
6693 return DAG.getUNDEF(VT);
6696 assert(V.getNode() && "The single defined operand is empty!");
6697 SmallVector<SDValue, 8> Opnds;
6698 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6700 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6703 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6704 AddToWorklist(NV.getNode());
6705 Opnds.push_back(NV);
6707 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6711 // Simplify the operands using demanded-bits information.
6712 if (!VT.isVector() &&
6713 SimplifyDemandedBits(SDValue(N, 0)))
6714 return SDValue(N, 0);
6719 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6720 SDValue Elt = N->getOperand(i);
6721 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6722 return Elt.getNode();
6723 return Elt.getOperand(Elt.getResNo()).getNode();
6726 /// build_pair (load, load) -> load
6727 /// if load locations are consecutive.
6728 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6729 assert(N->getOpcode() == ISD::BUILD_PAIR);
6731 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6732 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6733 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6734 LD1->getAddressSpace() != LD2->getAddressSpace())
6736 EVT LD1VT = LD1->getValueType(0);
6738 if (ISD::isNON_EXTLoad(LD2) &&
6740 // If both are volatile this would reduce the number of volatile loads.
6741 // If one is volatile it might be ok, but play conservative and bail out.
6742 !LD1->isVolatile() &&
6743 !LD2->isVolatile() &&
6744 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6745 unsigned Align = LD1->getAlignment();
6746 unsigned NewAlign = TLI.getDataLayout()->
6747 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6749 if (NewAlign <= Align &&
6750 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6751 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6752 LD1->getBasePtr(), LD1->getPointerInfo(),
6753 false, false, false, Align);
6759 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6760 SDValue N0 = N->getOperand(0);
6761 EVT VT = N->getValueType(0);
6763 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6764 // Only do this before legalize, since afterward the target may be depending
6765 // on the bitconvert.
6766 // First check to see if this is all constant.
6768 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6770 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6772 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6773 assert(!DestEltVT.isVector() &&
6774 "Element type of vector ValueType must not be vector!");
6776 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6779 // If the input is a constant, let getNode fold it.
6780 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6781 // If we can't allow illegal operations, we need to check that this is just
6782 // a fp -> int or int -> conversion and that the resulting operation will
6784 if (!LegalOperations ||
6785 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6786 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6787 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6788 TLI.isOperationLegal(ISD::Constant, VT)))
6789 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6792 // (conv (conv x, t1), t2) -> (conv x, t2)
6793 if (N0.getOpcode() == ISD::BITCAST)
6794 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6797 // fold (conv (load x)) -> (load (conv*)x)
6798 // If the resultant load doesn't need a higher alignment than the original!
6799 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6800 // Do not change the width of a volatile load.
6801 !cast<LoadSDNode>(N0)->isVolatile() &&
6802 // Do not remove the cast if the types differ in endian layout.
6803 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6804 TLI.hasBigEndianPartOrdering(VT) &&
6805 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6806 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6807 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6808 unsigned Align = TLI.getDataLayout()->
6809 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6810 unsigned OrigAlign = LN0->getAlignment();
6812 if (Align <= OrigAlign) {
6813 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6814 LN0->getBasePtr(), LN0->getPointerInfo(),
6815 LN0->isVolatile(), LN0->isNonTemporal(),
6816 LN0->isInvariant(), OrigAlign,
6818 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6823 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6824 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6825 // This often reduces constant pool loads.
6826 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6827 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6828 N0.getNode()->hasOneUse() && VT.isInteger() &&
6829 !VT.isVector() && !N0.getValueType().isVector()) {
6830 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6832 AddToWorklist(NewConv.getNode());
6834 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6835 if (N0.getOpcode() == ISD::FNEG)
6836 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6837 NewConv, DAG.getConstant(SignBit, VT));
6838 assert(N0.getOpcode() == ISD::FABS);
6839 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6840 NewConv, DAG.getConstant(~SignBit, VT));
6843 // fold (bitconvert (fcopysign cst, x)) ->
6844 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6845 // Note that we don't handle (copysign x, cst) because this can always be
6846 // folded to an fneg or fabs.
6847 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6848 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6849 VT.isInteger() && !VT.isVector()) {
6850 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6851 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6852 if (isTypeLegal(IntXVT)) {
6853 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6854 IntXVT, N0.getOperand(1));
6855 AddToWorklist(X.getNode());
6857 // If X has a different width than the result/lhs, sext it or truncate it.
6858 unsigned VTWidth = VT.getSizeInBits();
6859 if (OrigXWidth < VTWidth) {
6860 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6861 AddToWorklist(X.getNode());
6862 } else if (OrigXWidth > VTWidth) {
6863 // To get the sign bit in the right place, we have to shift it right
6864 // before truncating.
6865 X = DAG.getNode(ISD::SRL, SDLoc(X),
6866 X.getValueType(), X,
6867 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6868 AddToWorklist(X.getNode());
6869 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6870 AddToWorklist(X.getNode());
6873 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6874 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6875 X, DAG.getConstant(SignBit, VT));
6876 AddToWorklist(X.getNode());
6878 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6879 VT, N0.getOperand(0));
6880 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6881 Cst, DAG.getConstant(~SignBit, VT));
6882 AddToWorklist(Cst.getNode());
6884 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6888 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6889 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6890 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6891 if (CombineLD.getNode())
6898 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6899 EVT VT = N->getValueType(0);
6900 return CombineConsecutiveLoads(N, VT);
6903 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6904 /// operands. DstEltVT indicates the destination element value type.
6905 SDValue DAGCombiner::
6906 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6907 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6909 // If this is already the right type, we're done.
6910 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6912 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6913 unsigned DstBitSize = DstEltVT.getSizeInBits();
6915 // If this is a conversion of N elements of one type to N elements of another
6916 // type, convert each element. This handles FP<->INT cases.
6917 if (SrcBitSize == DstBitSize) {
6918 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6919 BV->getValueType(0).getVectorNumElements());
6921 // Due to the FP element handling below calling this routine recursively,
6922 // we can end up with a scalar-to-vector node here.
6923 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6924 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6925 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6926 DstEltVT, BV->getOperand(0)));
6928 SmallVector<SDValue, 8> Ops;
6929 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6930 SDValue Op = BV->getOperand(i);
6931 // If the vector element type is not legal, the BUILD_VECTOR operands
6932 // are promoted and implicitly truncated. Make that explicit here.
6933 if (Op.getValueType() != SrcEltVT)
6934 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6935 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6937 AddToWorklist(Ops.back().getNode());
6939 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6942 // Otherwise, we're growing or shrinking the elements. To avoid having to
6943 // handle annoying details of growing/shrinking FP values, we convert them to
6945 if (SrcEltVT.isFloatingPoint()) {
6946 // Convert the input float vector to a int vector where the elements are the
6948 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6949 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6953 // Now we know the input is an integer vector. If the output is a FP type,
6954 // convert to integer first, then to FP of the right size.
6955 if (DstEltVT.isFloatingPoint()) {
6956 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6957 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6959 // Next, convert to FP elements of the same size.
6960 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6963 // Okay, we know the src/dst types are both integers of differing types.
6964 // Handling growing first.
6965 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6966 if (SrcBitSize < DstBitSize) {
6967 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6969 SmallVector<SDValue, 8> Ops;
6970 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6971 i += NumInputsPerOutput) {
6972 bool isLE = TLI.isLittleEndian();
6973 APInt NewBits = APInt(DstBitSize, 0);
6974 bool EltIsUndef = true;
6975 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6976 // Shift the previously computed bits over.
6977 NewBits <<= SrcBitSize;
6978 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6979 if (Op.getOpcode() == ISD::UNDEF) continue;
6982 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6983 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6987 Ops.push_back(DAG.getUNDEF(DstEltVT));
6989 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6992 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6993 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6996 // Finally, this must be the case where we are shrinking elements: each input
6997 // turns into multiple outputs.
6998 bool isS2V = ISD::isScalarToVector(BV);
6999 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7000 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7001 NumOutputsPerInput*BV->getNumOperands());
7002 SmallVector<SDValue, 8> Ops;
7004 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7005 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7006 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7010 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7011 getAPIntValue().zextOrTrunc(SrcBitSize);
7013 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7014 APInt ThisVal = OpVal.trunc(DstBitSize);
7015 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7016 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7017 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7018 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7020 OpVal = OpVal.lshr(DstBitSize);
7023 // For big endian targets, swap the order of the pieces of each element.
7024 if (TLI.isBigEndian())
7025 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7028 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7031 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7032 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7035 const TargetLowering &TLI,
7036 SelectionDAG &DAG) {
7037 SDValue N0 = N->getOperand(0);
7038 SDValue N1 = N->getOperand(1);
7039 EVT VT = N->getValueType(0);
7041 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7042 if (N0.getOpcode() == ISD::FMUL &&
7043 (Aggressive || N0->hasOneUse())) {
7044 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7045 N0.getOperand(0), N0.getOperand(1), N1);
7048 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7049 // Note: Commutes FADD operands.
7050 if (N1.getOpcode() == ISD::FMUL &&
7051 (Aggressive || N1->hasOneUse())) {
7052 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7053 N1.getOperand(0), N1.getOperand(1), N0);
7056 // More folding opportunities when target permits.
7058 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7059 if (N0.getOpcode() == ISD::FMA &&
7060 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7061 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7062 N0.getOperand(0), N0.getOperand(1),
7063 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7064 N0.getOperand(2).getOperand(0),
7065 N0.getOperand(2).getOperand(1),
7069 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7070 if (N1->getOpcode() == ISD::FMA &&
7071 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7072 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7073 N1.getOperand(0), N1.getOperand(1),
7074 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7075 N1.getOperand(2).getOperand(0),
7076 N1.getOperand(2).getOperand(1),
7084 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7087 const TargetLowering &TLI,
7088 SelectionDAG &DAG) {
7089 SDValue N0 = N->getOperand(0);
7090 SDValue N1 = N->getOperand(1);
7091 EVT VT = N->getValueType(0);
7095 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7096 if (N0.getOpcode() == ISD::FMUL &&
7097 (Aggressive || N0->hasOneUse())) {
7098 return DAG.getNode(FusedOpcode, SL, VT,
7099 N0.getOperand(0), N0.getOperand(1),
7100 DAG.getNode(ISD::FNEG, SL, VT, N1));
7103 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7104 // Note: Commutes FSUB operands.
7105 if (N1.getOpcode() == ISD::FMUL &&
7106 (Aggressive || N1->hasOneUse()))
7107 return DAG.getNode(FusedOpcode, SL, VT,
7108 DAG.getNode(ISD::FNEG, SL, VT,
7110 N1.getOperand(1), N0);
7112 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7113 if (N0.getOpcode() == ISD::FNEG &&
7114 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7115 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7116 SDValue N00 = N0.getOperand(0).getOperand(0);
7117 SDValue N01 = N0.getOperand(0).getOperand(1);
7118 return DAG.getNode(FusedOpcode, SL, VT,
7119 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7120 DAG.getNode(ISD::FNEG, SL, VT, N1));
7123 // More folding opportunities when target permits.
7125 // fold (fsub (fma x, y, (fmul u, v)), z)
7126 // -> (fma x, y (fma u, v, (fneg z)))
7127 if (N0.getOpcode() == FusedOpcode &&
7128 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7129 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7130 N0.getOperand(0), N0.getOperand(1),
7131 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7132 N0.getOperand(2).getOperand(0),
7133 N0.getOperand(2).getOperand(1),
7134 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7138 // fold (fsub x, (fma y, z, (fmul u, v)))
7139 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7140 if (N1.getOpcode() == FusedOpcode &&
7141 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7142 SDValue N20 = N1.getOperand(2).getOperand(0);
7143 SDValue N21 = N1.getOperand(2).getOperand(1);
7144 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7145 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7148 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7149 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7158 SDValue DAGCombiner::visitFADD(SDNode *N) {
7159 SDValue N0 = N->getOperand(0);
7160 SDValue N1 = N->getOperand(1);
7161 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7162 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7163 EVT VT = N->getValueType(0);
7164 const TargetOptions &Options = DAG.getTarget().Options;
7167 if (VT.isVector()) {
7168 SDValue FoldedVOp = SimplifyVBinOp(N);
7169 if (FoldedVOp.getNode()) return FoldedVOp;
7172 // fold (fadd c1, c2) -> c1 + c2
7174 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7176 // canonicalize constant to RHS
7177 if (N0CFP && !N1CFP)
7178 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7180 // fold (fadd A, (fneg B)) -> (fsub A, B)
7181 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7182 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7183 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7184 GetNegatedExpression(N1, DAG, LegalOperations));
7186 // fold (fadd (fneg A), B) -> (fsub B, A)
7187 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7188 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7189 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7190 GetNegatedExpression(N0, DAG, LegalOperations));
7192 // If 'unsafe math' is enabled, fold lots of things.
7193 if (Options.UnsafeFPMath) {
7194 // No FP constant should be created after legalization as Instruction
7195 // Selection pass has a hard time dealing with FP constants.
7196 bool AllowNewConst = (Level < AfterLegalizeDAG);
7198 // fold (fadd A, 0) -> A
7199 if (N1CFP && N1CFP->getValueAPF().isZero())
7202 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7203 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7204 isa<ConstantFPSDNode>(N0.getOperand(1)))
7205 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7206 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7207 N0.getOperand(1), N1));
7209 // If allowed, fold (fadd (fneg x), x) -> 0.0
7210 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7211 return DAG.getConstantFP(0.0, VT);
7213 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7214 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7215 return DAG.getConstantFP(0.0, VT);
7217 // We can fold chains of FADD's of the same value into multiplications.
7218 // This transform is not safe in general because we are reducing the number
7219 // of rounding steps.
7220 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7221 if (N0.getOpcode() == ISD::FMUL) {
7222 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7223 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7225 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7226 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7227 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7229 DAG.getConstantFP(1.0, VT));
7230 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7233 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7234 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7235 N1.getOperand(0) == N1.getOperand(1) &&
7236 N0.getOperand(0) == N1.getOperand(0)) {
7237 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7239 DAG.getConstantFP(2.0, VT));
7240 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7241 N0.getOperand(0), NewCFP);
7245 if (N1.getOpcode() == ISD::FMUL) {
7246 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7247 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7249 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7250 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7251 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7253 DAG.getConstantFP(1.0, VT));
7254 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7257 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7258 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7259 N0.getOperand(0) == N0.getOperand(1) &&
7260 N1.getOperand(0) == N0.getOperand(0)) {
7261 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7263 DAG.getConstantFP(2.0, VT));
7264 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7268 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7269 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7270 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7271 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7272 (N0.getOperand(0) == N1))
7273 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7274 N1, DAG.getConstantFP(3.0, VT));
7277 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7278 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7279 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7280 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7281 N1.getOperand(0) == N0)
7282 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7283 N0, DAG.getConstantFP(3.0, VT));
7286 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7287 if (AllowNewConst &&
7288 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7289 N0.getOperand(0) == N0.getOperand(1) &&
7290 N1.getOperand(0) == N1.getOperand(1) &&
7291 N0.getOperand(0) == N1.getOperand(0))
7292 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7293 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7295 } // enable-unsafe-fp-math
7297 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7298 // Assume if there is an fmad instruction that it should be aggressively
7300 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7304 // FADD -> FMA combines:
7305 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7306 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7307 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7309 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7310 // Don't form FMA if we are preferring FMAD.
7312 = performFaddFmulCombines(ISD::FMA,
7313 TLI.enableAggressiveFMAFusion(VT),
7319 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7320 // to combine into FMA, arrange such nodes accordingly.
7321 if (TLI.isFPExtFree(VT)) {
7323 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7324 if (N0.getOpcode() == ISD::FP_EXTEND) {
7325 SDValue N00 = N0.getOperand(0);
7326 if (N00.getOpcode() == ISD::FMUL)
7327 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7328 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7330 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7331 N00.getOperand(1)), N1);
7334 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7335 // Note: Commutes FADD operands.
7336 if (N1.getOpcode() == ISD::FP_EXTEND) {
7337 SDValue N10 = N1.getOperand(0);
7338 if (N10.getOpcode() == ISD::FMUL)
7339 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7340 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7342 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7343 N10.getOperand(1)), N0);
7351 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7352 SDValue N0 = N->getOperand(0);
7353 SDValue N1 = N->getOperand(1);
7354 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7355 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7356 EVT VT = N->getValueType(0);
7358 const TargetOptions &Options = DAG.getTarget().Options;
7361 if (VT.isVector()) {
7362 SDValue FoldedVOp = SimplifyVBinOp(N);
7363 if (FoldedVOp.getNode()) return FoldedVOp;
7366 // fold (fsub c1, c2) -> c1-c2
7368 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7370 // fold (fsub A, (fneg B)) -> (fadd A, B)
7371 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7372 return DAG.getNode(ISD::FADD, dl, VT, N0,
7373 GetNegatedExpression(N1, DAG, LegalOperations));
7375 // If 'unsafe math' is enabled, fold lots of things.
7376 if (Options.UnsafeFPMath) {
7378 if (N1CFP && N1CFP->getValueAPF().isZero())
7381 // (fsub 0, B) -> -B
7382 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7383 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7384 return GetNegatedExpression(N1, DAG, LegalOperations);
7385 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7386 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7389 // (fsub x, x) -> 0.0
7391 return DAG.getConstantFP(0.0f, VT);
7393 // (fsub x, (fadd x, y)) -> (fneg y)
7394 // (fsub x, (fadd y, x)) -> (fneg y)
7395 if (N1.getOpcode() == ISD::FADD) {
7396 SDValue N10 = N1->getOperand(0);
7397 SDValue N11 = N1->getOperand(1);
7399 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7400 return GetNegatedExpression(N11, DAG, LegalOperations);
7402 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7403 return GetNegatedExpression(N10, DAG, LegalOperations);
7407 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7408 // Assume if there is an fmad instruction that it should be aggressively
7410 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7414 // FSUB -> FMA combines:
7415 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7416 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7417 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7419 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7420 // Don't form FMA if we are preferring FMAD.
7423 = performFsubFmulCombines(ISD::FMA,
7424 TLI.enableAggressiveFMAFusion(VT),
7430 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7431 // to combine into FMA, arrange such nodes accordingly.
7432 if (TLI.isFPExtFree(VT)) {
7433 // fold (fsub (fpext (fmul x, y)), z)
7434 // -> (fma (fpext x), (fpext y), (fneg z))
7435 if (N0.getOpcode() == ISD::FP_EXTEND) {
7436 SDValue N00 = N0.getOperand(0);
7437 if (N00.getOpcode() == ISD::FMUL)
7438 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7439 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7441 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7443 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7446 // fold (fsub x, (fpext (fmul y, z)))
7447 // -> (fma (fneg (fpext y)), (fpext z), x)
7448 // Note: Commutes FSUB operands.
7449 if (N1.getOpcode() == ISD::FP_EXTEND) {
7450 SDValue N10 = N1.getOperand(0);
7451 if (N10.getOpcode() == ISD::FMUL)
7452 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7453 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7454 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7455 VT, N10.getOperand(0))),
7456 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7461 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7462 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7463 if (N0.getOpcode() == ISD::FP_EXTEND) {
7464 SDValue N00 = N0.getOperand(0);
7465 if (N00.getOpcode() == ISD::FNEG) {
7466 SDValue N000 = N00.getOperand(0);
7467 if (N000.getOpcode() == ISD::FMUL) {
7468 return DAG.getNode(ISD::FMA, dl, VT,
7469 DAG.getNode(ISD::FNEG, dl, VT,
7470 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7471 VT, N000.getOperand(0))),
7472 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7473 N000.getOperand(1)),
7474 DAG.getNode(ISD::FNEG, dl, VT, N1));
7479 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7480 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7481 if (N0.getOpcode() == ISD::FNEG) {
7482 SDValue N00 = N0.getOperand(0);
7483 if (N00.getOpcode() == ISD::FP_EXTEND) {
7484 SDValue N000 = N00.getOperand(0);
7485 if (N000.getOpcode() == ISD::FMUL) {
7486 return DAG.getNode(ISD::FMA, dl, VT,
7487 DAG.getNode(ISD::FNEG, dl, VT,
7488 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7489 VT, N000.getOperand(0))),
7490 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7491 N000.getOperand(1)),
7492 DAG.getNode(ISD::FNEG, dl, VT, N1));
7502 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7503 SDValue N0 = N->getOperand(0);
7504 SDValue N1 = N->getOperand(1);
7505 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7506 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7507 EVT VT = N->getValueType(0);
7508 const TargetOptions &Options = DAG.getTarget().Options;
7511 if (VT.isVector()) {
7512 // This just handles C1 * C2 for vectors. Other vector folds are below.
7513 SDValue FoldedVOp = SimplifyVBinOp(N);
7514 if (FoldedVOp.getNode())
7516 // Canonicalize vector constant to RHS.
7517 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7518 N1.getOpcode() != ISD::BUILD_VECTOR)
7519 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7520 if (BV0->isConstant())
7521 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7524 // fold (fmul c1, c2) -> c1*c2
7526 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7528 // canonicalize constant to RHS
7529 if (N0CFP && !N1CFP)
7530 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7532 // fold (fmul A, 1.0) -> A
7533 if (N1CFP && N1CFP->isExactlyValue(1.0))
7536 if (Options.UnsafeFPMath) {
7537 // fold (fmul A, 0) -> 0
7538 if (N1CFP && N1CFP->getValueAPF().isZero())
7541 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7542 if (N0.getOpcode() == ISD::FMUL) {
7543 // Fold scalars or any vector constants (not just splats).
7544 // This fold is done in general by InstCombine, but extra fmul insts
7545 // may have been generated during lowering.
7546 SDValue N00 = N0.getOperand(0);
7547 SDValue N01 = N0.getOperand(1);
7548 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7549 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7550 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7552 // Check 1: Make sure that the first operand of the inner multiply is NOT
7553 // a constant. Otherwise, we may induce infinite looping.
7554 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7555 // Check 2: Make sure that the second operand of the inner multiply and
7556 // the second operand of the outer multiply are constants.
7557 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7558 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7560 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7561 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7566 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7567 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7568 // during an early run of DAGCombiner can prevent folding with fmuls
7569 // inserted during lowering.
7570 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7572 const SDValue Two = DAG.getConstantFP(2.0, VT);
7573 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7574 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7578 // fold (fmul X, 2.0) -> (fadd X, X)
7579 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7580 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7582 // fold (fmul X, -1.0) -> (fneg X)
7583 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7584 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7585 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7587 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7588 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7589 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7590 // Both can be negated for free, check to see if at least one is cheaper
7592 if (LHSNeg == 2 || RHSNeg == 2)
7593 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7594 GetNegatedExpression(N0, DAG, LegalOperations),
7595 GetNegatedExpression(N1, DAG, LegalOperations));
7602 SDValue DAGCombiner::visitFMA(SDNode *N) {
7603 SDValue N0 = N->getOperand(0);
7604 SDValue N1 = N->getOperand(1);
7605 SDValue N2 = N->getOperand(2);
7606 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7607 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7608 EVT VT = N->getValueType(0);
7610 const TargetOptions &Options = DAG.getTarget().Options;
7612 // Constant fold FMA.
7613 if (isa<ConstantFPSDNode>(N0) &&
7614 isa<ConstantFPSDNode>(N1) &&
7615 isa<ConstantFPSDNode>(N2)) {
7616 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7619 if (Options.UnsafeFPMath) {
7620 if (N0CFP && N0CFP->isZero())
7622 if (N1CFP && N1CFP->isZero())
7625 if (N0CFP && N0CFP->isExactlyValue(1.0))
7626 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7627 if (N1CFP && N1CFP->isExactlyValue(1.0))
7628 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7630 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7631 if (N0CFP && !N1CFP)
7632 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7634 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7635 if (Options.UnsafeFPMath && N1CFP &&
7636 N2.getOpcode() == ISD::FMUL &&
7637 N0 == N2.getOperand(0) &&
7638 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7639 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7640 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7644 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7645 if (Options.UnsafeFPMath &&
7646 N0.getOpcode() == ISD::FMUL && N1CFP &&
7647 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7648 return DAG.getNode(ISD::FMA, dl, VT,
7650 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7654 // (fma x, 1, y) -> (fadd x, y)
7655 // (fma x, -1, y) -> (fadd (fneg x), y)
7657 if (N1CFP->isExactlyValue(1.0))
7658 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7660 if (N1CFP->isExactlyValue(-1.0) &&
7661 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7662 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7663 AddToWorklist(RHSNeg.getNode());
7664 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7668 // (fma x, c, x) -> (fmul x, (c+1))
7669 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7670 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7671 DAG.getNode(ISD::FADD, dl, VT,
7672 N1, DAG.getConstantFP(1.0, VT)));
7674 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7675 if (Options.UnsafeFPMath && N1CFP &&
7676 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7677 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7678 DAG.getNode(ISD::FADD, dl, VT,
7679 N1, DAG.getConstantFP(-1.0, VT)));
7685 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7686 SDValue N0 = N->getOperand(0);
7687 SDValue N1 = N->getOperand(1);
7688 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7689 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7690 EVT VT = N->getValueType(0);
7692 const TargetOptions &Options = DAG.getTarget().Options;
7695 if (VT.isVector()) {
7696 SDValue FoldedVOp = SimplifyVBinOp(N);
7697 if (FoldedVOp.getNode()) return FoldedVOp;
7700 // fold (fdiv c1, c2) -> c1/c2
7702 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7704 if (Options.UnsafeFPMath) {
7705 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7707 // Compute the reciprocal 1.0 / c2.
7708 APFloat N1APF = N1CFP->getValueAPF();
7709 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7710 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7711 // Only do the transform if the reciprocal is a legal fp immediate that
7712 // isn't too nasty (eg NaN, denormal, ...).
7713 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7714 (!LegalOperations ||
7715 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7716 // backend)... we should handle this gracefully after Legalize.
7717 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7718 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7719 TLI.isFPImmLegal(Recip, VT)))
7720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7721 DAG.getConstantFP(Recip, VT));
7724 // If this FDIV is part of a reciprocal square root, it may be folded
7725 // into a target-specific square root estimate instruction.
7726 if (N1.getOpcode() == ISD::FSQRT) {
7727 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7728 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7730 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7731 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7732 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7733 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7734 AddToWorklist(RV.getNode());
7735 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7737 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7738 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7739 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7740 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7741 AddToWorklist(RV.getNode());
7742 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7744 } else if (N1.getOpcode() == ISD::FMUL) {
7745 // Look through an FMUL. Even though this won't remove the FDIV directly,
7746 // it's still worthwhile to get rid of the FSQRT if possible.
7749 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7750 SqrtOp = N1.getOperand(0);
7751 OtherOp = N1.getOperand(1);
7752 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7753 SqrtOp = N1.getOperand(1);
7754 OtherOp = N1.getOperand(0);
7756 if (SqrtOp.getNode()) {
7757 // We found a FSQRT, so try to make this fold:
7758 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7759 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7760 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7761 AddToWorklist(RV.getNode());
7762 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7767 // Fold into a reciprocal estimate and multiply instead of a real divide.
7768 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7769 AddToWorklist(RV.getNode());
7770 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7774 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7775 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7776 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7777 // Both can be negated for free, check to see if at least one is cheaper
7779 if (LHSNeg == 2 || RHSNeg == 2)
7780 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7781 GetNegatedExpression(N0, DAG, LegalOperations),
7782 GetNegatedExpression(N1, DAG, LegalOperations));
7786 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7788 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7789 // Notice that this is not always beneficial. One reason is different target
7790 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7791 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7792 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7793 if (Options.UnsafeFPMath) {
7794 // Skip if current node is a reciprocal.
7795 if (N0CFP && N0CFP->isExactlyValue(1.0))
7798 SmallVector<SDNode *, 4> Users;
7799 // Find all FDIV users of the same divisor.
7800 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7801 UE = N1.getNode()->use_end();
7803 SDNode *User = UI.getUse().getUser();
7804 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7805 Users.push_back(User);
7808 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7809 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7810 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7812 // Dividend / Divisor -> Dividend * Reciprocal
7813 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7814 if ((*I)->getOperand(0) != FPOne) {
7815 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7816 (*I)->getOperand(0), Reciprocal);
7817 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7827 SDValue DAGCombiner::visitFREM(SDNode *N) {
7828 SDValue N0 = N->getOperand(0);
7829 SDValue N1 = N->getOperand(1);
7830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7831 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7832 EVT VT = N->getValueType(0);
7834 // fold (frem c1, c2) -> fmod(c1,c2)
7836 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7841 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7842 if (DAG.getTarget().Options.UnsafeFPMath &&
7843 !TLI.isFsqrtCheap()) {
7844 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7845 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7846 EVT VT = RV.getValueType();
7847 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7848 AddToWorklist(RV.getNode());
7850 // Unfortunately, RV is now NaN if the input was exactly 0.
7851 // Select out this case and force the answer to 0.
7852 SDValue Zero = DAG.getConstantFP(0.0, VT);
7854 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7855 N->getOperand(0), Zero, ISD::SETEQ);
7856 AddToWorklist(ZeroCmp.getNode());
7857 AddToWorklist(RV.getNode());
7859 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7860 SDLoc(N), VT, ZeroCmp, Zero, RV);
7867 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7868 SDValue N0 = N->getOperand(0);
7869 SDValue N1 = N->getOperand(1);
7870 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7871 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7872 EVT VT = N->getValueType(0);
7874 if (N0CFP && N1CFP) // Constant fold
7875 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7878 const APFloat& V = N1CFP->getValueAPF();
7879 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7880 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7881 if (!V.isNegative()) {
7882 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7883 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7885 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7886 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7887 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7891 // copysign(fabs(x), y) -> copysign(x, y)
7892 // copysign(fneg(x), y) -> copysign(x, y)
7893 // copysign(copysign(x,z), y) -> copysign(x, y)
7894 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7895 N0.getOpcode() == ISD::FCOPYSIGN)
7896 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7897 N0.getOperand(0), N1);
7899 // copysign(x, abs(y)) -> abs(x)
7900 if (N1.getOpcode() == ISD::FABS)
7901 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7903 // copysign(x, copysign(y,z)) -> copysign(x, z)
7904 if (N1.getOpcode() == ISD::FCOPYSIGN)
7905 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7906 N0, N1.getOperand(1));
7908 // copysign(x, fp_extend(y)) -> copysign(x, y)
7909 // copysign(x, fp_round(y)) -> copysign(x, y)
7910 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7911 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7912 N0, N1.getOperand(0));
7917 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7918 SDValue N0 = N->getOperand(0);
7919 EVT VT = N->getValueType(0);
7920 EVT OpVT = N0.getValueType();
7922 // fold (sint_to_fp c1) -> c1fp
7923 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7925 // ...but only if the target supports immediate floating-point values
7926 (!LegalOperations ||
7927 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7928 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7930 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7931 // but UINT_TO_FP is legal on this target, try to convert.
7932 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7933 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7934 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7935 if (DAG.SignBitIsZero(N0))
7936 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7939 // The next optimizations are desirable only if SELECT_CC can be lowered.
7940 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7941 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7942 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7944 (!LegalOperations ||
7945 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7947 { N0.getOperand(0), N0.getOperand(1),
7948 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7950 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7953 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7954 // (select_cc x, y, 1.0, 0.0,, cc)
7955 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7956 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7957 (!LegalOperations ||
7958 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7960 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7961 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7962 N0.getOperand(0).getOperand(2) };
7963 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7970 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7971 SDValue N0 = N->getOperand(0);
7972 EVT VT = N->getValueType(0);
7973 EVT OpVT = N0.getValueType();
7975 // fold (uint_to_fp c1) -> c1fp
7976 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7978 // ...but only if the target supports immediate floating-point values
7979 (!LegalOperations ||
7980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7981 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7983 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7984 // but SINT_TO_FP is legal on this target, try to convert.
7985 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7986 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7987 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7988 if (DAG.SignBitIsZero(N0))
7989 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7992 // The next optimizations are desirable only if SELECT_CC can be lowered.
7993 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7994 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7996 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7997 (!LegalOperations ||
7998 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8000 { N0.getOperand(0), N0.getOperand(1),
8001 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8003 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8010 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8011 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8012 SDValue N0 = N->getOperand(0);
8013 EVT VT = N->getValueType(0);
8015 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8018 SDValue Src = N0.getOperand(0);
8019 EVT SrcVT = Src.getValueType();
8020 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8021 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8023 // We can safely assume the conversion won't overflow the output range,
8024 // because (for example) (uint8_t)18293.f is undefined behavior.
8026 // Since we can assume the conversion won't overflow, our decision as to
8027 // whether the input will fit in the float should depend on the minimum
8028 // of the input range and output range.
8030 // This means this is also safe for a signed input and unsigned output, since
8031 // a negative input would lead to undefined behavior.
8032 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8033 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8034 unsigned ActualSize = std::min(InputSize, OutputSize);
8035 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8037 // We can only fold away the float conversion if the input range can be
8038 // represented exactly in the float range.
8039 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8040 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8041 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8043 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8045 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8046 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8049 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8054 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8055 SDValue N0 = N->getOperand(0);
8056 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8057 EVT VT = N->getValueType(0);
8059 // fold (fp_to_sint c1fp) -> c1
8061 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8063 return FoldIntToFPToInt(N, DAG);
8066 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8067 SDValue N0 = N->getOperand(0);
8068 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8069 EVT VT = N->getValueType(0);
8071 // fold (fp_to_uint c1fp) -> c1
8073 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8075 return FoldIntToFPToInt(N, DAG);
8078 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8079 SDValue N0 = N->getOperand(0);
8080 SDValue N1 = N->getOperand(1);
8081 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8082 EVT VT = N->getValueType(0);
8084 // fold (fp_round c1fp) -> c1fp
8086 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8088 // fold (fp_round (fp_extend x)) -> x
8089 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8090 return N0.getOperand(0);
8092 // fold (fp_round (fp_round x)) -> (fp_round x)
8093 if (N0.getOpcode() == ISD::FP_ROUND) {
8094 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8095 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8096 // If the first fp_round isn't a value preserving truncation, it might
8097 // introduce a tie in the second fp_round, that wouldn't occur in the
8098 // single-step fp_round we want to fold to.
8099 // In other words, double rounding isn't the same as rounding.
8100 // Also, this is a value preserving truncation iff both fp_round's are.
8101 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8102 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8103 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8106 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8107 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8108 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8109 N0.getOperand(0), N1);
8110 AddToWorklist(Tmp.getNode());
8111 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8112 Tmp, N0.getOperand(1));
8118 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8119 SDValue N0 = N->getOperand(0);
8120 EVT VT = N->getValueType(0);
8121 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8122 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8124 // fold (fp_round_inreg c1fp) -> c1fp
8125 if (N0CFP && isTypeLegal(EVT)) {
8126 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8127 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8133 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8134 SDValue N0 = N->getOperand(0);
8135 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8136 EVT VT = N->getValueType(0);
8138 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8139 if (N->hasOneUse() &&
8140 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8143 // fold (fp_extend c1fp) -> c1fp
8145 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8147 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8149 if (N0.getOpcode() == ISD::FP_ROUND
8150 && N0.getNode()->getConstantOperandVal(1) == 1) {
8151 SDValue In = N0.getOperand(0);
8152 if (In.getValueType() == VT) return In;
8153 if (VT.bitsLT(In.getValueType()))
8154 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8155 In, N0.getOperand(1));
8156 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8159 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8160 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8161 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8163 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8165 LN0->getBasePtr(), N0.getValueType(),
8166 LN0->getMemOperand());
8167 CombineTo(N, ExtLoad);
8168 CombineTo(N0.getNode(),
8169 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8170 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8171 ExtLoad.getValue(1));
8172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8178 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8179 SDValue N0 = N->getOperand(0);
8180 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8181 EVT VT = N->getValueType(0);
8183 // fold (fceil c1) -> fceil(c1)
8185 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8190 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8191 SDValue N0 = N->getOperand(0);
8192 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8193 EVT VT = N->getValueType(0);
8195 // fold (ftrunc c1) -> ftrunc(c1)
8197 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8202 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8203 SDValue N0 = N->getOperand(0);
8204 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8205 EVT VT = N->getValueType(0);
8207 // fold (ffloor c1) -> ffloor(c1)
8209 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8214 // FIXME: FNEG and FABS have a lot in common; refactor.
8215 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8216 SDValue N0 = N->getOperand(0);
8217 EVT VT = N->getValueType(0);
8219 if (VT.isVector()) {
8220 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8221 if (FoldedVOp.getNode()) return FoldedVOp;
8224 // Constant fold FNEG.
8225 if (isa<ConstantFPSDNode>(N0))
8226 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8228 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8229 &DAG.getTarget().Options))
8230 return GetNegatedExpression(N0, DAG, LegalOperations);
8232 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8233 // constant pool values.
8234 if (!TLI.isFNegFree(VT) &&
8235 N0.getOpcode() == ISD::BITCAST &&
8236 N0.getNode()->hasOneUse()) {
8237 SDValue Int = N0.getOperand(0);
8238 EVT IntVT = Int.getValueType();
8239 if (IntVT.isInteger() && !IntVT.isVector()) {
8241 if (N0.getValueType().isVector()) {
8242 // For a vector, get a mask such as 0x80... per scalar element
8244 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8245 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8247 // For a scalar, just generate 0x80...
8248 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8250 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8251 DAG.getConstant(SignMask, IntVT));
8252 AddToWorklist(Int.getNode());
8253 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8257 // (fneg (fmul c, x)) -> (fmul -c, x)
8258 if (N0.getOpcode() == ISD::FMUL) {
8259 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8261 APFloat CVal = CFP1->getValueAPF();
8263 if (Level >= AfterLegalizeDAG &&
8264 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8265 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8267 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8268 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8275 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8276 SDValue N0 = N->getOperand(0);
8277 SDValue N1 = N->getOperand(1);
8278 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8279 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8281 if (N0CFP && N1CFP) {
8282 const APFloat &C0 = N0CFP->getValueAPF();
8283 const APFloat &C1 = N1CFP->getValueAPF();
8284 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8288 EVT VT = N->getValueType(0);
8289 // Canonicalize to constant on RHS.
8290 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8296 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8297 SDValue N0 = N->getOperand(0);
8298 SDValue N1 = N->getOperand(1);
8299 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8300 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8302 if (N0CFP && N1CFP) {
8303 const APFloat &C0 = N0CFP->getValueAPF();
8304 const APFloat &C1 = N1CFP->getValueAPF();
8305 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8309 EVT VT = N->getValueType(0);
8310 // Canonicalize to constant on RHS.
8311 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8317 SDValue DAGCombiner::visitFABS(SDNode *N) {
8318 SDValue N0 = N->getOperand(0);
8319 EVT VT = N->getValueType(0);
8321 if (VT.isVector()) {
8322 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8323 if (FoldedVOp.getNode()) return FoldedVOp;
8326 // fold (fabs c1) -> fabs(c1)
8327 if (isa<ConstantFPSDNode>(N0))
8328 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8330 // fold (fabs (fabs x)) -> (fabs x)
8331 if (N0.getOpcode() == ISD::FABS)
8332 return N->getOperand(0);
8334 // fold (fabs (fneg x)) -> (fabs x)
8335 // fold (fabs (fcopysign x, y)) -> (fabs x)
8336 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8337 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8339 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8340 // constant pool values.
8341 if (!TLI.isFAbsFree(VT) &&
8342 N0.getOpcode() == ISD::BITCAST &&
8343 N0.getNode()->hasOneUse()) {
8344 SDValue Int = N0.getOperand(0);
8345 EVT IntVT = Int.getValueType();
8346 if (IntVT.isInteger() && !IntVT.isVector()) {
8348 if (N0.getValueType().isVector()) {
8349 // For a vector, get a mask such as 0x7f... per scalar element
8351 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8352 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8354 // For a scalar, just generate 0x7f...
8355 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8357 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8358 DAG.getConstant(SignMask, IntVT));
8359 AddToWorklist(Int.getNode());
8360 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8367 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8368 SDValue Chain = N->getOperand(0);
8369 SDValue N1 = N->getOperand(1);
8370 SDValue N2 = N->getOperand(2);
8372 // If N is a constant we could fold this into a fallthrough or unconditional
8373 // branch. However that doesn't happen very often in normal code, because
8374 // Instcombine/SimplifyCFG should have handled the available opportunities.
8375 // If we did this folding here, it would be necessary to update the
8376 // MachineBasicBlock CFG, which is awkward.
8378 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8380 if (N1.getOpcode() == ISD::SETCC &&
8381 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8382 N1.getOperand(0).getValueType())) {
8383 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8384 Chain, N1.getOperand(2),
8385 N1.getOperand(0), N1.getOperand(1), N2);
8388 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8389 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8390 (N1.getOperand(0).hasOneUse() &&
8391 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8392 SDNode *Trunc = nullptr;
8393 if (N1.getOpcode() == ISD::TRUNCATE) {
8394 // Look pass the truncate.
8395 Trunc = N1.getNode();
8396 N1 = N1.getOperand(0);
8399 // Match this pattern so that we can generate simpler code:
8402 // %b = and i32 %a, 2
8403 // %c = srl i32 %b, 1
8404 // brcond i32 %c ...
8409 // %b = and i32 %a, 2
8410 // %c = setcc eq %b, 0
8413 // This applies only when the AND constant value has one bit set and the
8414 // SRL constant is equal to the log2 of the AND constant. The back-end is
8415 // smart enough to convert the result into a TEST/JMP sequence.
8416 SDValue Op0 = N1.getOperand(0);
8417 SDValue Op1 = N1.getOperand(1);
8419 if (Op0.getOpcode() == ISD::AND &&
8420 Op1.getOpcode() == ISD::Constant) {
8421 SDValue AndOp1 = Op0.getOperand(1);
8423 if (AndOp1.getOpcode() == ISD::Constant) {
8424 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8426 if (AndConst.isPowerOf2() &&
8427 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8429 DAG.getSetCC(SDLoc(N),
8430 getSetCCResultType(Op0.getValueType()),
8431 Op0, DAG.getConstant(0, Op0.getValueType()),
8434 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8435 MVT::Other, Chain, SetCC, N2);
8436 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8437 // will convert it back to (X & C1) >> C2.
8438 CombineTo(N, NewBRCond, false);
8439 // Truncate is dead.
8441 deleteAndRecombine(Trunc);
8442 // Replace the uses of SRL with SETCC
8443 WorklistRemover DeadNodes(*this);
8444 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8445 deleteAndRecombine(N1.getNode());
8446 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8452 // Restore N1 if the above transformation doesn't match.
8453 N1 = N->getOperand(1);
8456 // Transform br(xor(x, y)) -> br(x != y)
8457 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8458 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8459 SDNode *TheXor = N1.getNode();
8460 SDValue Op0 = TheXor->getOperand(0);
8461 SDValue Op1 = TheXor->getOperand(1);
8462 if (Op0.getOpcode() == Op1.getOpcode()) {
8463 // Avoid missing important xor optimizations.
8464 SDValue Tmp = visitXOR(TheXor);
8465 if (Tmp.getNode()) {
8466 if (Tmp.getNode() != TheXor) {
8467 DEBUG(dbgs() << "\nReplacing.8 ";
8469 dbgs() << "\nWith: ";
8470 Tmp.getNode()->dump(&DAG);
8472 WorklistRemover DeadNodes(*this);
8473 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8474 deleteAndRecombine(TheXor);
8475 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8476 MVT::Other, Chain, Tmp, N2);
8479 // visitXOR has changed XOR's operands or replaced the XOR completely,
8481 return SDValue(N, 0);
8485 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8487 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8488 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8489 Op0.getOpcode() == ISD::XOR) {
8490 TheXor = Op0.getNode();
8494 EVT SetCCVT = N1.getValueType();
8496 SetCCVT = getSetCCResultType(SetCCVT);
8497 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8500 Equal ? ISD::SETEQ : ISD::SETNE);
8501 // Replace the uses of XOR with SETCC
8502 WorklistRemover DeadNodes(*this);
8503 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8504 deleteAndRecombine(N1.getNode());
8505 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8506 MVT::Other, Chain, SetCC, N2);
8513 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8515 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8516 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8517 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8519 // If N is a constant we could fold this into a fallthrough or unconditional
8520 // branch. However that doesn't happen very often in normal code, because
8521 // Instcombine/SimplifyCFG should have handled the available opportunities.
8522 // If we did this folding here, it would be necessary to update the
8523 // MachineBasicBlock CFG, which is awkward.
8525 // Use SimplifySetCC to simplify SETCC's.
8526 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8527 CondLHS, CondRHS, CC->get(), SDLoc(N),
8529 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8531 // fold to a simpler setcc
8532 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8533 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8534 N->getOperand(0), Simp.getOperand(2),
8535 Simp.getOperand(0), Simp.getOperand(1),
8541 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8542 /// and that N may be folded in the load / store addressing mode.
8543 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8545 const TargetLowering &TLI) {
8547 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8548 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8550 VT = Use->getValueType(0);
8551 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8552 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8554 VT = ST->getValue().getValueType();
8558 TargetLowering::AddrMode AM;
8559 if (N->getOpcode() == ISD::ADD) {
8560 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8563 AM.BaseOffs = Offset->getSExtValue();
8567 } else if (N->getOpcode() == ISD::SUB) {
8568 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8571 AM.BaseOffs = -Offset->getSExtValue();
8578 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8581 /// Try turning a load/store into a pre-indexed load/store when the base
8582 /// pointer is an add or subtract and it has other uses besides the load/store.
8583 /// After the transformation, the new indexed load/store has effectively folded
8584 /// the add/subtract in and all of its other uses are redirected to the
8586 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8587 if (Level < AfterLegalizeDAG)
8593 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8594 if (LD->isIndexed())
8596 VT = LD->getMemoryVT();
8597 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8598 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8600 Ptr = LD->getBasePtr();
8601 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8602 if (ST->isIndexed())
8604 VT = ST->getMemoryVT();
8605 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8606 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8608 Ptr = ST->getBasePtr();
8614 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8615 // out. There is no reason to make this a preinc/predec.
8616 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8617 Ptr.getNode()->hasOneUse())
8620 // Ask the target to do addressing mode selection.
8623 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8624 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8627 // Backends without true r+i pre-indexed forms may need to pass a
8628 // constant base with a variable offset so that constant coercion
8629 // will work with the patterns in canonical form.
8630 bool Swapped = false;
8631 if (isa<ConstantSDNode>(BasePtr)) {
8632 std::swap(BasePtr, Offset);
8636 // Don't create a indexed load / store with zero offset.
8637 if (isa<ConstantSDNode>(Offset) &&
8638 cast<ConstantSDNode>(Offset)->isNullValue())
8641 // Try turning it into a pre-indexed load / store except when:
8642 // 1) The new base ptr is a frame index.
8643 // 2) If N is a store and the new base ptr is either the same as or is a
8644 // predecessor of the value being stored.
8645 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8646 // that would create a cycle.
8647 // 4) All uses are load / store ops that use it as old base ptr.
8649 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8650 // (plus the implicit offset) to a register to preinc anyway.
8651 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8656 SDValue Val = cast<StoreSDNode>(N)->getValue();
8657 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8661 // If the offset is a constant, there may be other adds of constants that
8662 // can be folded with this one. We should do this to avoid having to keep
8663 // a copy of the original base pointer.
8664 SmallVector<SDNode *, 16> OtherUses;
8665 if (isa<ConstantSDNode>(Offset))
8666 for (SDNode *Use : BasePtr.getNode()->uses()) {
8667 if (Use == Ptr.getNode())
8670 if (Use->isPredecessorOf(N))
8673 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8678 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8679 if (Op1.getNode() == BasePtr.getNode())
8680 std::swap(Op0, Op1);
8681 assert(Op0.getNode() == BasePtr.getNode() &&
8682 "Use of ADD/SUB but not an operand");
8684 if (!isa<ConstantSDNode>(Op1)) {
8689 // FIXME: In some cases, we can be smarter about this.
8690 if (Op1.getValueType() != Offset.getValueType()) {
8695 OtherUses.push_back(Use);
8699 std::swap(BasePtr, Offset);
8701 // Now check for #3 and #4.
8702 bool RealUse = false;
8704 // Caches for hasPredecessorHelper
8705 SmallPtrSet<const SDNode *, 32> Visited;
8706 SmallVector<const SDNode *, 16> Worklist;
8708 for (SDNode *Use : Ptr.getNode()->uses()) {
8711 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8714 // If Ptr may be folded in addressing mode of other use, then it's
8715 // not profitable to do this transformation.
8716 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8725 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8726 BasePtr, Offset, AM);
8728 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8729 BasePtr, Offset, AM);
8732 DEBUG(dbgs() << "\nReplacing.4 ";
8734 dbgs() << "\nWith: ";
8735 Result.getNode()->dump(&DAG);
8737 WorklistRemover DeadNodes(*this);
8739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8740 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8745 // Finally, since the node is now dead, remove it from the graph.
8746 deleteAndRecombine(N);
8749 std::swap(BasePtr, Offset);
8751 // Replace other uses of BasePtr that can be updated to use Ptr
8752 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8753 unsigned OffsetIdx = 1;
8754 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8756 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8757 BasePtr.getNode() && "Expected BasePtr operand");
8759 // We need to replace ptr0 in the following expression:
8760 // x0 * offset0 + y0 * ptr0 = t0
8762 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8764 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8765 // indexed load/store and the expresion that needs to be re-written.
8767 // Therefore, we have:
8768 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8770 ConstantSDNode *CN =
8771 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8773 APInt Offset0 = CN->getAPIntValue();
8774 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8776 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8777 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8778 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8779 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8781 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8783 APInt CNV = Offset0;
8784 if (X0 < 0) CNV = -CNV;
8785 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8786 else CNV = CNV - Offset1;
8788 // We can now generate the new expression.
8789 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8790 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8792 SDValue NewUse = DAG.getNode(Opcode,
8793 SDLoc(OtherUses[i]),
8794 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8795 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8796 deleteAndRecombine(OtherUses[i]);
8799 // Replace the uses of Ptr with uses of the updated base value.
8800 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8801 deleteAndRecombine(Ptr.getNode());
8806 /// Try to combine a load/store with a add/sub of the base pointer node into a
8807 /// post-indexed load/store. The transformation folded the add/subtract into the
8808 /// new indexed load/store effectively and all of its uses are redirected to the
8810 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8811 if (Level < AfterLegalizeDAG)
8817 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8818 if (LD->isIndexed())
8820 VT = LD->getMemoryVT();
8821 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8822 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8824 Ptr = LD->getBasePtr();
8825 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8826 if (ST->isIndexed())
8828 VT = ST->getMemoryVT();
8829 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8830 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8832 Ptr = ST->getBasePtr();
8838 if (Ptr.getNode()->hasOneUse())
8841 for (SDNode *Op : Ptr.getNode()->uses()) {
8843 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8848 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8849 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8850 // Don't create a indexed load / store with zero offset.
8851 if (isa<ConstantSDNode>(Offset) &&
8852 cast<ConstantSDNode>(Offset)->isNullValue())
8855 // Try turning it into a post-indexed load / store except when
8856 // 1) All uses are load / store ops that use it as base ptr (and
8857 // it may be folded as addressing mmode).
8858 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8859 // nor a successor of N. Otherwise, if Op is folded that would
8862 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8866 bool TryNext = false;
8867 for (SDNode *Use : BasePtr.getNode()->uses()) {
8868 if (Use == Ptr.getNode())
8871 // If all the uses are load / store addresses, then don't do the
8873 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8874 bool RealUse = false;
8875 for (SDNode *UseUse : Use->uses()) {
8876 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8891 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8892 SDValue Result = isLoad
8893 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8894 BasePtr, Offset, AM)
8895 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8896 BasePtr, Offset, AM);
8899 DEBUG(dbgs() << "\nReplacing.5 ";
8901 dbgs() << "\nWith: ";
8902 Result.getNode()->dump(&DAG);
8904 WorklistRemover DeadNodes(*this);
8906 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8907 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8909 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8912 // Finally, since the node is now dead, remove it from the graph.
8913 deleteAndRecombine(N);
8915 // Replace the uses of Use with uses of the updated base value.
8916 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8917 Result.getValue(isLoad ? 1 : 0));
8918 deleteAndRecombine(Op);
8927 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8928 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8929 ISD::MemIndexedMode AM = LD->getAddressingMode();
8930 assert(AM != ISD::UNINDEXED);
8931 SDValue BP = LD->getOperand(1);
8932 SDValue Inc = LD->getOperand(2);
8934 // Some backends use TargetConstants for load offsets, but don't expect
8935 // TargetConstants in general ADD nodes. We can convert these constants into
8936 // regular Constants (if the constant is not opaque).
8937 assert((Inc.getOpcode() != ISD::TargetConstant ||
8938 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8939 "Cannot split out indexing using opaque target constants");
8940 if (Inc.getOpcode() == ISD::TargetConstant) {
8941 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8942 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8943 ConstInc->getValueType(0));
8947 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8948 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8951 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8952 LoadSDNode *LD = cast<LoadSDNode>(N);
8953 SDValue Chain = LD->getChain();
8954 SDValue Ptr = LD->getBasePtr();
8956 // If load is not volatile and there are no uses of the loaded value (and
8957 // the updated indexed value in case of indexed loads), change uses of the
8958 // chain value into uses of the chain input (i.e. delete the dead load).
8959 if (!LD->isVolatile()) {
8960 if (N->getValueType(1) == MVT::Other) {
8962 if (!N->hasAnyUseOfValue(0)) {
8963 // It's not safe to use the two value CombineTo variant here. e.g.
8964 // v1, chain2 = load chain1, loc
8965 // v2, chain3 = load chain2, loc
8967 // Now we replace use of chain2 with chain1. This makes the second load
8968 // isomorphic to the one we are deleting, and thus makes this load live.
8969 DEBUG(dbgs() << "\nReplacing.6 ";
8971 dbgs() << "\nWith chain: ";
8972 Chain.getNode()->dump(&DAG);
8974 WorklistRemover DeadNodes(*this);
8975 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8978 deleteAndRecombine(N);
8980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8984 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8986 // If this load has an opaque TargetConstant offset, then we cannot split
8987 // the indexing into an add/sub directly (that TargetConstant may not be
8988 // valid for a different type of node, and we cannot convert an opaque
8989 // target constant into a regular constant).
8990 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8991 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8993 if (!N->hasAnyUseOfValue(0) &&
8994 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8995 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8997 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8998 Index = SplitIndexingFromLoad(LD);
8999 // Try to fold the base pointer arithmetic into subsequent loads and
9001 AddUsersToWorklist(N);
9003 Index = DAG.getUNDEF(N->getValueType(1));
9004 DEBUG(dbgs() << "\nReplacing.7 ";
9006 dbgs() << "\nWith: ";
9007 Undef.getNode()->dump(&DAG);
9008 dbgs() << " and 2 other values\n");
9009 WorklistRemover DeadNodes(*this);
9010 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9011 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9012 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9013 deleteAndRecombine(N);
9014 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9019 // If this load is directly stored, replace the load value with the stored
9021 // TODO: Handle store large -> read small portion.
9022 // TODO: Handle TRUNCSTORE/LOADEXT
9023 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9024 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9025 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9026 if (PrevST->getBasePtr() == Ptr &&
9027 PrevST->getValue().getValueType() == N->getValueType(0))
9028 return CombineTo(N, Chain.getOperand(1), Chain);
9032 // Try to infer better alignment information than the load already has.
9033 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9034 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9035 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9037 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9038 LD->getValueType(0),
9039 Chain, Ptr, LD->getPointerInfo(),
9041 LD->isVolatile(), LD->isNonTemporal(),
9042 LD->isInvariant(), Align, LD->getAAInfo());
9043 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9048 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9049 : DAG.getSubtarget().useAA();
9051 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9052 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9055 if (UseAA && LD->isUnindexed()) {
9056 // Walk up chain skipping non-aliasing memory nodes.
9057 SDValue BetterChain = FindBetterChain(N, Chain);
9059 // If there is a better chain.
9060 if (Chain != BetterChain) {
9063 // Replace the chain to void dependency.
9064 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9065 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9066 BetterChain, Ptr, LD->getMemOperand());
9068 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9069 LD->getValueType(0),
9070 BetterChain, Ptr, LD->getMemoryVT(),
9071 LD->getMemOperand());
9074 // Create token factor to keep old chain connected.
9075 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9076 MVT::Other, Chain, ReplLoad.getValue(1));
9078 // Make sure the new and old chains are cleaned up.
9079 AddToWorklist(Token.getNode());
9081 // Replace uses with load result and token factor. Don't add users
9083 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9087 // Try transforming N to an indexed load.
9088 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9089 return SDValue(N, 0);
9091 // Try to slice up N to more direct loads if the slices are mapped to
9092 // different register banks or pairing can take place.
9094 return SDValue(N, 0);
9100 /// \brief Helper structure used to slice a load in smaller loads.
9101 /// Basically a slice is obtained from the following sequence:
9102 /// Origin = load Ty1, Base
9103 /// Shift = srl Ty1 Origin, CstTy Amount
9104 /// Inst = trunc Shift to Ty2
9106 /// Then, it will be rewriten into:
9107 /// Slice = load SliceTy, Base + SliceOffset
9108 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9110 /// SliceTy is deduced from the number of bits that are actually used to
9112 struct LoadedSlice {
9113 /// \brief Helper structure used to compute the cost of a slice.
9115 /// Are we optimizing for code size.
9120 unsigned CrossRegisterBanksCopies;
9124 Cost(bool ForCodeSize = false)
9125 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9126 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9128 /// \brief Get the cost of one isolated slice.
9129 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9130 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9131 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9132 EVT TruncType = LS.Inst->getValueType(0);
9133 EVT LoadedType = LS.getLoadedType();
9134 if (TruncType != LoadedType &&
9135 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9139 /// \brief Account for slicing gain in the current cost.
9140 /// Slicing provide a few gains like removing a shift or a
9141 /// truncate. This method allows to grow the cost of the original
9142 /// load with the gain from this slice.
9143 void addSliceGain(const LoadedSlice &LS) {
9144 // Each slice saves a truncate.
9145 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9146 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9147 LS.Inst->getOperand(0).getValueType()))
9149 // If there is a shift amount, this slice gets rid of it.
9152 // If this slice can merge a cross register bank copy, account for it.
9153 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9154 ++CrossRegisterBanksCopies;
9157 Cost &operator+=(const Cost &RHS) {
9159 Truncates += RHS.Truncates;
9160 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9166 bool operator==(const Cost &RHS) const {
9167 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9168 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9169 ZExts == RHS.ZExts && Shift == RHS.Shift;
9172 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9174 bool operator<(const Cost &RHS) const {
9175 // Assume cross register banks copies are as expensive as loads.
9176 // FIXME: Do we want some more target hooks?
9177 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9178 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9179 // Unless we are optimizing for code size, consider the
9180 // expensive operation first.
9181 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9182 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9183 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9184 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9187 bool operator>(const Cost &RHS) const { return RHS < *this; }
9189 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9191 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9193 // The last instruction that represent the slice. This should be a
9194 // truncate instruction.
9196 // The original load instruction.
9198 // The right shift amount in bits from the original load.
9200 // The DAG from which Origin came from.
9201 // This is used to get some contextual information about legal types, etc.
9204 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9205 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9206 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9208 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9209 /// \return Result is \p BitWidth and has used bits set to 1 and
9210 /// not used bits set to 0.
9211 APInt getUsedBits() const {
9212 // Reproduce the trunc(lshr) sequence:
9213 // - Start from the truncated value.
9214 // - Zero extend to the desired bit width.
9216 assert(Origin && "No original load to compare against.");
9217 unsigned BitWidth = Origin->getValueSizeInBits(0);
9218 assert(Inst && "This slice is not bound to an instruction");
9219 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9220 "Extracted slice is bigger than the whole type!");
9221 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9222 UsedBits.setAllBits();
9223 UsedBits = UsedBits.zext(BitWidth);
9228 /// \brief Get the size of the slice to be loaded in bytes.
9229 unsigned getLoadedSize() const {
9230 unsigned SliceSize = getUsedBits().countPopulation();
9231 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9232 return SliceSize / 8;
9235 /// \brief Get the type that will be loaded for this slice.
9236 /// Note: This may not be the final type for the slice.
9237 EVT getLoadedType() const {
9238 assert(DAG && "Missing context");
9239 LLVMContext &Ctxt = *DAG->getContext();
9240 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9243 /// \brief Get the alignment of the load used for this slice.
9244 unsigned getAlignment() const {
9245 unsigned Alignment = Origin->getAlignment();
9246 unsigned Offset = getOffsetFromBase();
9248 Alignment = MinAlign(Alignment, Alignment + Offset);
9252 /// \brief Check if this slice can be rewritten with legal operations.
9253 bool isLegal() const {
9254 // An invalid slice is not legal.
9255 if (!Origin || !Inst || !DAG)
9258 // Offsets are for indexed load only, we do not handle that.
9259 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9262 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9264 // Check that the type is legal.
9265 EVT SliceType = getLoadedType();
9266 if (!TLI.isTypeLegal(SliceType))
9269 // Check that the load is legal for this type.
9270 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9273 // Check that the offset can be computed.
9274 // 1. Check its type.
9275 EVT PtrType = Origin->getBasePtr().getValueType();
9276 if (PtrType == MVT::Untyped || PtrType.isExtended())
9279 // 2. Check that it fits in the immediate.
9280 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9283 // 3. Check that the computation is legal.
9284 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9287 // Check that the zext is legal if it needs one.
9288 EVT TruncateType = Inst->getValueType(0);
9289 if (TruncateType != SliceType &&
9290 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9296 /// \brief Get the offset in bytes of this slice in the original chunk of
9298 /// \pre DAG != nullptr.
9299 uint64_t getOffsetFromBase() const {
9300 assert(DAG && "Missing context.");
9302 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9303 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9304 uint64_t Offset = Shift / 8;
9305 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9306 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9307 "The size of the original loaded type is not a multiple of a"
9309 // If Offset is bigger than TySizeInBytes, it means we are loading all
9310 // zeros. This should have been optimized before in the process.
9311 assert(TySizeInBytes > Offset &&
9312 "Invalid shift amount for given loaded size");
9314 Offset = TySizeInBytes - Offset - getLoadedSize();
9318 /// \brief Generate the sequence of instructions to load the slice
9319 /// represented by this object and redirect the uses of this slice to
9320 /// this new sequence of instructions.
9321 /// \pre this->Inst && this->Origin are valid Instructions and this
9322 /// object passed the legal check: LoadedSlice::isLegal returned true.
9323 /// \return The last instruction of the sequence used to load the slice.
9324 SDValue loadSlice() const {
9325 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9326 const SDValue &OldBaseAddr = Origin->getBasePtr();
9327 SDValue BaseAddr = OldBaseAddr;
9328 // Get the offset in that chunk of bytes w.r.t. the endianess.
9329 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9330 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9332 // BaseAddr = BaseAddr + Offset.
9333 EVT ArithType = BaseAddr.getValueType();
9334 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9335 DAG->getConstant(Offset, ArithType));
9338 // Create the type of the loaded slice according to its size.
9339 EVT SliceType = getLoadedType();
9341 // Create the load for the slice.
9342 SDValue LastInst = DAG->getLoad(
9343 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9344 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9345 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9346 // If the final type is not the same as the loaded type, this means that
9347 // we have to pad with zero. Create a zero extend for that.
9348 EVT FinalType = Inst->getValueType(0);
9349 if (SliceType != FinalType)
9351 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9355 /// \brief Check if this slice can be merged with an expensive cross register
9356 /// bank copy. E.g.,
9358 /// f = bitcast i32 i to float
9359 bool canMergeExpensiveCrossRegisterBankCopy() const {
9360 if (!Inst || !Inst->hasOneUse())
9362 SDNode *Use = *Inst->use_begin();
9363 if (Use->getOpcode() != ISD::BITCAST)
9365 assert(DAG && "Missing context");
9366 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9367 EVT ResVT = Use->getValueType(0);
9368 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9369 const TargetRegisterClass *ArgRC =
9370 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9371 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9374 // At this point, we know that we perform a cross-register-bank copy.
9375 // Check if it is expensive.
9376 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9377 // Assume bitcasts are cheap, unless both register classes do not
9378 // explicitly share a common sub class.
9379 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9382 // Check if it will be merged with the load.
9383 // 1. Check the alignment constraint.
9384 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9385 ResVT.getTypeForEVT(*DAG->getContext()));
9387 if (RequiredAlignment > getAlignment())
9390 // 2. Check that the load is a legal operation for that type.
9391 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9394 // 3. Check that we do not have a zext in the way.
9395 if (Inst->getValueType(0) != getLoadedType())
9403 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9404 /// \p UsedBits looks like 0..0 1..1 0..0.
9405 static bool areUsedBitsDense(const APInt &UsedBits) {
9406 // If all the bits are one, this is dense!
9407 if (UsedBits.isAllOnesValue())
9410 // Get rid of the unused bits on the right.
9411 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9412 // Get rid of the unused bits on the left.
9413 if (NarrowedUsedBits.countLeadingZeros())
9414 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9415 // Check that the chunk of bits is completely used.
9416 return NarrowedUsedBits.isAllOnesValue();
9419 /// \brief Check whether or not \p First and \p Second are next to each other
9420 /// in memory. This means that there is no hole between the bits loaded
9421 /// by \p First and the bits loaded by \p Second.
9422 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9423 const LoadedSlice &Second) {
9424 assert(First.Origin == Second.Origin && First.Origin &&
9425 "Unable to match different memory origins.");
9426 APInt UsedBits = First.getUsedBits();
9427 assert((UsedBits & Second.getUsedBits()) == 0 &&
9428 "Slices are not supposed to overlap.");
9429 UsedBits |= Second.getUsedBits();
9430 return areUsedBitsDense(UsedBits);
9433 /// \brief Adjust the \p GlobalLSCost according to the target
9434 /// paring capabilities and the layout of the slices.
9435 /// \pre \p GlobalLSCost should account for at least as many loads as
9436 /// there is in the slices in \p LoadedSlices.
9437 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9438 LoadedSlice::Cost &GlobalLSCost) {
9439 unsigned NumberOfSlices = LoadedSlices.size();
9440 // If there is less than 2 elements, no pairing is possible.
9441 if (NumberOfSlices < 2)
9444 // Sort the slices so that elements that are likely to be next to each
9445 // other in memory are next to each other in the list.
9446 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9447 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9448 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9449 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9451 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9452 // First (resp. Second) is the first (resp. Second) potentially candidate
9453 // to be placed in a paired load.
9454 const LoadedSlice *First = nullptr;
9455 const LoadedSlice *Second = nullptr;
9456 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9457 // Set the beginning of the pair.
9460 Second = &LoadedSlices[CurrSlice];
9462 // If First is NULL, it means we start a new pair.
9463 // Get to the next slice.
9467 EVT LoadedType = First->getLoadedType();
9469 // If the types of the slices are different, we cannot pair them.
9470 if (LoadedType != Second->getLoadedType())
9473 // Check if the target supplies paired loads for this type.
9474 unsigned RequiredAlignment = 0;
9475 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9476 // move to the next pair, this type is hopeless.
9480 // Check if we meet the alignment requirement.
9481 if (RequiredAlignment > First->getAlignment())
9484 // Check that both loads are next to each other in memory.
9485 if (!areSlicesNextToEachOther(*First, *Second))
9488 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9489 --GlobalLSCost.Loads;
9490 // Move to the next pair.
9495 /// \brief Check the profitability of all involved LoadedSlice.
9496 /// Currently, it is considered profitable if there is exactly two
9497 /// involved slices (1) which are (2) next to each other in memory, and
9498 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9500 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9501 /// the elements themselves.
9503 /// FIXME: When the cost model will be mature enough, we can relax
9504 /// constraints (1) and (2).
9505 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9506 const APInt &UsedBits, bool ForCodeSize) {
9507 unsigned NumberOfSlices = LoadedSlices.size();
9508 if (StressLoadSlicing)
9509 return NumberOfSlices > 1;
9512 if (NumberOfSlices != 2)
9516 if (!areUsedBitsDense(UsedBits))
9520 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9521 // The original code has one big load.
9523 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9524 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9525 // Accumulate the cost of all the slices.
9526 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9527 GlobalSlicingCost += SliceCost;
9529 // Account as cost in the original configuration the gain obtained
9530 // with the current slices.
9531 OrigCost.addSliceGain(LS);
9534 // If the target supports paired load, adjust the cost accordingly.
9535 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9536 return OrigCost > GlobalSlicingCost;
9539 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9540 /// operations, split it in the various pieces being extracted.
9542 /// This sort of thing is introduced by SROA.
9543 /// This slicing takes care not to insert overlapping loads.
9544 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9545 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9546 if (Level < AfterLegalizeDAG)
9549 LoadSDNode *LD = cast<LoadSDNode>(N);
9550 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9551 !LD->getValueType(0).isInteger())
9554 // Keep track of already used bits to detect overlapping values.
9555 // In that case, we will just abort the transformation.
9556 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9558 SmallVector<LoadedSlice, 4> LoadedSlices;
9560 // Check if this load is used as several smaller chunks of bits.
9561 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9562 // of computation for each trunc.
9563 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9564 UI != UIEnd; ++UI) {
9565 // Skip the uses of the chain.
9566 if (UI.getUse().getResNo() != 0)
9572 // Check if this is a trunc(lshr).
9573 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9574 isa<ConstantSDNode>(User->getOperand(1))) {
9575 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9576 User = *User->use_begin();
9579 // At this point, User is a Truncate, iff we encountered, trunc or
9581 if (User->getOpcode() != ISD::TRUNCATE)
9584 // The width of the type must be a power of 2 and greater than 8-bits.
9585 // Otherwise the load cannot be represented in LLVM IR.
9586 // Moreover, if we shifted with a non-8-bits multiple, the slice
9587 // will be across several bytes. We do not support that.
9588 unsigned Width = User->getValueSizeInBits(0);
9589 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9592 // Build the slice for this chain of computations.
9593 LoadedSlice LS(User, LD, Shift, &DAG);
9594 APInt CurrentUsedBits = LS.getUsedBits();
9596 // Check if this slice overlaps with another.
9597 if ((CurrentUsedBits & UsedBits) != 0)
9599 // Update the bits used globally.
9600 UsedBits |= CurrentUsedBits;
9602 // Check if the new slice would be legal.
9606 // Record the slice.
9607 LoadedSlices.push_back(LS);
9610 // Abort slicing if it does not seem to be profitable.
9611 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9616 // Rewrite each chain to use an independent load.
9617 // By construction, each chain can be represented by a unique load.
9619 // Prepare the argument for the new token factor for all the slices.
9620 SmallVector<SDValue, 8> ArgChains;
9621 for (SmallVectorImpl<LoadedSlice>::const_iterator
9622 LSIt = LoadedSlices.begin(),
9623 LSItEnd = LoadedSlices.end();
9624 LSIt != LSItEnd; ++LSIt) {
9625 SDValue SliceInst = LSIt->loadSlice();
9626 CombineTo(LSIt->Inst, SliceInst, true);
9627 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9628 SliceInst = SliceInst.getOperand(0);
9629 assert(SliceInst->getOpcode() == ISD::LOAD &&
9630 "It takes more than a zext to get to the loaded slice!!");
9631 ArgChains.push_back(SliceInst.getValue(1));
9634 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9636 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9640 /// Check to see if V is (and load (ptr), imm), where the load is having
9641 /// specific bytes cleared out. If so, return the byte size being masked out
9642 /// and the shift amount.
9643 static std::pair<unsigned, unsigned>
9644 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9645 std::pair<unsigned, unsigned> Result(0, 0);
9647 // Check for the structure we're looking for.
9648 if (V->getOpcode() != ISD::AND ||
9649 !isa<ConstantSDNode>(V->getOperand(1)) ||
9650 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9653 // Check the chain and pointer.
9654 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9655 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9657 // The store should be chained directly to the load or be an operand of a
9659 if (LD == Chain.getNode())
9661 else if (Chain->getOpcode() != ISD::TokenFactor)
9662 return Result; // Fail.
9665 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9666 if (Chain->getOperand(i).getNode() == LD) {
9670 if (!isOk) return Result;
9673 // This only handles simple types.
9674 if (V.getValueType() != MVT::i16 &&
9675 V.getValueType() != MVT::i32 &&
9676 V.getValueType() != MVT::i64)
9679 // Check the constant mask. Invert it so that the bits being masked out are
9680 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9681 // follow the sign bit for uniformity.
9682 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9683 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9684 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9685 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9686 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9687 if (NotMaskLZ == 64) return Result; // All zero mask.
9689 // See if we have a continuous run of bits. If so, we have 0*1+0*
9690 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9693 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9694 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9695 NotMaskLZ -= 64-V.getValueSizeInBits();
9697 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9698 switch (MaskedBytes) {
9702 default: return Result; // All one mask, or 5-byte mask.
9705 // Verify that the first bit starts at a multiple of mask so that the access
9706 // is aligned the same as the access width.
9707 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9709 Result.first = MaskedBytes;
9710 Result.second = NotMaskTZ/8;
9715 /// Check to see if IVal is something that provides a value as specified by
9716 /// MaskInfo. If so, replace the specified store with a narrower store of
9719 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9720 SDValue IVal, StoreSDNode *St,
9722 unsigned NumBytes = MaskInfo.first;
9723 unsigned ByteShift = MaskInfo.second;
9724 SelectionDAG &DAG = DC->getDAG();
9726 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9727 // that uses this. If not, this is not a replacement.
9728 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9729 ByteShift*8, (ByteShift+NumBytes)*8);
9730 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9732 // Check that it is legal on the target to do this. It is legal if the new
9733 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9735 MVT VT = MVT::getIntegerVT(NumBytes*8);
9736 if (!DC->isTypeLegal(VT))
9739 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9740 // shifted by ByteShift and truncated down to NumBytes.
9742 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9743 DAG.getConstant(ByteShift*8,
9744 DC->getShiftAmountTy(IVal.getValueType())));
9746 // Figure out the offset for the store and the alignment of the access.
9748 unsigned NewAlign = St->getAlignment();
9750 if (DAG.getTargetLoweringInfo().isLittleEndian())
9751 StOffset = ByteShift;
9753 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9755 SDValue Ptr = St->getBasePtr();
9757 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9758 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9759 NewAlign = MinAlign(NewAlign, StOffset);
9762 // Truncate down to the new size.
9763 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9766 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9767 St->getPointerInfo().getWithOffset(StOffset),
9768 false, false, NewAlign).getNode();
9772 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9773 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9774 /// narrowing the load and store if it would end up being a win for performance
9776 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9777 StoreSDNode *ST = cast<StoreSDNode>(N);
9778 if (ST->isVolatile())
9781 SDValue Chain = ST->getChain();
9782 SDValue Value = ST->getValue();
9783 SDValue Ptr = ST->getBasePtr();
9784 EVT VT = Value.getValueType();
9786 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9789 unsigned Opc = Value.getOpcode();
9791 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9792 // is a byte mask indicating a consecutive number of bytes, check to see if
9793 // Y is known to provide just those bytes. If so, we try to replace the
9794 // load + replace + store sequence with a single (narrower) store, which makes
9796 if (Opc == ISD::OR) {
9797 std::pair<unsigned, unsigned> MaskedLoad;
9798 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9799 if (MaskedLoad.first)
9800 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9801 Value.getOperand(1), ST,this))
9802 return SDValue(NewST, 0);
9804 // Or is commutative, so try swapping X and Y.
9805 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9806 if (MaskedLoad.first)
9807 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9808 Value.getOperand(0), ST,this))
9809 return SDValue(NewST, 0);
9812 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9813 Value.getOperand(1).getOpcode() != ISD::Constant)
9816 SDValue N0 = Value.getOperand(0);
9817 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9818 Chain == SDValue(N0.getNode(), 1)) {
9819 LoadSDNode *LD = cast<LoadSDNode>(N0);
9820 if (LD->getBasePtr() != Ptr ||
9821 LD->getPointerInfo().getAddrSpace() !=
9822 ST->getPointerInfo().getAddrSpace())
9825 // Find the type to narrow it the load / op / store to.
9826 SDValue N1 = Value.getOperand(1);
9827 unsigned BitWidth = N1.getValueSizeInBits();
9828 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9829 if (Opc == ISD::AND)
9830 Imm ^= APInt::getAllOnesValue(BitWidth);
9831 if (Imm == 0 || Imm.isAllOnesValue())
9833 unsigned ShAmt = Imm.countTrailingZeros();
9834 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9835 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9836 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9837 // The narrowing should be profitable, the load/store operation should be
9838 // legal (or custom) and the store size should be equal to the NewVT width.
9839 while (NewBW < BitWidth &&
9840 (NewVT.getStoreSizeInBits() != NewBW ||
9841 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9842 !TLI.isNarrowingProfitable(VT, NewVT))) {
9843 NewBW = NextPowerOf2(NewBW);
9844 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9846 if (NewBW >= BitWidth)
9849 // If the lsb changed does not start at the type bitwidth boundary,
9850 // start at the previous one.
9852 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9853 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9854 std::min(BitWidth, ShAmt + NewBW));
9855 if ((Imm & Mask) == Imm) {
9856 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9857 if (Opc == ISD::AND)
9858 NewImm ^= APInt::getAllOnesValue(NewBW);
9859 uint64_t PtrOff = ShAmt / 8;
9860 // For big endian targets, we need to adjust the offset to the pointer to
9861 // load the correct bytes.
9862 if (TLI.isBigEndian())
9863 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9865 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9866 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9867 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9870 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9871 Ptr.getValueType(), Ptr,
9872 DAG.getConstant(PtrOff, Ptr.getValueType()));
9873 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9874 LD->getChain(), NewPtr,
9875 LD->getPointerInfo().getWithOffset(PtrOff),
9876 LD->isVolatile(), LD->isNonTemporal(),
9877 LD->isInvariant(), NewAlign,
9879 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9880 DAG.getConstant(NewImm, NewVT));
9881 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9883 ST->getPointerInfo().getWithOffset(PtrOff),
9884 false, false, NewAlign);
9886 AddToWorklist(NewPtr.getNode());
9887 AddToWorklist(NewLD.getNode());
9888 AddToWorklist(NewVal.getNode());
9889 WorklistRemover DeadNodes(*this);
9890 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9899 /// For a given floating point load / store pair, if the load value isn't used
9900 /// by any other operations, then consider transforming the pair to integer
9901 /// load / store operations if the target deems the transformation profitable.
9902 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9903 StoreSDNode *ST = cast<StoreSDNode>(N);
9904 SDValue Chain = ST->getChain();
9905 SDValue Value = ST->getValue();
9906 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9907 Value.hasOneUse() &&
9908 Chain == SDValue(Value.getNode(), 1)) {
9909 LoadSDNode *LD = cast<LoadSDNode>(Value);
9910 EVT VT = LD->getMemoryVT();
9911 if (!VT.isFloatingPoint() ||
9912 VT != ST->getMemoryVT() ||
9913 LD->isNonTemporal() ||
9914 ST->isNonTemporal() ||
9915 LD->getPointerInfo().getAddrSpace() != 0 ||
9916 ST->getPointerInfo().getAddrSpace() != 0)
9919 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9920 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9921 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9922 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9923 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9926 unsigned LDAlign = LD->getAlignment();
9927 unsigned STAlign = ST->getAlignment();
9928 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9929 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9930 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9933 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9934 LD->getChain(), LD->getBasePtr(),
9935 LD->getPointerInfo(),
9936 false, false, false, LDAlign);
9938 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9939 NewLD, ST->getBasePtr(),
9940 ST->getPointerInfo(),
9941 false, false, STAlign);
9943 AddToWorklist(NewLD.getNode());
9944 AddToWorklist(NewST.getNode());
9945 WorklistRemover DeadNodes(*this);
9946 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9954 /// Helper struct to parse and store a memory address as base + index + offset.
9955 /// We ignore sign extensions when it is safe to do so.
9956 /// The following two expressions are not equivalent. To differentiate we need
9957 /// to store whether there was a sign extension involved in the index
9959 /// (load (i64 add (i64 copyfromreg %c)
9960 /// (i64 signextend (add (i8 load %index)
9964 /// (load (i64 add (i64 copyfromreg %c)
9965 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9967 struct BaseIndexOffset {
9971 bool IsIndexSignExt;
9973 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9975 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9976 bool IsIndexSignExt) :
9977 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9979 bool equalBaseIndex(const BaseIndexOffset &Other) {
9980 return Other.Base == Base && Other.Index == Index &&
9981 Other.IsIndexSignExt == IsIndexSignExt;
9984 /// Parses tree in Ptr for base, index, offset addresses.
9985 static BaseIndexOffset match(SDValue Ptr) {
9986 bool IsIndexSignExt = false;
9988 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9989 // instruction, then it could be just the BASE or everything else we don't
9990 // know how to handle. Just use Ptr as BASE and give up.
9991 if (Ptr->getOpcode() != ISD::ADD)
9992 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9994 // We know that we have at least an ADD instruction. Try to pattern match
9995 // the simple case of BASE + OFFSET.
9996 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9997 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9998 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10002 // Inside a loop the current BASE pointer is calculated using an ADD and a
10003 // MUL instruction. In this case Ptr is the actual BASE pointer.
10004 // (i64 add (i64 %array_ptr)
10005 // (i64 mul (i64 %induction_var)
10006 // (i64 %element_size)))
10007 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10008 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10010 // Look at Base + Index + Offset cases.
10011 SDValue Base = Ptr->getOperand(0);
10012 SDValue IndexOffset = Ptr->getOperand(1);
10014 // Skip signextends.
10015 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10016 IndexOffset = IndexOffset->getOperand(0);
10017 IsIndexSignExt = true;
10020 // Either the case of Base + Index (no offset) or something else.
10021 if (IndexOffset->getOpcode() != ISD::ADD)
10022 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10024 // Now we have the case of Base + Index + offset.
10025 SDValue Index = IndexOffset->getOperand(0);
10026 SDValue Offset = IndexOffset->getOperand(1);
10028 if (!isa<ConstantSDNode>(Offset))
10029 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10031 // Ignore signextends.
10032 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10033 Index = Index->getOperand(0);
10034 IsIndexSignExt = true;
10035 } else IsIndexSignExt = false;
10037 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10038 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10042 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10043 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10044 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10045 // Make sure we have something to merge.
10049 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10050 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10051 unsigned EarliestNodeUsed = 0;
10053 for (unsigned i=0; i < NumElem; ++i) {
10054 // Find a chain for the new wide-store operand. Notice that some
10055 // of the store nodes that we found may not be selected for inclusion
10056 // in the wide store. The chain we use needs to be the chain of the
10057 // earliest store node which is *used* and replaced by the wide store.
10058 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10059 EarliestNodeUsed = i;
10062 // The earliest Node in the DAG.
10063 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10064 SDLoc DL(StoreNodes[0].MemNode);
10068 // Find a legal type for the vector store.
10069 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10070 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10071 if (IsConstantSrc) {
10072 // A vector store with a constant source implies that the constant is
10073 // zero; we only handle merging stores of constant zeros because the zero
10074 // can be materialized without a load.
10075 // It may be beneficial to loosen this restriction to allow non-zero
10077 StoredVal = DAG.getConstant(0, Ty);
10079 SmallVector<SDValue, 8> Ops;
10080 for (unsigned i = 0; i < NumElem ; ++i) {
10081 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10082 SDValue Val = St->getValue();
10083 // All of the operands of a BUILD_VECTOR must have the same type.
10084 if (Val.getValueType() != MemVT)
10086 Ops.push_back(Val);
10089 // Build the extracted vector elements back into a vector.
10090 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10093 // We should always use a vector store when merging extracted vector
10094 // elements, so this path implies a store of constants.
10095 assert(IsConstantSrc && "Merged vector elements should use vector store");
10097 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10098 APInt StoreInt(StoreBW, 0);
10100 // Construct a single integer constant which is made of the smaller
10101 // constant inputs.
10102 bool IsLE = TLI.isLittleEndian();
10103 for (unsigned i = 0; i < NumElem ; ++i) {
10104 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10105 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10106 SDValue Val = St->getValue();
10107 StoreInt <<= ElementSizeBytes*8;
10108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10109 StoreInt |= C->getAPIntValue().zext(StoreBW);
10110 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10111 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10113 llvm_unreachable("Invalid constant element type");
10117 // Create the new Load and Store operations.
10118 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10119 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10122 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10123 FirstInChain->getBasePtr(),
10124 FirstInChain->getPointerInfo(),
10126 FirstInChain->getAlignment());
10128 // Replace the first store with the new store
10129 CombineTo(EarliestOp, NewStore);
10130 // Erase all other stores.
10131 for (unsigned i = 0; i < NumElem ; ++i) {
10132 if (StoreNodes[i].MemNode == EarliestOp)
10134 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10135 // ReplaceAllUsesWith will replace all uses that existed when it was
10136 // called, but graph optimizations may cause new ones to appear. For
10137 // example, the case in pr14333 looks like
10139 // St's chain -> St -> another store -> X
10141 // And the only difference from St to the other store is the chain.
10142 // When we change it's chain to be St's chain they become identical,
10143 // get CSEed and the net result is that X is now a use of St.
10144 // Since we know that St is redundant, just iterate.
10145 while (!St->use_empty())
10146 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10147 deleteAndRecombine(St);
10153 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10154 if (OptLevel == CodeGenOpt::None)
10157 EVT MemVT = St->getMemoryVT();
10158 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10159 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10160 Attribute::NoImplicitFloat);
10162 // Don't merge vectors into wider inputs.
10163 if (MemVT.isVector() || !MemVT.isSimple())
10166 // Perform an early exit check. Do not bother looking at stored values that
10167 // are not constants, loads, or extracted vector elements.
10168 SDValue StoredVal = St->getValue();
10169 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10170 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10171 isa<ConstantFPSDNode>(StoredVal);
10172 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10174 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10177 // Only look at ends of store sequences.
10178 SDValue Chain = SDValue(St, 0);
10179 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10182 // This holds the base pointer, index, and the offset in bytes from the base
10184 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10186 // We must have a base and an offset.
10187 if (!BasePtr.Base.getNode())
10190 // Do not handle stores to undef base pointers.
10191 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10194 // Save the LoadSDNodes that we find in the chain.
10195 // We need to make sure that these nodes do not interfere with
10196 // any of the store nodes.
10197 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10199 // Save the StoreSDNodes that we find in the chain.
10200 SmallVector<MemOpLink, 8> StoreNodes;
10202 // Walk up the chain and look for nodes with offsets from the same
10203 // base pointer. Stop when reaching an instruction with a different kind
10204 // or instruction which has a different base pointer.
10206 StoreSDNode *Index = St;
10208 // If the chain has more than one use, then we can't reorder the mem ops.
10209 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10212 // Find the base pointer and offset for this memory node.
10213 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10215 // Check that the base pointer is the same as the original one.
10216 if (!Ptr.equalBaseIndex(BasePtr))
10219 // Check that the alignment is the same.
10220 if (Index->getAlignment() != St->getAlignment())
10223 // The memory operands must not be volatile.
10224 if (Index->isVolatile() || Index->isIndexed())
10228 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10229 if (St->isTruncatingStore())
10232 // The stored memory type must be the same.
10233 if (Index->getMemoryVT() != MemVT)
10236 // We do not allow unaligned stores because we want to prevent overriding
10238 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10241 // We found a potential memory operand to merge.
10242 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10244 // Find the next memory operand in the chain. If the next operand in the
10245 // chain is a store then move up and continue the scan with the next
10246 // memory operand. If the next operand is a load save it and use alias
10247 // information to check if it interferes with anything.
10248 SDNode *NextInChain = Index->getChain().getNode();
10250 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10251 // We found a store node. Use it for the next iteration.
10254 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10255 if (Ldn->isVolatile()) {
10260 // Save the load node for later. Continue the scan.
10261 AliasLoadNodes.push_back(Ldn);
10262 NextInChain = Ldn->getChain().getNode();
10271 // Check if there is anything to merge.
10272 if (StoreNodes.size() < 2)
10275 // Sort the memory operands according to their distance from the base pointer.
10276 std::sort(StoreNodes.begin(), StoreNodes.end(),
10277 [](MemOpLink LHS, MemOpLink RHS) {
10278 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10279 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10280 LHS.SequenceNum > RHS.SequenceNum);
10283 // Scan the memory operations on the chain and find the first non-consecutive
10284 // store memory address.
10285 unsigned LastConsecutiveStore = 0;
10286 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10287 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10289 // Check that the addresses are consecutive starting from the second
10290 // element in the list of stores.
10292 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10293 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10297 bool Alias = false;
10298 // Check if this store interferes with any of the loads that we found.
10299 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10300 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10304 // We found a load that alias with this store. Stop the sequence.
10308 // Mark this node as useful.
10309 LastConsecutiveStore = i;
10312 // The node with the lowest store address.
10313 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10315 // Store the constants into memory as one consecutive store.
10316 if (IsConstantSrc) {
10317 unsigned LastLegalType = 0;
10318 unsigned LastLegalVectorType = 0;
10319 bool NonZero = false;
10320 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10321 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10322 SDValue StoredVal = St->getValue();
10324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10325 NonZero |= !C->isNullValue();
10326 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10327 NonZero |= !C->getConstantFPValue()->isNullValue();
10333 // Find a legal type for the constant store.
10334 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10335 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10336 if (TLI.isTypeLegal(StoreTy))
10337 LastLegalType = i+1;
10338 // Or check whether a truncstore is legal.
10339 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10340 TargetLowering::TypePromoteInteger) {
10341 EVT LegalizedStoredValueTy =
10342 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10343 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10344 LastLegalType = i+1;
10347 // Find a legal type for the vector store.
10348 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10349 if (TLI.isTypeLegal(Ty))
10350 LastLegalVectorType = i + 1;
10353 // We only use vectors if the constant is known to be zero and the
10354 // function is not marked with the noimplicitfloat attribute.
10355 if (NonZero || NoVectors)
10356 LastLegalVectorType = 0;
10358 // Check if we found a legal integer type to store.
10359 if (LastLegalType == 0 && LastLegalVectorType == 0)
10362 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10363 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10365 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10369 // When extracting multiple vector elements, try to store them
10370 // in one vector store rather than a sequence of scalar stores.
10371 if (IsExtractVecEltSrc) {
10372 unsigned NumElem = 0;
10373 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10374 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10375 SDValue StoredVal = St->getValue();
10376 // This restriction could be loosened.
10377 // Bail out if any stored values are not elements extracted from a vector.
10378 // It should be possible to handle mixed sources, but load sources need
10379 // more careful handling (see the block of code below that handles
10380 // consecutive loads).
10381 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10384 // Find a legal type for the vector store.
10385 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10386 if (TLI.isTypeLegal(Ty))
10390 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10394 // Below we handle the case of multiple consecutive stores that
10395 // come from multiple consecutive loads. We merge them into a single
10396 // wide load and a single wide store.
10398 // Look for load nodes which are used by the stored values.
10399 SmallVector<MemOpLink, 8> LoadNodes;
10401 // Find acceptable loads. Loads need to have the same chain (token factor),
10402 // must not be zext, volatile, indexed, and they must be consecutive.
10403 BaseIndexOffset LdBasePtr;
10404 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10405 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10406 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10409 // Loads must only have one use.
10410 if (!Ld->hasNUsesOfValue(1, 0))
10413 // Check that the alignment is the same as the stores.
10414 if (Ld->getAlignment() != St->getAlignment())
10417 // The memory operands must not be volatile.
10418 if (Ld->isVolatile() || Ld->isIndexed())
10421 // We do not accept ext loads.
10422 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10425 // The stored memory type must be the same.
10426 if (Ld->getMemoryVT() != MemVT)
10429 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10430 // If this is not the first ptr that we check.
10431 if (LdBasePtr.Base.getNode()) {
10432 // The base ptr must be the same.
10433 if (!LdPtr.equalBaseIndex(LdBasePtr))
10436 // Check that all other base pointers are the same as this one.
10440 // We found a potential memory operand to merge.
10441 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10444 if (LoadNodes.size() < 2)
10447 // If we have load/store pair instructions and we only have two values,
10449 unsigned RequiredAlignment;
10450 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10451 St->getAlignment() >= RequiredAlignment)
10454 // Scan the memory operations on the chain and find the first non-consecutive
10455 // load memory address. These variables hold the index in the store node
10457 unsigned LastConsecutiveLoad = 0;
10458 // This variable refers to the size and not index in the array.
10459 unsigned LastLegalVectorType = 0;
10460 unsigned LastLegalIntegerType = 0;
10461 StartAddress = LoadNodes[0].OffsetFromBase;
10462 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10463 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10464 // All loads much share the same chain.
10465 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10468 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10469 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10471 LastConsecutiveLoad = i;
10473 // Find a legal type for the vector store.
10474 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10475 if (TLI.isTypeLegal(StoreTy))
10476 LastLegalVectorType = i + 1;
10478 // Find a legal type for the integer store.
10479 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10480 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10481 if (TLI.isTypeLegal(StoreTy))
10482 LastLegalIntegerType = i + 1;
10483 // Or check whether a truncstore and extload is legal.
10484 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10485 TargetLowering::TypePromoteInteger) {
10486 EVT LegalizedStoredValueTy =
10487 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10488 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10489 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10490 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10491 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10492 LastLegalIntegerType = i+1;
10496 // Only use vector types if the vector type is larger than the integer type.
10497 // If they are the same, use integers.
10498 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10499 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10501 // We add +1 here because the LastXXX variables refer to location while
10502 // the NumElem refers to array/index size.
10503 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10504 NumElem = std::min(LastLegalType, NumElem);
10509 // The earliest Node in the DAG.
10510 unsigned EarliestNodeUsed = 0;
10511 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10512 for (unsigned i=1; i<NumElem; ++i) {
10513 // Find a chain for the new wide-store operand. Notice that some
10514 // of the store nodes that we found may not be selected for inclusion
10515 // in the wide store. The chain we use needs to be the chain of the
10516 // earliest store node which is *used* and replaced by the wide store.
10517 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10518 EarliestNodeUsed = i;
10521 // Find if it is better to use vectors or integers to load and store
10525 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10527 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10528 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10531 SDLoc LoadDL(LoadNodes[0].MemNode);
10532 SDLoc StoreDL(StoreNodes[0].MemNode);
10534 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10535 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10536 FirstLoad->getChain(),
10537 FirstLoad->getBasePtr(),
10538 FirstLoad->getPointerInfo(),
10539 false, false, false,
10540 FirstLoad->getAlignment());
10542 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10543 FirstInChain->getBasePtr(),
10544 FirstInChain->getPointerInfo(), false, false,
10545 FirstInChain->getAlignment());
10547 // Replace one of the loads with the new load.
10548 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10549 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10550 SDValue(NewLoad.getNode(), 1));
10552 // Remove the rest of the load chains.
10553 for (unsigned i = 1; i < NumElem ; ++i) {
10554 // Replace all chain users of the old load nodes with the chain of the new
10556 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10557 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10560 // Replace the first store with the new store.
10561 CombineTo(EarliestOp, NewStore);
10562 // Erase all other stores.
10563 for (unsigned i = 0; i < NumElem ; ++i) {
10564 // Remove all Store nodes.
10565 if (StoreNodes[i].MemNode == EarliestOp)
10567 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10568 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10569 deleteAndRecombine(St);
10575 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10576 StoreSDNode *ST = cast<StoreSDNode>(N);
10577 SDValue Chain = ST->getChain();
10578 SDValue Value = ST->getValue();
10579 SDValue Ptr = ST->getBasePtr();
10581 // If this is a store of a bit convert, store the input value if the
10582 // resultant store does not need a higher alignment than the original.
10583 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10584 ST->isUnindexed()) {
10585 unsigned OrigAlign = ST->getAlignment();
10586 EVT SVT = Value.getOperand(0).getValueType();
10587 unsigned Align = TLI.getDataLayout()->
10588 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10589 if (Align <= OrigAlign &&
10590 ((!LegalOperations && !ST->isVolatile()) ||
10591 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10592 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10593 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10594 ST->isNonTemporal(), OrigAlign,
10598 // Turn 'store undef, Ptr' -> nothing.
10599 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10602 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10603 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10604 // NOTE: If the original store is volatile, this transform must not increase
10605 // the number of stores. For example, on x86-32 an f64 can be stored in one
10606 // processor operation but an i64 (which is not legal) requires two. So the
10607 // transform should not be done in this case.
10608 if (Value.getOpcode() != ISD::TargetConstantFP) {
10610 switch (CFP->getSimpleValueType(0).SimpleTy) {
10611 default: llvm_unreachable("Unknown FP type");
10612 case MVT::f16: // We don't do this for these yet.
10618 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10619 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10620 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10621 bitcastToAPInt().getZExtValue(), MVT::i32);
10622 return DAG.getStore(Chain, SDLoc(N), Tmp,
10623 Ptr, ST->getMemOperand());
10627 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10628 !ST->isVolatile()) ||
10629 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10630 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10631 getZExtValue(), MVT::i64);
10632 return DAG.getStore(Chain, SDLoc(N), Tmp,
10633 Ptr, ST->getMemOperand());
10636 if (!ST->isVolatile() &&
10637 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10638 // Many FP stores are not made apparent until after legalize, e.g. for
10639 // argument passing. Since this is so common, custom legalize the
10640 // 64-bit integer store into two 32-bit stores.
10641 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10642 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10643 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10644 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10646 unsigned Alignment = ST->getAlignment();
10647 bool isVolatile = ST->isVolatile();
10648 bool isNonTemporal = ST->isNonTemporal();
10649 AAMDNodes AAInfo = ST->getAAInfo();
10651 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10652 Ptr, ST->getPointerInfo(),
10653 isVolatile, isNonTemporal,
10654 ST->getAlignment(), AAInfo);
10655 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10656 DAG.getConstant(4, Ptr.getValueType()));
10657 Alignment = MinAlign(Alignment, 4U);
10658 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10659 Ptr, ST->getPointerInfo().getWithOffset(4),
10660 isVolatile, isNonTemporal,
10661 Alignment, AAInfo);
10662 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10671 // Try to infer better alignment information than the store already has.
10672 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10673 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10674 if (Align > ST->getAlignment())
10675 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10676 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10677 ST->isVolatile(), ST->isNonTemporal(), Align,
10682 // Try transforming a pair floating point load / store ops to integer
10683 // load / store ops.
10684 SDValue NewST = TransformFPLoadStorePair(N);
10685 if (NewST.getNode())
10688 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10689 : DAG.getSubtarget().useAA();
10691 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10692 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10695 if (UseAA && ST->isUnindexed()) {
10696 // Walk up chain skipping non-aliasing memory nodes.
10697 SDValue BetterChain = FindBetterChain(N, Chain);
10699 // If there is a better chain.
10700 if (Chain != BetterChain) {
10703 // Replace the chain to avoid dependency.
10704 if (ST->isTruncatingStore()) {
10705 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10706 ST->getMemoryVT(), ST->getMemOperand());
10708 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10709 ST->getMemOperand());
10712 // Create token to keep both nodes around.
10713 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10714 MVT::Other, Chain, ReplStore);
10716 // Make sure the new and old chains are cleaned up.
10717 AddToWorklist(Token.getNode());
10719 // Don't add users to work list.
10720 return CombineTo(N, Token, false);
10724 // Try transforming N to an indexed store.
10725 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10726 return SDValue(N, 0);
10728 // FIXME: is there such a thing as a truncating indexed store?
10729 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10730 Value.getValueType().isInteger()) {
10731 // See if we can simplify the input to this truncstore with knowledge that
10732 // only the low bits are being used. For example:
10733 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10735 GetDemandedBits(Value,
10736 APInt::getLowBitsSet(
10737 Value.getValueType().getScalarType().getSizeInBits(),
10738 ST->getMemoryVT().getScalarType().getSizeInBits()));
10739 AddToWorklist(Value.getNode());
10740 if (Shorter.getNode())
10741 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10742 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10744 // Otherwise, see if we can simplify the operation with
10745 // SimplifyDemandedBits, which only works if the value has a single use.
10746 if (SimplifyDemandedBits(Value,
10747 APInt::getLowBitsSet(
10748 Value.getValueType().getScalarType().getSizeInBits(),
10749 ST->getMemoryVT().getScalarType().getSizeInBits())))
10750 return SDValue(N, 0);
10753 // If this is a load followed by a store to the same location, then the store
10755 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10756 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10757 ST->isUnindexed() && !ST->isVolatile() &&
10758 // There can't be any side effects between the load and store, such as
10759 // a call or store.
10760 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10761 // The store is dead, remove it.
10766 // If this is a store followed by a store with the same value to the same
10767 // location, then the store is dead/noop.
10768 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10769 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10770 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10771 ST1->isUnindexed() && !ST1->isVolatile()) {
10772 // The store is dead, remove it.
10777 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10778 // truncating store. We can do this even if this is already a truncstore.
10779 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10780 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10781 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10782 ST->getMemoryVT())) {
10783 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10784 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10787 // Only perform this optimization before the types are legal, because we
10788 // don't want to perform this optimization on every DAGCombine invocation.
10790 bool EverChanged = false;
10793 // There can be multiple store sequences on the same chain.
10794 // Keep trying to merge store sequences until we are unable to do so
10795 // or until we merge the last store on the chain.
10796 bool Changed = MergeConsecutiveStores(ST);
10797 EverChanged |= Changed;
10798 if (!Changed) break;
10799 } while (ST->getOpcode() != ISD::DELETED_NODE);
10802 return SDValue(N, 0);
10805 return ReduceLoadOpStoreWidth(N);
10808 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10809 SDValue InVec = N->getOperand(0);
10810 SDValue InVal = N->getOperand(1);
10811 SDValue EltNo = N->getOperand(2);
10814 // If the inserted element is an UNDEF, just use the input vector.
10815 if (InVal.getOpcode() == ISD::UNDEF)
10818 EVT VT = InVec.getValueType();
10820 // If we can't generate a legal BUILD_VECTOR, exit
10821 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10824 // Check that we know which element is being inserted
10825 if (!isa<ConstantSDNode>(EltNo))
10827 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10829 // Canonicalize insert_vector_elt dag nodes.
10831 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10832 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10834 // Do this only if the child insert_vector node has one use; also
10835 // do this only if indices are both constants and Idx1 < Idx0.
10836 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10837 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10838 unsigned OtherElt =
10839 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10840 if (Elt < OtherElt) {
10842 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10843 InVec.getOperand(0), InVal, EltNo);
10844 AddToWorklist(NewOp.getNode());
10845 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10846 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10850 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10851 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10852 // vector elements.
10853 SmallVector<SDValue, 8> Ops;
10854 // Do not combine these two vectors if the output vector will not replace
10855 // the input vector.
10856 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10857 Ops.append(InVec.getNode()->op_begin(),
10858 InVec.getNode()->op_end());
10859 } else if (InVec.getOpcode() == ISD::UNDEF) {
10860 unsigned NElts = VT.getVectorNumElements();
10861 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10866 // Insert the element
10867 if (Elt < Ops.size()) {
10868 // All the operands of BUILD_VECTOR must have the same type;
10869 // we enforce that here.
10870 EVT OpVT = Ops[0].getValueType();
10871 if (InVal.getValueType() != OpVT)
10872 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10873 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10874 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10878 // Return the new vector
10879 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10882 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10883 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10884 EVT ResultVT = EVE->getValueType(0);
10885 EVT VecEltVT = InVecVT.getVectorElementType();
10886 unsigned Align = OriginalLoad->getAlignment();
10887 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10888 VecEltVT.getTypeForEVT(*DAG.getContext()));
10890 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10895 SDValue NewPtr = OriginalLoad->getBasePtr();
10897 EVT PtrType = NewPtr.getValueType();
10898 MachinePointerInfo MPI;
10899 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10900 int Elt = ConstEltNo->getZExtValue();
10901 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10902 if (TLI.isBigEndian())
10903 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10904 Offset = DAG.getConstant(PtrOff, PtrType);
10905 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10907 Offset = DAG.getNode(
10908 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10909 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10910 if (TLI.isBigEndian())
10911 Offset = DAG.getNode(
10912 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10913 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10914 MPI = OriginalLoad->getPointerInfo();
10916 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10918 // The replacement we need to do here is a little tricky: we need to
10919 // replace an extractelement of a load with a load.
10920 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10921 // Note that this replacement assumes that the extractvalue is the only
10922 // use of the load; that's okay because we don't want to perform this
10923 // transformation in other cases anyway.
10926 if (ResultVT.bitsGT(VecEltVT)) {
10927 // If the result type of vextract is wider than the load, then issue an
10928 // extending load instead.
10929 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10933 Load = DAG.getExtLoad(
10934 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10935 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10936 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10937 Chain = Load.getValue(1);
10939 Load = DAG.getLoad(
10940 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10941 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10942 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10943 Chain = Load.getValue(1);
10944 if (ResultVT.bitsLT(VecEltVT))
10945 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10947 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10949 WorklistRemover DeadNodes(*this);
10950 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10951 SDValue To[] = { Load, Chain };
10952 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10953 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10954 // worklist explicitly as well.
10955 AddToWorklist(Load.getNode());
10956 AddUsersToWorklist(Load.getNode()); // Add users too
10957 // Make sure to revisit this node to clean it up; it will usually be dead.
10958 AddToWorklist(EVE);
10960 return SDValue(EVE, 0);
10963 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10964 // (vextract (scalar_to_vector val, 0) -> val
10965 SDValue InVec = N->getOperand(0);
10966 EVT VT = InVec.getValueType();
10967 EVT NVT = N->getValueType(0);
10969 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10970 // Check if the result type doesn't match the inserted element type. A
10971 // SCALAR_TO_VECTOR may truncate the inserted element and the
10972 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10973 SDValue InOp = InVec.getOperand(0);
10974 if (InOp.getValueType() != NVT) {
10975 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10976 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10981 SDValue EltNo = N->getOperand(1);
10982 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10984 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10985 // We only perform this optimization before the op legalization phase because
10986 // we may introduce new vector instructions which are not backed by TD
10987 // patterns. For example on AVX, extracting elements from a wide vector
10988 // without using extract_subvector. However, if we can find an underlying
10989 // scalar value, then we can always use that.
10990 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10992 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10993 int NumElem = VT.getVectorNumElements();
10994 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10995 // Find the new index to extract from.
10996 int OrigElt = SVOp->getMaskElt(Elt);
10998 // Extracting an undef index is undef.
11000 return DAG.getUNDEF(NVT);
11002 // Select the right vector half to extract from.
11004 if (OrigElt < NumElem) {
11005 SVInVec = InVec->getOperand(0);
11007 SVInVec = InVec->getOperand(1);
11008 OrigElt -= NumElem;
11011 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11012 SDValue InOp = SVInVec.getOperand(OrigElt);
11013 if (InOp.getValueType() != NVT) {
11014 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11015 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11021 // FIXME: We should handle recursing on other vector shuffles and
11022 // scalar_to_vector here as well.
11024 if (!LegalOperations) {
11025 EVT IndexTy = TLI.getVectorIdxTy();
11026 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11027 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11031 bool BCNumEltsChanged = false;
11032 EVT ExtVT = VT.getVectorElementType();
11035 // If the result of load has to be truncated, then it's not necessarily
11037 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11040 if (InVec.getOpcode() == ISD::BITCAST) {
11041 // Don't duplicate a load with other uses.
11042 if (!InVec.hasOneUse())
11045 EVT BCVT = InVec.getOperand(0).getValueType();
11046 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11048 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11049 BCNumEltsChanged = true;
11050 InVec = InVec.getOperand(0);
11051 ExtVT = BCVT.getVectorElementType();
11054 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11055 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11056 ISD::isNormalLoad(InVec.getNode()) &&
11057 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11058 SDValue Index = N->getOperand(1);
11059 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11060 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11064 // Perform only after legalization to ensure build_vector / vector_shuffle
11065 // optimizations have already been done.
11066 if (!LegalOperations) return SDValue();
11068 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11069 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11070 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11073 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11075 LoadSDNode *LN0 = nullptr;
11076 const ShuffleVectorSDNode *SVN = nullptr;
11077 if (ISD::isNormalLoad(InVec.getNode())) {
11078 LN0 = cast<LoadSDNode>(InVec);
11079 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11080 InVec.getOperand(0).getValueType() == ExtVT &&
11081 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11082 // Don't duplicate a load with other uses.
11083 if (!InVec.hasOneUse())
11086 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11087 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11088 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11090 // (load $addr+1*size)
11092 // Don't duplicate a load with other uses.
11093 if (!InVec.hasOneUse())
11096 // If the bit convert changed the number of elements, it is unsafe
11097 // to examine the mask.
11098 if (BCNumEltsChanged)
11101 // Select the input vector, guarding against out of range extract vector.
11102 unsigned NumElems = VT.getVectorNumElements();
11103 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11104 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11106 if (InVec.getOpcode() == ISD::BITCAST) {
11107 // Don't duplicate a load with other uses.
11108 if (!InVec.hasOneUse())
11111 InVec = InVec.getOperand(0);
11113 if (ISD::isNormalLoad(InVec.getNode())) {
11114 LN0 = cast<LoadSDNode>(InVec);
11115 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11116 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11120 // Make sure we found a non-volatile load and the extractelement is
11122 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11125 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11127 return DAG.getUNDEF(LVT);
11129 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11135 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11136 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11137 // We perform this optimization post type-legalization because
11138 // the type-legalizer often scalarizes integer-promoted vectors.
11139 // Performing this optimization before may create bit-casts which
11140 // will be type-legalized to complex code sequences.
11141 // We perform this optimization only before the operation legalizer because we
11142 // may introduce illegal operations.
11143 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11146 unsigned NumInScalars = N->getNumOperands();
11148 EVT VT = N->getValueType(0);
11150 // Check to see if this is a BUILD_VECTOR of a bunch of values
11151 // which come from any_extend or zero_extend nodes. If so, we can create
11152 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11153 // optimizations. We do not handle sign-extend because we can't fill the sign
11155 EVT SourceType = MVT::Other;
11156 bool AllAnyExt = true;
11158 for (unsigned i = 0; i != NumInScalars; ++i) {
11159 SDValue In = N->getOperand(i);
11160 // Ignore undef inputs.
11161 if (In.getOpcode() == ISD::UNDEF) continue;
11163 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11164 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11166 // Abort if the element is not an extension.
11167 if (!ZeroExt && !AnyExt) {
11168 SourceType = MVT::Other;
11172 // The input is a ZeroExt or AnyExt. Check the original type.
11173 EVT InTy = In.getOperand(0).getValueType();
11175 // Check that all of the widened source types are the same.
11176 if (SourceType == MVT::Other)
11179 else if (InTy != SourceType) {
11180 // Multiple income types. Abort.
11181 SourceType = MVT::Other;
11185 // Check if all of the extends are ANY_EXTENDs.
11186 AllAnyExt &= AnyExt;
11189 // In order to have valid types, all of the inputs must be extended from the
11190 // same source type and all of the inputs must be any or zero extend.
11191 // Scalar sizes must be a power of two.
11192 EVT OutScalarTy = VT.getScalarType();
11193 bool ValidTypes = SourceType != MVT::Other &&
11194 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11195 isPowerOf2_32(SourceType.getSizeInBits());
11197 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11198 // turn into a single shuffle instruction.
11202 bool isLE = TLI.isLittleEndian();
11203 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11204 assert(ElemRatio > 1 && "Invalid element size ratio");
11205 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11206 DAG.getConstant(0, SourceType);
11208 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11209 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11211 // Populate the new build_vector
11212 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11213 SDValue Cast = N->getOperand(i);
11214 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11215 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11216 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11218 if (Cast.getOpcode() == ISD::UNDEF)
11219 In = DAG.getUNDEF(SourceType);
11221 In = Cast->getOperand(0);
11222 unsigned Index = isLE ? (i * ElemRatio) :
11223 (i * ElemRatio + (ElemRatio - 1));
11225 assert(Index < Ops.size() && "Invalid index");
11229 // The type of the new BUILD_VECTOR node.
11230 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11231 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11232 "Invalid vector size");
11233 // Check if the new vector type is legal.
11234 if (!isTypeLegal(VecVT)) return SDValue();
11236 // Make the new BUILD_VECTOR.
11237 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11239 // The new BUILD_VECTOR node has the potential to be further optimized.
11240 AddToWorklist(BV.getNode());
11241 // Bitcast to the desired type.
11242 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11245 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11246 EVT VT = N->getValueType(0);
11248 unsigned NumInScalars = N->getNumOperands();
11251 EVT SrcVT = MVT::Other;
11252 unsigned Opcode = ISD::DELETED_NODE;
11253 unsigned NumDefs = 0;
11255 for (unsigned i = 0; i != NumInScalars; ++i) {
11256 SDValue In = N->getOperand(i);
11257 unsigned Opc = In.getOpcode();
11259 if (Opc == ISD::UNDEF)
11262 // If all scalar values are floats and converted from integers.
11263 if (Opcode == ISD::DELETED_NODE &&
11264 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11271 EVT InVT = In.getOperand(0).getValueType();
11273 // If all scalar values are typed differently, bail out. It's chosen to
11274 // simplify BUILD_VECTOR of integer types.
11275 if (SrcVT == MVT::Other)
11282 // If the vector has just one element defined, it's not worth to fold it into
11283 // a vectorized one.
11287 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11288 && "Should only handle conversion from integer to float.");
11289 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11291 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11293 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11296 // Just because the floating-point vector type is legal does not necessarily
11297 // mean that the corresponding integer vector type is.
11298 if (!isTypeLegal(NVT))
11301 SmallVector<SDValue, 8> Opnds;
11302 for (unsigned i = 0; i != NumInScalars; ++i) {
11303 SDValue In = N->getOperand(i);
11305 if (In.getOpcode() == ISD::UNDEF)
11306 Opnds.push_back(DAG.getUNDEF(SrcVT));
11308 Opnds.push_back(In.getOperand(0));
11310 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11311 AddToWorklist(BV.getNode());
11313 return DAG.getNode(Opcode, dl, VT, BV);
11316 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11317 unsigned NumInScalars = N->getNumOperands();
11319 EVT VT = N->getValueType(0);
11321 // A vector built entirely of undefs is undef.
11322 if (ISD::allOperandsUndef(N))
11323 return DAG.getUNDEF(VT);
11325 SDValue V = reduceBuildVecExtToExtBuildVec(N);
11329 V = reduceBuildVecConvertToConvertBuildVec(N);
11333 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11334 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11335 // at most two distinct vectors, turn this into a shuffle node.
11337 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11338 if (!isTypeLegal(VT))
11341 // May only combine to shuffle after legalize if shuffle is legal.
11342 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11345 SDValue VecIn1, VecIn2;
11346 bool UsesZeroVector = false;
11347 for (unsigned i = 0; i != NumInScalars; ++i) {
11348 SDValue Op = N->getOperand(i);
11349 // Ignore undef inputs.
11350 if (Op.getOpcode() == ISD::UNDEF) continue;
11352 // See if we can combine this build_vector into a blend with a zero vector.
11353 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11354 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11355 (Op.getOpcode() == ISD::ConstantFP &&
11356 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11357 UsesZeroVector = true;
11361 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11362 // constant index, bail out.
11363 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11364 !isa<ConstantSDNode>(Op.getOperand(1))) {
11365 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11369 // We allow up to two distinct input vectors.
11370 SDValue ExtractedFromVec = Op.getOperand(0);
11371 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11374 if (!VecIn1.getNode()) {
11375 VecIn1 = ExtractedFromVec;
11376 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11377 VecIn2 = ExtractedFromVec;
11379 // Too many inputs.
11380 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11385 // If everything is good, we can make a shuffle operation.
11386 if (VecIn1.getNode()) {
11387 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11388 SmallVector<int, 8> Mask;
11389 for (unsigned i = 0; i != NumInScalars; ++i) {
11390 unsigned Opcode = N->getOperand(i).getOpcode();
11391 if (Opcode == ISD::UNDEF) {
11392 Mask.push_back(-1);
11396 // Operands can also be zero.
11397 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11398 assert(UsesZeroVector &&
11399 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11400 "Unexpected node found!");
11401 Mask.push_back(NumInScalars+i);
11405 // If extracting from the first vector, just use the index directly.
11406 SDValue Extract = N->getOperand(i);
11407 SDValue ExtVal = Extract.getOperand(1);
11408 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11409 if (Extract.getOperand(0) == VecIn1) {
11410 Mask.push_back(ExtIndex);
11414 // Otherwise, use InIdx + InputVecSize
11415 Mask.push_back(InNumElements + ExtIndex);
11418 // Avoid introducing illegal shuffles with zero.
11419 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11422 // We can't generate a shuffle node with mismatched input and output types.
11423 // Attempt to transform a single input vector to the correct type.
11424 if ((VT != VecIn1.getValueType())) {
11425 // If the input vector type has a different base type to the output
11426 // vector type, bail out.
11427 EVT VTElemType = VT.getVectorElementType();
11428 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11429 (VecIn2.getNode() &&
11430 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11433 // If the input vector is too small, widen it.
11434 // We only support widening of vectors which are half the size of the
11435 // output registers. For example XMM->YMM widening on X86 with AVX.
11436 EVT VecInT = VecIn1.getValueType();
11437 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11438 // If we only have one small input, widen it by adding undef values.
11439 if (!VecIn2.getNode())
11440 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11441 DAG.getUNDEF(VecIn1.getValueType()));
11442 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11443 // If we have two small inputs of the same type, try to concat them.
11444 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11445 VecIn2 = SDValue(nullptr, 0);
11448 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11449 // If the input vector is too large, try to split it.
11450 // We don't support having two input vectors that are too large.
11451 // If the zero vector was used, we can not split the vector,
11452 // since we'd need 3 inputs.
11453 if (UsesZeroVector || VecIn2.getNode())
11456 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11459 // Try to replace VecIn1 with two extract_subvectors
11460 // No need to update the masks, they should still be correct.
11461 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11462 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11463 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11464 DAG.getConstant(0, TLI.getVectorIdxTy()));
11469 if (UsesZeroVector)
11470 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11471 DAG.getConstantFP(0.0, VT);
11473 // If VecIn2 is unused then change it to undef.
11474 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11476 // Check that we were able to transform all incoming values to the same
11478 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11479 VecIn1.getValueType() != VT)
11482 // Return the new VECTOR_SHUFFLE node.
11486 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11492 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11493 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11494 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11495 // inputs come from at most two distinct vectors, turn this into a shuffle
11498 // If we only have one input vector, we don't need to do any concatenation.
11499 if (N->getNumOperands() == 1)
11500 return N->getOperand(0);
11502 // Check if all of the operands are undefs.
11503 EVT VT = N->getValueType(0);
11504 if (ISD::allOperandsUndef(N))
11505 return DAG.getUNDEF(VT);
11507 // Optimize concat_vectors where one of the vectors is undef.
11508 if (N->getNumOperands() == 2 &&
11509 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11510 SDValue In = N->getOperand(0);
11511 assert(In.getValueType().isVector() && "Must concat vectors");
11513 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11514 if (In->getOpcode() == ISD::BITCAST &&
11515 !In->getOperand(0)->getValueType(0).isVector()) {
11516 SDValue Scalar = In->getOperand(0);
11517 EVT SclTy = Scalar->getValueType(0);
11519 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11522 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11523 VT.getSizeInBits() / SclTy.getSizeInBits());
11524 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11527 SDLoc dl = SDLoc(N);
11528 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11529 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11533 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11534 // We have already tested above for an UNDEF only concatenation.
11535 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11536 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11537 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11538 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11540 bool AllBuildVectorsOrUndefs =
11541 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11542 if (AllBuildVectorsOrUndefs) {
11543 SmallVector<SDValue, 8> Opnds;
11544 EVT SVT = VT.getScalarType();
11547 if (!SVT.isFloatingPoint()) {
11548 // If BUILD_VECTOR are from built from integer, they may have different
11549 // operand types. Get the smallest type and truncate all operands to it.
11550 bool FoundMinVT = false;
11551 for (const SDValue &Op : N->ops())
11552 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11553 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11554 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11557 assert(FoundMinVT && "Concat vector type mismatch");
11560 for (const SDValue &Op : N->ops()) {
11561 EVT OpVT = Op.getValueType();
11562 unsigned NumElts = OpVT.getVectorNumElements();
11564 if (ISD::UNDEF == Op.getOpcode())
11565 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11567 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11568 if (SVT.isFloatingPoint()) {
11569 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11570 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11572 for (unsigned i = 0; i != NumElts; ++i)
11574 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11579 assert(VT.getVectorNumElements() == Opnds.size() &&
11580 "Concat vector type mismatch");
11581 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11584 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11585 // nodes often generate nop CONCAT_VECTOR nodes.
11586 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11587 // place the incoming vectors at the exact same location.
11588 SDValue SingleSource = SDValue();
11589 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11591 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11592 SDValue Op = N->getOperand(i);
11594 if (Op.getOpcode() == ISD::UNDEF)
11597 // Check if this is the identity extract:
11598 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11601 // Find the single incoming vector for the extract_subvector.
11602 if (SingleSource.getNode()) {
11603 if (Op.getOperand(0) != SingleSource)
11606 SingleSource = Op.getOperand(0);
11608 // Check the source type is the same as the type of the result.
11609 // If not, this concat may extend the vector, so we can not
11610 // optimize it away.
11611 if (SingleSource.getValueType() != N->getValueType(0))
11615 unsigned IdentityIndex = i * PartNumElem;
11616 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11617 // The extract index must be constant.
11621 // Check that we are reading from the identity index.
11622 if (CS->getZExtValue() != IdentityIndex)
11626 if (SingleSource.getNode())
11627 return SingleSource;
11632 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11633 EVT NVT = N->getValueType(0);
11634 SDValue V = N->getOperand(0);
11636 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11638 // (extract_subvec (concat V1, V2, ...), i)
11641 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11643 if (V->getOperand(0).getValueType() != NVT)
11645 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11646 unsigned NumElems = NVT.getVectorNumElements();
11647 assert((Idx % NumElems) == 0 &&
11648 "IDX in concat is not a multiple of the result vector length.");
11649 return V->getOperand(Idx / NumElems);
11653 if (V->getOpcode() == ISD::BITCAST)
11654 V = V.getOperand(0);
11656 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11658 // Handle only simple case where vector being inserted and vector
11659 // being extracted are of same type, and are half size of larger vectors.
11660 EVT BigVT = V->getOperand(0).getValueType();
11661 EVT SmallVT = V->getOperand(1).getValueType();
11662 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11665 // Only handle cases where both indexes are constants with the same type.
11666 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11667 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11669 if (InsIdx && ExtIdx &&
11670 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11671 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11673 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11675 // indices are equal or bit offsets are equal => V1
11676 // otherwise => (extract_subvec V1, ExtIdx)
11677 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11678 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11679 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11680 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11681 DAG.getNode(ISD::BITCAST, dl,
11682 N->getOperand(0).getValueType(),
11683 V->getOperand(0)), N->getOperand(1));
11690 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11691 SDValue V, SelectionDAG &DAG) {
11693 EVT VT = V.getValueType();
11695 switch (V.getOpcode()) {
11699 case ISD::CONCAT_VECTORS: {
11700 EVT OpVT = V->getOperand(0).getValueType();
11701 int OpSize = OpVT.getVectorNumElements();
11702 SmallBitVector OpUsedElements(OpSize, false);
11703 bool FoundSimplification = false;
11704 SmallVector<SDValue, 4> NewOps;
11705 NewOps.reserve(V->getNumOperands());
11706 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11707 SDValue Op = V->getOperand(i);
11708 bool OpUsed = false;
11709 for (int j = 0; j < OpSize; ++j)
11710 if (UsedElements[i * OpSize + j]) {
11711 OpUsedElements[j] = true;
11715 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11716 : DAG.getUNDEF(OpVT));
11717 FoundSimplification |= Op == NewOps.back();
11718 OpUsedElements.reset();
11720 if (FoundSimplification)
11721 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11725 case ISD::INSERT_SUBVECTOR: {
11726 SDValue BaseV = V->getOperand(0);
11727 SDValue SubV = V->getOperand(1);
11728 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11732 int SubSize = SubV.getValueType().getVectorNumElements();
11733 int Idx = IdxN->getZExtValue();
11734 bool SubVectorUsed = false;
11735 SmallBitVector SubUsedElements(SubSize, false);
11736 for (int i = 0; i < SubSize; ++i)
11737 if (UsedElements[i + Idx]) {
11738 SubVectorUsed = true;
11739 SubUsedElements[i] = true;
11740 UsedElements[i + Idx] = false;
11743 // Now recurse on both the base and sub vectors.
11744 SDValue SimplifiedSubV =
11746 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11747 : DAG.getUNDEF(SubV.getValueType());
11748 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11749 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11750 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11751 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11757 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11758 SDValue N1, SelectionDAG &DAG) {
11759 EVT VT = SVN->getValueType(0);
11760 int NumElts = VT.getVectorNumElements();
11761 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11762 for (int M : SVN->getMask())
11763 if (M >= 0 && M < NumElts)
11764 N0UsedElements[M] = true;
11765 else if (M >= NumElts)
11766 N1UsedElements[M - NumElts] = true;
11768 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11769 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11770 if (S0 == N0 && S1 == N1)
11773 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11776 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11777 // or turn a shuffle of a single concat into simpler shuffle then concat.
11778 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11779 EVT VT = N->getValueType(0);
11780 unsigned NumElts = VT.getVectorNumElements();
11782 SDValue N0 = N->getOperand(0);
11783 SDValue N1 = N->getOperand(1);
11784 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11786 SmallVector<SDValue, 4> Ops;
11787 EVT ConcatVT = N0.getOperand(0).getValueType();
11788 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11789 unsigned NumConcats = NumElts / NumElemsPerConcat;
11791 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11792 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11793 // half vector elements.
11794 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11795 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11796 SVN->getMask().end(), [](int i) { return i == -1; })) {
11797 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11798 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11799 N1 = DAG.getUNDEF(ConcatVT);
11800 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11803 // Look at every vector that's inserted. We're looking for exact
11804 // subvector-sized copies from a concatenated vector
11805 for (unsigned I = 0; I != NumConcats; ++I) {
11806 // Make sure we're dealing with a copy.
11807 unsigned Begin = I * NumElemsPerConcat;
11808 bool AllUndef = true, NoUndef = true;
11809 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11810 if (SVN->getMaskElt(J) >= 0)
11817 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11820 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11821 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11824 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11825 if (FirstElt < N0.getNumOperands())
11826 Ops.push_back(N0.getOperand(FirstElt));
11828 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11830 } else if (AllUndef) {
11831 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11832 } else { // Mixed with general masks and undefs, can't do optimization.
11837 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11840 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11841 EVT VT = N->getValueType(0);
11842 unsigned NumElts = VT.getVectorNumElements();
11844 SDValue N0 = N->getOperand(0);
11845 SDValue N1 = N->getOperand(1);
11847 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11849 // Canonicalize shuffle undef, undef -> undef
11850 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11851 return DAG.getUNDEF(VT);
11853 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11855 // Canonicalize shuffle v, v -> v, undef
11857 SmallVector<int, 8> NewMask;
11858 for (unsigned i = 0; i != NumElts; ++i) {
11859 int Idx = SVN->getMaskElt(i);
11860 if (Idx >= (int)NumElts) Idx -= NumElts;
11861 NewMask.push_back(Idx);
11863 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11867 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11868 if (N0.getOpcode() == ISD::UNDEF) {
11869 SmallVector<int, 8> NewMask;
11870 for (unsigned i = 0; i != NumElts; ++i) {
11871 int Idx = SVN->getMaskElt(i);
11873 if (Idx >= (int)NumElts)
11876 Idx = -1; // remove reference to lhs
11878 NewMask.push_back(Idx);
11880 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11884 // Remove references to rhs if it is undef
11885 if (N1.getOpcode() == ISD::UNDEF) {
11886 bool Changed = false;
11887 SmallVector<int, 8> NewMask;
11888 for (unsigned i = 0; i != NumElts; ++i) {
11889 int Idx = SVN->getMaskElt(i);
11890 if (Idx >= (int)NumElts) {
11894 NewMask.push_back(Idx);
11897 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11900 // If it is a splat, check if the argument vector is another splat or a
11902 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11903 SDNode *V = N0.getNode();
11905 // If this is a bit convert that changes the element type of the vector but
11906 // not the number of vector elements, look through it. Be careful not to
11907 // look though conversions that change things like v4f32 to v2f64.
11908 if (V->getOpcode() == ISD::BITCAST) {
11909 SDValue ConvInput = V->getOperand(0);
11910 if (ConvInput.getValueType().isVector() &&
11911 ConvInput.getValueType().getVectorNumElements() == NumElts)
11912 V = ConvInput.getNode();
11915 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11916 assert(V->getNumOperands() == NumElts &&
11917 "BUILD_VECTOR has wrong number of operands");
11919 bool AllSame = true;
11920 for (unsigned i = 0; i != NumElts; ++i) {
11921 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11922 Base = V->getOperand(i);
11926 // Splat of <u, u, u, u>, return <u, u, u, u>
11927 if (!Base.getNode())
11929 for (unsigned i = 0; i != NumElts; ++i) {
11930 if (V->getOperand(i) != Base) {
11935 // Splat of <x, x, x, x>, return <x, x, x, x>
11939 // Canonicalize any other splat as a build_vector.
11940 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11941 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11942 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11943 V->getValueType(0), Ops);
11945 // We may have jumped through bitcasts, so the type of the
11946 // BUILD_VECTOR may not match the type of the shuffle.
11947 if (V->getValueType(0) != VT)
11948 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11953 // There are various patterns used to build up a vector from smaller vectors,
11954 // subvectors, or elements. Scan chains of these and replace unused insertions
11955 // or components with undef.
11956 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11959 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11960 Level < AfterLegalizeVectorOps &&
11961 (N1.getOpcode() == ISD::UNDEF ||
11962 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11963 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11964 SDValue V = partitionShuffleOfConcats(N, DAG);
11970 // If this shuffle only has a single input that is a bitcasted shuffle,
11971 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11972 // back to their original types.
11973 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11974 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11975 TLI.isTypeLegal(VT)) {
11977 // Peek through the bitcast only if there is one user.
11979 while (BC0.getOpcode() == ISD::BITCAST) {
11980 if (!BC0.hasOneUse())
11982 BC0 = BC0.getOperand(0);
11985 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
11987 return SmallVector<int, 8>(Mask.begin(), Mask.end());
11989 SmallVector<int, 8> NewMask;
11991 for (int s = 0; s != Scale; ++s)
11992 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
11996 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
11997 EVT SVT = VT.getScalarType();
11998 EVT InnerVT = BC0->getValueType(0);
11999 EVT InnerSVT = InnerVT.getScalarType();
12001 // Determine which shuffle works with the smaller scalar type.
12002 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12003 EVT ScaleSVT = ScaleVT.getScalarType();
12005 if (TLI.isTypeLegal(ScaleVT) &&
12006 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12007 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12009 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12010 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12012 // Scale the shuffle masks to the smaller scalar type.
12013 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12014 SmallVector<int, 8> InnerMask =
12015 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12016 SmallVector<int, 8> OuterMask =
12017 ScaleShuffleMask(SVN->getMask(), OuterScale);
12019 // Merge the shuffle masks.
12020 SmallVector<int, 8> NewMask;
12021 for (int M : OuterMask)
12022 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12024 // Test for shuffle mask legality over both commutations.
12025 SDValue SV0 = BC0->getOperand(0);
12026 SDValue SV1 = BC0->getOperand(1);
12027 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12029 for (int i = 0, e = (int)NewMask.size(); i != e; ++i) {
12030 int idx = NewMask[i];
12034 NewMask[i] = idx + e;
12036 NewMask[i] = idx - e;
12038 std::swap(SV0, SV1);
12039 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12043 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12044 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12045 return DAG.getNode(
12046 ISD::BITCAST, SDLoc(N), VT,
12047 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12053 // Canonicalize shuffles according to rules:
12054 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12055 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12056 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12057 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12058 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12059 TLI.isTypeLegal(VT)) {
12060 // The incoming shuffle must be of the same type as the result of the
12061 // current shuffle.
12062 assert(N1->getOperand(0).getValueType() == VT &&
12063 "Shuffle types don't match");
12065 SDValue SV0 = N1->getOperand(0);
12066 SDValue SV1 = N1->getOperand(1);
12067 bool HasSameOp0 = N0 == SV0;
12068 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12069 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12070 // Commute the operands of this shuffle so that next rule
12072 return DAG.getCommutedVectorShuffle(*SVN);
12075 // Try to fold according to rules:
12076 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12077 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12078 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12079 // Don't try to fold shuffles with illegal type.
12080 // Only fold if this shuffle is the only user of the other shuffle.
12081 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12082 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12083 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12085 // The incoming shuffle must be of the same type as the result of the
12086 // current shuffle.
12087 assert(OtherSV->getOperand(0).getValueType() == VT &&
12088 "Shuffle types don't match");
12091 SmallVector<int, 4> Mask;
12092 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12093 // operand, and SV1 as the second operand.
12094 for (unsigned i = 0; i != NumElts; ++i) {
12095 int Idx = SVN->getMaskElt(i);
12097 // Propagate Undef.
12098 Mask.push_back(Idx);
12102 SDValue CurrentVec;
12103 if (Idx < (int)NumElts) {
12104 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12105 // shuffle mask to identify which vector is actually referenced.
12106 Idx = OtherSV->getMaskElt(Idx);
12108 // Propagate Undef.
12109 Mask.push_back(Idx);
12113 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12114 : OtherSV->getOperand(1);
12116 // This shuffle index references an element within N1.
12120 // Simple case where 'CurrentVec' is UNDEF.
12121 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12122 Mask.push_back(-1);
12126 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12127 // will be the first or second operand of the combined shuffle.
12128 Idx = Idx % NumElts;
12129 if (!SV0.getNode() || SV0 == CurrentVec) {
12130 // Ok. CurrentVec is the left hand side.
12131 // Update the mask accordingly.
12133 Mask.push_back(Idx);
12137 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12138 if (SV1.getNode() && SV1 != CurrentVec)
12141 // Ok. CurrentVec is the right hand side.
12142 // Update the mask accordingly.
12144 Mask.push_back(Idx + NumElts);
12147 // Check if all indices in Mask are Undef. In case, propagate Undef.
12148 bool isUndefMask = true;
12149 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12150 isUndefMask &= Mask[i] < 0;
12153 return DAG.getUNDEF(VT);
12155 if (!SV0.getNode())
12156 SV0 = DAG.getUNDEF(VT);
12157 if (!SV1.getNode())
12158 SV1 = DAG.getUNDEF(VT);
12160 // Avoid introducing shuffles with illegal mask.
12161 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12162 // Compute the commuted shuffle mask and test again.
12163 for (unsigned i = 0; i != NumElts; ++i) {
12167 else if (idx < (int)NumElts)
12168 Mask[i] = idx + NumElts;
12170 Mask[i] = idx - NumElts;
12173 if (!TLI.isShuffleMaskLegal(Mask, VT))
12176 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12177 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12178 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12179 std::swap(SV0, SV1);
12182 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12183 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12184 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12185 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12191 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12192 SDValue N0 = N->getOperand(0);
12193 SDValue N2 = N->getOperand(2);
12195 // If the input vector is a concatenation, and the insert replaces
12196 // one of the halves, we can optimize into a single concat_vectors.
12197 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12198 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12199 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12200 EVT VT = N->getValueType(0);
12202 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12203 // (concat_vectors Z, Y)
12205 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12206 N->getOperand(1), N0.getOperand(1));
12208 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12209 // (concat_vectors X, Z)
12210 if (InsIdx == VT.getVectorNumElements()/2)
12211 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12212 N0.getOperand(0), N->getOperand(1));
12218 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12219 /// with the destination vector and a zero vector.
12220 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12221 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12222 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12223 EVT VT = N->getValueType(0);
12225 SDValue LHS = N->getOperand(0);
12226 SDValue RHS = N->getOperand(1);
12227 if (N->getOpcode() == ISD::AND) {
12228 if (RHS.getOpcode() == ISD::BITCAST)
12229 RHS = RHS.getOperand(0);
12230 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12231 SmallVector<int, 8> Indices;
12232 unsigned NumElts = RHS.getNumOperands();
12233 for (unsigned i = 0; i != NumElts; ++i) {
12234 SDValue Elt = RHS.getOperand(i);
12235 if (!isa<ConstantSDNode>(Elt))
12238 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12239 Indices.push_back(i);
12240 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12241 Indices.push_back(NumElts+i);
12246 // Let's see if the target supports this vector_shuffle and make sure
12247 // we're not running after operation legalization where it may have
12248 // custom lowered the vector shuffles.
12249 EVT RVT = RHS.getValueType();
12250 if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
12253 // Return the new VECTOR_SHUFFLE node.
12254 EVT EltVT = RVT.getVectorElementType();
12255 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12256 DAG.getConstant(0, EltVT));
12257 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12258 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12259 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12260 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12267 /// Visit a binary vector operation, like ADD.
12268 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12269 assert(N->getValueType(0).isVector() &&
12270 "SimplifyVBinOp only works on vectors!");
12272 SDValue LHS = N->getOperand(0);
12273 SDValue RHS = N->getOperand(1);
12274 SDValue Shuffle = XformToShuffleWithZero(N);
12275 if (Shuffle.getNode()) return Shuffle;
12277 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12279 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12280 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12281 // Check if both vectors are constants. If not bail out.
12282 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12283 cast<BuildVectorSDNode>(RHS)->isConstant()))
12286 SmallVector<SDValue, 8> Ops;
12287 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12288 SDValue LHSOp = LHS.getOperand(i);
12289 SDValue RHSOp = RHS.getOperand(i);
12291 // Can't fold divide by zero.
12292 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12293 N->getOpcode() == ISD::FDIV) {
12294 if ((RHSOp.getOpcode() == ISD::Constant &&
12295 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12296 (RHSOp.getOpcode() == ISD::ConstantFP &&
12297 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12301 EVT VT = LHSOp.getValueType();
12302 EVT RVT = RHSOp.getValueType();
12304 // Integer BUILD_VECTOR operands may have types larger than the element
12305 // size (e.g., when the element type is not legal). Prior to type
12306 // legalization, the types may not match between the two BUILD_VECTORS.
12307 // Truncate one of the operands to make them match.
12308 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12309 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12311 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12315 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12317 if (FoldOp.getOpcode() != ISD::UNDEF &&
12318 FoldOp.getOpcode() != ISD::Constant &&
12319 FoldOp.getOpcode() != ISD::ConstantFP)
12321 Ops.push_back(FoldOp);
12322 AddToWorklist(FoldOp.getNode());
12325 if (Ops.size() == LHS.getNumOperands())
12326 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12329 // Type legalization might introduce new shuffles in the DAG.
12330 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12331 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12332 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12333 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12334 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12335 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12336 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12337 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12339 if (SVN0->getMask().equals(SVN1->getMask())) {
12340 EVT VT = N->getValueType(0);
12341 SDValue UndefVector = LHS.getOperand(1);
12342 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12343 LHS.getOperand(0), RHS.getOperand(0));
12344 AddUsersToWorklist(N);
12345 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12346 &SVN0->getMask()[0]);
12353 /// Visit a binary vector operation, like FABS/FNEG.
12354 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12355 assert(N->getValueType(0).isVector() &&
12356 "SimplifyVUnaryOp only works on vectors!");
12358 SDValue N0 = N->getOperand(0);
12360 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12363 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12364 SmallVector<SDValue, 8> Ops;
12365 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12366 SDValue Op = N0.getOperand(i);
12367 if (Op.getOpcode() != ISD::UNDEF &&
12368 Op.getOpcode() != ISD::ConstantFP)
12370 EVT EltVT = Op.getValueType();
12371 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12372 if (FoldOp.getOpcode() != ISD::UNDEF &&
12373 FoldOp.getOpcode() != ISD::ConstantFP)
12375 Ops.push_back(FoldOp);
12376 AddToWorklist(FoldOp.getNode());
12379 if (Ops.size() != N0.getNumOperands())
12382 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12385 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12386 SDValue N1, SDValue N2){
12387 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12389 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12390 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12392 // If we got a simplified select_cc node back from SimplifySelectCC, then
12393 // break it down into a new SETCC node, and a new SELECT node, and then return
12394 // the SELECT node, since we were called with a SELECT node.
12395 if (SCC.getNode()) {
12396 // Check to see if we got a select_cc back (to turn into setcc/select).
12397 // Otherwise, just return whatever node we got back, like fabs.
12398 if (SCC.getOpcode() == ISD::SELECT_CC) {
12399 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12401 SCC.getOperand(0), SCC.getOperand(1),
12402 SCC.getOperand(4));
12403 AddToWorklist(SETCC.getNode());
12404 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12405 SCC.getOperand(2), SCC.getOperand(3));
12413 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12414 /// being selected between, see if we can simplify the select. Callers of this
12415 /// should assume that TheSelect is deleted if this returns true. As such, they
12416 /// should return the appropriate thing (e.g. the node) back to the top-level of
12417 /// the DAG combiner loop to avoid it being looked at.
12418 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12421 // Cannot simplify select with vector condition
12422 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12424 // If this is a select from two identical things, try to pull the operation
12425 // through the select.
12426 if (LHS.getOpcode() != RHS.getOpcode() ||
12427 !LHS.hasOneUse() || !RHS.hasOneUse())
12430 // If this is a load and the token chain is identical, replace the select
12431 // of two loads with a load through a select of the address to load from.
12432 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12433 // constants have been dropped into the constant pool.
12434 if (LHS.getOpcode() == ISD::LOAD) {
12435 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12436 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12438 // Token chains must be identical.
12439 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12440 // Do not let this transformation reduce the number of volatile loads.
12441 LLD->isVolatile() || RLD->isVolatile() ||
12442 // If this is an EXTLOAD, the VT's must match.
12443 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12444 // If this is an EXTLOAD, the kind of extension must match.
12445 (LLD->getExtensionType() != RLD->getExtensionType() &&
12446 // The only exception is if one of the extensions is anyext.
12447 LLD->getExtensionType() != ISD::EXTLOAD &&
12448 RLD->getExtensionType() != ISD::EXTLOAD) ||
12449 // FIXME: this discards src value information. This is
12450 // over-conservative. It would be beneficial to be able to remember
12451 // both potential memory locations. Since we are discarding
12452 // src value info, don't do the transformation if the memory
12453 // locations are not in the default address space.
12454 LLD->getPointerInfo().getAddrSpace() != 0 ||
12455 RLD->getPointerInfo().getAddrSpace() != 0 ||
12456 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12457 LLD->getBasePtr().getValueType()))
12460 // Check that the select condition doesn't reach either load. If so,
12461 // folding this will induce a cycle into the DAG. If not, this is safe to
12462 // xform, so create a select of the addresses.
12464 if (TheSelect->getOpcode() == ISD::SELECT) {
12465 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12466 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12467 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12469 // The loads must not depend on one another.
12470 if (LLD->isPredecessorOf(RLD) ||
12471 RLD->isPredecessorOf(LLD))
12473 Addr = DAG.getSelect(SDLoc(TheSelect),
12474 LLD->getBasePtr().getValueType(),
12475 TheSelect->getOperand(0), LLD->getBasePtr(),
12476 RLD->getBasePtr());
12477 } else { // Otherwise SELECT_CC
12478 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12479 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12481 if ((LLD->hasAnyUseOfValue(1) &&
12482 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12483 (RLD->hasAnyUseOfValue(1) &&
12484 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12487 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12488 LLD->getBasePtr().getValueType(),
12489 TheSelect->getOperand(0),
12490 TheSelect->getOperand(1),
12491 LLD->getBasePtr(), RLD->getBasePtr(),
12492 TheSelect->getOperand(4));
12496 // It is safe to replace the two loads if they have different alignments,
12497 // but the new load must be the minimum (most restrictive) alignment of the
12499 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12500 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12501 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12502 Load = DAG.getLoad(TheSelect->getValueType(0),
12504 // FIXME: Discards pointer and AA info.
12505 LLD->getChain(), Addr, MachinePointerInfo(),
12506 LLD->isVolatile(), LLD->isNonTemporal(),
12507 isInvariant, Alignment);
12509 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12510 RLD->getExtensionType() : LLD->getExtensionType(),
12512 TheSelect->getValueType(0),
12513 // FIXME: Discards pointer and AA info.
12514 LLD->getChain(), Addr, MachinePointerInfo(),
12515 LLD->getMemoryVT(), LLD->isVolatile(),
12516 LLD->isNonTemporal(), isInvariant, Alignment);
12519 // Users of the select now use the result of the load.
12520 CombineTo(TheSelect, Load);
12522 // Users of the old loads now use the new load's chain. We know the
12523 // old-load value is dead now.
12524 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12525 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12532 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12533 /// where 'cond' is the comparison specified by CC.
12534 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12535 SDValue N2, SDValue N3,
12536 ISD::CondCode CC, bool NotExtCompare) {
12537 // (x ? y : y) -> y.
12538 if (N2 == N3) return N2;
12540 EVT VT = N2.getValueType();
12541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12542 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12543 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12545 // Determine if the condition we're dealing with is constant
12546 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12547 N0, N1, CC, DL, false);
12548 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12549 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12551 // fold select_cc true, x, y -> x
12552 if (SCCC && !SCCC->isNullValue())
12554 // fold select_cc false, x, y -> y
12555 if (SCCC && SCCC->isNullValue())
12558 // Check to see if we can simplify the select into an fabs node
12559 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12560 // Allow either -0.0 or 0.0
12561 if (CFP->getValueAPF().isZero()) {
12562 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12563 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12564 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12565 N2 == N3.getOperand(0))
12566 return DAG.getNode(ISD::FABS, DL, VT, N0);
12568 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12569 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12570 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12571 N2.getOperand(0) == N3)
12572 return DAG.getNode(ISD::FABS, DL, VT, N3);
12576 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12577 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12578 // in it. This is a win when the constant is not otherwise available because
12579 // it replaces two constant pool loads with one. We only do this if the FP
12580 // type is known to be legal, because if it isn't, then we are before legalize
12581 // types an we want the other legalization to happen first (e.g. to avoid
12582 // messing with soft float) and if the ConstantFP is not legal, because if
12583 // it is legal, we may not need to store the FP constant in a constant pool.
12584 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12585 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12586 if (TLI.isTypeLegal(N2.getValueType()) &&
12587 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12588 TargetLowering::Legal &&
12589 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12590 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12591 // If both constants have multiple uses, then we won't need to do an
12592 // extra load, they are likely around in registers for other users.
12593 (TV->hasOneUse() || FV->hasOneUse())) {
12594 Constant *Elts[] = {
12595 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12596 const_cast<ConstantFP*>(TV->getConstantFPValue())
12598 Type *FPTy = Elts[0]->getType();
12599 const DataLayout &TD = *TLI.getDataLayout();
12601 // Create a ConstantArray of the two constants.
12602 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12603 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12604 TD.getPrefTypeAlignment(FPTy));
12605 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12607 // Get the offsets to the 0 and 1 element of the array so that we can
12608 // select between them.
12609 SDValue Zero = DAG.getIntPtrConstant(0);
12610 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12611 SDValue One = DAG.getIntPtrConstant(EltSize);
12613 SDValue Cond = DAG.getSetCC(DL,
12614 getSetCCResultType(N0.getValueType()),
12616 AddToWorklist(Cond.getNode());
12617 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12619 AddToWorklist(CstOffset.getNode());
12620 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12622 AddToWorklist(CPIdx.getNode());
12623 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12624 MachinePointerInfo::getConstantPool(), false,
12625 false, false, Alignment);
12630 // Check to see if we can perform the "gzip trick", transforming
12631 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12632 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12633 (N1C->isNullValue() || // (a < 0) ? b : 0
12634 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12635 EVT XType = N0.getValueType();
12636 EVT AType = N2.getValueType();
12637 if (XType.bitsGE(AType)) {
12638 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12639 // single-bit constant.
12640 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12641 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12642 ShCtV = XType.getSizeInBits()-ShCtV-1;
12643 SDValue ShCt = DAG.getConstant(ShCtV,
12644 getShiftAmountTy(N0.getValueType()));
12645 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12647 AddToWorklist(Shift.getNode());
12649 if (XType.bitsGT(AType)) {
12650 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12651 AddToWorklist(Shift.getNode());
12654 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12657 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12659 DAG.getConstant(XType.getSizeInBits()-1,
12660 getShiftAmountTy(N0.getValueType())));
12661 AddToWorklist(Shift.getNode());
12663 if (XType.bitsGT(AType)) {
12664 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12665 AddToWorklist(Shift.getNode());
12668 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12672 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12673 // where y is has a single bit set.
12674 // A plaintext description would be, we can turn the SELECT_CC into an AND
12675 // when the condition can be materialized as an all-ones register. Any
12676 // single bit-test can be materialized as an all-ones register with
12677 // shift-left and shift-right-arith.
12678 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12679 N0->getValueType(0) == VT &&
12680 N1C && N1C->isNullValue() &&
12681 N2C && N2C->isNullValue()) {
12682 SDValue AndLHS = N0->getOperand(0);
12683 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12684 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12685 // Shift the tested bit over the sign bit.
12686 APInt AndMask = ConstAndRHS->getAPIntValue();
12688 DAG.getConstant(AndMask.countLeadingZeros(),
12689 getShiftAmountTy(AndLHS.getValueType()));
12690 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12692 // Now arithmetic right shift it all the way over, so the result is either
12693 // all-ones, or zero.
12695 DAG.getConstant(AndMask.getBitWidth()-1,
12696 getShiftAmountTy(Shl.getValueType()));
12697 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12699 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12703 // fold select C, 16, 0 -> shl C, 4
12704 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12705 TLI.getBooleanContents(N0.getValueType()) ==
12706 TargetLowering::ZeroOrOneBooleanContent) {
12708 // If the caller doesn't want us to simplify this into a zext of a compare,
12710 if (NotExtCompare && N2C->getAPIntValue() == 1)
12713 // Get a SetCC of the condition
12714 // NOTE: Don't create a SETCC if it's not legal on this target.
12715 if (!LegalOperations ||
12716 TLI.isOperationLegal(ISD::SETCC,
12717 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12719 // cast from setcc result type to select result type
12721 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12723 if (N2.getValueType().bitsLT(SCC.getValueType()))
12724 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12725 N2.getValueType());
12727 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12728 N2.getValueType(), SCC);
12730 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12731 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12732 N2.getValueType(), SCC);
12735 AddToWorklist(SCC.getNode());
12736 AddToWorklist(Temp.getNode());
12738 if (N2C->getAPIntValue() == 1)
12741 // shl setcc result by log2 n2c
12742 return DAG.getNode(
12743 ISD::SHL, DL, N2.getValueType(), Temp,
12744 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12745 getShiftAmountTy(Temp.getValueType())));
12749 // Check to see if this is the equivalent of setcc
12750 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12751 // otherwise, go ahead with the folds.
12752 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12753 EVT XType = N0.getValueType();
12754 if (!LegalOperations ||
12755 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12756 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12757 if (Res.getValueType() != VT)
12758 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12762 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12763 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12764 (!LegalOperations ||
12765 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12766 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12767 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12768 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12769 getShiftAmountTy(Ctlz.getValueType())));
12771 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12772 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12773 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12774 XType, DAG.getConstant(0, XType), N0);
12775 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12776 return DAG.getNode(ISD::SRL, DL, XType,
12777 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12778 DAG.getConstant(XType.getSizeInBits()-1,
12779 getShiftAmountTy(XType)));
12781 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12782 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12783 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12784 DAG.getConstant(XType.getSizeInBits()-1,
12785 getShiftAmountTy(N0.getValueType())));
12786 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12790 // Check to see if this is an integer abs.
12791 // select_cc setg[te] X, 0, X, -X ->
12792 // select_cc setgt X, -1, X, -X ->
12793 // select_cc setl[te] X, 0, -X, X ->
12794 // select_cc setlt X, 1, -X, X ->
12795 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12797 ConstantSDNode *SubC = nullptr;
12798 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12799 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12800 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12801 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12802 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12803 (N1C->isOne() && CC == ISD::SETLT)) &&
12804 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12805 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12807 EVT XType = N0.getValueType();
12808 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12809 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12811 DAG.getConstant(XType.getSizeInBits()-1,
12812 getShiftAmountTy(N0.getValueType())));
12813 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12815 AddToWorklist(Shift.getNode());
12816 AddToWorklist(Add.getNode());
12817 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12824 /// This is a stub for TargetLowering::SimplifySetCC.
12825 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12826 SDValue N1, ISD::CondCode Cond,
12827 SDLoc DL, bool foldBooleans) {
12828 TargetLowering::DAGCombinerInfo
12829 DagCombineInfo(DAG, Level, false, this);
12830 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12833 /// Given an ISD::SDIV node expressing a divide by constant, return
12834 /// a DAG expression to select that will generate the same value by multiplying
12835 /// by a magic number.
12836 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12837 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12838 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12842 // Avoid division by zero.
12843 if (!C->getAPIntValue())
12846 std::vector<SDNode*> Built;
12848 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12850 for (SDNode *N : Built)
12855 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12856 /// DAG expression that will generate the same value by right shifting.
12857 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12858 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12862 // Avoid division by zero.
12863 if (!C->getAPIntValue())
12866 std::vector<SDNode *> Built;
12867 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12869 for (SDNode *N : Built)
12874 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12875 /// expression that will generate the same value by multiplying by a magic
12877 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12878 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12879 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12883 // Avoid division by zero.
12884 if (!C->getAPIntValue())
12887 std::vector<SDNode*> Built;
12889 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12891 for (SDNode *N : Built)
12896 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12897 if (Level >= AfterLegalizeDAG)
12900 // Expose the DAG combiner to the target combiner implementations.
12901 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12903 unsigned Iterations = 0;
12904 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12906 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12907 // For the reciprocal, we need to find the zero of the function:
12908 // F(X) = A X - 1 [which has a zero at X = 1/A]
12910 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12911 // does not require additional intermediate precision]
12912 EVT VT = Op.getValueType();
12914 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12916 AddToWorklist(Est.getNode());
12918 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12919 for (unsigned i = 0; i < Iterations; ++i) {
12920 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12921 AddToWorklist(NewEst.getNode());
12923 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12924 AddToWorklist(NewEst.getNode());
12926 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12927 AddToWorklist(NewEst.getNode());
12929 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12930 AddToWorklist(Est.getNode());
12939 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12940 /// For the reciprocal sqrt, we need to find the zero of the function:
12941 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12943 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12944 /// As a result, we precompute A/2 prior to the iteration loop.
12945 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12946 unsigned Iterations) {
12947 EVT VT = Arg.getValueType();
12949 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12951 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12952 // this entire sequence requires only one FP constant.
12953 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12954 AddToWorklist(HalfArg.getNode());
12956 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12957 AddToWorklist(HalfArg.getNode());
12959 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12960 for (unsigned i = 0; i < Iterations; ++i) {
12961 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12962 AddToWorklist(NewEst.getNode());
12964 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12965 AddToWorklist(NewEst.getNode());
12967 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12968 AddToWorklist(NewEst.getNode());
12970 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12971 AddToWorklist(Est.getNode());
12976 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12977 /// For the reciprocal sqrt, we need to find the zero of the function:
12978 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12980 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12981 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12982 unsigned Iterations) {
12983 EVT VT = Arg.getValueType();
12985 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12986 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12988 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12989 for (unsigned i = 0; i < Iterations; ++i) {
12990 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12991 AddToWorklist(HalfEst.getNode());
12993 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12994 AddToWorklist(Est.getNode());
12996 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12997 AddToWorklist(Est.getNode());
12999 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13000 AddToWorklist(Est.getNode());
13002 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13003 AddToWorklist(Est.getNode());
13008 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13009 if (Level >= AfterLegalizeDAG)
13012 // Expose the DAG combiner to the target combiner implementations.
13013 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13014 unsigned Iterations = 0;
13015 bool UseOneConstNR = false;
13016 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13017 AddToWorklist(Est.getNode());
13019 Est = UseOneConstNR ?
13020 BuildRsqrtNROneConst(Op, Est, Iterations) :
13021 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13029 /// Return true if base is a frame index, which is known not to alias with
13030 /// anything but itself. Provides base object and offset as results.
13031 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13032 const GlobalValue *&GV, const void *&CV) {
13033 // Assume it is a primitive operation.
13034 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13036 // If it's an adding a simple constant then integrate the offset.
13037 if (Base.getOpcode() == ISD::ADD) {
13038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13039 Base = Base.getOperand(0);
13040 Offset += C->getZExtValue();
13044 // Return the underlying GlobalValue, and update the Offset. Return false
13045 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13046 // by multiple nodes with different offsets.
13047 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13048 GV = G->getGlobal();
13049 Offset += G->getOffset();
13053 // Return the underlying Constant value, and update the Offset. Return false
13054 // for ConstantSDNodes since the same constant pool entry may be represented
13055 // by multiple nodes with different offsets.
13056 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13057 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13058 : (const void *)C->getConstVal();
13059 Offset += C->getOffset();
13062 // If it's any of the following then it can't alias with anything but itself.
13063 return isa<FrameIndexSDNode>(Base);
13066 /// Return true if there is any possibility that the two addresses overlap.
13067 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13068 // If they are the same then they must be aliases.
13069 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13071 // If they are both volatile then they cannot be reordered.
13072 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13074 // Gather base node and offset information.
13075 SDValue Base1, Base2;
13076 int64_t Offset1, Offset2;
13077 const GlobalValue *GV1, *GV2;
13078 const void *CV1, *CV2;
13079 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13080 Base1, Offset1, GV1, CV1);
13081 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13082 Base2, Offset2, GV2, CV2);
13084 // If they have a same base address then check to see if they overlap.
13085 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13086 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13087 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13089 // It is possible for different frame indices to alias each other, mostly
13090 // when tail call optimization reuses return address slots for arguments.
13091 // To catch this case, look up the actual index of frame indices to compute
13092 // the real alias relationship.
13093 if (isFrameIndex1 && isFrameIndex2) {
13094 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13095 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13096 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13097 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13098 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13101 // Otherwise, if we know what the bases are, and they aren't identical, then
13102 // we know they cannot alias.
13103 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13106 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13107 // compared to the size and offset of the access, we may be able to prove they
13108 // do not alias. This check is conservative for now to catch cases created by
13109 // splitting vector types.
13110 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13111 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13112 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13113 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13114 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13115 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13116 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13118 // There is no overlap between these relatively aligned accesses of similar
13119 // size, return no alias.
13120 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13121 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13125 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13127 : DAG.getSubtarget().useAA();
13129 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13130 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13134 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13135 // Use alias analysis information.
13136 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13137 Op1->getSrcValueOffset());
13138 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13139 Op0->getSrcValueOffset() - MinOffset;
13140 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13141 Op1->getSrcValueOffset() - MinOffset;
13142 AliasAnalysis::AliasResult AAResult =
13143 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13145 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13146 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13148 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13149 if (AAResult == AliasAnalysis::NoAlias)
13153 // Otherwise we have to assume they alias.
13157 /// Walk up chain skipping non-aliasing memory nodes,
13158 /// looking for aliasing nodes and adding them to the Aliases vector.
13159 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13160 SmallVectorImpl<SDValue> &Aliases) {
13161 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13162 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13164 // Get alias information for node.
13165 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13168 Chains.push_back(OriginalChain);
13169 unsigned Depth = 0;
13171 // Look at each chain and determine if it is an alias. If so, add it to the
13172 // aliases list. If not, then continue up the chain looking for the next
13174 while (!Chains.empty()) {
13175 SDValue Chain = Chains.back();
13178 // For TokenFactor nodes, look at each operand and only continue up the
13179 // chain until we find two aliases. If we've seen two aliases, assume we'll
13180 // find more and revert to original chain since the xform is unlikely to be
13183 // FIXME: The depth check could be made to return the last non-aliasing
13184 // chain we found before we hit a tokenfactor rather than the original
13186 if (Depth > 6 || Aliases.size() == 2) {
13188 Aliases.push_back(OriginalChain);
13192 // Don't bother if we've been before.
13193 if (!Visited.insert(Chain.getNode()).second)
13196 switch (Chain.getOpcode()) {
13197 case ISD::EntryToken:
13198 // Entry token is ideal chain operand, but handled in FindBetterChain.
13203 // Get alias information for Chain.
13204 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13205 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13207 // If chain is alias then stop here.
13208 if (!(IsLoad && IsOpLoad) &&
13209 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13210 Aliases.push_back(Chain);
13212 // Look further up the chain.
13213 Chains.push_back(Chain.getOperand(0));
13219 case ISD::TokenFactor:
13220 // We have to check each of the operands of the token factor for "small"
13221 // token factors, so we queue them up. Adding the operands to the queue
13222 // (stack) in reverse order maintains the original order and increases the
13223 // likelihood that getNode will find a matching token factor (CSE.)
13224 if (Chain.getNumOperands() > 16) {
13225 Aliases.push_back(Chain);
13228 for (unsigned n = Chain.getNumOperands(); n;)
13229 Chains.push_back(Chain.getOperand(--n));
13234 // For all other instructions we will just have to take what we can get.
13235 Aliases.push_back(Chain);
13240 // We need to be careful here to also search for aliases through the
13241 // value operand of a store, etc. Consider the following situation:
13243 // L1 = load Token1, %52
13244 // S1 = store Token1, L1, %51
13245 // L2 = load Token1, %52+8
13246 // S2 = store Token1, L2, %51+8
13247 // Token2 = Token(S1, S2)
13248 // L3 = load Token2, %53
13249 // S3 = store Token2, L3, %52
13250 // L4 = load Token2, %53+8
13251 // S4 = store Token2, L4, %52+8
13252 // If we search for aliases of S3 (which loads address %52), and we look
13253 // only through the chain, then we'll miss the trivial dependence on L1
13254 // (which also loads from %52). We then might change all loads and
13255 // stores to use Token1 as their chain operand, which could result in
13256 // copying %53 into %52 before copying %52 into %51 (which should
13259 // The problem is, however, that searching for such data dependencies
13260 // can become expensive, and the cost is not directly related to the
13261 // chain depth. Instead, we'll rule out such configurations here by
13262 // insisting that we've visited all chain users (except for users
13263 // of the original chain, which is not necessary). When doing this,
13264 // we need to look through nodes we don't care about (otherwise, things
13265 // like register copies will interfere with trivial cases).
13267 SmallVector<const SDNode *, 16> Worklist;
13268 for (const SDNode *N : Visited)
13269 if (N != OriginalChain.getNode())
13270 Worklist.push_back(N);
13272 while (!Worklist.empty()) {
13273 const SDNode *M = Worklist.pop_back_val();
13275 // We have already visited M, and want to make sure we've visited any uses
13276 // of M that we care about. For uses that we've not visisted, and don't
13277 // care about, queue them to the worklist.
13279 for (SDNode::use_iterator UI = M->use_begin(),
13280 UIE = M->use_end(); UI != UIE; ++UI)
13281 if (UI.getUse().getValueType() == MVT::Other &&
13282 Visited.insert(*UI).second) {
13283 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13284 // We've not visited this use, and we care about it (it could have an
13285 // ordering dependency with the original node).
13287 Aliases.push_back(OriginalChain);
13291 // We've not visited this use, but we don't care about it. Mark it as
13292 // visited and enqueue it to the worklist.
13293 Worklist.push_back(*UI);
13298 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13299 /// (aliasing node.)
13300 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13301 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13303 // Accumulate all the aliases to this node.
13304 GatherAllAliases(N, OldChain, Aliases);
13306 // If no operands then chain to entry token.
13307 if (Aliases.size() == 0)
13308 return DAG.getEntryNode();
13310 // If a single operand then chain to it. We don't need to revisit it.
13311 if (Aliases.size() == 1)
13314 // Construct a custom tailored token factor.
13315 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13318 /// This is the entry point for the file.
13319 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13320 CodeGenOpt::Level OptLevel) {
13321 /// This is the main entry point to this class.
13322 DAGCombiner(*this, AA, OptLevel).Run(Level);