1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 // AA - Used for DAG load/store alias analysis.
110 /// AddUsersToWorklist - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
114 void AddUsersToWorklist(SDNode *N) {
115 for (SDNode *Node : N->uses())
119 /// visit - call the node-specific routine that knows how to fold each
120 /// particular type of node.
121 SDValue visit(SDNode *N);
124 /// AddToWorklist - Add to the work list making sure its instance is at the
125 /// back (next to be processed.)
126 void AddToWorklist(SDNode *N) {
127 // Skip handle nodes as they can't usefully be combined and confuse the
128 // zero-use deletion strategy.
129 if (N->getOpcode() == ISD::HANDLENODE)
132 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
133 Worklist.push_back(N);
136 /// removeFromWorklist - remove all instances of N from the worklist.
138 void removeFromWorklist(SDNode *N) {
139 auto It = WorklistMap.find(N);
140 if (It == WorklistMap.end())
141 return; // Not in the worklist.
143 // Null out the entry rather than erasing it to avoid a linear operation.
144 Worklist[It->second] = nullptr;
145 WorklistMap.erase(It);
148 bool recursivelyDeleteUnusedNodes(SDNode *N);
150 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
153 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
154 return CombineTo(N, &Res, 1, AddTo);
157 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
159 SDValue To[] = { Res0, Res1 };
160 return CombineTo(N, To, 2, AddTo);
163 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
167 /// SimplifyDemandedBits - Check the specified integer node value to see if
168 /// it can be simplified or if things it uses can be simplified by bit
169 /// propagation. If so, return true.
170 bool SimplifyDemandedBits(SDValue Op) {
171 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
172 APInt Demanded = APInt::getAllOnesValue(BitWidth);
173 return SimplifyDemandedBits(Op, Demanded);
176 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
178 bool CombineToPreIndexedLoadStore(SDNode *N);
179 bool CombineToPostIndexedLoadStore(SDNode *N);
180 bool SliceUpLoad(SDNode *N);
182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
186 SDValue PromoteIntBinOp(SDValue Op);
187 SDValue PromoteIntShiftOp(SDValue Op);
188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
193 ISD::NodeType ExtType);
195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
198 SDValue combine(SDNode *N);
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
212 SDValue visitSUBC(SDNode *N);
213 SDValue visitADDE(SDNode *N);
214 SDValue visitSUBE(SDNode *N);
215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
232 SDValue SimplifyVUnaryOp(SDNode *N);
233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
236 SDValue visitRotate(SDNode *N);
237 SDValue visitCTLZ(SDNode *N);
238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
239 SDValue visitCTTZ(SDNode *N);
240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
243 SDValue visitVSELECT(SDNode *N);
244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
251 SDValue visitBITCAST(SDNode *N);
252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
256 SDValue visitFMA(SDNode *N);
257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
284 SDValue XformToShuffleWithZero(SDNode *N);
285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
293 SDValue N3, ISD::CondCode CC,
294 bool NotExtCompare = false);
295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
296 SDLoc DL, bool foldBooleans = true);
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
300 bool isOneUseSetCC(SDValue N) const;
302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
306 SDValue BuildSDIV(SDNode *N);
307 SDValue BuildUDIV(SDNode *N);
308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309 bool DemandHighBits = true);
310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312 SDValue InnerPos, SDValue InnerNeg,
313 unsigned PosOpcode, unsigned NegOpcode,
315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
316 SDValue ReduceLoadWidth(SDNode *N);
317 SDValue ReduceLoadOpStoreWidth(SDNode *N);
318 SDValue TransformFPLoadStorePair(SDNode *N);
319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
322 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for aliasing nodes and adding them to the Aliases vector.
326 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
327 SmallVectorImpl<SDValue> &Aliases);
329 /// isAlias - Return true if there is any possibility that the two addresses
331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
334 /// looking for a better chain (aliasing node.)
335 SDValue FindBetterChain(SDNode *N, SDValue Chain);
337 /// Merge consecutive store operations into a wide store.
338 /// This optimization uses wide integers or vectors when possible.
339 /// \return True if some memory operations were changed.
340 bool MergeConsecutiveStores(StoreSDNode *N);
342 /// \brief Try to transform a truncation where C is a constant:
343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
345 /// \p N needs to be a truncation and its first operand an AND. Other
346 /// requirements are checked by the function (e.g. that trunc is
347 /// single-use) and if missed an empty SDValue is returned.
348 SDValue distributeTruncateThroughAnd(SDNode *N);
351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
362 /// Run - runs the dag combiner on all nodes in the work list
363 void Run(CombineLevel AtLevel);
365 SelectionDAG &getDAG() const { return DAG; }
367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
369 EVT getShiftAmountTy(EVT LHSTy) {
370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
394 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
395 /// nodes from the worklist.
396 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
399 explicit WorklistRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
402 void NodeDeleted(SDNode *N, SDNode *E) override {
403 DC.removeFromWorklist(N);
408 //===----------------------------------------------------------------------===//
409 // TargetLowering::DAGCombinerInfo implementation
410 //===----------------------------------------------------------------------===//
412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorklist(N);
416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorklist(N);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
425 SDValue TargetLowering::DAGCombinerInfo::
426 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
431 SDValue TargetLowering::DAGCombinerInfo::
432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
436 void TargetLowering::DAGCombinerInfo::
437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
446 /// specified expression for the same cost as the expression itself, or 2 if we
447 /// can compute the negated form more cheaply than the expression itself.
448 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
449 const TargetLowering &TLI,
450 const TargetOptions *Options,
451 unsigned Depth = 0) {
452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
466 return LegalOperations ? 0 : 1;
468 // FIXME: determine better conditions for this xform.
469 if (!Options->UnsafeFPMath) return 0;
471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 // We can't turn -(A-B) into B-A when we honor signed zeros.
485 if (!Options->UnsafeFPMath) return 0;
487 // fold (fneg (fsub A, B)) -> (fsub B, A)
492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
511 /// returns the newly negated expression.
512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
513 bool LegalOperations, unsigned Depth = 0) {
514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
521 switch (Op.getOpcode()) {
522 default: llvm_unreachable("Unknown code");
523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 return DAG.getConstantFP(V, Op.getValueType());
529 // FIXME: determine better conditions for this xform.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
534 DAG.getTargetLoweringInfo(),
535 &DAG.getTarget().Options, Depth+1))
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(0), DAG,
538 LegalOperations, Depth+1),
540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
542 GetNegatedExpression(Op.getOperand(1), DAG,
543 LegalOperations, Depth+1),
546 // We can't turn -(A-B) into B-A when we honor signed zeros.
547 assert(DAG.getTarget().Options.UnsafeFPMath);
549 // fold (fneg (fsub 0, B)) -> B
550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
551 if (N0CFP->getValueAPF().isZero())
552 return Op.getOperand(1);
554 // fold (fneg (fsub A, B)) -> (fsub B, A)
555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556 Op.getOperand(1), Op.getOperand(0));
560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
564 DAG.getTargetLoweringInfo(),
565 &DAG.getTarget().Options, Depth+1))
566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1));
579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
580 GetNegatedExpression(Op.getOperand(0), DAG,
581 LegalOperations, Depth+1));
583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(0), DAG,
585 LegalOperations, Depth+1),
590 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
591 // that selects between the target values used for true and false, making it
592 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593 // the appropriate nodes based on the type of node we are checking. This
594 // simplifies life a bit for the callers.
595 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
597 if (N.getOpcode() == ISD::SETCC) {
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(2);
604 if (N.getOpcode() != ISD::SELECT_CC ||
605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
615 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616 // one use. If this is true, it allows the users to invert the operation for
617 // free when it is profitable to do so.
618 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
625 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626 /// elements are all the same constant or undefined.
627 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
633 unsigned SplatBitSize;
635 EVT EltVT = N->getValueType(0).getVectorElementType();
636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
638 EltVT.getSizeInBits() >= SplatBitSize);
641 // \brief Returns the SDNode if it is a constant BuildVector or constant.
642 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643 if (isa<ConstantSDNode>(N))
645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646 if(BV && BV->isConstant())
651 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
653 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
658 BitVector UndefElements;
659 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
661 // BuildVectors can truncate their operands. Ignore that case here.
662 // FIXME: We blindly ignore splats which include undef which is overly
664 if (CN && UndefElements.none() &&
665 CN->getValueType(0) == N.getValueType().getScalarType())
672 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
673 SDValue N0, SDValue N1) {
674 EVT VT = N0.getValueType();
675 if (N0.getOpcode() == Opc) {
676 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
677 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
678 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
679 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
680 if (!OpNode.getNode())
682 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
684 if (N0.hasOneUse()) {
685 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
687 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
688 if (!OpNode.getNode())
690 AddToWorklist(OpNode.getNode());
691 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
696 if (N1.getOpcode() == Opc) {
697 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
698 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
699 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
700 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
701 if (!OpNode.getNode())
703 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
705 if (N1.hasOneUse()) {
706 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
708 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
709 if (!OpNode.getNode())
711 AddToWorklist(OpNode.getNode());
712 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
720 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
722 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
724 DEBUG(dbgs() << "\nReplacing.1 ";
726 dbgs() << "\nWith: ";
727 To[0].getNode()->dump(&DAG);
728 dbgs() << " and " << NumTo-1 << " other values\n";
729 for (unsigned i = 0, e = NumTo; i != e; ++i)
730 assert((!To[i].getNode() ||
731 N->getValueType(i) == To[i].getValueType()) &&
732 "Cannot combine value to value of different type!"));
733 WorklistRemover DeadNodes(*this);
734 DAG.ReplaceAllUsesWith(N, To);
736 // Push the new nodes and any users onto the worklist
737 for (unsigned i = 0, e = NumTo; i != e; ++i) {
738 if (To[i].getNode()) {
739 AddToWorklist(To[i].getNode());
740 AddUsersToWorklist(To[i].getNode());
745 // Finally, if the node is now dead, remove it from the graph. The node
746 // may not be dead if the replacement process recursively simplified to
747 // something else needing this node.
748 if (N->use_empty()) {
749 // Nodes can be reintroduced into the worklist. Make sure we do not
750 // process a node that has been replaced.
751 removeFromWorklist(N);
753 // Finally, since the node is now dead, remove it from the graph.
756 return SDValue(N, 0);
760 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
761 // Replace all uses. If any nodes become isomorphic to other nodes and
762 // are deleted, make sure to remove them from our worklist.
763 WorklistRemover DeadNodes(*this);
764 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
766 // Push the new node and any (possibly new) users onto the worklist.
767 AddToWorklist(TLO.New.getNode());
768 AddUsersToWorklist(TLO.New.getNode());
770 // Finally, if the node is now dead, remove it from the graph. The node
771 // may not be dead if the replacement process recursively simplified to
772 // something else needing this node.
773 if (TLO.Old.getNode()->use_empty()) {
774 removeFromWorklist(TLO.Old.getNode());
776 // If the operands of this node are only used by the node, they will now
777 // be dead. Make sure to visit them first to delete dead nodes early.
778 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
779 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
780 AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
782 DAG.DeleteNode(TLO.Old.getNode());
786 /// SimplifyDemandedBits - Check the specified integer node value to see if
787 /// it can be simplified or if things it uses can be simplified by bit
788 /// propagation. If so, return true.
789 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
790 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
791 APInt KnownZero, KnownOne;
792 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
796 AddToWorklist(Op.getNode());
798 // Replace the old value with the new one.
800 DEBUG(dbgs() << "\nReplacing.2 ";
801 TLO.Old.getNode()->dump(&DAG);
802 dbgs() << "\nWith: ";
803 TLO.New.getNode()->dump(&DAG);
806 CommitTargetLoweringOpt(TLO);
810 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
812 EVT VT = Load->getValueType(0);
813 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
815 DEBUG(dbgs() << "\nReplacing.9 ";
817 dbgs() << "\nWith: ";
818 Trunc.getNode()->dump(&DAG);
820 WorklistRemover DeadNodes(*this);
821 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
822 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
823 removeFromWorklist(Load);
824 DAG.DeleteNode(Load);
825 AddToWorklist(Trunc.getNode());
828 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
832 EVT MemVT = LD->getMemoryVT();
833 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
834 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
836 : LD->getExtensionType();
838 return DAG.getExtLoad(ExtType, dl, PVT,
839 LD->getChain(), LD->getBasePtr(),
840 MemVT, LD->getMemOperand());
843 unsigned Opc = Op.getOpcode();
846 case ISD::AssertSext:
847 return DAG.getNode(ISD::AssertSext, dl, PVT,
848 SExtPromoteOperand(Op.getOperand(0), PVT),
850 case ISD::AssertZext:
851 return DAG.getNode(ISD::AssertZext, dl, PVT,
852 ZExtPromoteOperand(Op.getOperand(0), PVT),
854 case ISD::Constant: {
856 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
857 return DAG.getNode(ExtOpc, dl, PVT, Op);
861 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
863 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
866 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
867 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
869 EVT OldVT = Op.getValueType();
871 bool Replace = false;
872 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
873 if (!NewOp.getNode())
875 AddToWorklist(NewOp.getNode());
878 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
880 DAG.getValueType(OldVT));
883 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
884 EVT OldVT = Op.getValueType();
886 bool Replace = false;
887 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
888 if (!NewOp.getNode())
890 AddToWorklist(NewOp.getNode());
893 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
894 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
897 /// PromoteIntBinOp - Promote the specified integer binary operation if the
898 /// target indicates it is beneficial. e.g. On x86, it's usually better to
899 /// promote i16 operations to i32 since i16 instructions are longer.
900 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
901 if (!LegalOperations)
904 EVT VT = Op.getValueType();
905 if (VT.isVector() || !VT.isInteger())
908 // If operation type is 'undesirable', e.g. i16 on x86, consider
910 unsigned Opc = Op.getOpcode();
911 if (TLI.isTypeDesirableForOp(Opc, VT))
915 // Consult target whether it is a good idea to promote this operation and
916 // what's the right type to promote it to.
917 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
918 assert(PVT != VT && "Don't know what type to promote to!");
920 bool Replace0 = false;
921 SDValue N0 = Op.getOperand(0);
922 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926 bool Replace1 = false;
927 SDValue N1 = Op.getOperand(1);
932 NN1 = PromoteOperand(N1, PVT, Replace1);
937 AddToWorklist(NN0.getNode());
939 AddToWorklist(NN1.getNode());
942 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
944 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
946 DEBUG(dbgs() << "\nPromoting ";
947 Op.getNode()->dump(&DAG));
949 return DAG.getNode(ISD::TRUNCATE, dl, VT,
950 DAG.getNode(Opc, dl, PVT, NN0, NN1));
955 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
956 /// target indicates it is beneficial. e.g. On x86, it's usually better to
957 /// promote i16 operations to i32 since i16 instructions are longer.
958 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
959 if (!LegalOperations)
962 EVT VT = Op.getValueType();
963 if (VT.isVector() || !VT.isInteger())
966 // If operation type is 'undesirable', e.g. i16 on x86, consider
968 unsigned Opc = Op.getOpcode();
969 if (TLI.isTypeDesirableForOp(Opc, VT))
973 // Consult target whether it is a good idea to promote this operation and
974 // what's the right type to promote it to.
975 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
976 assert(PVT != VT && "Don't know what type to promote to!");
978 bool Replace = false;
979 SDValue N0 = Op.getOperand(0);
981 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
982 else if (Opc == ISD::SRL)
983 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
985 N0 = PromoteOperand(N0, PVT, Replace);
989 AddToWorklist(N0.getNode());
991 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
993 DEBUG(dbgs() << "\nPromoting ";
994 Op.getNode()->dump(&DAG));
996 return DAG.getNode(ISD::TRUNCATE, dl, VT,
997 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1002 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1003 if (!LegalOperations)
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector() || !VT.isInteger())
1010 // If operation type is 'undesirable', e.g. i16 on x86, consider
1012 unsigned Opc = Op.getOpcode();
1013 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 // Consult target whether it is a good idea to promote this operation and
1018 // what's the right type to promote it to.
1019 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020 assert(PVT != VT && "Don't know what type to promote to!");
1021 // fold (aext (aext x)) -> (aext x)
1022 // fold (aext (zext x)) -> (zext x)
1023 // fold (aext (sext x)) -> (sext x)
1024 DEBUG(dbgs() << "\nPromoting ";
1025 Op.getNode()->dump(&DAG));
1026 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1031 bool DAGCombiner::PromoteLoad(SDValue Op) {
1032 if (!LegalOperations)
1035 EVT VT = Op.getValueType();
1036 if (VT.isVector() || !VT.isInteger())
1039 // If operation type is 'undesirable', e.g. i16 on x86, consider
1041 unsigned Opc = Op.getOpcode();
1042 if (TLI.isTypeDesirableForOp(Opc, VT))
1046 // Consult target whether it is a good idea to promote this operation and
1047 // what's the right type to promote it to.
1048 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1049 assert(PVT != VT && "Don't know what type to promote to!");
1052 SDNode *N = Op.getNode();
1053 LoadSDNode *LD = cast<LoadSDNode>(N);
1054 EVT MemVT = LD->getMemoryVT();
1055 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1056 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1058 : LD->getExtensionType();
1059 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1060 LD->getChain(), LD->getBasePtr(),
1061 MemVT, LD->getMemOperand());
1062 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1064 DEBUG(dbgs() << "\nPromoting ";
1067 Result.getNode()->dump(&DAG);
1069 WorklistRemover DeadNodes(*this);
1070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1072 removeFromWorklist(N);
1074 AddToWorklist(Result.getNode());
1080 /// \brief Recursively delete a node which has no uses and any operands for
1081 /// which it is the only use.
1083 /// Note that this both deletes the nodes and removes them from the worklist.
1084 /// It also adds any nodes who have had a user deleted to the worklist as they
1085 /// may now have only one use and subject to other combines.
1086 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1087 if (!N->use_empty())
1090 SmallSetVector<SDNode *, 16> Nodes;
1093 N = Nodes.pop_back_val();
1097 if (N->use_empty()) {
1098 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1099 Nodes.insert(N->getOperand(i).getNode());
1101 removeFromWorklist(N);
1106 } while (!Nodes.empty());
1110 //===----------------------------------------------------------------------===//
1111 // Main DAG Combiner implementation
1112 //===----------------------------------------------------------------------===//
1114 void DAGCombiner::Run(CombineLevel AtLevel) {
1115 // set the instance variables, so that the various visit routines may use it.
1117 LegalOperations = Level >= AfterLegalizeVectorOps;
1118 LegalTypes = Level >= AfterLegalizeTypes;
1120 // Add all the dag nodes to the worklist.
1121 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1122 E = DAG.allnodes_end(); I != E; ++I)
1125 // Create a dummy node (which is not added to allnodes), that adds a reference
1126 // to the root node, preventing it from being deleted, and tracking any
1127 // changes of the root.
1128 HandleSDNode Dummy(DAG.getRoot());
1130 // The root of the dag may dangle to deleted nodes until the dag combiner is
1131 // done. Set it to null to avoid confusion.
1132 DAG.setRoot(SDValue());
1134 // while the worklist isn't empty, find a node and
1135 // try and combine it.
1136 while (!WorklistMap.empty()) {
1138 // The Worklist holds the SDNodes in order, but it may contain null entries.
1140 N = Worklist.pop_back_val();
1143 bool GoodWorklistEntry = WorklistMap.erase(N);
1144 (void)GoodWorklistEntry;
1145 assert(GoodWorklistEntry &&
1146 "Found a worklist entry without a corresponding map entry!");
1148 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1149 // N is deleted from the DAG, since they too may now be dead or may have a
1150 // reduced number of uses, allowing other xforms.
1151 if (recursivelyDeleteUnusedNodes(N))
1154 WorklistRemover DeadNodes(*this);
1156 SDValue RV = combine(N);
1163 // If we get back the same node we passed in, rather than a new node or
1164 // zero, we know that the node must have defined multiple values and
1165 // CombineTo was used. Since CombineTo takes care of the worklist
1166 // mechanics for us, we have no work to do in this case.
1167 if (RV.getNode() == N)
1170 assert(N->getOpcode() != ISD::DELETED_NODE &&
1171 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1172 "Node was deleted but visit returned new node!");
1174 DEBUG(dbgs() << "\nReplacing.3 ";
1176 dbgs() << "\nWith: ";
1177 RV.getNode()->dump(&DAG);
1180 // Transfer debug value.
1181 DAG.TransferDbgValues(SDValue(N, 0), RV);
1182 if (N->getNumValues() == RV.getNode()->getNumValues())
1183 DAG.ReplaceAllUsesWith(N, RV.getNode());
1185 assert(N->getValueType(0) == RV.getValueType() &&
1186 N->getNumValues() == 1 && "Type mismatch");
1188 DAG.ReplaceAllUsesWith(N, &OpV);
1191 // Push the new node and any users onto the worklist
1192 AddToWorklist(RV.getNode());
1193 AddUsersToWorklist(RV.getNode());
1195 // Finally, if the node is now dead, remove it from the graph. The node
1196 // may not be dead if the replacement process recursively simplified to
1197 // something else needing this node. This will also take care of adding any
1198 // operands which have lost a user to the worklist.
1199 recursivelyDeleteUnusedNodes(N);
1202 // If the root changed (e.g. it was a dead load, update the root).
1203 DAG.setRoot(Dummy.getValue());
1204 DAG.RemoveDeadNodes();
1207 SDValue DAGCombiner::visit(SDNode *N) {
1208 switch (N->getOpcode()) {
1210 case ISD::TokenFactor: return visitTokenFactor(N);
1211 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1212 case ISD::ADD: return visitADD(N);
1213 case ISD::SUB: return visitSUB(N);
1214 case ISD::ADDC: return visitADDC(N);
1215 case ISD::SUBC: return visitSUBC(N);
1216 case ISD::ADDE: return visitADDE(N);
1217 case ISD::SUBE: return visitSUBE(N);
1218 case ISD::MUL: return visitMUL(N);
1219 case ISD::SDIV: return visitSDIV(N);
1220 case ISD::UDIV: return visitUDIV(N);
1221 case ISD::SREM: return visitSREM(N);
1222 case ISD::UREM: return visitUREM(N);
1223 case ISD::MULHU: return visitMULHU(N);
1224 case ISD::MULHS: return visitMULHS(N);
1225 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1226 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1227 case ISD::SMULO: return visitSMULO(N);
1228 case ISD::UMULO: return visitUMULO(N);
1229 case ISD::SDIVREM: return visitSDIVREM(N);
1230 case ISD::UDIVREM: return visitUDIVREM(N);
1231 case ISD::AND: return visitAND(N);
1232 case ISD::OR: return visitOR(N);
1233 case ISD::XOR: return visitXOR(N);
1234 case ISD::SHL: return visitSHL(N);
1235 case ISD::SRA: return visitSRA(N);
1236 case ISD::SRL: return visitSRL(N);
1238 case ISD::ROTL: return visitRotate(N);
1239 case ISD::CTLZ: return visitCTLZ(N);
1240 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1241 case ISD::CTTZ: return visitCTTZ(N);
1242 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1243 case ISD::CTPOP: return visitCTPOP(N);
1244 case ISD::SELECT: return visitSELECT(N);
1245 case ISD::VSELECT: return visitVSELECT(N);
1246 case ISD::SELECT_CC: return visitSELECT_CC(N);
1247 case ISD::SETCC: return visitSETCC(N);
1248 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1249 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1250 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1251 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1252 case ISD::TRUNCATE: return visitTRUNCATE(N);
1253 case ISD::BITCAST: return visitBITCAST(N);
1254 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1255 case ISD::FADD: return visitFADD(N);
1256 case ISD::FSUB: return visitFSUB(N);
1257 case ISD::FMUL: return visitFMUL(N);
1258 case ISD::FMA: return visitFMA(N);
1259 case ISD::FDIV: return visitFDIV(N);
1260 case ISD::FREM: return visitFREM(N);
1261 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1262 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1263 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1264 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1265 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1266 case ISD::FP_ROUND: return visitFP_ROUND(N);
1267 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1268 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1269 case ISD::FNEG: return visitFNEG(N);
1270 case ISD::FABS: return visitFABS(N);
1271 case ISD::FFLOOR: return visitFFLOOR(N);
1272 case ISD::FCEIL: return visitFCEIL(N);
1273 case ISD::FTRUNC: return visitFTRUNC(N);
1274 case ISD::BRCOND: return visitBRCOND(N);
1275 case ISD::BR_CC: return visitBR_CC(N);
1276 case ISD::LOAD: return visitLOAD(N);
1277 case ISD::STORE: return visitSTORE(N);
1278 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1279 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1280 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1281 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1282 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1283 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1284 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1289 SDValue DAGCombiner::combine(SDNode *N) {
1290 SDValue RV = visit(N);
1292 // If nothing happened, try a target-specific DAG combine.
1293 if (!RV.getNode()) {
1294 assert(N->getOpcode() != ISD::DELETED_NODE &&
1295 "Node was deleted but visit returned NULL!");
1297 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1298 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1300 // Expose the DAG combiner to the target combiner impls.
1301 TargetLowering::DAGCombinerInfo
1302 DagCombineInfo(DAG, Level, false, this);
1304 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1308 // If nothing happened still, try promoting the operation.
1309 if (!RV.getNode()) {
1310 switch (N->getOpcode()) {
1318 RV = PromoteIntBinOp(SDValue(N, 0));
1323 RV = PromoteIntShiftOp(SDValue(N, 0));
1325 case ISD::SIGN_EXTEND:
1326 case ISD::ZERO_EXTEND:
1327 case ISD::ANY_EXTEND:
1328 RV = PromoteExtend(SDValue(N, 0));
1331 if (PromoteLoad(SDValue(N, 0)))
1337 // If N is a commutative binary node, try commuting it to enable more
1339 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1340 N->getNumValues() == 1) {
1341 SDValue N0 = N->getOperand(0);
1342 SDValue N1 = N->getOperand(1);
1344 // Constant operands are canonicalized to RHS.
1345 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1346 SDValue Ops[] = {N1, N0};
1348 if (const BinaryWithFlagsSDNode *BinNode =
1349 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1350 CSENode = DAG.getNodeIfExists(
1351 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1352 BinNode->hasNoSignedWrap(), BinNode->isExact());
1354 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1357 return SDValue(CSENode, 0);
1364 /// getInputChainForNode - Given a node, return its input chain if it has one,
1365 /// otherwise return a null sd operand.
1366 static SDValue getInputChainForNode(SDNode *N) {
1367 if (unsigned NumOps = N->getNumOperands()) {
1368 if (N->getOperand(0).getValueType() == MVT::Other)
1369 return N->getOperand(0);
1370 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1371 return N->getOperand(NumOps-1);
1372 for (unsigned i = 1; i < NumOps-1; ++i)
1373 if (N->getOperand(i).getValueType() == MVT::Other)
1374 return N->getOperand(i);
1379 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1380 // If N has two operands, where one has an input chain equal to the other,
1381 // the 'other' chain is redundant.
1382 if (N->getNumOperands() == 2) {
1383 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1384 return N->getOperand(0);
1385 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1386 return N->getOperand(1);
1389 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1390 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1391 SmallPtrSet<SDNode*, 16> SeenOps;
1392 bool Changed = false; // If we should replace this token factor.
1394 // Start out with this token factor.
1397 // Iterate through token factors. The TFs grows when new token factors are
1399 for (unsigned i = 0; i < TFs.size(); ++i) {
1400 SDNode *TF = TFs[i];
1402 // Check each of the operands.
1403 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1404 SDValue Op = TF->getOperand(i);
1406 switch (Op.getOpcode()) {
1407 case ISD::EntryToken:
1408 // Entry tokens don't need to be added to the list. They are
1413 case ISD::TokenFactor:
1414 if (Op.hasOneUse() &&
1415 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1416 // Queue up for processing.
1417 TFs.push_back(Op.getNode());
1418 // Clean up in case the token factor is removed.
1419 AddToWorklist(Op.getNode());
1426 // Only add if it isn't already in the list.
1427 if (SeenOps.insert(Op.getNode()))
1438 // If we've change things around then replace token factor.
1441 // The entry token is the only possible outcome.
1442 Result = DAG.getEntryNode();
1444 // New and improved token factor.
1445 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1448 // Don't add users to work list.
1449 return CombineTo(N, Result, false);
1455 /// MERGE_VALUES can always be eliminated.
1456 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1457 WorklistRemover DeadNodes(*this);
1458 // Replacing results may cause a different MERGE_VALUES to suddenly
1459 // be CSE'd with N, and carry its uses with it. Iterate until no
1460 // uses remain, to ensure that the node can be safely deleted.
1461 // First add the users of this node to the work list so that they
1462 // can be tried again once they have new operands.
1463 AddUsersToWorklist(N);
1465 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1467 } while (!N->use_empty());
1468 removeFromWorklist(N);
1470 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1474 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1475 SelectionDAG &DAG) {
1476 EVT VT = N0.getValueType();
1477 SDValue N00 = N0.getOperand(0);
1478 SDValue N01 = N0.getOperand(1);
1479 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1481 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1482 isa<ConstantSDNode>(N00.getOperand(1))) {
1483 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1484 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1485 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1486 N00.getOperand(0), N01),
1487 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1488 N00.getOperand(1), N01));
1489 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1495 SDValue DAGCombiner::visitADD(SDNode *N) {
1496 SDValue N0 = N->getOperand(0);
1497 SDValue N1 = N->getOperand(1);
1498 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1500 EVT VT = N0.getValueType();
1503 if (VT.isVector()) {
1504 SDValue FoldedVOp = SimplifyVBinOp(N);
1505 if (FoldedVOp.getNode()) return FoldedVOp;
1507 // fold (add x, 0) -> x, vector edition
1508 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1510 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1514 // fold (add x, undef) -> undef
1515 if (N0.getOpcode() == ISD::UNDEF)
1517 if (N1.getOpcode() == ISD::UNDEF)
1519 // fold (add c1, c2) -> c1+c2
1521 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1522 // canonicalize constant to RHS
1524 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1525 // fold (add x, 0) -> x
1526 if (N1C && N1C->isNullValue())
1528 // fold (add Sym, c) -> Sym+c
1529 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1530 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1531 GA->getOpcode() == ISD::GlobalAddress)
1532 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1534 (uint64_t)N1C->getSExtValue());
1535 // fold ((c1-A)+c2) -> (c1+c2)-A
1536 if (N1C && N0.getOpcode() == ISD::SUB)
1537 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1538 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539 DAG.getConstant(N1C->getAPIntValue()+
1540 N0C->getAPIntValue(), VT),
1543 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1546 // fold ((0-A) + B) -> B-A
1547 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1548 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1550 // fold (A + (0-B)) -> A-B
1551 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1552 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1553 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1554 // fold (A+(B-A)) -> B
1555 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1556 return N1.getOperand(0);
1557 // fold ((B-A)+A) -> B
1558 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1559 return N0.getOperand(0);
1560 // fold (A+(B-(A+C))) to (B-C)
1561 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1562 N0 == N1.getOperand(1).getOperand(0))
1563 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1564 N1.getOperand(1).getOperand(1));
1565 // fold (A+(B-(C+A))) to (B-C)
1566 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1567 N0 == N1.getOperand(1).getOperand(1))
1568 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1569 N1.getOperand(1).getOperand(0));
1570 // fold (A+((B-A)+or-C)) to (B+or-C)
1571 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1572 N1.getOperand(0).getOpcode() == ISD::SUB &&
1573 N0 == N1.getOperand(0).getOperand(1))
1574 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1575 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1577 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1578 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1579 SDValue N00 = N0.getOperand(0);
1580 SDValue N01 = N0.getOperand(1);
1581 SDValue N10 = N1.getOperand(0);
1582 SDValue N11 = N1.getOperand(1);
1584 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1585 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1586 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1587 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1590 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1591 return SDValue(N, 0);
1593 // fold (a+b) -> (a|b) iff a and b share no bits.
1594 if (VT.isInteger() && !VT.isVector()) {
1595 APInt LHSZero, LHSOne;
1596 APInt RHSZero, RHSOne;
1597 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1599 if (LHSZero.getBoolValue()) {
1600 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1602 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1603 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1604 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1605 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1606 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1611 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1612 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1613 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1614 if (Result.getNode()) return Result;
1616 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1617 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1618 if (Result.getNode()) return Result;
1621 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1622 if (N1.getOpcode() == ISD::SHL &&
1623 N1.getOperand(0).getOpcode() == ISD::SUB)
1624 if (ConstantSDNode *C =
1625 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1626 if (C->getAPIntValue() == 0)
1627 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1628 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1629 N1.getOperand(0).getOperand(1),
1631 if (N0.getOpcode() == ISD::SHL &&
1632 N0.getOperand(0).getOpcode() == ISD::SUB)
1633 if (ConstantSDNode *C =
1634 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1635 if (C->getAPIntValue() == 0)
1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1637 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1638 N0.getOperand(0).getOperand(1),
1641 if (N1.getOpcode() == ISD::AND) {
1642 SDValue AndOp0 = N1.getOperand(0);
1643 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1644 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1645 unsigned DestBits = VT.getScalarType().getSizeInBits();
1647 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1648 // and similar xforms where the inner op is either ~0 or 0.
1649 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1651 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1655 // add (sext i1), X -> sub X, (zext i1)
1656 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1657 N0.getOperand(0).getValueType() == MVT::i1 &&
1658 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1660 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1661 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1667 SDValue DAGCombiner::visitADDC(SDNode *N) {
1668 SDValue N0 = N->getOperand(0);
1669 SDValue N1 = N->getOperand(1);
1670 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1672 EVT VT = N0.getValueType();
1674 // If the flag result is dead, turn this into an ADD.
1675 if (!N->hasAnyUseOfValue(1))
1676 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1677 DAG.getNode(ISD::CARRY_FALSE,
1678 SDLoc(N), MVT::Glue));
1680 // canonicalize constant to RHS.
1682 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1684 // fold (addc x, 0) -> x + no carry out
1685 if (N1C && N1C->isNullValue())
1686 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1687 SDLoc(N), MVT::Glue));
1689 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1690 APInt LHSZero, LHSOne;
1691 APInt RHSZero, RHSOne;
1692 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1694 if (LHSZero.getBoolValue()) {
1695 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1697 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1698 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1699 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1700 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1701 DAG.getNode(ISD::CARRY_FALSE,
1702 SDLoc(N), MVT::Glue));
1708 SDValue DAGCombiner::visitADDE(SDNode *N) {
1709 SDValue N0 = N->getOperand(0);
1710 SDValue N1 = N->getOperand(1);
1711 SDValue CarryIn = N->getOperand(2);
1712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715 // canonicalize constant to RHS
1717 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1720 // fold (adde x, y, false) -> (addc x, y)
1721 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1722 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1727 // Since it may not be valid to emit a fold to zero for vector initializers
1728 // check if we can before folding.
1729 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1731 bool LegalOperations, bool LegalTypes) {
1733 return DAG.getConstant(0, VT);
1734 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1735 return DAG.getConstant(0, VT);
1739 SDValue DAGCombiner::visitSUB(SDNode *N) {
1740 SDValue N0 = N->getOperand(0);
1741 SDValue N1 = N->getOperand(1);
1742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1743 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1744 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1745 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1746 EVT VT = N0.getValueType();
1749 if (VT.isVector()) {
1750 SDValue FoldedVOp = SimplifyVBinOp(N);
1751 if (FoldedVOp.getNode()) return FoldedVOp;
1753 // fold (sub x, 0) -> x, vector edition
1754 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1758 // fold (sub x, x) -> 0
1759 // FIXME: Refactor this and xor and other similar operations together.
1761 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1762 // fold (sub c1, c2) -> c1-c2
1764 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1765 // fold (sub x, c) -> (add x, -c)
1767 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1768 DAG.getConstant(-N1C->getAPIntValue(), VT));
1769 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1770 if (N0C && N0C->isAllOnesValue())
1771 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1772 // fold A-(A-B) -> B
1773 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1774 return N1.getOperand(1);
1775 // fold (A+B)-A -> B
1776 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1777 return N0.getOperand(1);
1778 // fold (A+B)-B -> A
1779 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1780 return N0.getOperand(0);
1781 // fold C2-(A+C1) -> (C2-C1)-A
1782 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1783 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1785 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1788 // fold ((A+(B+or-C))-B) -> A+or-C
1789 if (N0.getOpcode() == ISD::ADD &&
1790 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1791 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1792 N0.getOperand(1).getOperand(0) == N1)
1793 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1794 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1795 // fold ((A+(C+B))-B) -> A+C
1796 if (N0.getOpcode() == ISD::ADD &&
1797 N0.getOperand(1).getOpcode() == ISD::ADD &&
1798 N0.getOperand(1).getOperand(1) == N1)
1799 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1800 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1801 // fold ((A-(B-C))-C) -> A-B
1802 if (N0.getOpcode() == ISD::SUB &&
1803 N0.getOperand(1).getOpcode() == ISD::SUB &&
1804 N0.getOperand(1).getOperand(1) == N1)
1805 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1806 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1808 // If either operand of a sub is undef, the result is undef
1809 if (N0.getOpcode() == ISD::UNDEF)
1811 if (N1.getOpcode() == ISD::UNDEF)
1814 // If the relocation model supports it, consider symbol offsets.
1815 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1816 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1817 // fold (sub Sym, c) -> Sym-c
1818 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1819 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1821 (uint64_t)N1C->getSExtValue());
1822 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1823 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1824 if (GA->getGlobal() == GB->getGlobal())
1825 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1832 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1833 SDValue N0 = N->getOperand(0);
1834 SDValue N1 = N->getOperand(1);
1835 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1836 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1837 EVT VT = N0.getValueType();
1839 // If the flag result is dead, turn this into an SUB.
1840 if (!N->hasAnyUseOfValue(1))
1841 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1842 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1845 // fold (subc x, x) -> 0 + no borrow
1847 return CombineTo(N, DAG.getConstant(0, VT),
1848 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1851 // fold (subc x, 0) -> x + no borrow
1852 if (N1C && N1C->isNullValue())
1853 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1856 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1857 if (N0C && N0C->isAllOnesValue())
1858 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1859 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1865 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1866 SDValue N0 = N->getOperand(0);
1867 SDValue N1 = N->getOperand(1);
1868 SDValue CarryIn = N->getOperand(2);
1870 // fold (sube x, y, false) -> (subc x, y)
1871 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1872 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1877 SDValue DAGCombiner::visitMUL(SDNode *N) {
1878 SDValue N0 = N->getOperand(0);
1879 SDValue N1 = N->getOperand(1);
1880 EVT VT = N0.getValueType();
1882 // fold (mul x, undef) -> 0
1883 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1884 return DAG.getConstant(0, VT);
1886 bool N0IsConst = false;
1887 bool N1IsConst = false;
1888 APInt ConstValue0, ConstValue1;
1890 if (VT.isVector()) {
1891 SDValue FoldedVOp = SimplifyVBinOp(N);
1892 if (FoldedVOp.getNode()) return FoldedVOp;
1894 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1895 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1897 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1898 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1900 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1901 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1905 // fold (mul c1, c2) -> c1*c2
1906 if (N0IsConst && N1IsConst)
1907 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1909 // canonicalize constant to RHS
1910 if (N0IsConst && !N1IsConst)
1911 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1912 // fold (mul x, 0) -> 0
1913 if (N1IsConst && ConstValue1 == 0)
1915 // We require a splat of the entire scalar bit width for non-contiguous
1918 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1919 // fold (mul x, 1) -> x
1920 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1922 // fold (mul x, -1) -> 0-x
1923 if (N1IsConst && ConstValue1.isAllOnesValue())
1924 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1925 DAG.getConstant(0, VT), N0);
1926 // fold (mul x, (1 << c)) -> x << c
1927 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1928 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1929 DAG.getConstant(ConstValue1.logBase2(),
1930 getShiftAmountTy(N0.getValueType())));
1931 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1932 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1933 unsigned Log2Val = (-ConstValue1).logBase2();
1934 // FIXME: If the input is something that is easily negated (e.g. a
1935 // single-use add), we should put the negate there.
1936 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1937 DAG.getConstant(0, VT),
1938 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1939 DAG.getConstant(Log2Val,
1940 getShiftAmountTy(N0.getValueType()))));
1944 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1945 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1946 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1947 isa<ConstantSDNode>(N0.getOperand(1)))) {
1948 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1949 N1, N0.getOperand(1));
1950 AddToWorklist(C3.getNode());
1951 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1952 N0.getOperand(0), C3);
1955 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1958 SDValue Sh(nullptr,0), Y(nullptr,0);
1959 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1960 if (N0.getOpcode() == ISD::SHL &&
1961 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1962 isa<ConstantSDNode>(N0.getOperand(1))) &&
1963 N0.getNode()->hasOneUse()) {
1965 } else if (N1.getOpcode() == ISD::SHL &&
1966 isa<ConstantSDNode>(N1.getOperand(1)) &&
1967 N1.getNode()->hasOneUse()) {
1972 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1973 Sh.getOperand(0), Y);
1974 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1975 Mul, Sh.getOperand(1));
1979 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1980 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1981 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1982 isa<ConstantSDNode>(N0.getOperand(1))))
1983 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1984 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1985 N0.getOperand(0), N1),
1986 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1987 N0.getOperand(1), N1));
1990 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1997 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1998 SDValue N0 = N->getOperand(0);
1999 SDValue N1 = N->getOperand(1);
2000 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2001 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2002 EVT VT = N->getValueType(0);
2005 if (VT.isVector()) {
2006 SDValue FoldedVOp = SimplifyVBinOp(N);
2007 if (FoldedVOp.getNode()) return FoldedVOp;
2010 // fold (sdiv c1, c2) -> c1/c2
2011 if (N0C && N1C && !N1C->isNullValue())
2012 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2013 // fold (sdiv X, 1) -> X
2014 if (N1C && N1C->getAPIntValue() == 1LL)
2016 // fold (sdiv X, -1) -> 0-X
2017 if (N1C && N1C->isAllOnesValue())
2018 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2019 DAG.getConstant(0, VT), N0);
2020 // If we know the sign bits of both operands are zero, strength reduce to a
2021 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2022 if (!VT.isVector()) {
2023 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2024 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2028 // fold (sdiv X, pow2) -> simple ops after legalize
2029 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2030 (-N1C->getAPIntValue()).isPowerOf2())) {
2031 // If dividing by powers of two is cheap, then don't perform the following
2033 if (TLI.isPow2DivCheap())
2036 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2038 // Splat the sign bit into the register
2040 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2041 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2042 getShiftAmountTy(N0.getValueType())));
2043 AddToWorklist(SGN.getNode());
2045 // Add (N0 < 0) ? abs2 - 1 : 0;
2047 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2048 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2049 getShiftAmountTy(SGN.getValueType())));
2050 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2051 AddToWorklist(SRL.getNode());
2052 AddToWorklist(ADD.getNode()); // Divide by pow2
2053 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2054 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2056 // If we're dividing by a positive value, we're done. Otherwise, we must
2057 // negate the result.
2058 if (N1C->getAPIntValue().isNonNegative())
2061 AddToWorklist(SRA.getNode());
2062 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2065 // if integer divide is expensive and we satisfy the requirements, emit an
2066 // alternate sequence.
2067 if (N1C && !TLI.isIntDivCheap()) {
2068 SDValue Op = BuildSDIV(N);
2069 if (Op.getNode()) return Op;
2073 if (N0.getOpcode() == ISD::UNDEF)
2074 return DAG.getConstant(0, VT);
2075 // X / undef -> undef
2076 if (N1.getOpcode() == ISD::UNDEF)
2082 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2083 SDValue N0 = N->getOperand(0);
2084 SDValue N1 = N->getOperand(1);
2085 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2086 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2087 EVT VT = N->getValueType(0);
2090 if (VT.isVector()) {
2091 SDValue FoldedVOp = SimplifyVBinOp(N);
2092 if (FoldedVOp.getNode()) return FoldedVOp;
2095 // fold (udiv c1, c2) -> c1/c2
2096 if (N0C && N1C && !N1C->isNullValue())
2097 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2098 // fold (udiv x, (1 << c)) -> x >>u c
2099 if (N1C && N1C->getAPIntValue().isPowerOf2())
2100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2101 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2102 getShiftAmountTy(N0.getValueType())));
2103 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2104 if (N1.getOpcode() == ISD::SHL) {
2105 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2106 if (SHC->getAPIntValue().isPowerOf2()) {
2107 EVT ADDVT = N1.getOperand(1).getValueType();
2108 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2110 DAG.getConstant(SHC->getAPIntValue()
2113 AddToWorklist(Add.getNode());
2114 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2118 // fold (udiv x, c) -> alternate
2119 if (N1C && !TLI.isIntDivCheap()) {
2120 SDValue Op = BuildUDIV(N);
2121 if (Op.getNode()) return Op;
2125 if (N0.getOpcode() == ISD::UNDEF)
2126 return DAG.getConstant(0, VT);
2127 // X / undef -> undef
2128 if (N1.getOpcode() == ISD::UNDEF)
2134 SDValue DAGCombiner::visitSREM(SDNode *N) {
2135 SDValue N0 = N->getOperand(0);
2136 SDValue N1 = N->getOperand(1);
2137 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2138 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2139 EVT VT = N->getValueType(0);
2141 // fold (srem c1, c2) -> c1%c2
2142 if (N0C && N1C && !N1C->isNullValue())
2143 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2144 // If we know the sign bits of both operands are zero, strength reduce to a
2145 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2146 if (!VT.isVector()) {
2147 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2148 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2151 // If X/C can be simplified by the division-by-constant logic, lower
2152 // X%C to the equivalent of X-X/C*C.
2153 if (N1C && !N1C->isNullValue()) {
2154 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2155 AddToWorklist(Div.getNode());
2156 SDValue OptimizedDiv = combine(Div.getNode());
2157 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2158 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2160 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2161 AddToWorklist(Mul.getNode());
2167 if (N0.getOpcode() == ISD::UNDEF)
2168 return DAG.getConstant(0, VT);
2169 // X % undef -> undef
2170 if (N1.getOpcode() == ISD::UNDEF)
2176 SDValue DAGCombiner::visitUREM(SDNode *N) {
2177 SDValue N0 = N->getOperand(0);
2178 SDValue N1 = N->getOperand(1);
2179 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2180 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2181 EVT VT = N->getValueType(0);
2183 // fold (urem c1, c2) -> c1%c2
2184 if (N0C && N1C && !N1C->isNullValue())
2185 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2186 // fold (urem x, pow2) -> (and x, pow2-1)
2187 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2188 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2189 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2190 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2191 if (N1.getOpcode() == ISD::SHL) {
2192 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2193 if (SHC->getAPIntValue().isPowerOf2()) {
2195 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2196 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2198 AddToWorklist(Add.getNode());
2199 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2204 // If X/C can be simplified by the division-by-constant logic, lower
2205 // X%C to the equivalent of X-X/C*C.
2206 if (N1C && !N1C->isNullValue()) {
2207 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2208 AddToWorklist(Div.getNode());
2209 SDValue OptimizedDiv = combine(Div.getNode());
2210 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2211 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2213 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2214 AddToWorklist(Mul.getNode());
2220 if (N0.getOpcode() == ISD::UNDEF)
2221 return DAG.getConstant(0, VT);
2222 // X % undef -> undef
2223 if (N1.getOpcode() == ISD::UNDEF)
2229 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2230 SDValue N0 = N->getOperand(0);
2231 SDValue N1 = N->getOperand(1);
2232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2233 EVT VT = N->getValueType(0);
2236 // fold (mulhs x, 0) -> 0
2237 if (N1C && N1C->isNullValue())
2239 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2240 if (N1C && N1C->getAPIntValue() == 1)
2241 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2242 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2243 getShiftAmountTy(N0.getValueType())));
2244 // fold (mulhs x, undef) -> 0
2245 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, VT);
2248 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2250 if (VT.isSimple() && !VT.isVector()) {
2251 MVT Simple = VT.getSimpleVT();
2252 unsigned SimpleSize = Simple.getSizeInBits();
2253 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2254 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2255 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2256 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2257 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2258 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2259 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2260 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2267 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2268 SDValue N0 = N->getOperand(0);
2269 SDValue N1 = N->getOperand(1);
2270 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2271 EVT VT = N->getValueType(0);
2274 // fold (mulhu x, 0) -> 0
2275 if (N1C && N1C->isNullValue())
2277 // fold (mulhu x, 1) -> 0
2278 if (N1C && N1C->getAPIntValue() == 1)
2279 return DAG.getConstant(0, N0.getValueType());
2280 // fold (mulhu x, undef) -> 0
2281 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2282 return DAG.getConstant(0, VT);
2284 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2286 if (VT.isSimple() && !VT.isVector()) {
2287 MVT Simple = VT.getSimpleVT();
2288 unsigned SimpleSize = Simple.getSizeInBits();
2289 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2290 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2291 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2292 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2293 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2294 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2295 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2296 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2303 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2304 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2305 /// that are being performed. Return true if a simplification was made.
2307 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2309 // If the high half is not needed, just compute the low half.
2310 bool HiExists = N->hasAnyUseOfValue(1);
2312 (!LegalOperations ||
2313 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2314 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2315 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2316 return CombineTo(N, Res, Res);
2319 // If the low half is not needed, just compute the high half.
2320 bool LoExists = N->hasAnyUseOfValue(0);
2322 (!LegalOperations ||
2323 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2324 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2325 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2326 return CombineTo(N, Res, Res);
2329 // If both halves are used, return as it is.
2330 if (LoExists && HiExists)
2333 // If the two computed results can be simplified separately, separate them.
2335 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2336 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2337 AddToWorklist(Lo.getNode());
2338 SDValue LoOpt = combine(Lo.getNode());
2339 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2340 (!LegalOperations ||
2341 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2342 return CombineTo(N, LoOpt, LoOpt);
2346 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2347 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2348 AddToWorklist(Hi.getNode());
2349 SDValue HiOpt = combine(Hi.getNode());
2350 if (HiOpt.getNode() && HiOpt != Hi &&
2351 (!LegalOperations ||
2352 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2353 return CombineTo(N, HiOpt, HiOpt);
2359 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2360 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2361 if (Res.getNode()) return Res;
2363 EVT VT = N->getValueType(0);
2366 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2368 if (VT.isSimple() && !VT.isVector()) {
2369 MVT Simple = VT.getSimpleVT();
2370 unsigned SimpleSize = Simple.getSizeInBits();
2371 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2372 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2373 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2374 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2375 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2376 // Compute the high part as N1.
2377 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2378 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2379 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2380 // Compute the low part as N0.
2381 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2382 return CombineTo(N, Lo, Hi);
2389 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2390 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2391 if (Res.getNode()) return Res;
2393 EVT VT = N->getValueType(0);
2396 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2398 if (VT.isSimple() && !VT.isVector()) {
2399 MVT Simple = VT.getSimpleVT();
2400 unsigned SimpleSize = Simple.getSizeInBits();
2401 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2402 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2403 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2404 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2405 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2406 // Compute the high part as N1.
2407 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2408 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2409 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2410 // Compute the low part as N0.
2411 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2412 return CombineTo(N, Lo, Hi);
2419 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2420 // (smulo x, 2) -> (saddo x, x)
2421 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2422 if (C2->getAPIntValue() == 2)
2423 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2424 N->getOperand(0), N->getOperand(0));
2429 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2430 // (umulo x, 2) -> (uaddo x, x)
2431 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2432 if (C2->getAPIntValue() == 2)
2433 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2434 N->getOperand(0), N->getOperand(0));
2439 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2440 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2441 if (Res.getNode()) return Res;
2446 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2447 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2448 if (Res.getNode()) return Res;
2453 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2454 /// two operands of the same opcode, try to simplify it.
2455 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2456 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2457 EVT VT = N0.getValueType();
2458 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2460 // Bail early if none of these transforms apply.
2461 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2463 // For each of OP in AND/OR/XOR:
2464 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2465 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2466 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2467 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2469 // do not sink logical op inside of a vector extend, since it may combine
2471 EVT Op0VT = N0.getOperand(0).getValueType();
2472 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2473 N0.getOpcode() == ISD::SIGN_EXTEND ||
2474 // Avoid infinite looping with PromoteIntBinOp.
2475 (N0.getOpcode() == ISD::ANY_EXTEND &&
2476 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2477 (N0.getOpcode() == ISD::TRUNCATE &&
2478 (!TLI.isZExtFree(VT, Op0VT) ||
2479 !TLI.isTruncateFree(Op0VT, VT)) &&
2480 TLI.isTypeLegal(Op0VT))) &&
2482 Op0VT == N1.getOperand(0).getValueType() &&
2483 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2484 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2485 N0.getOperand(0).getValueType(),
2486 N0.getOperand(0), N1.getOperand(0));
2487 AddToWorklist(ORNode.getNode());
2488 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2491 // For each of OP in SHL/SRL/SRA/AND...
2492 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2493 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2494 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2495 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2496 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2497 N0.getOperand(1) == N1.getOperand(1)) {
2498 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2499 N0.getOperand(0).getValueType(),
2500 N0.getOperand(0), N1.getOperand(0));
2501 AddToWorklist(ORNode.getNode());
2502 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2503 ORNode, N0.getOperand(1));
2506 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2507 // Only perform this optimization after type legalization and before
2508 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2509 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2510 // we don't want to undo this promotion.
2511 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2513 if ((N0.getOpcode() == ISD::BITCAST ||
2514 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2515 Level == AfterLegalizeTypes) {
2516 SDValue In0 = N0.getOperand(0);
2517 SDValue In1 = N1.getOperand(0);
2518 EVT In0Ty = In0.getValueType();
2519 EVT In1Ty = In1.getValueType();
2521 // If both incoming values are integers, and the original types are the
2523 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2524 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2525 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2526 AddToWorklist(Op.getNode());
2531 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2532 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2533 // If both shuffles use the same mask, and both shuffle within a single
2534 // vector, then it is worthwhile to move the swizzle after the operation.
2535 // The type-legalizer generates this pattern when loading illegal
2536 // vector types from memory. In many cases this allows additional shuffle
2538 // There are other cases where moving the shuffle after the xor/and/or
2539 // is profitable even if shuffles don't perform a swizzle.
2540 // If both shuffles use the same mask, and both shuffles have the same first
2541 // or second operand, then it might still be profitable to move the shuffle
2542 // after the xor/and/or operation.
2543 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2544 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2545 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2547 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2548 "Inputs to shuffles are not the same type");
2550 // Check that both shuffles use the same mask. The masks are known to be of
2551 // the same length because the result vector type is the same.
2552 // Check also that shuffles have only one use to avoid introducing extra
2554 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2555 SVN0->getMask().equals(SVN1->getMask())) {
2556 SDValue ShOp = N0->getOperand(1);
2558 // Don't try to fold this node if it requires introducing a
2559 // build vector of all zeros that might be illegal at this stage.
2560 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2562 ShOp = DAG.getConstant(0, VT);
2567 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2568 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2569 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2570 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2571 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2572 N0->getOperand(0), N1->getOperand(0));
2573 AddToWorklist(NewNode.getNode());
2574 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2575 &SVN0->getMask()[0]);
2578 // Don't try to fold this node if it requires introducing a
2579 // build vector of all zeros that might be illegal at this stage.
2580 ShOp = N0->getOperand(0);
2581 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2583 ShOp = DAG.getConstant(0, VT);
2588 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2589 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2590 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2591 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2592 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2593 N0->getOperand(1), N1->getOperand(1));
2594 AddToWorklist(NewNode.getNode());
2595 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2596 &SVN0->getMask()[0]);
2604 SDValue DAGCombiner::visitAND(SDNode *N) {
2605 SDValue N0 = N->getOperand(0);
2606 SDValue N1 = N->getOperand(1);
2607 SDValue LL, LR, RL, RR, CC0, CC1;
2608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2610 EVT VT = N1.getValueType();
2611 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2614 if (VT.isVector()) {
2615 SDValue FoldedVOp = SimplifyVBinOp(N);
2616 if (FoldedVOp.getNode()) return FoldedVOp;
2618 // fold (and x, 0) -> 0, vector edition
2619 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2621 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2624 // fold (and x, -1) -> x, vector edition
2625 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2627 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2631 // fold (and x, undef) -> 0
2632 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2633 return DAG.getConstant(0, VT);
2634 // fold (and c1, c2) -> c1&c2
2636 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2637 // canonicalize constant to RHS
2639 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2640 // fold (and x, -1) -> x
2641 if (N1C && N1C->isAllOnesValue())
2643 // if (and x, c) is known to be zero, return 0
2644 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2645 APInt::getAllOnesValue(BitWidth)))
2646 return DAG.getConstant(0, VT);
2648 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2651 // fold (and (or x, C), D) -> D if (C & D) == D
2652 if (N1C && N0.getOpcode() == ISD::OR)
2653 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2654 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2656 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2657 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2658 SDValue N0Op0 = N0.getOperand(0);
2659 APInt Mask = ~N1C->getAPIntValue();
2660 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2661 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2662 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2663 N0.getValueType(), N0Op0);
2665 // Replace uses of the AND with uses of the Zero extend node.
2668 // We actually want to replace all uses of the any_extend with the
2669 // zero_extend, to avoid duplicating things. This will later cause this
2670 // AND to be folded.
2671 CombineTo(N0.getNode(), Zext);
2672 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2675 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2676 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2677 // already be zero by virtue of the width of the base type of the load.
2679 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2681 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2682 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2683 N0.getOpcode() == ISD::LOAD) {
2684 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2685 N0 : N0.getOperand(0) );
2687 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2688 // This can be a pure constant or a vector splat, in which case we treat the
2689 // vector as a scalar and use the splat value.
2690 APInt Constant = APInt::getNullValue(1);
2691 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2692 Constant = C->getAPIntValue();
2693 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2694 APInt SplatValue, SplatUndef;
2695 unsigned SplatBitSize;
2697 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2698 SplatBitSize, HasAnyUndefs);
2700 // Undef bits can contribute to a possible optimisation if set, so
2702 SplatValue |= SplatUndef;
2704 // The splat value may be something like "0x00FFFFFF", which means 0 for
2705 // the first vector value and FF for the rest, repeating. We need a mask
2706 // that will apply equally to all members of the vector, so AND all the
2707 // lanes of the constant together.
2708 EVT VT = Vector->getValueType(0);
2709 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2711 // If the splat value has been compressed to a bitlength lower
2712 // than the size of the vector lane, we need to re-expand it to
2714 if (BitWidth > SplatBitSize)
2715 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2716 SplatBitSize < BitWidth;
2717 SplatBitSize = SplatBitSize * 2)
2718 SplatValue |= SplatValue.shl(SplatBitSize);
2720 Constant = APInt::getAllOnesValue(BitWidth);
2721 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2722 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2726 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2727 // actually legal and isn't going to get expanded, else this is a false
2729 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2730 Load->getMemoryVT());
2732 // Resize the constant to the same size as the original memory access before
2733 // extension. If it is still the AllOnesValue then this AND is completely
2736 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2739 switch (Load->getExtensionType()) {
2740 default: B = false; break;
2741 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2743 case ISD::NON_EXTLOAD: B = true; break;
2746 if (B && Constant.isAllOnesValue()) {
2747 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2748 // preserve semantics once we get rid of the AND.
2749 SDValue NewLoad(Load, 0);
2750 if (Load->getExtensionType() == ISD::EXTLOAD) {
2751 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2752 Load->getValueType(0), SDLoc(Load),
2753 Load->getChain(), Load->getBasePtr(),
2754 Load->getOffset(), Load->getMemoryVT(),
2755 Load->getMemOperand());
2756 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2757 if (Load->getNumValues() == 3) {
2758 // PRE/POST_INC loads have 3 values.
2759 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2760 NewLoad.getValue(2) };
2761 CombineTo(Load, To, 3, true);
2763 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2767 // Fold the AND away, taking care not to fold to the old load node if we
2769 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2771 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2774 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2775 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2776 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2777 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2779 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2780 LL.getValueType().isInteger()) {
2781 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2782 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2783 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2784 LR.getValueType(), LL, RL);
2785 AddToWorklist(ORNode.getNode());
2786 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2788 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2789 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2790 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2791 LR.getValueType(), LL, RL);
2792 AddToWorklist(ANDNode.getNode());
2793 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2795 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2796 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2797 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2798 LR.getValueType(), LL, RL);
2799 AddToWorklist(ORNode.getNode());
2800 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2803 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2804 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2805 Op0 == Op1 && LL.getValueType().isInteger() &&
2806 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2807 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2808 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2809 cast<ConstantSDNode>(RR)->isNullValue()))) {
2810 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2811 LL, DAG.getConstant(1, LL.getValueType()));
2812 AddToWorklist(ADDNode.getNode());
2813 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2814 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2816 // canonicalize equivalent to ll == rl
2817 if (LL == RR && LR == RL) {
2818 Op1 = ISD::getSetCCSwappedOperands(Op1);
2821 if (LL == RL && LR == RR) {
2822 bool isInteger = LL.getValueType().isInteger();
2823 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2824 if (Result != ISD::SETCC_INVALID &&
2825 (!LegalOperations ||
2826 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2827 TLI.isOperationLegal(ISD::SETCC,
2828 getSetCCResultType(N0.getSimpleValueType())))))
2829 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2834 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2835 if (N0.getOpcode() == N1.getOpcode()) {
2836 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2837 if (Tmp.getNode()) return Tmp;
2840 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2841 // fold (and (sra)) -> (and (srl)) when possible.
2842 if (!VT.isVector() &&
2843 SimplifyDemandedBits(SDValue(N, 0)))
2844 return SDValue(N, 0);
2846 // fold (zext_inreg (extload x)) -> (zextload x)
2847 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2848 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2849 EVT MemVT = LN0->getMemoryVT();
2850 // If we zero all the possible extended bits, then we can turn this into
2851 // a zextload if we are running before legalize or the operation is legal.
2852 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2853 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2854 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2855 ((!LegalOperations && !LN0->isVolatile()) ||
2856 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2857 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2858 LN0->getChain(), LN0->getBasePtr(),
2859 MemVT, LN0->getMemOperand());
2861 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2862 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2865 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2866 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2868 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2869 EVT MemVT = LN0->getMemoryVT();
2870 // If we zero all the possible extended bits, then we can turn this into
2871 // a zextload if we are running before legalize or the operation is legal.
2872 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2873 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2874 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2875 ((!LegalOperations && !LN0->isVolatile()) ||
2876 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2877 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2878 LN0->getChain(), LN0->getBasePtr(),
2879 MemVT, LN0->getMemOperand());
2881 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2886 // fold (and (load x), 255) -> (zextload x, i8)
2887 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2888 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2889 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2890 (N0.getOpcode() == ISD::ANY_EXTEND &&
2891 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2892 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2893 LoadSDNode *LN0 = HasAnyExt
2894 ? cast<LoadSDNode>(N0.getOperand(0))
2895 : cast<LoadSDNode>(N0);
2896 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2897 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2898 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2899 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2900 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2901 EVT LoadedVT = LN0->getMemoryVT();
2903 if (ExtVT == LoadedVT &&
2904 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2905 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2908 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2909 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2910 LN0->getMemOperand());
2912 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2916 // Do not change the width of a volatile load.
2917 // Do not generate loads of non-round integer types since these can
2918 // be expensive (and would be wrong if the type is not byte sized).
2919 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2920 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2921 EVT PtrType = LN0->getOperand(1).getValueType();
2923 unsigned Alignment = LN0->getAlignment();
2924 SDValue NewPtr = LN0->getBasePtr();
2926 // For big endian targets, we need to add an offset to the pointer
2927 // to load the correct bytes. For little endian systems, we merely
2928 // need to read fewer bytes from the same pointer.
2929 if (TLI.isBigEndian()) {
2930 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2931 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2932 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2933 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2934 NewPtr, DAG.getConstant(PtrOff, PtrType));
2935 Alignment = MinAlign(Alignment, PtrOff);
2938 AddToWorklist(NewPtr.getNode());
2940 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2942 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2943 LN0->getChain(), NewPtr,
2944 LN0->getPointerInfo(),
2945 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2946 Alignment, LN0->getTBAAInfo());
2948 CombineTo(LN0, Load, Load.getValue(1));
2949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2955 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2956 VT.getSizeInBits() <= 64) {
2957 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2958 APInt ADDC = ADDI->getAPIntValue();
2959 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2960 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2961 // immediate for an add, but it is legal if its top c2 bits are set,
2962 // transform the ADD so the immediate doesn't need to be materialized
2964 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2965 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2966 SRLI->getZExtValue());
2967 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2969 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2971 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2972 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2973 CombineTo(N0.getNode(), NewAdd);
2974 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2982 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2983 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2984 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2985 N0.getOperand(1), false);
2986 if (BSwap.getNode())
2993 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2995 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2996 bool DemandHighBits) {
2997 if (!LegalOperations)
3000 EVT VT = N->getValueType(0);
3001 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3003 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3006 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3007 bool LookPassAnd0 = false;
3008 bool LookPassAnd1 = false;
3009 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3011 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3013 if (N0.getOpcode() == ISD::AND) {
3014 if (!N0.getNode()->hasOneUse())
3016 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3017 if (!N01C || N01C->getZExtValue() != 0xFF00)
3019 N0 = N0.getOperand(0);
3020 LookPassAnd0 = true;
3023 if (N1.getOpcode() == ISD::AND) {
3024 if (!N1.getNode()->hasOneUse())
3026 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3027 if (!N11C || N11C->getZExtValue() != 0xFF)
3029 N1 = N1.getOperand(0);
3030 LookPassAnd1 = true;
3033 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3035 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3037 if (!N0.getNode()->hasOneUse() ||
3038 !N1.getNode()->hasOneUse())
3041 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3042 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3045 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3048 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3049 SDValue N00 = N0->getOperand(0);
3050 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3051 if (!N00.getNode()->hasOneUse())
3053 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3054 if (!N001C || N001C->getZExtValue() != 0xFF)
3056 N00 = N00.getOperand(0);
3057 LookPassAnd0 = true;
3060 SDValue N10 = N1->getOperand(0);
3061 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3062 if (!N10.getNode()->hasOneUse())
3064 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3065 if (!N101C || N101C->getZExtValue() != 0xFF00)
3067 N10 = N10.getOperand(0);
3068 LookPassAnd1 = true;
3074 // Make sure everything beyond the low halfword gets set to zero since the SRL
3075 // 16 will clear the top bits.
3076 unsigned OpSizeInBits = VT.getSizeInBits();
3077 if (DemandHighBits && OpSizeInBits > 16) {
3078 // If the left-shift isn't masked out then the only way this is a bswap is
3079 // if all bits beyond the low 8 are 0. In that case the entire pattern
3080 // reduces to a left shift anyway: leave it for other parts of the combiner.
3084 // However, if the right shift isn't masked out then it might be because
3085 // it's not needed. See if we can spot that too.
3086 if (!LookPassAnd1 &&
3087 !DAG.MaskedValueIsZero(
3088 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3092 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3093 if (OpSizeInBits > 16)
3094 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3095 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3099 /// isBSwapHWordElement - Return true if the specified node is an element
3100 /// that makes up a 32-bit packed halfword byteswap. i.e.
3101 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3102 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3103 if (!N.getNode()->hasOneUse())
3106 unsigned Opc = N.getOpcode();
3107 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3115 switch (N1C->getZExtValue()) {
3118 case 0xFF: Num = 0; break;
3119 case 0xFF00: Num = 1; break;
3120 case 0xFF0000: Num = 2; break;
3121 case 0xFF000000: Num = 3; break;
3124 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3125 SDValue N0 = N.getOperand(0);
3126 if (Opc == ISD::AND) {
3127 if (Num == 0 || Num == 2) {
3129 // (x >> 8) & 0xff0000
3130 if (N0.getOpcode() != ISD::SRL)
3132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3133 if (!C || C->getZExtValue() != 8)
3136 // (x << 8) & 0xff00
3137 // (x << 8) & 0xff000000
3138 if (N0.getOpcode() != ISD::SHL)
3140 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3141 if (!C || C->getZExtValue() != 8)
3144 } else if (Opc == ISD::SHL) {
3146 // (x & 0xff0000) << 8
3147 if (Num != 0 && Num != 2)
3149 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3150 if (!C || C->getZExtValue() != 8)
3152 } else { // Opc == ISD::SRL
3153 // (x & 0xff00) >> 8
3154 // (x & 0xff000000) >> 8
3155 if (Num != 1 && Num != 3)
3157 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3158 if (!C || C->getZExtValue() != 8)
3165 Parts[Num] = N0.getOperand(0).getNode();
3169 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3170 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3171 /// => (rotl (bswap x), 16)
3172 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3173 if (!LegalOperations)
3176 EVT VT = N->getValueType(0);
3179 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3182 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3184 // (or (or (and), (and)), (or (and), (and)))
3185 // (or (or (or (and), (and)), (and)), (and))
3186 if (N0.getOpcode() != ISD::OR)
3188 SDValue N00 = N0.getOperand(0);
3189 SDValue N01 = N0.getOperand(1);
3191 if (N1.getOpcode() == ISD::OR &&
3192 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3193 // (or (or (and), (and)), (or (and), (and)))
3194 SDValue N000 = N00.getOperand(0);
3195 if (!isBSwapHWordElement(N000, Parts))
3198 SDValue N001 = N00.getOperand(1);
3199 if (!isBSwapHWordElement(N001, Parts))
3201 SDValue N010 = N01.getOperand(0);
3202 if (!isBSwapHWordElement(N010, Parts))
3204 SDValue N011 = N01.getOperand(1);
3205 if (!isBSwapHWordElement(N011, Parts))
3208 // (or (or (or (and), (and)), (and)), (and))
3209 if (!isBSwapHWordElement(N1, Parts))
3211 if (!isBSwapHWordElement(N01, Parts))
3213 if (N00.getOpcode() != ISD::OR)
3215 SDValue N000 = N00.getOperand(0);
3216 if (!isBSwapHWordElement(N000, Parts))
3218 SDValue N001 = N00.getOperand(1);
3219 if (!isBSwapHWordElement(N001, Parts))
3223 // Make sure the parts are all coming from the same node.
3224 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3227 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3228 SDValue(Parts[0],0));
3230 // Result of the bswap should be rotated by 16. If it's not legal, then
3231 // do (x << 16) | (x >> 16).
3232 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3233 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3234 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3235 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3236 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3237 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3238 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3239 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3242 SDValue DAGCombiner::visitOR(SDNode *N) {
3243 SDValue N0 = N->getOperand(0);
3244 SDValue N1 = N->getOperand(1);
3245 SDValue LL, LR, RL, RR, CC0, CC1;
3246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3248 EVT VT = N1.getValueType();
3251 if (VT.isVector()) {
3252 SDValue FoldedVOp = SimplifyVBinOp(N);
3253 if (FoldedVOp.getNode()) return FoldedVOp;
3255 // fold (or x, 0) -> x, vector edition
3256 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3258 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3261 // fold (or x, -1) -> -1, vector edition
3262 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3264 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3267 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3268 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3269 // Do this only if the resulting shuffle is legal.
3270 if (isa<ShuffleVectorSDNode>(N0) &&
3271 isa<ShuffleVectorSDNode>(N1) &&
3272 // Avoid folding a node with illegal type.
3273 TLI.isTypeLegal(VT) &&
3274 N0->getOperand(1) == N1->getOperand(1) &&
3275 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3276 bool CanFold = true;
3277 unsigned NumElts = VT.getVectorNumElements();
3278 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3279 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3280 // We construct two shuffle masks:
3281 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3282 // and N1 as the second operand.
3283 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3284 // and N0 as the second operand.
3285 // We do this because OR is commutable and therefore there might be
3286 // two ways to fold this node into a shuffle.
3287 SmallVector<int,4> Mask1;
3288 SmallVector<int,4> Mask2;
3290 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3291 int M0 = SV0->getMaskElt(i);
3292 int M1 = SV1->getMaskElt(i);
3294 // Both shuffle indexes are undef. Propagate Undef.
3295 if (M0 < 0 && M1 < 0) {
3296 Mask1.push_back(M0);
3297 Mask2.push_back(M0);
3301 if (M0 < 0 || M1 < 0 ||
3302 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3303 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3308 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3309 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3313 // Fold this sequence only if the resulting shuffle is 'legal'.
3314 if (TLI.isShuffleMaskLegal(Mask1, VT))
3315 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3316 N1->getOperand(0), &Mask1[0]);
3317 if (TLI.isShuffleMaskLegal(Mask2, VT))
3318 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3319 N0->getOperand(0), &Mask2[0]);
3324 // fold (or x, undef) -> -1
3325 if (!LegalOperations &&
3326 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3327 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3328 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3330 // fold (or c1, c2) -> c1|c2
3332 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3333 // canonicalize constant to RHS
3335 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3336 // fold (or x, 0) -> x
3337 if (N1C && N1C->isNullValue())
3339 // fold (or x, -1) -> -1
3340 if (N1C && N1C->isAllOnesValue())
3342 // fold (or x, c) -> c iff (x & ~c) == 0
3343 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3346 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3347 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3348 if (BSwap.getNode())
3350 BSwap = MatchBSwapHWordLow(N, N0, N1);
3351 if (BSwap.getNode())
3355 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3358 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3359 // iff (c1 & c2) == 0.
3360 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3361 isa<ConstantSDNode>(N0.getOperand(1))) {
3362 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3363 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3364 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3367 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3368 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3369 N0.getOperand(0), N1), COR);
3372 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3373 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3374 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3375 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3377 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3378 LL.getValueType().isInteger()) {
3379 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3380 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3381 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3382 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3383 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3384 LR.getValueType(), LL, RL);
3385 AddToWorklist(ORNode.getNode());
3386 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3388 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3389 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3390 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3391 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3392 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3393 LR.getValueType(), LL, RL);
3394 AddToWorklist(ANDNode.getNode());
3395 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3398 // canonicalize equivalent to ll == rl
3399 if (LL == RR && LR == RL) {
3400 Op1 = ISD::getSetCCSwappedOperands(Op1);
3403 if (LL == RL && LR == RR) {
3404 bool isInteger = LL.getValueType().isInteger();
3405 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3406 if (Result != ISD::SETCC_INVALID &&
3407 (!LegalOperations ||
3408 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3409 TLI.isOperationLegal(ISD::SETCC,
3410 getSetCCResultType(N0.getValueType())))))
3411 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3416 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3417 if (N0.getOpcode() == N1.getOpcode()) {
3418 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3419 if (Tmp.getNode()) return Tmp;
3422 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3423 if (N0.getOpcode() == ISD::AND &&
3424 N1.getOpcode() == ISD::AND &&
3425 N0.getOperand(1).getOpcode() == ISD::Constant &&
3426 N1.getOperand(1).getOpcode() == ISD::Constant &&
3427 // Don't increase # computations.
3428 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3429 // We can only do this xform if we know that bits from X that are set in C2
3430 // but not in C1 are already zero. Likewise for Y.
3431 const APInt &LHSMask =
3432 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3433 const APInt &RHSMask =
3434 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3436 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3437 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3438 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3439 N0.getOperand(0), N1.getOperand(0));
3440 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3441 DAG.getConstant(LHSMask | RHSMask, VT));
3445 // See if this is some rotate idiom.
3446 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3447 return SDValue(Rot, 0);
3449 // Simplify the operands using demanded-bits information.
3450 if (!VT.isVector() &&
3451 SimplifyDemandedBits(SDValue(N, 0)))
3452 return SDValue(N, 0);
3457 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3458 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3459 if (Op.getOpcode() == ISD::AND) {
3460 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3461 Mask = Op.getOperand(1);
3462 Op = Op.getOperand(0);
3468 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3476 // Return true if we can prove that, whenever Neg and Pos are both in the
3477 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3478 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3480 // (or (shift1 X, Neg), (shift2 X, Pos))
3482 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3483 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3484 // to consider shift amounts with defined behavior.
3485 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3486 // If OpSize is a power of 2 then:
3488 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3489 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3491 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3492 // for the stronger condition:
3494 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3496 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3497 // we can just replace Neg with Neg' for the rest of the function.
3499 // In other cases we check for the even stronger condition:
3501 // Neg == OpSize - Pos [B]
3503 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3504 // behavior if Pos == 0 (and consequently Neg == OpSize).
3506 // We could actually use [A] whenever OpSize is a power of 2, but the
3507 // only extra cases that it would match are those uninteresting ones
3508 // where Neg and Pos are never in range at the same time. E.g. for
3509 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3510 // as well as (sub 32, Pos), but:
3512 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3514 // always invokes undefined behavior for 32-bit X.
3516 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3517 unsigned MaskLoBits = 0;
3518 if (Neg.getOpcode() == ISD::AND &&
3519 isPowerOf2_64(OpSize) &&
3520 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3521 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3522 Neg = Neg.getOperand(0);
3523 MaskLoBits = Log2_64(OpSize);
3526 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3527 if (Neg.getOpcode() != ISD::SUB)
3529 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3532 SDValue NegOp1 = Neg.getOperand(1);
3534 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3535 // Pos'. The truncation is redundant for the purpose of the equality.
3537 Pos.getOpcode() == ISD::AND &&
3538 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3539 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3540 Pos = Pos.getOperand(0);
3542 // The condition we need is now:
3544 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3546 // If NegOp1 == Pos then we need:
3548 // OpSize & Mask == NegC & Mask
3550 // (because "x & Mask" is a truncation and distributes through subtraction).
3553 Width = NegC->getAPIntValue();
3554 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3555 // Then the condition we want to prove becomes:
3557 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3559 // which, again because "x & Mask" is a truncation, becomes:
3561 // NegC & Mask == (OpSize - PosC) & Mask
3562 // OpSize & Mask == (NegC + PosC) & Mask
3563 else if (Pos.getOpcode() == ISD::ADD &&
3564 Pos.getOperand(0) == NegOp1 &&
3565 Pos.getOperand(1).getOpcode() == ISD::Constant)
3566 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3567 NegC->getAPIntValue());
3571 // Now we just need to check that OpSize & Mask == Width & Mask.
3573 // Opsize & Mask is 0 since Mask is Opsize - 1.
3574 return Width.getLoBits(MaskLoBits) == 0;
3575 return Width == OpSize;
3578 // A subroutine of MatchRotate used once we have found an OR of two opposite
3579 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3580 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3581 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3582 // Neg with outer conversions stripped away.
3583 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3584 SDValue Neg, SDValue InnerPos,
3585 SDValue InnerNeg, unsigned PosOpcode,
3586 unsigned NegOpcode, SDLoc DL) {
3587 // fold (or (shl x, (*ext y)),
3588 // (srl x, (*ext (sub 32, y)))) ->
3589 // (rotl x, y) or (rotr x, (sub 32, y))
3591 // fold (or (shl x, (*ext (sub 32, y))),
3592 // (srl x, (*ext y))) ->
3593 // (rotr x, y) or (rotl x, (sub 32, y))
3594 EVT VT = Shifted.getValueType();
3595 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3596 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3597 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3598 HasPos ? Pos : Neg).getNode();
3604 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3605 // idioms for rotate, and if the target supports rotation instructions, generate
3607 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3608 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3609 EVT VT = LHS.getValueType();
3610 if (!TLI.isTypeLegal(VT)) return nullptr;
3612 // The target must have at least one rotate flavor.
3613 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3614 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3615 if (!HasROTL && !HasROTR) return nullptr;
3617 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3618 SDValue LHSShift; // The shift.
3619 SDValue LHSMask; // AND value if any.
3620 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3621 return nullptr; // Not part of a rotate.
3623 SDValue RHSShift; // The shift.
3624 SDValue RHSMask; // AND value if any.
3625 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3626 return nullptr; // Not part of a rotate.
3628 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3629 return nullptr; // Not shifting the same value.
3631 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3632 return nullptr; // Shifts must disagree.
3634 // Canonicalize shl to left side in a shl/srl pair.
3635 if (RHSShift.getOpcode() == ISD::SHL) {
3636 std::swap(LHS, RHS);
3637 std::swap(LHSShift, RHSShift);
3638 std::swap(LHSMask , RHSMask );
3641 unsigned OpSizeInBits = VT.getSizeInBits();
3642 SDValue LHSShiftArg = LHSShift.getOperand(0);
3643 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3644 SDValue RHSShiftArg = RHSShift.getOperand(0);
3645 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3647 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3648 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3649 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3650 RHSShiftAmt.getOpcode() == ISD::Constant) {
3651 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3652 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3653 if ((LShVal + RShVal) != OpSizeInBits)
3656 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3657 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3659 // If there is an AND of either shifted operand, apply it to the result.
3660 if (LHSMask.getNode() || RHSMask.getNode()) {
3661 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3663 if (LHSMask.getNode()) {
3664 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3665 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3667 if (RHSMask.getNode()) {
3668 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3669 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3672 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3675 return Rot.getNode();
3678 // If there is a mask here, and we have a variable shift, we can't be sure
3679 // that we're masking out the right stuff.
3680 if (LHSMask.getNode() || RHSMask.getNode())
3683 // If the shift amount is sign/zext/any-extended just peel it off.
3684 SDValue LExtOp0 = LHSShiftAmt;
3685 SDValue RExtOp0 = RHSShiftAmt;
3686 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3687 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3688 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3689 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3690 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3691 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3692 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3693 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3694 LExtOp0 = LHSShiftAmt.getOperand(0);
3695 RExtOp0 = RHSShiftAmt.getOperand(0);
3698 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3699 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3703 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3704 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3711 SDValue DAGCombiner::visitXOR(SDNode *N) {
3712 SDValue N0 = N->getOperand(0);
3713 SDValue N1 = N->getOperand(1);
3714 SDValue LHS, RHS, CC;
3715 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3716 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3717 EVT VT = N0.getValueType();
3720 if (VT.isVector()) {
3721 SDValue FoldedVOp = SimplifyVBinOp(N);
3722 if (FoldedVOp.getNode()) return FoldedVOp;
3724 // fold (xor x, 0) -> x, vector edition
3725 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3727 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3731 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3732 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3733 return DAG.getConstant(0, VT);
3734 // fold (xor x, undef) -> undef
3735 if (N0.getOpcode() == ISD::UNDEF)
3737 if (N1.getOpcode() == ISD::UNDEF)
3739 // fold (xor c1, c2) -> c1^c2
3741 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3742 // canonicalize constant to RHS
3744 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3745 // fold (xor x, 0) -> x
3746 if (N1C && N1C->isNullValue())
3749 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3753 // fold !(x cc y) -> (x !cc y)
3754 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3755 bool isInt = LHS.getValueType().isInteger();
3756 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3759 if (!LegalOperations ||
3760 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3761 switch (N0.getOpcode()) {
3763 llvm_unreachable("Unhandled SetCC Equivalent!");
3765 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3766 case ISD::SELECT_CC:
3767 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3768 N0.getOperand(3), NotCC);
3773 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3774 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3775 N0.getNode()->hasOneUse() &&
3776 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3777 SDValue V = N0.getOperand(0);
3778 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3779 DAG.getConstant(1, V.getValueType()));
3780 AddToWorklist(V.getNode());
3781 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3784 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3785 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3786 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3787 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3788 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3789 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3790 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3791 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3792 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3793 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3796 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3797 if (N1C && N1C->isAllOnesValue() &&
3798 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3799 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3800 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3801 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3802 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3803 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3804 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3805 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3808 // fold (xor (and x, y), y) -> (and (not x), y)
3809 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3810 N0->getOperand(1) == N1) {
3811 SDValue X = N0->getOperand(0);
3812 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3813 AddToWorklist(NotX.getNode());
3814 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3816 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3817 if (N1C && N0.getOpcode() == ISD::XOR) {
3818 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3819 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3821 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3822 DAG.getConstant(N1C->getAPIntValue() ^
3823 N00C->getAPIntValue(), VT));
3825 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3826 DAG.getConstant(N1C->getAPIntValue() ^
3827 N01C->getAPIntValue(), VT));
3829 // fold (xor x, x) -> 0
3831 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3833 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3834 if (N0.getOpcode() == N1.getOpcode()) {
3835 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3836 if (Tmp.getNode()) return Tmp;
3839 // Simplify the expression using non-local knowledge.
3840 if (!VT.isVector() &&
3841 SimplifyDemandedBits(SDValue(N, 0)))
3842 return SDValue(N, 0);
3847 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3848 /// the shift amount is a constant.
3849 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3850 // We can't and shouldn't fold opaque constants.
3851 if (Amt->isOpaque())
3854 SDNode *LHS = N->getOperand(0).getNode();
3855 if (!LHS->hasOneUse()) return SDValue();
3857 // We want to pull some binops through shifts, so that we have (and (shift))
3858 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3859 // thing happens with address calculations, so it's important to canonicalize
3861 bool HighBitSet = false; // Can we transform this if the high bit is set?
3863 switch (LHS->getOpcode()) {
3864 default: return SDValue();
3867 HighBitSet = false; // We can only transform sra if the high bit is clear.
3870 HighBitSet = true; // We can only transform sra if the high bit is set.
3873 if (N->getOpcode() != ISD::SHL)
3874 return SDValue(); // only shl(add) not sr[al](add).
3875 HighBitSet = false; // We can only transform sra if the high bit is clear.
3879 // We require the RHS of the binop to be a constant and not opaque as well.
3880 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3881 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3883 // FIXME: disable this unless the input to the binop is a shift by a constant.
3884 // If it is not a shift, it pessimizes some common cases like:
3886 // void foo(int *X, int i) { X[i & 1235] = 1; }
3887 // int bar(int *X, int i) { return X[i & 255]; }
3888 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3889 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3890 BinOpLHSVal->getOpcode() != ISD::SRA &&
3891 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3892 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3895 EVT VT = N->getValueType(0);
3897 // If this is a signed shift right, and the high bit is modified by the
3898 // logical operation, do not perform the transformation. The highBitSet
3899 // boolean indicates the value of the high bit of the constant which would
3900 // cause it to be modified for this operation.
3901 if (N->getOpcode() == ISD::SRA) {
3902 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3903 if (BinOpRHSSignSet != HighBitSet)
3907 if (!TLI.isDesirableToCommuteWithShift(LHS))
3910 // Fold the constants, shifting the binop RHS by the shift amount.
3911 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3913 LHS->getOperand(1), N->getOperand(1));
3914 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3916 // Create the new shift.
3917 SDValue NewShift = DAG.getNode(N->getOpcode(),
3918 SDLoc(LHS->getOperand(0)),
3919 VT, LHS->getOperand(0), N->getOperand(1));
3921 // Create the new binop.
3922 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3925 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3926 assert(N->getOpcode() == ISD::TRUNCATE);
3927 assert(N->getOperand(0).getOpcode() == ISD::AND);
3929 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3930 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3931 SDValue N01 = N->getOperand(0).getOperand(1);
3933 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3934 EVT TruncVT = N->getValueType(0);
3935 SDValue N00 = N->getOperand(0).getOperand(0);
3936 APInt TruncC = N01C->getAPIntValue();
3937 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3939 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3940 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3941 DAG.getConstant(TruncC, TruncVT));
3948 SDValue DAGCombiner::visitRotate(SDNode *N) {
3949 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3950 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3951 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3952 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3953 if (NewOp1.getNode())
3954 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3955 N->getOperand(0), NewOp1);
3960 SDValue DAGCombiner::visitSHL(SDNode *N) {
3961 SDValue N0 = N->getOperand(0);
3962 SDValue N1 = N->getOperand(1);
3963 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3964 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3965 EVT VT = N0.getValueType();
3966 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3969 if (VT.isVector()) {
3970 SDValue FoldedVOp = SimplifyVBinOp(N);
3971 if (FoldedVOp.getNode()) return FoldedVOp;
3973 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3974 // If setcc produces all-one true value then:
3975 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3976 if (N1CV && N1CV->isConstant()) {
3977 if (N0.getOpcode() == ISD::AND) {
3978 SDValue N00 = N0->getOperand(0);
3979 SDValue N01 = N0->getOperand(1);
3980 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3982 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3983 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3984 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3985 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3987 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3990 N1C = isConstOrConstSplat(N1);
3995 // fold (shl c1, c2) -> c1<<c2
3997 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3998 // fold (shl 0, x) -> 0
3999 if (N0C && N0C->isNullValue())
4001 // fold (shl x, c >= size(x)) -> undef
4002 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4003 return DAG.getUNDEF(VT);
4004 // fold (shl x, 0) -> x
4005 if (N1C && N1C->isNullValue())
4007 // fold (shl undef, x) -> 0
4008 if (N0.getOpcode() == ISD::UNDEF)
4009 return DAG.getConstant(0, VT);
4010 // if (shl x, c) is known to be zero, return 0
4011 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4012 APInt::getAllOnesValue(OpSizeInBits)))
4013 return DAG.getConstant(0, VT);
4014 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4015 if (N1.getOpcode() == ISD::TRUNCATE &&
4016 N1.getOperand(0).getOpcode() == ISD::AND) {
4017 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4018 if (NewOp1.getNode())
4019 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4022 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4023 return SDValue(N, 0);
4025 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4026 if (N1C && N0.getOpcode() == ISD::SHL) {
4027 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4028 uint64_t c1 = N0C1->getZExtValue();
4029 uint64_t c2 = N1C->getZExtValue();
4030 if (c1 + c2 >= OpSizeInBits)
4031 return DAG.getConstant(0, VT);
4032 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4033 DAG.getConstant(c1 + c2, N1.getValueType()));
4037 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4038 // For this to be valid, the second form must not preserve any of the bits
4039 // that are shifted out by the inner shift in the first form. This means
4040 // the outer shift size must be >= the number of bits added by the ext.
4041 // As a corollary, we don't care what kind of ext it is.
4042 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4043 N0.getOpcode() == ISD::ANY_EXTEND ||
4044 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4045 N0.getOperand(0).getOpcode() == ISD::SHL) {
4046 SDValue N0Op0 = N0.getOperand(0);
4047 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4048 uint64_t c1 = N0Op0C1->getZExtValue();
4049 uint64_t c2 = N1C->getZExtValue();
4050 EVT InnerShiftVT = N0Op0.getValueType();
4051 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4052 if (c2 >= OpSizeInBits - InnerShiftSize) {
4053 if (c1 + c2 >= OpSizeInBits)
4054 return DAG.getConstant(0, VT);
4055 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4056 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4057 N0Op0->getOperand(0)),
4058 DAG.getConstant(c1 + c2, N1.getValueType()));
4063 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4064 // Only fold this if the inner zext has no other uses to avoid increasing
4065 // the total number of instructions.
4066 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4067 N0.getOperand(0).getOpcode() == ISD::SRL) {
4068 SDValue N0Op0 = N0.getOperand(0);
4069 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4070 uint64_t c1 = N0Op0C1->getZExtValue();
4071 if (c1 < VT.getScalarSizeInBits()) {
4072 uint64_t c2 = N1C->getZExtValue();
4074 SDValue NewOp0 = N0.getOperand(0);
4075 EVT CountVT = NewOp0.getOperand(1).getValueType();
4076 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4077 NewOp0, DAG.getConstant(c2, CountVT));
4078 AddToWorklist(NewSHL.getNode());
4079 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4085 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4086 // (and (srl x, (sub c1, c2), MASK)
4087 // Only fold this if the inner shift has no other uses -- if it does, folding
4088 // this will increase the total number of instructions.
4089 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4090 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4091 uint64_t c1 = N0C1->getZExtValue();
4092 if (c1 < OpSizeInBits) {
4093 uint64_t c2 = N1C->getZExtValue();
4094 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4097 Mask = Mask.shl(c2 - c1);
4098 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4099 DAG.getConstant(c2 - c1, N1.getValueType()));
4101 Mask = Mask.lshr(c1 - c2);
4102 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4103 DAG.getConstant(c1 - c2, N1.getValueType()));
4105 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4106 DAG.getConstant(Mask, VT));
4110 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4111 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4112 unsigned BitSize = VT.getScalarSizeInBits();
4113 SDValue HiBitsMask =
4114 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4115 BitSize - N1C->getZExtValue()), VT);
4116 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4121 SDValue NewSHL = visitShiftByConstant(N, N1C);
4122 if (NewSHL.getNode())
4129 SDValue DAGCombiner::visitSRA(SDNode *N) {
4130 SDValue N0 = N->getOperand(0);
4131 SDValue N1 = N->getOperand(1);
4132 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4134 EVT VT = N0.getValueType();
4135 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4138 if (VT.isVector()) {
4139 SDValue FoldedVOp = SimplifyVBinOp(N);
4140 if (FoldedVOp.getNode()) return FoldedVOp;
4142 N1C = isConstOrConstSplat(N1);
4145 // fold (sra c1, c2) -> (sra c1, c2)
4147 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4148 // fold (sra 0, x) -> 0
4149 if (N0C && N0C->isNullValue())
4151 // fold (sra -1, x) -> -1
4152 if (N0C && N0C->isAllOnesValue())
4154 // fold (sra x, (setge c, size(x))) -> undef
4155 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4156 return DAG.getUNDEF(VT);
4157 // fold (sra x, 0) -> x
4158 if (N1C && N1C->isNullValue())
4160 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4162 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4163 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4164 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4166 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4167 ExtVT, VT.getVectorNumElements());
4168 if ((!LegalOperations ||
4169 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4170 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4171 N0.getOperand(0), DAG.getValueType(ExtVT));
4174 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4175 if (N1C && N0.getOpcode() == ISD::SRA) {
4176 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4177 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4178 if (Sum >= OpSizeInBits)
4179 Sum = OpSizeInBits - 1;
4180 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4181 DAG.getConstant(Sum, N1.getValueType()));
4185 // fold (sra (shl X, m), (sub result_size, n))
4186 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4187 // result_size - n != m.
4188 // If truncate is free for the target sext(shl) is likely to result in better
4190 if (N0.getOpcode() == ISD::SHL && N1C) {
4191 // Get the two constanst of the shifts, CN0 = m, CN = n.
4192 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4194 LLVMContext &Ctx = *DAG.getContext();
4195 // Determine what the truncate's result bitsize and type would be.
4196 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4199 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4201 // Determine the residual right-shift amount.
4202 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4204 // If the shift is not a no-op (in which case this should be just a sign
4205 // extend already), the truncated to type is legal, sign_extend is legal
4206 // on that type, and the truncate to that type is both legal and free,
4207 // perform the transform.
4208 if ((ShiftAmt > 0) &&
4209 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4210 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4211 TLI.isTruncateFree(VT, TruncVT)) {
4213 SDValue Amt = DAG.getConstant(ShiftAmt,
4214 getShiftAmountTy(N0.getOperand(0).getValueType()));
4215 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4216 N0.getOperand(0), Amt);
4217 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4219 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4220 N->getValueType(0), Trunc);
4225 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4226 if (N1.getOpcode() == ISD::TRUNCATE &&
4227 N1.getOperand(0).getOpcode() == ISD::AND) {
4228 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4229 if (NewOp1.getNode())
4230 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4233 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4234 // if c1 is equal to the number of bits the trunc removes
4235 if (N0.getOpcode() == ISD::TRUNCATE &&
4236 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4237 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4238 N0.getOperand(0).hasOneUse() &&
4239 N0.getOperand(0).getOperand(1).hasOneUse() &&
4241 SDValue N0Op0 = N0.getOperand(0);
4242 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4243 unsigned LargeShiftVal = LargeShift->getZExtValue();
4244 EVT LargeVT = N0Op0.getValueType();
4246 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4248 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4249 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4250 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4251 N0Op0.getOperand(0), Amt);
4252 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4257 // Simplify, based on bits shifted out of the LHS.
4258 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4259 return SDValue(N, 0);
4262 // If the sign bit is known to be zero, switch this to a SRL.
4263 if (DAG.SignBitIsZero(N0))
4264 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4267 SDValue NewSRA = visitShiftByConstant(N, N1C);
4268 if (NewSRA.getNode())
4275 SDValue DAGCombiner::visitSRL(SDNode *N) {
4276 SDValue N0 = N->getOperand(0);
4277 SDValue N1 = N->getOperand(1);
4278 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4280 EVT VT = N0.getValueType();
4281 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4284 if (VT.isVector()) {
4285 SDValue FoldedVOp = SimplifyVBinOp(N);
4286 if (FoldedVOp.getNode()) return FoldedVOp;
4288 N1C = isConstOrConstSplat(N1);
4291 // fold (srl c1, c2) -> c1 >>u c2
4293 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4294 // fold (srl 0, x) -> 0
4295 if (N0C && N0C->isNullValue())
4297 // fold (srl x, c >= size(x)) -> undef
4298 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4299 return DAG.getUNDEF(VT);
4300 // fold (srl x, 0) -> x
4301 if (N1C && N1C->isNullValue())
4303 // if (srl x, c) is known to be zero, return 0
4304 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4305 APInt::getAllOnesValue(OpSizeInBits)))
4306 return DAG.getConstant(0, VT);
4308 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4309 if (N1C && N0.getOpcode() == ISD::SRL) {
4310 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4311 uint64_t c1 = N01C->getZExtValue();
4312 uint64_t c2 = N1C->getZExtValue();
4313 if (c1 + c2 >= OpSizeInBits)
4314 return DAG.getConstant(0, VT);
4315 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4316 DAG.getConstant(c1 + c2, N1.getValueType()));
4320 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4321 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4322 N0.getOperand(0).getOpcode() == ISD::SRL &&
4323 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4325 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4326 uint64_t c2 = N1C->getZExtValue();
4327 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4328 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4329 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4330 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4331 if (c1 + OpSizeInBits == InnerShiftSize) {
4332 if (c1 + c2 >= InnerShiftSize)
4333 return DAG.getConstant(0, VT);
4334 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4335 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4336 N0.getOperand(0)->getOperand(0),
4337 DAG.getConstant(c1 + c2, ShiftCountVT)));
4341 // fold (srl (shl x, c), c) -> (and x, cst2)
4342 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4343 unsigned BitSize = N0.getScalarValueSizeInBits();
4344 if (BitSize <= 64) {
4345 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4346 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4347 DAG.getConstant(~0ULL >> ShAmt, VT));
4351 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4352 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4353 // Shifting in all undef bits?
4354 EVT SmallVT = N0.getOperand(0).getValueType();
4355 unsigned BitSize = SmallVT.getScalarSizeInBits();
4356 if (N1C->getZExtValue() >= BitSize)
4357 return DAG.getUNDEF(VT);
4359 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4360 uint64_t ShiftAmt = N1C->getZExtValue();
4361 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4363 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4364 AddToWorklist(SmallShift.getNode());
4365 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4366 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4367 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4368 DAG.getConstant(Mask, VT));
4372 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4373 // bit, which is unmodified by sra.
4374 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4375 if (N0.getOpcode() == ISD::SRA)
4376 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4379 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4380 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4381 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4382 APInt KnownZero, KnownOne;
4383 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4385 // If any of the input bits are KnownOne, then the input couldn't be all
4386 // zeros, thus the result of the srl will always be zero.
4387 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4389 // If all of the bits input the to ctlz node are known to be zero, then
4390 // the result of the ctlz is "32" and the result of the shift is one.
4391 APInt UnknownBits = ~KnownZero;
4392 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4394 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4395 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4396 // Okay, we know that only that the single bit specified by UnknownBits
4397 // could be set on input to the CTLZ node. If this bit is set, the SRL
4398 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4399 // to an SRL/XOR pair, which is likely to simplify more.
4400 unsigned ShAmt = UnknownBits.countTrailingZeros();
4401 SDValue Op = N0.getOperand(0);
4404 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4405 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4406 AddToWorklist(Op.getNode());
4409 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4410 Op, DAG.getConstant(1, VT));
4414 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4415 if (N1.getOpcode() == ISD::TRUNCATE &&
4416 N1.getOperand(0).getOpcode() == ISD::AND) {
4417 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4418 if (NewOp1.getNode())
4419 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4422 // fold operands of srl based on knowledge that the low bits are not
4424 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4425 return SDValue(N, 0);
4428 SDValue NewSRL = visitShiftByConstant(N, N1C);
4429 if (NewSRL.getNode())
4433 // Attempt to convert a srl of a load into a narrower zero-extending load.
4434 SDValue NarrowLoad = ReduceLoadWidth(N);
4435 if (NarrowLoad.getNode())
4438 // Here is a common situation. We want to optimize:
4441 // %b = and i32 %a, 2
4442 // %c = srl i32 %b, 1
4443 // brcond i32 %c ...
4449 // %c = setcc eq %b, 0
4452 // However when after the source operand of SRL is optimized into AND, the SRL
4453 // itself may not be optimized further. Look for it and add the BRCOND into
4455 if (N->hasOneUse()) {
4456 SDNode *Use = *N->use_begin();
4457 if (Use->getOpcode() == ISD::BRCOND)
4459 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4460 // Also look pass the truncate.
4461 Use = *Use->use_begin();
4462 if (Use->getOpcode() == ISD::BRCOND)
4470 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4471 SDValue N0 = N->getOperand(0);
4472 EVT VT = N->getValueType(0);
4474 // fold (ctlz c1) -> c2
4475 if (isa<ConstantSDNode>(N0))
4476 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4480 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4481 SDValue N0 = N->getOperand(0);
4482 EVT VT = N->getValueType(0);
4484 // fold (ctlz_zero_undef c1) -> c2
4485 if (isa<ConstantSDNode>(N0))
4486 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4490 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4491 SDValue N0 = N->getOperand(0);
4492 EVT VT = N->getValueType(0);
4494 // fold (cttz c1) -> c2
4495 if (isa<ConstantSDNode>(N0))
4496 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4500 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4501 SDValue N0 = N->getOperand(0);
4502 EVT VT = N->getValueType(0);
4504 // fold (cttz_zero_undef c1) -> c2
4505 if (isa<ConstantSDNode>(N0))
4506 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4510 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4511 SDValue N0 = N->getOperand(0);
4512 EVT VT = N->getValueType(0);
4514 // fold (ctpop c1) -> c2
4515 if (isa<ConstantSDNode>(N0))
4516 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4520 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4521 SDValue N0 = N->getOperand(0);
4522 SDValue N1 = N->getOperand(1);
4523 SDValue N2 = N->getOperand(2);
4524 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4526 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4527 EVT VT = N->getValueType(0);
4528 EVT VT0 = N0.getValueType();
4530 // fold (select C, X, X) -> X
4533 // fold (select true, X, Y) -> X
4534 if (N0C && !N0C->isNullValue())
4536 // fold (select false, X, Y) -> Y
4537 if (N0C && N0C->isNullValue())
4539 // fold (select C, 1, X) -> (or C, X)
4540 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4541 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4542 // fold (select C, 0, 1) -> (xor C, 1)
4543 // We can't do this reliably if integer based booleans have different contents
4544 // to floating point based booleans. This is because we can't tell whether we
4545 // have an integer-based boolean or a floating-point-based boolean unless we
4546 // can find the SETCC that produced it and inspect its operands. This is
4547 // fairly easy if C is the SETCC node, but it can potentially be
4548 // undiscoverable (or not reasonably discoverable). For example, it could be
4549 // in another basic block or it could require searching a complicated
4551 if (VT.isInteger() &&
4552 (VT0 == MVT::i1 || (VT0.isInteger() &&
4553 TLI.getBooleanContents(false, false) ==
4554 TLI.getBooleanContents(false, true) &&
4555 TLI.getBooleanContents(false, false) ==
4556 TargetLowering::ZeroOrOneBooleanContent)) &&
4557 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4560 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4561 N0, DAG.getConstant(1, VT0));
4562 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4563 N0, DAG.getConstant(1, VT0));
4564 AddToWorklist(XORNode.getNode());
4566 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4567 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4569 // fold (select C, 0, X) -> (and (not C), X)
4570 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4571 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4572 AddToWorklist(NOTNode.getNode());
4573 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4575 // fold (select C, X, 1) -> (or (not C), X)
4576 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4577 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4578 AddToWorklist(NOTNode.getNode());
4579 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4581 // fold (select C, X, 0) -> (and C, X)
4582 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4583 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4584 // fold (select X, X, Y) -> (or X, Y)
4585 // fold (select X, 1, Y) -> (or X, Y)
4586 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4587 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4588 // fold (select X, Y, X) -> (and X, Y)
4589 // fold (select X, Y, 0) -> (and X, Y)
4590 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4591 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4593 // If we can fold this based on the true/false value, do so.
4594 if (SimplifySelectOps(N, N1, N2))
4595 return SDValue(N, 0); // Don't revisit N.
4597 // fold selects based on a setcc into other things, such as min/max/abs
4598 if (N0.getOpcode() == ISD::SETCC) {
4599 if ((!LegalOperations &&
4600 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4601 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4602 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4603 N0.getOperand(0), N0.getOperand(1),
4604 N1, N2, N0.getOperand(2));
4605 return SimplifySelect(SDLoc(N), N0, N1, N2);
4612 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4615 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4617 // Split the inputs.
4618 SDValue Lo, Hi, LL, LH, RL, RH;
4619 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4620 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4622 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4623 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4625 return std::make_pair(Lo, Hi);
4628 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4629 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4630 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4632 SDValue Cond = N->getOperand(0);
4633 SDValue LHS = N->getOperand(1);
4634 SDValue RHS = N->getOperand(2);
4635 MVT VT = N->getSimpleValueType(0);
4636 int NumElems = VT.getVectorNumElements();
4637 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4638 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4639 Cond.getOpcode() == ISD::BUILD_VECTOR);
4641 // We're sure we have an even number of elements due to the
4642 // concat_vectors we have as arguments to vselect.
4643 // Skip BV elements until we find one that's not an UNDEF
4644 // After we find an UNDEF element, keep looping until we get to half the
4645 // length of the BV and see if all the non-undef nodes are the same.
4646 ConstantSDNode *BottomHalf = nullptr;
4647 for (int i = 0; i < NumElems / 2; ++i) {
4648 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4651 if (BottomHalf == nullptr)
4652 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4653 else if (Cond->getOperand(i).getNode() != BottomHalf)
4657 // Do the same for the second half of the BuildVector
4658 ConstantSDNode *TopHalf = nullptr;
4659 for (int i = NumElems / 2; i < NumElems; ++i) {
4660 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4663 if (TopHalf == nullptr)
4664 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4665 else if (Cond->getOperand(i).getNode() != TopHalf)
4669 assert(TopHalf && BottomHalf &&
4670 "One half of the selector was all UNDEFs and the other was all the "
4671 "same value. This should have been addressed before this function.");
4673 ISD::CONCAT_VECTORS, dl, VT,
4674 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4675 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4678 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4679 SDValue N0 = N->getOperand(0);
4680 SDValue N1 = N->getOperand(1);
4681 SDValue N2 = N->getOperand(2);
4684 // Canonicalize integer abs.
4685 // vselect (setg[te] X, 0), X, -X ->
4686 // vselect (setgt X, -1), X, -X ->
4687 // vselect (setl[te] X, 0), -X, X ->
4688 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4689 if (N0.getOpcode() == ISD::SETCC) {
4690 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4691 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4693 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4695 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4696 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4697 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4698 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4699 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4700 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4701 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4704 EVT VT = LHS.getValueType();
4705 SDValue Shift = DAG.getNode(
4706 ISD::SRA, DL, VT, LHS,
4707 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4708 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4709 AddToWorklist(Shift.getNode());
4710 AddToWorklist(Add.getNode());
4711 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4715 // If the VSELECT result requires splitting and the mask is provided by a
4716 // SETCC, then split both nodes and its operands before legalization. This
4717 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4718 // and enables future optimizations (e.g. min/max pattern matching on X86).
4719 if (N0.getOpcode() == ISD::SETCC) {
4720 EVT VT = N->getValueType(0);
4722 // Check if any splitting is required.
4723 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4724 TargetLowering::TypeSplitVector)
4727 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4728 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4729 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4730 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4732 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4733 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4735 // Add the new VSELECT nodes to the work list in case they need to be split
4737 AddToWorklist(Lo.getNode());
4738 AddToWorklist(Hi.getNode());
4740 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4743 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4744 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4746 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4747 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4750 // The ConvertSelectToConcatVector function is assuming both the above
4751 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4753 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4754 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4755 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4756 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4764 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4765 SDValue N0 = N->getOperand(0);
4766 SDValue N1 = N->getOperand(1);
4767 SDValue N2 = N->getOperand(2);
4768 SDValue N3 = N->getOperand(3);
4769 SDValue N4 = N->getOperand(4);
4770 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4772 // fold select_cc lhs, rhs, x, x, cc -> x
4776 // Determine if the condition we're dealing with is constant
4777 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4778 N0, N1, CC, SDLoc(N), false);
4779 if (SCC.getNode()) {
4780 AddToWorklist(SCC.getNode());
4782 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4783 if (!SCCC->isNullValue())
4784 return N2; // cond always true -> true val
4786 return N3; // cond always false -> false val
4789 // Fold to a simpler select_cc
4790 if (SCC.getOpcode() == ISD::SETCC)
4791 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4792 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4796 // If we can fold this based on the true/false value, do so.
4797 if (SimplifySelectOps(N, N2, N3))
4798 return SDValue(N, 0); // Don't revisit N.
4800 // fold select_cc into other things, such as min/max/abs
4801 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4804 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4805 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4806 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4810 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4811 // dag node into a ConstantSDNode or a build_vector of constants.
4812 // This function is called by the DAGCombiner when visiting sext/zext/aext
4813 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4814 // Vector extends are not folded if operations are legal; this is to
4815 // avoid introducing illegal build_vector dag nodes.
4816 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4817 SelectionDAG &DAG, bool LegalTypes,
4818 bool LegalOperations) {
4819 unsigned Opcode = N->getOpcode();
4820 SDValue N0 = N->getOperand(0);
4821 EVT VT = N->getValueType(0);
4823 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4824 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4826 // fold (sext c1) -> c1
4827 // fold (zext c1) -> c1
4828 // fold (aext c1) -> c1
4829 if (isa<ConstantSDNode>(N0))
4830 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4832 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4833 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4834 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4835 EVT SVT = VT.getScalarType();
4836 if (!(VT.isVector() &&
4837 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4838 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4841 // We can fold this node into a build_vector.
4842 unsigned VTBits = SVT.getSizeInBits();
4843 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4844 unsigned ShAmt = VTBits - EVTBits;
4845 SmallVector<SDValue, 8> Elts;
4846 unsigned NumElts = N0->getNumOperands();
4849 for (unsigned i=0; i != NumElts; ++i) {
4850 SDValue Op = N0->getOperand(i);
4851 if (Op->getOpcode() == ISD::UNDEF) {
4852 Elts.push_back(DAG.getUNDEF(SVT));
4856 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4857 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4858 if (Opcode == ISD::SIGN_EXTEND)
4859 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4862 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4866 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4869 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4870 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4871 // transformation. Returns true if extension are possible and the above
4872 // mentioned transformation is profitable.
4873 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4875 SmallVectorImpl<SDNode *> &ExtendNodes,
4876 const TargetLowering &TLI) {
4877 bool HasCopyToRegUses = false;
4878 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4879 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4880 UE = N0.getNode()->use_end();
4885 if (UI.getUse().getResNo() != N0.getResNo())
4887 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4888 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4889 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4890 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4891 // Sign bits will be lost after a zext.
4894 for (unsigned i = 0; i != 2; ++i) {
4895 SDValue UseOp = User->getOperand(i);
4898 if (!isa<ConstantSDNode>(UseOp))
4903 ExtendNodes.push_back(User);
4906 // If truncates aren't free and there are users we can't
4907 // extend, it isn't worthwhile.
4910 // Remember if this value is live-out.
4911 if (User->getOpcode() == ISD::CopyToReg)
4912 HasCopyToRegUses = true;
4915 if (HasCopyToRegUses) {
4916 bool BothLiveOut = false;
4917 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4919 SDUse &Use = UI.getUse();
4920 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4926 // Both unextended and extended values are live out. There had better be
4927 // a good reason for the transformation.
4928 return ExtendNodes.size();
4933 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4934 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4935 ISD::NodeType ExtType) {
4936 // Extend SetCC uses if necessary.
4937 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4938 SDNode *SetCC = SetCCs[i];
4939 SmallVector<SDValue, 4> Ops;
4941 for (unsigned j = 0; j != 2; ++j) {
4942 SDValue SOp = SetCC->getOperand(j);
4944 Ops.push_back(ExtLoad);
4946 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4949 Ops.push_back(SetCC->getOperand(2));
4950 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4954 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4955 SDValue N0 = N->getOperand(0);
4956 EVT VT = N->getValueType(0);
4958 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4960 return SDValue(Res, 0);
4962 // fold (sext (sext x)) -> (sext x)
4963 // fold (sext (aext x)) -> (sext x)
4964 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4965 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4968 if (N0.getOpcode() == ISD::TRUNCATE) {
4969 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4970 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4971 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4972 if (NarrowLoad.getNode()) {
4973 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4974 if (NarrowLoad.getNode() != N0.getNode()) {
4975 CombineTo(N0.getNode(), NarrowLoad);
4976 // CombineTo deleted the truncate, if needed, but not what's under it.
4979 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4982 // See if the value being truncated is already sign extended. If so, just
4983 // eliminate the trunc/sext pair.
4984 SDValue Op = N0.getOperand(0);
4985 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4986 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4987 unsigned DestBits = VT.getScalarType().getSizeInBits();
4988 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4990 if (OpBits == DestBits) {
4991 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4992 // bits, it is already ready.
4993 if (NumSignBits > DestBits-MidBits)
4995 } else if (OpBits < DestBits) {
4996 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4997 // bits, just sext from i32.
4998 if (NumSignBits > OpBits-MidBits)
4999 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5001 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5002 // bits, just truncate to i32.
5003 if (NumSignBits > OpBits-MidBits)
5004 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5007 // fold (sext (truncate x)) -> (sextinreg x).
5008 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5009 N0.getValueType())) {
5010 if (OpBits < DestBits)
5011 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5012 else if (OpBits > DestBits)
5013 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5014 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5015 DAG.getValueType(N0.getValueType()));
5019 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5020 // None of the supported targets knows how to perform load and sign extend
5021 // on vectors in one instruction. We only perform this transformation on
5023 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5024 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5025 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5026 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5027 bool DoXform = true;
5028 SmallVector<SDNode*, 4> SetCCs;
5029 if (!N0.hasOneUse())
5030 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5032 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5033 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5035 LN0->getBasePtr(), N0.getValueType(),
5036 LN0->getMemOperand());
5037 CombineTo(N, ExtLoad);
5038 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5039 N0.getValueType(), ExtLoad);
5040 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5041 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5047 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5048 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5049 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5050 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5051 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5052 EVT MemVT = LN0->getMemoryVT();
5053 if ((!LegalOperations && !LN0->isVolatile()) ||
5054 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5055 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5057 LN0->getBasePtr(), MemVT,
5058 LN0->getMemOperand());
5059 CombineTo(N, ExtLoad);
5060 CombineTo(N0.getNode(),
5061 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5062 N0.getValueType(), ExtLoad),
5063 ExtLoad.getValue(1));
5064 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5068 // fold (sext (and/or/xor (load x), cst)) ->
5069 // (and/or/xor (sextload x), (sext cst))
5070 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5071 N0.getOpcode() == ISD::XOR) &&
5072 isa<LoadSDNode>(N0.getOperand(0)) &&
5073 N0.getOperand(1).getOpcode() == ISD::Constant &&
5074 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5075 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5076 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5077 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5078 bool DoXform = true;
5079 SmallVector<SDNode*, 4> SetCCs;
5080 if (!N0.hasOneUse())
5081 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5084 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5085 LN0->getChain(), LN0->getBasePtr(),
5087 LN0->getMemOperand());
5088 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5089 Mask = Mask.sext(VT.getSizeInBits());
5090 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5091 ExtLoad, DAG.getConstant(Mask, VT));
5092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5093 SDLoc(N0.getOperand(0)),
5094 N0.getOperand(0).getValueType(), ExtLoad);
5096 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5097 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5104 if (N0.getOpcode() == ISD::SETCC) {
5105 EVT N0VT = N0.getOperand(0).getValueType();
5106 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5107 // Only do this before legalize for now.
5108 if (VT.isVector() && !LegalOperations &&
5109 TLI.getBooleanContents(N0VT) ==
5110 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5111 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5112 // of the same size as the compared operands. Only optimize sext(setcc())
5113 // if this is the case.
5114 EVT SVT = getSetCCResultType(N0VT);
5116 // We know that the # elements of the results is the same as the
5117 // # elements of the compare (and the # elements of the compare result
5118 // for that matter). Check to see that they are the same size. If so,
5119 // we know that the element size of the sext'd result matches the
5120 // element size of the compare operands.
5121 if (VT.getSizeInBits() == SVT.getSizeInBits())
5122 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5124 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5126 // If the desired elements are smaller or larger than the source
5127 // elements we can use a matching integer vector type and then
5128 // truncate/sign extend
5129 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5130 if (SVT == MatchingVectorType) {
5131 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5132 N0.getOperand(0), N0.getOperand(1),
5133 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5134 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5138 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5139 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5141 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5143 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5144 NegOne, DAG.getConstant(0, VT),
5145 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5146 if (SCC.getNode()) return SCC;
5148 if (!VT.isVector()) {
5149 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5150 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5152 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5153 SDValue SetCC = DAG.getSetCC(DL,
5155 N0.getOperand(0), N0.getOperand(1), CC);
5156 EVT SelectVT = getSetCCResultType(VT);
5157 return DAG.getSelect(DL, VT,
5158 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5159 NegOne, DAG.getConstant(0, VT));
5165 // fold (sext x) -> (zext x) if the sign bit is known zero.
5166 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5167 DAG.SignBitIsZero(N0))
5168 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5173 // isTruncateOf - If N is a truncate of some other value, return true, record
5174 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5175 // This function computes KnownZero to avoid a duplicated call to
5176 // computeKnownBits in the caller.
5177 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5180 if (N->getOpcode() == ISD::TRUNCATE) {
5181 Op = N->getOperand(0);
5182 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5186 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5187 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5190 SDValue Op0 = N->getOperand(0);
5191 SDValue Op1 = N->getOperand(1);
5192 assert(Op0.getValueType() == Op1.getValueType());
5194 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5195 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5196 if (COp0 && COp0->isNullValue())
5198 else if (COp1 && COp1->isNullValue())
5203 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5205 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5211 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5212 SDValue N0 = N->getOperand(0);
5213 EVT VT = N->getValueType(0);
5215 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5217 return SDValue(Res, 0);
5219 // fold (zext (zext x)) -> (zext x)
5220 // fold (zext (aext x)) -> (zext x)
5221 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5225 // fold (zext (truncate x)) -> (zext x) or
5226 // (zext (truncate x)) -> (truncate x)
5227 // This is valid when the truncated bits of x are already zero.
5228 // FIXME: We should extend this to work for vectors too.
5231 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5232 APInt TruncatedBits =
5233 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5234 APInt(Op.getValueSizeInBits(), 0) :
5235 APInt::getBitsSet(Op.getValueSizeInBits(),
5236 N0.getValueSizeInBits(),
5237 std::min(Op.getValueSizeInBits(),
5238 VT.getSizeInBits()));
5239 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5240 if (VT.bitsGT(Op.getValueType()))
5241 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5242 if (VT.bitsLT(Op.getValueType()))
5243 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5249 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5250 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5251 if (N0.getOpcode() == ISD::TRUNCATE) {
5252 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5253 if (NarrowLoad.getNode()) {
5254 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5255 if (NarrowLoad.getNode() != N0.getNode()) {
5256 CombineTo(N0.getNode(), NarrowLoad);
5257 // CombineTo deleted the truncate, if needed, but not what's under it.
5260 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5264 // fold (zext (truncate x)) -> (and x, mask)
5265 if (N0.getOpcode() == ISD::TRUNCATE &&
5266 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5268 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5269 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5270 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5271 if (NarrowLoad.getNode()) {
5272 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5273 if (NarrowLoad.getNode() != N0.getNode()) {
5274 CombineTo(N0.getNode(), NarrowLoad);
5275 // CombineTo deleted the truncate, if needed, but not what's under it.
5278 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5281 SDValue Op = N0.getOperand(0);
5282 if (Op.getValueType().bitsLT(VT)) {
5283 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5284 AddToWorklist(Op.getNode());
5285 } else if (Op.getValueType().bitsGT(VT)) {
5286 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5287 AddToWorklist(Op.getNode());
5289 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5290 N0.getValueType().getScalarType());
5293 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5294 // if either of the casts is not free.
5295 if (N0.getOpcode() == ISD::AND &&
5296 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5297 N0.getOperand(1).getOpcode() == ISD::Constant &&
5298 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5299 N0.getValueType()) ||
5300 !TLI.isZExtFree(N0.getValueType(), VT))) {
5301 SDValue X = N0.getOperand(0).getOperand(0);
5302 if (X.getValueType().bitsLT(VT)) {
5303 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5304 } else if (X.getValueType().bitsGT(VT)) {
5305 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5307 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5308 Mask = Mask.zext(VT.getSizeInBits());
5309 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5310 X, DAG.getConstant(Mask, VT));
5313 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5314 // None of the supported targets knows how to perform load and vector_zext
5315 // on vectors in one instruction. We only perform this transformation on
5317 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5318 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5319 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5320 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5321 bool DoXform = true;
5322 SmallVector<SDNode*, 4> SetCCs;
5323 if (!N0.hasOneUse())
5324 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5326 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5327 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5329 LN0->getBasePtr(), N0.getValueType(),
5330 LN0->getMemOperand());
5331 CombineTo(N, ExtLoad);
5332 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5333 N0.getValueType(), ExtLoad);
5334 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5336 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5338 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5342 // fold (zext (and/or/xor (load x), cst)) ->
5343 // (and/or/xor (zextload x), (zext cst))
5344 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5345 N0.getOpcode() == ISD::XOR) &&
5346 isa<LoadSDNode>(N0.getOperand(0)) &&
5347 N0.getOperand(1).getOpcode() == ISD::Constant &&
5348 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5349 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5350 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5351 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5352 bool DoXform = true;
5353 SmallVector<SDNode*, 4> SetCCs;
5354 if (!N0.hasOneUse())
5355 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5358 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5359 LN0->getChain(), LN0->getBasePtr(),
5361 LN0->getMemOperand());
5362 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5363 Mask = Mask.zext(VT.getSizeInBits());
5364 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5365 ExtLoad, DAG.getConstant(Mask, VT));
5366 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5367 SDLoc(N0.getOperand(0)),
5368 N0.getOperand(0).getValueType(), ExtLoad);
5370 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5371 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5378 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5379 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5380 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5381 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5382 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5383 EVT MemVT = LN0->getMemoryVT();
5384 if ((!LegalOperations && !LN0->isVolatile()) ||
5385 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5386 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5388 LN0->getBasePtr(), MemVT,
5389 LN0->getMemOperand());
5390 CombineTo(N, ExtLoad);
5391 CombineTo(N0.getNode(),
5392 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5394 ExtLoad.getValue(1));
5395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5399 if (N0.getOpcode() == ISD::SETCC) {
5400 if (!LegalOperations && VT.isVector() &&
5401 N0.getValueType().getVectorElementType() == MVT::i1) {
5402 EVT N0VT = N0.getOperand(0).getValueType();
5403 if (getSetCCResultType(N0VT) == N0.getValueType())
5406 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5407 // Only do this before legalize for now.
5408 EVT EltVT = VT.getVectorElementType();
5409 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5410 DAG.getConstant(1, EltVT));
5411 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5412 // We know that the # elements of the results is the same as the
5413 // # elements of the compare (and the # elements of the compare result
5414 // for that matter). Check to see that they are the same size. If so,
5415 // we know that the element size of the sext'd result matches the
5416 // element size of the compare operands.
5417 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5418 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5420 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5421 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5424 // If the desired elements are smaller or larger than the source
5425 // elements we can use a matching integer vector type and then
5426 // truncate/sign extend
5427 EVT MatchingElementType =
5428 EVT::getIntegerVT(*DAG.getContext(),
5429 N0VT.getScalarType().getSizeInBits());
5430 EVT MatchingVectorType =
5431 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5432 N0VT.getVectorNumElements());
5434 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5436 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5437 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5438 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5439 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5442 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5444 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5445 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5446 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5447 if (SCC.getNode()) return SCC;
5450 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5451 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5452 isa<ConstantSDNode>(N0.getOperand(1)) &&
5453 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5455 SDValue ShAmt = N0.getOperand(1);
5456 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5457 if (N0.getOpcode() == ISD::SHL) {
5458 SDValue InnerZExt = N0.getOperand(0);
5459 // If the original shl may be shifting out bits, do not perform this
5461 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5462 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5463 if (ShAmtVal > KnownZeroBits)
5469 // Ensure that the shift amount is wide enough for the shifted value.
5470 if (VT.getSizeInBits() >= 256)
5471 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5473 return DAG.getNode(N0.getOpcode(), DL, VT,
5474 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5481 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5482 SDValue N0 = N->getOperand(0);
5483 EVT VT = N->getValueType(0);
5485 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5487 return SDValue(Res, 0);
5489 // fold (aext (aext x)) -> (aext x)
5490 // fold (aext (zext x)) -> (zext x)
5491 // fold (aext (sext x)) -> (sext x)
5492 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5493 N0.getOpcode() == ISD::ZERO_EXTEND ||
5494 N0.getOpcode() == ISD::SIGN_EXTEND)
5495 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5497 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5498 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5499 if (N0.getOpcode() == ISD::TRUNCATE) {
5500 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5501 if (NarrowLoad.getNode()) {
5502 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5503 if (NarrowLoad.getNode() != N0.getNode()) {
5504 CombineTo(N0.getNode(), NarrowLoad);
5505 // CombineTo deleted the truncate, if needed, but not what's under it.
5508 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5512 // fold (aext (truncate x))
5513 if (N0.getOpcode() == ISD::TRUNCATE) {
5514 SDValue TruncOp = N0.getOperand(0);
5515 if (TruncOp.getValueType() == VT)
5516 return TruncOp; // x iff x size == zext size.
5517 if (TruncOp.getValueType().bitsGT(VT))
5518 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5519 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5522 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5523 // if the trunc is not free.
5524 if (N0.getOpcode() == ISD::AND &&
5525 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5526 N0.getOperand(1).getOpcode() == ISD::Constant &&
5527 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5528 N0.getValueType())) {
5529 SDValue X = N0.getOperand(0).getOperand(0);
5530 if (X.getValueType().bitsLT(VT)) {
5531 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5532 } else if (X.getValueType().bitsGT(VT)) {
5533 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5535 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5536 Mask = Mask.zext(VT.getSizeInBits());
5537 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5538 X, DAG.getConstant(Mask, VT));
5541 // fold (aext (load x)) -> (aext (truncate (extload x)))
5542 // None of the supported targets knows how to perform load and any_ext
5543 // on vectors in one instruction. We only perform this transformation on
5545 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5546 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5547 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5548 bool DoXform = true;
5549 SmallVector<SDNode*, 4> SetCCs;
5550 if (!N0.hasOneUse())
5551 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5553 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5554 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5556 LN0->getBasePtr(), N0.getValueType(),
5557 LN0->getMemOperand());
5558 CombineTo(N, ExtLoad);
5559 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5560 N0.getValueType(), ExtLoad);
5561 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5562 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5568 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5569 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5570 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5571 if (N0.getOpcode() == ISD::LOAD &&
5572 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5574 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5575 ISD::LoadExtType ExtType = LN0->getExtensionType();
5576 EVT MemVT = LN0->getMemoryVT();
5577 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5578 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5579 VT, LN0->getChain(), LN0->getBasePtr(),
5580 MemVT, LN0->getMemOperand());
5581 CombineTo(N, ExtLoad);
5582 CombineTo(N0.getNode(),
5583 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5584 N0.getValueType(), ExtLoad),
5585 ExtLoad.getValue(1));
5586 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5590 if (N0.getOpcode() == ISD::SETCC) {
5592 // aext(setcc) -> vsetcc
5593 // aext(setcc) -> truncate(vsetcc)
5594 // aext(setcc) -> aext(vsetcc)
5595 // Only do this before legalize for now.
5596 if (VT.isVector() && !LegalOperations) {
5597 EVT N0VT = N0.getOperand(0).getValueType();
5598 // We know that the # elements of the results is the same as the
5599 // # elements of the compare (and the # elements of the compare result
5600 // for that matter). Check to see that they are the same size. If so,
5601 // we know that the element size of the sext'd result matches the
5602 // element size of the compare operands.
5603 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5604 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5606 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5607 // If the desired elements are smaller or larger than the source
5608 // elements we can use a matching integer vector type and then
5609 // truncate/any extend
5611 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5613 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5615 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5616 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5620 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5622 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5623 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5624 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5632 /// GetDemandedBits - See if the specified operand can be simplified with the
5633 /// knowledge that only the bits specified by Mask are used. If so, return the
5634 /// simpler operand, otherwise return a null SDValue.
5635 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5636 switch (V.getOpcode()) {
5638 case ISD::Constant: {
5639 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5640 assert(CV && "Const value should be ConstSDNode.");
5641 const APInt &CVal = CV->getAPIntValue();
5642 APInt NewVal = CVal & Mask;
5644 return DAG.getConstant(NewVal, V.getValueType());
5649 // If the LHS or RHS don't contribute bits to the or, drop them.
5650 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5651 return V.getOperand(1);
5652 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5653 return V.getOperand(0);
5656 // Only look at single-use SRLs.
5657 if (!V.getNode()->hasOneUse())
5659 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5660 // See if we can recursively simplify the LHS.
5661 unsigned Amt = RHSC->getZExtValue();
5663 // Watch out for shift count overflow though.
5664 if (Amt >= Mask.getBitWidth()) break;
5665 APInt NewMask = Mask << Amt;
5666 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5667 if (SimplifyLHS.getNode())
5668 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5669 SimplifyLHS, V.getOperand(1));
5675 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5676 /// bits and then truncated to a narrower type and where N is a multiple
5677 /// of number of bits of the narrower type, transform it to a narrower load
5678 /// from address + N / num of bits of new type. If the result is to be
5679 /// extended, also fold the extension to form a extending load.
5680 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5681 unsigned Opc = N->getOpcode();
5683 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5684 SDValue N0 = N->getOperand(0);
5685 EVT VT = N->getValueType(0);
5688 // This transformation isn't valid for vector loads.
5692 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5694 if (Opc == ISD::SIGN_EXTEND_INREG) {
5695 ExtType = ISD::SEXTLOAD;
5696 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5697 } else if (Opc == ISD::SRL) {
5698 // Another special-case: SRL is basically zero-extending a narrower value.
5699 ExtType = ISD::ZEXTLOAD;
5701 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5702 if (!N01) return SDValue();
5703 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5704 VT.getSizeInBits() - N01->getZExtValue());
5706 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5709 unsigned EVTBits = ExtVT.getSizeInBits();
5711 // Do not generate loads of non-round integer types since these can
5712 // be expensive (and would be wrong if the type is not byte sized).
5713 if (!ExtVT.isRound())
5717 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5718 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5719 ShAmt = N01->getZExtValue();
5720 // Is the shift amount a multiple of size of VT?
5721 if ((ShAmt & (EVTBits-1)) == 0) {
5722 N0 = N0.getOperand(0);
5723 // Is the load width a multiple of size of VT?
5724 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5728 // At this point, we must have a load or else we can't do the transform.
5729 if (!isa<LoadSDNode>(N0)) return SDValue();
5731 // Because a SRL must be assumed to *need* to zero-extend the high bits
5732 // (as opposed to anyext the high bits), we can't combine the zextload
5733 // lowering of SRL and an sextload.
5734 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5737 // If the shift amount is larger than the input type then we're not
5738 // accessing any of the loaded bytes. If the load was a zextload/extload
5739 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5740 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5745 // If the load is shifted left (and the result isn't shifted back right),
5746 // we can fold the truncate through the shift.
5747 unsigned ShLeftAmt = 0;
5748 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5749 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5750 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5751 ShLeftAmt = N01->getZExtValue();
5752 N0 = N0.getOperand(0);
5756 // If we haven't found a load, we can't narrow it. Don't transform one with
5757 // multiple uses, this would require adding a new load.
5758 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5761 // Don't change the width of a volatile load.
5762 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5763 if (LN0->isVolatile())
5766 // Verify that we are actually reducing a load width here.
5767 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5770 // For the transform to be legal, the load must produce only two values
5771 // (the value loaded and the chain). Don't transform a pre-increment
5772 // load, for example, which produces an extra value. Otherwise the
5773 // transformation is not equivalent, and the downstream logic to replace
5774 // uses gets things wrong.
5775 if (LN0->getNumValues() > 2)
5778 // If the load that we're shrinking is an extload and we're not just
5779 // discarding the extension we can't simply shrink the load. Bail.
5780 // TODO: It would be possible to merge the extensions in some cases.
5781 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5782 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5785 EVT PtrType = N0.getOperand(1).getValueType();
5787 if (PtrType == MVT::Untyped || PtrType.isExtended())
5788 // It's not possible to generate a constant of extended or untyped type.
5791 // For big endian targets, we need to adjust the offset to the pointer to
5792 // load the correct bytes.
5793 if (TLI.isBigEndian()) {
5794 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5795 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5796 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5799 uint64_t PtrOff = ShAmt / 8;
5800 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5801 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5802 PtrType, LN0->getBasePtr(),
5803 DAG.getConstant(PtrOff, PtrType));
5804 AddToWorklist(NewPtr.getNode());
5807 if (ExtType == ISD::NON_EXTLOAD)
5808 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5809 LN0->getPointerInfo().getWithOffset(PtrOff),
5810 LN0->isVolatile(), LN0->isNonTemporal(),
5811 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5813 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5814 LN0->getPointerInfo().getWithOffset(PtrOff),
5815 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5816 NewAlign, LN0->getTBAAInfo());
5818 // Replace the old load's chain with the new load's chain.
5819 WorklistRemover DeadNodes(*this);
5820 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5822 // Shift the result left, if we've swallowed a left shift.
5823 SDValue Result = Load;
5824 if (ShLeftAmt != 0) {
5825 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5826 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5828 // If the shift amount is as large as the result size (but, presumably,
5829 // no larger than the source) then the useful bits of the result are
5830 // zero; we can't simply return the shortened shift, because the result
5831 // of that operation is undefined.
5832 if (ShLeftAmt >= VT.getSizeInBits())
5833 Result = DAG.getConstant(0, VT);
5835 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5836 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5839 // Return the new loaded value.
5843 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5844 SDValue N0 = N->getOperand(0);
5845 SDValue N1 = N->getOperand(1);
5846 EVT VT = N->getValueType(0);
5847 EVT EVT = cast<VTSDNode>(N1)->getVT();
5848 unsigned VTBits = VT.getScalarType().getSizeInBits();
5849 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5851 // fold (sext_in_reg c1) -> c1
5852 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5855 // If the input is already sign extended, just drop the extension.
5856 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5859 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5860 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5861 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5862 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5863 N0.getOperand(0), N1);
5865 // fold (sext_in_reg (sext x)) -> (sext x)
5866 // fold (sext_in_reg (aext x)) -> (sext x)
5867 // if x is small enough.
5868 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5869 SDValue N00 = N0.getOperand(0);
5870 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5871 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5872 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5875 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5876 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5877 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5879 // fold operands of sext_in_reg based on knowledge that the top bits are not
5881 if (SimplifyDemandedBits(SDValue(N, 0)))
5882 return SDValue(N, 0);
5884 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5885 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5886 SDValue NarrowLoad = ReduceLoadWidth(N);
5887 if (NarrowLoad.getNode())
5890 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5891 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5892 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5893 if (N0.getOpcode() == ISD::SRL) {
5894 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5895 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5896 // We can turn this into an SRA iff the input to the SRL is already sign
5898 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5899 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5900 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5901 N0.getOperand(0), N0.getOperand(1));
5905 // fold (sext_inreg (extload x)) -> (sextload x)
5906 if (ISD::isEXTLoad(N0.getNode()) &&
5907 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5908 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5909 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5910 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5911 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5912 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5914 LN0->getBasePtr(), EVT,
5915 LN0->getMemOperand());
5916 CombineTo(N, ExtLoad);
5917 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5918 AddToWorklist(ExtLoad.getNode());
5919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5921 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5922 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5924 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5925 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5926 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5927 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5928 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5930 LN0->getBasePtr(), EVT,
5931 LN0->getMemOperand());
5932 CombineTo(N, ExtLoad);
5933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5937 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5938 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5939 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5940 N0.getOperand(1), false);
5941 if (BSwap.getNode())
5942 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5946 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5947 // into a build_vector.
5948 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5949 SmallVector<SDValue, 8> Elts;
5950 unsigned NumElts = N0->getNumOperands();
5951 unsigned ShAmt = VTBits - EVTBits;
5953 for (unsigned i = 0; i != NumElts; ++i) {
5954 SDValue Op = N0->getOperand(i);
5955 if (Op->getOpcode() == ISD::UNDEF) {
5960 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5961 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5962 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5963 Op.getValueType()));
5966 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5972 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5973 SDValue N0 = N->getOperand(0);
5974 EVT VT = N->getValueType(0);
5975 bool isLE = TLI.isLittleEndian();
5978 if (N0.getValueType() == N->getValueType(0))
5980 // fold (truncate c1) -> c1
5981 if (isa<ConstantSDNode>(N0))
5982 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5983 // fold (truncate (truncate x)) -> (truncate x)
5984 if (N0.getOpcode() == ISD::TRUNCATE)
5985 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5986 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5987 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5988 N0.getOpcode() == ISD::SIGN_EXTEND ||
5989 N0.getOpcode() == ISD::ANY_EXTEND) {
5990 if (N0.getOperand(0).getValueType().bitsLT(VT))
5991 // if the source is smaller than the dest, we still need an extend
5992 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5994 if (N0.getOperand(0).getValueType().bitsGT(VT))
5995 // if the source is larger than the dest, than we just need the truncate
5996 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5997 // if the source and dest are the same type, we can drop both the extend
5998 // and the truncate.
5999 return N0.getOperand(0);
6002 // Fold extract-and-trunc into a narrow extract. For example:
6003 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6004 // i32 y = TRUNCATE(i64 x)
6006 // v16i8 b = BITCAST (v2i64 val)
6007 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6009 // Note: We only run this optimization after type legalization (which often
6010 // creates this pattern) and before operation legalization after which
6011 // we need to be more careful about the vector instructions that we generate.
6012 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6013 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6015 EVT VecTy = N0.getOperand(0).getValueType();
6016 EVT ExTy = N0.getValueType();
6017 EVT TrTy = N->getValueType(0);
6019 unsigned NumElem = VecTy.getVectorNumElements();
6020 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6022 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6023 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6025 SDValue EltNo = N0->getOperand(1);
6026 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6027 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6028 EVT IndexTy = TLI.getVectorIdxTy();
6029 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6031 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6032 NVT, N0.getOperand(0));
6034 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6036 DAG.getConstant(Index, IndexTy));
6040 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6041 if (N0.getOpcode() == ISD::SELECT) {
6042 EVT SrcVT = N0.getValueType();
6043 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6044 TLI.isTruncateFree(SrcVT, VT)) {
6046 SDValue Cond = N0.getOperand(0);
6047 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6048 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6049 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6053 // Fold a series of buildvector, bitcast, and truncate if possible.
6055 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6056 // (2xi32 (buildvector x, y)).
6057 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6058 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6059 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6060 N0.getOperand(0).hasOneUse()) {
6062 SDValue BuildVect = N0.getOperand(0);
6063 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6064 EVT TruncVecEltTy = VT.getVectorElementType();
6066 // Check that the element types match.
6067 if (BuildVectEltTy == TruncVecEltTy) {
6068 // Now we only need to compute the offset of the truncated elements.
6069 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6070 unsigned TruncVecNumElts = VT.getVectorNumElements();
6071 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6073 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6074 "Invalid number of elements");
6076 SmallVector<SDValue, 8> Opnds;
6077 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6078 Opnds.push_back(BuildVect.getOperand(i));
6080 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6084 // See if we can simplify the input to this truncate through knowledge that
6085 // only the low bits are being used.
6086 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6087 // Currently we only perform this optimization on scalars because vectors
6088 // may have different active low bits.
6089 if (!VT.isVector()) {
6091 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6092 VT.getSizeInBits()));
6093 if (Shorter.getNode())
6094 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6096 // fold (truncate (load x)) -> (smaller load x)
6097 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6098 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6099 SDValue Reduced = ReduceLoadWidth(N);
6100 if (Reduced.getNode())
6102 // Handle the case where the load remains an extending load even
6103 // after truncation.
6104 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6105 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6106 if (!LN0->isVolatile() &&
6107 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6108 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6109 VT, LN0->getChain(), LN0->getBasePtr(),
6111 LN0->getMemOperand());
6112 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6117 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6118 // where ... are all 'undef'.
6119 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6120 SmallVector<EVT, 8> VTs;
6123 unsigned NumDefs = 0;
6125 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6126 SDValue X = N0.getOperand(i);
6127 if (X.getOpcode() != ISD::UNDEF) {
6132 // Stop if more than one members are non-undef.
6135 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6136 VT.getVectorElementType(),
6137 X.getValueType().getVectorNumElements()));
6141 return DAG.getUNDEF(VT);
6144 assert(V.getNode() && "The single defined operand is empty!");
6145 SmallVector<SDValue, 8> Opnds;
6146 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6148 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6151 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6152 AddToWorklist(NV.getNode());
6153 Opnds.push_back(NV);
6155 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6159 // Simplify the operands using demanded-bits information.
6160 if (!VT.isVector() &&
6161 SimplifyDemandedBits(SDValue(N, 0)))
6162 return SDValue(N, 0);
6167 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6168 SDValue Elt = N->getOperand(i);
6169 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6170 return Elt.getNode();
6171 return Elt.getOperand(Elt.getResNo()).getNode();
6174 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6175 /// if load locations are consecutive.
6176 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6177 assert(N->getOpcode() == ISD::BUILD_PAIR);
6179 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6180 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6181 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6182 LD1->getAddressSpace() != LD2->getAddressSpace())
6184 EVT LD1VT = LD1->getValueType(0);
6186 if (ISD::isNON_EXTLoad(LD2) &&
6188 // If both are volatile this would reduce the number of volatile loads.
6189 // If one is volatile it might be ok, but play conservative and bail out.
6190 !LD1->isVolatile() &&
6191 !LD2->isVolatile() &&
6192 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6193 unsigned Align = LD1->getAlignment();
6194 unsigned NewAlign = TLI.getDataLayout()->
6195 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6197 if (NewAlign <= Align &&
6198 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6199 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6200 LD1->getBasePtr(), LD1->getPointerInfo(),
6201 false, false, false, Align);
6207 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6208 SDValue N0 = N->getOperand(0);
6209 EVT VT = N->getValueType(0);
6211 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6212 // Only do this before legalize, since afterward the target may be depending
6213 // on the bitconvert.
6214 // First check to see if this is all constant.
6216 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6218 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6220 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6221 assert(!DestEltVT.isVector() &&
6222 "Element type of vector ValueType must not be vector!");
6224 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6227 // If the input is a constant, let getNode fold it.
6228 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6229 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6230 if (Res.getNode() != N) {
6231 if (!LegalOperations ||
6232 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6235 // Folding it resulted in an illegal node, and it's too late to
6236 // do that. Clean up the old node and forego the transformation.
6237 // Ideally this won't happen very often, because instcombine
6238 // and the earlier dagcombine runs (where illegal nodes are
6239 // permitted) should have folded most of them already.
6240 DAG.DeleteNode(Res.getNode());
6244 // (conv (conv x, t1), t2) -> (conv x, t2)
6245 if (N0.getOpcode() == ISD::BITCAST)
6246 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6249 // fold (conv (load x)) -> (load (conv*)x)
6250 // If the resultant load doesn't need a higher alignment than the original!
6251 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6252 // Do not change the width of a volatile load.
6253 !cast<LoadSDNode>(N0)->isVolatile() &&
6254 // Do not remove the cast if the types differ in endian layout.
6255 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6256 TLI.hasBigEndianPartOrdering(VT) &&
6257 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6258 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6259 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6260 unsigned Align = TLI.getDataLayout()->
6261 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6262 unsigned OrigAlign = LN0->getAlignment();
6264 if (Align <= OrigAlign) {
6265 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6266 LN0->getBasePtr(), LN0->getPointerInfo(),
6267 LN0->isVolatile(), LN0->isNonTemporal(),
6268 LN0->isInvariant(), OrigAlign,
6269 LN0->getTBAAInfo());
6271 CombineTo(N0.getNode(),
6272 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6273 N0.getValueType(), Load),
6279 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6280 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6281 // This often reduces constant pool loads.
6282 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6283 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6284 N0.getNode()->hasOneUse() && VT.isInteger() &&
6285 !VT.isVector() && !N0.getValueType().isVector()) {
6286 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6288 AddToWorklist(NewConv.getNode());
6290 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6291 if (N0.getOpcode() == ISD::FNEG)
6292 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6293 NewConv, DAG.getConstant(SignBit, VT));
6294 assert(N0.getOpcode() == ISD::FABS);
6295 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6296 NewConv, DAG.getConstant(~SignBit, VT));
6299 // fold (bitconvert (fcopysign cst, x)) ->
6300 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6301 // Note that we don't handle (copysign x, cst) because this can always be
6302 // folded to an fneg or fabs.
6303 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6304 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6305 VT.isInteger() && !VT.isVector()) {
6306 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6307 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6308 if (isTypeLegal(IntXVT)) {
6309 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6310 IntXVT, N0.getOperand(1));
6311 AddToWorklist(X.getNode());
6313 // If X has a different width than the result/lhs, sext it or truncate it.
6314 unsigned VTWidth = VT.getSizeInBits();
6315 if (OrigXWidth < VTWidth) {
6316 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6317 AddToWorklist(X.getNode());
6318 } else if (OrigXWidth > VTWidth) {
6319 // To get the sign bit in the right place, we have to shift it right
6320 // before truncating.
6321 X = DAG.getNode(ISD::SRL, SDLoc(X),
6322 X.getValueType(), X,
6323 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6324 AddToWorklist(X.getNode());
6325 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6326 AddToWorklist(X.getNode());
6329 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6330 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6331 X, DAG.getConstant(SignBit, VT));
6332 AddToWorklist(X.getNode());
6334 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6335 VT, N0.getOperand(0));
6336 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6337 Cst, DAG.getConstant(~SignBit, VT));
6338 AddToWorklist(Cst.getNode());
6340 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6344 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6345 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6346 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6347 if (CombineLD.getNode())
6354 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6355 EVT VT = N->getValueType(0);
6356 return CombineConsecutiveLoads(N, VT);
6359 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6360 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6361 /// destination element value type.
6362 SDValue DAGCombiner::
6363 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6364 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6366 // If this is already the right type, we're done.
6367 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6369 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6370 unsigned DstBitSize = DstEltVT.getSizeInBits();
6372 // If this is a conversion of N elements of one type to N elements of another
6373 // type, convert each element. This handles FP<->INT cases.
6374 if (SrcBitSize == DstBitSize) {
6375 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6376 BV->getValueType(0).getVectorNumElements());
6378 // Due to the FP element handling below calling this routine recursively,
6379 // we can end up with a scalar-to-vector node here.
6380 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6381 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6382 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6383 DstEltVT, BV->getOperand(0)));
6385 SmallVector<SDValue, 8> Ops;
6386 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6387 SDValue Op = BV->getOperand(i);
6388 // If the vector element type is not legal, the BUILD_VECTOR operands
6389 // are promoted and implicitly truncated. Make that explicit here.
6390 if (Op.getValueType() != SrcEltVT)
6391 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6392 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6394 AddToWorklist(Ops.back().getNode());
6396 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6399 // Otherwise, we're growing or shrinking the elements. To avoid having to
6400 // handle annoying details of growing/shrinking FP values, we convert them to
6402 if (SrcEltVT.isFloatingPoint()) {
6403 // Convert the input float vector to a int vector where the elements are the
6405 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6406 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6407 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6411 // Now we know the input is an integer vector. If the output is a FP type,
6412 // convert to integer first, then to FP of the right size.
6413 if (DstEltVT.isFloatingPoint()) {
6414 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6415 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6416 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6418 // Next, convert to FP elements of the same size.
6419 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6422 // Okay, we know the src/dst types are both integers of differing types.
6423 // Handling growing first.
6424 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6425 if (SrcBitSize < DstBitSize) {
6426 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6428 SmallVector<SDValue, 8> Ops;
6429 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6430 i += NumInputsPerOutput) {
6431 bool isLE = TLI.isLittleEndian();
6432 APInt NewBits = APInt(DstBitSize, 0);
6433 bool EltIsUndef = true;
6434 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6435 // Shift the previously computed bits over.
6436 NewBits <<= SrcBitSize;
6437 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6438 if (Op.getOpcode() == ISD::UNDEF) continue;
6441 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6442 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6446 Ops.push_back(DAG.getUNDEF(DstEltVT));
6448 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6451 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6452 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6455 // Finally, this must be the case where we are shrinking elements: each input
6456 // turns into multiple outputs.
6457 bool isS2V = ISD::isScalarToVector(BV);
6458 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6459 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6460 NumOutputsPerInput*BV->getNumOperands());
6461 SmallVector<SDValue, 8> Ops;
6463 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6464 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6465 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6466 Ops.push_back(DAG.getUNDEF(DstEltVT));
6470 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6471 getAPIntValue().zextOrTrunc(SrcBitSize);
6473 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6474 APInt ThisVal = OpVal.trunc(DstBitSize);
6475 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6476 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6477 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6478 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6480 OpVal = OpVal.lshr(DstBitSize);
6483 // For big endian targets, swap the order of the pieces of each element.
6484 if (TLI.isBigEndian())
6485 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6488 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6491 SDValue DAGCombiner::visitFADD(SDNode *N) {
6492 SDValue N0 = N->getOperand(0);
6493 SDValue N1 = N->getOperand(1);
6494 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6495 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6496 EVT VT = N->getValueType(0);
6499 if (VT.isVector()) {
6500 SDValue FoldedVOp = SimplifyVBinOp(N);
6501 if (FoldedVOp.getNode()) return FoldedVOp;
6504 // fold (fadd c1, c2) -> c1 + c2
6506 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6507 // canonicalize constant to RHS
6508 if (N0CFP && !N1CFP)
6509 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6510 // fold (fadd A, 0) -> A
6511 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6512 N1CFP->getValueAPF().isZero())
6514 // fold (fadd A, (fneg B)) -> (fsub A, B)
6515 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6516 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6517 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6518 GetNegatedExpression(N1, DAG, LegalOperations));
6519 // fold (fadd (fneg A), B) -> (fsub B, A)
6520 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6521 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6522 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6523 GetNegatedExpression(N0, DAG, LegalOperations));
6525 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6526 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6527 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6528 isa<ConstantFPSDNode>(N0.getOperand(1)))
6529 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6530 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6531 N0.getOperand(1), N1));
6533 // No FP constant should be created after legalization as Instruction
6534 // Selection pass has hard time in dealing with FP constant.
6536 // We don't need test this condition for transformation like following, as
6537 // the DAG being transformed implies it is legal to take FP constant as
6540 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6542 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6544 // If allow, fold (fadd (fneg x), x) -> 0.0
6545 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6546 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6547 return DAG.getConstantFP(0.0, VT);
6549 // If allow, fold (fadd x, (fneg x)) -> 0.0
6550 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6551 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6552 return DAG.getConstantFP(0.0, VT);
6554 // In unsafe math mode, we can fold chains of FADD's of the same value
6555 // into multiplications. This transform is not safe in general because
6556 // we are reducing the number of rounding steps.
6557 if (DAG.getTarget().Options.UnsafeFPMath &&
6558 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6560 if (N0.getOpcode() == ISD::FMUL) {
6561 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6562 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6564 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6565 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6566 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6568 DAG.getConstantFP(1.0, VT));
6569 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6573 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6574 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6575 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6577 DAG.getConstantFP(1.0, VT));
6578 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6582 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6583 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6584 N1.getOperand(0) == N1.getOperand(1) &&
6585 N0.getOperand(1) == N1.getOperand(0)) {
6586 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6588 DAG.getConstantFP(2.0, VT));
6589 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6590 N0.getOperand(1), NewCFP);
6593 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6594 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6595 N1.getOperand(0) == N1.getOperand(1) &&
6596 N0.getOperand(0) == N1.getOperand(0)) {
6597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6599 DAG.getConstantFP(2.0, VT));
6600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6601 N0.getOperand(0), NewCFP);
6605 if (N1.getOpcode() == ISD::FMUL) {
6606 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6607 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6609 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6610 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6611 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6613 DAG.getConstantFP(1.0, VT));
6614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6618 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6619 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6620 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6622 DAG.getConstantFP(1.0, VT));
6623 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6629 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6630 N0.getOperand(0) == N0.getOperand(1) &&
6631 N1.getOperand(1) == N0.getOperand(0)) {
6632 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6634 DAG.getConstantFP(2.0, VT));
6635 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6636 N1.getOperand(1), NewCFP);
6639 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6640 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6641 N0.getOperand(0) == N0.getOperand(1) &&
6642 N1.getOperand(0) == N0.getOperand(0)) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(2.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6647 N1.getOperand(0), NewCFP);
6651 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6652 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6653 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6654 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6655 (N0.getOperand(0) == N1))
6656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6657 N1, DAG.getConstantFP(3.0, VT));
6660 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6661 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6662 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6663 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6664 N1.getOperand(0) == N0)
6665 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6666 N0, DAG.getConstantFP(3.0, VT));
6669 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6670 if (AllowNewFpConst &&
6671 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6672 N0.getOperand(0) == N0.getOperand(1) &&
6673 N1.getOperand(0) == N1.getOperand(1) &&
6674 N0.getOperand(0) == N1.getOperand(0))
6675 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6677 DAG.getConstantFP(4.0, VT));
6680 // FADD -> FMA combines:
6681 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6682 DAG.getTarget().Options.UnsafeFPMath) &&
6683 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6684 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6686 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6687 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6688 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6689 N0.getOperand(0), N0.getOperand(1), N1);
6691 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6692 // Note: Commutes FADD operands.
6693 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6694 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6695 N1.getOperand(0), N1.getOperand(1), N0);
6701 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6702 SDValue N0 = N->getOperand(0);
6703 SDValue N1 = N->getOperand(1);
6704 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6705 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6706 EVT VT = N->getValueType(0);
6710 if (VT.isVector()) {
6711 SDValue FoldedVOp = SimplifyVBinOp(N);
6712 if (FoldedVOp.getNode()) return FoldedVOp;
6715 // fold (fsub c1, c2) -> c1-c2
6717 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6718 // fold (fsub A, 0) -> A
6719 if (DAG.getTarget().Options.UnsafeFPMath &&
6720 N1CFP && N1CFP->getValueAPF().isZero())
6722 // fold (fsub 0, B) -> -B
6723 if (DAG.getTarget().Options.UnsafeFPMath &&
6724 N0CFP && N0CFP->getValueAPF().isZero()) {
6725 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6726 return GetNegatedExpression(N1, DAG, LegalOperations);
6727 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6728 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6730 // fold (fsub A, (fneg B)) -> (fadd A, B)
6731 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6732 return DAG.getNode(ISD::FADD, dl, VT, N0,
6733 GetNegatedExpression(N1, DAG, LegalOperations));
6735 // If 'unsafe math' is enabled, fold
6736 // (fsub x, x) -> 0.0 &
6737 // (fsub x, (fadd x, y)) -> (fneg y) &
6738 // (fsub x, (fadd y, x)) -> (fneg y)
6739 if (DAG.getTarget().Options.UnsafeFPMath) {
6741 return DAG.getConstantFP(0.0f, VT);
6743 if (N1.getOpcode() == ISD::FADD) {
6744 SDValue N10 = N1->getOperand(0);
6745 SDValue N11 = N1->getOperand(1);
6747 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6748 &DAG.getTarget().Options))
6749 return GetNegatedExpression(N11, DAG, LegalOperations);
6751 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6752 &DAG.getTarget().Options))
6753 return GetNegatedExpression(N10, DAG, LegalOperations);
6757 // FSUB -> FMA combines:
6758 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6759 DAG.getTarget().Options.UnsafeFPMath) &&
6760 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6761 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6763 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6764 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6765 return DAG.getNode(ISD::FMA, dl, VT,
6766 N0.getOperand(0), N0.getOperand(1),
6767 DAG.getNode(ISD::FNEG, dl, VT, N1));
6769 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6770 // Note: Commutes FSUB operands.
6771 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6772 return DAG.getNode(ISD::FMA, dl, VT,
6773 DAG.getNode(ISD::FNEG, dl, VT,
6775 N1.getOperand(1), N0);
6777 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6778 if (N0.getOpcode() == ISD::FNEG &&
6779 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6780 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6781 SDValue N00 = N0.getOperand(0).getOperand(0);
6782 SDValue N01 = N0.getOperand(0).getOperand(1);
6783 return DAG.getNode(ISD::FMA, dl, VT,
6784 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6785 DAG.getNode(ISD::FNEG, dl, VT, N1));
6792 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6793 SDValue N0 = N->getOperand(0);
6794 SDValue N1 = N->getOperand(1);
6795 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6796 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6797 EVT VT = N->getValueType(0);
6798 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6801 if (VT.isVector()) {
6802 SDValue FoldedVOp = SimplifyVBinOp(N);
6803 if (FoldedVOp.getNode()) return FoldedVOp;
6806 // fold (fmul c1, c2) -> c1*c2
6808 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6809 // canonicalize constant to RHS
6810 if (N0CFP && !N1CFP)
6811 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6812 // fold (fmul A, 0) -> 0
6813 if (DAG.getTarget().Options.UnsafeFPMath &&
6814 N1CFP && N1CFP->getValueAPF().isZero())
6816 // fold (fmul A, 0) -> 0, vector edition.
6817 if (DAG.getTarget().Options.UnsafeFPMath &&
6818 ISD::isBuildVectorAllZeros(N1.getNode()))
6820 // fold (fmul A, 1.0) -> A
6821 if (N1CFP && N1CFP->isExactlyValue(1.0))
6823 // fold (fmul X, 2.0) -> (fadd X, X)
6824 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6825 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6826 // fold (fmul X, -1.0) -> (fneg X)
6827 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6828 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6829 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6831 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6832 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6833 &DAG.getTarget().Options)) {
6834 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6835 &DAG.getTarget().Options)) {
6836 // Both can be negated for free, check to see if at least one is cheaper
6838 if (LHSNeg == 2 || RHSNeg == 2)
6839 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6840 GetNegatedExpression(N0, DAG, LegalOperations),
6841 GetNegatedExpression(N1, DAG, LegalOperations));
6845 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6846 if (DAG.getTarget().Options.UnsafeFPMath &&
6847 N1CFP && N0.getOpcode() == ISD::FMUL &&
6848 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6849 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6850 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6851 N0.getOperand(1), N1));
6856 SDValue DAGCombiner::visitFMA(SDNode *N) {
6857 SDValue N0 = N->getOperand(0);
6858 SDValue N1 = N->getOperand(1);
6859 SDValue N2 = N->getOperand(2);
6860 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6861 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6862 EVT VT = N->getValueType(0);
6865 if (DAG.getTarget().Options.UnsafeFPMath) {
6866 if (N0CFP && N0CFP->isZero())
6868 if (N1CFP && N1CFP->isZero())
6871 if (N0CFP && N0CFP->isExactlyValue(1.0))
6872 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6873 if (N1CFP && N1CFP->isExactlyValue(1.0))
6874 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6876 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6877 if (N0CFP && !N1CFP)
6878 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6880 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6881 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6882 N2.getOpcode() == ISD::FMUL &&
6883 N0 == N2.getOperand(0) &&
6884 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6885 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6886 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6890 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6891 if (DAG.getTarget().Options.UnsafeFPMath &&
6892 N0.getOpcode() == ISD::FMUL && N1CFP &&
6893 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6894 return DAG.getNode(ISD::FMA, dl, VT,
6896 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6900 // (fma x, 1, y) -> (fadd x, y)
6901 // (fma x, -1, y) -> (fadd (fneg x), y)
6903 if (N1CFP->isExactlyValue(1.0))
6904 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6906 if (N1CFP->isExactlyValue(-1.0) &&
6907 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6908 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6909 AddToWorklist(RHSNeg.getNode());
6910 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6914 // (fma x, c, x) -> (fmul x, (c+1))
6915 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6916 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6917 DAG.getNode(ISD::FADD, dl, VT,
6918 N1, DAG.getConstantFP(1.0, VT)));
6920 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6921 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6922 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6923 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6924 DAG.getNode(ISD::FADD, dl, VT,
6925 N1, DAG.getConstantFP(-1.0, VT)));
6931 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6932 SDValue N0 = N->getOperand(0);
6933 SDValue N1 = N->getOperand(1);
6934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6935 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6936 EVT VT = N->getValueType(0);
6937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6940 if (VT.isVector()) {
6941 SDValue FoldedVOp = SimplifyVBinOp(N);
6942 if (FoldedVOp.getNode()) return FoldedVOp;
6945 // fold (fdiv c1, c2) -> c1/c2
6947 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6949 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6950 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6951 // Compute the reciprocal 1.0 / c2.
6952 APFloat N1APF = N1CFP->getValueAPF();
6953 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6954 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6955 // Only do the transform if the reciprocal is a legal fp immediate that
6956 // isn't too nasty (eg NaN, denormal, ...).
6957 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6958 (!LegalOperations ||
6959 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6960 // backend)... we should handle this gracefully after Legalize.
6961 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6962 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6963 TLI.isFPImmLegal(Recip, VT)))
6964 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6965 DAG.getConstantFP(Recip, VT));
6968 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6969 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6970 &DAG.getTarget().Options)) {
6971 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6972 &DAG.getTarget().Options)) {
6973 // Both can be negated for free, check to see if at least one is cheaper
6975 if (LHSNeg == 2 || RHSNeg == 2)
6976 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6977 GetNegatedExpression(N0, DAG, LegalOperations),
6978 GetNegatedExpression(N1, DAG, LegalOperations));
6985 SDValue DAGCombiner::visitFREM(SDNode *N) {
6986 SDValue N0 = N->getOperand(0);
6987 SDValue N1 = N->getOperand(1);
6988 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6989 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6990 EVT VT = N->getValueType(0);
6992 // fold (frem c1, c2) -> fmod(c1,c2)
6994 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6999 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7000 SDValue N0 = N->getOperand(0);
7001 SDValue N1 = N->getOperand(1);
7002 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7003 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7004 EVT VT = N->getValueType(0);
7006 if (N0CFP && N1CFP) // Constant fold
7007 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7010 const APFloat& V = N1CFP->getValueAPF();
7011 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7012 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7013 if (!V.isNegative()) {
7014 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7015 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7017 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7018 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7019 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7023 // copysign(fabs(x), y) -> copysign(x, y)
7024 // copysign(fneg(x), y) -> copysign(x, y)
7025 // copysign(copysign(x,z), y) -> copysign(x, y)
7026 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7027 N0.getOpcode() == ISD::FCOPYSIGN)
7028 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7029 N0.getOperand(0), N1);
7031 // copysign(x, abs(y)) -> abs(x)
7032 if (N1.getOpcode() == ISD::FABS)
7033 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7035 // copysign(x, copysign(y,z)) -> copysign(x, z)
7036 if (N1.getOpcode() == ISD::FCOPYSIGN)
7037 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7038 N0, N1.getOperand(1));
7040 // copysign(x, fp_extend(y)) -> copysign(x, y)
7041 // copysign(x, fp_round(y)) -> copysign(x, y)
7042 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7043 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7044 N0, N1.getOperand(0));
7049 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7050 SDValue N0 = N->getOperand(0);
7051 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7052 EVT VT = N->getValueType(0);
7053 EVT OpVT = N0.getValueType();
7055 // fold (sint_to_fp c1) -> c1fp
7057 // ...but only if the target supports immediate floating-point values
7058 (!LegalOperations ||
7059 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7060 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7062 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7063 // but UINT_TO_FP is legal on this target, try to convert.
7064 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7065 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7066 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7067 if (DAG.SignBitIsZero(N0))
7068 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7071 // The next optimizations are desirable only if SELECT_CC can be lowered.
7072 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7073 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7074 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7076 (!LegalOperations ||
7077 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7079 { N0.getOperand(0), N0.getOperand(1),
7080 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7082 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7085 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7086 // (select_cc x, y, 1.0, 0.0,, cc)
7087 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7088 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7089 (!LegalOperations ||
7090 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7092 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7093 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7094 N0.getOperand(0).getOperand(2) };
7095 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7102 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7103 SDValue N0 = N->getOperand(0);
7104 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7105 EVT VT = N->getValueType(0);
7106 EVT OpVT = N0.getValueType();
7108 // fold (uint_to_fp c1) -> c1fp
7110 // ...but only if the target supports immediate floating-point values
7111 (!LegalOperations ||
7112 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7113 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7115 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7116 // but SINT_TO_FP is legal on this target, try to convert.
7117 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7118 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7119 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7120 if (DAG.SignBitIsZero(N0))
7121 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7124 // The next optimizations are desirable only if SELECT_CC can be lowered.
7125 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7126 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7128 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7129 (!LegalOperations ||
7130 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7132 { N0.getOperand(0), N0.getOperand(1),
7133 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7135 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7142 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7143 SDValue N0 = N->getOperand(0);
7144 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7145 EVT VT = N->getValueType(0);
7147 // fold (fp_to_sint c1fp) -> c1
7149 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7154 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7155 SDValue N0 = N->getOperand(0);
7156 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7157 EVT VT = N->getValueType(0);
7159 // fold (fp_to_uint c1fp) -> c1
7161 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7166 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7167 SDValue N0 = N->getOperand(0);
7168 SDValue N1 = N->getOperand(1);
7169 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7170 EVT VT = N->getValueType(0);
7172 // fold (fp_round c1fp) -> c1fp
7174 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7176 // fold (fp_round (fp_extend x)) -> x
7177 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7178 return N0.getOperand(0);
7180 // fold (fp_round (fp_round x)) -> (fp_round x)
7181 if (N0.getOpcode() == ISD::FP_ROUND) {
7182 // This is a value preserving truncation if both round's are.
7183 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7184 N0.getNode()->getConstantOperandVal(1) == 1;
7185 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7186 DAG.getIntPtrConstant(IsTrunc));
7189 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7190 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7191 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7192 N0.getOperand(0), N1);
7193 AddToWorklist(Tmp.getNode());
7194 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7195 Tmp, N0.getOperand(1));
7201 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7202 SDValue N0 = N->getOperand(0);
7203 EVT VT = N->getValueType(0);
7204 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7205 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207 // fold (fp_round_inreg c1fp) -> c1fp
7208 if (N0CFP && isTypeLegal(EVT)) {
7209 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7210 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7216 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7217 SDValue N0 = N->getOperand(0);
7218 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7219 EVT VT = N->getValueType(0);
7221 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7222 if (N->hasOneUse() &&
7223 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7226 // fold (fp_extend c1fp) -> c1fp
7228 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7230 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7232 if (N0.getOpcode() == ISD::FP_ROUND
7233 && N0.getNode()->getConstantOperandVal(1) == 1) {
7234 SDValue In = N0.getOperand(0);
7235 if (In.getValueType() == VT) return In;
7236 if (VT.bitsLT(In.getValueType()))
7237 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7238 In, N0.getOperand(1));
7239 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7242 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7243 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7244 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7246 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7248 LN0->getBasePtr(), N0.getValueType(),
7249 LN0->getMemOperand());
7250 CombineTo(N, ExtLoad);
7251 CombineTo(N0.getNode(),
7252 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7253 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7254 ExtLoad.getValue(1));
7255 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7261 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7262 SDValue N0 = N->getOperand(0);
7263 EVT VT = N->getValueType(0);
7265 if (VT.isVector()) {
7266 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7267 if (FoldedVOp.getNode()) return FoldedVOp;
7270 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7271 &DAG.getTarget().Options))
7272 return GetNegatedExpression(N0, DAG, LegalOperations);
7274 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7275 // constant pool values.
7276 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7278 N0.getNode()->hasOneUse() &&
7279 N0.getOperand(0).getValueType().isInteger()) {
7280 SDValue Int = N0.getOperand(0);
7281 EVT IntVT = Int.getValueType();
7282 if (IntVT.isInteger() && !IntVT.isVector()) {
7283 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7284 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7285 AddToWorklist(Int.getNode());
7286 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7291 // (fneg (fmul c, x)) -> (fmul -c, x)
7292 if (N0.getOpcode() == ISD::FMUL) {
7293 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7295 APFloat CVal = CFP1->getValueAPF();
7297 if (Level >= AfterLegalizeDAG &&
7298 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7299 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7301 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7302 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7309 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7310 SDValue N0 = N->getOperand(0);
7311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312 EVT VT = N->getValueType(0);
7314 // fold (fceil c1) -> fceil(c1)
7316 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7321 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7322 SDValue N0 = N->getOperand(0);
7323 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7324 EVT VT = N->getValueType(0);
7326 // fold (ftrunc c1) -> ftrunc(c1)
7328 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7333 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7334 SDValue N0 = N->getOperand(0);
7335 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7336 EVT VT = N->getValueType(0);
7338 // fold (ffloor c1) -> ffloor(c1)
7340 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7345 SDValue DAGCombiner::visitFABS(SDNode *N) {
7346 SDValue N0 = N->getOperand(0);
7347 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7348 EVT VT = N->getValueType(0);
7350 if (VT.isVector()) {
7351 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7352 if (FoldedVOp.getNode()) return FoldedVOp;
7355 // fold (fabs c1) -> fabs(c1)
7357 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7358 // fold (fabs (fabs x)) -> (fabs x)
7359 if (N0.getOpcode() == ISD::FABS)
7360 return N->getOperand(0);
7361 // fold (fabs (fneg x)) -> (fabs x)
7362 // fold (fabs (fcopysign x, y)) -> (fabs x)
7363 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7364 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7366 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7367 // constant pool values.
7368 if (!TLI.isFAbsFree(VT) &&
7369 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7370 N0.getOperand(0).getValueType().isInteger() &&
7371 !N0.getOperand(0).getValueType().isVector()) {
7372 SDValue Int = N0.getOperand(0);
7373 EVT IntVT = Int.getValueType();
7374 if (IntVT.isInteger() && !IntVT.isVector()) {
7375 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7376 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7377 AddToWorklist(Int.getNode());
7378 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7379 N->getValueType(0), Int);
7386 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7387 SDValue Chain = N->getOperand(0);
7388 SDValue N1 = N->getOperand(1);
7389 SDValue N2 = N->getOperand(2);
7391 // If N is a constant we could fold this into a fallthrough or unconditional
7392 // branch. However that doesn't happen very often in normal code, because
7393 // Instcombine/SimplifyCFG should have handled the available opportunities.
7394 // If we did this folding here, it would be necessary to update the
7395 // MachineBasicBlock CFG, which is awkward.
7397 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7399 if (N1.getOpcode() == ISD::SETCC &&
7400 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7401 N1.getOperand(0).getValueType())) {
7402 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7403 Chain, N1.getOperand(2),
7404 N1.getOperand(0), N1.getOperand(1), N2);
7407 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7408 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7409 (N1.getOperand(0).hasOneUse() &&
7410 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7411 SDNode *Trunc = nullptr;
7412 if (N1.getOpcode() == ISD::TRUNCATE) {
7413 // Look pass the truncate.
7414 Trunc = N1.getNode();
7415 N1 = N1.getOperand(0);
7418 // Match this pattern so that we can generate simpler code:
7421 // %b = and i32 %a, 2
7422 // %c = srl i32 %b, 1
7423 // brcond i32 %c ...
7428 // %b = and i32 %a, 2
7429 // %c = setcc eq %b, 0
7432 // This applies only when the AND constant value has one bit set and the
7433 // SRL constant is equal to the log2 of the AND constant. The back-end is
7434 // smart enough to convert the result into a TEST/JMP sequence.
7435 SDValue Op0 = N1.getOperand(0);
7436 SDValue Op1 = N1.getOperand(1);
7438 if (Op0.getOpcode() == ISD::AND &&
7439 Op1.getOpcode() == ISD::Constant) {
7440 SDValue AndOp1 = Op0.getOperand(1);
7442 if (AndOp1.getOpcode() == ISD::Constant) {
7443 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7445 if (AndConst.isPowerOf2() &&
7446 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7448 DAG.getSetCC(SDLoc(N),
7449 getSetCCResultType(Op0.getValueType()),
7450 Op0, DAG.getConstant(0, Op0.getValueType()),
7453 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7454 MVT::Other, Chain, SetCC, N2);
7455 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7456 // will convert it back to (X & C1) >> C2.
7457 CombineTo(N, NewBRCond, false);
7458 // Truncate is dead.
7460 removeFromWorklist(Trunc);
7461 DAG.DeleteNode(Trunc);
7463 // Replace the uses of SRL with SETCC
7464 WorklistRemover DeadNodes(*this);
7465 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7466 removeFromWorklist(N1.getNode());
7467 DAG.DeleteNode(N1.getNode());
7468 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7474 // Restore N1 if the above transformation doesn't match.
7475 N1 = N->getOperand(1);
7478 // Transform br(xor(x, y)) -> br(x != y)
7479 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7480 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7481 SDNode *TheXor = N1.getNode();
7482 SDValue Op0 = TheXor->getOperand(0);
7483 SDValue Op1 = TheXor->getOperand(1);
7484 if (Op0.getOpcode() == Op1.getOpcode()) {
7485 // Avoid missing important xor optimizations.
7486 SDValue Tmp = visitXOR(TheXor);
7487 if (Tmp.getNode()) {
7488 if (Tmp.getNode() != TheXor) {
7489 DEBUG(dbgs() << "\nReplacing.8 ";
7491 dbgs() << "\nWith: ";
7492 Tmp.getNode()->dump(&DAG);
7494 WorklistRemover DeadNodes(*this);
7495 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7496 removeFromWorklist(TheXor);
7497 DAG.DeleteNode(TheXor);
7498 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7499 MVT::Other, Chain, Tmp, N2);
7502 // visitXOR has changed XOR's operands or replaced the XOR completely,
7504 return SDValue(N, 0);
7508 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7510 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7511 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7512 Op0.getOpcode() == ISD::XOR) {
7513 TheXor = Op0.getNode();
7517 EVT SetCCVT = N1.getValueType();
7519 SetCCVT = getSetCCResultType(SetCCVT);
7520 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7523 Equal ? ISD::SETEQ : ISD::SETNE);
7524 // Replace the uses of XOR with SETCC
7525 WorklistRemover DeadNodes(*this);
7526 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7527 removeFromWorklist(N1.getNode());
7528 DAG.DeleteNode(N1.getNode());
7529 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7530 MVT::Other, Chain, SetCC, N2);
7537 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7539 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7540 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7541 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7543 // If N is a constant we could fold this into a fallthrough or unconditional
7544 // branch. However that doesn't happen very often in normal code, because
7545 // Instcombine/SimplifyCFG should have handled the available opportunities.
7546 // If we did this folding here, it would be necessary to update the
7547 // MachineBasicBlock CFG, which is awkward.
7549 // Use SimplifySetCC to simplify SETCC's.
7550 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7551 CondLHS, CondRHS, CC->get(), SDLoc(N),
7553 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7555 // fold to a simpler setcc
7556 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7557 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7558 N->getOperand(0), Simp.getOperand(2),
7559 Simp.getOperand(0), Simp.getOperand(1),
7565 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7566 /// uses N as its base pointer and that N may be folded in the load / store
7567 /// addressing mode.
7568 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7570 const TargetLowering &TLI) {
7572 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7573 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7575 VT = Use->getValueType(0);
7576 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7577 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7579 VT = ST->getValue().getValueType();
7583 TargetLowering::AddrMode AM;
7584 if (N->getOpcode() == ISD::ADD) {
7585 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7588 AM.BaseOffs = Offset->getSExtValue();
7592 } else if (N->getOpcode() == ISD::SUB) {
7593 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7596 AM.BaseOffs = -Offset->getSExtValue();
7603 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7606 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7607 /// pre-indexed load / store when the base pointer is an add or subtract
7608 /// and it has other uses besides the load / store. After the
7609 /// transformation, the new indexed load / store has effectively folded
7610 /// the add / subtract in and all of its other uses are redirected to the
7611 /// new load / store.
7612 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7613 if (Level < AfterLegalizeDAG)
7619 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7620 if (LD->isIndexed())
7622 VT = LD->getMemoryVT();
7623 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7624 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7626 Ptr = LD->getBasePtr();
7627 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7628 if (ST->isIndexed())
7630 VT = ST->getMemoryVT();
7631 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7632 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7634 Ptr = ST->getBasePtr();
7640 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7641 // out. There is no reason to make this a preinc/predec.
7642 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7643 Ptr.getNode()->hasOneUse())
7646 // Ask the target to do addressing mode selection.
7649 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7650 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7653 // Backends without true r+i pre-indexed forms may need to pass a
7654 // constant base with a variable offset so that constant coercion
7655 // will work with the patterns in canonical form.
7656 bool Swapped = false;
7657 if (isa<ConstantSDNode>(BasePtr)) {
7658 std::swap(BasePtr, Offset);
7662 // Don't create a indexed load / store with zero offset.
7663 if (isa<ConstantSDNode>(Offset) &&
7664 cast<ConstantSDNode>(Offset)->isNullValue())
7667 // Try turning it into a pre-indexed load / store except when:
7668 // 1) The new base ptr is a frame index.
7669 // 2) If N is a store and the new base ptr is either the same as or is a
7670 // predecessor of the value being stored.
7671 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7672 // that would create a cycle.
7673 // 4) All uses are load / store ops that use it as old base ptr.
7675 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7676 // (plus the implicit offset) to a register to preinc anyway.
7677 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7682 SDValue Val = cast<StoreSDNode>(N)->getValue();
7683 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7687 // If the offset is a constant, there may be other adds of constants that
7688 // can be folded with this one. We should do this to avoid having to keep
7689 // a copy of the original base pointer.
7690 SmallVector<SDNode *, 16> OtherUses;
7691 if (isa<ConstantSDNode>(Offset))
7692 for (SDNode *Use : BasePtr.getNode()->uses()) {
7693 if (Use == Ptr.getNode())
7696 if (Use->isPredecessorOf(N))
7699 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7704 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7705 if (Op1.getNode() == BasePtr.getNode())
7706 std::swap(Op0, Op1);
7707 assert(Op0.getNode() == BasePtr.getNode() &&
7708 "Use of ADD/SUB but not an operand");
7710 if (!isa<ConstantSDNode>(Op1)) {
7715 // FIXME: In some cases, we can be smarter about this.
7716 if (Op1.getValueType() != Offset.getValueType()) {
7721 OtherUses.push_back(Use);
7725 std::swap(BasePtr, Offset);
7727 // Now check for #3 and #4.
7728 bool RealUse = false;
7730 // Caches for hasPredecessorHelper
7731 SmallPtrSet<const SDNode *, 32> Visited;
7732 SmallVector<const SDNode *, 16> Worklist;
7734 for (SDNode *Use : Ptr.getNode()->uses()) {
7737 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7740 // If Ptr may be folded in addressing mode of other use, then it's
7741 // not profitable to do this transformation.
7742 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7751 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7752 BasePtr, Offset, AM);
7754 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7755 BasePtr, Offset, AM);
7758 DEBUG(dbgs() << "\nReplacing.4 ";
7760 dbgs() << "\nWith: ";
7761 Result.getNode()->dump(&DAG);
7763 WorklistRemover DeadNodes(*this);
7765 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7766 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7768 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7771 // Finally, since the node is now dead, remove it from the graph.
7775 std::swap(BasePtr, Offset);
7777 // Replace other uses of BasePtr that can be updated to use Ptr
7778 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7779 unsigned OffsetIdx = 1;
7780 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7782 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7783 BasePtr.getNode() && "Expected BasePtr operand");
7785 // We need to replace ptr0 in the following expression:
7786 // x0 * offset0 + y0 * ptr0 = t0
7788 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7790 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7791 // indexed load/store and the expresion that needs to be re-written.
7793 // Therefore, we have:
7794 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7796 ConstantSDNode *CN =
7797 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7799 APInt Offset0 = CN->getAPIntValue();
7800 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7802 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7803 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7804 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7805 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7807 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7809 APInt CNV = Offset0;
7810 if (X0 < 0) CNV = -CNV;
7811 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7812 else CNV = CNV - Offset1;
7814 // We can now generate the new expression.
7815 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7816 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7818 SDValue NewUse = DAG.getNode(Opcode,
7819 SDLoc(OtherUses[i]),
7820 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7821 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7822 removeFromWorklist(OtherUses[i]);
7823 DAG.DeleteNode(OtherUses[i]);
7826 // Replace the uses of Ptr with uses of the updated base value.
7827 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7828 removeFromWorklist(Ptr.getNode());
7829 DAG.DeleteNode(Ptr.getNode());
7834 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7835 /// add / sub of the base pointer node into a post-indexed load / store.
7836 /// The transformation folded the add / subtract into the new indexed
7837 /// load / store effectively and all of its uses are redirected to the
7838 /// new load / store.
7839 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7840 if (Level < AfterLegalizeDAG)
7846 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7847 if (LD->isIndexed())
7849 VT = LD->getMemoryVT();
7850 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7851 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7853 Ptr = LD->getBasePtr();
7854 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7855 if (ST->isIndexed())
7857 VT = ST->getMemoryVT();
7858 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7859 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7861 Ptr = ST->getBasePtr();
7867 if (Ptr.getNode()->hasOneUse())
7870 for (SDNode *Op : Ptr.getNode()->uses()) {
7872 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7877 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7878 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7879 // Don't create a indexed load / store with zero offset.
7880 if (isa<ConstantSDNode>(Offset) &&
7881 cast<ConstantSDNode>(Offset)->isNullValue())
7884 // Try turning it into a post-indexed load / store except when
7885 // 1) All uses are load / store ops that use it as base ptr (and
7886 // it may be folded as addressing mmode).
7887 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7888 // nor a successor of N. Otherwise, if Op is folded that would
7891 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7895 bool TryNext = false;
7896 for (SDNode *Use : BasePtr.getNode()->uses()) {
7897 if (Use == Ptr.getNode())
7900 // If all the uses are load / store addresses, then don't do the
7902 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7903 bool RealUse = false;
7904 for (SDNode *UseUse : Use->uses()) {
7905 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7920 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7921 SDValue Result = isLoad
7922 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7923 BasePtr, Offset, AM)
7924 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7925 BasePtr, Offset, AM);
7928 DEBUG(dbgs() << "\nReplacing.5 ";
7930 dbgs() << "\nWith: ";
7931 Result.getNode()->dump(&DAG);
7933 WorklistRemover DeadNodes(*this);
7935 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7936 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7941 // Finally, since the node is now dead, remove it from the graph.
7944 // Replace the uses of Use with uses of the updated base value.
7945 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7946 Result.getValue(isLoad ? 1 : 0));
7947 removeFromWorklist(Op);
7957 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7958 LoadSDNode *LD = cast<LoadSDNode>(N);
7959 SDValue Chain = LD->getChain();
7960 SDValue Ptr = LD->getBasePtr();
7962 // If load is not volatile and there are no uses of the loaded value (and
7963 // the updated indexed value in case of indexed loads), change uses of the
7964 // chain value into uses of the chain input (i.e. delete the dead load).
7965 if (!LD->isVolatile()) {
7966 if (N->getValueType(1) == MVT::Other) {
7968 if (!N->hasAnyUseOfValue(0)) {
7969 // It's not safe to use the two value CombineTo variant here. e.g.
7970 // v1, chain2 = load chain1, loc
7971 // v2, chain3 = load chain2, loc
7973 // Now we replace use of chain2 with chain1. This makes the second load
7974 // isomorphic to the one we are deleting, and thus makes this load live.
7975 DEBUG(dbgs() << "\nReplacing.6 ";
7977 dbgs() << "\nWith chain: ";
7978 Chain.getNode()->dump(&DAG);
7980 WorklistRemover DeadNodes(*this);
7981 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7983 if (N->use_empty()) {
7984 removeFromWorklist(N);
7988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7992 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7993 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7994 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7995 DEBUG(dbgs() << "\nReplacing.7 ";
7997 dbgs() << "\nWith: ";
7998 Undef.getNode()->dump(&DAG);
7999 dbgs() << " and 2 other values\n");
8000 WorklistRemover DeadNodes(*this);
8001 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8002 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8003 DAG.getUNDEF(N->getValueType(1)));
8004 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8005 removeFromWorklist(N);
8007 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8012 // If this load is directly stored, replace the load value with the stored
8014 // TODO: Handle store large -> read small portion.
8015 // TODO: Handle TRUNCSTORE/LOADEXT
8016 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8017 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8018 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8019 if (PrevST->getBasePtr() == Ptr &&
8020 PrevST->getValue().getValueType() == N->getValueType(0))
8021 return CombineTo(N, Chain.getOperand(1), Chain);
8025 // Try to infer better alignment information than the load already has.
8026 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8027 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8028 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8030 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8031 LD->getValueType(0),
8032 Chain, Ptr, LD->getPointerInfo(),
8034 LD->isVolatile(), LD->isNonTemporal(), Align,
8036 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8041 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8042 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8044 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8045 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8048 if (UseAA && LD->isUnindexed()) {
8049 // Walk up chain skipping non-aliasing memory nodes.
8050 SDValue BetterChain = FindBetterChain(N, Chain);
8052 // If there is a better chain.
8053 if (Chain != BetterChain) {
8056 // Replace the chain to void dependency.
8057 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8058 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8059 BetterChain, Ptr, LD->getMemOperand());
8061 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8062 LD->getValueType(0),
8063 BetterChain, Ptr, LD->getMemoryVT(),
8064 LD->getMemOperand());
8067 // Create token factor to keep old chain connected.
8068 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8069 MVT::Other, Chain, ReplLoad.getValue(1));
8071 // Make sure the new and old chains are cleaned up.
8072 AddToWorklist(Token.getNode());
8074 // Replace uses with load result and token factor. Don't add users
8076 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8080 // Try transforming N to an indexed load.
8081 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8082 return SDValue(N, 0);
8084 // Try to slice up N to more direct loads if the slices are mapped to
8085 // different register banks or pairing can take place.
8087 return SDValue(N, 0);
8093 /// \brief Helper structure used to slice a load in smaller loads.
8094 /// Basically a slice is obtained from the following sequence:
8095 /// Origin = load Ty1, Base
8096 /// Shift = srl Ty1 Origin, CstTy Amount
8097 /// Inst = trunc Shift to Ty2
8099 /// Then, it will be rewriten into:
8100 /// Slice = load SliceTy, Base + SliceOffset
8101 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8103 /// SliceTy is deduced from the number of bits that are actually used to
8105 struct LoadedSlice {
8106 /// \brief Helper structure used to compute the cost of a slice.
8108 /// Are we optimizing for code size.
8113 unsigned CrossRegisterBanksCopies;
8117 Cost(bool ForCodeSize = false)
8118 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8119 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8121 /// \brief Get the cost of one isolated slice.
8122 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8123 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8124 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8125 EVT TruncType = LS.Inst->getValueType(0);
8126 EVT LoadedType = LS.getLoadedType();
8127 if (TruncType != LoadedType &&
8128 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8132 /// \brief Account for slicing gain in the current cost.
8133 /// Slicing provide a few gains like removing a shift or a
8134 /// truncate. This method allows to grow the cost of the original
8135 /// load with the gain from this slice.
8136 void addSliceGain(const LoadedSlice &LS) {
8137 // Each slice saves a truncate.
8138 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8139 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8140 LS.Inst->getOperand(0).getValueType()))
8142 // If there is a shift amount, this slice gets rid of it.
8145 // If this slice can merge a cross register bank copy, account for it.
8146 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8147 ++CrossRegisterBanksCopies;
8150 Cost &operator+=(const Cost &RHS) {
8152 Truncates += RHS.Truncates;
8153 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8159 bool operator==(const Cost &RHS) const {
8160 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8161 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8162 ZExts == RHS.ZExts && Shift == RHS.Shift;
8165 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8167 bool operator<(const Cost &RHS) const {
8168 // Assume cross register banks copies are as expensive as loads.
8169 // FIXME: Do we want some more target hooks?
8170 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8171 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8172 // Unless we are optimizing for code size, consider the
8173 // expensive operation first.
8174 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8175 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8176 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8177 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8180 bool operator>(const Cost &RHS) const { return RHS < *this; }
8182 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8184 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8186 // The last instruction that represent the slice. This should be a
8187 // truncate instruction.
8189 // The original load instruction.
8191 // The right shift amount in bits from the original load.
8193 // The DAG from which Origin came from.
8194 // This is used to get some contextual information about legal types, etc.
8197 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8198 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8199 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8201 LoadedSlice(const LoadedSlice &LS)
8202 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8204 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8205 /// \return Result is \p BitWidth and has used bits set to 1 and
8206 /// not used bits set to 0.
8207 APInt getUsedBits() const {
8208 // Reproduce the trunc(lshr) sequence:
8209 // - Start from the truncated value.
8210 // - Zero extend to the desired bit width.
8212 assert(Origin && "No original load to compare against.");
8213 unsigned BitWidth = Origin->getValueSizeInBits(0);
8214 assert(Inst && "This slice is not bound to an instruction");
8215 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8216 "Extracted slice is bigger than the whole type!");
8217 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8218 UsedBits.setAllBits();
8219 UsedBits = UsedBits.zext(BitWidth);
8224 /// \brief Get the size of the slice to be loaded in bytes.
8225 unsigned getLoadedSize() const {
8226 unsigned SliceSize = getUsedBits().countPopulation();
8227 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8228 return SliceSize / 8;
8231 /// \brief Get the type that will be loaded for this slice.
8232 /// Note: This may not be the final type for the slice.
8233 EVT getLoadedType() const {
8234 assert(DAG && "Missing context");
8235 LLVMContext &Ctxt = *DAG->getContext();
8236 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8239 /// \brief Get the alignment of the load used for this slice.
8240 unsigned getAlignment() const {
8241 unsigned Alignment = Origin->getAlignment();
8242 unsigned Offset = getOffsetFromBase();
8244 Alignment = MinAlign(Alignment, Alignment + Offset);
8248 /// \brief Check if this slice can be rewritten with legal operations.
8249 bool isLegal() const {
8250 // An invalid slice is not legal.
8251 if (!Origin || !Inst || !DAG)
8254 // Offsets are for indexed load only, we do not handle that.
8255 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8258 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8260 // Check that the type is legal.
8261 EVT SliceType = getLoadedType();
8262 if (!TLI.isTypeLegal(SliceType))
8265 // Check that the load is legal for this type.
8266 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8269 // Check that the offset can be computed.
8270 // 1. Check its type.
8271 EVT PtrType = Origin->getBasePtr().getValueType();
8272 if (PtrType == MVT::Untyped || PtrType.isExtended())
8275 // 2. Check that it fits in the immediate.
8276 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8279 // 3. Check that the computation is legal.
8280 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8283 // Check that the zext is legal if it needs one.
8284 EVT TruncateType = Inst->getValueType(0);
8285 if (TruncateType != SliceType &&
8286 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8292 /// \brief Get the offset in bytes of this slice in the original chunk of
8294 /// \pre DAG != nullptr.
8295 uint64_t getOffsetFromBase() const {
8296 assert(DAG && "Missing context.");
8298 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8299 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8300 uint64_t Offset = Shift / 8;
8301 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8302 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8303 "The size of the original loaded type is not a multiple of a"
8305 // If Offset is bigger than TySizeInBytes, it means we are loading all
8306 // zeros. This should have been optimized before in the process.
8307 assert(TySizeInBytes > Offset &&
8308 "Invalid shift amount for given loaded size");
8310 Offset = TySizeInBytes - Offset - getLoadedSize();
8314 /// \brief Generate the sequence of instructions to load the slice
8315 /// represented by this object and redirect the uses of this slice to
8316 /// this new sequence of instructions.
8317 /// \pre this->Inst && this->Origin are valid Instructions and this
8318 /// object passed the legal check: LoadedSlice::isLegal returned true.
8319 /// \return The last instruction of the sequence used to load the slice.
8320 SDValue loadSlice() const {
8321 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8322 const SDValue &OldBaseAddr = Origin->getBasePtr();
8323 SDValue BaseAddr = OldBaseAddr;
8324 // Get the offset in that chunk of bytes w.r.t. the endianess.
8325 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8326 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8328 // BaseAddr = BaseAddr + Offset.
8329 EVT ArithType = BaseAddr.getValueType();
8330 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8331 DAG->getConstant(Offset, ArithType));
8334 // Create the type of the loaded slice according to its size.
8335 EVT SliceType = getLoadedType();
8337 // Create the load for the slice.
8338 SDValue LastInst = DAG->getLoad(
8339 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8340 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8341 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8342 // If the final type is not the same as the loaded type, this means that
8343 // we have to pad with zero. Create a zero extend for that.
8344 EVT FinalType = Inst->getValueType(0);
8345 if (SliceType != FinalType)
8347 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8351 /// \brief Check if this slice can be merged with an expensive cross register
8352 /// bank copy. E.g.,
8354 /// f = bitcast i32 i to float
8355 bool canMergeExpensiveCrossRegisterBankCopy() const {
8356 if (!Inst || !Inst->hasOneUse())
8358 SDNode *Use = *Inst->use_begin();
8359 if (Use->getOpcode() != ISD::BITCAST)
8361 assert(DAG && "Missing context");
8362 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8363 EVT ResVT = Use->getValueType(0);
8364 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8365 const TargetRegisterClass *ArgRC =
8366 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8367 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8370 // At this point, we know that we perform a cross-register-bank copy.
8371 // Check if it is expensive.
8372 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8373 // Assume bitcasts are cheap, unless both register classes do not
8374 // explicitly share a common sub class.
8375 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8378 // Check if it will be merged with the load.
8379 // 1. Check the alignment constraint.
8380 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8381 ResVT.getTypeForEVT(*DAG->getContext()));
8383 if (RequiredAlignment > getAlignment())
8386 // 2. Check that the load is a legal operation for that type.
8387 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8390 // 3. Check that we do not have a zext in the way.
8391 if (Inst->getValueType(0) != getLoadedType())
8399 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8400 /// \p UsedBits looks like 0..0 1..1 0..0.
8401 static bool areUsedBitsDense(const APInt &UsedBits) {
8402 // If all the bits are one, this is dense!
8403 if (UsedBits.isAllOnesValue())
8406 // Get rid of the unused bits on the right.
8407 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8408 // Get rid of the unused bits on the left.
8409 if (NarrowedUsedBits.countLeadingZeros())
8410 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8411 // Check that the chunk of bits is completely used.
8412 return NarrowedUsedBits.isAllOnesValue();
8415 /// \brief Check whether or not \p First and \p Second are next to each other
8416 /// in memory. This means that there is no hole between the bits loaded
8417 /// by \p First and the bits loaded by \p Second.
8418 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8419 const LoadedSlice &Second) {
8420 assert(First.Origin == Second.Origin && First.Origin &&
8421 "Unable to match different memory origins.");
8422 APInt UsedBits = First.getUsedBits();
8423 assert((UsedBits & Second.getUsedBits()) == 0 &&
8424 "Slices are not supposed to overlap.");
8425 UsedBits |= Second.getUsedBits();
8426 return areUsedBitsDense(UsedBits);
8429 /// \brief Adjust the \p GlobalLSCost according to the target
8430 /// paring capabilities and the layout of the slices.
8431 /// \pre \p GlobalLSCost should account for at least as many loads as
8432 /// there is in the slices in \p LoadedSlices.
8433 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8434 LoadedSlice::Cost &GlobalLSCost) {
8435 unsigned NumberOfSlices = LoadedSlices.size();
8436 // If there is less than 2 elements, no pairing is possible.
8437 if (NumberOfSlices < 2)
8440 // Sort the slices so that elements that are likely to be next to each
8441 // other in memory are next to each other in the list.
8442 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8443 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8444 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8445 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8447 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8448 // First (resp. Second) is the first (resp. Second) potentially candidate
8449 // to be placed in a paired load.
8450 const LoadedSlice *First = nullptr;
8451 const LoadedSlice *Second = nullptr;
8452 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8453 // Set the beginning of the pair.
8456 Second = &LoadedSlices[CurrSlice];
8458 // If First is NULL, it means we start a new pair.
8459 // Get to the next slice.
8463 EVT LoadedType = First->getLoadedType();
8465 // If the types of the slices are different, we cannot pair them.
8466 if (LoadedType != Second->getLoadedType())
8469 // Check if the target supplies paired loads for this type.
8470 unsigned RequiredAlignment = 0;
8471 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8472 // move to the next pair, this type is hopeless.
8476 // Check if we meet the alignment requirement.
8477 if (RequiredAlignment > First->getAlignment())
8480 // Check that both loads are next to each other in memory.
8481 if (!areSlicesNextToEachOther(*First, *Second))
8484 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8485 --GlobalLSCost.Loads;
8486 // Move to the next pair.
8491 /// \brief Check the profitability of all involved LoadedSlice.
8492 /// Currently, it is considered profitable if there is exactly two
8493 /// involved slices (1) which are (2) next to each other in memory, and
8494 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8496 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8497 /// the elements themselves.
8499 /// FIXME: When the cost model will be mature enough, we can relax
8500 /// constraints (1) and (2).
8501 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8502 const APInt &UsedBits, bool ForCodeSize) {
8503 unsigned NumberOfSlices = LoadedSlices.size();
8504 if (StressLoadSlicing)
8505 return NumberOfSlices > 1;
8508 if (NumberOfSlices != 2)
8512 if (!areUsedBitsDense(UsedBits))
8516 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8517 // The original code has one big load.
8519 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8520 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8521 // Accumulate the cost of all the slices.
8522 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8523 GlobalSlicingCost += SliceCost;
8525 // Account as cost in the original configuration the gain obtained
8526 // with the current slices.
8527 OrigCost.addSliceGain(LS);
8530 // If the target supports paired load, adjust the cost accordingly.
8531 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8532 return OrigCost > GlobalSlicingCost;
8535 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8536 /// operations, split it in the various pieces being extracted.
8538 /// This sort of thing is introduced by SROA.
8539 /// This slicing takes care not to insert overlapping loads.
8540 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8541 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8542 if (Level < AfterLegalizeDAG)
8545 LoadSDNode *LD = cast<LoadSDNode>(N);
8546 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8547 !LD->getValueType(0).isInteger())
8550 // Keep track of already used bits to detect overlapping values.
8551 // In that case, we will just abort the transformation.
8552 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8554 SmallVector<LoadedSlice, 4> LoadedSlices;
8556 // Check if this load is used as several smaller chunks of bits.
8557 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8558 // of computation for each trunc.
8559 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8560 UI != UIEnd; ++UI) {
8561 // Skip the uses of the chain.
8562 if (UI.getUse().getResNo() != 0)
8568 // Check if this is a trunc(lshr).
8569 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8570 isa<ConstantSDNode>(User->getOperand(1))) {
8571 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8572 User = *User->use_begin();
8575 // At this point, User is a Truncate, iff we encountered, trunc or
8577 if (User->getOpcode() != ISD::TRUNCATE)
8580 // The width of the type must be a power of 2 and greater than 8-bits.
8581 // Otherwise the load cannot be represented in LLVM IR.
8582 // Moreover, if we shifted with a non-8-bits multiple, the slice
8583 // will be across several bytes. We do not support that.
8584 unsigned Width = User->getValueSizeInBits(0);
8585 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8588 // Build the slice for this chain of computations.
8589 LoadedSlice LS(User, LD, Shift, &DAG);
8590 APInt CurrentUsedBits = LS.getUsedBits();
8592 // Check if this slice overlaps with another.
8593 if ((CurrentUsedBits & UsedBits) != 0)
8595 // Update the bits used globally.
8596 UsedBits |= CurrentUsedBits;
8598 // Check if the new slice would be legal.
8602 // Record the slice.
8603 LoadedSlices.push_back(LS);
8606 // Abort slicing if it does not seem to be profitable.
8607 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8612 // Rewrite each chain to use an independent load.
8613 // By construction, each chain can be represented by a unique load.
8615 // Prepare the argument for the new token factor for all the slices.
8616 SmallVector<SDValue, 8> ArgChains;
8617 for (SmallVectorImpl<LoadedSlice>::const_iterator
8618 LSIt = LoadedSlices.begin(),
8619 LSItEnd = LoadedSlices.end();
8620 LSIt != LSItEnd; ++LSIt) {
8621 SDValue SliceInst = LSIt->loadSlice();
8622 CombineTo(LSIt->Inst, SliceInst, true);
8623 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8624 SliceInst = SliceInst.getOperand(0);
8625 assert(SliceInst->getOpcode() == ISD::LOAD &&
8626 "It takes more than a zext to get to the loaded slice!!");
8627 ArgChains.push_back(SliceInst.getValue(1));
8630 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8632 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8636 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8637 /// load is having specific bytes cleared out. If so, return the byte size
8638 /// being masked out and the shift amount.
8639 static std::pair<unsigned, unsigned>
8640 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8641 std::pair<unsigned, unsigned> Result(0, 0);
8643 // Check for the structure we're looking for.
8644 if (V->getOpcode() != ISD::AND ||
8645 !isa<ConstantSDNode>(V->getOperand(1)) ||
8646 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8649 // Check the chain and pointer.
8650 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8651 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8653 // The store should be chained directly to the load or be an operand of a
8655 if (LD == Chain.getNode())
8657 else if (Chain->getOpcode() != ISD::TokenFactor)
8658 return Result; // Fail.
8661 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8662 if (Chain->getOperand(i).getNode() == LD) {
8666 if (!isOk) return Result;
8669 // This only handles simple types.
8670 if (V.getValueType() != MVT::i16 &&
8671 V.getValueType() != MVT::i32 &&
8672 V.getValueType() != MVT::i64)
8675 // Check the constant mask. Invert it so that the bits being masked out are
8676 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8677 // follow the sign bit for uniformity.
8678 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8679 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8680 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8681 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8682 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8683 if (NotMaskLZ == 64) return Result; // All zero mask.
8685 // See if we have a continuous run of bits. If so, we have 0*1+0*
8686 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8689 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8690 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8691 NotMaskLZ -= 64-V.getValueSizeInBits();
8693 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8694 switch (MaskedBytes) {
8698 default: return Result; // All one mask, or 5-byte mask.
8701 // Verify that the first bit starts at a multiple of mask so that the access
8702 // is aligned the same as the access width.
8703 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8705 Result.first = MaskedBytes;
8706 Result.second = NotMaskTZ/8;
8711 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8712 /// provides a value as specified by MaskInfo. If so, replace the specified
8713 /// store with a narrower store of truncated IVal.
8715 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8716 SDValue IVal, StoreSDNode *St,
8718 unsigned NumBytes = MaskInfo.first;
8719 unsigned ByteShift = MaskInfo.second;
8720 SelectionDAG &DAG = DC->getDAG();
8722 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8723 // that uses this. If not, this is not a replacement.
8724 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8725 ByteShift*8, (ByteShift+NumBytes)*8);
8726 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8728 // Check that it is legal on the target to do this. It is legal if the new
8729 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8731 MVT VT = MVT::getIntegerVT(NumBytes*8);
8732 if (!DC->isTypeLegal(VT))
8735 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8736 // shifted by ByteShift and truncated down to NumBytes.
8738 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8739 DAG.getConstant(ByteShift*8,
8740 DC->getShiftAmountTy(IVal.getValueType())));
8742 // Figure out the offset for the store and the alignment of the access.
8744 unsigned NewAlign = St->getAlignment();
8746 if (DAG.getTargetLoweringInfo().isLittleEndian())
8747 StOffset = ByteShift;
8749 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8751 SDValue Ptr = St->getBasePtr();
8753 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8754 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8755 NewAlign = MinAlign(NewAlign, StOffset);
8758 // Truncate down to the new size.
8759 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8762 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8763 St->getPointerInfo().getWithOffset(StOffset),
8764 false, false, NewAlign).getNode();
8768 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8769 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8770 /// of the loaded bits, try narrowing the load and store if it would end up
8771 /// being a win for performance or code size.
8772 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8773 StoreSDNode *ST = cast<StoreSDNode>(N);
8774 if (ST->isVolatile())
8777 SDValue Chain = ST->getChain();
8778 SDValue Value = ST->getValue();
8779 SDValue Ptr = ST->getBasePtr();
8780 EVT VT = Value.getValueType();
8782 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8785 unsigned Opc = Value.getOpcode();
8787 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8788 // is a byte mask indicating a consecutive number of bytes, check to see if
8789 // Y is known to provide just those bytes. If so, we try to replace the
8790 // load + replace + store sequence with a single (narrower) store, which makes
8792 if (Opc == ISD::OR) {
8793 std::pair<unsigned, unsigned> MaskedLoad;
8794 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8795 if (MaskedLoad.first)
8796 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8797 Value.getOperand(1), ST,this))
8798 return SDValue(NewST, 0);
8800 // Or is commutative, so try swapping X and Y.
8801 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8802 if (MaskedLoad.first)
8803 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8804 Value.getOperand(0), ST,this))
8805 return SDValue(NewST, 0);
8808 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8809 Value.getOperand(1).getOpcode() != ISD::Constant)
8812 SDValue N0 = Value.getOperand(0);
8813 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8814 Chain == SDValue(N0.getNode(), 1)) {
8815 LoadSDNode *LD = cast<LoadSDNode>(N0);
8816 if (LD->getBasePtr() != Ptr ||
8817 LD->getPointerInfo().getAddrSpace() !=
8818 ST->getPointerInfo().getAddrSpace())
8821 // Find the type to narrow it the load / op / store to.
8822 SDValue N1 = Value.getOperand(1);
8823 unsigned BitWidth = N1.getValueSizeInBits();
8824 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8825 if (Opc == ISD::AND)
8826 Imm ^= APInt::getAllOnesValue(BitWidth);
8827 if (Imm == 0 || Imm.isAllOnesValue())
8829 unsigned ShAmt = Imm.countTrailingZeros();
8830 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8831 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8832 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8833 while (NewBW < BitWidth &&
8834 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8835 TLI.isNarrowingProfitable(VT, NewVT))) {
8836 NewBW = NextPowerOf2(NewBW);
8837 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8839 if (NewBW >= BitWidth)
8842 // If the lsb changed does not start at the type bitwidth boundary,
8843 // start at the previous one.
8845 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8846 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8847 std::min(BitWidth, ShAmt + NewBW));
8848 if ((Imm & Mask) == Imm) {
8849 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8850 if (Opc == ISD::AND)
8851 NewImm ^= APInt::getAllOnesValue(NewBW);
8852 uint64_t PtrOff = ShAmt / 8;
8853 // For big endian targets, we need to adjust the offset to the pointer to
8854 // load the correct bytes.
8855 if (TLI.isBigEndian())
8856 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8858 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8859 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8860 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8863 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8864 Ptr.getValueType(), Ptr,
8865 DAG.getConstant(PtrOff, Ptr.getValueType()));
8866 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8867 LD->getChain(), NewPtr,
8868 LD->getPointerInfo().getWithOffset(PtrOff),
8869 LD->isVolatile(), LD->isNonTemporal(),
8870 LD->isInvariant(), NewAlign,
8872 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8873 DAG.getConstant(NewImm, NewVT));
8874 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8876 ST->getPointerInfo().getWithOffset(PtrOff),
8877 false, false, NewAlign);
8879 AddToWorklist(NewPtr.getNode());
8880 AddToWorklist(NewLD.getNode());
8881 AddToWorklist(NewVal.getNode());
8882 WorklistRemover DeadNodes(*this);
8883 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8892 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8893 /// if the load value isn't used by any other operations, then consider
8894 /// transforming the pair to integer load / store operations if the target
8895 /// deems the transformation profitable.
8896 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8897 StoreSDNode *ST = cast<StoreSDNode>(N);
8898 SDValue Chain = ST->getChain();
8899 SDValue Value = ST->getValue();
8900 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8901 Value.hasOneUse() &&
8902 Chain == SDValue(Value.getNode(), 1)) {
8903 LoadSDNode *LD = cast<LoadSDNode>(Value);
8904 EVT VT = LD->getMemoryVT();
8905 if (!VT.isFloatingPoint() ||
8906 VT != ST->getMemoryVT() ||
8907 LD->isNonTemporal() ||
8908 ST->isNonTemporal() ||
8909 LD->getPointerInfo().getAddrSpace() != 0 ||
8910 ST->getPointerInfo().getAddrSpace() != 0)
8913 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8914 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8915 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8916 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8917 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8920 unsigned LDAlign = LD->getAlignment();
8921 unsigned STAlign = ST->getAlignment();
8922 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8923 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8924 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8927 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8928 LD->getChain(), LD->getBasePtr(),
8929 LD->getPointerInfo(),
8930 false, false, false, LDAlign);
8932 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8933 NewLD, ST->getBasePtr(),
8934 ST->getPointerInfo(),
8935 false, false, STAlign);
8937 AddToWorklist(NewLD.getNode());
8938 AddToWorklist(NewST.getNode());
8939 WorklistRemover DeadNodes(*this);
8940 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8948 /// Helper struct to parse and store a memory address as base + index + offset.
8949 /// We ignore sign extensions when it is safe to do so.
8950 /// The following two expressions are not equivalent. To differentiate we need
8951 /// to store whether there was a sign extension involved in the index
8953 /// (load (i64 add (i64 copyfromreg %c)
8954 /// (i64 signextend (add (i8 load %index)
8958 /// (load (i64 add (i64 copyfromreg %c)
8959 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8961 struct BaseIndexOffset {
8965 bool IsIndexSignExt;
8967 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8969 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8970 bool IsIndexSignExt) :
8971 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8973 bool equalBaseIndex(const BaseIndexOffset &Other) {
8974 return Other.Base == Base && Other.Index == Index &&
8975 Other.IsIndexSignExt == IsIndexSignExt;
8978 /// Parses tree in Ptr for base, index, offset addresses.
8979 static BaseIndexOffset match(SDValue Ptr) {
8980 bool IsIndexSignExt = false;
8982 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8983 // instruction, then it could be just the BASE or everything else we don't
8984 // know how to handle. Just use Ptr as BASE and give up.
8985 if (Ptr->getOpcode() != ISD::ADD)
8986 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8988 // We know that we have at least an ADD instruction. Try to pattern match
8989 // the simple case of BASE + OFFSET.
8990 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8991 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8992 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8996 // Inside a loop the current BASE pointer is calculated using an ADD and a
8997 // MUL instruction. In this case Ptr is the actual BASE pointer.
8998 // (i64 add (i64 %array_ptr)
8999 // (i64 mul (i64 %induction_var)
9000 // (i64 %element_size)))
9001 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9002 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9004 // Look at Base + Index + Offset cases.
9005 SDValue Base = Ptr->getOperand(0);
9006 SDValue IndexOffset = Ptr->getOperand(1);
9008 // Skip signextends.
9009 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9010 IndexOffset = IndexOffset->getOperand(0);
9011 IsIndexSignExt = true;
9014 // Either the case of Base + Index (no offset) or something else.
9015 if (IndexOffset->getOpcode() != ISD::ADD)
9016 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9018 // Now we have the case of Base + Index + offset.
9019 SDValue Index = IndexOffset->getOperand(0);
9020 SDValue Offset = IndexOffset->getOperand(1);
9022 if (!isa<ConstantSDNode>(Offset))
9023 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9025 // Ignore signextends.
9026 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9027 Index = Index->getOperand(0);
9028 IsIndexSignExt = true;
9029 } else IsIndexSignExt = false;
9031 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9032 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9036 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9037 /// is located in a sequence of memory operations connected by a chain.
9039 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9040 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9041 // Ptr to the mem node.
9042 LSBaseSDNode *MemNode;
9043 // Offset from the base ptr.
9044 int64_t OffsetFromBase;
9045 // What is the sequence number of this mem node.
9046 // Lowest mem operand in the DAG starts at zero.
9047 unsigned SequenceNum;
9050 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9051 EVT MemVT = St->getMemoryVT();
9052 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9053 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9054 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9056 // Don't merge vectors into wider inputs.
9057 if (MemVT.isVector() || !MemVT.isSimple())
9060 // Perform an early exit check. Do not bother looking at stored values that
9061 // are not constants or loads.
9062 SDValue StoredVal = St->getValue();
9063 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9064 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9068 // Only look at ends of store sequences.
9069 SDValue Chain = SDValue(St, 1);
9070 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9073 // This holds the base pointer, index, and the offset in bytes from the base
9075 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9077 // We must have a base and an offset.
9078 if (!BasePtr.Base.getNode())
9081 // Do not handle stores to undef base pointers.
9082 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9085 // Save the LoadSDNodes that we find in the chain.
9086 // We need to make sure that these nodes do not interfere with
9087 // any of the store nodes.
9088 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9090 // Save the StoreSDNodes that we find in the chain.
9091 SmallVector<MemOpLink, 8> StoreNodes;
9093 // Walk up the chain and look for nodes with offsets from the same
9094 // base pointer. Stop when reaching an instruction with a different kind
9095 // or instruction which has a different base pointer.
9097 StoreSDNode *Index = St;
9099 // If the chain has more than one use, then we can't reorder the mem ops.
9100 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9103 // Find the base pointer and offset for this memory node.
9104 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9106 // Check that the base pointer is the same as the original one.
9107 if (!Ptr.equalBaseIndex(BasePtr))
9110 // Check that the alignment is the same.
9111 if (Index->getAlignment() != St->getAlignment())
9114 // The memory operands must not be volatile.
9115 if (Index->isVolatile() || Index->isIndexed())
9119 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9120 if (St->isTruncatingStore())
9123 // The stored memory type must be the same.
9124 if (Index->getMemoryVT() != MemVT)
9127 // We do not allow unaligned stores because we want to prevent overriding
9129 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9132 // We found a potential memory operand to merge.
9133 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9135 // Find the next memory operand in the chain. If the next operand in the
9136 // chain is a store then move up and continue the scan with the next
9137 // memory operand. If the next operand is a load save it and use alias
9138 // information to check if it interferes with anything.
9139 SDNode *NextInChain = Index->getChain().getNode();
9141 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9142 // We found a store node. Use it for the next iteration.
9145 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9146 if (Ldn->isVolatile()) {
9151 // Save the load node for later. Continue the scan.
9152 AliasLoadNodes.push_back(Ldn);
9153 NextInChain = Ldn->getChain().getNode();
9162 // Check if there is anything to merge.
9163 if (StoreNodes.size() < 2)
9166 // Sort the memory operands according to their distance from the base pointer.
9167 std::sort(StoreNodes.begin(), StoreNodes.end(),
9168 [](MemOpLink LHS, MemOpLink RHS) {
9169 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9170 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9171 LHS.SequenceNum > RHS.SequenceNum);
9174 // Scan the memory operations on the chain and find the first non-consecutive
9175 // store memory address.
9176 unsigned LastConsecutiveStore = 0;
9177 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9178 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9180 // Check that the addresses are consecutive starting from the second
9181 // element in the list of stores.
9183 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9184 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9189 // Check if this store interferes with any of the loads that we found.
9190 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9191 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9195 // We found a load that alias with this store. Stop the sequence.
9199 // Mark this node as useful.
9200 LastConsecutiveStore = i;
9203 // The node with the lowest store address.
9204 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9206 // Store the constants into memory as one consecutive store.
9208 unsigned LastLegalType = 0;
9209 unsigned LastLegalVectorType = 0;
9210 bool NonZero = false;
9211 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9212 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9213 SDValue StoredVal = St->getValue();
9215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9216 NonZero |= !C->isNullValue();
9217 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9218 NonZero |= !C->getConstantFPValue()->isNullValue();
9224 // Find a legal type for the constant store.
9225 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9226 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9227 if (TLI.isTypeLegal(StoreTy))
9228 LastLegalType = i+1;
9229 // Or check whether a truncstore is legal.
9230 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9231 TargetLowering::TypePromoteInteger) {
9232 EVT LegalizedStoredValueTy =
9233 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9234 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9235 LastLegalType = i+1;
9238 // Find a legal type for the vector store.
9239 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9240 if (TLI.isTypeLegal(Ty))
9241 LastLegalVectorType = i + 1;
9244 // We only use vectors if the constant is known to be zero and the
9245 // function is not marked with the noimplicitfloat attribute.
9246 if (NonZero || NoVectors)
9247 LastLegalVectorType = 0;
9249 // Check if we found a legal integer type to store.
9250 if (LastLegalType == 0 && LastLegalVectorType == 0)
9253 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9254 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9256 // Make sure we have something to merge.
9260 unsigned EarliestNodeUsed = 0;
9261 for (unsigned i=0; i < NumElem; ++i) {
9262 // Find a chain for the new wide-store operand. Notice that some
9263 // of the store nodes that we found may not be selected for inclusion
9264 // in the wide store. The chain we use needs to be the chain of the
9265 // earliest store node which is *used* and replaced by the wide store.
9266 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9267 EarliestNodeUsed = i;
9270 // The earliest Node in the DAG.
9271 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9272 SDLoc DL(StoreNodes[0].MemNode);
9276 // Find a legal type for the vector store.
9277 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9278 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9279 StoredVal = DAG.getConstant(0, Ty);
9281 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9282 APInt StoreInt(StoreBW, 0);
9284 // Construct a single integer constant which is made of the smaller
9286 bool IsLE = TLI.isLittleEndian();
9287 for (unsigned i = 0; i < NumElem ; ++i) {
9288 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9289 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9290 SDValue Val = St->getValue();
9291 StoreInt<<=ElementSizeBytes*8;
9292 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9293 StoreInt|=C->getAPIntValue().zext(StoreBW);
9294 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9295 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9297 assert(false && "Invalid constant element type");
9301 // Create the new Load and Store operations.
9302 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9303 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9306 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9307 FirstInChain->getBasePtr(),
9308 FirstInChain->getPointerInfo(),
9310 FirstInChain->getAlignment());
9312 // Replace the first store with the new store
9313 CombineTo(EarliestOp, NewStore);
9314 // Erase all other stores.
9315 for (unsigned i = 0; i < NumElem ; ++i) {
9316 if (StoreNodes[i].MemNode == EarliestOp)
9318 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9319 // ReplaceAllUsesWith will replace all uses that existed when it was
9320 // called, but graph optimizations may cause new ones to appear. For
9321 // example, the case in pr14333 looks like
9323 // St's chain -> St -> another store -> X
9325 // And the only difference from St to the other store is the chain.
9326 // When we change it's chain to be St's chain they become identical,
9327 // get CSEed and the net result is that X is now a use of St.
9328 // Since we know that St is redundant, just iterate.
9329 while (!St->use_empty())
9330 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9331 removeFromWorklist(St);
9338 // Below we handle the case of multiple consecutive stores that
9339 // come from multiple consecutive loads. We merge them into a single
9340 // wide load and a single wide store.
9342 // Look for load nodes which are used by the stored values.
9343 SmallVector<MemOpLink, 8> LoadNodes;
9345 // Find acceptable loads. Loads need to have the same chain (token factor),
9346 // must not be zext, volatile, indexed, and they must be consecutive.
9347 BaseIndexOffset LdBasePtr;
9348 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9349 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9350 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9353 // Loads must only have one use.
9354 if (!Ld->hasNUsesOfValue(1, 0))
9357 // Check that the alignment is the same as the stores.
9358 if (Ld->getAlignment() != St->getAlignment())
9361 // The memory operands must not be volatile.
9362 if (Ld->isVolatile() || Ld->isIndexed())
9365 // We do not accept ext loads.
9366 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9369 // The stored memory type must be the same.
9370 if (Ld->getMemoryVT() != MemVT)
9373 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9374 // If this is not the first ptr that we check.
9375 if (LdBasePtr.Base.getNode()) {
9376 // The base ptr must be the same.
9377 if (!LdPtr.equalBaseIndex(LdBasePtr))
9380 // Check that all other base pointers are the same as this one.
9384 // We found a potential memory operand to merge.
9385 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9388 if (LoadNodes.size() < 2)
9391 // Scan the memory operations on the chain and find the first non-consecutive
9392 // load memory address. These variables hold the index in the store node
9394 unsigned LastConsecutiveLoad = 0;
9395 // This variable refers to the size and not index in the array.
9396 unsigned LastLegalVectorType = 0;
9397 unsigned LastLegalIntegerType = 0;
9398 StartAddress = LoadNodes[0].OffsetFromBase;
9399 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9400 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9401 // All loads much share the same chain.
9402 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9405 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9406 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9408 LastConsecutiveLoad = i;
9410 // Find a legal type for the vector store.
9411 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9412 if (TLI.isTypeLegal(StoreTy))
9413 LastLegalVectorType = i + 1;
9415 // Find a legal type for the integer store.
9416 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9417 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9418 if (TLI.isTypeLegal(StoreTy))
9419 LastLegalIntegerType = i + 1;
9420 // Or check whether a truncstore and extload is legal.
9421 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9422 TargetLowering::TypePromoteInteger) {
9423 EVT LegalizedStoredValueTy =
9424 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9425 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9426 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9427 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9428 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9429 LastLegalIntegerType = i+1;
9433 // Only use vector types if the vector type is larger than the integer type.
9434 // If they are the same, use integers.
9435 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9436 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9438 // We add +1 here because the LastXXX variables refer to location while
9439 // the NumElem refers to array/index size.
9440 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9441 NumElem = std::min(LastLegalType, NumElem);
9446 // The earliest Node in the DAG.
9447 unsigned EarliestNodeUsed = 0;
9448 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9449 for (unsigned i=1; i<NumElem; ++i) {
9450 // Find a chain for the new wide-store operand. Notice that some
9451 // of the store nodes that we found may not be selected for inclusion
9452 // in the wide store. The chain we use needs to be the chain of the
9453 // earliest store node which is *used* and replaced by the wide store.
9454 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9455 EarliestNodeUsed = i;
9458 // Find if it is better to use vectors or integers to load and store
9462 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9464 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9465 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9468 SDLoc LoadDL(LoadNodes[0].MemNode);
9469 SDLoc StoreDL(StoreNodes[0].MemNode);
9471 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9472 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9473 FirstLoad->getChain(),
9474 FirstLoad->getBasePtr(),
9475 FirstLoad->getPointerInfo(),
9476 false, false, false,
9477 FirstLoad->getAlignment());
9479 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9480 FirstInChain->getBasePtr(),
9481 FirstInChain->getPointerInfo(), false, false,
9482 FirstInChain->getAlignment());
9484 // Replace one of the loads with the new load.
9485 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9486 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9487 SDValue(NewLoad.getNode(), 1));
9489 // Remove the rest of the load chains.
9490 for (unsigned i = 1; i < NumElem ; ++i) {
9491 // Replace all chain users of the old load nodes with the chain of the new
9493 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9494 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9497 // Replace the first store with the new store.
9498 CombineTo(EarliestOp, NewStore);
9499 // Erase all other stores.
9500 for (unsigned i = 0; i < NumElem ; ++i) {
9501 // Remove all Store nodes.
9502 if (StoreNodes[i].MemNode == EarliestOp)
9504 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9505 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9506 removeFromWorklist(St);
9513 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9514 StoreSDNode *ST = cast<StoreSDNode>(N);
9515 SDValue Chain = ST->getChain();
9516 SDValue Value = ST->getValue();
9517 SDValue Ptr = ST->getBasePtr();
9519 // If this is a store of a bit convert, store the input value if the
9520 // resultant store does not need a higher alignment than the original.
9521 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9522 ST->isUnindexed()) {
9523 unsigned OrigAlign = ST->getAlignment();
9524 EVT SVT = Value.getOperand(0).getValueType();
9525 unsigned Align = TLI.getDataLayout()->
9526 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9527 if (Align <= OrigAlign &&
9528 ((!LegalOperations && !ST->isVolatile()) ||
9529 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9530 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9531 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9532 ST->isNonTemporal(), OrigAlign,
9536 // Turn 'store undef, Ptr' -> nothing.
9537 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9540 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9541 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9542 // NOTE: If the original store is volatile, this transform must not increase
9543 // the number of stores. For example, on x86-32 an f64 can be stored in one
9544 // processor operation but an i64 (which is not legal) requires two. So the
9545 // transform should not be done in this case.
9546 if (Value.getOpcode() != ISD::TargetConstantFP) {
9548 switch (CFP->getSimpleValueType(0).SimpleTy) {
9549 default: llvm_unreachable("Unknown FP type");
9550 case MVT::f16: // We don't do this for these yet.
9556 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9557 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9558 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9559 bitcastToAPInt().getZExtValue(), MVT::i32);
9560 return DAG.getStore(Chain, SDLoc(N), Tmp,
9561 Ptr, ST->getMemOperand());
9565 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9566 !ST->isVolatile()) ||
9567 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9568 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9569 getZExtValue(), MVT::i64);
9570 return DAG.getStore(Chain, SDLoc(N), Tmp,
9571 Ptr, ST->getMemOperand());
9574 if (!ST->isVolatile() &&
9575 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9576 // Many FP stores are not made apparent until after legalize, e.g. for
9577 // argument passing. Since this is so common, custom legalize the
9578 // 64-bit integer store into two 32-bit stores.
9579 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9580 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9581 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9582 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9584 unsigned Alignment = ST->getAlignment();
9585 bool isVolatile = ST->isVolatile();
9586 bool isNonTemporal = ST->isNonTemporal();
9587 const MDNode *TBAAInfo = ST->getTBAAInfo();
9589 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9590 Ptr, ST->getPointerInfo(),
9591 isVolatile, isNonTemporal,
9592 ST->getAlignment(), TBAAInfo);
9593 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9594 DAG.getConstant(4, Ptr.getValueType()));
9595 Alignment = MinAlign(Alignment, 4U);
9596 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9597 Ptr, ST->getPointerInfo().getWithOffset(4),
9598 isVolatile, isNonTemporal,
9599 Alignment, TBAAInfo);
9600 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9609 // Try to infer better alignment information than the store already has.
9610 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9611 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9612 if (Align > ST->getAlignment())
9613 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9614 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9615 ST->isVolatile(), ST->isNonTemporal(), Align,
9620 // Try transforming a pair floating point load / store ops to integer
9621 // load / store ops.
9622 SDValue NewST = TransformFPLoadStorePair(N);
9623 if (NewST.getNode())
9626 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9627 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9629 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9630 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9633 if (UseAA && ST->isUnindexed()) {
9634 // Walk up chain skipping non-aliasing memory nodes.
9635 SDValue BetterChain = FindBetterChain(N, Chain);
9637 // If there is a better chain.
9638 if (Chain != BetterChain) {
9641 // Replace the chain to avoid dependency.
9642 if (ST->isTruncatingStore()) {
9643 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9644 ST->getMemoryVT(), ST->getMemOperand());
9646 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9647 ST->getMemOperand());
9650 // Create token to keep both nodes around.
9651 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9652 MVT::Other, Chain, ReplStore);
9654 // Make sure the new and old chains are cleaned up.
9655 AddToWorklist(Token.getNode());
9657 // Don't add users to work list.
9658 return CombineTo(N, Token, false);
9662 // Try transforming N to an indexed store.
9663 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9664 return SDValue(N, 0);
9666 // FIXME: is there such a thing as a truncating indexed store?
9667 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9668 Value.getValueType().isInteger()) {
9669 // See if we can simplify the input to this truncstore with knowledge that
9670 // only the low bits are being used. For example:
9671 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9673 GetDemandedBits(Value,
9674 APInt::getLowBitsSet(
9675 Value.getValueType().getScalarType().getSizeInBits(),
9676 ST->getMemoryVT().getScalarType().getSizeInBits()));
9677 AddToWorklist(Value.getNode());
9678 if (Shorter.getNode())
9679 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9680 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9682 // Otherwise, see if we can simplify the operation with
9683 // SimplifyDemandedBits, which only works if the value has a single use.
9684 if (SimplifyDemandedBits(Value,
9685 APInt::getLowBitsSet(
9686 Value.getValueType().getScalarType().getSizeInBits(),
9687 ST->getMemoryVT().getScalarType().getSizeInBits())))
9688 return SDValue(N, 0);
9691 // If this is a load followed by a store to the same location, then the store
9693 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9694 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9695 ST->isUnindexed() && !ST->isVolatile() &&
9696 // There can't be any side effects between the load and store, such as
9698 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9699 // The store is dead, remove it.
9704 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9705 // truncating store. We can do this even if this is already a truncstore.
9706 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9707 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9708 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9709 ST->getMemoryVT())) {
9710 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9711 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9714 // Only perform this optimization before the types are legal, because we
9715 // don't want to perform this optimization on every DAGCombine invocation.
9717 bool EverChanged = false;
9720 // There can be multiple store sequences on the same chain.
9721 // Keep trying to merge store sequences until we are unable to do so
9722 // or until we merge the last store on the chain.
9723 bool Changed = MergeConsecutiveStores(ST);
9724 EverChanged |= Changed;
9725 if (!Changed) break;
9726 } while (ST->getOpcode() != ISD::DELETED_NODE);
9729 return SDValue(N, 0);
9732 return ReduceLoadOpStoreWidth(N);
9735 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9736 SDValue InVec = N->getOperand(0);
9737 SDValue InVal = N->getOperand(1);
9738 SDValue EltNo = N->getOperand(2);
9741 // If the inserted element is an UNDEF, just use the input vector.
9742 if (InVal.getOpcode() == ISD::UNDEF)
9745 EVT VT = InVec.getValueType();
9747 // If we can't generate a legal BUILD_VECTOR, exit
9748 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9751 // Check that we know which element is being inserted
9752 if (!isa<ConstantSDNode>(EltNo))
9754 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9756 // Canonicalize insert_vector_elt dag nodes.
9758 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9759 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9761 // Do this only if the child insert_vector node has one use; also
9762 // do this only if indices are both constants and Idx1 < Idx0.
9763 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9764 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9766 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9767 if (Elt < OtherElt) {
9769 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9770 InVec.getOperand(0), InVal, EltNo);
9771 AddToWorklist(NewOp.getNode());
9772 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9773 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9777 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9778 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9780 SmallVector<SDValue, 8> Ops;
9781 // Do not combine these two vectors if the output vector will not replace
9782 // the input vector.
9783 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9784 Ops.append(InVec.getNode()->op_begin(),
9785 InVec.getNode()->op_end());
9786 } else if (InVec.getOpcode() == ISD::UNDEF) {
9787 unsigned NElts = VT.getVectorNumElements();
9788 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9793 // Insert the element
9794 if (Elt < Ops.size()) {
9795 // All the operands of BUILD_VECTOR must have the same type;
9796 // we enforce that here.
9797 EVT OpVT = Ops[0].getValueType();
9798 if (InVal.getValueType() != OpVT)
9799 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9800 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9801 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9805 // Return the new vector
9806 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9809 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9810 // (vextract (scalar_to_vector val, 0) -> val
9811 SDValue InVec = N->getOperand(0);
9812 EVT VT = InVec.getValueType();
9813 EVT NVT = N->getValueType(0);
9815 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9816 // Check if the result type doesn't match the inserted element type. A
9817 // SCALAR_TO_VECTOR may truncate the inserted element and the
9818 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9819 SDValue InOp = InVec.getOperand(0);
9820 if (InOp.getValueType() != NVT) {
9821 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9822 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9827 SDValue EltNo = N->getOperand(1);
9828 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9830 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9831 // We only perform this optimization before the op legalization phase because
9832 // we may introduce new vector instructions which are not backed by TD
9833 // patterns. For example on AVX, extracting elements from a wide vector
9834 // without using extract_subvector. However, if we can find an underlying
9835 // scalar value, then we can always use that.
9836 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9838 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9839 int NumElem = VT.getVectorNumElements();
9840 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9841 // Find the new index to extract from.
9842 int OrigElt = SVOp->getMaskElt(Elt);
9844 // Extracting an undef index is undef.
9846 return DAG.getUNDEF(NVT);
9848 // Select the right vector half to extract from.
9850 if (OrigElt < NumElem) {
9851 SVInVec = InVec->getOperand(0);
9853 SVInVec = InVec->getOperand(1);
9857 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9858 SDValue InOp = SVInVec.getOperand(OrigElt);
9859 if (InOp.getValueType() != NVT) {
9860 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9861 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9867 // FIXME: We should handle recursing on other vector shuffles and
9868 // scalar_to_vector here as well.
9870 if (!LegalOperations) {
9871 EVT IndexTy = TLI.getVectorIdxTy();
9872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9873 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9877 // Perform only after legalization to ensure build_vector / vector_shuffle
9878 // optimizations have already been done.
9879 if (!LegalOperations) return SDValue();
9881 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9882 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9883 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9886 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9887 bool NewLoad = false;
9888 bool BCNumEltsChanged = false;
9889 EVT ExtVT = VT.getVectorElementType();
9892 // If the result of load has to be truncated, then it's not necessarily
9894 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9897 if (InVec.getOpcode() == ISD::BITCAST) {
9898 // Don't duplicate a load with other uses.
9899 if (!InVec.hasOneUse())
9902 EVT BCVT = InVec.getOperand(0).getValueType();
9903 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9905 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9906 BCNumEltsChanged = true;
9907 InVec = InVec.getOperand(0);
9908 ExtVT = BCVT.getVectorElementType();
9912 LoadSDNode *LN0 = nullptr;
9913 const ShuffleVectorSDNode *SVN = nullptr;
9914 if (ISD::isNormalLoad(InVec.getNode())) {
9915 LN0 = cast<LoadSDNode>(InVec);
9916 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9917 InVec.getOperand(0).getValueType() == ExtVT &&
9918 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9919 // Don't duplicate a load with other uses.
9920 if (!InVec.hasOneUse())
9923 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9924 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9925 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9927 // (load $addr+1*size)
9929 // Don't duplicate a load with other uses.
9930 if (!InVec.hasOneUse())
9933 // If the bit convert changed the number of elements, it is unsafe
9934 // to examine the mask.
9935 if (BCNumEltsChanged)
9938 // Select the input vector, guarding against out of range extract vector.
9939 unsigned NumElems = VT.getVectorNumElements();
9940 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9941 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9943 if (InVec.getOpcode() == ISD::BITCAST) {
9944 // Don't duplicate a load with other uses.
9945 if (!InVec.hasOneUse())
9948 InVec = InVec.getOperand(0);
9950 if (ISD::isNormalLoad(InVec.getNode())) {
9951 LN0 = cast<LoadSDNode>(InVec);
9952 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9956 // Make sure we found a non-volatile load and the extractelement is
9958 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9961 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9963 return DAG.getUNDEF(LVT);
9965 unsigned Align = LN0->getAlignment();
9967 // Check the resultant load doesn't need a higher alignment than the
9971 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9973 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9979 SDValue NewPtr = LN0->getBasePtr();
9980 unsigned PtrOff = 0;
9983 PtrOff = LVT.getSizeInBits() * Elt / 8;
9984 EVT PtrType = NewPtr.getValueType();
9985 if (TLI.isBigEndian())
9986 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9987 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9988 DAG.getConstant(PtrOff, PtrType));
9991 // The replacement we need to do here is a little tricky: we need to
9992 // replace an extractelement of a load with a load.
9993 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9994 // Note that this replacement assumes that the extractvalue is the only
9995 // use of the load; that's okay because we don't want to perform this
9996 // transformation in other cases anyway.
9999 if (NVT.bitsGT(LVT)) {
10000 // If the result type of vextract is wider than the load, then issue an
10001 // extending load instead.
10002 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10003 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10004 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10005 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10006 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10007 Align, LN0->getTBAAInfo());
10008 Chain = Load.getValue(1);
10010 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10011 LN0->getPointerInfo().getWithOffset(PtrOff),
10012 LN0->isVolatile(), LN0->isNonTemporal(),
10013 LN0->isInvariant(), Align, LN0->getTBAAInfo());
10014 Chain = Load.getValue(1);
10015 if (NVT.bitsLT(LVT))
10016 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10018 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10020 WorklistRemover DeadNodes(*this);
10021 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10022 SDValue To[] = { Load, Chain };
10023 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10024 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10025 // worklist explicitly as well.
10026 AddToWorklist(Load.getNode());
10027 AddUsersToWorklist(Load.getNode()); // Add users too
10028 // Make sure to revisit this node to clean it up; it will usually be dead.
10030 return SDValue(N, 0);
10036 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10037 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10038 // We perform this optimization post type-legalization because
10039 // the type-legalizer often scalarizes integer-promoted vectors.
10040 // Performing this optimization before may create bit-casts which
10041 // will be type-legalized to complex code sequences.
10042 // We perform this optimization only before the operation legalizer because we
10043 // may introduce illegal operations.
10044 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10047 unsigned NumInScalars = N->getNumOperands();
10049 EVT VT = N->getValueType(0);
10051 // Check to see if this is a BUILD_VECTOR of a bunch of values
10052 // which come from any_extend or zero_extend nodes. If so, we can create
10053 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10054 // optimizations. We do not handle sign-extend because we can't fill the sign
10056 EVT SourceType = MVT::Other;
10057 bool AllAnyExt = true;
10059 for (unsigned i = 0; i != NumInScalars; ++i) {
10060 SDValue In = N->getOperand(i);
10061 // Ignore undef inputs.
10062 if (In.getOpcode() == ISD::UNDEF) continue;
10064 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10065 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10067 // Abort if the element is not an extension.
10068 if (!ZeroExt && !AnyExt) {
10069 SourceType = MVT::Other;
10073 // The input is a ZeroExt or AnyExt. Check the original type.
10074 EVT InTy = In.getOperand(0).getValueType();
10076 // Check that all of the widened source types are the same.
10077 if (SourceType == MVT::Other)
10080 else if (InTy != SourceType) {
10081 // Multiple income types. Abort.
10082 SourceType = MVT::Other;
10086 // Check if all of the extends are ANY_EXTENDs.
10087 AllAnyExt &= AnyExt;
10090 // In order to have valid types, all of the inputs must be extended from the
10091 // same source type and all of the inputs must be any or zero extend.
10092 // Scalar sizes must be a power of two.
10093 EVT OutScalarTy = VT.getScalarType();
10094 bool ValidTypes = SourceType != MVT::Other &&
10095 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10096 isPowerOf2_32(SourceType.getSizeInBits());
10098 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10099 // turn into a single shuffle instruction.
10103 bool isLE = TLI.isLittleEndian();
10104 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10105 assert(ElemRatio > 1 && "Invalid element size ratio");
10106 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10107 DAG.getConstant(0, SourceType);
10109 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10110 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10112 // Populate the new build_vector
10113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10114 SDValue Cast = N->getOperand(i);
10115 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10116 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10117 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10119 if (Cast.getOpcode() == ISD::UNDEF)
10120 In = DAG.getUNDEF(SourceType);
10122 In = Cast->getOperand(0);
10123 unsigned Index = isLE ? (i * ElemRatio) :
10124 (i * ElemRatio + (ElemRatio - 1));
10126 assert(Index < Ops.size() && "Invalid index");
10130 // The type of the new BUILD_VECTOR node.
10131 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10132 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10133 "Invalid vector size");
10134 // Check if the new vector type is legal.
10135 if (!isTypeLegal(VecVT)) return SDValue();
10137 // Make the new BUILD_VECTOR.
10138 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10140 // The new BUILD_VECTOR node has the potential to be further optimized.
10141 AddToWorklist(BV.getNode());
10142 // Bitcast to the desired type.
10143 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10146 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10147 EVT VT = N->getValueType(0);
10149 unsigned NumInScalars = N->getNumOperands();
10152 EVT SrcVT = MVT::Other;
10153 unsigned Opcode = ISD::DELETED_NODE;
10154 unsigned NumDefs = 0;
10156 for (unsigned i = 0; i != NumInScalars; ++i) {
10157 SDValue In = N->getOperand(i);
10158 unsigned Opc = In.getOpcode();
10160 if (Opc == ISD::UNDEF)
10163 // If all scalar values are floats and converted from integers.
10164 if (Opcode == ISD::DELETED_NODE &&
10165 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10172 EVT InVT = In.getOperand(0).getValueType();
10174 // If all scalar values are typed differently, bail out. It's chosen to
10175 // simplify BUILD_VECTOR of integer types.
10176 if (SrcVT == MVT::Other)
10183 // If the vector has just one element defined, it's not worth to fold it into
10184 // a vectorized one.
10188 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10189 && "Should only handle conversion from integer to float.");
10190 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10192 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10194 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10197 SmallVector<SDValue, 8> Opnds;
10198 for (unsigned i = 0; i != NumInScalars; ++i) {
10199 SDValue In = N->getOperand(i);
10201 if (In.getOpcode() == ISD::UNDEF)
10202 Opnds.push_back(DAG.getUNDEF(SrcVT));
10204 Opnds.push_back(In.getOperand(0));
10206 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10207 AddToWorklist(BV.getNode());
10209 return DAG.getNode(Opcode, dl, VT, BV);
10212 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10213 unsigned NumInScalars = N->getNumOperands();
10215 EVT VT = N->getValueType(0);
10217 // A vector built entirely of undefs is undef.
10218 if (ISD::allOperandsUndef(N))
10219 return DAG.getUNDEF(VT);
10221 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10225 V = reduceBuildVecConvertToConvertBuildVec(N);
10229 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10230 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10231 // at most two distinct vectors, turn this into a shuffle node.
10233 // May only combine to shuffle after legalize if shuffle is legal.
10234 if (LegalOperations &&
10235 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10238 SDValue VecIn1, VecIn2;
10239 for (unsigned i = 0; i != NumInScalars; ++i) {
10240 // Ignore undef inputs.
10241 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10243 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10244 // constant index, bail out.
10245 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10246 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10247 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10251 // We allow up to two distinct input vectors.
10252 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10253 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10256 if (!VecIn1.getNode()) {
10257 VecIn1 = ExtractedFromVec;
10258 } else if (!VecIn2.getNode()) {
10259 VecIn2 = ExtractedFromVec;
10261 // Too many inputs.
10262 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10267 // If everything is good, we can make a shuffle operation.
10268 if (VecIn1.getNode()) {
10269 SmallVector<int, 8> Mask;
10270 for (unsigned i = 0; i != NumInScalars; ++i) {
10271 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10272 Mask.push_back(-1);
10276 // If extracting from the first vector, just use the index directly.
10277 SDValue Extract = N->getOperand(i);
10278 SDValue ExtVal = Extract.getOperand(1);
10279 if (Extract.getOperand(0) == VecIn1) {
10280 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10281 if (ExtIndex > VT.getVectorNumElements())
10284 Mask.push_back(ExtIndex);
10288 // Otherwise, use InIdx + VecSize
10289 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10290 Mask.push_back(Idx+NumInScalars);
10293 // We can't generate a shuffle node with mismatched input and output types.
10294 // Attempt to transform a single input vector to the correct type.
10295 if ((VT != VecIn1.getValueType())) {
10296 // We don't support shuffeling between TWO values of different types.
10297 if (VecIn2.getNode())
10300 // We only support widening of vectors which are half the size of the
10301 // output registers. For example XMM->YMM widening on X86 with AVX.
10302 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10305 // If the input vector type has a different base type to the output
10306 // vector type, bail out.
10307 if (VecIn1.getValueType().getVectorElementType() !=
10308 VT.getVectorElementType())
10311 // Widen the input vector by adding undef values.
10312 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10313 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10316 // If VecIn2 is unused then change it to undef.
10317 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10319 // Check that we were able to transform all incoming values to the same
10321 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10322 VecIn1.getValueType() != VT)
10325 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10326 if (!isTypeLegal(VT))
10329 // Return the new VECTOR_SHUFFLE node.
10333 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10339 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10340 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10341 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10342 // inputs come from at most two distinct vectors, turn this into a shuffle
10345 // If we only have one input vector, we don't need to do any concatenation.
10346 if (N->getNumOperands() == 1)
10347 return N->getOperand(0);
10349 // Check if all of the operands are undefs.
10350 EVT VT = N->getValueType(0);
10351 if (ISD::allOperandsUndef(N))
10352 return DAG.getUNDEF(VT);
10354 // Optimize concat_vectors where one of the vectors is undef.
10355 if (N->getNumOperands() == 2 &&
10356 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10357 SDValue In = N->getOperand(0);
10358 assert(In.getValueType().isVector() && "Must concat vectors");
10360 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10361 if (In->getOpcode() == ISD::BITCAST &&
10362 !In->getOperand(0)->getValueType(0).isVector()) {
10363 SDValue Scalar = In->getOperand(0);
10364 EVT SclTy = Scalar->getValueType(0);
10366 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10369 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10370 VT.getSizeInBits() / SclTy.getSizeInBits());
10371 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10374 SDLoc dl = SDLoc(N);
10375 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10376 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10380 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10381 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10382 if (N->getNumOperands() == 2 &&
10383 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10384 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10385 EVT VT = N->getValueType(0);
10386 SDValue N0 = N->getOperand(0);
10387 SDValue N1 = N->getOperand(1);
10388 SmallVector<SDValue, 8> Opnds;
10389 unsigned BuildVecNumElts = N0.getNumOperands();
10391 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10392 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10393 if (SclTy0.isFloatingPoint()) {
10394 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10395 Opnds.push_back(N0.getOperand(i));
10396 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10397 Opnds.push_back(N1.getOperand(i));
10399 // If BUILD_VECTOR are from built from integer, they may have different
10400 // operand types. Get the smaller type and truncate all operands to it.
10401 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10402 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10403 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10404 N0.getOperand(i)));
10405 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10406 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10407 N1.getOperand(i)));
10410 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10413 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10414 // nodes often generate nop CONCAT_VECTOR nodes.
10415 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10416 // place the incoming vectors at the exact same location.
10417 SDValue SingleSource = SDValue();
10418 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10420 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10421 SDValue Op = N->getOperand(i);
10423 if (Op.getOpcode() == ISD::UNDEF)
10426 // Check if this is the identity extract:
10427 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10430 // Find the single incoming vector for the extract_subvector.
10431 if (SingleSource.getNode()) {
10432 if (Op.getOperand(0) != SingleSource)
10435 SingleSource = Op.getOperand(0);
10437 // Check the source type is the same as the type of the result.
10438 // If not, this concat may extend the vector, so we can not
10439 // optimize it away.
10440 if (SingleSource.getValueType() != N->getValueType(0))
10444 unsigned IdentityIndex = i * PartNumElem;
10445 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10446 // The extract index must be constant.
10450 // Check that we are reading from the identity index.
10451 if (CS->getZExtValue() != IdentityIndex)
10455 if (SingleSource.getNode())
10456 return SingleSource;
10461 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10462 EVT NVT = N->getValueType(0);
10463 SDValue V = N->getOperand(0);
10465 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10467 // (extract_subvec (concat V1, V2, ...), i)
10470 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10472 if (V->getOperand(0).getValueType() != NVT)
10474 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10475 unsigned NumElems = NVT.getVectorNumElements();
10476 assert((Idx % NumElems) == 0 &&
10477 "IDX in concat is not a multiple of the result vector length.");
10478 return V->getOperand(Idx / NumElems);
10482 if (V->getOpcode() == ISD::BITCAST)
10483 V = V.getOperand(0);
10485 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10487 // Handle only simple case where vector being inserted and vector
10488 // being extracted are of same type, and are half size of larger vectors.
10489 EVT BigVT = V->getOperand(0).getValueType();
10490 EVT SmallVT = V->getOperand(1).getValueType();
10491 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10494 // Only handle cases where both indexes are constants with the same type.
10495 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10496 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10498 if (InsIdx && ExtIdx &&
10499 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10500 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10502 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10504 // indices are equal or bit offsets are equal => V1
10505 // otherwise => (extract_subvec V1, ExtIdx)
10506 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10507 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10508 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10509 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10510 DAG.getNode(ISD::BITCAST, dl,
10511 N->getOperand(0).getValueType(),
10512 V->getOperand(0)), N->getOperand(1));
10519 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10520 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10521 EVT VT = N->getValueType(0);
10522 unsigned NumElts = VT.getVectorNumElements();
10524 SDValue N0 = N->getOperand(0);
10525 SDValue N1 = N->getOperand(1);
10526 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10528 SmallVector<SDValue, 4> Ops;
10529 EVT ConcatVT = N0.getOperand(0).getValueType();
10530 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10531 unsigned NumConcats = NumElts / NumElemsPerConcat;
10533 // Look at every vector that's inserted. We're looking for exact
10534 // subvector-sized copies from a concatenated vector
10535 for (unsigned I = 0; I != NumConcats; ++I) {
10536 // Make sure we're dealing with a copy.
10537 unsigned Begin = I * NumElemsPerConcat;
10538 bool AllUndef = true, NoUndef = true;
10539 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10540 if (SVN->getMaskElt(J) >= 0)
10547 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10550 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10551 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10554 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10555 if (FirstElt < N0.getNumOperands())
10556 Ops.push_back(N0.getOperand(FirstElt));
10558 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10560 } else if (AllUndef) {
10561 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10562 } else { // Mixed with general masks and undefs, can't do optimization.
10567 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10570 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10571 EVT VT = N->getValueType(0);
10572 unsigned NumElts = VT.getVectorNumElements();
10574 SDValue N0 = N->getOperand(0);
10575 SDValue N1 = N->getOperand(1);
10577 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10579 // Canonicalize shuffle undef, undef -> undef
10580 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10581 return DAG.getUNDEF(VT);
10583 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10585 // Canonicalize shuffle v, v -> v, undef
10587 SmallVector<int, 8> NewMask;
10588 for (unsigned i = 0; i != NumElts; ++i) {
10589 int Idx = SVN->getMaskElt(i);
10590 if (Idx >= (int)NumElts) Idx -= NumElts;
10591 NewMask.push_back(Idx);
10593 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10597 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10598 if (N0.getOpcode() == ISD::UNDEF) {
10599 SmallVector<int, 8> NewMask;
10600 for (unsigned i = 0; i != NumElts; ++i) {
10601 int Idx = SVN->getMaskElt(i);
10603 if (Idx >= (int)NumElts)
10606 Idx = -1; // remove reference to lhs
10608 NewMask.push_back(Idx);
10610 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10614 // Remove references to rhs if it is undef
10615 if (N1.getOpcode() == ISD::UNDEF) {
10616 bool Changed = false;
10617 SmallVector<int, 8> NewMask;
10618 for (unsigned i = 0; i != NumElts; ++i) {
10619 int Idx = SVN->getMaskElt(i);
10620 if (Idx >= (int)NumElts) {
10624 NewMask.push_back(Idx);
10627 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10630 // If it is a splat, check if the argument vector is another splat or a
10631 // build_vector with all scalar elements the same.
10632 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10633 SDNode *V = N0.getNode();
10635 // If this is a bit convert that changes the element type of the vector but
10636 // not the number of vector elements, look through it. Be careful not to
10637 // look though conversions that change things like v4f32 to v2f64.
10638 if (V->getOpcode() == ISD::BITCAST) {
10639 SDValue ConvInput = V->getOperand(0);
10640 if (ConvInput.getValueType().isVector() &&
10641 ConvInput.getValueType().getVectorNumElements() == NumElts)
10642 V = ConvInput.getNode();
10645 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10646 assert(V->getNumOperands() == NumElts &&
10647 "BUILD_VECTOR has wrong number of operands");
10649 bool AllSame = true;
10650 for (unsigned i = 0; i != NumElts; ++i) {
10651 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10652 Base = V->getOperand(i);
10656 // Splat of <u, u, u, u>, return <u, u, u, u>
10657 if (!Base.getNode())
10659 for (unsigned i = 0; i != NumElts; ++i) {
10660 if (V->getOperand(i) != Base) {
10665 // Splat of <x, x, x, x>, return <x, x, x, x>
10671 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10672 Level < AfterLegalizeVectorOps &&
10673 (N1.getOpcode() == ISD::UNDEF ||
10674 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10675 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10676 SDValue V = partitionShuffleOfConcats(N, DAG);
10682 // If this shuffle node is simply a swizzle of another shuffle node,
10683 // then try to simplify it.
10684 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10685 N1.getOpcode() == ISD::UNDEF) {
10687 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10689 // The incoming shuffle must be of the same type as the result of the
10690 // current shuffle.
10691 assert(OtherSV->getOperand(0).getValueType() == VT &&
10692 "Shuffle types don't match");
10694 SmallVector<int, 4> Mask;
10695 // Compute the combined shuffle mask.
10696 for (unsigned i = 0; i != NumElts; ++i) {
10697 int Idx = SVN->getMaskElt(i);
10698 assert(Idx < (int)NumElts && "Index references undef operand");
10699 // Next, this index comes from the first value, which is the incoming
10700 // shuffle. Adopt the incoming index.
10702 Idx = OtherSV->getMaskElt(Idx);
10703 Mask.push_back(Idx);
10706 bool CommuteOperands = false;
10707 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10708 // To be valid, the combine shuffle mask should only reference elements
10709 // from one of the two vectors in input to the inner shufflevector.
10710 bool IsValidMask = true;
10711 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10712 // See if the combined mask only reference undefs or elements coming
10713 // from the first shufflevector operand.
10714 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10716 if (!IsValidMask) {
10717 IsValidMask = true;
10718 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10719 // Check that all the elements come from the second shuffle operand.
10720 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10721 CommuteOperands = IsValidMask;
10724 // Early exit if the combined shuffle mask is not valid.
10729 // See if this pair of shuffles can be safely folded according to either
10730 // of the following rules:
10731 // shuffle(shuffle(x, y), undef) -> x
10732 // shuffle(shuffle(x, undef), undef) -> x
10733 // shuffle(shuffle(x, y), undef) -> y
10734 bool IsIdentityMask = true;
10735 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10736 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10741 // The combined shuffle must map each index to itself.
10742 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10745 if (IsIdentityMask) {
10746 if (CommuteOperands)
10747 // optimize shuffle(shuffle(x, y), undef) -> y.
10748 return OtherSV->getOperand(1);
10750 // optimize shuffle(shuffle(x, undef), undef) -> x
10751 // optimize shuffle(shuffle(x, y), undef) -> x
10752 return OtherSV->getOperand(0);
10755 // It may still be beneficial to combine the two shuffles if the
10756 // resulting shuffle is legal.
10757 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10758 if (!CommuteOperands)
10759 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10760 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10761 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10764 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10765 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10770 // Canonicalize shuffles according to rules:
10771 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10772 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10773 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10774 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10775 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10776 TLI.isTypeLegal(VT)) {
10777 // The incoming shuffle must be of the same type as the result of the
10778 // current shuffle.
10779 assert(N1->getOperand(0).getValueType() == VT &&
10780 "Shuffle types don't match");
10782 SDValue SV0 = N1->getOperand(0);
10783 SDValue SV1 = N1->getOperand(1);
10784 bool HasSameOp0 = N0 == SV0;
10785 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10786 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10787 // Commute the operands of this shuffle so that next rule
10789 return DAG.getCommutedVectorShuffle(*SVN);
10792 // Try to fold according to rules:
10793 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10794 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10795 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10796 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10797 // Don't try to fold shuffles with illegal type.
10798 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10799 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10800 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10802 // The incoming shuffle must be of the same type as the result of the
10803 // current shuffle.
10804 assert(OtherSV->getOperand(0).getValueType() == VT &&
10805 "Shuffle types don't match");
10807 SDValue SV0 = OtherSV->getOperand(0);
10808 SDValue SV1 = OtherSV->getOperand(1);
10809 bool HasSameOp0 = N1 == SV0;
10810 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10811 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10815 SmallVector<int, 4> Mask;
10816 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10817 // operand, and SV1 as the second operand.
10818 for (unsigned i = 0; i != NumElts; ++i) {
10819 int Idx = SVN->getMaskElt(i);
10821 // Propagate Undef.
10822 Mask.push_back(Idx);
10826 if (Idx < (int)NumElts) {
10827 Idx = OtherSV->getMaskElt(Idx);
10828 if (IsSV1Undef && Idx >= (int) NumElts)
10829 Idx = -1; // Propagate Undef.
10831 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10833 Mask.push_back(Idx);
10836 // Avoid introducing shuffles with illegal mask.
10837 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10839 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10840 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10841 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10842 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10849 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10850 SDValue N0 = N->getOperand(0);
10851 SDValue N2 = N->getOperand(2);
10853 // If the input vector is a concatenation, and the insert replaces
10854 // one of the halves, we can optimize into a single concat_vectors.
10855 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10856 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10857 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10858 EVT VT = N->getValueType(0);
10860 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10861 // (concat_vectors Z, Y)
10863 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10864 N->getOperand(1), N0.getOperand(1));
10866 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10867 // (concat_vectors X, Z)
10868 if (InsIdx == VT.getVectorNumElements()/2)
10869 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10870 N0.getOperand(0), N->getOperand(1));
10876 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10877 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10878 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10879 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10880 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10881 EVT VT = N->getValueType(0);
10883 SDValue LHS = N->getOperand(0);
10884 SDValue RHS = N->getOperand(1);
10885 if (N->getOpcode() == ISD::AND) {
10886 if (RHS.getOpcode() == ISD::BITCAST)
10887 RHS = RHS.getOperand(0);
10888 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10889 SmallVector<int, 8> Indices;
10890 unsigned NumElts = RHS.getNumOperands();
10891 for (unsigned i = 0; i != NumElts; ++i) {
10892 SDValue Elt = RHS.getOperand(i);
10893 if (!isa<ConstantSDNode>(Elt))
10896 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10897 Indices.push_back(i);
10898 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10899 Indices.push_back(NumElts);
10904 // Let's see if the target supports this vector_shuffle.
10905 EVT RVT = RHS.getValueType();
10906 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10909 // Return the new VECTOR_SHUFFLE node.
10910 EVT EltVT = RVT.getVectorElementType();
10911 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10912 DAG.getConstant(0, EltVT));
10913 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10914 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10915 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10916 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10923 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10924 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10925 assert(N->getValueType(0).isVector() &&
10926 "SimplifyVBinOp only works on vectors!");
10928 SDValue LHS = N->getOperand(0);
10929 SDValue RHS = N->getOperand(1);
10930 SDValue Shuffle = XformToShuffleWithZero(N);
10931 if (Shuffle.getNode()) return Shuffle;
10933 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10935 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10936 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10937 // Check if both vectors are constants. If not bail out.
10938 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10939 cast<BuildVectorSDNode>(RHS)->isConstant()))
10942 SmallVector<SDValue, 8> Ops;
10943 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10944 SDValue LHSOp = LHS.getOperand(i);
10945 SDValue RHSOp = RHS.getOperand(i);
10947 // Can't fold divide by zero.
10948 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10949 N->getOpcode() == ISD::FDIV) {
10950 if ((RHSOp.getOpcode() == ISD::Constant &&
10951 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10952 (RHSOp.getOpcode() == ISD::ConstantFP &&
10953 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10957 EVT VT = LHSOp.getValueType();
10958 EVT RVT = RHSOp.getValueType();
10960 // Integer BUILD_VECTOR operands may have types larger than the element
10961 // size (e.g., when the element type is not legal). Prior to type
10962 // legalization, the types may not match between the two BUILD_VECTORS.
10963 // Truncate one of the operands to make them match.
10964 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10965 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10967 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10971 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10973 if (FoldOp.getOpcode() != ISD::UNDEF &&
10974 FoldOp.getOpcode() != ISD::Constant &&
10975 FoldOp.getOpcode() != ISD::ConstantFP)
10977 Ops.push_back(FoldOp);
10978 AddToWorklist(FoldOp.getNode());
10981 if (Ops.size() == LHS.getNumOperands())
10982 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10985 // Type legalization might introduce new shuffles in the DAG.
10986 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10987 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10988 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10989 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10990 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10991 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10992 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10993 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10995 if (SVN0->getMask().equals(SVN1->getMask())) {
10996 EVT VT = N->getValueType(0);
10997 SDValue UndefVector = LHS.getOperand(1);
10998 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10999 LHS.getOperand(0), RHS.getOperand(0));
11000 AddUsersToWorklist(N);
11001 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11002 &SVN0->getMask()[0]);
11009 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11010 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11011 assert(N->getValueType(0).isVector() &&
11012 "SimplifyVUnaryOp only works on vectors!");
11014 SDValue N0 = N->getOperand(0);
11016 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11019 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11020 SmallVector<SDValue, 8> Ops;
11021 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11022 SDValue Op = N0.getOperand(i);
11023 if (Op.getOpcode() != ISD::UNDEF &&
11024 Op.getOpcode() != ISD::ConstantFP)
11026 EVT EltVT = Op.getValueType();
11027 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11028 if (FoldOp.getOpcode() != ISD::UNDEF &&
11029 FoldOp.getOpcode() != ISD::ConstantFP)
11031 Ops.push_back(FoldOp);
11032 AddToWorklist(FoldOp.getNode());
11035 if (Ops.size() != N0.getNumOperands())
11038 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11041 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11042 SDValue N1, SDValue N2){
11043 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11045 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11046 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11048 // If we got a simplified select_cc node back from SimplifySelectCC, then
11049 // break it down into a new SETCC node, and a new SELECT node, and then return
11050 // the SELECT node, since we were called with a SELECT node.
11051 if (SCC.getNode()) {
11052 // Check to see if we got a select_cc back (to turn into setcc/select).
11053 // Otherwise, just return whatever node we got back, like fabs.
11054 if (SCC.getOpcode() == ISD::SELECT_CC) {
11055 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11057 SCC.getOperand(0), SCC.getOperand(1),
11058 SCC.getOperand(4));
11059 AddToWorklist(SETCC.getNode());
11060 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11061 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11069 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11070 /// are the two values being selected between, see if we can simplify the
11071 /// select. Callers of this should assume that TheSelect is deleted if this
11072 /// returns true. As such, they should return the appropriate thing (e.g. the
11073 /// node) back to the top-level of the DAG combiner loop to avoid it being
11075 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11078 // Cannot simplify select with vector condition
11079 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11081 // If this is a select from two identical things, try to pull the operation
11082 // through the select.
11083 if (LHS.getOpcode() != RHS.getOpcode() ||
11084 !LHS.hasOneUse() || !RHS.hasOneUse())
11087 // If this is a load and the token chain is identical, replace the select
11088 // of two loads with a load through a select of the address to load from.
11089 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11090 // constants have been dropped into the constant pool.
11091 if (LHS.getOpcode() == ISD::LOAD) {
11092 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11093 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11095 // Token chains must be identical.
11096 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11097 // Do not let this transformation reduce the number of volatile loads.
11098 LLD->isVolatile() || RLD->isVolatile() ||
11099 // If this is an EXTLOAD, the VT's must match.
11100 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11101 // If this is an EXTLOAD, the kind of extension must match.
11102 (LLD->getExtensionType() != RLD->getExtensionType() &&
11103 // The only exception is if one of the extensions is anyext.
11104 LLD->getExtensionType() != ISD::EXTLOAD &&
11105 RLD->getExtensionType() != ISD::EXTLOAD) ||
11106 // FIXME: this discards src value information. This is
11107 // over-conservative. It would be beneficial to be able to remember
11108 // both potential memory locations. Since we are discarding
11109 // src value info, don't do the transformation if the memory
11110 // locations are not in the default address space.
11111 LLD->getPointerInfo().getAddrSpace() != 0 ||
11112 RLD->getPointerInfo().getAddrSpace() != 0 ||
11113 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11114 LLD->getBasePtr().getValueType()))
11117 // Check that the select condition doesn't reach either load. If so,
11118 // folding this will induce a cycle into the DAG. If not, this is safe to
11119 // xform, so create a select of the addresses.
11121 if (TheSelect->getOpcode() == ISD::SELECT) {
11122 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11123 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11124 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11126 // The loads must not depend on one another.
11127 if (LLD->isPredecessorOf(RLD) ||
11128 RLD->isPredecessorOf(LLD))
11130 Addr = DAG.getSelect(SDLoc(TheSelect),
11131 LLD->getBasePtr().getValueType(),
11132 TheSelect->getOperand(0), LLD->getBasePtr(),
11133 RLD->getBasePtr());
11134 } else { // Otherwise SELECT_CC
11135 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11136 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11138 if ((LLD->hasAnyUseOfValue(1) &&
11139 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11140 (RLD->hasAnyUseOfValue(1) &&
11141 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11144 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11145 LLD->getBasePtr().getValueType(),
11146 TheSelect->getOperand(0),
11147 TheSelect->getOperand(1),
11148 LLD->getBasePtr(), RLD->getBasePtr(),
11149 TheSelect->getOperand(4));
11153 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11154 Load = DAG.getLoad(TheSelect->getValueType(0),
11156 // FIXME: Discards pointer and TBAA info.
11157 LLD->getChain(), Addr, MachinePointerInfo(),
11158 LLD->isVolatile(), LLD->isNonTemporal(),
11159 LLD->isInvariant(), LLD->getAlignment());
11161 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11162 RLD->getExtensionType() : LLD->getExtensionType(),
11164 TheSelect->getValueType(0),
11165 // FIXME: Discards pointer and TBAA info.
11166 LLD->getChain(), Addr, MachinePointerInfo(),
11167 LLD->getMemoryVT(), LLD->isVolatile(),
11168 LLD->isNonTemporal(), LLD->getAlignment());
11171 // Users of the select now use the result of the load.
11172 CombineTo(TheSelect, Load);
11174 // Users of the old loads now use the new load's chain. We know the
11175 // old-load value is dead now.
11176 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11177 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11184 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11185 /// where 'cond' is the comparison specified by CC.
11186 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11187 SDValue N2, SDValue N3,
11188 ISD::CondCode CC, bool NotExtCompare) {
11189 // (x ? y : y) -> y.
11190 if (N2 == N3) return N2;
11192 EVT VT = N2.getValueType();
11193 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11194 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11195 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11197 // Determine if the condition we're dealing with is constant
11198 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11199 N0, N1, CC, DL, false);
11200 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11201 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11203 // fold select_cc true, x, y -> x
11204 if (SCCC && !SCCC->isNullValue())
11206 // fold select_cc false, x, y -> y
11207 if (SCCC && SCCC->isNullValue())
11210 // Check to see if we can simplify the select into an fabs node
11211 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11212 // Allow either -0.0 or 0.0
11213 if (CFP->getValueAPF().isZero()) {
11214 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11215 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11216 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11217 N2 == N3.getOperand(0))
11218 return DAG.getNode(ISD::FABS, DL, VT, N0);
11220 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11221 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11222 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11223 N2.getOperand(0) == N3)
11224 return DAG.getNode(ISD::FABS, DL, VT, N3);
11228 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11229 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11230 // in it. This is a win when the constant is not otherwise available because
11231 // it replaces two constant pool loads with one. We only do this if the FP
11232 // type is known to be legal, because if it isn't, then we are before legalize
11233 // types an we want the other legalization to happen first (e.g. to avoid
11234 // messing with soft float) and if the ConstantFP is not legal, because if
11235 // it is legal, we may not need to store the FP constant in a constant pool.
11236 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11237 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11238 if (TLI.isTypeLegal(N2.getValueType()) &&
11239 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11240 TargetLowering::Legal &&
11241 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11242 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11243 // If both constants have multiple uses, then we won't need to do an
11244 // extra load, they are likely around in registers for other users.
11245 (TV->hasOneUse() || FV->hasOneUse())) {
11246 Constant *Elts[] = {
11247 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11248 const_cast<ConstantFP*>(TV->getConstantFPValue())
11250 Type *FPTy = Elts[0]->getType();
11251 const DataLayout &TD = *TLI.getDataLayout();
11253 // Create a ConstantArray of the two constants.
11254 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11255 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11256 TD.getPrefTypeAlignment(FPTy));
11257 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11259 // Get the offsets to the 0 and 1 element of the array so that we can
11260 // select between them.
11261 SDValue Zero = DAG.getIntPtrConstant(0);
11262 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11263 SDValue One = DAG.getIntPtrConstant(EltSize);
11265 SDValue Cond = DAG.getSetCC(DL,
11266 getSetCCResultType(N0.getValueType()),
11268 AddToWorklist(Cond.getNode());
11269 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11271 AddToWorklist(CstOffset.getNode());
11272 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11274 AddToWorklist(CPIdx.getNode());
11275 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11276 MachinePointerInfo::getConstantPool(), false,
11277 false, false, Alignment);
11282 // Check to see if we can perform the "gzip trick", transforming
11283 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11284 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11285 (N1C->isNullValue() || // (a < 0) ? b : 0
11286 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11287 EVT XType = N0.getValueType();
11288 EVT AType = N2.getValueType();
11289 if (XType.bitsGE(AType)) {
11290 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11291 // single-bit constant.
11292 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11293 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11294 ShCtV = XType.getSizeInBits()-ShCtV-1;
11295 SDValue ShCt = DAG.getConstant(ShCtV,
11296 getShiftAmountTy(N0.getValueType()));
11297 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11299 AddToWorklist(Shift.getNode());
11301 if (XType.bitsGT(AType)) {
11302 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11303 AddToWorklist(Shift.getNode());
11306 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11309 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11311 DAG.getConstant(XType.getSizeInBits()-1,
11312 getShiftAmountTy(N0.getValueType())));
11313 AddToWorklist(Shift.getNode());
11315 if (XType.bitsGT(AType)) {
11316 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11317 AddToWorklist(Shift.getNode());
11320 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11324 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11325 // where y is has a single bit set.
11326 // A plaintext description would be, we can turn the SELECT_CC into an AND
11327 // when the condition can be materialized as an all-ones register. Any
11328 // single bit-test can be materialized as an all-ones register with
11329 // shift-left and shift-right-arith.
11330 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11331 N0->getValueType(0) == VT &&
11332 N1C && N1C->isNullValue() &&
11333 N2C && N2C->isNullValue()) {
11334 SDValue AndLHS = N0->getOperand(0);
11335 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11336 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11337 // Shift the tested bit over the sign bit.
11338 APInt AndMask = ConstAndRHS->getAPIntValue();
11340 DAG.getConstant(AndMask.countLeadingZeros(),
11341 getShiftAmountTy(AndLHS.getValueType()));
11342 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11344 // Now arithmetic right shift it all the way over, so the result is either
11345 // all-ones, or zero.
11347 DAG.getConstant(AndMask.getBitWidth()-1,
11348 getShiftAmountTy(Shl.getValueType()));
11349 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11351 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11355 // fold select C, 16, 0 -> shl C, 4
11356 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11357 TLI.getBooleanContents(N0.getValueType()) ==
11358 TargetLowering::ZeroOrOneBooleanContent) {
11360 // If the caller doesn't want us to simplify this into a zext of a compare,
11362 if (NotExtCompare && N2C->getAPIntValue() == 1)
11365 // Get a SetCC of the condition
11366 // NOTE: Don't create a SETCC if it's not legal on this target.
11367 if (!LegalOperations ||
11368 TLI.isOperationLegal(ISD::SETCC,
11369 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11371 // cast from setcc result type to select result type
11373 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11375 if (N2.getValueType().bitsLT(SCC.getValueType()))
11376 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11377 N2.getValueType());
11379 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11380 N2.getValueType(), SCC);
11382 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11383 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11384 N2.getValueType(), SCC);
11387 AddToWorklist(SCC.getNode());
11388 AddToWorklist(Temp.getNode());
11390 if (N2C->getAPIntValue() == 1)
11393 // shl setcc result by log2 n2c
11394 return DAG.getNode(
11395 ISD::SHL, DL, N2.getValueType(), Temp,
11396 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11397 getShiftAmountTy(Temp.getValueType())));
11401 // Check to see if this is the equivalent of setcc
11402 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11403 // otherwise, go ahead with the folds.
11404 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11405 EVT XType = N0.getValueType();
11406 if (!LegalOperations ||
11407 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11408 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11409 if (Res.getValueType() != VT)
11410 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11414 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11415 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11416 (!LegalOperations ||
11417 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11418 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11419 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11420 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11421 getShiftAmountTy(Ctlz.getValueType())));
11423 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11424 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11425 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11426 XType, DAG.getConstant(0, XType), N0);
11427 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11428 return DAG.getNode(ISD::SRL, DL, XType,
11429 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11430 DAG.getConstant(XType.getSizeInBits()-1,
11431 getShiftAmountTy(XType)));
11433 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11434 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11435 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11436 DAG.getConstant(XType.getSizeInBits()-1,
11437 getShiftAmountTy(N0.getValueType())));
11438 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11442 // Check to see if this is an integer abs.
11443 // select_cc setg[te] X, 0, X, -X ->
11444 // select_cc setgt X, -1, X, -X ->
11445 // select_cc setl[te] X, 0, -X, X ->
11446 // select_cc setlt X, 1, -X, X ->
11447 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11449 ConstantSDNode *SubC = nullptr;
11450 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11451 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11452 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11453 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11454 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11455 (N1C->isOne() && CC == ISD::SETLT)) &&
11456 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11457 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11459 EVT XType = N0.getValueType();
11460 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11461 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11463 DAG.getConstant(XType.getSizeInBits()-1,
11464 getShiftAmountTy(N0.getValueType())));
11465 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11467 AddToWorklist(Shift.getNode());
11468 AddToWorklist(Add.getNode());
11469 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11476 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11477 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11478 SDValue N1, ISD::CondCode Cond,
11479 SDLoc DL, bool foldBooleans) {
11480 TargetLowering::DAGCombinerInfo
11481 DagCombineInfo(DAG, Level, false, this);
11482 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11485 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11486 /// return a DAG expression to select that will generate the same value by
11487 /// multiplying by a magic number. See:
11488 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11489 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11490 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11494 // Avoid division by zero.
11495 if (!C->getAPIntValue())
11498 std::vector<SDNode*> Built;
11500 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11502 for (SDNode *N : Built)
11507 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11508 /// return a DAG expression to select that will generate the same value by
11509 /// multiplying by a magic number. See:
11510 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11511 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11512 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11516 // Avoid division by zero.
11517 if (!C->getAPIntValue())
11520 std::vector<SDNode*> Built;
11522 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11524 for (SDNode *N : Built)
11529 /// FindBaseOffset - Return true if base is a frame index, which is known not
11530 // to alias with anything but itself. Provides base object and offset as
11532 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11533 const GlobalValue *&GV, const void *&CV) {
11534 // Assume it is a primitive operation.
11535 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11537 // If it's an adding a simple constant then integrate the offset.
11538 if (Base.getOpcode() == ISD::ADD) {
11539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11540 Base = Base.getOperand(0);
11541 Offset += C->getZExtValue();
11545 // Return the underlying GlobalValue, and update the Offset. Return false
11546 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11547 // by multiple nodes with different offsets.
11548 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11549 GV = G->getGlobal();
11550 Offset += G->getOffset();
11554 // Return the underlying Constant value, and update the Offset. Return false
11555 // for ConstantSDNodes since the same constant pool entry may be represented
11556 // by multiple nodes with different offsets.
11557 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11558 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11559 : (const void *)C->getConstVal();
11560 Offset += C->getOffset();
11563 // If it's any of the following then it can't alias with anything but itself.
11564 return isa<FrameIndexSDNode>(Base);
11567 /// isAlias - Return true if there is any possibility that the two addresses
11569 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11570 // If they are the same then they must be aliases.
11571 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11573 // If they are both volatile then they cannot be reordered.
11574 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11576 // Gather base node and offset information.
11577 SDValue Base1, Base2;
11578 int64_t Offset1, Offset2;
11579 const GlobalValue *GV1, *GV2;
11580 const void *CV1, *CV2;
11581 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11582 Base1, Offset1, GV1, CV1);
11583 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11584 Base2, Offset2, GV2, CV2);
11586 // If they have a same base address then check to see if they overlap.
11587 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11588 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11589 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11591 // It is possible for different frame indices to alias each other, mostly
11592 // when tail call optimization reuses return address slots for arguments.
11593 // To catch this case, look up the actual index of frame indices to compute
11594 // the real alias relationship.
11595 if (isFrameIndex1 && isFrameIndex2) {
11596 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11597 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11598 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11599 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11600 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11603 // Otherwise, if we know what the bases are, and they aren't identical, then
11604 // we know they cannot alias.
11605 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11608 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11609 // compared to the size and offset of the access, we may be able to prove they
11610 // do not alias. This check is conservative for now to catch cases created by
11611 // splitting vector types.
11612 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11613 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11614 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11615 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11616 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11617 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11618 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11620 // There is no overlap between these relatively aligned accesses of similar
11621 // size, return no alias.
11622 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11623 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11627 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11628 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11630 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11631 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11635 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11636 // Use alias analysis information.
11637 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11638 Op1->getSrcValueOffset());
11639 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11640 Op0->getSrcValueOffset() - MinOffset;
11641 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11642 Op1->getSrcValueOffset() - MinOffset;
11643 AliasAnalysis::AliasResult AAResult =
11644 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11646 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11647 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11649 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11650 if (AAResult == AliasAnalysis::NoAlias)
11654 // Otherwise we have to assume they alias.
11658 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11659 /// looking for aliasing nodes and adding them to the Aliases vector.
11660 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11661 SmallVectorImpl<SDValue> &Aliases) {
11662 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11663 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11665 // Get alias information for node.
11666 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11669 Chains.push_back(OriginalChain);
11670 unsigned Depth = 0;
11672 // Look at each chain and determine if it is an alias. If so, add it to the
11673 // aliases list. If not, then continue up the chain looking for the next
11675 while (!Chains.empty()) {
11676 SDValue Chain = Chains.back();
11679 // For TokenFactor nodes, look at each operand and only continue up the
11680 // chain until we find two aliases. If we've seen two aliases, assume we'll
11681 // find more and revert to original chain since the xform is unlikely to be
11684 // FIXME: The depth check could be made to return the last non-aliasing
11685 // chain we found before we hit a tokenfactor rather than the original
11687 if (Depth > 6 || Aliases.size() == 2) {
11689 Aliases.push_back(OriginalChain);
11693 // Don't bother if we've been before.
11694 if (!Visited.insert(Chain.getNode()))
11697 switch (Chain.getOpcode()) {
11698 case ISD::EntryToken:
11699 // Entry token is ideal chain operand, but handled in FindBetterChain.
11704 // Get alias information for Chain.
11705 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11706 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11708 // If chain is alias then stop here.
11709 if (!(IsLoad && IsOpLoad) &&
11710 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11711 Aliases.push_back(Chain);
11713 // Look further up the chain.
11714 Chains.push_back(Chain.getOperand(0));
11720 case ISD::TokenFactor:
11721 // We have to check each of the operands of the token factor for "small"
11722 // token factors, so we queue them up. Adding the operands to the queue
11723 // (stack) in reverse order maintains the original order and increases the
11724 // likelihood that getNode will find a matching token factor (CSE.)
11725 if (Chain.getNumOperands() > 16) {
11726 Aliases.push_back(Chain);
11729 for (unsigned n = Chain.getNumOperands(); n;)
11730 Chains.push_back(Chain.getOperand(--n));
11735 // For all other instructions we will just have to take what we can get.
11736 Aliases.push_back(Chain);
11741 // We need to be careful here to also search for aliases through the
11742 // value operand of a store, etc. Consider the following situation:
11744 // L1 = load Token1, %52
11745 // S1 = store Token1, L1, %51
11746 // L2 = load Token1, %52+8
11747 // S2 = store Token1, L2, %51+8
11748 // Token2 = Token(S1, S2)
11749 // L3 = load Token2, %53
11750 // S3 = store Token2, L3, %52
11751 // L4 = load Token2, %53+8
11752 // S4 = store Token2, L4, %52+8
11753 // If we search for aliases of S3 (which loads address %52), and we look
11754 // only through the chain, then we'll miss the trivial dependence on L1
11755 // (which also loads from %52). We then might change all loads and
11756 // stores to use Token1 as their chain operand, which could result in
11757 // copying %53 into %52 before copying %52 into %51 (which should
11760 // The problem is, however, that searching for such data dependencies
11761 // can become expensive, and the cost is not directly related to the
11762 // chain depth. Instead, we'll rule out such configurations here by
11763 // insisting that we've visited all chain users (except for users
11764 // of the original chain, which is not necessary). When doing this,
11765 // we need to look through nodes we don't care about (otherwise, things
11766 // like register copies will interfere with trivial cases).
11768 SmallVector<const SDNode *, 16> Worklist;
11769 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11770 IE = Visited.end(); I != IE; ++I)
11771 if (*I != OriginalChain.getNode())
11772 Worklist.push_back(*I);
11774 while (!Worklist.empty()) {
11775 const SDNode *M = Worklist.pop_back_val();
11777 // We have already visited M, and want to make sure we've visited any uses
11778 // of M that we care about. For uses that we've not visisted, and don't
11779 // care about, queue them to the worklist.
11781 for (SDNode::use_iterator UI = M->use_begin(),
11782 UIE = M->use_end(); UI != UIE; ++UI)
11783 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11784 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11785 // We've not visited this use, and we care about it (it could have an
11786 // ordering dependency with the original node).
11788 Aliases.push_back(OriginalChain);
11792 // We've not visited this use, but we don't care about it. Mark it as
11793 // visited and enqueue it to the worklist.
11794 Worklist.push_back(*UI);
11799 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11800 /// for a better chain (aliasing node.)
11801 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11802 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11804 // Accumulate all the aliases to this node.
11805 GatherAllAliases(N, OldChain, Aliases);
11807 // If no operands then chain to entry token.
11808 if (Aliases.size() == 0)
11809 return DAG.getEntryNode();
11811 // If a single operand then chain to it. We don't need to revisit it.
11812 if (Aliases.size() == 1)
11815 // Construct a custom tailored token factor.
11816 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11819 // SelectionDAG::Combine - This is the entry point for the file.
11821 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11822 CodeGenOpt::Level OptLevel) {
11823 /// run - This is the main entry point to this class.
11825 DAGCombiner(*this, AA, OptLevel).Run(Level);