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 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.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 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 // 1. Stack coloring does not update TBAA when merging allocas
61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 // Because BasicAA does not handle inttoptr, we'll often miss basic type
63 // punning idioms that we need to catch so we don't miscompile real-world
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
76 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 // Worklist of all of the nodes that need to be simplified.
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
113 SmallVector<SDNode*, 64> WorkListOrder;
115 // AA - Used for DAG load/store alias analysis.
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
130 SDValue visit(SDNode *N);
133 /// AddToWorkList - Add to the work list making sure its instance is at the
134 /// back (next to be processed.)
135 void AddToWorkList(SDNode *N) {
136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
140 /// removeFromWorkList - remove all instances of N from the worklist.
142 void removeFromWorkList(SDNode *N) {
143 WorkListContents.erase(N);
146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150 return CombineTo(N, &Res, 1, AddTo);
153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
155 SDValue To[] = { Res0, Res1 };
156 return CombineTo(N, To, 2, AddTo);
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
163 /// SimplifyDemandedBits - Check the specified integer node value to see if
164 /// it can be simplified or if things it uses can be simplified by bit
165 /// propagation. If so, return true.
166 bool SimplifyDemandedBits(SDValue Op) {
167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
169 return SimplifyDemandedBits(Op, Demanded);
172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
176 bool SliceUpLoad(SDNode *N);
178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182 SDValue PromoteIntBinOp(SDValue Op);
183 SDValue PromoteIntShiftOp(SDValue Op);
184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189 ISD::NodeType ExtType);
191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
194 SDValue combine(SDNode *N);
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
208 SDValue visitSUBC(SDNode *N);
209 SDValue visitADDE(SDNode *N);
210 SDValue visitSUBE(SDNode *N);
211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
228 SDValue SimplifyVUnaryOp(SDNode *N);
229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitRotate(SDNode *N);
233 SDValue visitCTLZ(SDNode *N);
234 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
235 SDValue visitCTTZ(SDNode *N);
236 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
237 SDValue visitCTPOP(SDNode *N);
238 SDValue visitSELECT(SDNode *N);
239 SDValue visitVSELECT(SDNode *N);
240 SDValue visitSELECT_CC(SDNode *N);
241 SDValue visitSETCC(SDNode *N);
242 SDValue visitSIGN_EXTEND(SDNode *N);
243 SDValue visitZERO_EXTEND(SDNode *N);
244 SDValue visitANY_EXTEND(SDNode *N);
245 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246 SDValue visitTRUNCATE(SDNode *N);
247 SDValue visitBITCAST(SDNode *N);
248 SDValue visitBUILD_PAIR(SDNode *N);
249 SDValue visitFADD(SDNode *N);
250 SDValue visitFSUB(SDNode *N);
251 SDValue visitFMUL(SDNode *N);
252 SDValue visitFMA(SDNode *N);
253 SDValue visitFDIV(SDNode *N);
254 SDValue visitFREM(SDNode *N);
255 SDValue visitFCOPYSIGN(SDNode *N);
256 SDValue visitSINT_TO_FP(SDNode *N);
257 SDValue visitUINT_TO_FP(SDNode *N);
258 SDValue visitFP_TO_SINT(SDNode *N);
259 SDValue visitFP_TO_UINT(SDNode *N);
260 SDValue visitFP_ROUND(SDNode *N);
261 SDValue visitFP_ROUND_INREG(SDNode *N);
262 SDValue visitFP_EXTEND(SDNode *N);
263 SDValue visitFNEG(SDNode *N);
264 SDValue visitFABS(SDNode *N);
265 SDValue visitFCEIL(SDNode *N);
266 SDValue visitFTRUNC(SDNode *N);
267 SDValue visitFFLOOR(SDNode *N);
268 SDValue visitBRCOND(SDNode *N);
269 SDValue visitBR_CC(SDNode *N);
270 SDValue visitLOAD(SDNode *N);
271 SDValue visitSTORE(SDNode *N);
272 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274 SDValue visitBUILD_VECTOR(SDNode *N);
275 SDValue visitCONCAT_VECTORS(SDNode *N);
276 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
277 SDValue visitVECTOR_SHUFFLE(SDNode *N);
278 SDValue visitINSERT_SUBVECTOR(SDNode *N);
280 SDValue XformToShuffleWithZero(SDNode *N);
281 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
283 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
285 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
287 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
289 SDValue N3, ISD::CondCode CC,
290 bool NotExtCompare = false);
291 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
292 SDLoc DL, bool foldBooleans = true);
294 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
296 bool isOneUseSetCC(SDValue N) const;
298 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
300 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
301 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
302 SDValue BuildSDIV(SDNode *N);
303 SDValue BuildUDIV(SDNode *N);
304 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
305 bool DemandHighBits = true);
306 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
307 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
308 SDValue InnerPos, SDValue InnerNeg,
309 unsigned PosOpcode, unsigned NegOpcode,
311 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
312 SDValue ReduceLoadWidth(SDNode *N);
313 SDValue ReduceLoadOpStoreWidth(SDNode *N);
314 SDValue TransformFPLoadStorePair(SDNode *N);
315 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
316 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
318 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
320 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
321 /// looking for aliasing nodes and adding them to the Aliases vector.
322 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
323 SmallVectorImpl<SDValue> &Aliases);
325 /// isAlias - Return true if there is any possibility that the two addresses
327 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
328 const Value *SrcValue1, int SrcValueOffset1,
329 unsigned SrcValueAlign1,
330 const MDNode *TBAAInfo1,
331 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
332 const Value *SrcValue2, int SrcValueOffset2,
333 unsigned SrcValueAlign2,
334 const MDNode *TBAAInfo2) const;
336 /// isAlias - Return true if there is any possibility that the two addresses
338 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
340 /// FindAliasInfo - Extracts the relevant alias information from the memory
341 /// node. Returns true if the operand was a load.
342 bool FindAliasInfo(SDNode *N,
343 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
344 const Value *&SrcValue, int &SrcValueOffset,
345 unsigned &SrcValueAlignment,
346 const MDNode *&TBAAInfo) const;
348 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
349 /// looking for a better chain (aliasing node.)
350 SDValue FindBetterChain(SDNode *N, SDValue Chain);
352 /// Merge consecutive store operations into a wide store.
353 /// This optimization uses wide integers or vectors when possible.
354 /// \return True if some memory operations were changed.
355 bool MergeConsecutiveStores(StoreSDNode *N);
357 /// \brief Try to transform a truncation where C is a constant:
358 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
360 /// \p N needs to be a truncation and its first operand an AND. Other
361 /// requirements are checked by the function (e.g. that trunc is
362 /// single-use) and if missed an empty SDValue is returned.
363 SDValue distributeTruncateThroughAnd(SDNode *N);
366 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
367 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
368 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
369 AttributeSet FnAttrs =
370 DAG.getMachineFunction().getFunction()->getAttributes();
372 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
373 Attribute::OptimizeForSize) ||
374 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
377 /// Run - runs the dag combiner on all nodes in the work list
378 void Run(CombineLevel AtLevel);
380 SelectionDAG &getDAG() const { return DAG; }
382 /// getShiftAmountTy - Returns a type large enough to hold any valid
383 /// shift amount - before type legalization these can be huge.
384 EVT getShiftAmountTy(EVT LHSTy) {
385 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
386 if (LHSTy.isVector())
388 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
389 : TLI.getPointerTy();
392 /// isTypeLegal - This method returns true if we are running before type
393 /// legalization or if the specified VT is legal.
394 bool isTypeLegal(const EVT &VT) {
395 if (!LegalTypes) return true;
396 return TLI.isTypeLegal(VT);
399 /// getSetCCResultType - Convenience wrapper around
400 /// TargetLowering::getSetCCResultType
401 EVT getSetCCResultType(EVT VT) const {
402 return TLI.getSetCCResultType(*DAG.getContext(), VT);
409 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
410 /// nodes from the worklist.
411 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
414 explicit WorkListRemover(DAGCombiner &dc)
415 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
417 void NodeDeleted(SDNode *N, SDNode *E) override {
418 DC.removeFromWorkList(N);
423 //===----------------------------------------------------------------------===//
424 // TargetLowering::DAGCombinerInfo implementation
425 //===----------------------------------------------------------------------===//
427 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
428 ((DAGCombiner*)DC)->AddToWorkList(N);
431 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
432 ((DAGCombiner*)DC)->removeFromWorkList(N);
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
448 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
451 void TargetLowering::DAGCombinerInfo::
452 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
453 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
456 //===----------------------------------------------------------------------===//
458 //===----------------------------------------------------------------------===//
460 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
461 /// specified expression for the same cost as the expression itself, or 2 if we
462 /// can compute the negated form more cheaply than the expression itself.
463 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
464 const TargetLowering &TLI,
465 const TargetOptions *Options,
466 unsigned Depth = 0) {
467 // fneg is removable even if it has multiple uses.
468 if (Op.getOpcode() == ISD::FNEG) return 2;
470 // Don't allow anything with multiple uses.
471 if (!Op.hasOneUse()) return 0;
473 // Don't recurse exponentially.
474 if (Depth > 6) return 0;
476 switch (Op.getOpcode()) {
477 default: return false;
478 case ISD::ConstantFP:
479 // Don't invert constant FP values after legalize. The negated constant
480 // isn't necessarily legal.
481 return LegalOperations ? 0 : 1;
483 // FIXME: determine better conditions for this xform.
484 if (!Options->UnsafeFPMath) return 0;
486 // After operation legalization, it might not be legal to create new FSUBs.
487 if (LegalOperations &&
488 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
491 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
495 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
496 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
499 // We can't turn -(A-B) into B-A when we honor signed zeros.
500 if (!Options->UnsafeFPMath) return 0;
502 // fold (fneg (fsub A, B)) -> (fsub B, A)
507 if (Options->HonorSignDependentRoundingFPMath()) return 0;
509 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
510 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
514 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
520 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
525 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
526 /// returns the newly negated expression.
527 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
528 bool LegalOperations, unsigned Depth = 0) {
529 // fneg is removable even if it has multiple uses.
530 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
532 // Don't allow anything with multiple uses.
533 assert(Op.hasOneUse() && "Unknown reuse!");
535 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
536 switch (Op.getOpcode()) {
537 default: llvm_unreachable("Unknown code");
538 case ISD::ConstantFP: {
539 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
541 return DAG.getConstantFP(V, Op.getValueType());
544 // FIXME: determine better conditions for this xform.
545 assert(DAG.getTarget().Options.UnsafeFPMath);
547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
549 DAG.getTargetLoweringInfo(),
550 &DAG.getTarget().Options, Depth+1))
551 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
552 GetNegatedExpression(Op.getOperand(0), DAG,
553 LegalOperations, Depth+1),
555 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
557 GetNegatedExpression(Op.getOperand(1), DAG,
558 LegalOperations, Depth+1),
561 // We can't turn -(A-B) into B-A when we honor signed zeros.
562 assert(DAG.getTarget().Options.UnsafeFPMath);
564 // fold (fneg (fsub 0, B)) -> B
565 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
566 if (N0CFP->getValueAPF().isZero())
567 return Op.getOperand(1);
569 // fold (fneg (fsub A, B)) -> (fsub B, A)
570 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
571 Op.getOperand(1), Op.getOperand(0));
575 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
577 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
578 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
579 DAG.getTargetLoweringInfo(),
580 &DAG.getTarget().Options, Depth+1))
581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
582 GetNegatedExpression(Op.getOperand(0), DAG,
583 LegalOperations, Depth+1),
586 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
587 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589 GetNegatedExpression(Op.getOperand(1), DAG,
590 LegalOperations, Depth+1));
594 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
595 GetNegatedExpression(Op.getOperand(0), DAG,
596 LegalOperations, Depth+1));
598 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
605 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
606 // that selects between the target values used for true and false, making it
607 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
608 // the appropriate nodes based on the type of node we are checking. This
609 // simplifies life a bit for the callers.
610 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
612 if (N.getOpcode() == ISD::SETCC) {
613 LHS = N.getOperand(0);
614 RHS = N.getOperand(1);
615 CC = N.getOperand(2);
619 if (N.getOpcode() != ISD::SELECT_CC ||
620 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
621 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
624 LHS = N.getOperand(0);
625 RHS = N.getOperand(1);
626 CC = N.getOperand(4);
630 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
631 // one use. If this is true, it allows the users to invert the operation for
632 // free when it is profitable to do so.
633 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
635 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
640 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
641 /// elements are all the same constant or undefined.
642 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
643 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
648 unsigned SplatBitSize;
650 EVT EltVT = N->getValueType(0).getVectorElementType();
651 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
653 EltVT.getSizeInBits() >= SplatBitSize);
656 // \brief Returns the SDNode if it is a constant BuildVector or constant.
657 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
658 if (isa<ConstantSDNode>(N))
660 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
661 if(BV && BV->isConstant())
666 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
668 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
669 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
672 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
673 return BV->getConstantSplatValue();
678 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
679 SDValue N0, SDValue N1) {
680 EVT VT = N0.getValueType();
681 if (N0.getOpcode() == Opc) {
682 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
683 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
684 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
685 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
686 if (!OpNode.getNode())
688 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
690 if (N0.hasOneUse()) {
691 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
693 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
694 if (!OpNode.getNode())
696 AddToWorkList(OpNode.getNode());
697 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
702 if (N1.getOpcode() == Opc) {
703 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
704 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
705 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
706 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
707 if (!OpNode.getNode())
709 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
711 if (N1.hasOneUse()) {
712 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
714 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
715 if (!OpNode.getNode())
717 AddToWorkList(OpNode.getNode());
718 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
726 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
728 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
730 DEBUG(dbgs() << "\nReplacing.1 ";
732 dbgs() << "\nWith: ";
733 To[0].getNode()->dump(&DAG);
734 dbgs() << " and " << NumTo-1 << " other values\n";
735 for (unsigned i = 0, e = NumTo; i != e; ++i)
736 assert((!To[i].getNode() ||
737 N->getValueType(i) == To[i].getValueType()) &&
738 "Cannot combine value to value of different type!"));
739 WorkListRemover DeadNodes(*this);
740 DAG.ReplaceAllUsesWith(N, To);
742 // Push the new nodes and any users onto the worklist
743 for (unsigned i = 0, e = NumTo; i != e; ++i) {
744 if (To[i].getNode()) {
745 AddToWorkList(To[i].getNode());
746 AddUsersToWorkList(To[i].getNode());
751 // Finally, if the node is now dead, remove it from the graph. The node
752 // may not be dead if the replacement process recursively simplified to
753 // something else needing this node.
754 if (N->use_empty()) {
755 // Nodes can be reintroduced into the worklist. Make sure we do not
756 // process a node that has been replaced.
757 removeFromWorkList(N);
759 // Finally, since the node is now dead, remove it from the graph.
762 return SDValue(N, 0);
766 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
767 // Replace all uses. If any nodes become isomorphic to other nodes and
768 // are deleted, make sure to remove them from our worklist.
769 WorkListRemover DeadNodes(*this);
770 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
772 // Push the new node and any (possibly new) users onto the worklist.
773 AddToWorkList(TLO.New.getNode());
774 AddUsersToWorkList(TLO.New.getNode());
776 // Finally, if the node is now dead, remove it from the graph. The node
777 // may not be dead if the replacement process recursively simplified to
778 // something else needing this node.
779 if (TLO.Old.getNode()->use_empty()) {
780 removeFromWorkList(TLO.Old.getNode());
782 // If the operands of this node are only used by the node, they will now
783 // be dead. Make sure to visit them first to delete dead nodes early.
784 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
785 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
786 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
788 DAG.DeleteNode(TLO.Old.getNode());
792 /// SimplifyDemandedBits - Check the specified integer node value to see if
793 /// it can be simplified or if things it uses can be simplified by bit
794 /// propagation. If so, return true.
795 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
796 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
797 APInt KnownZero, KnownOne;
798 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
802 AddToWorkList(Op.getNode());
804 // Replace the old value with the new one.
806 DEBUG(dbgs() << "\nReplacing.2 ";
807 TLO.Old.getNode()->dump(&DAG);
808 dbgs() << "\nWith: ";
809 TLO.New.getNode()->dump(&DAG);
812 CommitTargetLoweringOpt(TLO);
816 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
818 EVT VT = Load->getValueType(0);
819 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
821 DEBUG(dbgs() << "\nReplacing.9 ";
823 dbgs() << "\nWith: ";
824 Trunc.getNode()->dump(&DAG);
826 WorkListRemover DeadNodes(*this);
827 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
828 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
829 removeFromWorkList(Load);
830 DAG.DeleteNode(Load);
831 AddToWorkList(Trunc.getNode());
834 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
838 EVT MemVT = LD->getMemoryVT();
839 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
840 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
842 : LD->getExtensionType();
844 return DAG.getExtLoad(ExtType, dl, PVT,
845 LD->getChain(), LD->getBasePtr(),
846 MemVT, LD->getMemOperand());
849 unsigned Opc = Op.getOpcode();
852 case ISD::AssertSext:
853 return DAG.getNode(ISD::AssertSext, dl, PVT,
854 SExtPromoteOperand(Op.getOperand(0), PVT),
856 case ISD::AssertZext:
857 return DAG.getNode(ISD::AssertZext, dl, PVT,
858 ZExtPromoteOperand(Op.getOperand(0), PVT),
860 case ISD::Constant: {
862 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
863 return DAG.getNode(ExtOpc, dl, PVT, Op);
867 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
869 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
872 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
873 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
875 EVT OldVT = Op.getValueType();
877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
879 if (NewOp.getNode() == 0)
881 AddToWorkList(NewOp.getNode());
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
886 DAG.getValueType(OldVT));
889 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
890 EVT OldVT = Op.getValueType();
892 bool Replace = false;
893 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
894 if (NewOp.getNode() == 0)
896 AddToWorkList(NewOp.getNode());
899 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
900 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
903 /// PromoteIntBinOp - Promote the specified integer binary operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
907 if (!LegalOperations)
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
914 // If operation type is 'undesirable', e.g. i16 on x86, consider
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924 assert(PVT != VT && "Don't know what type to promote to!");
926 bool Replace0 = false;
927 SDValue N0 = Op.getOperand(0);
928 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
929 if (NN0.getNode() == 0)
932 bool Replace1 = false;
933 SDValue N1 = Op.getOperand(1);
938 NN1 = PromoteOperand(N1, PVT, Replace1);
939 if (NN1.getNode() == 0)
943 AddToWorkList(NN0.getNode());
945 AddToWorkList(NN1.getNode());
948 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
950 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
955 return DAG.getNode(ISD::TRUNCATE, dl, VT,
956 DAG.getNode(Opc, dl, PVT, NN0, NN1));
961 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
962 /// target indicates it is beneficial. e.g. On x86, it's usually better to
963 /// promote i16 operations to i32 since i16 instructions are longer.
964 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
965 if (!LegalOperations)
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
972 // If operation type is 'undesirable', e.g. i16 on x86, consider
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982 assert(PVT != VT && "Don't know what type to promote to!");
984 bool Replace = false;
985 SDValue N0 = Op.getOperand(0);
987 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
988 else if (Opc == ISD::SRL)
989 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
991 N0 = PromoteOperand(N0, PVT, Replace);
992 if (N0.getNode() == 0)
995 AddToWorkList(N0.getNode());
997 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
999 DEBUG(dbgs() << "\nPromoting ";
1000 Op.getNode()->dump(&DAG));
1002 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1003 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1008 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1009 if (!LegalOperations)
1012 EVT VT = Op.getValueType();
1013 if (VT.isVector() || !VT.isInteger())
1016 // If operation type is 'undesirable', e.g. i16 on x86, consider
1018 unsigned Opc = Op.getOpcode();
1019 if (TLI.isTypeDesirableForOp(Opc, VT))
1023 // Consult target whether it is a good idea to promote this operation and
1024 // what's the right type to promote it to.
1025 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1026 assert(PVT != VT && "Don't know what type to promote to!");
1027 // fold (aext (aext x)) -> (aext x)
1028 // fold (aext (zext x)) -> (zext x)
1029 // fold (aext (sext x)) -> (sext x)
1030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
1032 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1037 bool DAGCombiner::PromoteLoad(SDValue Op) {
1038 if (!LegalOperations)
1041 EVT VT = Op.getValueType();
1042 if (VT.isVector() || !VT.isInteger())
1045 // If operation type is 'undesirable', e.g. i16 on x86, consider
1047 unsigned Opc = Op.getOpcode();
1048 if (TLI.isTypeDesirableForOp(Opc, VT))
1052 // Consult target whether it is a good idea to promote this operation and
1053 // what's the right type to promote it to.
1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055 assert(PVT != VT && "Don't know what type to promote to!");
1058 SDNode *N = Op.getNode();
1059 LoadSDNode *LD = cast<LoadSDNode>(N);
1060 EVT MemVT = LD->getMemoryVT();
1061 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1062 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1064 : LD->getExtensionType();
1065 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1066 LD->getChain(), LD->getBasePtr(),
1067 MemVT, LD->getMemOperand());
1068 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1070 DEBUG(dbgs() << "\nPromoting ";
1073 Result.getNode()->dump(&DAG);
1075 WorkListRemover DeadNodes(*this);
1076 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1078 removeFromWorkList(N);
1080 AddToWorkList(Result.getNode());
1087 //===----------------------------------------------------------------------===//
1088 // Main DAG Combiner implementation
1089 //===----------------------------------------------------------------------===//
1091 void DAGCombiner::Run(CombineLevel AtLevel) {
1092 // set the instance variables, so that the various visit routines may use it.
1094 LegalOperations = Level >= AfterLegalizeVectorOps;
1095 LegalTypes = Level >= AfterLegalizeTypes;
1097 // Add all the dag nodes to the worklist.
1098 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1099 E = DAG.allnodes_end(); I != E; ++I)
1102 // Create a dummy node (which is not added to allnodes), that adds a reference
1103 // to the root node, preventing it from being deleted, and tracking any
1104 // changes of the root.
1105 HandleSDNode Dummy(DAG.getRoot());
1107 // The root of the dag may dangle to deleted nodes until the dag combiner is
1108 // done. Set it to null to avoid confusion.
1109 DAG.setRoot(SDValue());
1111 // while the worklist isn't empty, find a node and
1112 // try and combine it.
1113 while (!WorkListContents.empty()) {
1115 // The WorkListOrder holds the SDNodes in order, but it may contain
1117 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1118 // worklist *should* contain, and check the node we want to visit is should
1119 // actually be visited.
1121 N = WorkListOrder.pop_back_val();
1122 } while (!WorkListContents.erase(N));
1124 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1125 // N is deleted from the DAG, since they too may now be dead or may have a
1126 // reduced number of uses, allowing other xforms.
1127 if (N->use_empty() && N != &Dummy) {
1128 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1129 AddToWorkList(N->getOperand(i).getNode());
1135 SDValue RV = combine(N);
1137 if (RV.getNode() == 0)
1142 // If we get back the same node we passed in, rather than a new node or
1143 // zero, we know that the node must have defined multiple values and
1144 // CombineTo was used. Since CombineTo takes care of the worklist
1145 // mechanics for us, we have no work to do in this case.
1146 if (RV.getNode() == N)
1149 assert(N->getOpcode() != ISD::DELETED_NODE &&
1150 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1151 "Node was deleted but visit returned new node!");
1153 DEBUG(dbgs() << "\nReplacing.3 ";
1155 dbgs() << "\nWith: ";
1156 RV.getNode()->dump(&DAG);
1159 // Transfer debug value.
1160 DAG.TransferDbgValues(SDValue(N, 0), RV);
1161 WorkListRemover DeadNodes(*this);
1162 if (N->getNumValues() == RV.getNode()->getNumValues())
1163 DAG.ReplaceAllUsesWith(N, RV.getNode());
1165 assert(N->getValueType(0) == RV.getValueType() &&
1166 N->getNumValues() == 1 && "Type mismatch");
1168 DAG.ReplaceAllUsesWith(N, &OpV);
1171 // Push the new node and any users onto the worklist
1172 AddToWorkList(RV.getNode());
1173 AddUsersToWorkList(RV.getNode());
1175 // Add any uses of the old node to the worklist in case this node is the
1176 // last one that uses them. They may become dead after this node is
1178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1179 AddToWorkList(N->getOperand(i).getNode());
1181 // Finally, if the node is now dead, remove it from the graph. The node
1182 // may not be dead if the replacement process recursively simplified to
1183 // something else needing this node.
1184 if (N->use_empty()) {
1185 // Nodes can be reintroduced into the worklist. Make sure we do not
1186 // process a node that has been replaced.
1187 removeFromWorkList(N);
1189 // Finally, since the node is now dead, remove it from the graph.
1194 // If the root changed (e.g. it was a dead load, update the root).
1195 DAG.setRoot(Dummy.getValue());
1196 DAG.RemoveDeadNodes();
1199 SDValue DAGCombiner::visit(SDNode *N) {
1200 switch (N->getOpcode()) {
1202 case ISD::TokenFactor: return visitTokenFactor(N);
1203 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1204 case ISD::ADD: return visitADD(N);
1205 case ISD::SUB: return visitSUB(N);
1206 case ISD::ADDC: return visitADDC(N);
1207 case ISD::SUBC: return visitSUBC(N);
1208 case ISD::ADDE: return visitADDE(N);
1209 case ISD::SUBE: return visitSUBE(N);
1210 case ISD::MUL: return visitMUL(N);
1211 case ISD::SDIV: return visitSDIV(N);
1212 case ISD::UDIV: return visitUDIV(N);
1213 case ISD::SREM: return visitSREM(N);
1214 case ISD::UREM: return visitUREM(N);
1215 case ISD::MULHU: return visitMULHU(N);
1216 case ISD::MULHS: return visitMULHS(N);
1217 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1218 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1219 case ISD::SMULO: return visitSMULO(N);
1220 case ISD::UMULO: return visitUMULO(N);
1221 case ISD::SDIVREM: return visitSDIVREM(N);
1222 case ISD::UDIVREM: return visitUDIVREM(N);
1223 case ISD::AND: return visitAND(N);
1224 case ISD::OR: return visitOR(N);
1225 case ISD::XOR: return visitXOR(N);
1226 case ISD::SHL: return visitSHL(N);
1227 case ISD::SRA: return visitSRA(N);
1228 case ISD::SRL: return visitSRL(N);
1230 case ISD::ROTL: return visitRotate(N);
1231 case ISD::CTLZ: return visitCTLZ(N);
1232 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1233 case ISD::CTTZ: return visitCTTZ(N);
1234 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1235 case ISD::CTPOP: return visitCTPOP(N);
1236 case ISD::SELECT: return visitSELECT(N);
1237 case ISD::VSELECT: return visitVSELECT(N);
1238 case ISD::SELECT_CC: return visitSELECT_CC(N);
1239 case ISD::SETCC: return visitSETCC(N);
1240 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1241 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1242 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1243 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1244 case ISD::TRUNCATE: return visitTRUNCATE(N);
1245 case ISD::BITCAST: return visitBITCAST(N);
1246 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1247 case ISD::FADD: return visitFADD(N);
1248 case ISD::FSUB: return visitFSUB(N);
1249 case ISD::FMUL: return visitFMUL(N);
1250 case ISD::FMA: return visitFMA(N);
1251 case ISD::FDIV: return visitFDIV(N);
1252 case ISD::FREM: return visitFREM(N);
1253 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1254 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1255 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1256 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1257 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1258 case ISD::FP_ROUND: return visitFP_ROUND(N);
1259 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1260 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1261 case ISD::FNEG: return visitFNEG(N);
1262 case ISD::FABS: return visitFABS(N);
1263 case ISD::FFLOOR: return visitFFLOOR(N);
1264 case ISD::FCEIL: return visitFCEIL(N);
1265 case ISD::FTRUNC: return visitFTRUNC(N);
1266 case ISD::BRCOND: return visitBRCOND(N);
1267 case ISD::BR_CC: return visitBR_CC(N);
1268 case ISD::LOAD: return visitLOAD(N);
1269 case ISD::STORE: return visitSTORE(N);
1270 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1271 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1272 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1273 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1274 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1275 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1276 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1281 SDValue DAGCombiner::combine(SDNode *N) {
1282 SDValue RV = visit(N);
1284 // If nothing happened, try a target-specific DAG combine.
1285 if (RV.getNode() == 0) {
1286 assert(N->getOpcode() != ISD::DELETED_NODE &&
1287 "Node was deleted but visit returned NULL!");
1289 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1290 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1292 // Expose the DAG combiner to the target combiner impls.
1293 TargetLowering::DAGCombinerInfo
1294 DagCombineInfo(DAG, Level, false, this);
1296 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1300 // If nothing happened still, try promoting the operation.
1301 if (RV.getNode() == 0) {
1302 switch (N->getOpcode()) {
1310 RV = PromoteIntBinOp(SDValue(N, 0));
1315 RV = PromoteIntShiftOp(SDValue(N, 0));
1317 case ISD::SIGN_EXTEND:
1318 case ISD::ZERO_EXTEND:
1319 case ISD::ANY_EXTEND:
1320 RV = PromoteExtend(SDValue(N, 0));
1323 if (PromoteLoad(SDValue(N, 0)))
1329 // If N is a commutative binary node, try commuting it to enable more
1331 if (RV.getNode() == 0 &&
1332 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1333 N->getNumValues() == 1) {
1334 SDValue N0 = N->getOperand(0);
1335 SDValue N1 = N->getOperand(1);
1337 // Constant operands are canonicalized to RHS.
1338 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1339 SDValue Ops[] = { N1, N0 };
1340 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1343 return SDValue(CSENode, 0);
1350 /// getInputChainForNode - Given a node, return its input chain if it has one,
1351 /// otherwise return a null sd operand.
1352 static SDValue getInputChainForNode(SDNode *N) {
1353 if (unsigned NumOps = N->getNumOperands()) {
1354 if (N->getOperand(0).getValueType() == MVT::Other)
1355 return N->getOperand(0);
1356 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1357 return N->getOperand(NumOps-1);
1358 for (unsigned i = 1; i < NumOps-1; ++i)
1359 if (N->getOperand(i).getValueType() == MVT::Other)
1360 return N->getOperand(i);
1365 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1366 // If N has two operands, where one has an input chain equal to the other,
1367 // the 'other' chain is redundant.
1368 if (N->getNumOperands() == 2) {
1369 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1370 return N->getOperand(0);
1371 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1372 return N->getOperand(1);
1375 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1376 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1377 SmallPtrSet<SDNode*, 16> SeenOps;
1378 bool Changed = false; // If we should replace this token factor.
1380 // Start out with this token factor.
1383 // Iterate through token factors. The TFs grows when new token factors are
1385 for (unsigned i = 0; i < TFs.size(); ++i) {
1386 SDNode *TF = TFs[i];
1388 // Check each of the operands.
1389 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1390 SDValue Op = TF->getOperand(i);
1392 switch (Op.getOpcode()) {
1393 case ISD::EntryToken:
1394 // Entry tokens don't need to be added to the list. They are
1399 case ISD::TokenFactor:
1400 if (Op.hasOneUse() &&
1401 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1402 // Queue up for processing.
1403 TFs.push_back(Op.getNode());
1404 // Clean up in case the token factor is removed.
1405 AddToWorkList(Op.getNode());
1412 // Only add if it isn't already in the list.
1413 if (SeenOps.insert(Op.getNode()))
1424 // If we've change things around then replace token factor.
1427 // The entry token is the only possible outcome.
1428 Result = DAG.getEntryNode();
1430 // New and improved token factor.
1431 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1432 MVT::Other, &Ops[0], Ops.size());
1435 // Don't add users to work list.
1436 return CombineTo(N, Result, false);
1442 /// MERGE_VALUES can always be eliminated.
1443 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1444 WorkListRemover DeadNodes(*this);
1445 // Replacing results may cause a different MERGE_VALUES to suddenly
1446 // be CSE'd with N, and carry its uses with it. Iterate until no
1447 // uses remain, to ensure that the node can be safely deleted.
1448 // First add the users of this node to the work list so that they
1449 // can be tried again once they have new operands.
1450 AddUsersToWorkList(N);
1452 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1454 } while (!N->use_empty());
1455 removeFromWorkList(N);
1457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1461 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1462 SelectionDAG &DAG) {
1463 EVT VT = N0.getValueType();
1464 SDValue N00 = N0.getOperand(0);
1465 SDValue N01 = N0.getOperand(1);
1466 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1468 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1469 isa<ConstantSDNode>(N00.getOperand(1))) {
1470 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1471 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1472 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1473 N00.getOperand(0), N01),
1474 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1475 N00.getOperand(1), N01));
1476 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1482 SDValue DAGCombiner::visitADD(SDNode *N) {
1483 SDValue N0 = N->getOperand(0);
1484 SDValue N1 = N->getOperand(1);
1485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1486 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1487 EVT VT = N0.getValueType();
1490 if (VT.isVector()) {
1491 SDValue FoldedVOp = SimplifyVBinOp(N);
1492 if (FoldedVOp.getNode()) return FoldedVOp;
1494 // fold (add x, 0) -> x, vector edition
1495 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1497 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1501 // fold (add x, undef) -> undef
1502 if (N0.getOpcode() == ISD::UNDEF)
1504 if (N1.getOpcode() == ISD::UNDEF)
1506 // fold (add c1, c2) -> c1+c2
1508 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1509 // canonicalize constant to RHS
1511 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1512 // fold (add x, 0) -> x
1513 if (N1C && N1C->isNullValue())
1515 // fold (add Sym, c) -> Sym+c
1516 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1517 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1518 GA->getOpcode() == ISD::GlobalAddress)
1519 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1521 (uint64_t)N1C->getSExtValue());
1522 // fold ((c1-A)+c2) -> (c1+c2)-A
1523 if (N1C && N0.getOpcode() == ISD::SUB)
1524 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1525 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1526 DAG.getConstant(N1C->getAPIntValue()+
1527 N0C->getAPIntValue(), VT),
1530 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1531 if (RADD.getNode() != 0)
1533 // fold ((0-A) + B) -> B-A
1534 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1535 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1536 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1537 // fold (A + (0-B)) -> A-B
1538 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1539 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1540 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1541 // fold (A+(B-A)) -> B
1542 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1543 return N1.getOperand(0);
1544 // fold ((B-A)+A) -> B
1545 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1546 return N0.getOperand(0);
1547 // fold (A+(B-(A+C))) to (B-C)
1548 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1549 N0 == N1.getOperand(1).getOperand(0))
1550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1551 N1.getOperand(1).getOperand(1));
1552 // fold (A+(B-(C+A))) to (B-C)
1553 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1554 N0 == N1.getOperand(1).getOperand(1))
1555 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1556 N1.getOperand(1).getOperand(0));
1557 // fold (A+((B-A)+or-C)) to (B+or-C)
1558 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1559 N1.getOperand(0).getOpcode() == ISD::SUB &&
1560 N0 == N1.getOperand(0).getOperand(1))
1561 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1562 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1564 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1565 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1566 SDValue N00 = N0.getOperand(0);
1567 SDValue N01 = N0.getOperand(1);
1568 SDValue N10 = N1.getOperand(0);
1569 SDValue N11 = N1.getOperand(1);
1571 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1572 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1573 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1574 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1577 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1578 return SDValue(N, 0);
1580 // fold (a+b) -> (a|b) iff a and b share no bits.
1581 if (VT.isInteger() && !VT.isVector()) {
1582 APInt LHSZero, LHSOne;
1583 APInt RHSZero, RHSOne;
1584 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1586 if (LHSZero.getBoolValue()) {
1587 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1589 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1590 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1591 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1592 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1593 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1598 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1599 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1600 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1601 if (Result.getNode()) return Result;
1603 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1604 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1605 if (Result.getNode()) return Result;
1608 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1609 if (N1.getOpcode() == ISD::SHL &&
1610 N1.getOperand(0).getOpcode() == ISD::SUB)
1611 if (ConstantSDNode *C =
1612 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1613 if (C->getAPIntValue() == 0)
1614 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1615 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1616 N1.getOperand(0).getOperand(1),
1618 if (N0.getOpcode() == ISD::SHL &&
1619 N0.getOperand(0).getOpcode() == ISD::SUB)
1620 if (ConstantSDNode *C =
1621 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1622 if (C->getAPIntValue() == 0)
1623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1624 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1625 N0.getOperand(0).getOperand(1),
1628 if (N1.getOpcode() == ISD::AND) {
1629 SDValue AndOp0 = N1.getOperand(0);
1630 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1631 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1632 unsigned DestBits = VT.getScalarType().getSizeInBits();
1634 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1635 // and similar xforms where the inner op is either ~0 or 0.
1636 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1638 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1642 // add (sext i1), X -> sub X, (zext i1)
1643 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1644 N0.getOperand(0).getValueType() == MVT::i1 &&
1645 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1647 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1648 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1654 SDValue DAGCombiner::visitADDC(SDNode *N) {
1655 SDValue N0 = N->getOperand(0);
1656 SDValue N1 = N->getOperand(1);
1657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1659 EVT VT = N0.getValueType();
1661 // If the flag result is dead, turn this into an ADD.
1662 if (!N->hasAnyUseOfValue(1))
1663 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1664 DAG.getNode(ISD::CARRY_FALSE,
1665 SDLoc(N), MVT::Glue));
1667 // canonicalize constant to RHS.
1669 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1671 // fold (addc x, 0) -> x + no carry out
1672 if (N1C && N1C->isNullValue())
1673 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1674 SDLoc(N), MVT::Glue));
1676 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1677 APInt LHSZero, LHSOne;
1678 APInt RHSZero, RHSOne;
1679 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1681 if (LHSZero.getBoolValue()) {
1682 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1684 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1685 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1686 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1687 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1688 DAG.getNode(ISD::CARRY_FALSE,
1689 SDLoc(N), MVT::Glue));
1695 SDValue DAGCombiner::visitADDE(SDNode *N) {
1696 SDValue N0 = N->getOperand(0);
1697 SDValue N1 = N->getOperand(1);
1698 SDValue CarryIn = N->getOperand(2);
1699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1702 // canonicalize constant to RHS
1704 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1707 // fold (adde x, y, false) -> (addc x, y)
1708 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1709 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1714 // Since it may not be valid to emit a fold to zero for vector initializers
1715 // check if we can before folding.
1716 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1718 bool LegalOperations, bool LegalTypes) {
1720 return DAG.getConstant(0, VT);
1721 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1722 return DAG.getConstant(0, VT);
1726 SDValue DAGCombiner::visitSUB(SDNode *N) {
1727 SDValue N0 = N->getOperand(0);
1728 SDValue N1 = N->getOperand(1);
1729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1731 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1732 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1733 EVT VT = N0.getValueType();
1736 if (VT.isVector()) {
1737 SDValue FoldedVOp = SimplifyVBinOp(N);
1738 if (FoldedVOp.getNode()) return FoldedVOp;
1740 // fold (sub x, 0) -> x, vector edition
1741 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1745 // fold (sub x, x) -> 0
1746 // FIXME: Refactor this and xor and other similar operations together.
1748 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1749 // fold (sub c1, c2) -> c1-c2
1751 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1752 // fold (sub x, c) -> (add x, -c)
1754 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1755 DAG.getConstant(-N1C->getAPIntValue(), VT));
1756 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1757 if (N0C && N0C->isAllOnesValue())
1758 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1759 // fold A-(A-B) -> B
1760 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1761 return N1.getOperand(1);
1762 // fold (A+B)-A -> B
1763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1764 return N0.getOperand(1);
1765 // fold (A+B)-B -> A
1766 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1767 return N0.getOperand(0);
1768 // fold C2-(A+C1) -> (C2-C1)-A
1769 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1770 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1775 // fold ((A+(B+or-C))-B) -> A+or-C
1776 if (N0.getOpcode() == ISD::ADD &&
1777 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1778 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1779 N0.getOperand(1).getOperand(0) == N1)
1780 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1781 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1782 // fold ((A+(C+B))-B) -> A+C
1783 if (N0.getOpcode() == ISD::ADD &&
1784 N0.getOperand(1).getOpcode() == ISD::ADD &&
1785 N0.getOperand(1).getOperand(1) == N1)
1786 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1788 // fold ((A-(B-C))-C) -> A-B
1789 if (N0.getOpcode() == ISD::SUB &&
1790 N0.getOperand(1).getOpcode() == ISD::SUB &&
1791 N0.getOperand(1).getOperand(1) == N1)
1792 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1793 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1795 // If either operand of a sub is undef, the result is undef
1796 if (N0.getOpcode() == ISD::UNDEF)
1798 if (N1.getOpcode() == ISD::UNDEF)
1801 // If the relocation model supports it, consider symbol offsets.
1802 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1803 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1804 // fold (sub Sym, c) -> Sym-c
1805 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1806 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1808 (uint64_t)N1C->getSExtValue());
1809 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1810 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1811 if (GA->getGlobal() == GB->getGlobal())
1812 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1819 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1820 SDValue N0 = N->getOperand(0);
1821 SDValue N1 = N->getOperand(1);
1822 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1824 EVT VT = N0.getValueType();
1826 // If the flag result is dead, turn this into an SUB.
1827 if (!N->hasAnyUseOfValue(1))
1828 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1832 // fold (subc x, x) -> 0 + no borrow
1834 return CombineTo(N, DAG.getConstant(0, VT),
1835 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1838 // fold (subc x, 0) -> x + no borrow
1839 if (N1C && N1C->isNullValue())
1840 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1843 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1844 if (N0C && N0C->isAllOnesValue())
1845 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1846 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1852 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 SDValue CarryIn = N->getOperand(2);
1857 // fold (sube x, y, false) -> (subc x, y)
1858 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1859 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1864 SDValue DAGCombiner::visitMUL(SDNode *N) {
1865 SDValue N0 = N->getOperand(0);
1866 SDValue N1 = N->getOperand(1);
1867 EVT VT = N0.getValueType();
1869 // fold (mul x, undef) -> 0
1870 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1871 return DAG.getConstant(0, VT);
1873 bool N0IsConst = false;
1874 bool N1IsConst = false;
1875 APInt ConstValue0, ConstValue1;
1877 if (VT.isVector()) {
1878 SDValue FoldedVOp = SimplifyVBinOp(N);
1879 if (FoldedVOp.getNode()) return FoldedVOp;
1881 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1882 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1884 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1885 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1887 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1888 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1892 // fold (mul c1, c2) -> c1*c2
1893 if (N0IsConst && N1IsConst)
1894 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1896 // canonicalize constant to RHS
1897 if (N0IsConst && !N1IsConst)
1898 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1899 // fold (mul x, 0) -> 0
1900 if (N1IsConst && ConstValue1 == 0)
1902 // We require a splat of the entire scalar bit width for non-contiguous
1905 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1906 // fold (mul x, 1) -> x
1907 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1909 // fold (mul x, -1) -> 0-x
1910 if (N1IsConst && ConstValue1.isAllOnesValue())
1911 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1912 DAG.getConstant(0, VT), N0);
1913 // fold (mul x, (1 << c)) -> x << c
1914 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1915 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1916 DAG.getConstant(ConstValue1.logBase2(),
1917 getShiftAmountTy(N0.getValueType())));
1918 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1919 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1920 unsigned Log2Val = (-ConstValue1).logBase2();
1921 // FIXME: If the input is something that is easily negated (e.g. a
1922 // single-use add), we should put the negate there.
1923 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1924 DAG.getConstant(0, VT),
1925 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1926 DAG.getConstant(Log2Val,
1927 getShiftAmountTy(N0.getValueType()))));
1931 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1932 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1933 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1934 isa<ConstantSDNode>(N0.getOperand(1)))) {
1935 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1936 N1, N0.getOperand(1));
1937 AddToWorkList(C3.getNode());
1938 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1939 N0.getOperand(0), C3);
1942 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1945 SDValue Sh(0,0), Y(0,0);
1946 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1947 if (N0.getOpcode() == ISD::SHL &&
1948 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1949 isa<ConstantSDNode>(N0.getOperand(1))) &&
1950 N0.getNode()->hasOneUse()) {
1952 } else if (N1.getOpcode() == ISD::SHL &&
1953 isa<ConstantSDNode>(N1.getOperand(1)) &&
1954 N1.getNode()->hasOneUse()) {
1959 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1960 Sh.getOperand(0), Y);
1961 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1962 Mul, Sh.getOperand(1));
1966 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1967 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1968 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1969 isa<ConstantSDNode>(N0.getOperand(1))))
1970 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1971 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1972 N0.getOperand(0), N1),
1973 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1974 N0.getOperand(1), N1));
1977 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1978 if (RMUL.getNode() != 0)
1984 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1989 EVT VT = N->getValueType(0);
1992 if (VT.isVector()) {
1993 SDValue FoldedVOp = SimplifyVBinOp(N);
1994 if (FoldedVOp.getNode()) return FoldedVOp;
1997 // fold (sdiv c1, c2) -> c1/c2
1998 if (N0C && N1C && !N1C->isNullValue())
1999 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2000 // fold (sdiv X, 1) -> X
2001 if (N1C && N1C->getAPIntValue() == 1LL)
2003 // fold (sdiv X, -1) -> 0-X
2004 if (N1C && N1C->isAllOnesValue())
2005 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2006 DAG.getConstant(0, VT), N0);
2007 // If we know the sign bits of both operands are zero, strength reduce to a
2008 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2009 if (!VT.isVector()) {
2010 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2011 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2014 // fold (sdiv X, pow2) -> simple ops after legalize
2015 if (N1C && !N1C->isNullValue() &&
2016 (N1C->getAPIntValue().isPowerOf2() ||
2017 (-N1C->getAPIntValue()).isPowerOf2())) {
2018 // If dividing by powers of two is cheap, then don't perform the following
2020 if (TLI.isPow2DivCheap())
2023 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2025 // Splat the sign bit into the register
2026 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2027 DAG.getConstant(VT.getSizeInBits()-1,
2028 getShiftAmountTy(N0.getValueType())));
2029 AddToWorkList(SGN.getNode());
2031 // Add (N0 < 0) ? abs2 - 1 : 0;
2032 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2033 DAG.getConstant(VT.getSizeInBits() - lg2,
2034 getShiftAmountTy(SGN.getValueType())));
2035 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2036 AddToWorkList(SRL.getNode());
2037 AddToWorkList(ADD.getNode()); // Divide by pow2
2038 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2039 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2041 // If we're dividing by a positive value, we're done. Otherwise, we must
2042 // negate the result.
2043 if (N1C->getAPIntValue().isNonNegative())
2046 AddToWorkList(SRA.getNode());
2047 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2048 DAG.getConstant(0, VT), SRA);
2051 // if integer divide is expensive and we satisfy the requirements, emit an
2052 // alternate sequence.
2053 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2054 SDValue Op = BuildSDIV(N);
2055 if (Op.getNode()) return Op;
2059 if (N0.getOpcode() == ISD::UNDEF)
2060 return DAG.getConstant(0, VT);
2061 // X / undef -> undef
2062 if (N1.getOpcode() == ISD::UNDEF)
2068 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2069 SDValue N0 = N->getOperand(0);
2070 SDValue N1 = N->getOperand(1);
2071 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2073 EVT VT = N->getValueType(0);
2076 if (VT.isVector()) {
2077 SDValue FoldedVOp = SimplifyVBinOp(N);
2078 if (FoldedVOp.getNode()) return FoldedVOp;
2081 // fold (udiv c1, c2) -> c1/c2
2082 if (N0C && N1C && !N1C->isNullValue())
2083 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2084 // fold (udiv x, (1 << c)) -> x >>u c
2085 if (N1C && N1C->getAPIntValue().isPowerOf2())
2086 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2087 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2088 getShiftAmountTy(N0.getValueType())));
2089 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2090 if (N1.getOpcode() == ISD::SHL) {
2091 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2092 if (SHC->getAPIntValue().isPowerOf2()) {
2093 EVT ADDVT = N1.getOperand(1).getValueType();
2094 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2096 DAG.getConstant(SHC->getAPIntValue()
2099 AddToWorkList(Add.getNode());
2100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2104 // fold (udiv x, c) -> alternate
2105 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2106 SDValue Op = BuildUDIV(N);
2107 if (Op.getNode()) return Op;
2111 if (N0.getOpcode() == ISD::UNDEF)
2112 return DAG.getConstant(0, VT);
2113 // X / undef -> undef
2114 if (N1.getOpcode() == ISD::UNDEF)
2120 SDValue DAGCombiner::visitSREM(SDNode *N) {
2121 SDValue N0 = N->getOperand(0);
2122 SDValue N1 = N->getOperand(1);
2123 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2124 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2125 EVT VT = N->getValueType(0);
2127 // fold (srem c1, c2) -> c1%c2
2128 if (N0C && N1C && !N1C->isNullValue())
2129 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2130 // If we know the sign bits of both operands are zero, strength reduce to a
2131 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2132 if (!VT.isVector()) {
2133 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2137 // If X/C can be simplified by the division-by-constant logic, lower
2138 // X%C to the equivalent of X-X/C*C.
2139 if (N1C && !N1C->isNullValue()) {
2140 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2141 AddToWorkList(Div.getNode());
2142 SDValue OptimizedDiv = combine(Div.getNode());
2143 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2144 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2146 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2147 AddToWorkList(Mul.getNode());
2153 if (N0.getOpcode() == ISD::UNDEF)
2154 return DAG.getConstant(0, VT);
2155 // X % undef -> undef
2156 if (N1.getOpcode() == ISD::UNDEF)
2162 SDValue DAGCombiner::visitUREM(SDNode *N) {
2163 SDValue N0 = N->getOperand(0);
2164 SDValue N1 = N->getOperand(1);
2165 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2166 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2167 EVT VT = N->getValueType(0);
2169 // fold (urem c1, c2) -> c1%c2
2170 if (N0C && N1C && !N1C->isNullValue())
2171 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2172 // fold (urem x, pow2) -> (and x, pow2-1)
2173 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2174 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2175 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2176 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2177 if (N1.getOpcode() == ISD::SHL) {
2178 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2179 if (SHC->getAPIntValue().isPowerOf2()) {
2181 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2182 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2184 AddToWorkList(Add.getNode());
2185 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2190 // If X/C can be simplified by the division-by-constant logic, lower
2191 // X%C to the equivalent of X-X/C*C.
2192 if (N1C && !N1C->isNullValue()) {
2193 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2194 AddToWorkList(Div.getNode());
2195 SDValue OptimizedDiv = combine(Div.getNode());
2196 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2197 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2199 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2200 AddToWorkList(Mul.getNode());
2206 if (N0.getOpcode() == ISD::UNDEF)
2207 return DAG.getConstant(0, VT);
2208 // X % undef -> undef
2209 if (N1.getOpcode() == ISD::UNDEF)
2215 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2216 SDValue N0 = N->getOperand(0);
2217 SDValue N1 = N->getOperand(1);
2218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2219 EVT VT = N->getValueType(0);
2222 // fold (mulhs x, 0) -> 0
2223 if (N1C && N1C->isNullValue())
2225 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2226 if (N1C && N1C->getAPIntValue() == 1)
2227 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2228 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2229 getShiftAmountTy(N0.getValueType())));
2230 // fold (mulhs x, undef) -> 0
2231 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2232 return DAG.getConstant(0, VT);
2234 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2236 if (VT.isSimple() && !VT.isVector()) {
2237 MVT Simple = VT.getSimpleVT();
2238 unsigned SimpleSize = Simple.getSizeInBits();
2239 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2240 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2241 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2242 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2243 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2244 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2245 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2246 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2253 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
2256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2257 EVT VT = N->getValueType(0);
2260 // fold (mulhu x, 0) -> 0
2261 if (N1C && N1C->isNullValue())
2263 // fold (mulhu x, 1) -> 0
2264 if (N1C && N1C->getAPIntValue() == 1)
2265 return DAG.getConstant(0, N0.getValueType());
2266 // fold (mulhu x, undef) -> 0
2267 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2268 return DAG.getConstant(0, VT);
2270 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2272 if (VT.isSimple() && !VT.isVector()) {
2273 MVT Simple = VT.getSimpleVT();
2274 unsigned SimpleSize = Simple.getSizeInBits();
2275 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2278 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2279 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2281 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2282 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2289 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2290 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2291 /// that are being performed. Return true if a simplification was made.
2293 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2295 // If the high half is not needed, just compute the low half.
2296 bool HiExists = N->hasAnyUseOfValue(1);
2298 (!LegalOperations ||
2299 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2300 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2301 N->op_begin(), N->getNumOperands());
2302 return CombineTo(N, Res, Res);
2305 // If the low half is not needed, just compute the high half.
2306 bool LoExists = N->hasAnyUseOfValue(0);
2308 (!LegalOperations ||
2309 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2310 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2311 N->op_begin(), N->getNumOperands());
2312 return CombineTo(N, Res, Res);
2315 // If both halves are used, return as it is.
2316 if (LoExists && HiExists)
2319 // If the two computed results can be simplified separately, separate them.
2321 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2322 N->op_begin(), N->getNumOperands());
2323 AddToWorkList(Lo.getNode());
2324 SDValue LoOpt = combine(Lo.getNode());
2325 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2326 (!LegalOperations ||
2327 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2328 return CombineTo(N, LoOpt, LoOpt);
2332 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2333 N->op_begin(), N->getNumOperands());
2334 AddToWorkList(Hi.getNode());
2335 SDValue HiOpt = combine(Hi.getNode());
2336 if (HiOpt.getNode() && HiOpt != Hi &&
2337 (!LegalOperations ||
2338 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2339 return CombineTo(N, HiOpt, HiOpt);
2345 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2347 if (Res.getNode()) return Res;
2349 EVT VT = N->getValueType(0);
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2360 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362 // Compute the high part as N1.
2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366 // Compute the low part as N0.
2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368 return CombineTo(N, Lo, Hi);
2375 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2377 if (Res.getNode()) return Res;
2379 EVT VT = N->getValueType(0);
2382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2390 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2391 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2392 // Compute the high part as N1.
2393 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2394 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2395 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2396 // Compute the low part as N0.
2397 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2398 return CombineTo(N, Lo, Hi);
2405 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2406 // (smulo x, 2) -> (saddo x, x)
2407 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408 if (C2->getAPIntValue() == 2)
2409 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2410 N->getOperand(0), N->getOperand(0));
2415 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2416 // (umulo x, 2) -> (uaddo x, x)
2417 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2418 if (C2->getAPIntValue() == 2)
2419 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2420 N->getOperand(0), N->getOperand(0));
2425 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2427 if (Res.getNode()) return Res;
2432 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2433 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2434 if (Res.getNode()) return Res;
2439 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2440 /// two operands of the same opcode, try to simplify it.
2441 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2442 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2443 EVT VT = N0.getValueType();
2444 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2446 // Bail early if none of these transforms apply.
2447 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2449 // For each of OP in AND/OR/XOR:
2450 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2451 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2452 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2453 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2455 // do not sink logical op inside of a vector extend, since it may combine
2457 EVT Op0VT = N0.getOperand(0).getValueType();
2458 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2459 N0.getOpcode() == ISD::SIGN_EXTEND ||
2460 // Avoid infinite looping with PromoteIntBinOp.
2461 (N0.getOpcode() == ISD::ANY_EXTEND &&
2462 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2463 (N0.getOpcode() == ISD::TRUNCATE &&
2464 (!TLI.isZExtFree(VT, Op0VT) ||
2465 !TLI.isTruncateFree(Op0VT, VT)) &&
2466 TLI.isTypeLegal(Op0VT))) &&
2468 Op0VT == N1.getOperand(0).getValueType() &&
2469 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2470 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2471 N0.getOperand(0).getValueType(),
2472 N0.getOperand(0), N1.getOperand(0));
2473 AddToWorkList(ORNode.getNode());
2474 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2477 // For each of OP in SHL/SRL/SRA/AND...
2478 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2479 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2480 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2481 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2482 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2483 N0.getOperand(1) == N1.getOperand(1)) {
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,
2489 ORNode, N0.getOperand(1));
2492 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2493 // Only perform this optimization after type legalization and before
2494 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2495 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2496 // we don't want to undo this promotion.
2497 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2499 if ((N0.getOpcode() == ISD::BITCAST ||
2500 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2501 Level == AfterLegalizeTypes) {
2502 SDValue In0 = N0.getOperand(0);
2503 SDValue In1 = N1.getOperand(0);
2504 EVT In0Ty = In0.getValueType();
2505 EVT In1Ty = In1.getValueType();
2507 // If both incoming values are integers, and the original types are the
2509 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2510 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2511 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2512 AddToWorkList(Op.getNode());
2517 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2518 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2519 // If both shuffles use the same mask, and both shuffle within a single
2520 // vector, then it is worthwhile to move the swizzle after the operation.
2521 // The type-legalizer generates this pattern when loading illegal
2522 // vector types from memory. In many cases this allows additional shuffle
2524 // There are other cases where moving the shuffle after the xor/and/or
2525 // is profitable even if shuffles don't perform a swizzle.
2526 // If both shuffles use the same mask, and both shuffles have the same first
2527 // or second operand, then it might still be profitable to move the shuffle
2528 // after the xor/and/or operation.
2529 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2533 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2534 "Inputs to shuffles are not the same type");
2536 // Check that both shuffles use the same mask. The masks are known to be of
2537 // the same length because the result vector type is the same.
2538 // Check also that shuffles have only one use to avoid introducing extra
2540 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2541 SVN0->getMask().equals(SVN1->getMask())) {
2542 SDValue ShOp = N0->getOperand(1);
2544 // Don't try to fold this node if it requires introducing a
2545 // build vector of all zeros that might be illegal at this stage.
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2548 ShOp = DAG.getConstant(0, VT);
2553 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2554 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2555 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2556 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(0), N1->getOperand(0));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2561 &SVN0->getMask()[0]);
2564 // Don't try to fold this node if it requires introducing a
2565 // build vector of all zeros that might be illegal at this stage.
2566 ShOp = N0->getOperand(0);
2567 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2569 ShOp = DAG.getConstant(0, VT);
2574 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2575 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2576 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2577 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2578 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2579 N0->getOperand(1), N1->getOperand(1));
2580 AddToWorkList(NewNode.getNode());
2581 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2582 &SVN0->getMask()[0]);
2590 SDValue DAGCombiner::visitAND(SDNode *N) {
2591 SDValue N0 = N->getOperand(0);
2592 SDValue N1 = N->getOperand(1);
2593 SDValue LL, LR, RL, RR, CC0, CC1;
2594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2596 EVT VT = N1.getValueType();
2597 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2600 if (VT.isVector()) {
2601 SDValue FoldedVOp = SimplifyVBinOp(N);
2602 if (FoldedVOp.getNode()) return FoldedVOp;
2604 // fold (and x, 0) -> 0, vector edition
2605 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2607 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2610 // fold (and x, -1) -> x, vector edition
2611 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2613 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2617 // fold (and x, undef) -> 0
2618 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2619 return DAG.getConstant(0, VT);
2620 // fold (and c1, c2) -> c1&c2
2622 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2623 // canonicalize constant to RHS
2625 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2626 // fold (and x, -1) -> x
2627 if (N1C && N1C->isAllOnesValue())
2629 // if (and x, c) is known to be zero, return 0
2630 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2631 APInt::getAllOnesValue(BitWidth)))
2632 return DAG.getConstant(0, VT);
2634 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2635 if (RAND.getNode() != 0)
2637 // fold (and (or x, C), D) -> D if (C & D) == D
2638 if (N1C && N0.getOpcode() == ISD::OR)
2639 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2640 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2642 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2643 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2644 SDValue N0Op0 = N0.getOperand(0);
2645 APInt Mask = ~N1C->getAPIntValue();
2646 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2647 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2648 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2649 N0.getValueType(), N0Op0);
2651 // Replace uses of the AND with uses of the Zero extend node.
2654 // We actually want to replace all uses of the any_extend with the
2655 // zero_extend, to avoid duplicating things. This will later cause this
2656 // AND to be folded.
2657 CombineTo(N0.getNode(), Zext);
2658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2661 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2662 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2663 // already be zero by virtue of the width of the base type of the load.
2665 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2667 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2668 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2669 N0.getOpcode() == ISD::LOAD) {
2670 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2671 N0 : N0.getOperand(0) );
2673 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2674 // This can be a pure constant or a vector splat, in which case we treat the
2675 // vector as a scalar and use the splat value.
2676 APInt Constant = APInt::getNullValue(1);
2677 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2678 Constant = C->getAPIntValue();
2679 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2680 APInt SplatValue, SplatUndef;
2681 unsigned SplatBitSize;
2683 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2684 SplatBitSize, HasAnyUndefs);
2686 // Undef bits can contribute to a possible optimisation if set, so
2688 SplatValue |= SplatUndef;
2690 // The splat value may be something like "0x00FFFFFF", which means 0 for
2691 // the first vector value and FF for the rest, repeating. We need a mask
2692 // that will apply equally to all members of the vector, so AND all the
2693 // lanes of the constant together.
2694 EVT VT = Vector->getValueType(0);
2695 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2697 // If the splat value has been compressed to a bitlength lower
2698 // than the size of the vector lane, we need to re-expand it to
2700 if (BitWidth > SplatBitSize)
2701 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2702 SplatBitSize < BitWidth;
2703 SplatBitSize = SplatBitSize * 2)
2704 SplatValue |= SplatValue.shl(SplatBitSize);
2706 Constant = APInt::getAllOnesValue(BitWidth);
2707 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2708 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2712 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2713 // actually legal and isn't going to get expanded, else this is a false
2715 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2716 Load->getMemoryVT());
2718 // Resize the constant to the same size as the original memory access before
2719 // extension. If it is still the AllOnesValue then this AND is completely
2722 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2725 switch (Load->getExtensionType()) {
2726 default: B = false; break;
2727 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2729 case ISD::NON_EXTLOAD: B = true; break;
2732 if (B && Constant.isAllOnesValue()) {
2733 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2734 // preserve semantics once we get rid of the AND.
2735 SDValue NewLoad(Load, 0);
2736 if (Load->getExtensionType() == ISD::EXTLOAD) {
2737 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2738 Load->getValueType(0), SDLoc(Load),
2739 Load->getChain(), Load->getBasePtr(),
2740 Load->getOffset(), Load->getMemoryVT(),
2741 Load->getMemOperand());
2742 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2743 if (Load->getNumValues() == 3) {
2744 // PRE/POST_INC loads have 3 values.
2745 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2746 NewLoad.getValue(2) };
2747 CombineTo(Load, To, 3, true);
2749 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2753 // Fold the AND away, taking care not to fold to the old load node if we
2755 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2760 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2761 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2762 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2763 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2765 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2766 LL.getValueType().isInteger()) {
2767 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2768 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770 LR.getValueType(), LL, RL);
2771 AddToWorkList(ORNode.getNode());
2772 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2774 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2775 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2776 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2777 LR.getValueType(), LL, RL);
2778 AddToWorkList(ANDNode.getNode());
2779 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2781 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2782 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
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);
2789 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2790 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2791 Op0 == Op1 && LL.getValueType().isInteger() &&
2792 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2793 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2794 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2795 cast<ConstantSDNode>(RR)->isNullValue()))) {
2796 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2797 LL, DAG.getConstant(1, LL.getValueType()));
2798 AddToWorkList(ADDNode.getNode());
2799 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2800 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2802 // canonicalize equivalent to ll == rl
2803 if (LL == RR && LR == RL) {
2804 Op1 = ISD::getSetCCSwappedOperands(Op1);
2807 if (LL == RL && LR == RR) {
2808 bool isInteger = LL.getValueType().isInteger();
2809 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2810 if (Result != ISD::SETCC_INVALID &&
2811 (!LegalOperations ||
2812 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2813 TLI.isOperationLegal(ISD::SETCC,
2814 getSetCCResultType(N0.getSimpleValueType())))))
2815 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2820 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2821 if (N0.getOpcode() == N1.getOpcode()) {
2822 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2823 if (Tmp.getNode()) return Tmp;
2826 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2827 // fold (and (sra)) -> (and (srl)) when possible.
2828 if (!VT.isVector() &&
2829 SimplifyDemandedBits(SDValue(N, 0)))
2830 return SDValue(N, 0);
2832 // fold (zext_inreg (extload x)) -> (zextload x)
2833 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2835 EVT MemVT = LN0->getMemoryVT();
2836 // If we zero all the possible extended bits, then we can turn this into
2837 // a zextload if we are running before legalize or the operation is legal.
2838 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2839 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2840 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2841 ((!LegalOperations && !LN0->isVolatile()) ||
2842 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2843 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2844 LN0->getChain(), LN0->getBasePtr(),
2845 MemVT, LN0->getMemOperand());
2847 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2851 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2852 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2855 EVT MemVT = LN0->getMemoryVT();
2856 // If we zero all the possible extended bits, then we can turn this into
2857 // a zextload if we are running before legalize or the operation is legal.
2858 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2859 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2860 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2861 ((!LegalOperations && !LN0->isVolatile()) ||
2862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2863 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2864 LN0->getChain(), LN0->getBasePtr(),
2865 MemVT, LN0->getMemOperand());
2867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2872 // fold (and (load x), 255) -> (zextload x, i8)
2873 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2874 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2875 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2876 (N0.getOpcode() == ISD::ANY_EXTEND &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2878 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2879 LoadSDNode *LN0 = HasAnyExt
2880 ? cast<LoadSDNode>(N0.getOperand(0))
2881 : cast<LoadSDNode>(N0);
2882 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2883 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2884 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2885 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2886 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2887 EVT LoadedVT = LN0->getMemoryVT();
2889 if (ExtVT == LoadedVT &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2895 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2896 LN0->getMemOperand());
2898 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2902 // Do not change the width of a volatile load.
2903 // Do not generate loads of non-round integer types since these can
2904 // be expensive (and would be wrong if the type is not byte sized).
2905 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2906 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2907 EVT PtrType = LN0->getOperand(1).getValueType();
2909 unsigned Alignment = LN0->getAlignment();
2910 SDValue NewPtr = LN0->getBasePtr();
2912 // For big endian targets, we need to add an offset to the pointer
2913 // to load the correct bytes. For little endian systems, we merely
2914 // need to read fewer bytes from the same pointer.
2915 if (TLI.isBigEndian()) {
2916 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2917 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2918 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2919 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2920 NewPtr, DAG.getConstant(PtrOff, PtrType));
2921 Alignment = MinAlign(Alignment, PtrOff);
2924 AddToWorkList(NewPtr.getNode());
2926 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2928 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2929 LN0->getChain(), NewPtr,
2930 LN0->getPointerInfo(),
2931 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2932 Alignment, LN0->getTBAAInfo());
2934 CombineTo(LN0, Load, Load.getValue(1));
2935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2941 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2942 VT.getSizeInBits() <= 64) {
2943 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2944 APInt ADDC = ADDI->getAPIntValue();
2945 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2947 // immediate for an add, but it is legal if its top c2 bits are set,
2948 // transform the ADD so the immediate doesn't need to be materialized
2950 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2951 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2952 SRLI->getZExtValue());
2953 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2955 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2957 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2958 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2959 CombineTo(N0.getNode(), NewAdd);
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2968 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2969 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2970 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2971 N0.getOperand(1), false);
2972 if (BSwap.getNode())
2979 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2981 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2982 bool DemandHighBits) {
2983 if (!LegalOperations)
2986 EVT VT = N->getValueType(0);
2987 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2989 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2992 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2993 bool LookPassAnd0 = false;
2994 bool LookPassAnd1 = false;
2995 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2997 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2999 if (N0.getOpcode() == ISD::AND) {
3000 if (!N0.getNode()->hasOneUse())
3002 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3003 if (!N01C || N01C->getZExtValue() != 0xFF00)
3005 N0 = N0.getOperand(0);
3006 LookPassAnd0 = true;
3009 if (N1.getOpcode() == ISD::AND) {
3010 if (!N1.getNode()->hasOneUse())
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013 if (!N11C || N11C->getZExtValue() != 0xFF)
3015 N1 = N1.getOperand(0);
3016 LookPassAnd1 = true;
3019 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3021 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3023 if (!N0.getNode()->hasOneUse() ||
3024 !N1.getNode()->hasOneUse())
3027 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3031 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3034 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3035 SDValue N00 = N0->getOperand(0);
3036 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3037 if (!N00.getNode()->hasOneUse())
3039 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3040 if (!N001C || N001C->getZExtValue() != 0xFF)
3042 N00 = N00.getOperand(0);
3043 LookPassAnd0 = true;
3046 SDValue N10 = N1->getOperand(0);
3047 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3048 if (!N10.getNode()->hasOneUse())
3050 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3051 if (!N101C || N101C->getZExtValue() != 0xFF00)
3053 N10 = N10.getOperand(0);
3054 LookPassAnd1 = true;
3060 // Make sure everything beyond the low halfword gets set to zero since the SRL
3061 // 16 will clear the top bits.
3062 unsigned OpSizeInBits = VT.getSizeInBits();
3063 if (DemandHighBits && OpSizeInBits > 16) {
3064 // If the left-shift isn't masked out then the only way this is a bswap is
3065 // if all bits beyond the low 8 are 0. In that case the entire pattern
3066 // reduces to a left shift anyway: leave it for other parts of the combiner.
3070 // However, if the right shift isn't masked out then it might be because
3071 // it's not needed. See if we can spot that too.
3072 if (!LookPassAnd1 &&
3073 !DAG.MaskedValueIsZero(
3074 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3078 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3079 if (OpSizeInBits > 16)
3080 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3081 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3085 /// isBSwapHWordElement - Return true if the specified node is an element
3086 /// that makes up a 32-bit packed halfword byteswap. i.e.
3087 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3088 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3089 if (!N.getNode()->hasOneUse())
3092 unsigned Opc = N.getOpcode();
3093 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3101 switch (N1C->getZExtValue()) {
3104 case 0xFF: Num = 0; break;
3105 case 0xFF00: Num = 1; break;
3106 case 0xFF0000: Num = 2; break;
3107 case 0xFF000000: Num = 3; break;
3110 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3111 SDValue N0 = N.getOperand(0);
3112 if (Opc == ISD::AND) {
3113 if (Num == 0 || Num == 2) {
3115 // (x >> 8) & 0xff0000
3116 if (N0.getOpcode() != ISD::SRL)
3118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119 if (!C || C->getZExtValue() != 8)
3122 // (x << 8) & 0xff00
3123 // (x << 8) & 0xff000000
3124 if (N0.getOpcode() != ISD::SHL)
3126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127 if (!C || C->getZExtValue() != 8)
3130 } else if (Opc == ISD::SHL) {
3132 // (x & 0xff0000) << 8
3133 if (Num != 0 && Num != 2)
3135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136 if (!C || C->getZExtValue() != 8)
3138 } else { // Opc == ISD::SRL
3139 // (x & 0xff00) >> 8
3140 // (x & 0xff000000) >> 8
3141 if (Num != 1 && Num != 3)
3143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3144 if (!C || C->getZExtValue() != 8)
3151 Parts[Num] = N0.getOperand(0).getNode();
3155 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3156 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3157 /// => (rotl (bswap x), 16)
3158 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3159 if (!LegalOperations)
3162 EVT VT = N->getValueType(0);
3165 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3168 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3170 // (or (or (and), (and)), (or (and), (and)))
3171 // (or (or (or (and), (and)), (and)), (and))
3172 if (N0.getOpcode() != ISD::OR)
3174 SDValue N00 = N0.getOperand(0);
3175 SDValue N01 = N0.getOperand(1);
3177 if (N1.getOpcode() == ISD::OR &&
3178 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3179 // (or (or (and), (and)), (or (and), (and)))
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3184 SDValue N001 = N00.getOperand(1);
3185 if (!isBSwapHWordElement(N001, Parts))
3187 SDValue N010 = N01.getOperand(0);
3188 if (!isBSwapHWordElement(N010, Parts))
3190 SDValue N011 = N01.getOperand(1);
3191 if (!isBSwapHWordElement(N011, Parts))
3194 // (or (or (or (and), (and)), (and)), (and))
3195 if (!isBSwapHWordElement(N1, Parts))
3197 if (!isBSwapHWordElement(N01, Parts))
3199 if (N00.getOpcode() != ISD::OR)
3201 SDValue N000 = N00.getOperand(0);
3202 if (!isBSwapHWordElement(N000, Parts))
3204 SDValue N001 = N00.getOperand(1);
3205 if (!isBSwapHWordElement(N001, Parts))
3209 // Make sure the parts are all coming from the same node.
3210 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3213 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3214 SDValue(Parts[0],0));
3216 // Result of the bswap should be rotated by 16. If it's not legal, then
3217 // do (x << 16) | (x >> 16).
3218 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3219 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3220 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3221 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3222 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3223 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3224 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3225 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3228 SDValue DAGCombiner::visitOR(SDNode *N) {
3229 SDValue N0 = N->getOperand(0);
3230 SDValue N1 = N->getOperand(1);
3231 SDValue LL, LR, RL, RR, CC0, CC1;
3232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3234 EVT VT = N1.getValueType();
3237 if (VT.isVector()) {
3238 SDValue FoldedVOp = SimplifyVBinOp(N);
3239 if (FoldedVOp.getNode()) return FoldedVOp;
3241 // fold (or x, 0) -> x, vector edition
3242 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3244 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3247 // fold (or x, -1) -> -1, vector edition
3248 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3250 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3253 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3254 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3255 // Do this only if the resulting shuffle is legal.
3256 if (isa<ShuffleVectorSDNode>(N0) &&
3257 isa<ShuffleVectorSDNode>(N1) &&
3258 N0->getOperand(1) == N1->getOperand(1) &&
3259 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3260 bool CanFold = true;
3261 unsigned NumElts = VT.getVectorNumElements();
3262 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3263 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3264 // We construct two shuffle masks:
3265 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3266 // and N1 as the second operand.
3267 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3268 // and N0 as the second operand.
3269 // We do this because OR is commutable and therefore there might be
3270 // two ways to fold this node into a shuffle.
3271 SmallVector<int,4> Mask1;
3272 SmallVector<int,4> Mask2;
3274 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3275 int M0 = SV0->getMaskElt(i);
3276 int M1 = SV1->getMaskElt(i);
3278 // Both shuffle indexes are undef. Propagate Undef.
3279 if (M0 < 0 && M1 < 0) {
3280 Mask1.push_back(M0);
3281 Mask2.push_back(M0);
3285 if (M0 < 0 || M1 < 0 ||
3286 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3287 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3292 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3293 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3297 // Fold this sequence only if the resulting shuffle is 'legal'.
3298 if (TLI.isShuffleMaskLegal(Mask1, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3300 N1->getOperand(0), &Mask1[0]);
3301 if (TLI.isShuffleMaskLegal(Mask2, VT))
3302 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3303 N0->getOperand(0), &Mask2[0]);
3308 // fold (or x, undef) -> -1
3309 if (!LegalOperations &&
3310 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3311 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3312 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3314 // fold (or c1, c2) -> c1|c2
3316 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3317 // canonicalize constant to RHS
3319 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3320 // fold (or x, 0) -> x
3321 if (N1C && N1C->isNullValue())
3323 // fold (or x, -1) -> -1
3324 if (N1C && N1C->isAllOnesValue())
3326 // fold (or x, c) -> c iff (x & ~c) == 0
3327 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3330 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3331 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3332 if (BSwap.getNode() != 0)
3334 BSwap = MatchBSwapHWordLow(N, N0, N1);
3335 if (BSwap.getNode() != 0)
3339 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3340 if (ROR.getNode() != 0)
3342 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3343 // iff (c1 & c2) == 0.
3344 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3345 isa<ConstantSDNode>(N0.getOperand(1))) {
3346 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3347 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3348 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3352 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3353 N0.getOperand(0), N1), COR);
3356 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3357 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3358 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3359 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3361 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3362 LL.getValueType().isInteger()) {
3363 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3364 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3365 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3366 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3367 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3368 LR.getValueType(), LL, RL);
3369 AddToWorkList(ORNode.getNode());
3370 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3372 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3373 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3374 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3375 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3376 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3377 LR.getValueType(), LL, RL);
3378 AddToWorkList(ANDNode.getNode());
3379 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3382 // canonicalize equivalent to ll == rl
3383 if (LL == RR && LR == RL) {
3384 Op1 = ISD::getSetCCSwappedOperands(Op1);
3387 if (LL == RL && LR == RR) {
3388 bool isInteger = LL.getValueType().isInteger();
3389 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3390 if (Result != ISD::SETCC_INVALID &&
3391 (!LegalOperations ||
3392 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3393 TLI.isOperationLegal(ISD::SETCC,
3394 getSetCCResultType(N0.getValueType())))))
3395 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3400 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3401 if (N0.getOpcode() == N1.getOpcode()) {
3402 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3403 if (Tmp.getNode()) return Tmp;
3406 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3407 if (N0.getOpcode() == ISD::AND &&
3408 N1.getOpcode() == ISD::AND &&
3409 N0.getOperand(1).getOpcode() == ISD::Constant &&
3410 N1.getOperand(1).getOpcode() == ISD::Constant &&
3411 // Don't increase # computations.
3412 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3413 // We can only do this xform if we know that bits from X that are set in C2
3414 // but not in C1 are already zero. Likewise for Y.
3415 const APInt &LHSMask =
3416 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3417 const APInt &RHSMask =
3418 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3420 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3421 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3422 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3423 N0.getOperand(0), N1.getOperand(0));
3424 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3425 DAG.getConstant(LHSMask | RHSMask, VT));
3429 // See if this is some rotate idiom.
3430 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3431 return SDValue(Rot, 0);
3433 // Simplify the operands using demanded-bits information.
3434 if (!VT.isVector() &&
3435 SimplifyDemandedBits(SDValue(N, 0)))
3436 return SDValue(N, 0);
3441 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3442 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3443 if (Op.getOpcode() == ISD::AND) {
3444 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3445 Mask = Op.getOperand(1);
3446 Op = Op.getOperand(0);
3452 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3460 // Return true if we can prove that, whenever Neg and Pos are both in the
3461 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3462 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3464 // (or (shift1 X, Neg), (shift2 X, Pos))
3466 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3467 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3468 // to consider shift amounts with defined behavior.
3469 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3470 // If OpSize is a power of 2 then:
3472 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3473 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3475 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3476 // for the stronger condition:
3478 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3480 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3481 // we can just replace Neg with Neg' for the rest of the function.
3483 // In other cases we check for the even stronger condition:
3485 // Neg == OpSize - Pos [B]
3487 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3488 // behavior if Pos == 0 (and consequently Neg == OpSize).
3490 // We could actually use [A] whenever OpSize is a power of 2, but the
3491 // only extra cases that it would match are those uninteresting ones
3492 // where Neg and Pos are never in range at the same time. E.g. for
3493 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3494 // as well as (sub 32, Pos), but:
3496 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3498 // always invokes undefined behavior for 32-bit X.
3500 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3501 unsigned MaskLoBits = 0;
3502 if (Neg.getOpcode() == ISD::AND &&
3503 isPowerOf2_64(OpSize) &&
3504 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3505 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3506 Neg = Neg.getOperand(0);
3507 MaskLoBits = Log2_64(OpSize);
3510 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3511 if (Neg.getOpcode() != ISD::SUB)
3513 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3516 SDValue NegOp1 = Neg.getOperand(1);
3518 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3519 // Pos'. The truncation is redundant for the purpose of the equality.
3521 Pos.getOpcode() == ISD::AND &&
3522 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3523 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3524 Pos = Pos.getOperand(0);
3526 // The condition we need is now:
3528 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3530 // If NegOp1 == Pos then we need:
3532 // OpSize & Mask == NegC & Mask
3534 // (because "x & Mask" is a truncation and distributes through subtraction).
3537 Width = NegC->getAPIntValue();
3538 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3539 // Then the condition we want to prove becomes:
3541 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3543 // which, again because "x & Mask" is a truncation, becomes:
3545 // NegC & Mask == (OpSize - PosC) & Mask
3546 // OpSize & Mask == (NegC + PosC) & Mask
3547 else if (Pos.getOpcode() == ISD::ADD &&
3548 Pos.getOperand(0) == NegOp1 &&
3549 Pos.getOperand(1).getOpcode() == ISD::Constant)
3550 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3551 NegC->getAPIntValue());
3555 // Now we just need to check that OpSize & Mask == Width & Mask.
3557 // Opsize & Mask is 0 since Mask is Opsize - 1.
3558 return Width.getLoBits(MaskLoBits) == 0;
3559 return Width == OpSize;
3562 // A subroutine of MatchRotate used once we have found an OR of two opposite
3563 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3564 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3565 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3566 // Neg with outer conversions stripped away.
3567 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3568 SDValue Neg, SDValue InnerPos,
3569 SDValue InnerNeg, unsigned PosOpcode,
3570 unsigned NegOpcode, SDLoc DL) {
3571 // fold (or (shl x, (*ext y)),
3572 // (srl x, (*ext (sub 32, y)))) ->
3573 // (rotl x, y) or (rotr x, (sub 32, y))
3575 // fold (or (shl x, (*ext (sub 32, y))),
3576 // (srl x, (*ext y))) ->
3577 // (rotr x, y) or (rotl x, (sub 32, y))
3578 EVT VT = Shifted.getValueType();
3579 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3580 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3581 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3582 HasPos ? Pos : Neg).getNode();
3585 // fold (or (shl (*ext x), (*ext y)),
3586 // (srl (*ext x), (*ext (sub 32, y)))) ->
3587 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3589 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3590 // (srl (*ext x), (*ext y))) ->
3591 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3592 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3593 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3594 SDValue InnerShifted = Shifted.getOperand(0);
3595 EVT InnerVT = InnerShifted.getValueType();
3596 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3597 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3598 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3599 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3600 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3601 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3609 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3610 // idioms for rotate, and if the target supports rotation instructions, generate
3612 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3613 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3614 EVT VT = LHS.getValueType();
3615 if (!TLI.isTypeLegal(VT)) return 0;
3617 // The target must have at least one rotate flavor.
3618 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3619 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3620 if (!HasROTL && !HasROTR) return 0;
3622 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3623 SDValue LHSShift; // The shift.
3624 SDValue LHSMask; // AND value if any.
3625 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3626 return 0; // Not part of a rotate.
3628 SDValue RHSShift; // The shift.
3629 SDValue RHSMask; // AND value if any.
3630 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3631 return 0; // Not part of a rotate.
3633 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3634 return 0; // Not shifting the same value.
3636 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3637 return 0; // Shifts must disagree.
3639 // Canonicalize shl to left side in a shl/srl pair.
3640 if (RHSShift.getOpcode() == ISD::SHL) {
3641 std::swap(LHS, RHS);
3642 std::swap(LHSShift, RHSShift);
3643 std::swap(LHSMask , RHSMask );
3646 unsigned OpSizeInBits = VT.getSizeInBits();
3647 SDValue LHSShiftArg = LHSShift.getOperand(0);
3648 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3649 SDValue RHSShiftArg = RHSShift.getOperand(0);
3650 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3652 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3653 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3654 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3655 RHSShiftAmt.getOpcode() == ISD::Constant) {
3656 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3657 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3658 if ((LShVal + RShVal) != OpSizeInBits)
3661 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3662 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3664 // If there is an AND of either shifted operand, apply it to the result.
3665 if (LHSMask.getNode() || RHSMask.getNode()) {
3666 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3668 if (LHSMask.getNode()) {
3669 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3670 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3672 if (RHSMask.getNode()) {
3673 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3674 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3677 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3680 return Rot.getNode();
3683 // If there is a mask here, and we have a variable shift, we can't be sure
3684 // that we're masking out the right stuff.
3685 if (LHSMask.getNode() || RHSMask.getNode())
3688 // If the shift amount is sign/zext/any-extended just peel it off.
3689 SDValue LExtOp0 = LHSShiftAmt;
3690 SDValue RExtOp0 = RHSShiftAmt;
3691 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3692 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3693 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3694 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3695 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3696 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3697 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3698 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3699 LExtOp0 = LHSShiftAmt.getOperand(0);
3700 RExtOp0 = RHSShiftAmt.getOperand(0);
3703 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3704 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3708 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3709 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3716 SDValue DAGCombiner::visitXOR(SDNode *N) {
3717 SDValue N0 = N->getOperand(0);
3718 SDValue N1 = N->getOperand(1);
3719 SDValue LHS, RHS, CC;
3720 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3721 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3722 EVT VT = N0.getValueType();
3725 if (VT.isVector()) {
3726 SDValue FoldedVOp = SimplifyVBinOp(N);
3727 if (FoldedVOp.getNode()) return FoldedVOp;
3729 // fold (xor x, 0) -> x, vector edition
3730 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3732 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3736 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3737 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3738 return DAG.getConstant(0, VT);
3739 // fold (xor x, undef) -> undef
3740 if (N0.getOpcode() == ISD::UNDEF)
3742 if (N1.getOpcode() == ISD::UNDEF)
3744 // fold (xor c1, c2) -> c1^c2
3746 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3747 // canonicalize constant to RHS
3749 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3750 // fold (xor x, 0) -> x
3751 if (N1C && N1C->isNullValue())
3754 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3755 if (RXOR.getNode() != 0)
3758 // fold !(x cc y) -> (x !cc y)
3759 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3760 bool isInt = LHS.getValueType().isInteger();
3761 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3764 if (!LegalOperations ||
3765 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3766 switch (N0.getOpcode()) {
3768 llvm_unreachable("Unhandled SetCC Equivalent!");
3770 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3771 case ISD::SELECT_CC:
3772 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3773 N0.getOperand(3), NotCC);
3778 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3779 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3780 N0.getNode()->hasOneUse() &&
3781 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3782 SDValue V = N0.getOperand(0);
3783 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3784 DAG.getConstant(1, V.getValueType()));
3785 AddToWorkList(V.getNode());
3786 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3789 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3790 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3791 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3792 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3793 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3794 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3795 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3796 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3797 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3798 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3801 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3802 if (N1C && N1C->isAllOnesValue() &&
3803 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3804 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3805 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3806 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3807 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3808 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3809 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3810 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3813 // fold (xor (and x, y), y) -> (and (not x), y)
3814 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3815 N0->getOperand(1) == N1) {
3816 SDValue X = N0->getOperand(0);
3817 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3818 AddToWorkList(NotX.getNode());
3819 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3821 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3822 if (N1C && N0.getOpcode() == ISD::XOR) {
3823 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3824 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3826 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3827 DAG.getConstant(N1C->getAPIntValue() ^
3828 N00C->getAPIntValue(), VT));
3830 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3831 DAG.getConstant(N1C->getAPIntValue() ^
3832 N01C->getAPIntValue(), VT));
3834 // fold (xor x, x) -> 0
3836 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3838 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3839 if (N0.getOpcode() == N1.getOpcode()) {
3840 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3841 if (Tmp.getNode()) return Tmp;
3844 // Simplify the expression using non-local knowledge.
3845 if (!VT.isVector() &&
3846 SimplifyDemandedBits(SDValue(N, 0)))
3847 return SDValue(N, 0);
3852 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3853 /// the shift amount is a constant.
3854 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3855 // We can't and shouldn't fold opaque constants.
3856 if (Amt->isOpaque())
3859 SDNode *LHS = N->getOperand(0).getNode();
3860 if (!LHS->hasOneUse()) return SDValue();
3862 // We want to pull some binops through shifts, so that we have (and (shift))
3863 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3864 // thing happens with address calculations, so it's important to canonicalize
3866 bool HighBitSet = false; // Can we transform this if the high bit is set?
3868 switch (LHS->getOpcode()) {
3869 default: return SDValue();
3872 HighBitSet = false; // We can only transform sra if the high bit is clear.
3875 HighBitSet = true; // We can only transform sra if the high bit is set.
3878 if (N->getOpcode() != ISD::SHL)
3879 return SDValue(); // only shl(add) not sr[al](add).
3880 HighBitSet = false; // We can only transform sra if the high bit is clear.
3884 // We require the RHS of the binop to be a constant and not opaque as well.
3885 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3886 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3888 // FIXME: disable this unless the input to the binop is a shift by a constant.
3889 // If it is not a shift, it pessimizes some common cases like:
3891 // void foo(int *X, int i) { X[i & 1235] = 1; }
3892 // int bar(int *X, int i) { return X[i & 255]; }
3893 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3894 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3895 BinOpLHSVal->getOpcode() != ISD::SRA &&
3896 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3897 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3900 EVT VT = N->getValueType(0);
3902 // If this is a signed shift right, and the high bit is modified by the
3903 // logical operation, do not perform the transformation. The highBitSet
3904 // boolean indicates the value of the high bit of the constant which would
3905 // cause it to be modified for this operation.
3906 if (N->getOpcode() == ISD::SRA) {
3907 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3908 if (BinOpRHSSignSet != HighBitSet)
3912 // Fold the constants, shifting the binop RHS by the shift amount.
3913 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3915 LHS->getOperand(1), N->getOperand(1));
3916 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3918 // Create the new shift.
3919 SDValue NewShift = DAG.getNode(N->getOpcode(),
3920 SDLoc(LHS->getOperand(0)),
3921 VT, LHS->getOperand(0), N->getOperand(1));
3923 // Create the new binop.
3924 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3927 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3928 assert(N->getOpcode() == ISD::TRUNCATE);
3929 assert(N->getOperand(0).getOpcode() == ISD::AND);
3931 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3932 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3933 SDValue N01 = N->getOperand(0).getOperand(1);
3935 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3936 EVT TruncVT = N->getValueType(0);
3937 SDValue N00 = N->getOperand(0).getOperand(0);
3938 APInt TruncC = N01C->getAPIntValue();
3939 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3941 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3942 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3943 DAG.getConstant(TruncC, TruncVT));
3950 SDValue DAGCombiner::visitRotate(SDNode *N) {
3951 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3952 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3953 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3954 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3955 if (NewOp1.getNode())
3956 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3957 N->getOperand(0), NewOp1);
3962 SDValue DAGCombiner::visitSHL(SDNode *N) {
3963 SDValue N0 = N->getOperand(0);
3964 SDValue N1 = N->getOperand(1);
3965 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3966 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3967 EVT VT = N0.getValueType();
3968 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3971 if (VT.isVector()) {
3972 SDValue FoldedVOp = SimplifyVBinOp(N);
3973 if (FoldedVOp.getNode()) return FoldedVOp;
3975 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3976 // If setcc produces all-one true value then:
3977 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3978 if (N1CV && N1CV->isConstant()) {
3979 if (N0.getOpcode() == ISD::AND &&
3980 TLI.getBooleanContents(true) ==
3981 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3982 SDValue N00 = N0->getOperand(0);
3983 SDValue N01 = N0->getOperand(1);
3984 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3986 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3987 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3989 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3992 N1C = isConstOrConstSplat(N1);
3997 // fold (shl c1, c2) -> c1<<c2
3999 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4000 // fold (shl 0, x) -> 0
4001 if (N0C && N0C->isNullValue())
4003 // fold (shl x, c >= size(x)) -> undef
4004 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4005 return DAG.getUNDEF(VT);
4006 // fold (shl x, 0) -> x
4007 if (N1C && N1C->isNullValue())
4009 // fold (shl undef, x) -> 0
4010 if (N0.getOpcode() == ISD::UNDEF)
4011 return DAG.getConstant(0, VT);
4012 // if (shl x, c) is known to be zero, return 0
4013 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4014 APInt::getAllOnesValue(OpSizeInBits)))
4015 return DAG.getConstant(0, VT);
4016 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4017 if (N1.getOpcode() == ISD::TRUNCATE &&
4018 N1.getOperand(0).getOpcode() == ISD::AND) {
4019 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4020 if (NewOp1.getNode())
4021 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4024 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4025 return SDValue(N, 0);
4027 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4028 if (N1C && N0.getOpcode() == ISD::SHL) {
4029 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4030 uint64_t c1 = N0C1->getZExtValue();
4031 uint64_t c2 = N1C->getZExtValue();
4032 if (c1 + c2 >= OpSizeInBits)
4033 return DAG.getConstant(0, VT);
4034 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4035 DAG.getConstant(c1 + c2, N1.getValueType()));
4039 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4040 // For this to be valid, the second form must not preserve any of the bits
4041 // that are shifted out by the inner shift in the first form. This means
4042 // the outer shift size must be >= the number of bits added by the ext.
4043 // As a corollary, we don't care what kind of ext it is.
4044 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4045 N0.getOpcode() == ISD::ANY_EXTEND ||
4046 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4047 N0.getOperand(0).getOpcode() == ISD::SHL) {
4048 SDValue N0Op0 = N0.getOperand(0);
4049 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4050 uint64_t c1 = N0Op0C1->getZExtValue();
4051 uint64_t c2 = N1C->getZExtValue();
4052 EVT InnerShiftVT = N0Op0.getValueType();
4053 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4054 if (c2 >= OpSizeInBits - InnerShiftSize) {
4055 if (c1 + c2 >= OpSizeInBits)
4056 return DAG.getConstant(0, VT);
4057 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4058 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4059 N0Op0->getOperand(0)),
4060 DAG.getConstant(c1 + c2, N1.getValueType()));
4065 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4066 // Only fold this if the inner zext has no other uses to avoid increasing
4067 // the total number of instructions.
4068 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4069 N0.getOperand(0).getOpcode() == ISD::SRL) {
4070 SDValue N0Op0 = N0.getOperand(0);
4071 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4072 uint64_t c1 = N0Op0C1->getZExtValue();
4073 if (c1 < VT.getScalarSizeInBits()) {
4074 uint64_t c2 = N1C->getZExtValue();
4076 SDValue NewOp0 = N0.getOperand(0);
4077 EVT CountVT = NewOp0.getOperand(1).getValueType();
4078 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4079 NewOp0, DAG.getConstant(c2, CountVT));
4080 AddToWorkList(NewSHL.getNode());
4081 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4087 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4088 // (and (srl x, (sub c1, c2), MASK)
4089 // Only fold this if the inner shift has no other uses -- if it does, folding
4090 // this will increase the total number of instructions.
4091 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4092 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4093 uint64_t c1 = N0C1->getZExtValue();
4094 if (c1 < OpSizeInBits) {
4095 uint64_t c2 = N1C->getZExtValue();
4096 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4099 Mask = Mask.shl(c2 - c1);
4100 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4101 DAG.getConstant(c2 - c1, N1.getValueType()));
4103 Mask = Mask.lshr(c1 - c2);
4104 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4105 DAG.getConstant(c1 - c2, N1.getValueType()));
4107 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4108 DAG.getConstant(Mask, VT));
4112 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4113 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4114 unsigned BitSize = VT.getScalarSizeInBits();
4115 SDValue HiBitsMask =
4116 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4117 BitSize - N1C->getZExtValue()), VT);
4118 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4123 SDValue NewSHL = visitShiftByConstant(N, N1C);
4124 if (NewSHL.getNode())
4131 SDValue DAGCombiner::visitSRA(SDNode *N) {
4132 SDValue N0 = N->getOperand(0);
4133 SDValue N1 = N->getOperand(1);
4134 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4135 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4136 EVT VT = N0.getValueType();
4137 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4140 if (VT.isVector()) {
4141 SDValue FoldedVOp = SimplifyVBinOp(N);
4142 if (FoldedVOp.getNode()) return FoldedVOp;
4144 N1C = isConstOrConstSplat(N1);
4147 // fold (sra c1, c2) -> (sra c1, c2)
4149 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4150 // fold (sra 0, x) -> 0
4151 if (N0C && N0C->isNullValue())
4153 // fold (sra -1, x) -> -1
4154 if (N0C && N0C->isAllOnesValue())
4156 // fold (sra x, (setge c, size(x))) -> undef
4157 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4158 return DAG.getUNDEF(VT);
4159 // fold (sra x, 0) -> x
4160 if (N1C && N1C->isNullValue())
4162 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4164 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4165 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4166 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4168 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4169 ExtVT, VT.getVectorNumElements());
4170 if ((!LegalOperations ||
4171 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4172 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4173 N0.getOperand(0), DAG.getValueType(ExtVT));
4176 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4177 if (N1C && N0.getOpcode() == ISD::SRA) {
4178 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4179 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4180 if (Sum >= OpSizeInBits)
4181 Sum = OpSizeInBits - 1;
4182 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4183 DAG.getConstant(Sum, N1.getValueType()));
4187 // fold (sra (shl X, m), (sub result_size, n))
4188 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4189 // result_size - n != m.
4190 // If truncate is free for the target sext(shl) is likely to result in better
4192 if (N0.getOpcode() == ISD::SHL && N1C) {
4193 // Get the two constanst of the shifts, CN0 = m, CN = n.
4194 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4196 LLVMContext &Ctx = *DAG.getContext();
4197 // Determine what the truncate's result bitsize and type would be.
4198 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4201 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4203 // Determine the residual right-shift amount.
4204 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4206 // If the shift is not a no-op (in which case this should be just a sign
4207 // extend already), the truncated to type is legal, sign_extend is legal
4208 // on that type, and the truncate to that type is both legal and free,
4209 // perform the transform.
4210 if ((ShiftAmt > 0) &&
4211 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4212 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4213 TLI.isTruncateFree(VT, TruncVT)) {
4215 SDValue Amt = DAG.getConstant(ShiftAmt,
4216 getShiftAmountTy(N0.getOperand(0).getValueType()));
4217 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4218 N0.getOperand(0), Amt);
4219 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4221 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4222 N->getValueType(0), Trunc);
4227 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4228 if (N1.getOpcode() == ISD::TRUNCATE &&
4229 N1.getOperand(0).getOpcode() == ISD::AND) {
4230 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4231 if (NewOp1.getNode())
4232 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4235 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4236 // if c1 is equal to the number of bits the trunc removes
4237 if (N0.getOpcode() == ISD::TRUNCATE &&
4238 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4239 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4240 N0.getOperand(0).hasOneUse() &&
4241 N0.getOperand(0).getOperand(1).hasOneUse() &&
4243 SDValue N0Op0 = N0.getOperand(0);
4244 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4245 unsigned LargeShiftVal = LargeShift->getZExtValue();
4246 EVT LargeVT = N0Op0.getValueType();
4248 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4250 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4251 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4252 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4253 N0Op0.getOperand(0), Amt);
4254 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4259 // Simplify, based on bits shifted out of the LHS.
4260 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261 return SDValue(N, 0);
4264 // If the sign bit is known to be zero, switch this to a SRL.
4265 if (DAG.SignBitIsZero(N0))
4266 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4269 SDValue NewSRA = visitShiftByConstant(N, N1C);
4270 if (NewSRA.getNode())
4277 SDValue DAGCombiner::visitSRL(SDNode *N) {
4278 SDValue N0 = N->getOperand(0);
4279 SDValue N1 = N->getOperand(1);
4280 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4282 EVT VT = N0.getValueType();
4283 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4286 if (VT.isVector()) {
4287 SDValue FoldedVOp = SimplifyVBinOp(N);
4288 if (FoldedVOp.getNode()) return FoldedVOp;
4290 N1C = isConstOrConstSplat(N1);
4293 // fold (srl c1, c2) -> c1 >>u c2
4295 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4296 // fold (srl 0, x) -> 0
4297 if (N0C && N0C->isNullValue())
4299 // fold (srl x, c >= size(x)) -> undef
4300 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4301 return DAG.getUNDEF(VT);
4302 // fold (srl x, 0) -> x
4303 if (N1C && N1C->isNullValue())
4305 // if (srl x, c) is known to be zero, return 0
4306 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4307 APInt::getAllOnesValue(OpSizeInBits)))
4308 return DAG.getConstant(0, VT);
4310 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4311 if (N1C && N0.getOpcode() == ISD::SRL) {
4312 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4313 uint64_t c1 = N01C->getZExtValue();
4314 uint64_t c2 = N1C->getZExtValue();
4315 if (c1 + c2 >= OpSizeInBits)
4316 return DAG.getConstant(0, VT);
4317 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4318 DAG.getConstant(c1 + c2, N1.getValueType()));
4322 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4323 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4324 N0.getOperand(0).getOpcode() == ISD::SRL &&
4325 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4327 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4328 uint64_t c2 = N1C->getZExtValue();
4329 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4330 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4331 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4332 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4333 if (c1 + OpSizeInBits == InnerShiftSize) {
4334 if (c1 + c2 >= InnerShiftSize)
4335 return DAG.getConstant(0, VT);
4336 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4337 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4338 N0.getOperand(0)->getOperand(0),
4339 DAG.getConstant(c1 + c2, ShiftCountVT)));
4343 // fold (srl (shl x, c), c) -> (and x, cst2)
4344 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4345 unsigned BitSize = N0.getScalarValueSizeInBits();
4346 if (BitSize <= 64) {
4347 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4348 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4349 DAG.getConstant(~0ULL >> ShAmt, VT));
4353 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4354 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4355 // Shifting in all undef bits?
4356 EVT SmallVT = N0.getOperand(0).getValueType();
4357 unsigned BitSize = SmallVT.getScalarSizeInBits();
4358 if (N1C->getZExtValue() >= BitSize)
4359 return DAG.getUNDEF(VT);
4361 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4362 uint64_t ShiftAmt = N1C->getZExtValue();
4363 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4365 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4366 AddToWorkList(SmallShift.getNode());
4367 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4368 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4369 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4370 DAG.getConstant(Mask, VT));
4374 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4375 // bit, which is unmodified by sra.
4376 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4377 if (N0.getOpcode() == ISD::SRA)
4378 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4381 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4382 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4383 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4384 APInt KnownZero, KnownOne;
4385 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4387 // If any of the input bits are KnownOne, then the input couldn't be all
4388 // zeros, thus the result of the srl will always be zero.
4389 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4391 // If all of the bits input the to ctlz node are known to be zero, then
4392 // the result of the ctlz is "32" and the result of the shift is one.
4393 APInt UnknownBits = ~KnownZero;
4394 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4396 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4397 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4398 // Okay, we know that only that the single bit specified by UnknownBits
4399 // could be set on input to the CTLZ node. If this bit is set, the SRL
4400 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4401 // to an SRL/XOR pair, which is likely to simplify more.
4402 unsigned ShAmt = UnknownBits.countTrailingZeros();
4403 SDValue Op = N0.getOperand(0);
4406 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4407 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4408 AddToWorkList(Op.getNode());
4411 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4412 Op, DAG.getConstant(1, VT));
4416 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4417 if (N1.getOpcode() == ISD::TRUNCATE &&
4418 N1.getOperand(0).getOpcode() == ISD::AND) {
4419 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4420 if (NewOp1.getNode())
4421 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4424 // fold operands of srl based on knowledge that the low bits are not
4426 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4427 return SDValue(N, 0);
4430 SDValue NewSRL = visitShiftByConstant(N, N1C);
4431 if (NewSRL.getNode())
4435 // Attempt to convert a srl of a load into a narrower zero-extending load.
4436 SDValue NarrowLoad = ReduceLoadWidth(N);
4437 if (NarrowLoad.getNode())
4440 // Here is a common situation. We want to optimize:
4443 // %b = and i32 %a, 2
4444 // %c = srl i32 %b, 1
4445 // brcond i32 %c ...
4451 // %c = setcc eq %b, 0
4454 // However when after the source operand of SRL is optimized into AND, the SRL
4455 // itself may not be optimized further. Look for it and add the BRCOND into
4457 if (N->hasOneUse()) {
4458 SDNode *Use = *N->use_begin();
4459 if (Use->getOpcode() == ISD::BRCOND)
4461 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4462 // Also look pass the truncate.
4463 Use = *Use->use_begin();
4464 if (Use->getOpcode() == ISD::BRCOND)
4472 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4473 SDValue N0 = N->getOperand(0);
4474 EVT VT = N->getValueType(0);
4476 // fold (ctlz c1) -> c2
4477 if (isa<ConstantSDNode>(N0))
4478 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4482 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4483 SDValue N0 = N->getOperand(0);
4484 EVT VT = N->getValueType(0);
4486 // fold (ctlz_zero_undef c1) -> c2
4487 if (isa<ConstantSDNode>(N0))
4488 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4492 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4493 SDValue N0 = N->getOperand(0);
4494 EVT VT = N->getValueType(0);
4496 // fold (cttz c1) -> c2
4497 if (isa<ConstantSDNode>(N0))
4498 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4502 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4503 SDValue N0 = N->getOperand(0);
4504 EVT VT = N->getValueType(0);
4506 // fold (cttz_zero_undef c1) -> c2
4507 if (isa<ConstantSDNode>(N0))
4508 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4512 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4513 SDValue N0 = N->getOperand(0);
4514 EVT VT = N->getValueType(0);
4516 // fold (ctpop c1) -> c2
4517 if (isa<ConstantSDNode>(N0))
4518 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4522 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4523 SDValue N0 = N->getOperand(0);
4524 SDValue N1 = N->getOperand(1);
4525 SDValue N2 = N->getOperand(2);
4526 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4527 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4528 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4529 EVT VT = N->getValueType(0);
4530 EVT VT0 = N0.getValueType();
4532 // fold (select C, X, X) -> X
4535 // fold (select true, X, Y) -> X
4536 if (N0C && !N0C->isNullValue())
4538 // fold (select false, X, Y) -> Y
4539 if (N0C && N0C->isNullValue())
4541 // fold (select C, 1, X) -> (or C, X)
4542 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4543 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4544 // fold (select C, 0, 1) -> (xor C, 1)
4545 if (VT.isInteger() &&
4548 TLI.getBooleanContents(false) ==
4549 TargetLowering::ZeroOrOneBooleanContent)) &&
4550 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4553 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4554 N0, DAG.getConstant(1, VT0));
4555 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4556 N0, DAG.getConstant(1, VT0));
4557 AddToWorkList(XORNode.getNode());
4559 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4560 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4562 // fold (select C, 0, X) -> (and (not C), X)
4563 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4564 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4565 AddToWorkList(NOTNode.getNode());
4566 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4568 // fold (select C, X, 1) -> (or (not C), X)
4569 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4570 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4571 AddToWorkList(NOTNode.getNode());
4572 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4574 // fold (select C, X, 0) -> (and C, X)
4575 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4577 // fold (select X, X, Y) -> (or X, Y)
4578 // fold (select X, 1, Y) -> (or X, Y)
4579 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4580 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4581 // fold (select X, Y, X) -> (and X, Y)
4582 // fold (select X, Y, 0) -> (and X, Y)
4583 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4584 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4586 // If we can fold this based on the true/false value, do so.
4587 if (SimplifySelectOps(N, N1, N2))
4588 return SDValue(N, 0); // Don't revisit N.
4590 // fold selects based on a setcc into other things, such as min/max/abs
4591 if (N0.getOpcode() == ISD::SETCC) {
4593 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4594 // having to say they don't support SELECT_CC on every type the DAG knows
4595 // about, since there is no way to mark an opcode illegal at all value types
4596 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4597 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4598 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4599 N0.getOperand(0), N0.getOperand(1),
4600 N1, N2, N0.getOperand(2));
4601 return SimplifySelect(SDLoc(N), N0, N1, N2);
4608 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4611 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4613 // Split the inputs.
4614 SDValue Lo, Hi, LL, LH, RL, RH;
4615 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4616 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4618 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4619 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4621 return std::make_pair(Lo, Hi);
4624 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4625 SDValue N0 = N->getOperand(0);
4626 SDValue N1 = N->getOperand(1);
4627 SDValue N2 = N->getOperand(2);
4630 // Canonicalize integer abs.
4631 // vselect (setg[te] X, 0), X, -X ->
4632 // vselect (setgt X, -1), X, -X ->
4633 // vselect (setl[te] X, 0), -X, X ->
4634 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4635 if (N0.getOpcode() == ISD::SETCC) {
4636 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4637 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4639 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4641 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4642 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4643 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4644 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4645 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4646 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4647 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4650 EVT VT = LHS.getValueType();
4651 SDValue Shift = DAG.getNode(
4652 ISD::SRA, DL, VT, LHS,
4653 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4654 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4655 AddToWorkList(Shift.getNode());
4656 AddToWorkList(Add.getNode());
4657 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4661 // If the VSELECT result requires splitting and the mask is provided by a
4662 // SETCC, then split both nodes and its operands before legalization. This
4663 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4664 // and enables future optimizations (e.g. min/max pattern matching on X86).
4665 if (N0.getOpcode() == ISD::SETCC) {
4666 EVT VT = N->getValueType(0);
4668 // Check if any splitting is required.
4669 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4670 TargetLowering::TypeSplitVector)
4673 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4674 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4675 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4676 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4678 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4679 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4681 // Add the new VSELECT nodes to the work list in case they need to be split
4683 AddToWorkList(Lo.getNode());
4684 AddToWorkList(Hi.getNode());
4686 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4689 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4690 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4692 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4693 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4699 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4700 SDValue N0 = N->getOperand(0);
4701 SDValue N1 = N->getOperand(1);
4702 SDValue N2 = N->getOperand(2);
4703 SDValue N3 = N->getOperand(3);
4704 SDValue N4 = N->getOperand(4);
4705 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4707 // fold select_cc lhs, rhs, x, x, cc -> x
4711 // Determine if the condition we're dealing with is constant
4712 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4713 N0, N1, CC, SDLoc(N), false);
4714 if (SCC.getNode()) {
4715 AddToWorkList(SCC.getNode());
4717 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4718 if (!SCCC->isNullValue())
4719 return N2; // cond always true -> true val
4721 return N3; // cond always false -> false val
4724 // Fold to a simpler select_cc
4725 if (SCC.getOpcode() == ISD::SETCC)
4726 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4727 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4731 // If we can fold this based on the true/false value, do so.
4732 if (SimplifySelectOps(N, N2, N3))
4733 return SDValue(N, 0); // Don't revisit N.
4735 // fold select_cc into other things, such as min/max/abs
4736 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4739 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4740 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4741 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4745 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4746 // dag node into a ConstantSDNode or a build_vector of constants.
4747 // This function is called by the DAGCombiner when visiting sext/zext/aext
4748 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4749 // Vector extends are not folded if operations are legal; this is to
4750 // avoid introducing illegal build_vector dag nodes.
4751 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4752 SelectionDAG &DAG, bool LegalTypes,
4753 bool LegalOperations) {
4754 unsigned Opcode = N->getOpcode();
4755 SDValue N0 = N->getOperand(0);
4756 EVT VT = N->getValueType(0);
4758 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4759 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4761 // fold (sext c1) -> c1
4762 // fold (zext c1) -> c1
4763 // fold (aext c1) -> c1
4764 if (isa<ConstantSDNode>(N0))
4765 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4767 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4768 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4769 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4770 EVT SVT = VT.getScalarType();
4771 if (!(VT.isVector() &&
4772 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4773 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4776 // We can fold this node into a build_vector.
4777 unsigned VTBits = SVT.getSizeInBits();
4778 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4779 unsigned ShAmt = VTBits - EVTBits;
4780 SmallVector<SDValue, 8> Elts;
4781 unsigned NumElts = N0->getNumOperands();
4784 for (unsigned i=0; i != NumElts; ++i) {
4785 SDValue Op = N0->getOperand(i);
4786 if (Op->getOpcode() == ISD::UNDEF) {
4787 Elts.push_back(DAG.getUNDEF(SVT));
4791 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4792 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4793 if (Opcode == ISD::SIGN_EXTEND)
4794 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4797 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4801 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4804 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4805 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4806 // transformation. Returns true if extension are possible and the above
4807 // mentioned transformation is profitable.
4808 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4810 SmallVectorImpl<SDNode *> &ExtendNodes,
4811 const TargetLowering &TLI) {
4812 bool HasCopyToRegUses = false;
4813 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4814 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4815 UE = N0.getNode()->use_end();
4820 if (UI.getUse().getResNo() != N0.getResNo())
4822 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4823 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4824 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4825 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4826 // Sign bits will be lost after a zext.
4829 for (unsigned i = 0; i != 2; ++i) {
4830 SDValue UseOp = User->getOperand(i);
4833 if (!isa<ConstantSDNode>(UseOp))
4838 ExtendNodes.push_back(User);
4841 // If truncates aren't free and there are users we can't
4842 // extend, it isn't worthwhile.
4845 // Remember if this value is live-out.
4846 if (User->getOpcode() == ISD::CopyToReg)
4847 HasCopyToRegUses = true;
4850 if (HasCopyToRegUses) {
4851 bool BothLiveOut = false;
4852 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4854 SDUse &Use = UI.getUse();
4855 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4861 // Both unextended and extended values are live out. There had better be
4862 // a good reason for the transformation.
4863 return ExtendNodes.size();
4868 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4869 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4870 ISD::NodeType ExtType) {
4871 // Extend SetCC uses if necessary.
4872 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4873 SDNode *SetCC = SetCCs[i];
4874 SmallVector<SDValue, 4> Ops;
4876 for (unsigned j = 0; j != 2; ++j) {
4877 SDValue SOp = SetCC->getOperand(j);
4879 Ops.push_back(ExtLoad);
4881 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4884 Ops.push_back(SetCC->getOperand(2));
4885 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4886 &Ops[0], Ops.size()));
4890 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4891 SDValue N0 = N->getOperand(0);
4892 EVT VT = N->getValueType(0);
4894 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4896 return SDValue(Res, 0);
4898 // fold (sext (sext x)) -> (sext x)
4899 // fold (sext (aext x)) -> (sext x)
4900 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4901 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4904 if (N0.getOpcode() == ISD::TRUNCATE) {
4905 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4906 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4907 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4908 if (NarrowLoad.getNode()) {
4909 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4910 if (NarrowLoad.getNode() != N0.getNode()) {
4911 CombineTo(N0.getNode(), NarrowLoad);
4912 // CombineTo deleted the truncate, if needed, but not what's under it.
4915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4918 // See if the value being truncated is already sign extended. If so, just
4919 // eliminate the trunc/sext pair.
4920 SDValue Op = N0.getOperand(0);
4921 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4922 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4923 unsigned DestBits = VT.getScalarType().getSizeInBits();
4924 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4926 if (OpBits == DestBits) {
4927 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4928 // bits, it is already ready.
4929 if (NumSignBits > DestBits-MidBits)
4931 } else if (OpBits < DestBits) {
4932 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4933 // bits, just sext from i32.
4934 if (NumSignBits > OpBits-MidBits)
4935 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4937 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4938 // bits, just truncate to i32.
4939 if (NumSignBits > OpBits-MidBits)
4940 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4943 // fold (sext (truncate x)) -> (sextinreg x).
4944 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4945 N0.getValueType())) {
4946 if (OpBits < DestBits)
4947 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4948 else if (OpBits > DestBits)
4949 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4950 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4951 DAG.getValueType(N0.getValueType()));
4955 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4956 // None of the supported targets knows how to perform load and sign extend
4957 // on vectors in one instruction. We only perform this transformation on
4959 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4960 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4961 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4962 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4963 bool DoXform = true;
4964 SmallVector<SDNode*, 4> SetCCs;
4965 if (!N0.hasOneUse())
4966 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4969 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4971 LN0->getBasePtr(), N0.getValueType(),
4972 LN0->getMemOperand());
4973 CombineTo(N, ExtLoad);
4974 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4975 N0.getValueType(), ExtLoad);
4976 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4977 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4979 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4983 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4984 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4985 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4986 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4987 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4988 EVT MemVT = LN0->getMemoryVT();
4989 if ((!LegalOperations && !LN0->isVolatile()) ||
4990 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4991 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4993 LN0->getBasePtr(), MemVT,
4994 LN0->getMemOperand());
4995 CombineTo(N, ExtLoad);
4996 CombineTo(N0.getNode(),
4997 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4998 N0.getValueType(), ExtLoad),
4999 ExtLoad.getValue(1));
5000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5004 // fold (sext (and/or/xor (load x), cst)) ->
5005 // (and/or/xor (sextload x), (sext cst))
5006 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5007 N0.getOpcode() == ISD::XOR) &&
5008 isa<LoadSDNode>(N0.getOperand(0)) &&
5009 N0.getOperand(1).getOpcode() == ISD::Constant &&
5010 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5011 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5012 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5013 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5014 bool DoXform = true;
5015 SmallVector<SDNode*, 4> SetCCs;
5016 if (!N0.hasOneUse())
5017 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5020 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5021 LN0->getChain(), LN0->getBasePtr(),
5023 LN0->getMemOperand());
5024 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5025 Mask = Mask.sext(VT.getSizeInBits());
5026 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5027 ExtLoad, DAG.getConstant(Mask, VT));
5028 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5029 SDLoc(N0.getOperand(0)),
5030 N0.getOperand(0).getValueType(), ExtLoad);
5032 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5033 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5035 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5040 if (N0.getOpcode() == ISD::SETCC) {
5041 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5042 // Only do this before legalize for now.
5043 if (VT.isVector() && !LegalOperations &&
5044 TLI.getBooleanContents(true) ==
5045 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5046 EVT N0VT = N0.getOperand(0).getValueType();
5047 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5048 // of the same size as the compared operands. Only optimize sext(setcc())
5049 // if this is the case.
5050 EVT SVT = getSetCCResultType(N0VT);
5052 // We know that the # elements of the results is the same as the
5053 // # elements of the compare (and the # elements of the compare result
5054 // for that matter). Check to see that they are the same size. If so,
5055 // we know that the element size of the sext'd result matches the
5056 // element size of the compare operands.
5057 if (VT.getSizeInBits() == SVT.getSizeInBits())
5058 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5060 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5062 // If the desired elements are smaller or larger than the source
5063 // elements we can use a matching integer vector type and then
5064 // truncate/sign extend
5065 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5066 if (SVT == MatchingVectorType) {
5067 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5068 N0.getOperand(0), N0.getOperand(1),
5069 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5070 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5074 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5075 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5077 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5079 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5080 NegOne, DAG.getConstant(0, VT),
5081 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5082 if (SCC.getNode()) return SCC;
5084 if (!VT.isVector()) {
5085 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5086 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5088 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5089 SDValue SetCC = DAG.getSetCC(DL,
5091 N0.getOperand(0), N0.getOperand(1), CC);
5092 EVT SelectVT = getSetCCResultType(VT);
5093 return DAG.getSelect(DL, VT,
5094 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5095 NegOne, DAG.getConstant(0, VT));
5101 // fold (sext x) -> (zext x) if the sign bit is known zero.
5102 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5103 DAG.SignBitIsZero(N0))
5104 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5109 // isTruncateOf - If N is a truncate of some other value, return true, record
5110 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5111 // This function computes KnownZero to avoid a duplicated call to
5112 // ComputeMaskedBits in the caller.
5113 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5116 if (N->getOpcode() == ISD::TRUNCATE) {
5117 Op = N->getOperand(0);
5118 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5122 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5123 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5126 SDValue Op0 = N->getOperand(0);
5127 SDValue Op1 = N->getOperand(1);
5128 assert(Op0.getValueType() == Op1.getValueType());
5130 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5131 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5132 if (COp0 && COp0->isNullValue())
5134 else if (COp1 && COp1->isNullValue())
5139 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5141 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5147 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5148 SDValue N0 = N->getOperand(0);
5149 EVT VT = N->getValueType(0);
5151 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5153 return SDValue(Res, 0);
5155 // fold (zext (zext x)) -> (zext x)
5156 // fold (zext (aext x)) -> (zext x)
5157 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5158 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5161 // fold (zext (truncate x)) -> (zext x) or
5162 // (zext (truncate x)) -> (truncate x)
5163 // This is valid when the truncated bits of x are already zero.
5164 // FIXME: We should extend this to work for vectors too.
5167 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5168 APInt TruncatedBits =
5169 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5170 APInt(Op.getValueSizeInBits(), 0) :
5171 APInt::getBitsSet(Op.getValueSizeInBits(),
5172 N0.getValueSizeInBits(),
5173 std::min(Op.getValueSizeInBits(),
5174 VT.getSizeInBits()));
5175 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5176 if (VT.bitsGT(Op.getValueType()))
5177 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5178 if (VT.bitsLT(Op.getValueType()))
5179 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5185 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5186 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5187 if (N0.getOpcode() == ISD::TRUNCATE) {
5188 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5189 if (NarrowLoad.getNode()) {
5190 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5191 if (NarrowLoad.getNode() != N0.getNode()) {
5192 CombineTo(N0.getNode(), NarrowLoad);
5193 // CombineTo deleted the truncate, if needed, but not what's under it.
5196 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5200 // fold (zext (truncate x)) -> (and x, mask)
5201 if (N0.getOpcode() == ISD::TRUNCATE &&
5202 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5204 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5205 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5206 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5207 if (NarrowLoad.getNode()) {
5208 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5209 if (NarrowLoad.getNode() != N0.getNode()) {
5210 CombineTo(N0.getNode(), NarrowLoad);
5211 // CombineTo deleted the truncate, if needed, but not what's under it.
5214 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5217 SDValue Op = N0.getOperand(0);
5218 if (Op.getValueType().bitsLT(VT)) {
5219 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5220 AddToWorkList(Op.getNode());
5221 } else if (Op.getValueType().bitsGT(VT)) {
5222 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5223 AddToWorkList(Op.getNode());
5225 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5226 N0.getValueType().getScalarType());
5229 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5230 // if either of the casts is not free.
5231 if (N0.getOpcode() == ISD::AND &&
5232 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5233 N0.getOperand(1).getOpcode() == ISD::Constant &&
5234 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5235 N0.getValueType()) ||
5236 !TLI.isZExtFree(N0.getValueType(), VT))) {
5237 SDValue X = N0.getOperand(0).getOperand(0);
5238 if (X.getValueType().bitsLT(VT)) {
5239 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5240 } else if (X.getValueType().bitsGT(VT)) {
5241 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5243 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5244 Mask = Mask.zext(VT.getSizeInBits());
5245 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5246 X, DAG.getConstant(Mask, VT));
5249 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5250 // None of the supported targets knows how to perform load and vector_zext
5251 // on vectors in one instruction. We only perform this transformation on
5253 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5254 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5255 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5256 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5257 bool DoXform = true;
5258 SmallVector<SDNode*, 4> SetCCs;
5259 if (!N0.hasOneUse())
5260 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5262 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5263 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5265 LN0->getBasePtr(), N0.getValueType(),
5266 LN0->getMemOperand());
5267 CombineTo(N, ExtLoad);
5268 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5269 N0.getValueType(), ExtLoad);
5270 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5272 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5274 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5278 // fold (zext (and/or/xor (load x), cst)) ->
5279 // (and/or/xor (zextload x), (zext cst))
5280 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5281 N0.getOpcode() == ISD::XOR) &&
5282 isa<LoadSDNode>(N0.getOperand(0)) &&
5283 N0.getOperand(1).getOpcode() == ISD::Constant &&
5284 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5285 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5286 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5287 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5288 bool DoXform = true;
5289 SmallVector<SDNode*, 4> SetCCs;
5290 if (!N0.hasOneUse())
5291 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5294 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5295 LN0->getChain(), LN0->getBasePtr(),
5297 LN0->getMemOperand());
5298 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5299 Mask = Mask.zext(VT.getSizeInBits());
5300 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5301 ExtLoad, DAG.getConstant(Mask, VT));
5302 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5303 SDLoc(N0.getOperand(0)),
5304 N0.getOperand(0).getValueType(), ExtLoad);
5306 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5307 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5314 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5315 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5316 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5317 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5318 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5319 EVT MemVT = LN0->getMemoryVT();
5320 if ((!LegalOperations && !LN0->isVolatile()) ||
5321 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5322 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5324 LN0->getBasePtr(), MemVT,
5325 LN0->getMemOperand());
5326 CombineTo(N, ExtLoad);
5327 CombineTo(N0.getNode(),
5328 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5330 ExtLoad.getValue(1));
5331 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5335 if (N0.getOpcode() == ISD::SETCC) {
5336 if (!LegalOperations && VT.isVector() &&
5337 N0.getValueType().getVectorElementType() == MVT::i1) {
5338 EVT N0VT = N0.getOperand(0).getValueType();
5339 if (getSetCCResultType(N0VT) == N0.getValueType())
5342 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5343 // Only do this before legalize for now.
5344 EVT EltVT = VT.getVectorElementType();
5345 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5346 DAG.getConstant(1, EltVT));
5347 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5348 // We know that the # elements of the results is the same as the
5349 // # elements of the compare (and the # elements of the compare result
5350 // for that matter). Check to see that they are the same size. If so,
5351 // we know that the element size of the sext'd result matches the
5352 // element size of the compare operands.
5353 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5354 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5356 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5357 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5358 &OneOps[0], OneOps.size()));
5360 // If the desired elements are smaller or larger than the source
5361 // elements we can use a matching integer vector type and then
5362 // truncate/sign extend
5363 EVT MatchingElementType =
5364 EVT::getIntegerVT(*DAG.getContext(),
5365 N0VT.getScalarType().getSizeInBits());
5366 EVT MatchingVectorType =
5367 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5368 N0VT.getVectorNumElements());
5370 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5372 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5373 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5374 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5375 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5376 &OneOps[0], OneOps.size()));
5379 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5381 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5382 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5383 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5384 if (SCC.getNode()) return SCC;
5387 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5388 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5389 isa<ConstantSDNode>(N0.getOperand(1)) &&
5390 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5392 SDValue ShAmt = N0.getOperand(1);
5393 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5394 if (N0.getOpcode() == ISD::SHL) {
5395 SDValue InnerZExt = N0.getOperand(0);
5396 // If the original shl may be shifting out bits, do not perform this
5398 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5399 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5400 if (ShAmtVal > KnownZeroBits)
5406 // Ensure that the shift amount is wide enough for the shifted value.
5407 if (VT.getSizeInBits() >= 256)
5408 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5410 return DAG.getNode(N0.getOpcode(), DL, VT,
5411 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5418 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5419 SDValue N0 = N->getOperand(0);
5420 EVT VT = N->getValueType(0);
5422 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5424 return SDValue(Res, 0);
5426 // fold (aext (aext x)) -> (aext x)
5427 // fold (aext (zext x)) -> (zext x)
5428 // fold (aext (sext x)) -> (sext x)
5429 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5430 N0.getOpcode() == ISD::ZERO_EXTEND ||
5431 N0.getOpcode() == ISD::SIGN_EXTEND)
5432 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5434 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5435 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5436 if (N0.getOpcode() == ISD::TRUNCATE) {
5437 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5438 if (NarrowLoad.getNode()) {
5439 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5440 if (NarrowLoad.getNode() != N0.getNode()) {
5441 CombineTo(N0.getNode(), NarrowLoad);
5442 // CombineTo deleted the truncate, if needed, but not what's under it.
5445 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5449 // fold (aext (truncate x))
5450 if (N0.getOpcode() == ISD::TRUNCATE) {
5451 SDValue TruncOp = N0.getOperand(0);
5452 if (TruncOp.getValueType() == VT)
5453 return TruncOp; // x iff x size == zext size.
5454 if (TruncOp.getValueType().bitsGT(VT))
5455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5456 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5459 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5460 // if the trunc is not free.
5461 if (N0.getOpcode() == ISD::AND &&
5462 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5463 N0.getOperand(1).getOpcode() == ISD::Constant &&
5464 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5465 N0.getValueType())) {
5466 SDValue X = N0.getOperand(0).getOperand(0);
5467 if (X.getValueType().bitsLT(VT)) {
5468 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5469 } else if (X.getValueType().bitsGT(VT)) {
5470 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5472 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5473 Mask = Mask.zext(VT.getSizeInBits());
5474 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475 X, DAG.getConstant(Mask, VT));
5478 // fold (aext (load x)) -> (aext (truncate (extload x)))
5479 // None of the supported targets knows how to perform load and any_ext
5480 // on vectors in one instruction. We only perform this transformation on
5482 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5483 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5484 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5485 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5486 bool DoXform = true;
5487 SmallVector<SDNode*, 4> SetCCs;
5488 if (!N0.hasOneUse())
5489 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5491 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5492 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5494 LN0->getBasePtr(), N0.getValueType(),
5495 LN0->getMemOperand());
5496 CombineTo(N, ExtLoad);
5497 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5498 N0.getValueType(), ExtLoad);
5499 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5500 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5502 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5506 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5507 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5508 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5509 if (N0.getOpcode() == ISD::LOAD &&
5510 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5512 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5513 ISD::LoadExtType ExtType = LN0->getExtensionType();
5514 EVT MemVT = LN0->getMemoryVT();
5515 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5516 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5517 VT, LN0->getChain(), LN0->getBasePtr(),
5518 MemVT, LN0->getMemOperand());
5519 CombineTo(N, ExtLoad);
5520 CombineTo(N0.getNode(),
5521 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5522 N0.getValueType(), ExtLoad),
5523 ExtLoad.getValue(1));
5524 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5528 if (N0.getOpcode() == ISD::SETCC) {
5529 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5530 // Only do this before legalize for now.
5531 if (VT.isVector() && !LegalOperations) {
5532 EVT N0VT = N0.getOperand(0).getValueType();
5533 // We know that the # elements of the results is the same as the
5534 // # elements of the compare (and the # elements of the compare result
5535 // for that matter). Check to see that they are the same size. If so,
5536 // we know that the element size of the sext'd result matches the
5537 // element size of the compare operands.
5538 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5539 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5541 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5542 // If the desired elements are smaller or larger than the source
5543 // elements we can use a matching integer vector type and then
5544 // truncate/sign extend
5546 EVT MatchingElementType =
5547 EVT::getIntegerVT(*DAG.getContext(),
5548 N0VT.getScalarType().getSizeInBits());
5549 EVT MatchingVectorType =
5550 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5551 N0VT.getVectorNumElements());
5553 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5555 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5556 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5560 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5562 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5563 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5564 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5572 /// GetDemandedBits - See if the specified operand can be simplified with the
5573 /// knowledge that only the bits specified by Mask are used. If so, return the
5574 /// simpler operand, otherwise return a null SDValue.
5575 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5576 switch (V.getOpcode()) {
5578 case ISD::Constant: {
5579 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5580 assert(CV != 0 && "Const value should be ConstSDNode.");
5581 const APInt &CVal = CV->getAPIntValue();
5582 APInt NewVal = CVal & Mask;
5584 return DAG.getConstant(NewVal, V.getValueType());
5589 // If the LHS or RHS don't contribute bits to the or, drop them.
5590 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5591 return V.getOperand(1);
5592 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5593 return V.getOperand(0);
5596 // Only look at single-use SRLs.
5597 if (!V.getNode()->hasOneUse())
5599 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5600 // See if we can recursively simplify the LHS.
5601 unsigned Amt = RHSC->getZExtValue();
5603 // Watch out for shift count overflow though.
5604 if (Amt >= Mask.getBitWidth()) break;
5605 APInt NewMask = Mask << Amt;
5606 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5607 if (SimplifyLHS.getNode())
5608 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5609 SimplifyLHS, V.getOperand(1));
5615 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5616 /// bits and then truncated to a narrower type and where N is a multiple
5617 /// of number of bits of the narrower type, transform it to a narrower load
5618 /// from address + N / num of bits of new type. If the result is to be
5619 /// extended, also fold the extension to form a extending load.
5620 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5621 unsigned Opc = N->getOpcode();
5623 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5624 SDValue N0 = N->getOperand(0);
5625 EVT VT = N->getValueType(0);
5628 // This transformation isn't valid for vector loads.
5632 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5634 if (Opc == ISD::SIGN_EXTEND_INREG) {
5635 ExtType = ISD::SEXTLOAD;
5636 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5637 } else if (Opc == ISD::SRL) {
5638 // Another special-case: SRL is basically zero-extending a narrower value.
5639 ExtType = ISD::ZEXTLOAD;
5641 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5642 if (!N01) return SDValue();
5643 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5644 VT.getSizeInBits() - N01->getZExtValue());
5646 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5649 unsigned EVTBits = ExtVT.getSizeInBits();
5651 // Do not generate loads of non-round integer types since these can
5652 // be expensive (and would be wrong if the type is not byte sized).
5653 if (!ExtVT.isRound())
5657 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5658 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5659 ShAmt = N01->getZExtValue();
5660 // Is the shift amount a multiple of size of VT?
5661 if ((ShAmt & (EVTBits-1)) == 0) {
5662 N0 = N0.getOperand(0);
5663 // Is the load width a multiple of size of VT?
5664 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5668 // At this point, we must have a load or else we can't do the transform.
5669 if (!isa<LoadSDNode>(N0)) return SDValue();
5671 // Because a SRL must be assumed to *need* to zero-extend the high bits
5672 // (as opposed to anyext the high bits), we can't combine the zextload
5673 // lowering of SRL and an sextload.
5674 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5677 // If the shift amount is larger than the input type then we're not
5678 // accessing any of the loaded bytes. If the load was a zextload/extload
5679 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5680 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5685 // If the load is shifted left (and the result isn't shifted back right),
5686 // we can fold the truncate through the shift.
5687 unsigned ShLeftAmt = 0;
5688 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5689 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5690 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5691 ShLeftAmt = N01->getZExtValue();
5692 N0 = N0.getOperand(0);
5696 // If we haven't found a load, we can't narrow it. Don't transform one with
5697 // multiple uses, this would require adding a new load.
5698 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5701 // Don't change the width of a volatile load.
5702 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5703 if (LN0->isVolatile())
5706 // Verify that we are actually reducing a load width here.
5707 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5710 // For the transform to be legal, the load must produce only two values
5711 // (the value loaded and the chain). Don't transform a pre-increment
5712 // load, for example, which produces an extra value. Otherwise the
5713 // transformation is not equivalent, and the downstream logic to replace
5714 // uses gets things wrong.
5715 if (LN0->getNumValues() > 2)
5718 // If the load that we're shrinking is an extload and we're not just
5719 // discarding the extension we can't simply shrink the load. Bail.
5720 // TODO: It would be possible to merge the extensions in some cases.
5721 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5722 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5725 EVT PtrType = N0.getOperand(1).getValueType();
5727 if (PtrType == MVT::Untyped || PtrType.isExtended())
5728 // It's not possible to generate a constant of extended or untyped type.
5731 // For big endian targets, we need to adjust the offset to the pointer to
5732 // load the correct bytes.
5733 if (TLI.isBigEndian()) {
5734 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5735 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5736 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5739 uint64_t PtrOff = ShAmt / 8;
5740 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5741 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5742 PtrType, LN0->getBasePtr(),
5743 DAG.getConstant(PtrOff, PtrType));
5744 AddToWorkList(NewPtr.getNode());
5747 if (ExtType == ISD::NON_EXTLOAD)
5748 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5749 LN0->getPointerInfo().getWithOffset(PtrOff),
5750 LN0->isVolatile(), LN0->isNonTemporal(),
5751 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5753 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5754 LN0->getPointerInfo().getWithOffset(PtrOff),
5755 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5756 NewAlign, LN0->getTBAAInfo());
5758 // Replace the old load's chain with the new load's chain.
5759 WorkListRemover DeadNodes(*this);
5760 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5762 // Shift the result left, if we've swallowed a left shift.
5763 SDValue Result = Load;
5764 if (ShLeftAmt != 0) {
5765 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5766 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5768 // If the shift amount is as large as the result size (but, presumably,
5769 // no larger than the source) then the useful bits of the result are
5770 // zero; we can't simply return the shortened shift, because the result
5771 // of that operation is undefined.
5772 if (ShLeftAmt >= VT.getSizeInBits())
5773 Result = DAG.getConstant(0, VT);
5775 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5776 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5779 // Return the new loaded value.
5783 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5784 SDValue N0 = N->getOperand(0);
5785 SDValue N1 = N->getOperand(1);
5786 EVT VT = N->getValueType(0);
5787 EVT EVT = cast<VTSDNode>(N1)->getVT();
5788 unsigned VTBits = VT.getScalarType().getSizeInBits();
5789 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5791 // fold (sext_in_reg c1) -> c1
5792 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5793 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5795 // If the input is already sign extended, just drop the extension.
5796 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5799 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5800 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5801 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5802 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5803 N0.getOperand(0), N1);
5805 // fold (sext_in_reg (sext x)) -> (sext x)
5806 // fold (sext_in_reg (aext x)) -> (sext x)
5807 // if x is small enough.
5808 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5809 SDValue N00 = N0.getOperand(0);
5810 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5811 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5812 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5815 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5816 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5817 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5819 // fold operands of sext_in_reg based on knowledge that the top bits are not
5821 if (SimplifyDemandedBits(SDValue(N, 0)))
5822 return SDValue(N, 0);
5824 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5825 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5826 SDValue NarrowLoad = ReduceLoadWidth(N);
5827 if (NarrowLoad.getNode())
5830 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5831 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5832 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5833 if (N0.getOpcode() == ISD::SRL) {
5834 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5835 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5836 // We can turn this into an SRA iff the input to the SRL is already sign
5838 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5839 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5840 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5841 N0.getOperand(0), N0.getOperand(1));
5845 // fold (sext_inreg (extload x)) -> (sextload x)
5846 if (ISD::isEXTLoad(N0.getNode()) &&
5847 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5848 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5849 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5850 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5852 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5854 LN0->getBasePtr(), EVT,
5855 LN0->getMemOperand());
5856 CombineTo(N, ExtLoad);
5857 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5858 AddToWorkList(ExtLoad.getNode());
5859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5861 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5862 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5864 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5865 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5866 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5867 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5868 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5870 LN0->getBasePtr(), EVT,
5871 LN0->getMemOperand());
5872 CombineTo(N, ExtLoad);
5873 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5877 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5878 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5879 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5880 N0.getOperand(1), false);
5881 if (BSwap.getNode() != 0)
5882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5886 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5887 // into a build_vector.
5888 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5889 SmallVector<SDValue, 8> Elts;
5890 unsigned NumElts = N0->getNumOperands();
5891 unsigned ShAmt = VTBits - EVTBits;
5893 for (unsigned i = 0; i != NumElts; ++i) {
5894 SDValue Op = N0->getOperand(i);
5895 if (Op->getOpcode() == ISD::UNDEF) {
5900 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5901 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5902 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5903 Op.getValueType()));
5906 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5912 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5913 SDValue N0 = N->getOperand(0);
5914 EVT VT = N->getValueType(0);
5915 bool isLE = TLI.isLittleEndian();
5918 if (N0.getValueType() == N->getValueType(0))
5920 // fold (truncate c1) -> c1
5921 if (isa<ConstantSDNode>(N0))
5922 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5923 // fold (truncate (truncate x)) -> (truncate x)
5924 if (N0.getOpcode() == ISD::TRUNCATE)
5925 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5926 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5927 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5928 N0.getOpcode() == ISD::SIGN_EXTEND ||
5929 N0.getOpcode() == ISD::ANY_EXTEND) {
5930 if (N0.getOperand(0).getValueType().bitsLT(VT))
5931 // if the source is smaller than the dest, we still need an extend
5932 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5934 if (N0.getOperand(0).getValueType().bitsGT(VT))
5935 // if the source is larger than the dest, than we just need the truncate
5936 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5937 // if the source and dest are the same type, we can drop both the extend
5938 // and the truncate.
5939 return N0.getOperand(0);
5942 // Fold extract-and-trunc into a narrow extract. For example:
5943 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5944 // i32 y = TRUNCATE(i64 x)
5946 // v16i8 b = BITCAST (v2i64 val)
5947 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5949 // Note: We only run this optimization after type legalization (which often
5950 // creates this pattern) and before operation legalization after which
5951 // we need to be more careful about the vector instructions that we generate.
5952 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5953 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5955 EVT VecTy = N0.getOperand(0).getValueType();
5956 EVT ExTy = N0.getValueType();
5957 EVT TrTy = N->getValueType(0);
5959 unsigned NumElem = VecTy.getVectorNumElements();
5960 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5962 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5963 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5965 SDValue EltNo = N0->getOperand(1);
5966 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5967 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5968 EVT IndexTy = TLI.getVectorIdxTy();
5969 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5971 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5972 NVT, N0.getOperand(0));
5974 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5976 DAG.getConstant(Index, IndexTy));
5980 // Fold a series of buildvector, bitcast, and truncate if possible.
5982 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5983 // (2xi32 (buildvector x, y)).
5984 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5985 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5986 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5987 N0.getOperand(0).hasOneUse()) {
5989 SDValue BuildVect = N0.getOperand(0);
5990 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5991 EVT TruncVecEltTy = VT.getVectorElementType();
5993 // Check that the element types match.
5994 if (BuildVectEltTy == TruncVecEltTy) {
5995 // Now we only need to compute the offset of the truncated elements.
5996 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5997 unsigned TruncVecNumElts = VT.getVectorNumElements();
5998 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6000 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6001 "Invalid number of elements");
6003 SmallVector<SDValue, 8> Opnds;
6004 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6005 Opnds.push_back(BuildVect.getOperand(i));
6007 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6012 // See if we can simplify the input to this truncate through knowledge that
6013 // only the low bits are being used.
6014 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6015 // Currently we only perform this optimization on scalars because vectors
6016 // may have different active low bits.
6017 if (!VT.isVector()) {
6019 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6020 VT.getSizeInBits()));
6021 if (Shorter.getNode())
6022 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6024 // fold (truncate (load x)) -> (smaller load x)
6025 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6026 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6027 SDValue Reduced = ReduceLoadWidth(N);
6028 if (Reduced.getNode())
6030 // Handle the case where the load remains an extending load even
6031 // after truncation.
6032 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6033 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6034 if (!LN0->isVolatile() &&
6035 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6036 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6037 VT, LN0->getChain(), LN0->getBasePtr(),
6039 LN0->getMemOperand());
6040 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6045 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6046 // where ... are all 'undef'.
6047 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6048 SmallVector<EVT, 8> VTs;
6051 unsigned NumDefs = 0;
6053 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6054 SDValue X = N0.getOperand(i);
6055 if (X.getOpcode() != ISD::UNDEF) {
6060 // Stop if more than one members are non-undef.
6063 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6064 VT.getVectorElementType(),
6065 X.getValueType().getVectorNumElements()));
6069 return DAG.getUNDEF(VT);
6072 assert(V.getNode() && "The single defined operand is empty!");
6073 SmallVector<SDValue, 8> Opnds;
6074 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6076 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6079 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6080 AddToWorkList(NV.getNode());
6081 Opnds.push_back(NV);
6083 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6084 &Opnds[0], Opnds.size());
6088 // Simplify the operands using demanded-bits information.
6089 if (!VT.isVector() &&
6090 SimplifyDemandedBits(SDValue(N, 0)))
6091 return SDValue(N, 0);
6096 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6097 SDValue Elt = N->getOperand(i);
6098 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6099 return Elt.getNode();
6100 return Elt.getOperand(Elt.getResNo()).getNode();
6103 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6104 /// if load locations are consecutive.
6105 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6106 assert(N->getOpcode() == ISD::BUILD_PAIR);
6108 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6109 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6110 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6111 LD1->getAddressSpace() != LD2->getAddressSpace())
6113 EVT LD1VT = LD1->getValueType(0);
6115 if (ISD::isNON_EXTLoad(LD2) &&
6117 // If both are volatile this would reduce the number of volatile loads.
6118 // If one is volatile it might be ok, but play conservative and bail out.
6119 !LD1->isVolatile() &&
6120 !LD2->isVolatile() &&
6121 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6122 unsigned Align = LD1->getAlignment();
6123 unsigned NewAlign = TLI.getDataLayout()->
6124 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6126 if (NewAlign <= Align &&
6127 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6128 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6129 LD1->getBasePtr(), LD1->getPointerInfo(),
6130 false, false, false, Align);
6136 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6137 SDValue N0 = N->getOperand(0);
6138 EVT VT = N->getValueType(0);
6140 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6141 // Only do this before legalize, since afterward the target may be depending
6142 // on the bitconvert.
6143 // First check to see if this is all constant.
6145 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6147 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6149 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6150 assert(!DestEltVT.isVector() &&
6151 "Element type of vector ValueType must not be vector!");
6153 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6156 // If the input is a constant, let getNode fold it.
6157 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6158 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6159 if (Res.getNode() != N) {
6160 if (!LegalOperations ||
6161 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6164 // Folding it resulted in an illegal node, and it's too late to
6165 // do that. Clean up the old node and forego the transformation.
6166 // Ideally this won't happen very often, because instcombine
6167 // and the earlier dagcombine runs (where illegal nodes are
6168 // permitted) should have folded most of them already.
6169 DAG.DeleteNode(Res.getNode());
6173 // (conv (conv x, t1), t2) -> (conv x, t2)
6174 if (N0.getOpcode() == ISD::BITCAST)
6175 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6178 // fold (conv (load x)) -> (load (conv*)x)
6179 // If the resultant load doesn't need a higher alignment than the original!
6180 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6181 // Do not change the width of a volatile load.
6182 !cast<LoadSDNode>(N0)->isVolatile() &&
6183 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6184 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6185 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6186 unsigned Align = TLI.getDataLayout()->
6187 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6188 unsigned OrigAlign = LN0->getAlignment();
6190 if (Align <= OrigAlign) {
6191 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6192 LN0->getBasePtr(), LN0->getPointerInfo(),
6193 LN0->isVolatile(), LN0->isNonTemporal(),
6194 LN0->isInvariant(), OrigAlign,
6195 LN0->getTBAAInfo());
6197 CombineTo(N0.getNode(),
6198 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6199 N0.getValueType(), Load),
6205 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6206 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6207 // This often reduces constant pool loads.
6208 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6209 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6210 N0.getNode()->hasOneUse() && VT.isInteger() &&
6211 !VT.isVector() && !N0.getValueType().isVector()) {
6212 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6214 AddToWorkList(NewConv.getNode());
6216 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6217 if (N0.getOpcode() == ISD::FNEG)
6218 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6219 NewConv, DAG.getConstant(SignBit, VT));
6220 assert(N0.getOpcode() == ISD::FABS);
6221 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6222 NewConv, DAG.getConstant(~SignBit, VT));
6225 // fold (bitconvert (fcopysign cst, x)) ->
6226 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6227 // Note that we don't handle (copysign x, cst) because this can always be
6228 // folded to an fneg or fabs.
6229 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6230 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6231 VT.isInteger() && !VT.isVector()) {
6232 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6233 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6234 if (isTypeLegal(IntXVT)) {
6235 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6236 IntXVT, N0.getOperand(1));
6237 AddToWorkList(X.getNode());
6239 // If X has a different width than the result/lhs, sext it or truncate it.
6240 unsigned VTWidth = VT.getSizeInBits();
6241 if (OrigXWidth < VTWidth) {
6242 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6243 AddToWorkList(X.getNode());
6244 } else if (OrigXWidth > VTWidth) {
6245 // To get the sign bit in the right place, we have to shift it right
6246 // before truncating.
6247 X = DAG.getNode(ISD::SRL, SDLoc(X),
6248 X.getValueType(), X,
6249 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6250 AddToWorkList(X.getNode());
6251 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6252 AddToWorkList(X.getNode());
6255 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6256 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6257 X, DAG.getConstant(SignBit, VT));
6258 AddToWorkList(X.getNode());
6260 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6261 VT, N0.getOperand(0));
6262 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6263 Cst, DAG.getConstant(~SignBit, VT));
6264 AddToWorkList(Cst.getNode());
6266 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6270 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6271 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6272 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6273 if (CombineLD.getNode())
6280 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6281 EVT VT = N->getValueType(0);
6282 return CombineConsecutiveLoads(N, VT);
6285 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6286 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6287 /// destination element value type.
6288 SDValue DAGCombiner::
6289 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6290 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6292 // If this is already the right type, we're done.
6293 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6295 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6296 unsigned DstBitSize = DstEltVT.getSizeInBits();
6298 // If this is a conversion of N elements of one type to N elements of another
6299 // type, convert each element. This handles FP<->INT cases.
6300 if (SrcBitSize == DstBitSize) {
6301 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6302 BV->getValueType(0).getVectorNumElements());
6304 // Due to the FP element handling below calling this routine recursively,
6305 // we can end up with a scalar-to-vector node here.
6306 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6307 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6308 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6309 DstEltVT, BV->getOperand(0)));
6311 SmallVector<SDValue, 8> Ops;
6312 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6313 SDValue Op = BV->getOperand(i);
6314 // If the vector element type is not legal, the BUILD_VECTOR operands
6315 // are promoted and implicitly truncated. Make that explicit here.
6316 if (Op.getValueType() != SrcEltVT)
6317 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6318 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6320 AddToWorkList(Ops.back().getNode());
6322 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6323 &Ops[0], Ops.size());
6326 // Otherwise, we're growing or shrinking the elements. To avoid having to
6327 // handle annoying details of growing/shrinking FP values, we convert them to
6329 if (SrcEltVT.isFloatingPoint()) {
6330 // Convert the input float vector to a int vector where the elements are the
6332 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6333 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6334 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6338 // Now we know the input is an integer vector. If the output is a FP type,
6339 // convert to integer first, then to FP of the right size.
6340 if (DstEltVT.isFloatingPoint()) {
6341 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6342 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6343 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6345 // Next, convert to FP elements of the same size.
6346 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6349 // Okay, we know the src/dst types are both integers of differing types.
6350 // Handling growing first.
6351 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6352 if (SrcBitSize < DstBitSize) {
6353 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6355 SmallVector<SDValue, 8> Ops;
6356 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6357 i += NumInputsPerOutput) {
6358 bool isLE = TLI.isLittleEndian();
6359 APInt NewBits = APInt(DstBitSize, 0);
6360 bool EltIsUndef = true;
6361 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6362 // Shift the previously computed bits over.
6363 NewBits <<= SrcBitSize;
6364 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6365 if (Op.getOpcode() == ISD::UNDEF) continue;
6368 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6369 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6373 Ops.push_back(DAG.getUNDEF(DstEltVT));
6375 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6378 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6380 &Ops[0], Ops.size());
6383 // Finally, this must be the case where we are shrinking elements: each input
6384 // turns into multiple outputs.
6385 bool isS2V = ISD::isScalarToVector(BV);
6386 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6387 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6388 NumOutputsPerInput*BV->getNumOperands());
6389 SmallVector<SDValue, 8> Ops;
6391 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6392 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6393 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6394 Ops.push_back(DAG.getUNDEF(DstEltVT));
6398 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6399 getAPIntValue().zextOrTrunc(SrcBitSize);
6401 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6402 APInt ThisVal = OpVal.trunc(DstBitSize);
6403 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6404 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6405 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6406 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6408 OpVal = OpVal.lshr(DstBitSize);
6411 // For big endian targets, swap the order of the pieces of each element.
6412 if (TLI.isBigEndian())
6413 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6416 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6417 &Ops[0], Ops.size());
6420 SDValue DAGCombiner::visitFADD(SDNode *N) {
6421 SDValue N0 = N->getOperand(0);
6422 SDValue N1 = N->getOperand(1);
6423 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6424 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6425 EVT VT = N->getValueType(0);
6428 if (VT.isVector()) {
6429 SDValue FoldedVOp = SimplifyVBinOp(N);
6430 if (FoldedVOp.getNode()) return FoldedVOp;
6433 // fold (fadd c1, c2) -> c1 + c2
6435 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6436 // canonicalize constant to RHS
6437 if (N0CFP && !N1CFP)
6438 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6439 // fold (fadd A, 0) -> A
6440 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6441 N1CFP->getValueAPF().isZero())
6443 // fold (fadd A, (fneg B)) -> (fsub A, B)
6444 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6445 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6446 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6447 GetNegatedExpression(N1, DAG, LegalOperations));
6448 // fold (fadd (fneg A), B) -> (fsub B, A)
6449 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6450 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6451 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6452 GetNegatedExpression(N0, DAG, LegalOperations));
6454 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6455 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6456 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6457 isa<ConstantFPSDNode>(N0.getOperand(1)))
6458 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6459 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6460 N0.getOperand(1), N1));
6462 // No FP constant should be created after legalization as Instruction
6463 // Selection pass has hard time in dealing with FP constant.
6465 // We don't need test this condition for transformation like following, as
6466 // the DAG being transformed implies it is legal to take FP constant as
6469 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6471 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6473 // If allow, fold (fadd (fneg x), x) -> 0.0
6474 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6475 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6476 return DAG.getConstantFP(0.0, VT);
6478 // If allow, fold (fadd x, (fneg x)) -> 0.0
6479 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6480 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6481 return DAG.getConstantFP(0.0, VT);
6483 // In unsafe math mode, we can fold chains of FADD's of the same value
6484 // into multiplications. This transform is not safe in general because
6485 // we are reducing the number of rounding steps.
6486 if (DAG.getTarget().Options.UnsafeFPMath &&
6487 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6489 if (N0.getOpcode() == ISD::FMUL) {
6490 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6491 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6493 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6494 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6495 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6497 DAG.getConstantFP(1.0, VT));
6498 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6502 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6503 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6504 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6506 DAG.getConstantFP(1.0, VT));
6507 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6511 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6512 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6513 N1.getOperand(0) == N1.getOperand(1) &&
6514 N0.getOperand(1) == N1.getOperand(0)) {
6515 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6517 DAG.getConstantFP(2.0, VT));
6518 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6519 N0.getOperand(1), NewCFP);
6522 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6523 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6524 N1.getOperand(0) == N1.getOperand(1) &&
6525 N0.getOperand(0) == N1.getOperand(0)) {
6526 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6528 DAG.getConstantFP(2.0, VT));
6529 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6530 N0.getOperand(0), NewCFP);
6534 if (N1.getOpcode() == ISD::FMUL) {
6535 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6536 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6538 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6539 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6540 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6542 DAG.getConstantFP(1.0, VT));
6543 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6547 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6548 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6549 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6551 DAG.getConstantFP(1.0, VT));
6552 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6558 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6559 N0.getOperand(0) == N0.getOperand(1) &&
6560 N1.getOperand(1) == N0.getOperand(0)) {
6561 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563 DAG.getConstantFP(2.0, VT));
6564 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6565 N1.getOperand(1), NewCFP);
6568 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6569 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6570 N0.getOperand(0) == N0.getOperand(1) &&
6571 N1.getOperand(0) == N0.getOperand(0)) {
6572 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6574 DAG.getConstantFP(2.0, VT));
6575 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6576 N1.getOperand(0), NewCFP);
6580 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6581 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6582 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6583 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6584 (N0.getOperand(0) == N1))
6585 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6586 N1, DAG.getConstantFP(3.0, VT));
6589 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6590 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6591 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6592 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6593 N1.getOperand(0) == N0)
6594 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6595 N0, DAG.getConstantFP(3.0, VT));
6598 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6599 if (AllowNewFpConst &&
6600 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6601 N0.getOperand(0) == N0.getOperand(1) &&
6602 N1.getOperand(0) == N1.getOperand(1) &&
6603 N0.getOperand(0) == N1.getOperand(0))
6604 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6606 DAG.getConstantFP(4.0, VT));
6609 // FADD -> FMA combines:
6610 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6611 DAG.getTarget().Options.UnsafeFPMath) &&
6612 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6613 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6615 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6616 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6617 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6618 N0.getOperand(0), N0.getOperand(1), N1);
6620 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6621 // Note: Commutes FADD operands.
6622 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6623 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6624 N1.getOperand(0), N1.getOperand(1), N0);
6630 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6631 SDValue N0 = N->getOperand(0);
6632 SDValue N1 = N->getOperand(1);
6633 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6634 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6635 EVT VT = N->getValueType(0);
6639 if (VT.isVector()) {
6640 SDValue FoldedVOp = SimplifyVBinOp(N);
6641 if (FoldedVOp.getNode()) return FoldedVOp;
6644 // fold (fsub c1, c2) -> c1-c2
6646 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6647 // fold (fsub A, 0) -> A
6648 if (DAG.getTarget().Options.UnsafeFPMath &&
6649 N1CFP && N1CFP->getValueAPF().isZero())
6651 // fold (fsub 0, B) -> -B
6652 if (DAG.getTarget().Options.UnsafeFPMath &&
6653 N0CFP && N0CFP->getValueAPF().isZero()) {
6654 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6655 return GetNegatedExpression(N1, DAG, LegalOperations);
6656 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6657 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6659 // fold (fsub A, (fneg B)) -> (fadd A, B)
6660 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6661 return DAG.getNode(ISD::FADD, dl, VT, N0,
6662 GetNegatedExpression(N1, DAG, LegalOperations));
6664 // If 'unsafe math' is enabled, fold
6665 // (fsub x, x) -> 0.0 &
6666 // (fsub x, (fadd x, y)) -> (fneg y) &
6667 // (fsub x, (fadd y, x)) -> (fneg y)
6668 if (DAG.getTarget().Options.UnsafeFPMath) {
6670 return DAG.getConstantFP(0.0f, VT);
6672 if (N1.getOpcode() == ISD::FADD) {
6673 SDValue N10 = N1->getOperand(0);
6674 SDValue N11 = N1->getOperand(1);
6676 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6677 &DAG.getTarget().Options))
6678 return GetNegatedExpression(N11, DAG, LegalOperations);
6680 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6681 &DAG.getTarget().Options))
6682 return GetNegatedExpression(N10, DAG, LegalOperations);
6686 // FSUB -> FMA combines:
6687 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6688 DAG.getTarget().Options.UnsafeFPMath) &&
6689 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6690 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6692 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6693 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6694 return DAG.getNode(ISD::FMA, dl, VT,
6695 N0.getOperand(0), N0.getOperand(1),
6696 DAG.getNode(ISD::FNEG, dl, VT, N1));
6698 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6699 // Note: Commutes FSUB operands.
6700 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6701 return DAG.getNode(ISD::FMA, dl, VT,
6702 DAG.getNode(ISD::FNEG, dl, VT,
6704 N1.getOperand(1), N0);
6706 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6707 if (N0.getOpcode() == ISD::FNEG &&
6708 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6709 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6710 SDValue N00 = N0.getOperand(0).getOperand(0);
6711 SDValue N01 = N0.getOperand(0).getOperand(1);
6712 return DAG.getNode(ISD::FMA, dl, VT,
6713 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6714 DAG.getNode(ISD::FNEG, dl, VT, N1));
6721 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6722 SDValue N0 = N->getOperand(0);
6723 SDValue N1 = N->getOperand(1);
6724 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6725 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6726 EVT VT = N->getValueType(0);
6727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6730 if (VT.isVector()) {
6731 SDValue FoldedVOp = SimplifyVBinOp(N);
6732 if (FoldedVOp.getNode()) return FoldedVOp;
6735 // fold (fmul c1, c2) -> c1*c2
6737 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6738 // canonicalize constant to RHS
6739 if (N0CFP && !N1CFP)
6740 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6741 // fold (fmul A, 0) -> 0
6742 if (DAG.getTarget().Options.UnsafeFPMath &&
6743 N1CFP && N1CFP->getValueAPF().isZero())
6745 // fold (fmul A, 0) -> 0, vector edition.
6746 if (DAG.getTarget().Options.UnsafeFPMath &&
6747 ISD::isBuildVectorAllZeros(N1.getNode()))
6749 // fold (fmul A, 1.0) -> A
6750 if (N1CFP && N1CFP->isExactlyValue(1.0))
6752 // fold (fmul X, 2.0) -> (fadd X, X)
6753 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6754 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6755 // fold (fmul X, -1.0) -> (fneg X)
6756 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6757 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6758 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6760 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6761 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6762 &DAG.getTarget().Options)) {
6763 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6764 &DAG.getTarget().Options)) {
6765 // Both can be negated for free, check to see if at least one is cheaper
6767 if (LHSNeg == 2 || RHSNeg == 2)
6768 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6769 GetNegatedExpression(N0, DAG, LegalOperations),
6770 GetNegatedExpression(N1, DAG, LegalOperations));
6774 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6775 if (DAG.getTarget().Options.UnsafeFPMath &&
6776 N1CFP && N0.getOpcode() == ISD::FMUL &&
6777 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6778 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6779 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6780 N0.getOperand(1), N1));
6785 SDValue DAGCombiner::visitFMA(SDNode *N) {
6786 SDValue N0 = N->getOperand(0);
6787 SDValue N1 = N->getOperand(1);
6788 SDValue N2 = N->getOperand(2);
6789 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6790 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6791 EVT VT = N->getValueType(0);
6794 if (DAG.getTarget().Options.UnsafeFPMath) {
6795 if (N0CFP && N0CFP->isZero())
6797 if (N1CFP && N1CFP->isZero())
6800 if (N0CFP && N0CFP->isExactlyValue(1.0))
6801 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6802 if (N1CFP && N1CFP->isExactlyValue(1.0))
6803 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6805 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6806 if (N0CFP && !N1CFP)
6807 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6809 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6810 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6811 N2.getOpcode() == ISD::FMUL &&
6812 N0 == N2.getOperand(0) &&
6813 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6814 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6815 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6819 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6820 if (DAG.getTarget().Options.UnsafeFPMath &&
6821 N0.getOpcode() == ISD::FMUL && N1CFP &&
6822 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6823 return DAG.getNode(ISD::FMA, dl, VT,
6825 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6829 // (fma x, 1, y) -> (fadd x, y)
6830 // (fma x, -1, y) -> (fadd (fneg x), y)
6832 if (N1CFP->isExactlyValue(1.0))
6833 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6835 if (N1CFP->isExactlyValue(-1.0) &&
6836 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6837 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6838 AddToWorkList(RHSNeg.getNode());
6839 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6843 // (fma x, c, x) -> (fmul x, (c+1))
6844 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6845 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6846 DAG.getNode(ISD::FADD, dl, VT,
6847 N1, DAG.getConstantFP(1.0, VT)));
6849 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6850 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6851 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6852 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6853 DAG.getNode(ISD::FADD, dl, VT,
6854 N1, DAG.getConstantFP(-1.0, VT)));
6860 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6861 SDValue N0 = N->getOperand(0);
6862 SDValue N1 = N->getOperand(1);
6863 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6864 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6865 EVT VT = N->getValueType(0);
6866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6869 if (VT.isVector()) {
6870 SDValue FoldedVOp = SimplifyVBinOp(N);
6871 if (FoldedVOp.getNode()) return FoldedVOp;
6874 // fold (fdiv c1, c2) -> c1/c2
6876 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6878 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6879 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6880 // Compute the reciprocal 1.0 / c2.
6881 APFloat N1APF = N1CFP->getValueAPF();
6882 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6883 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6884 // Only do the transform if the reciprocal is a legal fp immediate that
6885 // isn't too nasty (eg NaN, denormal, ...).
6886 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6887 (!LegalOperations ||
6888 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6889 // backend)... we should handle this gracefully after Legalize.
6890 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6891 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6892 TLI.isFPImmLegal(Recip, VT)))
6893 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6894 DAG.getConstantFP(Recip, VT));
6897 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6898 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6899 &DAG.getTarget().Options)) {
6900 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6901 &DAG.getTarget().Options)) {
6902 // Both can be negated for free, check to see if at least one is cheaper
6904 if (LHSNeg == 2 || RHSNeg == 2)
6905 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6906 GetNegatedExpression(N0, DAG, LegalOperations),
6907 GetNegatedExpression(N1, DAG, LegalOperations));
6914 SDValue DAGCombiner::visitFREM(SDNode *N) {
6915 SDValue N0 = N->getOperand(0);
6916 SDValue N1 = N->getOperand(1);
6917 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6918 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6919 EVT VT = N->getValueType(0);
6921 // fold (frem c1, c2) -> fmod(c1,c2)
6923 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6928 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6929 SDValue N0 = N->getOperand(0);
6930 SDValue N1 = N->getOperand(1);
6931 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6932 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6933 EVT VT = N->getValueType(0);
6935 if (N0CFP && N1CFP) // Constant fold
6936 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6939 const APFloat& V = N1CFP->getValueAPF();
6940 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6941 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6942 if (!V.isNegative()) {
6943 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6944 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6946 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6947 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6948 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6952 // copysign(fabs(x), y) -> copysign(x, y)
6953 // copysign(fneg(x), y) -> copysign(x, y)
6954 // copysign(copysign(x,z), y) -> copysign(x, y)
6955 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6956 N0.getOpcode() == ISD::FCOPYSIGN)
6957 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6958 N0.getOperand(0), N1);
6960 // copysign(x, abs(y)) -> abs(x)
6961 if (N1.getOpcode() == ISD::FABS)
6962 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6964 // copysign(x, copysign(y,z)) -> copysign(x, z)
6965 if (N1.getOpcode() == ISD::FCOPYSIGN)
6966 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6967 N0, N1.getOperand(1));
6969 // copysign(x, fp_extend(y)) -> copysign(x, y)
6970 // copysign(x, fp_round(y)) -> copysign(x, y)
6971 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6972 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6973 N0, N1.getOperand(0));
6978 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6979 SDValue N0 = N->getOperand(0);
6980 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6981 EVT VT = N->getValueType(0);
6982 EVT OpVT = N0.getValueType();
6984 // fold (sint_to_fp c1) -> c1fp
6986 // ...but only if the target supports immediate floating-point values
6987 (!LegalOperations ||
6988 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6989 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6991 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6992 // but UINT_TO_FP is legal on this target, try to convert.
6993 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6994 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6995 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6996 if (DAG.SignBitIsZero(N0))
6997 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7000 // The next optimizations are desirable only if SELECT_CC can be lowered.
7001 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7002 // having to say they don't support SELECT_CC on every type the DAG knows
7003 // about, since there is no way to mark an opcode illegal at all value types
7004 // (See also visitSELECT)
7005 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7006 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7007 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7009 (!LegalOperations ||
7010 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7012 { N0.getOperand(0), N0.getOperand(1),
7013 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7015 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7018 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7019 // (select_cc x, y, 1.0, 0.0,, cc)
7020 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7021 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7022 (!LegalOperations ||
7023 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7025 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7026 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7027 N0.getOperand(0).getOperand(2) };
7028 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7035 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7036 SDValue N0 = N->getOperand(0);
7037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7038 EVT VT = N->getValueType(0);
7039 EVT OpVT = N0.getValueType();
7041 // fold (uint_to_fp c1) -> c1fp
7043 // ...but only if the target supports immediate floating-point values
7044 (!LegalOperations ||
7045 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7046 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7048 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7049 // but SINT_TO_FP is legal on this target, try to convert.
7050 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7051 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7052 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7053 if (DAG.SignBitIsZero(N0))
7054 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7057 // The next optimizations are desirable only if SELECT_CC can be lowered.
7058 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7059 // having to say they don't support SELECT_CC on every type the DAG knows
7060 // about, since there is no way to mark an opcode illegal at all value types
7061 // (See also visitSELECT)
7062 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7063 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7065 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7066 (!LegalOperations ||
7067 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7069 { N0.getOperand(0), N0.getOperand(1),
7070 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7072 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7079 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7080 SDValue N0 = N->getOperand(0);
7081 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7082 EVT VT = N->getValueType(0);
7084 // fold (fp_to_sint c1fp) -> c1
7086 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7091 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7092 SDValue N0 = N->getOperand(0);
7093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7094 EVT VT = N->getValueType(0);
7096 // fold (fp_to_uint c1fp) -> c1
7098 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7103 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7104 SDValue N0 = N->getOperand(0);
7105 SDValue N1 = N->getOperand(1);
7106 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7107 EVT VT = N->getValueType(0);
7109 // fold (fp_round c1fp) -> c1fp
7111 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7113 // fold (fp_round (fp_extend x)) -> x
7114 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7115 return N0.getOperand(0);
7117 // fold (fp_round (fp_round x)) -> (fp_round x)
7118 if (N0.getOpcode() == ISD::FP_ROUND) {
7119 // This is a value preserving truncation if both round's are.
7120 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7121 N0.getNode()->getConstantOperandVal(1) == 1;
7122 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7123 DAG.getIntPtrConstant(IsTrunc));
7126 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7127 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7128 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7129 N0.getOperand(0), N1);
7130 AddToWorkList(Tmp.getNode());
7131 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7132 Tmp, N0.getOperand(1));
7138 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7139 SDValue N0 = N->getOperand(0);
7140 EVT VT = N->getValueType(0);
7141 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7142 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7144 // fold (fp_round_inreg c1fp) -> c1fp
7145 if (N0CFP && isTypeLegal(EVT)) {
7146 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7147 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7153 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7154 SDValue N0 = N->getOperand(0);
7155 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7156 EVT VT = N->getValueType(0);
7158 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7159 if (N->hasOneUse() &&
7160 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7163 // fold (fp_extend c1fp) -> c1fp
7165 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7167 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7169 if (N0.getOpcode() == ISD::FP_ROUND
7170 && N0.getNode()->getConstantOperandVal(1) == 1) {
7171 SDValue In = N0.getOperand(0);
7172 if (In.getValueType() == VT) return In;
7173 if (VT.bitsLT(In.getValueType()))
7174 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7175 In, N0.getOperand(1));
7176 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7179 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7180 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7181 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7182 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7184 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7186 LN0->getBasePtr(), N0.getValueType(),
7187 LN0->getMemOperand());
7188 CombineTo(N, ExtLoad);
7189 CombineTo(N0.getNode(),
7190 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7191 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7192 ExtLoad.getValue(1));
7193 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7199 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7200 SDValue N0 = N->getOperand(0);
7201 EVT VT = N->getValueType(0);
7203 if (VT.isVector()) {
7204 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7205 if (FoldedVOp.getNode()) return FoldedVOp;
7208 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7209 &DAG.getTarget().Options))
7210 return GetNegatedExpression(N0, DAG, LegalOperations);
7212 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7213 // constant pool values.
7214 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7216 N0.getNode()->hasOneUse() &&
7217 N0.getOperand(0).getValueType().isInteger()) {
7218 SDValue Int = N0.getOperand(0);
7219 EVT IntVT = Int.getValueType();
7220 if (IntVT.isInteger() && !IntVT.isVector()) {
7221 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7222 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7223 AddToWorkList(Int.getNode());
7224 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7229 // (fneg (fmul c, x)) -> (fmul -c, x)
7230 if (N0.getOpcode() == ISD::FMUL) {
7231 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7233 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7235 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7242 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7243 SDValue N0 = N->getOperand(0);
7244 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7245 EVT VT = N->getValueType(0);
7247 // fold (fceil c1) -> fceil(c1)
7249 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7254 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7255 SDValue N0 = N->getOperand(0);
7256 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7257 EVT VT = N->getValueType(0);
7259 // fold (ftrunc c1) -> ftrunc(c1)
7261 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7266 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7267 SDValue N0 = N->getOperand(0);
7268 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7269 EVT VT = N->getValueType(0);
7271 // fold (ffloor c1) -> ffloor(c1)
7273 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7278 SDValue DAGCombiner::visitFABS(SDNode *N) {
7279 SDValue N0 = N->getOperand(0);
7280 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7281 EVT VT = N->getValueType(0);
7283 if (VT.isVector()) {
7284 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7285 if (FoldedVOp.getNode()) return FoldedVOp;
7288 // fold (fabs c1) -> fabs(c1)
7290 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7291 // fold (fabs (fabs x)) -> (fabs x)
7292 if (N0.getOpcode() == ISD::FABS)
7293 return N->getOperand(0);
7294 // fold (fabs (fneg x)) -> (fabs x)
7295 // fold (fabs (fcopysign x, y)) -> (fabs x)
7296 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7297 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7299 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7300 // constant pool values.
7301 if (!TLI.isFAbsFree(VT) &&
7302 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7303 N0.getOperand(0).getValueType().isInteger() &&
7304 !N0.getOperand(0).getValueType().isVector()) {
7305 SDValue Int = N0.getOperand(0);
7306 EVT IntVT = Int.getValueType();
7307 if (IntVT.isInteger() && !IntVT.isVector()) {
7308 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7309 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7310 AddToWorkList(Int.getNode());
7311 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7312 N->getValueType(0), Int);
7319 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7320 SDValue Chain = N->getOperand(0);
7321 SDValue N1 = N->getOperand(1);
7322 SDValue N2 = N->getOperand(2);
7324 // If N is a constant we could fold this into a fallthrough or unconditional
7325 // branch. However that doesn't happen very often in normal code, because
7326 // Instcombine/SimplifyCFG should have handled the available opportunities.
7327 // If we did this folding here, it would be necessary to update the
7328 // MachineBasicBlock CFG, which is awkward.
7330 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7332 if (N1.getOpcode() == ISD::SETCC &&
7333 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7334 N1.getOperand(0).getValueType())) {
7335 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7336 Chain, N1.getOperand(2),
7337 N1.getOperand(0), N1.getOperand(1), N2);
7340 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7341 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7342 (N1.getOperand(0).hasOneUse() &&
7343 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7345 if (N1.getOpcode() == ISD::TRUNCATE) {
7346 // Look pass the truncate.
7347 Trunc = N1.getNode();
7348 N1 = N1.getOperand(0);
7351 // Match this pattern so that we can generate simpler code:
7354 // %b = and i32 %a, 2
7355 // %c = srl i32 %b, 1
7356 // brcond i32 %c ...
7361 // %b = and i32 %a, 2
7362 // %c = setcc eq %b, 0
7365 // This applies only when the AND constant value has one bit set and the
7366 // SRL constant is equal to the log2 of the AND constant. The back-end is
7367 // smart enough to convert the result into a TEST/JMP sequence.
7368 SDValue Op0 = N1.getOperand(0);
7369 SDValue Op1 = N1.getOperand(1);
7371 if (Op0.getOpcode() == ISD::AND &&
7372 Op1.getOpcode() == ISD::Constant) {
7373 SDValue AndOp1 = Op0.getOperand(1);
7375 if (AndOp1.getOpcode() == ISD::Constant) {
7376 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7378 if (AndConst.isPowerOf2() &&
7379 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7381 DAG.getSetCC(SDLoc(N),
7382 getSetCCResultType(Op0.getValueType()),
7383 Op0, DAG.getConstant(0, Op0.getValueType()),
7386 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7387 MVT::Other, Chain, SetCC, N2);
7388 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7389 // will convert it back to (X & C1) >> C2.
7390 CombineTo(N, NewBRCond, false);
7391 // Truncate is dead.
7393 removeFromWorkList(Trunc);
7394 DAG.DeleteNode(Trunc);
7396 // Replace the uses of SRL with SETCC
7397 WorkListRemover DeadNodes(*this);
7398 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7399 removeFromWorkList(N1.getNode());
7400 DAG.DeleteNode(N1.getNode());
7401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7407 // Restore N1 if the above transformation doesn't match.
7408 N1 = N->getOperand(1);
7411 // Transform br(xor(x, y)) -> br(x != y)
7412 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7413 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7414 SDNode *TheXor = N1.getNode();
7415 SDValue Op0 = TheXor->getOperand(0);
7416 SDValue Op1 = TheXor->getOperand(1);
7417 if (Op0.getOpcode() == Op1.getOpcode()) {
7418 // Avoid missing important xor optimizations.
7419 SDValue Tmp = visitXOR(TheXor);
7420 if (Tmp.getNode()) {
7421 if (Tmp.getNode() != TheXor) {
7422 DEBUG(dbgs() << "\nReplacing.8 ";
7424 dbgs() << "\nWith: ";
7425 Tmp.getNode()->dump(&DAG);
7427 WorkListRemover DeadNodes(*this);
7428 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7429 removeFromWorkList(TheXor);
7430 DAG.DeleteNode(TheXor);
7431 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7432 MVT::Other, Chain, Tmp, N2);
7435 // visitXOR has changed XOR's operands or replaced the XOR completely,
7437 return SDValue(N, 0);
7441 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7443 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7444 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7445 Op0.getOpcode() == ISD::XOR) {
7446 TheXor = Op0.getNode();
7450 EVT SetCCVT = N1.getValueType();
7452 SetCCVT = getSetCCResultType(SetCCVT);
7453 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7456 Equal ? ISD::SETEQ : ISD::SETNE);
7457 // Replace the uses of XOR with SETCC
7458 WorkListRemover DeadNodes(*this);
7459 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7460 removeFromWorkList(N1.getNode());
7461 DAG.DeleteNode(N1.getNode());
7462 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7463 MVT::Other, Chain, SetCC, N2);
7470 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7472 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7473 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7474 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7476 // If N is a constant we could fold this into a fallthrough or unconditional
7477 // branch. However that doesn't happen very often in normal code, because
7478 // Instcombine/SimplifyCFG should have handled the available opportunities.
7479 // If we did this folding here, it would be necessary to update the
7480 // MachineBasicBlock CFG, which is awkward.
7482 // Use SimplifySetCC to simplify SETCC's.
7483 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7484 CondLHS, CondRHS, CC->get(), SDLoc(N),
7486 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7488 // fold to a simpler setcc
7489 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7490 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7491 N->getOperand(0), Simp.getOperand(2),
7492 Simp.getOperand(0), Simp.getOperand(1),
7498 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7499 /// uses N as its base pointer and that N may be folded in the load / store
7500 /// addressing mode.
7501 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7503 const TargetLowering &TLI) {
7505 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7506 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7508 VT = Use->getValueType(0);
7509 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7510 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7512 VT = ST->getValue().getValueType();
7516 TargetLowering::AddrMode AM;
7517 if (N->getOpcode() == ISD::ADD) {
7518 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7521 AM.BaseOffs = Offset->getSExtValue();
7525 } else if (N->getOpcode() == ISD::SUB) {
7526 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7529 AM.BaseOffs = -Offset->getSExtValue();
7536 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7539 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7540 /// pre-indexed load / store when the base pointer is an add or subtract
7541 /// and it has other uses besides the load / store. After the
7542 /// transformation, the new indexed load / store has effectively folded
7543 /// the add / subtract in and all of its other uses are redirected to the
7544 /// new load / store.
7545 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7546 if (Level < AfterLegalizeDAG)
7552 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7553 if (LD->isIndexed())
7555 VT = LD->getMemoryVT();
7556 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7557 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7559 Ptr = LD->getBasePtr();
7560 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7561 if (ST->isIndexed())
7563 VT = ST->getMemoryVT();
7564 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7565 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7567 Ptr = ST->getBasePtr();
7573 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7574 // out. There is no reason to make this a preinc/predec.
7575 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7576 Ptr.getNode()->hasOneUse())
7579 // Ask the target to do addressing mode selection.
7582 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7583 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7586 // Backends without true r+i pre-indexed forms may need to pass a
7587 // constant base with a variable offset so that constant coercion
7588 // will work with the patterns in canonical form.
7589 bool Swapped = false;
7590 if (isa<ConstantSDNode>(BasePtr)) {
7591 std::swap(BasePtr, Offset);
7595 // Don't create a indexed load / store with zero offset.
7596 if (isa<ConstantSDNode>(Offset) &&
7597 cast<ConstantSDNode>(Offset)->isNullValue())
7600 // Try turning it into a pre-indexed load / store except when:
7601 // 1) The new base ptr is a frame index.
7602 // 2) If N is a store and the new base ptr is either the same as or is a
7603 // predecessor of the value being stored.
7604 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7605 // that would create a cycle.
7606 // 4) All uses are load / store ops that use it as old base ptr.
7608 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7609 // (plus the implicit offset) to a register to preinc anyway.
7610 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7615 SDValue Val = cast<StoreSDNode>(N)->getValue();
7616 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7620 // If the offset is a constant, there may be other adds of constants that
7621 // can be folded with this one. We should do this to avoid having to keep
7622 // a copy of the original base pointer.
7623 SmallVector<SDNode *, 16> OtherUses;
7624 if (isa<ConstantSDNode>(Offset))
7625 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7626 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7628 if (Use == Ptr.getNode())
7631 if (Use->isPredecessorOf(N))
7634 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7639 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7640 if (Op1.getNode() == BasePtr.getNode())
7641 std::swap(Op0, Op1);
7642 assert(Op0.getNode() == BasePtr.getNode() &&
7643 "Use of ADD/SUB but not an operand");
7645 if (!isa<ConstantSDNode>(Op1)) {
7650 // FIXME: In some cases, we can be smarter about this.
7651 if (Op1.getValueType() != Offset.getValueType()) {
7656 OtherUses.push_back(Use);
7660 std::swap(BasePtr, Offset);
7662 // Now check for #3 and #4.
7663 bool RealUse = false;
7665 // Caches for hasPredecessorHelper
7666 SmallPtrSet<const SDNode *, 32> Visited;
7667 SmallVector<const SDNode *, 16> Worklist;
7669 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7670 E = Ptr.getNode()->use_end(); I != E; ++I) {
7674 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7677 // If Ptr may be folded in addressing mode of other use, then it's
7678 // not profitable to do this transformation.
7679 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7688 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7689 BasePtr, Offset, AM);
7691 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7692 BasePtr, Offset, AM);
7695 DEBUG(dbgs() << "\nReplacing.4 ";
7697 dbgs() << "\nWith: ";
7698 Result.getNode()->dump(&DAG);
7700 WorkListRemover DeadNodes(*this);
7702 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7703 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7705 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7708 // Finally, since the node is now dead, remove it from the graph.
7712 std::swap(BasePtr, Offset);
7714 // Replace other uses of BasePtr that can be updated to use Ptr
7715 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7716 unsigned OffsetIdx = 1;
7717 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7719 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7720 BasePtr.getNode() && "Expected BasePtr operand");
7722 // We need to replace ptr0 in the following expression:
7723 // x0 * offset0 + y0 * ptr0 = t0
7725 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7727 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7728 // indexed load/store and the expresion that needs to be re-written.
7730 // Therefore, we have:
7731 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7733 ConstantSDNode *CN =
7734 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7736 APInt Offset0 = CN->getAPIntValue();
7737 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7739 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7740 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7741 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7742 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7744 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7746 APInt CNV = Offset0;
7747 if (X0 < 0) CNV = -CNV;
7748 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7749 else CNV = CNV - Offset1;
7751 // We can now generate the new expression.
7752 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7753 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7755 SDValue NewUse = DAG.getNode(Opcode,
7756 SDLoc(OtherUses[i]),
7757 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7758 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7759 removeFromWorkList(OtherUses[i]);
7760 DAG.DeleteNode(OtherUses[i]);
7763 // Replace the uses of Ptr with uses of the updated base value.
7764 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7765 removeFromWorkList(Ptr.getNode());
7766 DAG.DeleteNode(Ptr.getNode());
7771 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7772 /// add / sub of the base pointer node into a post-indexed load / store.
7773 /// The transformation folded the add / subtract into the new indexed
7774 /// load / store effectively and all of its uses are redirected to the
7775 /// new load / store.
7776 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7777 if (Level < AfterLegalizeDAG)
7783 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7784 if (LD->isIndexed())
7786 VT = LD->getMemoryVT();
7787 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7788 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7790 Ptr = LD->getBasePtr();
7791 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7792 if (ST->isIndexed())
7794 VT = ST->getMemoryVT();
7795 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7796 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7798 Ptr = ST->getBasePtr();
7804 if (Ptr.getNode()->hasOneUse())
7807 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7808 E = Ptr.getNode()->use_end(); I != E; ++I) {
7811 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7816 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7817 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7818 // Don't create a indexed load / store with zero offset.
7819 if (isa<ConstantSDNode>(Offset) &&
7820 cast<ConstantSDNode>(Offset)->isNullValue())
7823 // Try turning it into a post-indexed load / store except when
7824 // 1) All uses are load / store ops that use it as base ptr (and
7825 // it may be folded as addressing mmode).
7826 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7827 // nor a successor of N. Otherwise, if Op is folded that would
7830 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7834 bool TryNext = false;
7835 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7836 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7838 if (Use == Ptr.getNode())
7841 // If all the uses are load / store addresses, then don't do the
7843 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7844 bool RealUse = false;
7845 for (SDNode::use_iterator III = Use->use_begin(),
7846 EEE = Use->use_end(); III != EEE; ++III) {
7847 SDNode *UseUse = *III;
7848 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7863 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7864 SDValue Result = isLoad
7865 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7866 BasePtr, Offset, AM)
7867 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7868 BasePtr, Offset, AM);
7871 DEBUG(dbgs() << "\nReplacing.5 ";
7873 dbgs() << "\nWith: ";
7874 Result.getNode()->dump(&DAG);
7876 WorkListRemover DeadNodes(*this);
7878 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7879 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7881 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7884 // Finally, since the node is now dead, remove it from the graph.
7887 // Replace the uses of Use with uses of the updated base value.
7888 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7889 Result.getValue(isLoad ? 1 : 0));
7890 removeFromWorkList(Op);
7900 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7901 LoadSDNode *LD = cast<LoadSDNode>(N);
7902 SDValue Chain = LD->getChain();
7903 SDValue Ptr = LD->getBasePtr();
7905 // If load is not volatile and there are no uses of the loaded value (and
7906 // the updated indexed value in case of indexed loads), change uses of the
7907 // chain value into uses of the chain input (i.e. delete the dead load).
7908 if (!LD->isVolatile()) {
7909 if (N->getValueType(1) == MVT::Other) {
7911 if (!N->hasAnyUseOfValue(0)) {
7912 // It's not safe to use the two value CombineTo variant here. e.g.
7913 // v1, chain2 = load chain1, loc
7914 // v2, chain3 = load chain2, loc
7916 // Now we replace use of chain2 with chain1. This makes the second load
7917 // isomorphic to the one we are deleting, and thus makes this load live.
7918 DEBUG(dbgs() << "\nReplacing.6 ";
7920 dbgs() << "\nWith chain: ";
7921 Chain.getNode()->dump(&DAG);
7923 WorkListRemover DeadNodes(*this);
7924 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7926 if (N->use_empty()) {
7927 removeFromWorkList(N);
7931 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7935 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7936 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7937 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7938 DEBUG(dbgs() << "\nReplacing.7 ";
7940 dbgs() << "\nWith: ";
7941 Undef.getNode()->dump(&DAG);
7942 dbgs() << " and 2 other values\n");
7943 WorkListRemover DeadNodes(*this);
7944 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7945 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7946 DAG.getUNDEF(N->getValueType(1)));
7947 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7948 removeFromWorkList(N);
7950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7955 // If this load is directly stored, replace the load value with the stored
7957 // TODO: Handle store large -> read small portion.
7958 // TODO: Handle TRUNCSTORE/LOADEXT
7959 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7960 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7961 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7962 if (PrevST->getBasePtr() == Ptr &&
7963 PrevST->getValue().getValueType() == N->getValueType(0))
7964 return CombineTo(N, Chain.getOperand(1), Chain);
7968 // Try to infer better alignment information than the load already has.
7969 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7970 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7971 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7973 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7974 LD->getValueType(0),
7975 Chain, Ptr, LD->getPointerInfo(),
7977 LD->isVolatile(), LD->isNonTemporal(), Align,
7979 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7984 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7985 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7987 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7988 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7991 if (UseAA && LD->isUnindexed()) {
7992 // Walk up chain skipping non-aliasing memory nodes.
7993 SDValue BetterChain = FindBetterChain(N, Chain);
7995 // If there is a better chain.
7996 if (Chain != BetterChain) {
7999 // Replace the chain to void dependency.
8000 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8001 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8002 BetterChain, Ptr, LD->getMemOperand());
8004 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8005 LD->getValueType(0),
8006 BetterChain, Ptr, LD->getMemoryVT(),
8007 LD->getMemOperand());
8010 // Create token factor to keep old chain connected.
8011 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8012 MVT::Other, Chain, ReplLoad.getValue(1));
8014 // Make sure the new and old chains are cleaned up.
8015 AddToWorkList(Token.getNode());
8017 // Replace uses with load result and token factor. Don't add users
8019 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8023 // Try transforming N to an indexed load.
8024 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8025 return SDValue(N, 0);
8027 // Try to slice up N to more direct loads if the slices are mapped to
8028 // different register banks or pairing can take place.
8030 return SDValue(N, 0);
8036 /// \brief Helper structure used to slice a load in smaller loads.
8037 /// Basically a slice is obtained from the following sequence:
8038 /// Origin = load Ty1, Base
8039 /// Shift = srl Ty1 Origin, CstTy Amount
8040 /// Inst = trunc Shift to Ty2
8042 /// Then, it will be rewriten into:
8043 /// Slice = load SliceTy, Base + SliceOffset
8044 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8046 /// SliceTy is deduced from the number of bits that are actually used to
8048 struct LoadedSlice {
8049 /// \brief Helper structure used to compute the cost of a slice.
8051 /// Are we optimizing for code size.
8056 unsigned CrossRegisterBanksCopies;
8060 Cost(bool ForCodeSize = false)
8061 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8062 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8064 /// \brief Get the cost of one isolated slice.
8065 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8066 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8067 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8068 EVT TruncType = LS.Inst->getValueType(0);
8069 EVT LoadedType = LS.getLoadedType();
8070 if (TruncType != LoadedType &&
8071 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8075 /// \brief Account for slicing gain in the current cost.
8076 /// Slicing provide a few gains like removing a shift or a
8077 /// truncate. This method allows to grow the cost of the original
8078 /// load with the gain from this slice.
8079 void addSliceGain(const LoadedSlice &LS) {
8080 // Each slice saves a truncate.
8081 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8082 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8083 LS.Inst->getOperand(0).getValueType()))
8085 // If there is a shift amount, this slice gets rid of it.
8088 // If this slice can merge a cross register bank copy, account for it.
8089 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8090 ++CrossRegisterBanksCopies;
8093 Cost &operator+=(const Cost &RHS) {
8095 Truncates += RHS.Truncates;
8096 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8102 bool operator==(const Cost &RHS) const {
8103 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8104 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8105 ZExts == RHS.ZExts && Shift == RHS.Shift;
8108 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8110 bool operator<(const Cost &RHS) const {
8111 // Assume cross register banks copies are as expensive as loads.
8112 // FIXME: Do we want some more target hooks?
8113 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8114 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8115 // Unless we are optimizing for code size, consider the
8116 // expensive operation first.
8117 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8118 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8119 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8120 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8123 bool operator>(const Cost &RHS) const { return RHS < *this; }
8125 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8127 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8129 // The last instruction that represent the slice. This should be a
8130 // truncate instruction.
8132 // The original load instruction.
8134 // The right shift amount in bits from the original load.
8136 // The DAG from which Origin came from.
8137 // This is used to get some contextual information about legal types, etc.
8140 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8141 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8142 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8144 LoadedSlice(const LoadedSlice &LS)
8145 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8147 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8148 /// \return Result is \p BitWidth and has used bits set to 1 and
8149 /// not used bits set to 0.
8150 APInt getUsedBits() const {
8151 // Reproduce the trunc(lshr) sequence:
8152 // - Start from the truncated value.
8153 // - Zero extend to the desired bit width.
8155 assert(Origin && "No original load to compare against.");
8156 unsigned BitWidth = Origin->getValueSizeInBits(0);
8157 assert(Inst && "This slice is not bound to an instruction");
8158 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8159 "Extracted slice is bigger than the whole type!");
8160 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8161 UsedBits.setAllBits();
8162 UsedBits = UsedBits.zext(BitWidth);
8167 /// \brief Get the size of the slice to be loaded in bytes.
8168 unsigned getLoadedSize() const {
8169 unsigned SliceSize = getUsedBits().countPopulation();
8170 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8171 return SliceSize / 8;
8174 /// \brief Get the type that will be loaded for this slice.
8175 /// Note: This may not be the final type for the slice.
8176 EVT getLoadedType() const {
8177 assert(DAG && "Missing context");
8178 LLVMContext &Ctxt = *DAG->getContext();
8179 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8182 /// \brief Get the alignment of the load used for this slice.
8183 unsigned getAlignment() const {
8184 unsigned Alignment = Origin->getAlignment();
8185 unsigned Offset = getOffsetFromBase();
8187 Alignment = MinAlign(Alignment, Alignment + Offset);
8191 /// \brief Check if this slice can be rewritten with legal operations.
8192 bool isLegal() const {
8193 // An invalid slice is not legal.
8194 if (!Origin || !Inst || !DAG)
8197 // Offsets are for indexed load only, we do not handle that.
8198 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8201 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8203 // Check that the type is legal.
8204 EVT SliceType = getLoadedType();
8205 if (!TLI.isTypeLegal(SliceType))
8208 // Check that the load is legal for this type.
8209 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8212 // Check that the offset can be computed.
8213 // 1. Check its type.
8214 EVT PtrType = Origin->getBasePtr().getValueType();
8215 if (PtrType == MVT::Untyped || PtrType.isExtended())
8218 // 2. Check that it fits in the immediate.
8219 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8222 // 3. Check that the computation is legal.
8223 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8226 // Check that the zext is legal if it needs one.
8227 EVT TruncateType = Inst->getValueType(0);
8228 if (TruncateType != SliceType &&
8229 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8235 /// \brief Get the offset in bytes of this slice in the original chunk of
8237 /// \pre DAG != NULL.
8238 uint64_t getOffsetFromBase() const {
8239 assert(DAG && "Missing context.");
8241 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8242 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8243 uint64_t Offset = Shift / 8;
8244 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8245 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8246 "The size of the original loaded type is not a multiple of a"
8248 // If Offset is bigger than TySizeInBytes, it means we are loading all
8249 // zeros. This should have been optimized before in the process.
8250 assert(TySizeInBytes > Offset &&
8251 "Invalid shift amount for given loaded size");
8253 Offset = TySizeInBytes - Offset - getLoadedSize();
8257 /// \brief Generate the sequence of instructions to load the slice
8258 /// represented by this object and redirect the uses of this slice to
8259 /// this new sequence of instructions.
8260 /// \pre this->Inst && this->Origin are valid Instructions and this
8261 /// object passed the legal check: LoadedSlice::isLegal returned true.
8262 /// \return The last instruction of the sequence used to load the slice.
8263 SDValue loadSlice() const {
8264 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8265 const SDValue &OldBaseAddr = Origin->getBasePtr();
8266 SDValue BaseAddr = OldBaseAddr;
8267 // Get the offset in that chunk of bytes w.r.t. the endianess.
8268 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8269 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8271 // BaseAddr = BaseAddr + Offset.
8272 EVT ArithType = BaseAddr.getValueType();
8273 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8274 DAG->getConstant(Offset, ArithType));
8277 // Create the type of the loaded slice according to its size.
8278 EVT SliceType = getLoadedType();
8280 // Create the load for the slice.
8281 SDValue LastInst = DAG->getLoad(
8282 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8283 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8284 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8285 // If the final type is not the same as the loaded type, this means that
8286 // we have to pad with zero. Create a zero extend for that.
8287 EVT FinalType = Inst->getValueType(0);
8288 if (SliceType != FinalType)
8290 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8294 /// \brief Check if this slice can be merged with an expensive cross register
8295 /// bank copy. E.g.,
8297 /// f = bitcast i32 i to float
8298 bool canMergeExpensiveCrossRegisterBankCopy() const {
8299 if (!Inst || !Inst->hasOneUse())
8301 SDNode *Use = *Inst->use_begin();
8302 if (Use->getOpcode() != ISD::BITCAST)
8304 assert(DAG && "Missing context");
8305 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8306 EVT ResVT = Use->getValueType(0);
8307 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8308 const TargetRegisterClass *ArgRC =
8309 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8310 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8313 // At this point, we know that we perform a cross-register-bank copy.
8314 // Check if it is expensive.
8315 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8316 // Assume bitcasts are cheap, unless both register classes do not
8317 // explicitly share a common sub class.
8318 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8321 // Check if it will be merged with the load.
8322 // 1. Check the alignment constraint.
8323 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8324 ResVT.getTypeForEVT(*DAG->getContext()));
8326 if (RequiredAlignment > getAlignment())
8329 // 2. Check that the load is a legal operation for that type.
8330 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8333 // 3. Check that we do not have a zext in the way.
8334 if (Inst->getValueType(0) != getLoadedType())
8342 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8343 /// \p UsedBits looks like 0..0 1..1 0..0.
8344 static bool areUsedBitsDense(const APInt &UsedBits) {
8345 // If all the bits are one, this is dense!
8346 if (UsedBits.isAllOnesValue())
8349 // Get rid of the unused bits on the right.
8350 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8351 // Get rid of the unused bits on the left.
8352 if (NarrowedUsedBits.countLeadingZeros())
8353 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8354 // Check that the chunk of bits is completely used.
8355 return NarrowedUsedBits.isAllOnesValue();
8358 /// \brief Check whether or not \p First and \p Second are next to each other
8359 /// in memory. This means that there is no hole between the bits loaded
8360 /// by \p First and the bits loaded by \p Second.
8361 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8362 const LoadedSlice &Second) {
8363 assert(First.Origin == Second.Origin && First.Origin &&
8364 "Unable to match different memory origins.");
8365 APInt UsedBits = First.getUsedBits();
8366 assert((UsedBits & Second.getUsedBits()) == 0 &&
8367 "Slices are not supposed to overlap.");
8368 UsedBits |= Second.getUsedBits();
8369 return areUsedBitsDense(UsedBits);
8372 /// \brief Adjust the \p GlobalLSCost according to the target
8373 /// paring capabilities and the layout of the slices.
8374 /// \pre \p GlobalLSCost should account for at least as many loads as
8375 /// there is in the slices in \p LoadedSlices.
8376 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8377 LoadedSlice::Cost &GlobalLSCost) {
8378 unsigned NumberOfSlices = LoadedSlices.size();
8379 // If there is less than 2 elements, no pairing is possible.
8380 if (NumberOfSlices < 2)
8383 // Sort the slices so that elements that are likely to be next to each
8384 // other in memory are next to each other in the list.
8385 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8386 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8387 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8388 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8390 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8391 // First (resp. Second) is the first (resp. Second) potentially candidate
8392 // to be placed in a paired load.
8393 const LoadedSlice *First = NULL;
8394 const LoadedSlice *Second = NULL;
8395 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8396 // Set the beginning of the pair.
8399 Second = &LoadedSlices[CurrSlice];
8401 // If First is NULL, it means we start a new pair.
8402 // Get to the next slice.
8406 EVT LoadedType = First->getLoadedType();
8408 // If the types of the slices are different, we cannot pair them.
8409 if (LoadedType != Second->getLoadedType())
8412 // Check if the target supplies paired loads for this type.
8413 unsigned RequiredAlignment = 0;
8414 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8415 // move to the next pair, this type is hopeless.
8419 // Check if we meet the alignment requirement.
8420 if (RequiredAlignment > First->getAlignment())
8423 // Check that both loads are next to each other in memory.
8424 if (!areSlicesNextToEachOther(*First, *Second))
8427 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8428 --GlobalLSCost.Loads;
8429 // Move to the next pair.
8434 /// \brief Check the profitability of all involved LoadedSlice.
8435 /// Currently, it is considered profitable if there is exactly two
8436 /// involved slices (1) which are (2) next to each other in memory, and
8437 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8439 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8440 /// the elements themselves.
8442 /// FIXME: When the cost model will be mature enough, we can relax
8443 /// constraints (1) and (2).
8444 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8445 const APInt &UsedBits, bool ForCodeSize) {
8446 unsigned NumberOfSlices = LoadedSlices.size();
8447 if (StressLoadSlicing)
8448 return NumberOfSlices > 1;
8451 if (NumberOfSlices != 2)
8455 if (!areUsedBitsDense(UsedBits))
8459 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8460 // The original code has one big load.
8462 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8463 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8464 // Accumulate the cost of all the slices.
8465 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8466 GlobalSlicingCost += SliceCost;
8468 // Account as cost in the original configuration the gain obtained
8469 // with the current slices.
8470 OrigCost.addSliceGain(LS);
8473 // If the target supports paired load, adjust the cost accordingly.
8474 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8475 return OrigCost > GlobalSlicingCost;
8478 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8479 /// operations, split it in the various pieces being extracted.
8481 /// This sort of thing is introduced by SROA.
8482 /// This slicing takes care not to insert overlapping loads.
8483 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8484 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8485 if (Level < AfterLegalizeDAG)
8488 LoadSDNode *LD = cast<LoadSDNode>(N);
8489 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8490 !LD->getValueType(0).isInteger())
8493 // Keep track of already used bits to detect overlapping values.
8494 // In that case, we will just abort the transformation.
8495 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8497 SmallVector<LoadedSlice, 4> LoadedSlices;
8499 // Check if this load is used as several smaller chunks of bits.
8500 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8501 // of computation for each trunc.
8502 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8503 UI != UIEnd; ++UI) {
8504 // Skip the uses of the chain.
8505 if (UI.getUse().getResNo() != 0)
8511 // Check if this is a trunc(lshr).
8512 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8513 isa<ConstantSDNode>(User->getOperand(1))) {
8514 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8515 User = *User->use_begin();
8518 // At this point, User is a Truncate, iff we encountered, trunc or
8520 if (User->getOpcode() != ISD::TRUNCATE)
8523 // The width of the type must be a power of 2 and greater than 8-bits.
8524 // Otherwise the load cannot be represented in LLVM IR.
8525 // Moreover, if we shifted with a non-8-bits multiple, the slice
8526 // will be across several bytes. We do not support that.
8527 unsigned Width = User->getValueSizeInBits(0);
8528 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8531 // Build the slice for this chain of computations.
8532 LoadedSlice LS(User, LD, Shift, &DAG);
8533 APInt CurrentUsedBits = LS.getUsedBits();
8535 // Check if this slice overlaps with another.
8536 if ((CurrentUsedBits & UsedBits) != 0)
8538 // Update the bits used globally.
8539 UsedBits |= CurrentUsedBits;
8541 // Check if the new slice would be legal.
8545 // Record the slice.
8546 LoadedSlices.push_back(LS);
8549 // Abort slicing if it does not seem to be profitable.
8550 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8555 // Rewrite each chain to use an independent load.
8556 // By construction, each chain can be represented by a unique load.
8558 // Prepare the argument for the new token factor for all the slices.
8559 SmallVector<SDValue, 8> ArgChains;
8560 for (SmallVectorImpl<LoadedSlice>::const_iterator
8561 LSIt = LoadedSlices.begin(),
8562 LSItEnd = LoadedSlices.end();
8563 LSIt != LSItEnd; ++LSIt) {
8564 SDValue SliceInst = LSIt->loadSlice();
8565 CombineTo(LSIt->Inst, SliceInst, true);
8566 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8567 SliceInst = SliceInst.getOperand(0);
8568 assert(SliceInst->getOpcode() == ISD::LOAD &&
8569 "It takes more than a zext to get to the loaded slice!!");
8570 ArgChains.push_back(SliceInst.getValue(1));
8573 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8574 &ArgChains[0], ArgChains.size());
8575 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8579 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8580 /// load is having specific bytes cleared out. If so, return the byte size
8581 /// being masked out and the shift amount.
8582 static std::pair<unsigned, unsigned>
8583 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8584 std::pair<unsigned, unsigned> Result(0, 0);
8586 // Check for the structure we're looking for.
8587 if (V->getOpcode() != ISD::AND ||
8588 !isa<ConstantSDNode>(V->getOperand(1)) ||
8589 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8592 // Check the chain and pointer.
8593 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8594 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8596 // The store should be chained directly to the load or be an operand of a
8598 if (LD == Chain.getNode())
8600 else if (Chain->getOpcode() != ISD::TokenFactor)
8601 return Result; // Fail.
8604 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8605 if (Chain->getOperand(i).getNode() == LD) {
8609 if (!isOk) return Result;
8612 // This only handles simple types.
8613 if (V.getValueType() != MVT::i16 &&
8614 V.getValueType() != MVT::i32 &&
8615 V.getValueType() != MVT::i64)
8618 // Check the constant mask. Invert it so that the bits being masked out are
8619 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8620 // follow the sign bit for uniformity.
8621 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8622 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8623 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8624 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8625 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8626 if (NotMaskLZ == 64) return Result; // All zero mask.
8628 // See if we have a continuous run of bits. If so, we have 0*1+0*
8629 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8632 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8633 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8634 NotMaskLZ -= 64-V.getValueSizeInBits();
8636 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8637 switch (MaskedBytes) {
8641 default: return Result; // All one mask, or 5-byte mask.
8644 // Verify that the first bit starts at a multiple of mask so that the access
8645 // is aligned the same as the access width.
8646 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8648 Result.first = MaskedBytes;
8649 Result.second = NotMaskTZ/8;
8654 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8655 /// provides a value as specified by MaskInfo. If so, replace the specified
8656 /// store with a narrower store of truncated IVal.
8658 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8659 SDValue IVal, StoreSDNode *St,
8661 unsigned NumBytes = MaskInfo.first;
8662 unsigned ByteShift = MaskInfo.second;
8663 SelectionDAG &DAG = DC->getDAG();
8665 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8666 // that uses this. If not, this is not a replacement.
8667 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8668 ByteShift*8, (ByteShift+NumBytes)*8);
8669 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8671 // Check that it is legal on the target to do this. It is legal if the new
8672 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8674 MVT VT = MVT::getIntegerVT(NumBytes*8);
8675 if (!DC->isTypeLegal(VT))
8678 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8679 // shifted by ByteShift and truncated down to NumBytes.
8681 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8682 DAG.getConstant(ByteShift*8,
8683 DC->getShiftAmountTy(IVal.getValueType())));
8685 // Figure out the offset for the store and the alignment of the access.
8687 unsigned NewAlign = St->getAlignment();
8689 if (DAG.getTargetLoweringInfo().isLittleEndian())
8690 StOffset = ByteShift;
8692 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8694 SDValue Ptr = St->getBasePtr();
8696 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8697 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8698 NewAlign = MinAlign(NewAlign, StOffset);
8701 // Truncate down to the new size.
8702 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8705 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8706 St->getPointerInfo().getWithOffset(StOffset),
8707 false, false, NewAlign).getNode();
8711 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8712 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8713 /// of the loaded bits, try narrowing the load and store if it would end up
8714 /// being a win for performance or code size.
8715 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8716 StoreSDNode *ST = cast<StoreSDNode>(N);
8717 if (ST->isVolatile())
8720 SDValue Chain = ST->getChain();
8721 SDValue Value = ST->getValue();
8722 SDValue Ptr = ST->getBasePtr();
8723 EVT VT = Value.getValueType();
8725 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8728 unsigned Opc = Value.getOpcode();
8730 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8731 // is a byte mask indicating a consecutive number of bytes, check to see if
8732 // Y is known to provide just those bytes. If so, we try to replace the
8733 // load + replace + store sequence with a single (narrower) store, which makes
8735 if (Opc == ISD::OR) {
8736 std::pair<unsigned, unsigned> MaskedLoad;
8737 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8738 if (MaskedLoad.first)
8739 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8740 Value.getOperand(1), ST,this))
8741 return SDValue(NewST, 0);
8743 // Or is commutative, so try swapping X and Y.
8744 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8745 if (MaskedLoad.first)
8746 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8747 Value.getOperand(0), ST,this))
8748 return SDValue(NewST, 0);
8751 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8752 Value.getOperand(1).getOpcode() != ISD::Constant)
8755 SDValue N0 = Value.getOperand(0);
8756 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8757 Chain == SDValue(N0.getNode(), 1)) {
8758 LoadSDNode *LD = cast<LoadSDNode>(N0);
8759 if (LD->getBasePtr() != Ptr ||
8760 LD->getPointerInfo().getAddrSpace() !=
8761 ST->getPointerInfo().getAddrSpace())
8764 // Find the type to narrow it the load / op / store to.
8765 SDValue N1 = Value.getOperand(1);
8766 unsigned BitWidth = N1.getValueSizeInBits();
8767 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8768 if (Opc == ISD::AND)
8769 Imm ^= APInt::getAllOnesValue(BitWidth);
8770 if (Imm == 0 || Imm.isAllOnesValue())
8772 unsigned ShAmt = Imm.countTrailingZeros();
8773 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8774 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8775 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8776 while (NewBW < BitWidth &&
8777 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8778 TLI.isNarrowingProfitable(VT, NewVT))) {
8779 NewBW = NextPowerOf2(NewBW);
8780 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8782 if (NewBW >= BitWidth)
8785 // If the lsb changed does not start at the type bitwidth boundary,
8786 // start at the previous one.
8788 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8789 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8790 std::min(BitWidth, ShAmt + NewBW));
8791 if ((Imm & Mask) == Imm) {
8792 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8793 if (Opc == ISD::AND)
8794 NewImm ^= APInt::getAllOnesValue(NewBW);
8795 uint64_t PtrOff = ShAmt / 8;
8796 // For big endian targets, we need to adjust the offset to the pointer to
8797 // load the correct bytes.
8798 if (TLI.isBigEndian())
8799 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8801 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8802 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8803 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8806 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8807 Ptr.getValueType(), Ptr,
8808 DAG.getConstant(PtrOff, Ptr.getValueType()));
8809 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8810 LD->getChain(), NewPtr,
8811 LD->getPointerInfo().getWithOffset(PtrOff),
8812 LD->isVolatile(), LD->isNonTemporal(),
8813 LD->isInvariant(), NewAlign,
8815 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8816 DAG.getConstant(NewImm, NewVT));
8817 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8819 ST->getPointerInfo().getWithOffset(PtrOff),
8820 false, false, NewAlign);
8822 AddToWorkList(NewPtr.getNode());
8823 AddToWorkList(NewLD.getNode());
8824 AddToWorkList(NewVal.getNode());
8825 WorkListRemover DeadNodes(*this);
8826 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8835 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8836 /// if the load value isn't used by any other operations, then consider
8837 /// transforming the pair to integer load / store operations if the target
8838 /// deems the transformation profitable.
8839 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8840 StoreSDNode *ST = cast<StoreSDNode>(N);
8841 SDValue Chain = ST->getChain();
8842 SDValue Value = ST->getValue();
8843 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8844 Value.hasOneUse() &&
8845 Chain == SDValue(Value.getNode(), 1)) {
8846 LoadSDNode *LD = cast<LoadSDNode>(Value);
8847 EVT VT = LD->getMemoryVT();
8848 if (!VT.isFloatingPoint() ||
8849 VT != ST->getMemoryVT() ||
8850 LD->isNonTemporal() ||
8851 ST->isNonTemporal() ||
8852 LD->getPointerInfo().getAddrSpace() != 0 ||
8853 ST->getPointerInfo().getAddrSpace() != 0)
8856 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8857 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8858 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8859 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8860 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8863 unsigned LDAlign = LD->getAlignment();
8864 unsigned STAlign = ST->getAlignment();
8865 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8866 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8867 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8870 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8871 LD->getChain(), LD->getBasePtr(),
8872 LD->getPointerInfo(),
8873 false, false, false, LDAlign);
8875 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8876 NewLD, ST->getBasePtr(),
8877 ST->getPointerInfo(),
8878 false, false, STAlign);
8880 AddToWorkList(NewLD.getNode());
8881 AddToWorkList(NewST.getNode());
8882 WorkListRemover DeadNodes(*this);
8883 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8891 /// Helper struct to parse and store a memory address as base + index + offset.
8892 /// We ignore sign extensions when it is safe to do so.
8893 /// The following two expressions are not equivalent. To differentiate we need
8894 /// to store whether there was a sign extension involved in the index
8896 /// (load (i64 add (i64 copyfromreg %c)
8897 /// (i64 signextend (add (i8 load %index)
8901 /// (load (i64 add (i64 copyfromreg %c)
8902 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8904 struct BaseIndexOffset {
8908 bool IsIndexSignExt;
8910 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8912 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8913 bool IsIndexSignExt) :
8914 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8916 bool equalBaseIndex(const BaseIndexOffset &Other) {
8917 return Other.Base == Base && Other.Index == Index &&
8918 Other.IsIndexSignExt == IsIndexSignExt;
8921 /// Parses tree in Ptr for base, index, offset addresses.
8922 static BaseIndexOffset match(SDValue Ptr) {
8923 bool IsIndexSignExt = false;
8925 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8926 // instruction, then it could be just the BASE or everything else we don't
8927 // know how to handle. Just use Ptr as BASE and give up.
8928 if (Ptr->getOpcode() != ISD::ADD)
8929 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8931 // We know that we have at least an ADD instruction. Try to pattern match
8932 // the simple case of BASE + OFFSET.
8933 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8934 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8935 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8939 // Inside a loop the current BASE pointer is calculated using an ADD and a
8940 // MUL instruction. In this case Ptr is the actual BASE pointer.
8941 // (i64 add (i64 %array_ptr)
8942 // (i64 mul (i64 %induction_var)
8943 // (i64 %element_size)))
8944 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8945 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8947 // Look at Base + Index + Offset cases.
8948 SDValue Base = Ptr->getOperand(0);
8949 SDValue IndexOffset = Ptr->getOperand(1);
8951 // Skip signextends.
8952 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8953 IndexOffset = IndexOffset->getOperand(0);
8954 IsIndexSignExt = true;
8957 // Either the case of Base + Index (no offset) or something else.
8958 if (IndexOffset->getOpcode() != ISD::ADD)
8959 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8961 // Now we have the case of Base + Index + offset.
8962 SDValue Index = IndexOffset->getOperand(0);
8963 SDValue Offset = IndexOffset->getOperand(1);
8965 if (!isa<ConstantSDNode>(Offset))
8966 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8968 // Ignore signextends.
8969 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8970 Index = Index->getOperand(0);
8971 IsIndexSignExt = true;
8972 } else IsIndexSignExt = false;
8974 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8975 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8979 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8980 /// is located in a sequence of memory operations connected by a chain.
8982 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8983 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8984 // Ptr to the mem node.
8985 LSBaseSDNode *MemNode;
8986 // Offset from the base ptr.
8987 int64_t OffsetFromBase;
8988 // What is the sequence number of this mem node.
8989 // Lowest mem operand in the DAG starts at zero.
8990 unsigned SequenceNum;
8993 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8994 EVT MemVT = St->getMemoryVT();
8995 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8996 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8997 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8999 // Don't merge vectors into wider inputs.
9000 if (MemVT.isVector() || !MemVT.isSimple())
9003 // Perform an early exit check. Do not bother looking at stored values that
9004 // are not constants or loads.
9005 SDValue StoredVal = St->getValue();
9006 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9007 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9011 // Only look at ends of store sequences.
9012 SDValue Chain = SDValue(St, 1);
9013 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9016 // This holds the base pointer, index, and the offset in bytes from the base
9018 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9020 // We must have a base and an offset.
9021 if (!BasePtr.Base.getNode())
9024 // Do not handle stores to undef base pointers.
9025 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9028 // Save the LoadSDNodes that we find in the chain.
9029 // We need to make sure that these nodes do not interfere with
9030 // any of the store nodes.
9031 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9033 // Save the StoreSDNodes that we find in the chain.
9034 SmallVector<MemOpLink, 8> StoreNodes;
9036 // Walk up the chain and look for nodes with offsets from the same
9037 // base pointer. Stop when reaching an instruction with a different kind
9038 // or instruction which has a different base pointer.
9040 StoreSDNode *Index = St;
9042 // If the chain has more than one use, then we can't reorder the mem ops.
9043 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9046 // Find the base pointer and offset for this memory node.
9047 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9049 // Check that the base pointer is the same as the original one.
9050 if (!Ptr.equalBaseIndex(BasePtr))
9053 // Check that the alignment is the same.
9054 if (Index->getAlignment() != St->getAlignment())
9057 // The memory operands must not be volatile.
9058 if (Index->isVolatile() || Index->isIndexed())
9062 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9063 if (St->isTruncatingStore())
9066 // The stored memory type must be the same.
9067 if (Index->getMemoryVT() != MemVT)
9070 // We do not allow unaligned stores because we want to prevent overriding
9072 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9075 // We found a potential memory operand to merge.
9076 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9078 // Find the next memory operand in the chain. If the next operand in the
9079 // chain is a store then move up and continue the scan with the next
9080 // memory operand. If the next operand is a load save it and use alias
9081 // information to check if it interferes with anything.
9082 SDNode *NextInChain = Index->getChain().getNode();
9084 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9085 // We found a store node. Use it for the next iteration.
9088 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9089 if (Ldn->isVolatile()) {
9094 // Save the load node for later. Continue the scan.
9095 AliasLoadNodes.push_back(Ldn);
9096 NextInChain = Ldn->getChain().getNode();
9105 // Check if there is anything to merge.
9106 if (StoreNodes.size() < 2)
9109 // Sort the memory operands according to their distance from the base pointer.
9110 std::sort(StoreNodes.begin(), StoreNodes.end(),
9111 [](MemOpLink LHS, MemOpLink RHS) {
9112 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9113 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9114 LHS.SequenceNum > RHS.SequenceNum);
9117 // Scan the memory operations on the chain and find the first non-consecutive
9118 // store memory address.
9119 unsigned LastConsecutiveStore = 0;
9120 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9121 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9123 // Check that the addresses are consecutive starting from the second
9124 // element in the list of stores.
9126 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9127 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9132 // Check if this store interferes with any of the loads that we found.
9133 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9134 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9138 // We found a load that alias with this store. Stop the sequence.
9142 // Mark this node as useful.
9143 LastConsecutiveStore = i;
9146 // The node with the lowest store address.
9147 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9149 // Store the constants into memory as one consecutive store.
9151 unsigned LastLegalType = 0;
9152 unsigned LastLegalVectorType = 0;
9153 bool NonZero = false;
9154 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9155 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9156 SDValue StoredVal = St->getValue();
9158 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9159 NonZero |= !C->isNullValue();
9160 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9161 NonZero |= !C->getConstantFPValue()->isNullValue();
9167 // Find a legal type for the constant store.
9168 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9169 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9170 if (TLI.isTypeLegal(StoreTy))
9171 LastLegalType = i+1;
9172 // Or check whether a truncstore is legal.
9173 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9174 TargetLowering::TypePromoteInteger) {
9175 EVT LegalizedStoredValueTy =
9176 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9177 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9178 LastLegalType = i+1;
9181 // Find a legal type for the vector store.
9182 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9183 if (TLI.isTypeLegal(Ty))
9184 LastLegalVectorType = i + 1;
9187 // We only use vectors if the constant is known to be zero and the
9188 // function is not marked with the noimplicitfloat attribute.
9189 if (NonZero || NoVectors)
9190 LastLegalVectorType = 0;
9192 // Check if we found a legal integer type to store.
9193 if (LastLegalType == 0 && LastLegalVectorType == 0)
9196 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9197 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9199 // Make sure we have something to merge.
9203 unsigned EarliestNodeUsed = 0;
9204 for (unsigned i=0; i < NumElem; ++i) {
9205 // Find a chain for the new wide-store operand. Notice that some
9206 // of the store nodes that we found may not be selected for inclusion
9207 // in the wide store. The chain we use needs to be the chain of the
9208 // earliest store node which is *used* and replaced by the wide store.
9209 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9210 EarliestNodeUsed = i;
9213 // The earliest Node in the DAG.
9214 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9215 SDLoc DL(StoreNodes[0].MemNode);
9219 // Find a legal type for the vector store.
9220 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9221 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9222 StoredVal = DAG.getConstant(0, Ty);
9224 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9225 APInt StoreInt(StoreBW, 0);
9227 // Construct a single integer constant which is made of the smaller
9229 bool IsLE = TLI.isLittleEndian();
9230 for (unsigned i = 0; i < NumElem ; ++i) {
9231 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9232 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9233 SDValue Val = St->getValue();
9234 StoreInt<<=ElementSizeBytes*8;
9235 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9236 StoreInt|=C->getAPIntValue().zext(StoreBW);
9237 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9238 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9240 assert(false && "Invalid constant element type");
9244 // Create the new Load and Store operations.
9245 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9246 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9249 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9250 FirstInChain->getBasePtr(),
9251 FirstInChain->getPointerInfo(),
9253 FirstInChain->getAlignment());
9255 // Replace the first store with the new store
9256 CombineTo(EarliestOp, NewStore);
9257 // Erase all other stores.
9258 for (unsigned i = 0; i < NumElem ; ++i) {
9259 if (StoreNodes[i].MemNode == EarliestOp)
9261 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9262 // ReplaceAllUsesWith will replace all uses that existed when it was
9263 // called, but graph optimizations may cause new ones to appear. For
9264 // example, the case in pr14333 looks like
9266 // St's chain -> St -> another store -> X
9268 // And the only difference from St to the other store is the chain.
9269 // When we change it's chain to be St's chain they become identical,
9270 // get CSEed and the net result is that X is now a use of St.
9271 // Since we know that St is redundant, just iterate.
9272 while (!St->use_empty())
9273 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9274 removeFromWorkList(St);
9281 // Below we handle the case of multiple consecutive stores that
9282 // come from multiple consecutive loads. We merge them into a single
9283 // wide load and a single wide store.
9285 // Look for load nodes which are used by the stored values.
9286 SmallVector<MemOpLink, 8> LoadNodes;
9288 // Find acceptable loads. Loads need to have the same chain (token factor),
9289 // must not be zext, volatile, indexed, and they must be consecutive.
9290 BaseIndexOffset LdBasePtr;
9291 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9292 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9293 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9296 // Loads must only have one use.
9297 if (!Ld->hasNUsesOfValue(1, 0))
9300 // Check that the alignment is the same as the stores.
9301 if (Ld->getAlignment() != St->getAlignment())
9304 // The memory operands must not be volatile.
9305 if (Ld->isVolatile() || Ld->isIndexed())
9308 // We do not accept ext loads.
9309 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9312 // The stored memory type must be the same.
9313 if (Ld->getMemoryVT() != MemVT)
9316 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9317 // If this is not the first ptr that we check.
9318 if (LdBasePtr.Base.getNode()) {
9319 // The base ptr must be the same.
9320 if (!LdPtr.equalBaseIndex(LdBasePtr))
9323 // Check that all other base pointers are the same as this one.
9327 // We found a potential memory operand to merge.
9328 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9331 if (LoadNodes.size() < 2)
9334 // Scan the memory operations on the chain and find the first non-consecutive
9335 // load memory address. These variables hold the index in the store node
9337 unsigned LastConsecutiveLoad = 0;
9338 // This variable refers to the size and not index in the array.
9339 unsigned LastLegalVectorType = 0;
9340 unsigned LastLegalIntegerType = 0;
9341 StartAddress = LoadNodes[0].OffsetFromBase;
9342 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9343 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9344 // All loads much share the same chain.
9345 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9348 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9349 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9351 LastConsecutiveLoad = i;
9353 // Find a legal type for the vector store.
9354 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9355 if (TLI.isTypeLegal(StoreTy))
9356 LastLegalVectorType = i + 1;
9358 // Find a legal type for the integer store.
9359 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9360 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9361 if (TLI.isTypeLegal(StoreTy))
9362 LastLegalIntegerType = i + 1;
9363 // Or check whether a truncstore and extload is legal.
9364 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9365 TargetLowering::TypePromoteInteger) {
9366 EVT LegalizedStoredValueTy =
9367 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9368 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9369 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9370 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9371 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9372 LastLegalIntegerType = i+1;
9376 // Only use vector types if the vector type is larger than the integer type.
9377 // If they are the same, use integers.
9378 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9379 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9381 // We add +1 here because the LastXXX variables refer to location while
9382 // the NumElem refers to array/index size.
9383 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9384 NumElem = std::min(LastLegalType, NumElem);
9389 // The earliest Node in the DAG.
9390 unsigned EarliestNodeUsed = 0;
9391 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9392 for (unsigned i=1; i<NumElem; ++i) {
9393 // Find a chain for the new wide-store operand. Notice that some
9394 // of the store nodes that we found may not be selected for inclusion
9395 // in the wide store. The chain we use needs to be the chain of the
9396 // earliest store node which is *used* and replaced by the wide store.
9397 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9398 EarliestNodeUsed = i;
9401 // Find if it is better to use vectors or integers to load and store
9405 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9407 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9408 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9411 SDLoc LoadDL(LoadNodes[0].MemNode);
9412 SDLoc StoreDL(StoreNodes[0].MemNode);
9414 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9415 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9416 FirstLoad->getChain(),
9417 FirstLoad->getBasePtr(),
9418 FirstLoad->getPointerInfo(),
9419 false, false, false,
9420 FirstLoad->getAlignment());
9422 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9423 FirstInChain->getBasePtr(),
9424 FirstInChain->getPointerInfo(), false, false,
9425 FirstInChain->getAlignment());
9427 // Replace one of the loads with the new load.
9428 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9429 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9430 SDValue(NewLoad.getNode(), 1));
9432 // Remove the rest of the load chains.
9433 for (unsigned i = 1; i < NumElem ; ++i) {
9434 // Replace all chain users of the old load nodes with the chain of the new
9436 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9437 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9440 // Replace the first store with the new store.
9441 CombineTo(EarliestOp, NewStore);
9442 // Erase all other stores.
9443 for (unsigned i = 0; i < NumElem ; ++i) {
9444 // Remove all Store nodes.
9445 if (StoreNodes[i].MemNode == EarliestOp)
9447 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9448 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9449 removeFromWorkList(St);
9456 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9457 StoreSDNode *ST = cast<StoreSDNode>(N);
9458 SDValue Chain = ST->getChain();
9459 SDValue Value = ST->getValue();
9460 SDValue Ptr = ST->getBasePtr();
9462 // If this is a store of a bit convert, store the input value if the
9463 // resultant store does not need a higher alignment than the original.
9464 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9465 ST->isUnindexed()) {
9466 unsigned OrigAlign = ST->getAlignment();
9467 EVT SVT = Value.getOperand(0).getValueType();
9468 unsigned Align = TLI.getDataLayout()->
9469 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9470 if (Align <= OrigAlign &&
9471 ((!LegalOperations && !ST->isVolatile()) ||
9472 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9473 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9474 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9475 ST->isNonTemporal(), OrigAlign,
9479 // Turn 'store undef, Ptr' -> nothing.
9480 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9483 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9484 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9485 // NOTE: If the original store is volatile, this transform must not increase
9486 // the number of stores. For example, on x86-32 an f64 can be stored in one
9487 // processor operation but an i64 (which is not legal) requires two. So the
9488 // transform should not be done in this case.
9489 if (Value.getOpcode() != ISD::TargetConstantFP) {
9491 switch (CFP->getSimpleValueType(0).SimpleTy) {
9492 default: llvm_unreachable("Unknown FP type");
9493 case MVT::f16: // We don't do this for these yet.
9499 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9500 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9501 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9502 bitcastToAPInt().getZExtValue(), MVT::i32);
9503 return DAG.getStore(Chain, SDLoc(N), Tmp,
9504 Ptr, ST->getMemOperand());
9508 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9509 !ST->isVolatile()) ||
9510 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9511 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9512 getZExtValue(), MVT::i64);
9513 return DAG.getStore(Chain, SDLoc(N), Tmp,
9514 Ptr, ST->getMemOperand());
9517 if (!ST->isVolatile() &&
9518 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9519 // Many FP stores are not made apparent until after legalize, e.g. for
9520 // argument passing. Since this is so common, custom legalize the
9521 // 64-bit integer store into two 32-bit stores.
9522 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9523 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9524 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9525 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9527 unsigned Alignment = ST->getAlignment();
9528 bool isVolatile = ST->isVolatile();
9529 bool isNonTemporal = ST->isNonTemporal();
9530 const MDNode *TBAAInfo = ST->getTBAAInfo();
9532 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9533 Ptr, ST->getPointerInfo(),
9534 isVolatile, isNonTemporal,
9535 ST->getAlignment(), TBAAInfo);
9536 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9537 DAG.getConstant(4, Ptr.getValueType()));
9538 Alignment = MinAlign(Alignment, 4U);
9539 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9540 Ptr, ST->getPointerInfo().getWithOffset(4),
9541 isVolatile, isNonTemporal,
9542 Alignment, TBAAInfo);
9543 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9552 // Try to infer better alignment information than the store already has.
9553 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9554 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9555 if (Align > ST->getAlignment())
9556 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9557 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9558 ST->isVolatile(), ST->isNonTemporal(), Align,
9563 // Try transforming a pair floating point load / store ops to integer
9564 // load / store ops.
9565 SDValue NewST = TransformFPLoadStorePair(N);
9566 if (NewST.getNode())
9569 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9570 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9572 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9573 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9576 if (UseAA && ST->isUnindexed()) {
9577 // Walk up chain skipping non-aliasing memory nodes.
9578 SDValue BetterChain = FindBetterChain(N, Chain);
9580 // If there is a better chain.
9581 if (Chain != BetterChain) {
9584 // Replace the chain to avoid dependency.
9585 if (ST->isTruncatingStore()) {
9586 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9587 ST->getMemoryVT(), ST->getMemOperand());
9589 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9590 ST->getMemOperand());
9593 // Create token to keep both nodes around.
9594 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9595 MVT::Other, Chain, ReplStore);
9597 // Make sure the new and old chains are cleaned up.
9598 AddToWorkList(Token.getNode());
9600 // Don't add users to work list.
9601 return CombineTo(N, Token, false);
9605 // Try transforming N to an indexed store.
9606 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9607 return SDValue(N, 0);
9609 // FIXME: is there such a thing as a truncating indexed store?
9610 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9611 Value.getValueType().isInteger()) {
9612 // See if we can simplify the input to this truncstore with knowledge that
9613 // only the low bits are being used. For example:
9614 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9616 GetDemandedBits(Value,
9617 APInt::getLowBitsSet(
9618 Value.getValueType().getScalarType().getSizeInBits(),
9619 ST->getMemoryVT().getScalarType().getSizeInBits()));
9620 AddToWorkList(Value.getNode());
9621 if (Shorter.getNode())
9622 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9623 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9625 // Otherwise, see if we can simplify the operation with
9626 // SimplifyDemandedBits, which only works if the value has a single use.
9627 if (SimplifyDemandedBits(Value,
9628 APInt::getLowBitsSet(
9629 Value.getValueType().getScalarType().getSizeInBits(),
9630 ST->getMemoryVT().getScalarType().getSizeInBits())))
9631 return SDValue(N, 0);
9634 // If this is a load followed by a store to the same location, then the store
9636 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9637 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9638 ST->isUnindexed() && !ST->isVolatile() &&
9639 // There can't be any side effects between the load and store, such as
9641 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9642 // The store is dead, remove it.
9647 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9648 // truncating store. We can do this even if this is already a truncstore.
9649 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9650 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9651 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9652 ST->getMemoryVT())) {
9653 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9654 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9657 // Only perform this optimization before the types are legal, because we
9658 // don't want to perform this optimization on every DAGCombine invocation.
9660 bool EverChanged = false;
9663 // There can be multiple store sequences on the same chain.
9664 // Keep trying to merge store sequences until we are unable to do so
9665 // or until we merge the last store on the chain.
9666 bool Changed = MergeConsecutiveStores(ST);
9667 EverChanged |= Changed;
9668 if (!Changed) break;
9669 } while (ST->getOpcode() != ISD::DELETED_NODE);
9672 return SDValue(N, 0);
9675 return ReduceLoadOpStoreWidth(N);
9678 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9679 SDValue InVec = N->getOperand(0);
9680 SDValue InVal = N->getOperand(1);
9681 SDValue EltNo = N->getOperand(2);
9684 // If the inserted element is an UNDEF, just use the input vector.
9685 if (InVal.getOpcode() == ISD::UNDEF)
9688 EVT VT = InVec.getValueType();
9690 // If we can't generate a legal BUILD_VECTOR, exit
9691 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9694 // Check that we know which element is being inserted
9695 if (!isa<ConstantSDNode>(EltNo))
9697 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9699 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9700 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9702 SmallVector<SDValue, 8> Ops;
9703 // Do not combine these two vectors if the output vector will not replace
9704 // the input vector.
9705 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9706 Ops.append(InVec.getNode()->op_begin(),
9707 InVec.getNode()->op_end());
9708 } else if (InVec.getOpcode() == ISD::UNDEF) {
9709 unsigned NElts = VT.getVectorNumElements();
9710 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9715 // Insert the element
9716 if (Elt < Ops.size()) {
9717 // All the operands of BUILD_VECTOR must have the same type;
9718 // we enforce that here.
9719 EVT OpVT = Ops[0].getValueType();
9720 if (InVal.getValueType() != OpVT)
9721 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9722 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9723 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9727 // Return the new vector
9728 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9729 VT, &Ops[0], Ops.size());
9732 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9733 // (vextract (scalar_to_vector val, 0) -> val
9734 SDValue InVec = N->getOperand(0);
9735 EVT VT = InVec.getValueType();
9736 EVT NVT = N->getValueType(0);
9738 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9739 // Check if the result type doesn't match the inserted element type. A
9740 // SCALAR_TO_VECTOR may truncate the inserted element and the
9741 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9742 SDValue InOp = InVec.getOperand(0);
9743 if (InOp.getValueType() != NVT) {
9744 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9745 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9750 SDValue EltNo = N->getOperand(1);
9751 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9753 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9754 // We only perform this optimization before the op legalization phase because
9755 // we may introduce new vector instructions which are not backed by TD
9756 // patterns. For example on AVX, extracting elements from a wide vector
9757 // without using extract_subvector. However, if we can find an underlying
9758 // scalar value, then we can always use that.
9759 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9761 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9762 int NumElem = VT.getVectorNumElements();
9763 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9764 // Find the new index to extract from.
9765 int OrigElt = SVOp->getMaskElt(Elt);
9767 // Extracting an undef index is undef.
9769 return DAG.getUNDEF(NVT);
9771 // Select the right vector half to extract from.
9773 if (OrigElt < NumElem) {
9774 SVInVec = InVec->getOperand(0);
9776 SVInVec = InVec->getOperand(1);
9780 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9781 SDValue InOp = SVInVec.getOperand(OrigElt);
9782 if (InOp.getValueType() != NVT) {
9783 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9784 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9790 // FIXME: We should handle recursing on other vector shuffles and
9791 // scalar_to_vector here as well.
9793 if (!LegalOperations) {
9794 EVT IndexTy = TLI.getVectorIdxTy();
9795 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9796 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9800 // Perform only after legalization to ensure build_vector / vector_shuffle
9801 // optimizations have already been done.
9802 if (!LegalOperations) return SDValue();
9804 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9805 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9806 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9809 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9810 bool NewLoad = false;
9811 bool BCNumEltsChanged = false;
9812 EVT ExtVT = VT.getVectorElementType();
9815 // If the result of load has to be truncated, then it's not necessarily
9817 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9820 if (InVec.getOpcode() == ISD::BITCAST) {
9821 // Don't duplicate a load with other uses.
9822 if (!InVec.hasOneUse())
9825 EVT BCVT = InVec.getOperand(0).getValueType();
9826 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9828 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9829 BCNumEltsChanged = true;
9830 InVec = InVec.getOperand(0);
9831 ExtVT = BCVT.getVectorElementType();
9835 LoadSDNode *LN0 = NULL;
9836 const ShuffleVectorSDNode *SVN = NULL;
9837 if (ISD::isNormalLoad(InVec.getNode())) {
9838 LN0 = cast<LoadSDNode>(InVec);
9839 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9840 InVec.getOperand(0).getValueType() == ExtVT &&
9841 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9842 // Don't duplicate a load with other uses.
9843 if (!InVec.hasOneUse())
9846 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9847 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9848 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9850 // (load $addr+1*size)
9852 // Don't duplicate a load with other uses.
9853 if (!InVec.hasOneUse())
9856 // If the bit convert changed the number of elements, it is unsafe
9857 // to examine the mask.
9858 if (BCNumEltsChanged)
9861 // Select the input vector, guarding against out of range extract vector.
9862 unsigned NumElems = VT.getVectorNumElements();
9863 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9864 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9866 if (InVec.getOpcode() == ISD::BITCAST) {
9867 // Don't duplicate a load with other uses.
9868 if (!InVec.hasOneUse())
9871 InVec = InVec.getOperand(0);
9873 if (ISD::isNormalLoad(InVec.getNode())) {
9874 LN0 = cast<LoadSDNode>(InVec);
9875 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9879 // Make sure we found a non-volatile load and the extractelement is
9881 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9884 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9886 return DAG.getUNDEF(LVT);
9888 unsigned Align = LN0->getAlignment();
9890 // Check the resultant load doesn't need a higher alignment than the
9894 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9896 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9902 SDValue NewPtr = LN0->getBasePtr();
9903 unsigned PtrOff = 0;
9906 PtrOff = LVT.getSizeInBits() * Elt / 8;
9907 EVT PtrType = NewPtr.getValueType();
9908 if (TLI.isBigEndian())
9909 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9910 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9911 DAG.getConstant(PtrOff, PtrType));
9914 // The replacement we need to do here is a little tricky: we need to
9915 // replace an extractelement of a load with a load.
9916 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9917 // Note that this replacement assumes that the extractvalue is the only
9918 // use of the load; that's okay because we don't want to perform this
9919 // transformation in other cases anyway.
9922 if (NVT.bitsGT(LVT)) {
9923 // If the result type of vextract is wider than the load, then issue an
9924 // extending load instead.
9925 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9926 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9927 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9928 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9929 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9930 Align, LN0->getTBAAInfo());
9931 Chain = Load.getValue(1);
9933 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9934 LN0->getPointerInfo().getWithOffset(PtrOff),
9935 LN0->isVolatile(), LN0->isNonTemporal(),
9936 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9937 Chain = Load.getValue(1);
9938 if (NVT.bitsLT(LVT))
9939 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9941 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9943 WorkListRemover DeadNodes(*this);
9944 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9945 SDValue To[] = { Load, Chain };
9946 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9947 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9948 // worklist explicitly as well.
9949 AddToWorkList(Load.getNode());
9950 AddUsersToWorkList(Load.getNode()); // Add users too
9951 // Make sure to revisit this node to clean it up; it will usually be dead.
9953 return SDValue(N, 0);
9959 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9960 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9961 // We perform this optimization post type-legalization because
9962 // the type-legalizer often scalarizes integer-promoted vectors.
9963 // Performing this optimization before may create bit-casts which
9964 // will be type-legalized to complex code sequences.
9965 // We perform this optimization only before the operation legalizer because we
9966 // may introduce illegal operations.
9967 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9970 unsigned NumInScalars = N->getNumOperands();
9972 EVT VT = N->getValueType(0);
9974 // Check to see if this is a BUILD_VECTOR of a bunch of values
9975 // which come from any_extend or zero_extend nodes. If so, we can create
9976 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9977 // optimizations. We do not handle sign-extend because we can't fill the sign
9979 EVT SourceType = MVT::Other;
9980 bool AllAnyExt = true;
9982 for (unsigned i = 0; i != NumInScalars; ++i) {
9983 SDValue In = N->getOperand(i);
9984 // Ignore undef inputs.
9985 if (In.getOpcode() == ISD::UNDEF) continue;
9987 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9988 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9990 // Abort if the element is not an extension.
9991 if (!ZeroExt && !AnyExt) {
9992 SourceType = MVT::Other;
9996 // The input is a ZeroExt or AnyExt. Check the original type.
9997 EVT InTy = In.getOperand(0).getValueType();
9999 // Check that all of the widened source types are the same.
10000 if (SourceType == MVT::Other)
10003 else if (InTy != SourceType) {
10004 // Multiple income types. Abort.
10005 SourceType = MVT::Other;
10009 // Check if all of the extends are ANY_EXTENDs.
10010 AllAnyExt &= AnyExt;
10013 // In order to have valid types, all of the inputs must be extended from the
10014 // same source type and all of the inputs must be any or zero extend.
10015 // Scalar sizes must be a power of two.
10016 EVT OutScalarTy = VT.getScalarType();
10017 bool ValidTypes = SourceType != MVT::Other &&
10018 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10019 isPowerOf2_32(SourceType.getSizeInBits());
10021 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10022 // turn into a single shuffle instruction.
10026 bool isLE = TLI.isLittleEndian();
10027 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10028 assert(ElemRatio > 1 && "Invalid element size ratio");
10029 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10030 DAG.getConstant(0, SourceType);
10032 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10033 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10035 // Populate the new build_vector
10036 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10037 SDValue Cast = N->getOperand(i);
10038 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10039 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10040 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10042 if (Cast.getOpcode() == ISD::UNDEF)
10043 In = DAG.getUNDEF(SourceType);
10045 In = Cast->getOperand(0);
10046 unsigned Index = isLE ? (i * ElemRatio) :
10047 (i * ElemRatio + (ElemRatio - 1));
10049 assert(Index < Ops.size() && "Invalid index");
10053 // The type of the new BUILD_VECTOR node.
10054 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10055 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10056 "Invalid vector size");
10057 // Check if the new vector type is legal.
10058 if (!isTypeLegal(VecVT)) return SDValue();
10060 // Make the new BUILD_VECTOR.
10061 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10063 // The new BUILD_VECTOR node has the potential to be further optimized.
10064 AddToWorkList(BV.getNode());
10065 // Bitcast to the desired type.
10066 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10069 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10070 EVT VT = N->getValueType(0);
10072 unsigned NumInScalars = N->getNumOperands();
10075 EVT SrcVT = MVT::Other;
10076 unsigned Opcode = ISD::DELETED_NODE;
10077 unsigned NumDefs = 0;
10079 for (unsigned i = 0; i != NumInScalars; ++i) {
10080 SDValue In = N->getOperand(i);
10081 unsigned Opc = In.getOpcode();
10083 if (Opc == ISD::UNDEF)
10086 // If all scalar values are floats and converted from integers.
10087 if (Opcode == ISD::DELETED_NODE &&
10088 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10095 EVT InVT = In.getOperand(0).getValueType();
10097 // If all scalar values are typed differently, bail out. It's chosen to
10098 // simplify BUILD_VECTOR of integer types.
10099 if (SrcVT == MVT::Other)
10106 // If the vector has just one element defined, it's not worth to fold it into
10107 // a vectorized one.
10111 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10112 && "Should only handle conversion from integer to float.");
10113 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10115 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10117 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10120 SmallVector<SDValue, 8> Opnds;
10121 for (unsigned i = 0; i != NumInScalars; ++i) {
10122 SDValue In = N->getOperand(i);
10124 if (In.getOpcode() == ISD::UNDEF)
10125 Opnds.push_back(DAG.getUNDEF(SrcVT));
10127 Opnds.push_back(In.getOperand(0));
10129 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10130 &Opnds[0], Opnds.size());
10131 AddToWorkList(BV.getNode());
10133 return DAG.getNode(Opcode, dl, VT, BV);
10136 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10137 unsigned NumInScalars = N->getNumOperands();
10139 EVT VT = N->getValueType(0);
10141 // A vector built entirely of undefs is undef.
10142 if (ISD::allOperandsUndef(N))
10143 return DAG.getUNDEF(VT);
10145 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10149 V = reduceBuildVecConvertToConvertBuildVec(N);
10153 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10154 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10155 // at most two distinct vectors, turn this into a shuffle node.
10157 // May only combine to shuffle after legalize if shuffle is legal.
10158 if (LegalOperations &&
10159 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10162 SDValue VecIn1, VecIn2;
10163 for (unsigned i = 0; i != NumInScalars; ++i) {
10164 // Ignore undef inputs.
10165 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10167 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10168 // constant index, bail out.
10169 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10170 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10171 VecIn1 = VecIn2 = SDValue(0, 0);
10175 // We allow up to two distinct input vectors.
10176 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10177 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10180 if (VecIn1.getNode() == 0) {
10181 VecIn1 = ExtractedFromVec;
10182 } else if (VecIn2.getNode() == 0) {
10183 VecIn2 = ExtractedFromVec;
10185 // Too many inputs.
10186 VecIn1 = VecIn2 = SDValue(0, 0);
10191 // If everything is good, we can make a shuffle operation.
10192 if (VecIn1.getNode()) {
10193 SmallVector<int, 8> Mask;
10194 for (unsigned i = 0; i != NumInScalars; ++i) {
10195 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10196 Mask.push_back(-1);
10200 // If extracting from the first vector, just use the index directly.
10201 SDValue Extract = N->getOperand(i);
10202 SDValue ExtVal = Extract.getOperand(1);
10203 if (Extract.getOperand(0) == VecIn1) {
10204 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10205 if (ExtIndex > VT.getVectorNumElements())
10208 Mask.push_back(ExtIndex);
10212 // Otherwise, use InIdx + VecSize
10213 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10214 Mask.push_back(Idx+NumInScalars);
10217 // We can't generate a shuffle node with mismatched input and output types.
10218 // Attempt to transform a single input vector to the correct type.
10219 if ((VT != VecIn1.getValueType())) {
10220 // We don't support shuffeling between TWO values of different types.
10221 if (VecIn2.getNode() != 0)
10224 // We only support widening of vectors which are half the size of the
10225 // output registers. For example XMM->YMM widening on X86 with AVX.
10226 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10229 // If the input vector type has a different base type to the output
10230 // vector type, bail out.
10231 if (VecIn1.getValueType().getVectorElementType() !=
10232 VT.getVectorElementType())
10235 // Widen the input vector by adding undef values.
10236 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10237 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10240 // If VecIn2 is unused then change it to undef.
10241 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10243 // Check that we were able to transform all incoming values to the same
10245 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10246 VecIn1.getValueType() != VT)
10249 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10250 if (!isTypeLegal(VT))
10253 // Return the new VECTOR_SHUFFLE node.
10257 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10263 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10264 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10265 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10266 // inputs come from at most two distinct vectors, turn this into a shuffle
10269 // If we only have one input vector, we don't need to do any concatenation.
10270 if (N->getNumOperands() == 1)
10271 return N->getOperand(0);
10273 // Check if all of the operands are undefs.
10274 EVT VT = N->getValueType(0);
10275 if (ISD::allOperandsUndef(N))
10276 return DAG.getUNDEF(VT);
10278 // Optimize concat_vectors where one of the vectors is undef.
10279 if (N->getNumOperands() == 2 &&
10280 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10281 SDValue In = N->getOperand(0);
10282 assert(In.getValueType().isVector() && "Must concat vectors");
10284 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10285 if (In->getOpcode() == ISD::BITCAST &&
10286 !In->getOperand(0)->getValueType(0).isVector()) {
10287 SDValue Scalar = In->getOperand(0);
10288 EVT SclTy = Scalar->getValueType(0);
10290 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10293 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10294 VT.getSizeInBits() / SclTy.getSizeInBits());
10295 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10298 SDLoc dl = SDLoc(N);
10299 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10300 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10304 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10305 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10306 if (N->getNumOperands() == 2 &&
10307 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10308 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10309 EVT VT = N->getValueType(0);
10310 SDValue N0 = N->getOperand(0);
10311 SDValue N1 = N->getOperand(1);
10312 SmallVector<SDValue, 8> Opnds;
10313 unsigned BuildVecNumElts = N0.getNumOperands();
10315 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10316 Opnds.push_back(N0.getOperand(i));
10317 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10318 Opnds.push_back(N1.getOperand(i));
10320 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10324 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10325 // nodes often generate nop CONCAT_VECTOR nodes.
10326 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10327 // place the incoming vectors at the exact same location.
10328 SDValue SingleSource = SDValue();
10329 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10331 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10332 SDValue Op = N->getOperand(i);
10334 if (Op.getOpcode() == ISD::UNDEF)
10337 // Check if this is the identity extract:
10338 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10341 // Find the single incoming vector for the extract_subvector.
10342 if (SingleSource.getNode()) {
10343 if (Op.getOperand(0) != SingleSource)
10346 SingleSource = Op.getOperand(0);
10348 // Check the source type is the same as the type of the result.
10349 // If not, this concat may extend the vector, so we can not
10350 // optimize it away.
10351 if (SingleSource.getValueType() != N->getValueType(0))
10355 unsigned IdentityIndex = i * PartNumElem;
10356 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10357 // The extract index must be constant.
10361 // Check that we are reading from the identity index.
10362 if (CS->getZExtValue() != IdentityIndex)
10366 if (SingleSource.getNode())
10367 return SingleSource;
10372 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10373 EVT NVT = N->getValueType(0);
10374 SDValue V = N->getOperand(0);
10376 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10378 // (extract_subvec (concat V1, V2, ...), i)
10381 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10383 if (V->getOperand(0).getValueType() != NVT)
10385 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10386 unsigned NumElems = NVT.getVectorNumElements();
10387 assert((Idx % NumElems) == 0 &&
10388 "IDX in concat is not a multiple of the result vector length.");
10389 return V->getOperand(Idx / NumElems);
10393 if (V->getOpcode() == ISD::BITCAST)
10394 V = V.getOperand(0);
10396 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10398 // Handle only simple case where vector being inserted and vector
10399 // being extracted are of same type, and are half size of larger vectors.
10400 EVT BigVT = V->getOperand(0).getValueType();
10401 EVT SmallVT = V->getOperand(1).getValueType();
10402 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10405 // Only handle cases where both indexes are constants with the same type.
10406 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10407 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10409 if (InsIdx && ExtIdx &&
10410 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10411 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10413 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10415 // indices are equal or bit offsets are equal => V1
10416 // otherwise => (extract_subvec V1, ExtIdx)
10417 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10418 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10419 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10420 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10421 DAG.getNode(ISD::BITCAST, dl,
10422 N->getOperand(0).getValueType(),
10423 V->getOperand(0)), N->getOperand(1));
10430 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10431 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10432 EVT VT = N->getValueType(0);
10433 unsigned NumElts = VT.getVectorNumElements();
10435 SDValue N0 = N->getOperand(0);
10436 SDValue N1 = N->getOperand(1);
10437 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10439 SmallVector<SDValue, 4> Ops;
10440 EVT ConcatVT = N0.getOperand(0).getValueType();
10441 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10442 unsigned NumConcats = NumElts / NumElemsPerConcat;
10444 // Look at every vector that's inserted. We're looking for exact
10445 // subvector-sized copies from a concatenated vector
10446 for (unsigned I = 0; I != NumConcats; ++I) {
10447 // Make sure we're dealing with a copy.
10448 unsigned Begin = I * NumElemsPerConcat;
10449 bool AllUndef = true, NoUndef = true;
10450 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10451 if (SVN->getMaskElt(J) >= 0)
10458 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10461 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10462 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10465 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10466 if (FirstElt < N0.getNumOperands())
10467 Ops.push_back(N0.getOperand(FirstElt));
10469 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10471 } else if (AllUndef) {
10472 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10473 } else { // Mixed with general masks and undefs, can't do optimization.
10478 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10482 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10483 EVT VT = N->getValueType(0);
10484 unsigned NumElts = VT.getVectorNumElements();
10486 SDValue N0 = N->getOperand(0);
10487 SDValue N1 = N->getOperand(1);
10489 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10491 // Canonicalize shuffle undef, undef -> undef
10492 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10493 return DAG.getUNDEF(VT);
10495 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10497 // Canonicalize shuffle v, v -> v, undef
10499 SmallVector<int, 8> NewMask;
10500 for (unsigned i = 0; i != NumElts; ++i) {
10501 int Idx = SVN->getMaskElt(i);
10502 if (Idx >= (int)NumElts) Idx -= NumElts;
10503 NewMask.push_back(Idx);
10505 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10509 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10510 if (N0.getOpcode() == ISD::UNDEF) {
10511 SmallVector<int, 8> NewMask;
10512 for (unsigned i = 0; i != NumElts; ++i) {
10513 int Idx = SVN->getMaskElt(i);
10515 if (Idx >= (int)NumElts)
10518 Idx = -1; // remove reference to lhs
10520 NewMask.push_back(Idx);
10522 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10526 // Remove references to rhs if it is undef
10527 if (N1.getOpcode() == ISD::UNDEF) {
10528 bool Changed = false;
10529 SmallVector<int, 8> NewMask;
10530 for (unsigned i = 0; i != NumElts; ++i) {
10531 int Idx = SVN->getMaskElt(i);
10532 if (Idx >= (int)NumElts) {
10536 NewMask.push_back(Idx);
10539 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10542 // If it is a splat, check if the argument vector is another splat or a
10543 // build_vector with all scalar elements the same.
10544 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10545 SDNode *V = N0.getNode();
10547 // If this is a bit convert that changes the element type of the vector but
10548 // not the number of vector elements, look through it. Be careful not to
10549 // look though conversions that change things like v4f32 to v2f64.
10550 if (V->getOpcode() == ISD::BITCAST) {
10551 SDValue ConvInput = V->getOperand(0);
10552 if (ConvInput.getValueType().isVector() &&
10553 ConvInput.getValueType().getVectorNumElements() == NumElts)
10554 V = ConvInput.getNode();
10557 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10558 assert(V->getNumOperands() == NumElts &&
10559 "BUILD_VECTOR has wrong number of operands");
10561 bool AllSame = true;
10562 for (unsigned i = 0; i != NumElts; ++i) {
10563 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10564 Base = V->getOperand(i);
10568 // Splat of <u, u, u, u>, return <u, u, u, u>
10569 if (!Base.getNode())
10571 for (unsigned i = 0; i != NumElts; ++i) {
10572 if (V->getOperand(i) != Base) {
10577 // Splat of <x, x, x, x>, return <x, x, x, x>
10583 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10584 Level < AfterLegalizeVectorOps &&
10585 (N1.getOpcode() == ISD::UNDEF ||
10586 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10587 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10588 SDValue V = partitionShuffleOfConcats(N, DAG);
10594 // If this shuffle node is simply a swizzle of another shuffle node,
10595 // and it reverses the swizzle of the previous shuffle then we can
10596 // optimize shuffle(shuffle(x, undef), undef) -> x.
10597 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10598 N1.getOpcode() == ISD::UNDEF) {
10600 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10602 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10603 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10606 // The incoming shuffle must be of the same type as the result of the
10607 // current shuffle.
10608 assert(OtherSV->getOperand(0).getValueType() == VT &&
10609 "Shuffle types don't match");
10611 for (unsigned i = 0; i != NumElts; ++i) {
10612 int Idx = SVN->getMaskElt(i);
10613 assert(Idx < (int)NumElts && "Index references undef operand");
10614 // Next, this index comes from the first value, which is the incoming
10615 // shuffle. Adopt the incoming index.
10617 Idx = OtherSV->getMaskElt(Idx);
10619 // The combined shuffle must map each index to itself.
10620 if (Idx >= 0 && (unsigned)Idx != i)
10624 return OtherSV->getOperand(0);
10630 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10631 SDValue N0 = N->getOperand(0);
10632 SDValue N2 = N->getOperand(2);
10634 // If the input vector is a concatenation, and the insert replaces
10635 // one of the halves, we can optimize into a single concat_vectors.
10636 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10637 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10638 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10639 EVT VT = N->getValueType(0);
10641 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10642 // (concat_vectors Z, Y)
10644 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10645 N->getOperand(1), N0.getOperand(1));
10647 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10648 // (concat_vectors X, Z)
10649 if (InsIdx == VT.getVectorNumElements()/2)
10650 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10651 N0.getOperand(0), N->getOperand(1));
10657 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10658 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10659 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10660 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10661 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10662 EVT VT = N->getValueType(0);
10664 SDValue LHS = N->getOperand(0);
10665 SDValue RHS = N->getOperand(1);
10666 if (N->getOpcode() == ISD::AND) {
10667 if (RHS.getOpcode() == ISD::BITCAST)
10668 RHS = RHS.getOperand(0);
10669 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10670 SmallVector<int, 8> Indices;
10671 unsigned NumElts = RHS.getNumOperands();
10672 for (unsigned i = 0; i != NumElts; ++i) {
10673 SDValue Elt = RHS.getOperand(i);
10674 if (!isa<ConstantSDNode>(Elt))
10677 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10678 Indices.push_back(i);
10679 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10680 Indices.push_back(NumElts);
10685 // Let's see if the target supports this vector_shuffle.
10686 EVT RVT = RHS.getValueType();
10687 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10690 // Return the new VECTOR_SHUFFLE node.
10691 EVT EltVT = RVT.getVectorElementType();
10692 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10693 DAG.getConstant(0, EltVT));
10694 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10695 RVT, &ZeroOps[0], ZeroOps.size());
10696 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10697 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10698 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10705 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10706 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10707 assert(N->getValueType(0).isVector() &&
10708 "SimplifyVBinOp only works on vectors!");
10710 SDValue LHS = N->getOperand(0);
10711 SDValue RHS = N->getOperand(1);
10712 SDValue Shuffle = XformToShuffleWithZero(N);
10713 if (Shuffle.getNode()) return Shuffle;
10715 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10717 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10718 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10719 // Check if both vectors are constants. If not bail out.
10720 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10721 cast<BuildVectorSDNode>(RHS)->isConstant()))
10724 SmallVector<SDValue, 8> Ops;
10725 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10726 SDValue LHSOp = LHS.getOperand(i);
10727 SDValue RHSOp = RHS.getOperand(i);
10729 // Can't fold divide by zero.
10730 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10731 N->getOpcode() == ISD::FDIV) {
10732 if ((RHSOp.getOpcode() == ISD::Constant &&
10733 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10734 (RHSOp.getOpcode() == ISD::ConstantFP &&
10735 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10739 EVT VT = LHSOp.getValueType();
10740 EVT RVT = RHSOp.getValueType();
10742 // Integer BUILD_VECTOR operands may have types larger than the element
10743 // size (e.g., when the element type is not legal). Prior to type
10744 // legalization, the types may not match between the two BUILD_VECTORS.
10745 // Truncate one of the operands to make them match.
10746 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10747 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10749 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10753 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10755 if (FoldOp.getOpcode() != ISD::UNDEF &&
10756 FoldOp.getOpcode() != ISD::Constant &&
10757 FoldOp.getOpcode() != ISD::ConstantFP)
10759 Ops.push_back(FoldOp);
10760 AddToWorkList(FoldOp.getNode());
10763 if (Ops.size() == LHS.getNumOperands())
10764 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10765 LHS.getValueType(), &Ops[0], Ops.size());
10771 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10772 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10773 assert(N->getValueType(0).isVector() &&
10774 "SimplifyVUnaryOp only works on vectors!");
10776 SDValue N0 = N->getOperand(0);
10778 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10781 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10782 SmallVector<SDValue, 8> Ops;
10783 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10784 SDValue Op = N0.getOperand(i);
10785 if (Op.getOpcode() != ISD::UNDEF &&
10786 Op.getOpcode() != ISD::ConstantFP)
10788 EVT EltVT = Op.getValueType();
10789 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10790 if (FoldOp.getOpcode() != ISD::UNDEF &&
10791 FoldOp.getOpcode() != ISD::ConstantFP)
10793 Ops.push_back(FoldOp);
10794 AddToWorkList(FoldOp.getNode());
10797 if (Ops.size() != N0.getNumOperands())
10800 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10801 N0.getValueType(), &Ops[0], Ops.size());
10804 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10805 SDValue N1, SDValue N2){
10806 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10808 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10809 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10811 // If we got a simplified select_cc node back from SimplifySelectCC, then
10812 // break it down into a new SETCC node, and a new SELECT node, and then return
10813 // the SELECT node, since we were called with a SELECT node.
10814 if (SCC.getNode()) {
10815 // Check to see if we got a select_cc back (to turn into setcc/select).
10816 // Otherwise, just return whatever node we got back, like fabs.
10817 if (SCC.getOpcode() == ISD::SELECT_CC) {
10818 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10820 SCC.getOperand(0), SCC.getOperand(1),
10821 SCC.getOperand(4));
10822 AddToWorkList(SETCC.getNode());
10823 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10824 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10832 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10833 /// are the two values being selected between, see if we can simplify the
10834 /// select. Callers of this should assume that TheSelect is deleted if this
10835 /// returns true. As such, they should return the appropriate thing (e.g. the
10836 /// node) back to the top-level of the DAG combiner loop to avoid it being
10838 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10841 // Cannot simplify select with vector condition
10842 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10844 // If this is a select from two identical things, try to pull the operation
10845 // through the select.
10846 if (LHS.getOpcode() != RHS.getOpcode() ||
10847 !LHS.hasOneUse() || !RHS.hasOneUse())
10850 // If this is a load and the token chain is identical, replace the select
10851 // of two loads with a load through a select of the address to load from.
10852 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10853 // constants have been dropped into the constant pool.
10854 if (LHS.getOpcode() == ISD::LOAD) {
10855 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10856 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10858 // Token chains must be identical.
10859 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10860 // Do not let this transformation reduce the number of volatile loads.
10861 LLD->isVolatile() || RLD->isVolatile() ||
10862 // If this is an EXTLOAD, the VT's must match.
10863 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10864 // If this is an EXTLOAD, the kind of extension must match.
10865 (LLD->getExtensionType() != RLD->getExtensionType() &&
10866 // The only exception is if one of the extensions is anyext.
10867 LLD->getExtensionType() != ISD::EXTLOAD &&
10868 RLD->getExtensionType() != ISD::EXTLOAD) ||
10869 // FIXME: this discards src value information. This is
10870 // over-conservative. It would be beneficial to be able to remember
10871 // both potential memory locations. Since we are discarding
10872 // src value info, don't do the transformation if the memory
10873 // locations are not in the default address space.
10874 LLD->getPointerInfo().getAddrSpace() != 0 ||
10875 RLD->getPointerInfo().getAddrSpace() != 0 ||
10876 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10877 LLD->getBasePtr().getValueType()))
10880 // Check that the select condition doesn't reach either load. If so,
10881 // folding this will induce a cycle into the DAG. If not, this is safe to
10882 // xform, so create a select of the addresses.
10884 if (TheSelect->getOpcode() == ISD::SELECT) {
10885 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10886 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10887 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10889 // The loads must not depend on one another.
10890 if (LLD->isPredecessorOf(RLD) ||
10891 RLD->isPredecessorOf(LLD))
10893 Addr = DAG.getSelect(SDLoc(TheSelect),
10894 LLD->getBasePtr().getValueType(),
10895 TheSelect->getOperand(0), LLD->getBasePtr(),
10896 RLD->getBasePtr());
10897 } else { // Otherwise SELECT_CC
10898 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10899 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10901 if ((LLD->hasAnyUseOfValue(1) &&
10902 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10903 (RLD->hasAnyUseOfValue(1) &&
10904 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10907 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10908 LLD->getBasePtr().getValueType(),
10909 TheSelect->getOperand(0),
10910 TheSelect->getOperand(1),
10911 LLD->getBasePtr(), RLD->getBasePtr(),
10912 TheSelect->getOperand(4));
10916 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10917 Load = DAG.getLoad(TheSelect->getValueType(0),
10919 // FIXME: Discards pointer and TBAA info.
10920 LLD->getChain(), Addr, MachinePointerInfo(),
10921 LLD->isVolatile(), LLD->isNonTemporal(),
10922 LLD->isInvariant(), LLD->getAlignment());
10924 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10925 RLD->getExtensionType() : LLD->getExtensionType(),
10927 TheSelect->getValueType(0),
10928 // FIXME: Discards pointer and TBAA info.
10929 LLD->getChain(), Addr, MachinePointerInfo(),
10930 LLD->getMemoryVT(), LLD->isVolatile(),
10931 LLD->isNonTemporal(), LLD->getAlignment());
10934 // Users of the select now use the result of the load.
10935 CombineTo(TheSelect, Load);
10937 // Users of the old loads now use the new load's chain. We know the
10938 // old-load value is dead now.
10939 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10940 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10947 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10948 /// where 'cond' is the comparison specified by CC.
10949 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10950 SDValue N2, SDValue N3,
10951 ISD::CondCode CC, bool NotExtCompare) {
10952 // (x ? y : y) -> y.
10953 if (N2 == N3) return N2;
10955 EVT VT = N2.getValueType();
10956 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10957 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10958 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10960 // Determine if the condition we're dealing with is constant
10961 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10962 N0, N1, CC, DL, false);
10963 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10964 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10966 // fold select_cc true, x, y -> x
10967 if (SCCC && !SCCC->isNullValue())
10969 // fold select_cc false, x, y -> y
10970 if (SCCC && SCCC->isNullValue())
10973 // Check to see if we can simplify the select into an fabs node
10974 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10975 // Allow either -0.0 or 0.0
10976 if (CFP->getValueAPF().isZero()) {
10977 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10978 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10979 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10980 N2 == N3.getOperand(0))
10981 return DAG.getNode(ISD::FABS, DL, VT, N0);
10983 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10984 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10985 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10986 N2.getOperand(0) == N3)
10987 return DAG.getNode(ISD::FABS, DL, VT, N3);
10991 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10992 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10993 // in it. This is a win when the constant is not otherwise available because
10994 // it replaces two constant pool loads with one. We only do this if the FP
10995 // type is known to be legal, because if it isn't, then we are before legalize
10996 // types an we want the other legalization to happen first (e.g. to avoid
10997 // messing with soft float) and if the ConstantFP is not legal, because if
10998 // it is legal, we may not need to store the FP constant in a constant pool.
10999 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11000 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11001 if (TLI.isTypeLegal(N2.getValueType()) &&
11002 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11003 TargetLowering::Legal) &&
11004 // If both constants have multiple uses, then we won't need to do an
11005 // extra load, they are likely around in registers for other users.
11006 (TV->hasOneUse() || FV->hasOneUse())) {
11007 Constant *Elts[] = {
11008 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11009 const_cast<ConstantFP*>(TV->getConstantFPValue())
11011 Type *FPTy = Elts[0]->getType();
11012 const DataLayout &TD = *TLI.getDataLayout();
11014 // Create a ConstantArray of the two constants.
11015 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11016 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11017 TD.getPrefTypeAlignment(FPTy));
11018 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11020 // Get the offsets to the 0 and 1 element of the array so that we can
11021 // select between them.
11022 SDValue Zero = DAG.getIntPtrConstant(0);
11023 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11024 SDValue One = DAG.getIntPtrConstant(EltSize);
11026 SDValue Cond = DAG.getSetCC(DL,
11027 getSetCCResultType(N0.getValueType()),
11029 AddToWorkList(Cond.getNode());
11030 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11032 AddToWorkList(CstOffset.getNode());
11033 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11035 AddToWorkList(CPIdx.getNode());
11036 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11037 MachinePointerInfo::getConstantPool(), false,
11038 false, false, Alignment);
11043 // Check to see if we can perform the "gzip trick", transforming
11044 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11045 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11046 (N1C->isNullValue() || // (a < 0) ? b : 0
11047 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11048 EVT XType = N0.getValueType();
11049 EVT AType = N2.getValueType();
11050 if (XType.bitsGE(AType)) {
11051 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11052 // single-bit constant.
11053 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11054 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11055 ShCtV = XType.getSizeInBits()-ShCtV-1;
11056 SDValue ShCt = DAG.getConstant(ShCtV,
11057 getShiftAmountTy(N0.getValueType()));
11058 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11060 AddToWorkList(Shift.getNode());
11062 if (XType.bitsGT(AType)) {
11063 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11064 AddToWorkList(Shift.getNode());
11067 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11070 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11072 DAG.getConstant(XType.getSizeInBits()-1,
11073 getShiftAmountTy(N0.getValueType())));
11074 AddToWorkList(Shift.getNode());
11076 if (XType.bitsGT(AType)) {
11077 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11078 AddToWorkList(Shift.getNode());
11081 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11085 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11086 // where y is has a single bit set.
11087 // A plaintext description would be, we can turn the SELECT_CC into an AND
11088 // when the condition can be materialized as an all-ones register. Any
11089 // single bit-test can be materialized as an all-ones register with
11090 // shift-left and shift-right-arith.
11091 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11092 N0->getValueType(0) == VT &&
11093 N1C && N1C->isNullValue() &&
11094 N2C && N2C->isNullValue()) {
11095 SDValue AndLHS = N0->getOperand(0);
11096 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11097 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11098 // Shift the tested bit over the sign bit.
11099 APInt AndMask = ConstAndRHS->getAPIntValue();
11101 DAG.getConstant(AndMask.countLeadingZeros(),
11102 getShiftAmountTy(AndLHS.getValueType()));
11103 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11105 // Now arithmetic right shift it all the way over, so the result is either
11106 // all-ones, or zero.
11108 DAG.getConstant(AndMask.getBitWidth()-1,
11109 getShiftAmountTy(Shl.getValueType()));
11110 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11112 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11116 // fold select C, 16, 0 -> shl C, 4
11117 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11118 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11119 TargetLowering::ZeroOrOneBooleanContent) {
11121 // If the caller doesn't want us to simplify this into a zext of a compare,
11123 if (NotExtCompare && N2C->getAPIntValue() == 1)
11126 // Get a SetCC of the condition
11127 // NOTE: Don't create a SETCC if it's not legal on this target.
11128 if (!LegalOperations ||
11129 TLI.isOperationLegal(ISD::SETCC,
11130 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11132 // cast from setcc result type to select result type
11134 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11136 if (N2.getValueType().bitsLT(SCC.getValueType()))
11137 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11138 N2.getValueType());
11140 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11141 N2.getValueType(), SCC);
11143 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11144 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11145 N2.getValueType(), SCC);
11148 AddToWorkList(SCC.getNode());
11149 AddToWorkList(Temp.getNode());
11151 if (N2C->getAPIntValue() == 1)
11154 // shl setcc result by log2 n2c
11155 return DAG.getNode(
11156 ISD::SHL, DL, N2.getValueType(), Temp,
11157 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11158 getShiftAmountTy(Temp.getValueType())));
11162 // Check to see if this is the equivalent of setcc
11163 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11164 // otherwise, go ahead with the folds.
11165 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11166 EVT XType = N0.getValueType();
11167 if (!LegalOperations ||
11168 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11169 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11170 if (Res.getValueType() != VT)
11171 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11175 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11176 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11177 (!LegalOperations ||
11178 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11179 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11180 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11181 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11182 getShiftAmountTy(Ctlz.getValueType())));
11184 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11185 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11186 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11187 XType, DAG.getConstant(0, XType), N0);
11188 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11189 return DAG.getNode(ISD::SRL, DL, XType,
11190 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11191 DAG.getConstant(XType.getSizeInBits()-1,
11192 getShiftAmountTy(XType)));
11194 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11195 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11196 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11197 DAG.getConstant(XType.getSizeInBits()-1,
11198 getShiftAmountTy(N0.getValueType())));
11199 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11203 // Check to see if this is an integer abs.
11204 // select_cc setg[te] X, 0, X, -X ->
11205 // select_cc setgt X, -1, X, -X ->
11206 // select_cc setl[te] X, 0, -X, X ->
11207 // select_cc setlt X, 1, -X, X ->
11208 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11210 ConstantSDNode *SubC = NULL;
11211 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11212 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11213 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11214 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11215 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11216 (N1C->isOne() && CC == ISD::SETLT)) &&
11217 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11218 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11220 EVT XType = N0.getValueType();
11221 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11222 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11224 DAG.getConstant(XType.getSizeInBits()-1,
11225 getShiftAmountTy(N0.getValueType())));
11226 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11228 AddToWorkList(Shift.getNode());
11229 AddToWorkList(Add.getNode());
11230 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11237 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11238 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11239 SDValue N1, ISD::CondCode Cond,
11240 SDLoc DL, bool foldBooleans) {
11241 TargetLowering::DAGCombinerInfo
11242 DagCombineInfo(DAG, Level, false, this);
11243 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11246 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11247 /// return a DAG expression to select that will generate the same value by
11248 /// multiplying by a magic number. See:
11249 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11250 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11251 std::vector<SDNode*> Built;
11252 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11254 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11256 AddToWorkList(*ii);
11260 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11261 /// return a DAG expression to select that will generate the same value by
11262 /// multiplying by a magic number. See:
11263 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11264 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11265 std::vector<SDNode*> Built;
11266 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11268 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11270 AddToWorkList(*ii);
11274 /// FindBaseOffset - Return true if base is a frame index, which is known not
11275 // to alias with anything but itself. Provides base object and offset as
11277 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11278 const GlobalValue *&GV, const void *&CV) {
11279 // Assume it is a primitive operation.
11280 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11282 // If it's an adding a simple constant then integrate the offset.
11283 if (Base.getOpcode() == ISD::ADD) {
11284 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11285 Base = Base.getOperand(0);
11286 Offset += C->getZExtValue();
11290 // Return the underlying GlobalValue, and update the Offset. Return false
11291 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11292 // by multiple nodes with different offsets.
11293 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11294 GV = G->getGlobal();
11295 Offset += G->getOffset();
11299 // Return the underlying Constant value, and update the Offset. Return false
11300 // for ConstantSDNodes since the same constant pool entry may be represented
11301 // by multiple nodes with different offsets.
11302 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11303 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11304 : (const void *)C->getConstVal();
11305 Offset += C->getOffset();
11308 // If it's any of the following then it can't alias with anything but itself.
11309 return isa<FrameIndexSDNode>(Base);
11312 /// isAlias - Return true if there is any possibility that the two addresses
11314 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11315 const Value *SrcValue1, int SrcValueOffset1,
11316 unsigned SrcValueAlign1,
11317 const MDNode *TBAAInfo1,
11318 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11319 const Value *SrcValue2, int SrcValueOffset2,
11320 unsigned SrcValueAlign2,
11321 const MDNode *TBAAInfo2) const {
11322 // If they are the same then they must be aliases.
11323 if (Ptr1 == Ptr2) return true;
11325 // If they are both volatile then they cannot be reordered.
11326 if (IsVolatile1 && IsVolatile2) return true;
11328 // Gather base node and offset information.
11329 SDValue Base1, Base2;
11330 int64_t Offset1, Offset2;
11331 const GlobalValue *GV1, *GV2;
11332 const void *CV1, *CV2;
11333 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11334 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11336 // If they have a same base address then check to see if they overlap.
11337 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11338 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11340 // It is possible for different frame indices to alias each other, mostly
11341 // when tail call optimization reuses return address slots for arguments.
11342 // To catch this case, look up the actual index of frame indices to compute
11343 // the real alias relationship.
11344 if (isFrameIndex1 && isFrameIndex2) {
11345 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11346 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11347 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11348 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11351 // Otherwise, if we know what the bases are, and they aren't identical, then
11352 // we know they cannot alias.
11353 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11356 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11357 // compared to the size and offset of the access, we may be able to prove they
11358 // do not alias. This check is conservative for now to catch cases created by
11359 // splitting vector types.
11360 if ((SrcValueAlign1 == SrcValueAlign2) &&
11361 (SrcValueOffset1 != SrcValueOffset2) &&
11362 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11363 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11364 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11366 // There is no overlap between these relatively aligned accesses of similar
11367 // size, return no alias.
11368 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11372 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11373 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11375 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11376 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11379 if (UseAA && SrcValue1 && SrcValue2) {
11380 // Use alias analysis information.
11381 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11382 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11383 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11384 AliasAnalysis::AliasResult AAResult =
11385 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11386 UseTBAA ? TBAAInfo1 : 0),
11387 AliasAnalysis::Location(SrcValue2, Overlap2,
11388 UseTBAA ? TBAAInfo2 : 0));
11389 if (AAResult == AliasAnalysis::NoAlias)
11393 // Otherwise we have to assume they alias.
11397 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11398 SDValue Ptr0, Ptr1;
11399 int64_t Size0, Size1;
11400 bool IsVolatile0, IsVolatile1;
11401 const Value *SrcValue0, *SrcValue1;
11402 int SrcValueOffset0, SrcValueOffset1;
11403 unsigned SrcValueAlign0, SrcValueAlign1;
11404 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11405 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11406 SrcValueAlign0, SrcTBAAInfo0);
11407 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11408 SrcValueAlign1, SrcTBAAInfo1);
11409 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11410 SrcValueAlign0, SrcTBAAInfo0,
11411 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11412 SrcValueAlign1, SrcTBAAInfo1);
11415 /// FindAliasInfo - Extracts the relevant alias information from the memory
11416 /// node. Returns true if the operand was a nonvolatile load.
11417 bool DAGCombiner::FindAliasInfo(SDNode *N,
11418 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11419 const Value *&SrcValue,
11420 int &SrcValueOffset,
11421 unsigned &SrcValueAlign,
11422 const MDNode *&TBAAInfo) const {
11423 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11425 Ptr = LS->getBasePtr();
11426 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11427 IsVolatile = LS->isVolatile();
11428 SrcValue = LS->getSrcValue();
11429 SrcValueOffset = LS->getSrcValueOffset();
11430 SrcValueAlign = LS->getOriginalAlignment();
11431 TBAAInfo = LS->getTBAAInfo();
11432 return isa<LoadSDNode>(LS) && !IsVolatile;
11435 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11436 /// looking for aliasing nodes and adding them to the Aliases vector.
11437 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11438 SmallVectorImpl<SDValue> &Aliases) {
11439 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11440 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11442 // Get alias information for node.
11446 const Value *SrcValue;
11447 int SrcValueOffset;
11448 unsigned SrcValueAlign;
11449 const MDNode *SrcTBAAInfo;
11450 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11451 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11454 Chains.push_back(OriginalChain);
11455 unsigned Depth = 0;
11457 // Look at each chain and determine if it is an alias. If so, add it to the
11458 // aliases list. If not, then continue up the chain looking for the next
11460 while (!Chains.empty()) {
11461 SDValue Chain = Chains.back();
11464 // For TokenFactor nodes, look at each operand and only continue up the
11465 // chain until we find two aliases. If we've seen two aliases, assume we'll
11466 // find more and revert to original chain since the xform is unlikely to be
11469 // FIXME: The depth check could be made to return the last non-aliasing
11470 // chain we found before we hit a tokenfactor rather than the original
11472 if (Depth > 6 || Aliases.size() == 2) {
11474 Aliases.push_back(OriginalChain);
11478 // Don't bother if we've been before.
11479 if (!Visited.insert(Chain.getNode()))
11482 switch (Chain.getOpcode()) {
11483 case ISD::EntryToken:
11484 // Entry token is ideal chain operand, but handled in FindBetterChain.
11489 // Get alias information for Chain.
11493 const Value *OpSrcValue;
11494 int OpSrcValueOffset;
11495 unsigned OpSrcValueAlign;
11496 const MDNode *OpSrcTBAAInfo;
11497 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11498 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11502 // If chain is alias then stop here.
11503 if (!(IsLoad && IsOpLoad) &&
11504 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11505 SrcValueAlign, SrcTBAAInfo,
11506 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11507 OpSrcValueAlign, OpSrcTBAAInfo)) {
11508 Aliases.push_back(Chain);
11510 // Look further up the chain.
11511 Chains.push_back(Chain.getOperand(0));
11517 case ISD::TokenFactor:
11518 // We have to check each of the operands of the token factor for "small"
11519 // token factors, so we queue them up. Adding the operands to the queue
11520 // (stack) in reverse order maintains the original order and increases the
11521 // likelihood that getNode will find a matching token factor (CSE.)
11522 if (Chain.getNumOperands() > 16) {
11523 Aliases.push_back(Chain);
11526 for (unsigned n = Chain.getNumOperands(); n;)
11527 Chains.push_back(Chain.getOperand(--n));
11532 // For all other instructions we will just have to take what we can get.
11533 Aliases.push_back(Chain);
11538 // We need to be careful here to also search for aliases through the
11539 // value operand of a store, etc. Consider the following situation:
11541 // L1 = load Token1, %52
11542 // S1 = store Token1, L1, %51
11543 // L2 = load Token1, %52+8
11544 // S2 = store Token1, L2, %51+8
11545 // Token2 = Token(S1, S2)
11546 // L3 = load Token2, %53
11547 // S3 = store Token2, L3, %52
11548 // L4 = load Token2, %53+8
11549 // S4 = store Token2, L4, %52+8
11550 // If we search for aliases of S3 (which loads address %52), and we look
11551 // only through the chain, then we'll miss the trivial dependence on L1
11552 // (which also loads from %52). We then might change all loads and
11553 // stores to use Token1 as their chain operand, which could result in
11554 // copying %53 into %52 before copying %52 into %51 (which should
11557 // The problem is, however, that searching for such data dependencies
11558 // can become expensive, and the cost is not directly related to the
11559 // chain depth. Instead, we'll rule out such configurations here by
11560 // insisting that we've visited all chain users (except for users
11561 // of the original chain, which is not necessary). When doing this,
11562 // we need to look through nodes we don't care about (otherwise, things
11563 // like register copies will interfere with trivial cases).
11565 SmallVector<const SDNode *, 16> Worklist;
11566 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11567 IE = Visited.end(); I != IE; ++I)
11568 if (*I != OriginalChain.getNode())
11569 Worklist.push_back(*I);
11571 while (!Worklist.empty()) {
11572 const SDNode *M = Worklist.pop_back_val();
11574 // We have already visited M, and want to make sure we've visited any uses
11575 // of M that we care about. For uses that we've not visisted, and don't
11576 // care about, queue them to the worklist.
11578 for (SDNode::use_iterator UI = M->use_begin(),
11579 UIE = M->use_end(); UI != UIE; ++UI)
11580 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11581 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11582 // We've not visited this use, and we care about it (it could have an
11583 // ordering dependency with the original node).
11585 Aliases.push_back(OriginalChain);
11589 // We've not visited this use, but we don't care about it. Mark it as
11590 // visited and enqueue it to the worklist.
11591 Worklist.push_back(*UI);
11596 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11597 /// for a better chain (aliasing node.)
11598 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11599 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11601 // Accumulate all the aliases to this node.
11602 GatherAllAliases(N, OldChain, Aliases);
11604 // If no operands then chain to entry token.
11605 if (Aliases.size() == 0)
11606 return DAG.getEntryNode();
11608 // If a single operand then chain to it. We don't need to revisit it.
11609 if (Aliases.size() == 1)
11612 // Construct a custom tailored token factor.
11613 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11614 &Aliases[0], Aliases.size());
11617 // SelectionDAG::Combine - This is the entry point for the file.
11619 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11620 CodeGenOpt::Level OptLevel) {
11621 /// run - This is the main entry point to this class.
11623 DAGCombiner(*this, AA, OptLevel).Run(Level);