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 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4961 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4962 bool DoXform = true;
4963 SmallVector<SDNode*, 4> SetCCs;
4964 if (!N0.hasOneUse())
4965 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4967 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4968 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4970 LN0->getBasePtr(), N0.getValueType(),
4971 LN0->getMemOperand());
4972 CombineTo(N, ExtLoad);
4973 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4974 N0.getValueType(), ExtLoad);
4975 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4976 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4978 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4982 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4983 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4984 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4985 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4987 EVT MemVT = LN0->getMemoryVT();
4988 if ((!LegalOperations && !LN0->isVolatile()) ||
4989 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4990 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4992 LN0->getBasePtr(), MemVT,
4993 LN0->getMemOperand());
4994 CombineTo(N, ExtLoad);
4995 CombineTo(N0.getNode(),
4996 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4997 N0.getValueType(), ExtLoad),
4998 ExtLoad.getValue(1));
4999 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5003 // fold (sext (and/or/xor (load x), cst)) ->
5004 // (and/or/xor (sextload x), (sext cst))
5005 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5006 N0.getOpcode() == ISD::XOR) &&
5007 isa<LoadSDNode>(N0.getOperand(0)) &&
5008 N0.getOperand(1).getOpcode() == ISD::Constant &&
5009 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5010 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5011 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5012 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
5013 bool DoXform = true;
5014 SmallVector<SDNode*, 4> SetCCs;
5015 if (!N0.hasOneUse())
5016 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5019 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5020 LN0->getChain(), LN0->getBasePtr(),
5022 LN0->getMemOperand());
5023 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5024 Mask = Mask.sext(VT.getSizeInBits());
5025 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5026 ExtLoad, DAG.getConstant(Mask, VT));
5027 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5028 SDLoc(N0.getOperand(0)),
5029 N0.getOperand(0).getValueType(), ExtLoad);
5031 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5032 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5039 if (N0.getOpcode() == ISD::SETCC) {
5040 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5041 // Only do this before legalize for now.
5042 if (VT.isVector() && !LegalOperations &&
5043 TLI.getBooleanContents(true) ==
5044 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5045 EVT N0VT = N0.getOperand(0).getValueType();
5046 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5047 // of the same size as the compared operands. Only optimize sext(setcc())
5048 // if this is the case.
5049 EVT SVT = getSetCCResultType(N0VT);
5051 // We know that the # elements of the results is the same as the
5052 // # elements of the compare (and the # elements of the compare result
5053 // for that matter). Check to see that they are the same size. If so,
5054 // we know that the element size of the sext'd result matches the
5055 // element size of the compare operands.
5056 if (VT.getSizeInBits() == SVT.getSizeInBits())
5057 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5059 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5061 // If the desired elements are smaller or larger than the source
5062 // elements we can use a matching integer vector type and then
5063 // truncate/sign extend
5064 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5065 if (SVT == MatchingVectorType) {
5066 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5067 N0.getOperand(0), N0.getOperand(1),
5068 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5069 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5073 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5074 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5076 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5078 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5079 NegOne, DAG.getConstant(0, VT),
5080 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5081 if (SCC.getNode()) return SCC;
5083 if (!VT.isVector()) {
5084 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5085 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5087 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5088 SDValue SetCC = DAG.getSetCC(DL,
5090 N0.getOperand(0), N0.getOperand(1), CC);
5091 EVT SelectVT = getSetCCResultType(VT);
5092 return DAG.getSelect(DL, VT,
5093 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5094 NegOne, DAG.getConstant(0, VT));
5100 // fold (sext x) -> (zext x) if the sign bit is known zero.
5101 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5102 DAG.SignBitIsZero(N0))
5103 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5108 // isTruncateOf - If N is a truncate of some other value, return true, record
5109 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5110 // This function computes KnownZero to avoid a duplicated call to
5111 // ComputeMaskedBits in the caller.
5112 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5115 if (N->getOpcode() == ISD::TRUNCATE) {
5116 Op = N->getOperand(0);
5117 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5121 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5122 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5125 SDValue Op0 = N->getOperand(0);
5126 SDValue Op1 = N->getOperand(1);
5127 assert(Op0.getValueType() == Op1.getValueType());
5129 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5130 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5131 if (COp0 && COp0->isNullValue())
5133 else if (COp1 && COp1->isNullValue())
5138 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5140 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5146 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5147 SDValue N0 = N->getOperand(0);
5148 EVT VT = N->getValueType(0);
5150 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5152 return SDValue(Res, 0);
5154 // fold (zext (zext x)) -> (zext x)
5155 // fold (zext (aext x)) -> (zext x)
5156 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5157 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5160 // fold (zext (truncate x)) -> (zext x) or
5161 // (zext (truncate x)) -> (truncate x)
5162 // This is valid when the truncated bits of x are already zero.
5163 // FIXME: We should extend this to work for vectors too.
5166 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5167 APInt TruncatedBits =
5168 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5169 APInt(Op.getValueSizeInBits(), 0) :
5170 APInt::getBitsSet(Op.getValueSizeInBits(),
5171 N0.getValueSizeInBits(),
5172 std::min(Op.getValueSizeInBits(),
5173 VT.getSizeInBits()));
5174 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5175 if (VT.bitsGT(Op.getValueType()))
5176 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5177 if (VT.bitsLT(Op.getValueType()))
5178 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5184 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5185 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5186 if (N0.getOpcode() == ISD::TRUNCATE) {
5187 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5188 if (NarrowLoad.getNode()) {
5189 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5190 if (NarrowLoad.getNode() != N0.getNode()) {
5191 CombineTo(N0.getNode(), NarrowLoad);
5192 // CombineTo deleted the truncate, if needed, but not what's under it.
5195 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5199 // fold (zext (truncate x)) -> (and x, mask)
5200 if (N0.getOpcode() == ISD::TRUNCATE &&
5201 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5203 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5204 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5205 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5206 if (NarrowLoad.getNode()) {
5207 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5208 if (NarrowLoad.getNode() != N0.getNode()) {
5209 CombineTo(N0.getNode(), NarrowLoad);
5210 // CombineTo deleted the truncate, if needed, but not what's under it.
5213 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5216 SDValue Op = N0.getOperand(0);
5217 if (Op.getValueType().bitsLT(VT)) {
5218 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5219 AddToWorkList(Op.getNode());
5220 } else if (Op.getValueType().bitsGT(VT)) {
5221 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5222 AddToWorkList(Op.getNode());
5224 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5225 N0.getValueType().getScalarType());
5228 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5229 // if either of the casts is not free.
5230 if (N0.getOpcode() == ISD::AND &&
5231 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5232 N0.getOperand(1).getOpcode() == ISD::Constant &&
5233 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5234 N0.getValueType()) ||
5235 !TLI.isZExtFree(N0.getValueType(), VT))) {
5236 SDValue X = N0.getOperand(0).getOperand(0);
5237 if (X.getValueType().bitsLT(VT)) {
5238 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5239 } else if (X.getValueType().bitsGT(VT)) {
5240 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5242 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5243 Mask = Mask.zext(VT.getSizeInBits());
5244 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5245 X, DAG.getConstant(Mask, VT));
5248 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5249 // None of the supported targets knows how to perform load and vector_zext
5250 // on vectors in one instruction. We only perform this transformation on
5252 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5253 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5254 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5255 bool DoXform = true;
5256 SmallVector<SDNode*, 4> SetCCs;
5257 if (!N0.hasOneUse())
5258 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5260 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5261 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5263 LN0->getBasePtr(), N0.getValueType(),
5264 LN0->getMemOperand());
5265 CombineTo(N, ExtLoad);
5266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5267 N0.getValueType(), ExtLoad);
5268 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5270 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5272 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5276 // fold (zext (and/or/xor (load x), cst)) ->
5277 // (and/or/xor (zextload x), (zext cst))
5278 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5279 N0.getOpcode() == ISD::XOR) &&
5280 isa<LoadSDNode>(N0.getOperand(0)) &&
5281 N0.getOperand(1).getOpcode() == ISD::Constant &&
5282 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5283 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5284 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5285 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5286 bool DoXform = true;
5287 SmallVector<SDNode*, 4> SetCCs;
5288 if (!N0.hasOneUse())
5289 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5292 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5293 LN0->getChain(), LN0->getBasePtr(),
5295 LN0->getMemOperand());
5296 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5297 Mask = Mask.zext(VT.getSizeInBits());
5298 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5299 ExtLoad, DAG.getConstant(Mask, VT));
5300 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5301 SDLoc(N0.getOperand(0)),
5302 N0.getOperand(0).getValueType(), ExtLoad);
5304 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5305 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5312 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5313 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5314 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5315 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5317 EVT MemVT = LN0->getMemoryVT();
5318 if ((!LegalOperations && !LN0->isVolatile()) ||
5319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5320 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5322 LN0->getBasePtr(), MemVT,
5323 LN0->getMemOperand());
5324 CombineTo(N, ExtLoad);
5325 CombineTo(N0.getNode(),
5326 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5328 ExtLoad.getValue(1));
5329 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5333 if (N0.getOpcode() == ISD::SETCC) {
5334 if (!LegalOperations && VT.isVector() &&
5335 N0.getValueType().getVectorElementType() == MVT::i1) {
5336 EVT N0VT = N0.getOperand(0).getValueType();
5337 if (getSetCCResultType(N0VT) == N0.getValueType())
5340 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5341 // Only do this before legalize for now.
5342 EVT EltVT = VT.getVectorElementType();
5343 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5344 DAG.getConstant(1, EltVT));
5345 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5346 // We know that the # elements of the results is the same as the
5347 // # elements of the compare (and the # elements of the compare result
5348 // for that matter). Check to see that they are the same size. If so,
5349 // we know that the element size of the sext'd result matches the
5350 // element size of the compare operands.
5351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5352 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5354 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5355 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5356 &OneOps[0], OneOps.size()));
5358 // If the desired elements are smaller or larger than the source
5359 // elements we can use a matching integer vector type and then
5360 // truncate/sign extend
5361 EVT MatchingElementType =
5362 EVT::getIntegerVT(*DAG.getContext(),
5363 N0VT.getScalarType().getSizeInBits());
5364 EVT MatchingVectorType =
5365 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5366 N0VT.getVectorNumElements());
5368 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5370 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5371 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5372 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5373 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5374 &OneOps[0], OneOps.size()));
5377 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5379 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5380 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5381 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5382 if (SCC.getNode()) return SCC;
5385 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5386 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5387 isa<ConstantSDNode>(N0.getOperand(1)) &&
5388 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5390 SDValue ShAmt = N0.getOperand(1);
5391 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5392 if (N0.getOpcode() == ISD::SHL) {
5393 SDValue InnerZExt = N0.getOperand(0);
5394 // If the original shl may be shifting out bits, do not perform this
5396 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5397 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5398 if (ShAmtVal > KnownZeroBits)
5404 // Ensure that the shift amount is wide enough for the shifted value.
5405 if (VT.getSizeInBits() >= 256)
5406 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5408 return DAG.getNode(N0.getOpcode(), DL, VT,
5409 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5416 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5417 SDValue N0 = N->getOperand(0);
5418 EVT VT = N->getValueType(0);
5420 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5422 return SDValue(Res, 0);
5424 // fold (aext (aext x)) -> (aext x)
5425 // fold (aext (zext x)) -> (zext x)
5426 // fold (aext (sext x)) -> (sext x)
5427 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5428 N0.getOpcode() == ISD::ZERO_EXTEND ||
5429 N0.getOpcode() == ISD::SIGN_EXTEND)
5430 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5432 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5433 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5434 if (N0.getOpcode() == ISD::TRUNCATE) {
5435 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5436 if (NarrowLoad.getNode()) {
5437 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5438 if (NarrowLoad.getNode() != N0.getNode()) {
5439 CombineTo(N0.getNode(), NarrowLoad);
5440 // CombineTo deleted the truncate, if needed, but not what's under it.
5443 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5447 // fold (aext (truncate x))
5448 if (N0.getOpcode() == ISD::TRUNCATE) {
5449 SDValue TruncOp = N0.getOperand(0);
5450 if (TruncOp.getValueType() == VT)
5451 return TruncOp; // x iff x size == zext size.
5452 if (TruncOp.getValueType().bitsGT(VT))
5453 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5454 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5457 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5458 // if the trunc is not free.
5459 if (N0.getOpcode() == ISD::AND &&
5460 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5461 N0.getOperand(1).getOpcode() == ISD::Constant &&
5462 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5463 N0.getValueType())) {
5464 SDValue X = N0.getOperand(0).getOperand(0);
5465 if (X.getValueType().bitsLT(VT)) {
5466 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5467 } else if (X.getValueType().bitsGT(VT)) {
5468 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5470 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5471 Mask = Mask.zext(VT.getSizeInBits());
5472 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5473 X, DAG.getConstant(Mask, VT));
5476 // fold (aext (load x)) -> (aext (truncate (extload x)))
5477 // None of the supported targets knows how to perform load and any_ext
5478 // on vectors in one instruction. We only perform this transformation on
5480 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5481 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5482 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5483 bool DoXform = true;
5484 SmallVector<SDNode*, 4> SetCCs;
5485 if (!N0.hasOneUse())
5486 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5488 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5489 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5491 LN0->getBasePtr(), N0.getValueType(),
5492 LN0->getMemOperand());
5493 CombineTo(N, ExtLoad);
5494 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5495 N0.getValueType(), ExtLoad);
5496 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5497 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5503 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5504 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5505 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5506 if (N0.getOpcode() == ISD::LOAD &&
5507 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5509 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5510 EVT MemVT = LN0->getMemoryVT();
5511 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5512 VT, LN0->getChain(), LN0->getBasePtr(),
5513 MemVT, LN0->getMemOperand());
5514 CombineTo(N, ExtLoad);
5515 CombineTo(N0.getNode(),
5516 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5517 N0.getValueType(), ExtLoad),
5518 ExtLoad.getValue(1));
5519 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5522 if (N0.getOpcode() == ISD::SETCC) {
5523 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5524 // Only do this before legalize for now.
5525 if (VT.isVector() && !LegalOperations) {
5526 EVT N0VT = N0.getOperand(0).getValueType();
5527 // We know that the # elements of the results is the same as the
5528 // # elements of the compare (and the # elements of the compare result
5529 // for that matter). Check to see that they are the same size. If so,
5530 // we know that the element size of the sext'd result matches the
5531 // element size of the compare operands.
5532 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5533 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5535 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5536 // If the desired elements are smaller or larger than the source
5537 // elements we can use a matching integer vector type and then
5538 // truncate/sign extend
5540 EVT MatchingElementType =
5541 EVT::getIntegerVT(*DAG.getContext(),
5542 N0VT.getScalarType().getSizeInBits());
5543 EVT MatchingVectorType =
5544 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5545 N0VT.getVectorNumElements());
5547 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5549 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5550 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5554 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5556 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5557 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5558 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5566 /// GetDemandedBits - See if the specified operand can be simplified with the
5567 /// knowledge that only the bits specified by Mask are used. If so, return the
5568 /// simpler operand, otherwise return a null SDValue.
5569 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5570 switch (V.getOpcode()) {
5572 case ISD::Constant: {
5573 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5574 assert(CV != 0 && "Const value should be ConstSDNode.");
5575 const APInt &CVal = CV->getAPIntValue();
5576 APInt NewVal = CVal & Mask;
5578 return DAG.getConstant(NewVal, V.getValueType());
5583 // If the LHS or RHS don't contribute bits to the or, drop them.
5584 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5585 return V.getOperand(1);
5586 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5587 return V.getOperand(0);
5590 // Only look at single-use SRLs.
5591 if (!V.getNode()->hasOneUse())
5593 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5594 // See if we can recursively simplify the LHS.
5595 unsigned Amt = RHSC->getZExtValue();
5597 // Watch out for shift count overflow though.
5598 if (Amt >= Mask.getBitWidth()) break;
5599 APInt NewMask = Mask << Amt;
5600 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5601 if (SimplifyLHS.getNode())
5602 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5603 SimplifyLHS, V.getOperand(1));
5609 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5610 /// bits and then truncated to a narrower type and where N is a multiple
5611 /// of number of bits of the narrower type, transform it to a narrower load
5612 /// from address + N / num of bits of new type. If the result is to be
5613 /// extended, also fold the extension to form a extending load.
5614 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5615 unsigned Opc = N->getOpcode();
5617 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5618 SDValue N0 = N->getOperand(0);
5619 EVT VT = N->getValueType(0);
5622 // This transformation isn't valid for vector loads.
5626 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5628 if (Opc == ISD::SIGN_EXTEND_INREG) {
5629 ExtType = ISD::SEXTLOAD;
5630 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5631 } else if (Opc == ISD::SRL) {
5632 // Another special-case: SRL is basically zero-extending a narrower value.
5633 ExtType = ISD::ZEXTLOAD;
5635 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5636 if (!N01) return SDValue();
5637 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5638 VT.getSizeInBits() - N01->getZExtValue());
5640 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5643 unsigned EVTBits = ExtVT.getSizeInBits();
5645 // Do not generate loads of non-round integer types since these can
5646 // be expensive (and would be wrong if the type is not byte sized).
5647 if (!ExtVT.isRound())
5651 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5652 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5653 ShAmt = N01->getZExtValue();
5654 // Is the shift amount a multiple of size of VT?
5655 if ((ShAmt & (EVTBits-1)) == 0) {
5656 N0 = N0.getOperand(0);
5657 // Is the load width a multiple of size of VT?
5658 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5662 // At this point, we must have a load or else we can't do the transform.
5663 if (!isa<LoadSDNode>(N0)) return SDValue();
5665 // Because a SRL must be assumed to *need* to zero-extend the high bits
5666 // (as opposed to anyext the high bits), we can't combine the zextload
5667 // lowering of SRL and an sextload.
5668 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5671 // If the shift amount is larger than the input type then we're not
5672 // accessing any of the loaded bytes. If the load was a zextload/extload
5673 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5674 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5679 // If the load is shifted left (and the result isn't shifted back right),
5680 // we can fold the truncate through the shift.
5681 unsigned ShLeftAmt = 0;
5682 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5683 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5684 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5685 ShLeftAmt = N01->getZExtValue();
5686 N0 = N0.getOperand(0);
5690 // If we haven't found a load, we can't narrow it. Don't transform one with
5691 // multiple uses, this would require adding a new load.
5692 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5695 // Don't change the width of a volatile load.
5696 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5697 if (LN0->isVolatile())
5700 // Verify that we are actually reducing a load width here.
5701 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5704 // For the transform to be legal, the load must produce only two values
5705 // (the value loaded and the chain). Don't transform a pre-increment
5706 // load, for example, which produces an extra value. Otherwise the
5707 // transformation is not equivalent, and the downstream logic to replace
5708 // uses gets things wrong.
5709 if (LN0->getNumValues() > 2)
5712 // If the load that we're shrinking is an extload and we're not just
5713 // discarding the extension we can't simply shrink the load. Bail.
5714 // TODO: It would be possible to merge the extensions in some cases.
5715 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5716 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5719 EVT PtrType = N0.getOperand(1).getValueType();
5721 if (PtrType == MVT::Untyped || PtrType.isExtended())
5722 // It's not possible to generate a constant of extended or untyped type.
5725 // For big endian targets, we need to adjust the offset to the pointer to
5726 // load the correct bytes.
5727 if (TLI.isBigEndian()) {
5728 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5729 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5730 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5733 uint64_t PtrOff = ShAmt / 8;
5734 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5735 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5736 PtrType, LN0->getBasePtr(),
5737 DAG.getConstant(PtrOff, PtrType));
5738 AddToWorkList(NewPtr.getNode());
5741 if (ExtType == ISD::NON_EXTLOAD)
5742 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5743 LN0->getPointerInfo().getWithOffset(PtrOff),
5744 LN0->isVolatile(), LN0->isNonTemporal(),
5745 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5747 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5748 LN0->getPointerInfo().getWithOffset(PtrOff),
5749 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5750 NewAlign, LN0->getTBAAInfo());
5752 // Replace the old load's chain with the new load's chain.
5753 WorkListRemover DeadNodes(*this);
5754 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5756 // Shift the result left, if we've swallowed a left shift.
5757 SDValue Result = Load;
5758 if (ShLeftAmt != 0) {
5759 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5760 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5762 // If the shift amount is as large as the result size (but, presumably,
5763 // no larger than the source) then the useful bits of the result are
5764 // zero; we can't simply return the shortened shift, because the result
5765 // of that operation is undefined.
5766 if (ShLeftAmt >= VT.getSizeInBits())
5767 Result = DAG.getConstant(0, VT);
5769 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5770 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5773 // Return the new loaded value.
5777 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5778 SDValue N0 = N->getOperand(0);
5779 SDValue N1 = N->getOperand(1);
5780 EVT VT = N->getValueType(0);
5781 EVT EVT = cast<VTSDNode>(N1)->getVT();
5782 unsigned VTBits = VT.getScalarType().getSizeInBits();
5783 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5785 // fold (sext_in_reg c1) -> c1
5786 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5787 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5789 // If the input is already sign extended, just drop the extension.
5790 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5793 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5794 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5795 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5796 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5797 N0.getOperand(0), N1);
5799 // fold (sext_in_reg (sext x)) -> (sext x)
5800 // fold (sext_in_reg (aext x)) -> (sext x)
5801 // if x is small enough.
5802 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5803 SDValue N00 = N0.getOperand(0);
5804 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5805 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5806 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5809 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5810 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5811 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5813 // fold operands of sext_in_reg based on knowledge that the top bits are not
5815 if (SimplifyDemandedBits(SDValue(N, 0)))
5816 return SDValue(N, 0);
5818 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5819 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5820 SDValue NarrowLoad = ReduceLoadWidth(N);
5821 if (NarrowLoad.getNode())
5824 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5825 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5826 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5827 if (N0.getOpcode() == ISD::SRL) {
5828 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5829 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5830 // We can turn this into an SRA iff the input to the SRL is already sign
5832 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5833 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5834 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5835 N0.getOperand(0), N0.getOperand(1));
5839 // fold (sext_inreg (extload x)) -> (sextload x)
5840 if (ISD::isEXTLoad(N0.getNode()) &&
5841 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5842 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5843 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5844 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5845 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5846 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5848 LN0->getBasePtr(), EVT,
5849 LN0->getMemOperand());
5850 CombineTo(N, ExtLoad);
5851 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5852 AddToWorkList(ExtLoad.getNode());
5853 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5855 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5856 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5858 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5859 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5860 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5861 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5862 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5864 LN0->getBasePtr(), EVT,
5865 LN0->getMemOperand());
5866 CombineTo(N, ExtLoad);
5867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5871 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5872 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5873 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5874 N0.getOperand(1), false);
5875 if (BSwap.getNode() != 0)
5876 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5880 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5881 // into a build_vector.
5882 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5883 SmallVector<SDValue, 8> Elts;
5884 unsigned NumElts = N0->getNumOperands();
5885 unsigned ShAmt = VTBits - EVTBits;
5887 for (unsigned i = 0; i != NumElts; ++i) {
5888 SDValue Op = N0->getOperand(i);
5889 if (Op->getOpcode() == ISD::UNDEF) {
5894 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5895 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5896 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5897 Op.getValueType()));
5900 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5906 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5907 SDValue N0 = N->getOperand(0);
5908 EVT VT = N->getValueType(0);
5909 bool isLE = TLI.isLittleEndian();
5912 if (N0.getValueType() == N->getValueType(0))
5914 // fold (truncate c1) -> c1
5915 if (isa<ConstantSDNode>(N0))
5916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5917 // fold (truncate (truncate x)) -> (truncate x)
5918 if (N0.getOpcode() == ISD::TRUNCATE)
5919 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5920 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5921 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5922 N0.getOpcode() == ISD::SIGN_EXTEND ||
5923 N0.getOpcode() == ISD::ANY_EXTEND) {
5924 if (N0.getOperand(0).getValueType().bitsLT(VT))
5925 // if the source is smaller than the dest, we still need an extend
5926 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5928 if (N0.getOperand(0).getValueType().bitsGT(VT))
5929 // if the source is larger than the dest, than we just need the truncate
5930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5931 // if the source and dest are the same type, we can drop both the extend
5932 // and the truncate.
5933 return N0.getOperand(0);
5936 // Fold extract-and-trunc into a narrow extract. For example:
5937 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5938 // i32 y = TRUNCATE(i64 x)
5940 // v16i8 b = BITCAST (v2i64 val)
5941 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5943 // Note: We only run this optimization after type legalization (which often
5944 // creates this pattern) and before operation legalization after which
5945 // we need to be more careful about the vector instructions that we generate.
5946 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5947 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5949 EVT VecTy = N0.getOperand(0).getValueType();
5950 EVT ExTy = N0.getValueType();
5951 EVT TrTy = N->getValueType(0);
5953 unsigned NumElem = VecTy.getVectorNumElements();
5954 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5956 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5957 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5959 SDValue EltNo = N0->getOperand(1);
5960 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5961 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5962 EVT IndexTy = TLI.getVectorIdxTy();
5963 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5965 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5966 NVT, N0.getOperand(0));
5968 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5970 DAG.getConstant(Index, IndexTy));
5974 // Fold a series of buildvector, bitcast, and truncate if possible.
5976 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5977 // (2xi32 (buildvector x, y)).
5978 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5979 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5980 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5981 N0.getOperand(0).hasOneUse()) {
5983 SDValue BuildVect = N0.getOperand(0);
5984 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5985 EVT TruncVecEltTy = VT.getVectorElementType();
5987 // Check that the element types match.
5988 if (BuildVectEltTy == TruncVecEltTy) {
5989 // Now we only need to compute the offset of the truncated elements.
5990 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5991 unsigned TruncVecNumElts = VT.getVectorNumElements();
5992 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5994 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5995 "Invalid number of elements");
5997 SmallVector<SDValue, 8> Opnds;
5998 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5999 Opnds.push_back(BuildVect.getOperand(i));
6001 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6006 // See if we can simplify the input to this truncate through knowledge that
6007 // only the low bits are being used.
6008 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6009 // Currently we only perform this optimization on scalars because vectors
6010 // may have different active low bits.
6011 if (!VT.isVector()) {
6013 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6014 VT.getSizeInBits()));
6015 if (Shorter.getNode())
6016 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6018 // fold (truncate (load x)) -> (smaller load x)
6019 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6020 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6021 SDValue Reduced = ReduceLoadWidth(N);
6022 if (Reduced.getNode())
6024 // Handle the case where the load remains an extending load even
6025 // after truncation.
6026 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6027 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6028 if (!LN0->isVolatile() &&
6029 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6030 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6031 VT, LN0->getChain(), LN0->getBasePtr(),
6033 LN0->getMemOperand());
6034 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6039 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6040 // where ... are all 'undef'.
6041 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6042 SmallVector<EVT, 8> VTs;
6045 unsigned NumDefs = 0;
6047 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6048 SDValue X = N0.getOperand(i);
6049 if (X.getOpcode() != ISD::UNDEF) {
6054 // Stop if more than one members are non-undef.
6057 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6058 VT.getVectorElementType(),
6059 X.getValueType().getVectorNumElements()));
6063 return DAG.getUNDEF(VT);
6066 assert(V.getNode() && "The single defined operand is empty!");
6067 SmallVector<SDValue, 8> Opnds;
6068 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6070 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6073 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6074 AddToWorkList(NV.getNode());
6075 Opnds.push_back(NV);
6077 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6078 &Opnds[0], Opnds.size());
6082 // Simplify the operands using demanded-bits information.
6083 if (!VT.isVector() &&
6084 SimplifyDemandedBits(SDValue(N, 0)))
6085 return SDValue(N, 0);
6090 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6091 SDValue Elt = N->getOperand(i);
6092 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6093 return Elt.getNode();
6094 return Elt.getOperand(Elt.getResNo()).getNode();
6097 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6098 /// if load locations are consecutive.
6099 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6100 assert(N->getOpcode() == ISD::BUILD_PAIR);
6102 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6103 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6104 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6105 LD1->getAddressSpace() != LD2->getAddressSpace())
6107 EVT LD1VT = LD1->getValueType(0);
6109 if (ISD::isNON_EXTLoad(LD2) &&
6111 // If both are volatile this would reduce the number of volatile loads.
6112 // If one is volatile it might be ok, but play conservative and bail out.
6113 !LD1->isVolatile() &&
6114 !LD2->isVolatile() &&
6115 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6116 unsigned Align = LD1->getAlignment();
6117 unsigned NewAlign = TLI.getDataLayout()->
6118 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6120 if (NewAlign <= Align &&
6121 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6122 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6123 LD1->getBasePtr(), LD1->getPointerInfo(),
6124 false, false, false, Align);
6130 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6131 SDValue N0 = N->getOperand(0);
6132 EVT VT = N->getValueType(0);
6134 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6135 // Only do this before legalize, since afterward the target may be depending
6136 // on the bitconvert.
6137 // First check to see if this is all constant.
6139 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6141 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6143 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6144 assert(!DestEltVT.isVector() &&
6145 "Element type of vector ValueType must not be vector!");
6147 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6150 // If the input is a constant, let getNode fold it.
6151 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6152 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6153 if (Res.getNode() != N) {
6154 if (!LegalOperations ||
6155 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6158 // Folding it resulted in an illegal node, and it's too late to
6159 // do that. Clean up the old node and forego the transformation.
6160 // Ideally this won't happen very often, because instcombine
6161 // and the earlier dagcombine runs (where illegal nodes are
6162 // permitted) should have folded most of them already.
6163 DAG.DeleteNode(Res.getNode());
6167 // (conv (conv x, t1), t2) -> (conv x, t2)
6168 if (N0.getOpcode() == ISD::BITCAST)
6169 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6172 // fold (conv (load x)) -> (load (conv*)x)
6173 // If the resultant load doesn't need a higher alignment than the original!
6174 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6175 // Do not change the width of a volatile load.
6176 !cast<LoadSDNode>(N0)->isVolatile() &&
6177 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6178 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6179 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6180 unsigned Align = TLI.getDataLayout()->
6181 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6182 unsigned OrigAlign = LN0->getAlignment();
6184 if (Align <= OrigAlign) {
6185 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6186 LN0->getBasePtr(), LN0->getPointerInfo(),
6187 LN0->isVolatile(), LN0->isNonTemporal(),
6188 LN0->isInvariant(), OrigAlign,
6189 LN0->getTBAAInfo());
6191 CombineTo(N0.getNode(),
6192 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6193 N0.getValueType(), Load),
6199 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6200 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6201 // This often reduces constant pool loads.
6202 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6203 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6204 N0.getNode()->hasOneUse() && VT.isInteger() &&
6205 !VT.isVector() && !N0.getValueType().isVector()) {
6206 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6208 AddToWorkList(NewConv.getNode());
6210 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6211 if (N0.getOpcode() == ISD::FNEG)
6212 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6213 NewConv, DAG.getConstant(SignBit, VT));
6214 assert(N0.getOpcode() == ISD::FABS);
6215 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6216 NewConv, DAG.getConstant(~SignBit, VT));
6219 // fold (bitconvert (fcopysign cst, x)) ->
6220 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6221 // Note that we don't handle (copysign x, cst) because this can always be
6222 // folded to an fneg or fabs.
6223 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6224 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6225 VT.isInteger() && !VT.isVector()) {
6226 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6227 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6228 if (isTypeLegal(IntXVT)) {
6229 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6230 IntXVT, N0.getOperand(1));
6231 AddToWorkList(X.getNode());
6233 // If X has a different width than the result/lhs, sext it or truncate it.
6234 unsigned VTWidth = VT.getSizeInBits();
6235 if (OrigXWidth < VTWidth) {
6236 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6237 AddToWorkList(X.getNode());
6238 } else if (OrigXWidth > VTWidth) {
6239 // To get the sign bit in the right place, we have to shift it right
6240 // before truncating.
6241 X = DAG.getNode(ISD::SRL, SDLoc(X),
6242 X.getValueType(), X,
6243 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6244 AddToWorkList(X.getNode());
6245 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6246 AddToWorkList(X.getNode());
6249 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6250 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6251 X, DAG.getConstant(SignBit, VT));
6252 AddToWorkList(X.getNode());
6254 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6255 VT, N0.getOperand(0));
6256 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6257 Cst, DAG.getConstant(~SignBit, VT));
6258 AddToWorkList(Cst.getNode());
6260 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6264 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6265 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6266 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6267 if (CombineLD.getNode())
6274 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6275 EVT VT = N->getValueType(0);
6276 return CombineConsecutiveLoads(N, VT);
6279 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6280 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6281 /// destination element value type.
6282 SDValue DAGCombiner::
6283 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6284 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6286 // If this is already the right type, we're done.
6287 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6289 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6290 unsigned DstBitSize = DstEltVT.getSizeInBits();
6292 // If this is a conversion of N elements of one type to N elements of another
6293 // type, convert each element. This handles FP<->INT cases.
6294 if (SrcBitSize == DstBitSize) {
6295 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6296 BV->getValueType(0).getVectorNumElements());
6298 // Due to the FP element handling below calling this routine recursively,
6299 // we can end up with a scalar-to-vector node here.
6300 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6301 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6302 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6303 DstEltVT, BV->getOperand(0)));
6305 SmallVector<SDValue, 8> Ops;
6306 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6307 SDValue Op = BV->getOperand(i);
6308 // If the vector element type is not legal, the BUILD_VECTOR operands
6309 // are promoted and implicitly truncated. Make that explicit here.
6310 if (Op.getValueType() != SrcEltVT)
6311 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6312 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6314 AddToWorkList(Ops.back().getNode());
6316 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6317 &Ops[0], Ops.size());
6320 // Otherwise, we're growing or shrinking the elements. To avoid having to
6321 // handle annoying details of growing/shrinking FP values, we convert them to
6323 if (SrcEltVT.isFloatingPoint()) {
6324 // Convert the input float vector to a int vector where the elements are the
6326 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6327 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6328 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6332 // Now we know the input is an integer vector. If the output is a FP type,
6333 // convert to integer first, then to FP of the right size.
6334 if (DstEltVT.isFloatingPoint()) {
6335 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6336 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6337 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6339 // Next, convert to FP elements of the same size.
6340 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6343 // Okay, we know the src/dst types are both integers of differing types.
6344 // Handling growing first.
6345 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6346 if (SrcBitSize < DstBitSize) {
6347 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6349 SmallVector<SDValue, 8> Ops;
6350 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6351 i += NumInputsPerOutput) {
6352 bool isLE = TLI.isLittleEndian();
6353 APInt NewBits = APInt(DstBitSize, 0);
6354 bool EltIsUndef = true;
6355 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6356 // Shift the previously computed bits over.
6357 NewBits <<= SrcBitSize;
6358 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6359 if (Op.getOpcode() == ISD::UNDEF) continue;
6362 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6363 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6367 Ops.push_back(DAG.getUNDEF(DstEltVT));
6369 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6372 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6373 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6374 &Ops[0], Ops.size());
6377 // Finally, this must be the case where we are shrinking elements: each input
6378 // turns into multiple outputs.
6379 bool isS2V = ISD::isScalarToVector(BV);
6380 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6381 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6382 NumOutputsPerInput*BV->getNumOperands());
6383 SmallVector<SDValue, 8> Ops;
6385 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6386 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6387 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6388 Ops.push_back(DAG.getUNDEF(DstEltVT));
6392 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6393 getAPIntValue().zextOrTrunc(SrcBitSize);
6395 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6396 APInt ThisVal = OpVal.trunc(DstBitSize);
6397 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6398 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6399 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6400 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6402 OpVal = OpVal.lshr(DstBitSize);
6405 // For big endian targets, swap the order of the pieces of each element.
6406 if (TLI.isBigEndian())
6407 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6410 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6411 &Ops[0], Ops.size());
6414 SDValue DAGCombiner::visitFADD(SDNode *N) {
6415 SDValue N0 = N->getOperand(0);
6416 SDValue N1 = N->getOperand(1);
6417 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6418 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6419 EVT VT = N->getValueType(0);
6422 if (VT.isVector()) {
6423 SDValue FoldedVOp = SimplifyVBinOp(N);
6424 if (FoldedVOp.getNode()) return FoldedVOp;
6427 // fold (fadd c1, c2) -> c1 + c2
6429 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6430 // canonicalize constant to RHS
6431 if (N0CFP && !N1CFP)
6432 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6433 // fold (fadd A, 0) -> A
6434 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6435 N1CFP->getValueAPF().isZero())
6437 // fold (fadd A, (fneg B)) -> (fsub A, B)
6438 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6439 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6440 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6441 GetNegatedExpression(N1, DAG, LegalOperations));
6442 // fold (fadd (fneg A), B) -> (fsub B, A)
6443 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6444 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6445 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6446 GetNegatedExpression(N0, DAG, LegalOperations));
6448 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6449 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6450 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6451 isa<ConstantFPSDNode>(N0.getOperand(1)))
6452 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6453 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6454 N0.getOperand(1), N1));
6456 // No FP constant should be created after legalization as Instruction
6457 // Selection pass has hard time in dealing with FP constant.
6459 // We don't need test this condition for transformation like following, as
6460 // the DAG being transformed implies it is legal to take FP constant as
6463 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6465 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6467 // If allow, fold (fadd (fneg x), x) -> 0.0
6468 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6469 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6470 return DAG.getConstantFP(0.0, VT);
6472 // If allow, fold (fadd x, (fneg x)) -> 0.0
6473 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6474 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6475 return DAG.getConstantFP(0.0, VT);
6477 // In unsafe math mode, we can fold chains of FADD's of the same value
6478 // into multiplications. This transform is not safe in general because
6479 // we are reducing the number of rounding steps.
6480 if (DAG.getTarget().Options.UnsafeFPMath &&
6481 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6483 if (N0.getOpcode() == ISD::FMUL) {
6484 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6485 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6487 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6488 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6489 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6491 DAG.getConstantFP(1.0, VT));
6492 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6496 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6497 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6498 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6500 DAG.getConstantFP(1.0, VT));
6501 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6505 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6506 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6507 N1.getOperand(0) == N1.getOperand(1) &&
6508 N0.getOperand(1) == N1.getOperand(0)) {
6509 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6511 DAG.getConstantFP(2.0, VT));
6512 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6513 N0.getOperand(1), NewCFP);
6516 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6517 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6518 N1.getOperand(0) == N1.getOperand(1) &&
6519 N0.getOperand(0) == N1.getOperand(0)) {
6520 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6522 DAG.getConstantFP(2.0, VT));
6523 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6524 N0.getOperand(0), NewCFP);
6528 if (N1.getOpcode() == ISD::FMUL) {
6529 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6530 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6532 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6533 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6536 DAG.getConstantFP(1.0, VT));
6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6541 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6542 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6543 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6545 DAG.getConstantFP(1.0, VT));
6546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6551 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6552 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6553 N0.getOperand(0) == N0.getOperand(1) &&
6554 N1.getOperand(1) == N0.getOperand(0)) {
6555 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6557 DAG.getConstantFP(2.0, VT));
6558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559 N1.getOperand(1), NewCFP);
6562 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6563 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6564 N0.getOperand(0) == N0.getOperand(1) &&
6565 N1.getOperand(0) == N0.getOperand(0)) {
6566 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6568 DAG.getConstantFP(2.0, VT));
6569 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6570 N1.getOperand(0), NewCFP);
6574 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6575 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6576 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6577 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6578 (N0.getOperand(0) == N1))
6579 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6580 N1, DAG.getConstantFP(3.0, VT));
6583 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6584 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6585 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6586 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6587 N1.getOperand(0) == N0)
6588 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6589 N0, DAG.getConstantFP(3.0, VT));
6592 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6593 if (AllowNewFpConst &&
6594 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6595 N0.getOperand(0) == N0.getOperand(1) &&
6596 N1.getOperand(0) == N1.getOperand(1) &&
6597 N0.getOperand(0) == N1.getOperand(0))
6598 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6600 DAG.getConstantFP(4.0, VT));
6603 // FADD -> FMA combines:
6604 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6605 DAG.getTarget().Options.UnsafeFPMath) &&
6606 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6607 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6609 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6610 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6611 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6612 N0.getOperand(0), N0.getOperand(1), N1);
6614 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6615 // Note: Commutes FADD operands.
6616 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6617 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6618 N1.getOperand(0), N1.getOperand(1), N0);
6624 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6625 SDValue N0 = N->getOperand(0);
6626 SDValue N1 = N->getOperand(1);
6627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6629 EVT VT = N->getValueType(0);
6633 if (VT.isVector()) {
6634 SDValue FoldedVOp = SimplifyVBinOp(N);
6635 if (FoldedVOp.getNode()) return FoldedVOp;
6638 // fold (fsub c1, c2) -> c1-c2
6640 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6641 // fold (fsub A, 0) -> A
6642 if (DAG.getTarget().Options.UnsafeFPMath &&
6643 N1CFP && N1CFP->getValueAPF().isZero())
6645 // fold (fsub 0, B) -> -B
6646 if (DAG.getTarget().Options.UnsafeFPMath &&
6647 N0CFP && N0CFP->getValueAPF().isZero()) {
6648 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6649 return GetNegatedExpression(N1, DAG, LegalOperations);
6650 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6651 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6653 // fold (fsub A, (fneg B)) -> (fadd A, B)
6654 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6655 return DAG.getNode(ISD::FADD, dl, VT, N0,
6656 GetNegatedExpression(N1, DAG, LegalOperations));
6658 // If 'unsafe math' is enabled, fold
6659 // (fsub x, x) -> 0.0 &
6660 // (fsub x, (fadd x, y)) -> (fneg y) &
6661 // (fsub x, (fadd y, x)) -> (fneg y)
6662 if (DAG.getTarget().Options.UnsafeFPMath) {
6664 return DAG.getConstantFP(0.0f, VT);
6666 if (N1.getOpcode() == ISD::FADD) {
6667 SDValue N10 = N1->getOperand(0);
6668 SDValue N11 = N1->getOperand(1);
6670 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6671 &DAG.getTarget().Options))
6672 return GetNegatedExpression(N11, DAG, LegalOperations);
6674 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6675 &DAG.getTarget().Options))
6676 return GetNegatedExpression(N10, DAG, LegalOperations);
6680 // FSUB -> FMA combines:
6681 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6682 DAG.getTarget().Options.UnsafeFPMath) &&
6683 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6684 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6686 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6687 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6688 return DAG.getNode(ISD::FMA, dl, VT,
6689 N0.getOperand(0), N0.getOperand(1),
6690 DAG.getNode(ISD::FNEG, dl, VT, N1));
6692 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6693 // Note: Commutes FSUB operands.
6694 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6695 return DAG.getNode(ISD::FMA, dl, VT,
6696 DAG.getNode(ISD::FNEG, dl, VT,
6698 N1.getOperand(1), N0);
6700 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6701 if (N0.getOpcode() == ISD::FNEG &&
6702 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6703 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6704 SDValue N00 = N0.getOperand(0).getOperand(0);
6705 SDValue N01 = N0.getOperand(0).getOperand(1);
6706 return DAG.getNode(ISD::FMA, dl, VT,
6707 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6708 DAG.getNode(ISD::FNEG, dl, VT, N1));
6715 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6716 SDValue N0 = N->getOperand(0);
6717 SDValue N1 = N->getOperand(1);
6718 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6719 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6720 EVT VT = N->getValueType(0);
6721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6724 if (VT.isVector()) {
6725 SDValue FoldedVOp = SimplifyVBinOp(N);
6726 if (FoldedVOp.getNode()) return FoldedVOp;
6729 // fold (fmul c1, c2) -> c1*c2
6731 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6732 // canonicalize constant to RHS
6733 if (N0CFP && !N1CFP)
6734 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6735 // fold (fmul A, 0) -> 0
6736 if (DAG.getTarget().Options.UnsafeFPMath &&
6737 N1CFP && N1CFP->getValueAPF().isZero())
6739 // fold (fmul A, 0) -> 0, vector edition.
6740 if (DAG.getTarget().Options.UnsafeFPMath &&
6741 ISD::isBuildVectorAllZeros(N1.getNode()))
6743 // fold (fmul A, 1.0) -> A
6744 if (N1CFP && N1CFP->isExactlyValue(1.0))
6746 // fold (fmul X, 2.0) -> (fadd X, X)
6747 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6748 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6749 // fold (fmul X, -1.0) -> (fneg X)
6750 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6751 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6752 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6754 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6755 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6756 &DAG.getTarget().Options)) {
6757 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6758 &DAG.getTarget().Options)) {
6759 // Both can be negated for free, check to see if at least one is cheaper
6761 if (LHSNeg == 2 || RHSNeg == 2)
6762 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6763 GetNegatedExpression(N0, DAG, LegalOperations),
6764 GetNegatedExpression(N1, DAG, LegalOperations));
6768 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6769 if (DAG.getTarget().Options.UnsafeFPMath &&
6770 N1CFP && N0.getOpcode() == ISD::FMUL &&
6771 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6772 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6773 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6774 N0.getOperand(1), N1));
6779 SDValue DAGCombiner::visitFMA(SDNode *N) {
6780 SDValue N0 = N->getOperand(0);
6781 SDValue N1 = N->getOperand(1);
6782 SDValue N2 = N->getOperand(2);
6783 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6784 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6785 EVT VT = N->getValueType(0);
6788 if (DAG.getTarget().Options.UnsafeFPMath) {
6789 if (N0CFP && N0CFP->isZero())
6791 if (N1CFP && N1CFP->isZero())
6794 if (N0CFP && N0CFP->isExactlyValue(1.0))
6795 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6796 if (N1CFP && N1CFP->isExactlyValue(1.0))
6797 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6799 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6800 if (N0CFP && !N1CFP)
6801 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6803 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6804 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6805 N2.getOpcode() == ISD::FMUL &&
6806 N0 == N2.getOperand(0) &&
6807 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6808 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6809 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6813 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6814 if (DAG.getTarget().Options.UnsafeFPMath &&
6815 N0.getOpcode() == ISD::FMUL && N1CFP &&
6816 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6817 return DAG.getNode(ISD::FMA, dl, VT,
6819 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6823 // (fma x, 1, y) -> (fadd x, y)
6824 // (fma x, -1, y) -> (fadd (fneg x), y)
6826 if (N1CFP->isExactlyValue(1.0))
6827 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6829 if (N1CFP->isExactlyValue(-1.0) &&
6830 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6831 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6832 AddToWorkList(RHSNeg.getNode());
6833 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6837 // (fma x, c, x) -> (fmul x, (c+1))
6838 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6839 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6840 DAG.getNode(ISD::FADD, dl, VT,
6841 N1, DAG.getConstantFP(1.0, VT)));
6843 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6844 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6845 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6846 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6847 DAG.getNode(ISD::FADD, dl, VT,
6848 N1, DAG.getConstantFP(-1.0, VT)));
6854 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6855 SDValue N0 = N->getOperand(0);
6856 SDValue N1 = N->getOperand(1);
6857 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6858 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6859 EVT VT = N->getValueType(0);
6860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6863 if (VT.isVector()) {
6864 SDValue FoldedVOp = SimplifyVBinOp(N);
6865 if (FoldedVOp.getNode()) return FoldedVOp;
6868 // fold (fdiv c1, c2) -> c1/c2
6870 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6872 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6873 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6874 // Compute the reciprocal 1.0 / c2.
6875 APFloat N1APF = N1CFP->getValueAPF();
6876 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6877 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6878 // Only do the transform if the reciprocal is a legal fp immediate that
6879 // isn't too nasty (eg NaN, denormal, ...).
6880 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6881 (!LegalOperations ||
6882 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6883 // backend)... we should handle this gracefully after Legalize.
6884 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6885 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6886 TLI.isFPImmLegal(Recip, VT)))
6887 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6888 DAG.getConstantFP(Recip, VT));
6891 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6892 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6893 &DAG.getTarget().Options)) {
6894 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6895 &DAG.getTarget().Options)) {
6896 // Both can be negated for free, check to see if at least one is cheaper
6898 if (LHSNeg == 2 || RHSNeg == 2)
6899 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6900 GetNegatedExpression(N0, DAG, LegalOperations),
6901 GetNegatedExpression(N1, DAG, LegalOperations));
6908 SDValue DAGCombiner::visitFREM(SDNode *N) {
6909 SDValue N0 = N->getOperand(0);
6910 SDValue N1 = N->getOperand(1);
6911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6912 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6913 EVT VT = N->getValueType(0);
6915 // fold (frem c1, c2) -> fmod(c1,c2)
6917 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6922 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6923 SDValue N0 = N->getOperand(0);
6924 SDValue N1 = N->getOperand(1);
6925 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6926 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6927 EVT VT = N->getValueType(0);
6929 if (N0CFP && N1CFP) // Constant fold
6930 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6933 const APFloat& V = N1CFP->getValueAPF();
6934 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6935 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6936 if (!V.isNegative()) {
6937 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6938 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6940 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6941 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6942 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6946 // copysign(fabs(x), y) -> copysign(x, y)
6947 // copysign(fneg(x), y) -> copysign(x, y)
6948 // copysign(copysign(x,z), y) -> copysign(x, y)
6949 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6950 N0.getOpcode() == ISD::FCOPYSIGN)
6951 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6952 N0.getOperand(0), N1);
6954 // copysign(x, abs(y)) -> abs(x)
6955 if (N1.getOpcode() == ISD::FABS)
6956 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6958 // copysign(x, copysign(y,z)) -> copysign(x, z)
6959 if (N1.getOpcode() == ISD::FCOPYSIGN)
6960 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6961 N0, N1.getOperand(1));
6963 // copysign(x, fp_extend(y)) -> copysign(x, y)
6964 // copysign(x, fp_round(y)) -> copysign(x, y)
6965 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6966 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6967 N0, N1.getOperand(0));
6972 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6973 SDValue N0 = N->getOperand(0);
6974 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6975 EVT VT = N->getValueType(0);
6976 EVT OpVT = N0.getValueType();
6978 // fold (sint_to_fp c1) -> c1fp
6980 // ...but only if the target supports immediate floating-point values
6981 (!LegalOperations ||
6982 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6983 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6985 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6986 // but UINT_TO_FP is legal on this target, try to convert.
6987 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6988 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6989 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6990 if (DAG.SignBitIsZero(N0))
6991 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6994 // The next optimizations are desirable only if SELECT_CC can be lowered.
6995 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6996 // having to say they don't support SELECT_CC on every type the DAG knows
6997 // about, since there is no way to mark an opcode illegal at all value types
6998 // (See also visitSELECT)
6999 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7000 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7001 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7003 (!LegalOperations ||
7004 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7006 { N0.getOperand(0), N0.getOperand(1),
7007 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7009 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7012 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7013 // (select_cc x, y, 1.0, 0.0,, cc)
7014 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7015 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7016 (!LegalOperations ||
7017 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7019 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7020 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7021 N0.getOperand(0).getOperand(2) };
7022 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7029 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7030 SDValue N0 = N->getOperand(0);
7031 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7032 EVT VT = N->getValueType(0);
7033 EVT OpVT = N0.getValueType();
7035 // fold (uint_to_fp c1) -> c1fp
7037 // ...but only if the target supports immediate floating-point values
7038 (!LegalOperations ||
7039 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7040 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7042 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7043 // but SINT_TO_FP is legal on this target, try to convert.
7044 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7045 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7046 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7047 if (DAG.SignBitIsZero(N0))
7048 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7051 // The next optimizations are desirable only if SELECT_CC can be lowered.
7052 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7053 // having to say they don't support SELECT_CC on every type the DAG knows
7054 // about, since there is no way to mark an opcode illegal at all value types
7055 // (See also visitSELECT)
7056 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7057 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7059 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7060 (!LegalOperations ||
7061 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7063 { N0.getOperand(0), N0.getOperand(1),
7064 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7066 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7073 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7074 SDValue N0 = N->getOperand(0);
7075 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7076 EVT VT = N->getValueType(0);
7078 // fold (fp_to_sint c1fp) -> c1
7080 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7085 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7086 SDValue N0 = N->getOperand(0);
7087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7088 EVT VT = N->getValueType(0);
7090 // fold (fp_to_uint c1fp) -> c1
7092 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7097 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7098 SDValue N0 = N->getOperand(0);
7099 SDValue N1 = N->getOperand(1);
7100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7101 EVT VT = N->getValueType(0);
7103 // fold (fp_round c1fp) -> c1fp
7105 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7107 // fold (fp_round (fp_extend x)) -> x
7108 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7109 return N0.getOperand(0);
7111 // fold (fp_round (fp_round x)) -> (fp_round x)
7112 if (N0.getOpcode() == ISD::FP_ROUND) {
7113 // This is a value preserving truncation if both round's are.
7114 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7115 N0.getNode()->getConstantOperandVal(1) == 1;
7116 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7117 DAG.getIntPtrConstant(IsTrunc));
7120 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7121 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7122 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7123 N0.getOperand(0), N1);
7124 AddToWorkList(Tmp.getNode());
7125 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7126 Tmp, N0.getOperand(1));
7132 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7133 SDValue N0 = N->getOperand(0);
7134 EVT VT = N->getValueType(0);
7135 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7136 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7138 // fold (fp_round_inreg c1fp) -> c1fp
7139 if (N0CFP && isTypeLegal(EVT)) {
7140 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7141 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7147 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7148 SDValue N0 = N->getOperand(0);
7149 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7150 EVT VT = N->getValueType(0);
7152 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7153 if (N->hasOneUse() &&
7154 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7157 // fold (fp_extend c1fp) -> c1fp
7159 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7161 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7163 if (N0.getOpcode() == ISD::FP_ROUND
7164 && N0.getNode()->getConstantOperandVal(1) == 1) {
7165 SDValue In = N0.getOperand(0);
7166 if (In.getValueType() == VT) return In;
7167 if (VT.bitsLT(In.getValueType()))
7168 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7169 In, N0.getOperand(1));
7170 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7173 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7174 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7175 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7176 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7177 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7178 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7180 LN0->getBasePtr(), N0.getValueType(),
7181 LN0->getMemOperand());
7182 CombineTo(N, ExtLoad);
7183 CombineTo(N0.getNode(),
7184 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7185 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7186 ExtLoad.getValue(1));
7187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7193 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
7195 EVT VT = N->getValueType(0);
7197 if (VT.isVector()) {
7198 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7199 if (FoldedVOp.getNode()) return FoldedVOp;
7202 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7203 &DAG.getTarget().Options))
7204 return GetNegatedExpression(N0, DAG, LegalOperations);
7206 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7207 // constant pool values.
7208 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7210 N0.getNode()->hasOneUse() &&
7211 N0.getOperand(0).getValueType().isInteger()) {
7212 SDValue Int = N0.getOperand(0);
7213 EVT IntVT = Int.getValueType();
7214 if (IntVT.isInteger() && !IntVT.isVector()) {
7215 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7216 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7217 AddToWorkList(Int.getNode());
7218 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7223 // (fneg (fmul c, x)) -> (fmul -c, x)
7224 if (N0.getOpcode() == ISD::FMUL) {
7225 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7227 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7229 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7236 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7237 SDValue N0 = N->getOperand(0);
7238 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7239 EVT VT = N->getValueType(0);
7241 // fold (fceil c1) -> fceil(c1)
7243 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7248 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7249 SDValue N0 = N->getOperand(0);
7250 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7251 EVT VT = N->getValueType(0);
7253 // fold (ftrunc c1) -> ftrunc(c1)
7255 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7260 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7261 SDValue N0 = N->getOperand(0);
7262 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7263 EVT VT = N->getValueType(0);
7265 // fold (ffloor c1) -> ffloor(c1)
7267 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7272 SDValue DAGCombiner::visitFABS(SDNode *N) {
7273 SDValue N0 = N->getOperand(0);
7274 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7275 EVT VT = N->getValueType(0);
7277 if (VT.isVector()) {
7278 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7279 if (FoldedVOp.getNode()) return FoldedVOp;
7282 // fold (fabs c1) -> fabs(c1)
7284 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7285 // fold (fabs (fabs x)) -> (fabs x)
7286 if (N0.getOpcode() == ISD::FABS)
7287 return N->getOperand(0);
7288 // fold (fabs (fneg x)) -> (fabs x)
7289 // fold (fabs (fcopysign x, y)) -> (fabs x)
7290 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7291 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7293 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7294 // constant pool values.
7295 if (!TLI.isFAbsFree(VT) &&
7296 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7297 N0.getOperand(0).getValueType().isInteger() &&
7298 !N0.getOperand(0).getValueType().isVector()) {
7299 SDValue Int = N0.getOperand(0);
7300 EVT IntVT = Int.getValueType();
7301 if (IntVT.isInteger() && !IntVT.isVector()) {
7302 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7303 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7304 AddToWorkList(Int.getNode());
7305 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7306 N->getValueType(0), Int);
7313 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7314 SDValue Chain = N->getOperand(0);
7315 SDValue N1 = N->getOperand(1);
7316 SDValue N2 = N->getOperand(2);
7318 // If N is a constant we could fold this into a fallthrough or unconditional
7319 // branch. However that doesn't happen very often in normal code, because
7320 // Instcombine/SimplifyCFG should have handled the available opportunities.
7321 // If we did this folding here, it would be necessary to update the
7322 // MachineBasicBlock CFG, which is awkward.
7324 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7326 if (N1.getOpcode() == ISD::SETCC &&
7327 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7328 N1.getOperand(0).getValueType())) {
7329 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7330 Chain, N1.getOperand(2),
7331 N1.getOperand(0), N1.getOperand(1), N2);
7334 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7335 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7336 (N1.getOperand(0).hasOneUse() &&
7337 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7339 if (N1.getOpcode() == ISD::TRUNCATE) {
7340 // Look pass the truncate.
7341 Trunc = N1.getNode();
7342 N1 = N1.getOperand(0);
7345 // Match this pattern so that we can generate simpler code:
7348 // %b = and i32 %a, 2
7349 // %c = srl i32 %b, 1
7350 // brcond i32 %c ...
7355 // %b = and i32 %a, 2
7356 // %c = setcc eq %b, 0
7359 // This applies only when the AND constant value has one bit set and the
7360 // SRL constant is equal to the log2 of the AND constant. The back-end is
7361 // smart enough to convert the result into a TEST/JMP sequence.
7362 SDValue Op0 = N1.getOperand(0);
7363 SDValue Op1 = N1.getOperand(1);
7365 if (Op0.getOpcode() == ISD::AND &&
7366 Op1.getOpcode() == ISD::Constant) {
7367 SDValue AndOp1 = Op0.getOperand(1);
7369 if (AndOp1.getOpcode() == ISD::Constant) {
7370 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7372 if (AndConst.isPowerOf2() &&
7373 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7375 DAG.getSetCC(SDLoc(N),
7376 getSetCCResultType(Op0.getValueType()),
7377 Op0, DAG.getConstant(0, Op0.getValueType()),
7380 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7381 MVT::Other, Chain, SetCC, N2);
7382 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7383 // will convert it back to (X & C1) >> C2.
7384 CombineTo(N, NewBRCond, false);
7385 // Truncate is dead.
7387 removeFromWorkList(Trunc);
7388 DAG.DeleteNode(Trunc);
7390 // Replace the uses of SRL with SETCC
7391 WorkListRemover DeadNodes(*this);
7392 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7393 removeFromWorkList(N1.getNode());
7394 DAG.DeleteNode(N1.getNode());
7395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7401 // Restore N1 if the above transformation doesn't match.
7402 N1 = N->getOperand(1);
7405 // Transform br(xor(x, y)) -> br(x != y)
7406 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7407 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7408 SDNode *TheXor = N1.getNode();
7409 SDValue Op0 = TheXor->getOperand(0);
7410 SDValue Op1 = TheXor->getOperand(1);
7411 if (Op0.getOpcode() == Op1.getOpcode()) {
7412 // Avoid missing important xor optimizations.
7413 SDValue Tmp = visitXOR(TheXor);
7414 if (Tmp.getNode()) {
7415 if (Tmp.getNode() != TheXor) {
7416 DEBUG(dbgs() << "\nReplacing.8 ";
7418 dbgs() << "\nWith: ";
7419 Tmp.getNode()->dump(&DAG);
7421 WorkListRemover DeadNodes(*this);
7422 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7423 removeFromWorkList(TheXor);
7424 DAG.DeleteNode(TheXor);
7425 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7426 MVT::Other, Chain, Tmp, N2);
7429 // visitXOR has changed XOR's operands or replaced the XOR completely,
7431 return SDValue(N, 0);
7435 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7437 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7438 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7439 Op0.getOpcode() == ISD::XOR) {
7440 TheXor = Op0.getNode();
7444 EVT SetCCVT = N1.getValueType();
7446 SetCCVT = getSetCCResultType(SetCCVT);
7447 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7450 Equal ? ISD::SETEQ : ISD::SETNE);
7451 // Replace the uses of XOR with SETCC
7452 WorkListRemover DeadNodes(*this);
7453 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7454 removeFromWorkList(N1.getNode());
7455 DAG.DeleteNode(N1.getNode());
7456 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7457 MVT::Other, Chain, SetCC, N2);
7464 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7466 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7467 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7468 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7470 // If N is a constant we could fold this into a fallthrough or unconditional
7471 // branch. However that doesn't happen very often in normal code, because
7472 // Instcombine/SimplifyCFG should have handled the available opportunities.
7473 // If we did this folding here, it would be necessary to update the
7474 // MachineBasicBlock CFG, which is awkward.
7476 // Use SimplifySetCC to simplify SETCC's.
7477 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7478 CondLHS, CondRHS, CC->get(), SDLoc(N),
7480 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7482 // fold to a simpler setcc
7483 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7484 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7485 N->getOperand(0), Simp.getOperand(2),
7486 Simp.getOperand(0), Simp.getOperand(1),
7492 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7493 /// uses N as its base pointer and that N may be folded in the load / store
7494 /// addressing mode.
7495 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7497 const TargetLowering &TLI) {
7499 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7500 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7502 VT = Use->getValueType(0);
7503 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7504 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7506 VT = ST->getValue().getValueType();
7510 TargetLowering::AddrMode AM;
7511 if (N->getOpcode() == ISD::ADD) {
7512 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7515 AM.BaseOffs = Offset->getSExtValue();
7519 } else if (N->getOpcode() == ISD::SUB) {
7520 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7523 AM.BaseOffs = -Offset->getSExtValue();
7530 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7533 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7534 /// pre-indexed load / store when the base pointer is an add or subtract
7535 /// and it has other uses besides the load / store. After the
7536 /// transformation, the new indexed load / store has effectively folded
7537 /// the add / subtract in and all of its other uses are redirected to the
7538 /// new load / store.
7539 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7540 if (Level < AfterLegalizeDAG)
7546 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7547 if (LD->isIndexed())
7549 VT = LD->getMemoryVT();
7550 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7551 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7553 Ptr = LD->getBasePtr();
7554 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7555 if (ST->isIndexed())
7557 VT = ST->getMemoryVT();
7558 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7559 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7561 Ptr = ST->getBasePtr();
7567 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7568 // out. There is no reason to make this a preinc/predec.
7569 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7570 Ptr.getNode()->hasOneUse())
7573 // Ask the target to do addressing mode selection.
7576 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7577 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7580 // Backends without true r+i pre-indexed forms may need to pass a
7581 // constant base with a variable offset so that constant coercion
7582 // will work with the patterns in canonical form.
7583 bool Swapped = false;
7584 if (isa<ConstantSDNode>(BasePtr)) {
7585 std::swap(BasePtr, Offset);
7589 // Don't create a indexed load / store with zero offset.
7590 if (isa<ConstantSDNode>(Offset) &&
7591 cast<ConstantSDNode>(Offset)->isNullValue())
7594 // Try turning it into a pre-indexed load / store except when:
7595 // 1) The new base ptr is a frame index.
7596 // 2) If N is a store and the new base ptr is either the same as or is a
7597 // predecessor of the value being stored.
7598 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7599 // that would create a cycle.
7600 // 4) All uses are load / store ops that use it as old base ptr.
7602 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7603 // (plus the implicit offset) to a register to preinc anyway.
7604 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7609 SDValue Val = cast<StoreSDNode>(N)->getValue();
7610 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7614 // If the offset is a constant, there may be other adds of constants that
7615 // can be folded with this one. We should do this to avoid having to keep
7616 // a copy of the original base pointer.
7617 SmallVector<SDNode *, 16> OtherUses;
7618 if (isa<ConstantSDNode>(Offset))
7619 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7620 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7622 if (Use == Ptr.getNode())
7625 if (Use->isPredecessorOf(N))
7628 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7633 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7634 if (Op1.getNode() == BasePtr.getNode())
7635 std::swap(Op0, Op1);
7636 assert(Op0.getNode() == BasePtr.getNode() &&
7637 "Use of ADD/SUB but not an operand");
7639 if (!isa<ConstantSDNode>(Op1)) {
7644 // FIXME: In some cases, we can be smarter about this.
7645 if (Op1.getValueType() != Offset.getValueType()) {
7650 OtherUses.push_back(Use);
7654 std::swap(BasePtr, Offset);
7656 // Now check for #3 and #4.
7657 bool RealUse = false;
7659 // Caches for hasPredecessorHelper
7660 SmallPtrSet<const SDNode *, 32> Visited;
7661 SmallVector<const SDNode *, 16> Worklist;
7663 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7664 E = Ptr.getNode()->use_end(); I != E; ++I) {
7668 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7671 // If Ptr may be folded in addressing mode of other use, then it's
7672 // not profitable to do this transformation.
7673 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7682 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7683 BasePtr, Offset, AM);
7685 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7686 BasePtr, Offset, AM);
7689 DEBUG(dbgs() << "\nReplacing.4 ";
7691 dbgs() << "\nWith: ";
7692 Result.getNode()->dump(&DAG);
7694 WorkListRemover DeadNodes(*this);
7696 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7697 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7699 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7702 // Finally, since the node is now dead, remove it from the graph.
7706 std::swap(BasePtr, Offset);
7708 // Replace other uses of BasePtr that can be updated to use Ptr
7709 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7710 unsigned OffsetIdx = 1;
7711 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7713 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7714 BasePtr.getNode() && "Expected BasePtr operand");
7716 // We need to replace ptr0 in the following expression:
7717 // x0 * offset0 + y0 * ptr0 = t0
7719 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7721 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7722 // indexed load/store and the expresion that needs to be re-written.
7724 // Therefore, we have:
7725 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7727 ConstantSDNode *CN =
7728 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7730 APInt Offset0 = CN->getAPIntValue();
7731 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7733 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7734 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7735 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7736 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7738 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7740 APInt CNV = Offset0;
7741 if (X0 < 0) CNV = -CNV;
7742 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7743 else CNV = CNV - Offset1;
7745 // We can now generate the new expression.
7746 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7747 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7749 SDValue NewUse = DAG.getNode(Opcode,
7750 SDLoc(OtherUses[i]),
7751 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7752 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7753 removeFromWorkList(OtherUses[i]);
7754 DAG.DeleteNode(OtherUses[i]);
7757 // Replace the uses of Ptr with uses of the updated base value.
7758 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7759 removeFromWorkList(Ptr.getNode());
7760 DAG.DeleteNode(Ptr.getNode());
7765 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7766 /// add / sub of the base pointer node into a post-indexed load / store.
7767 /// The transformation folded the add / subtract into the new indexed
7768 /// load / store effectively and all of its uses are redirected to the
7769 /// new load / store.
7770 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7771 if (Level < AfterLegalizeDAG)
7777 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7778 if (LD->isIndexed())
7780 VT = LD->getMemoryVT();
7781 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7782 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7784 Ptr = LD->getBasePtr();
7785 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7786 if (ST->isIndexed())
7788 VT = ST->getMemoryVT();
7789 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7790 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7792 Ptr = ST->getBasePtr();
7798 if (Ptr.getNode()->hasOneUse())
7801 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7802 E = Ptr.getNode()->use_end(); I != E; ++I) {
7805 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7810 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7811 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7812 // Don't create a indexed load / store with zero offset.
7813 if (isa<ConstantSDNode>(Offset) &&
7814 cast<ConstantSDNode>(Offset)->isNullValue())
7817 // Try turning it into a post-indexed load / store except when
7818 // 1) All uses are load / store ops that use it as base ptr (and
7819 // it may be folded as addressing mmode).
7820 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7821 // nor a successor of N. Otherwise, if Op is folded that would
7824 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7828 bool TryNext = false;
7829 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7830 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7832 if (Use == Ptr.getNode())
7835 // If all the uses are load / store addresses, then don't do the
7837 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7838 bool RealUse = false;
7839 for (SDNode::use_iterator III = Use->use_begin(),
7840 EEE = Use->use_end(); III != EEE; ++III) {
7841 SDNode *UseUse = *III;
7842 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7857 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7858 SDValue Result = isLoad
7859 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7860 BasePtr, Offset, AM)
7861 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7862 BasePtr, Offset, AM);
7865 DEBUG(dbgs() << "\nReplacing.5 ";
7867 dbgs() << "\nWith: ";
7868 Result.getNode()->dump(&DAG);
7870 WorkListRemover DeadNodes(*this);
7872 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7873 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7875 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7878 // Finally, since the node is now dead, remove it from the graph.
7881 // Replace the uses of Use with uses of the updated base value.
7882 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7883 Result.getValue(isLoad ? 1 : 0));
7884 removeFromWorkList(Op);
7894 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7895 LoadSDNode *LD = cast<LoadSDNode>(N);
7896 SDValue Chain = LD->getChain();
7897 SDValue Ptr = LD->getBasePtr();
7899 // If load is not volatile and there are no uses of the loaded value (and
7900 // the updated indexed value in case of indexed loads), change uses of the
7901 // chain value into uses of the chain input (i.e. delete the dead load).
7902 if (!LD->isVolatile()) {
7903 if (N->getValueType(1) == MVT::Other) {
7905 if (!N->hasAnyUseOfValue(0)) {
7906 // It's not safe to use the two value CombineTo variant here. e.g.
7907 // v1, chain2 = load chain1, loc
7908 // v2, chain3 = load chain2, loc
7910 // Now we replace use of chain2 with chain1. This makes the second load
7911 // isomorphic to the one we are deleting, and thus makes this load live.
7912 DEBUG(dbgs() << "\nReplacing.6 ";
7914 dbgs() << "\nWith chain: ";
7915 Chain.getNode()->dump(&DAG);
7917 WorkListRemover DeadNodes(*this);
7918 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7920 if (N->use_empty()) {
7921 removeFromWorkList(N);
7925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7929 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7930 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7931 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7932 DEBUG(dbgs() << "\nReplacing.7 ";
7934 dbgs() << "\nWith: ";
7935 Undef.getNode()->dump(&DAG);
7936 dbgs() << " and 2 other values\n");
7937 WorkListRemover DeadNodes(*this);
7938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7939 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7940 DAG.getUNDEF(N->getValueType(1)));
7941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7942 removeFromWorkList(N);
7944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7949 // If this load is directly stored, replace the load value with the stored
7951 // TODO: Handle store large -> read small portion.
7952 // TODO: Handle TRUNCSTORE/LOADEXT
7953 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7954 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7955 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7956 if (PrevST->getBasePtr() == Ptr &&
7957 PrevST->getValue().getValueType() == N->getValueType(0))
7958 return CombineTo(N, Chain.getOperand(1), Chain);
7962 // Try to infer better alignment information than the load already has.
7963 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7964 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7965 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7967 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7968 LD->getValueType(0),
7969 Chain, Ptr, LD->getPointerInfo(),
7971 LD->isVolatile(), LD->isNonTemporal(), Align,
7973 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7978 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7979 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7981 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7982 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7985 if (UseAA && LD->isUnindexed()) {
7986 // Walk up chain skipping non-aliasing memory nodes.
7987 SDValue BetterChain = FindBetterChain(N, Chain);
7989 // If there is a better chain.
7990 if (Chain != BetterChain) {
7993 // Replace the chain to void dependency.
7994 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7995 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7996 BetterChain, Ptr, LD->getMemOperand());
7998 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7999 LD->getValueType(0),
8000 BetterChain, Ptr, LD->getMemoryVT(),
8001 LD->getMemOperand());
8004 // Create token factor to keep old chain connected.
8005 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8006 MVT::Other, Chain, ReplLoad.getValue(1));
8008 // Make sure the new and old chains are cleaned up.
8009 AddToWorkList(Token.getNode());
8011 // Replace uses with load result and token factor. Don't add users
8013 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8017 // Try transforming N to an indexed load.
8018 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8019 return SDValue(N, 0);
8021 // Try to slice up N to more direct loads if the slices are mapped to
8022 // different register banks or pairing can take place.
8024 return SDValue(N, 0);
8030 /// \brief Helper structure used to slice a load in smaller loads.
8031 /// Basically a slice is obtained from the following sequence:
8032 /// Origin = load Ty1, Base
8033 /// Shift = srl Ty1 Origin, CstTy Amount
8034 /// Inst = trunc Shift to Ty2
8036 /// Then, it will be rewriten into:
8037 /// Slice = load SliceTy, Base + SliceOffset
8038 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8040 /// SliceTy is deduced from the number of bits that are actually used to
8042 struct LoadedSlice {
8043 /// \brief Helper structure used to compute the cost of a slice.
8045 /// Are we optimizing for code size.
8050 unsigned CrossRegisterBanksCopies;
8054 Cost(bool ForCodeSize = false)
8055 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8056 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8058 /// \brief Get the cost of one isolated slice.
8059 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8060 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8061 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8062 EVT TruncType = LS.Inst->getValueType(0);
8063 EVT LoadedType = LS.getLoadedType();
8064 if (TruncType != LoadedType &&
8065 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8069 /// \brief Account for slicing gain in the current cost.
8070 /// Slicing provide a few gains like removing a shift or a
8071 /// truncate. This method allows to grow the cost of the original
8072 /// load with the gain from this slice.
8073 void addSliceGain(const LoadedSlice &LS) {
8074 // Each slice saves a truncate.
8075 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8076 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8077 LS.Inst->getOperand(0).getValueType()))
8079 // If there is a shift amount, this slice gets rid of it.
8082 // If this slice can merge a cross register bank copy, account for it.
8083 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8084 ++CrossRegisterBanksCopies;
8087 Cost &operator+=(const Cost &RHS) {
8089 Truncates += RHS.Truncates;
8090 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8096 bool operator==(const Cost &RHS) const {
8097 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8098 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8099 ZExts == RHS.ZExts && Shift == RHS.Shift;
8102 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8104 bool operator<(const Cost &RHS) const {
8105 // Assume cross register banks copies are as expensive as loads.
8106 // FIXME: Do we want some more target hooks?
8107 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8108 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8109 // Unless we are optimizing for code size, consider the
8110 // expensive operation first.
8111 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8112 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8113 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8114 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8117 bool operator>(const Cost &RHS) const { return RHS < *this; }
8119 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8121 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8123 // The last instruction that represent the slice. This should be a
8124 // truncate instruction.
8126 // The original load instruction.
8128 // The right shift amount in bits from the original load.
8130 // The DAG from which Origin came from.
8131 // This is used to get some contextual information about legal types, etc.
8134 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8135 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8136 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8138 LoadedSlice(const LoadedSlice &LS)
8139 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8141 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8142 /// \return Result is \p BitWidth and has used bits set to 1 and
8143 /// not used bits set to 0.
8144 APInt getUsedBits() const {
8145 // Reproduce the trunc(lshr) sequence:
8146 // - Start from the truncated value.
8147 // - Zero extend to the desired bit width.
8149 assert(Origin && "No original load to compare against.");
8150 unsigned BitWidth = Origin->getValueSizeInBits(0);
8151 assert(Inst && "This slice is not bound to an instruction");
8152 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8153 "Extracted slice is bigger than the whole type!");
8154 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8155 UsedBits.setAllBits();
8156 UsedBits = UsedBits.zext(BitWidth);
8161 /// \brief Get the size of the slice to be loaded in bytes.
8162 unsigned getLoadedSize() const {
8163 unsigned SliceSize = getUsedBits().countPopulation();
8164 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8165 return SliceSize / 8;
8168 /// \brief Get the type that will be loaded for this slice.
8169 /// Note: This may not be the final type for the slice.
8170 EVT getLoadedType() const {
8171 assert(DAG && "Missing context");
8172 LLVMContext &Ctxt = *DAG->getContext();
8173 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8176 /// \brief Get the alignment of the load used for this slice.
8177 unsigned getAlignment() const {
8178 unsigned Alignment = Origin->getAlignment();
8179 unsigned Offset = getOffsetFromBase();
8181 Alignment = MinAlign(Alignment, Alignment + Offset);
8185 /// \brief Check if this slice can be rewritten with legal operations.
8186 bool isLegal() const {
8187 // An invalid slice is not legal.
8188 if (!Origin || !Inst || !DAG)
8191 // Offsets are for indexed load only, we do not handle that.
8192 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8195 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8197 // Check that the type is legal.
8198 EVT SliceType = getLoadedType();
8199 if (!TLI.isTypeLegal(SliceType))
8202 // Check that the load is legal for this type.
8203 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8206 // Check that the offset can be computed.
8207 // 1. Check its type.
8208 EVT PtrType = Origin->getBasePtr().getValueType();
8209 if (PtrType == MVT::Untyped || PtrType.isExtended())
8212 // 2. Check that it fits in the immediate.
8213 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8216 // 3. Check that the computation is legal.
8217 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8220 // Check that the zext is legal if it needs one.
8221 EVT TruncateType = Inst->getValueType(0);
8222 if (TruncateType != SliceType &&
8223 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8229 /// \brief Get the offset in bytes of this slice in the original chunk of
8231 /// \pre DAG != NULL.
8232 uint64_t getOffsetFromBase() const {
8233 assert(DAG && "Missing context.");
8235 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8236 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8237 uint64_t Offset = Shift / 8;
8238 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8239 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8240 "The size of the original loaded type is not a multiple of a"
8242 // If Offset is bigger than TySizeInBytes, it means we are loading all
8243 // zeros. This should have been optimized before in the process.
8244 assert(TySizeInBytes > Offset &&
8245 "Invalid shift amount for given loaded size");
8247 Offset = TySizeInBytes - Offset - getLoadedSize();
8251 /// \brief Generate the sequence of instructions to load the slice
8252 /// represented by this object and redirect the uses of this slice to
8253 /// this new sequence of instructions.
8254 /// \pre this->Inst && this->Origin are valid Instructions and this
8255 /// object passed the legal check: LoadedSlice::isLegal returned true.
8256 /// \return The last instruction of the sequence used to load the slice.
8257 SDValue loadSlice() const {
8258 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8259 const SDValue &OldBaseAddr = Origin->getBasePtr();
8260 SDValue BaseAddr = OldBaseAddr;
8261 // Get the offset in that chunk of bytes w.r.t. the endianess.
8262 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8263 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8265 // BaseAddr = BaseAddr + Offset.
8266 EVT ArithType = BaseAddr.getValueType();
8267 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8268 DAG->getConstant(Offset, ArithType));
8271 // Create the type of the loaded slice according to its size.
8272 EVT SliceType = getLoadedType();
8274 // Create the load for the slice.
8275 SDValue LastInst = DAG->getLoad(
8276 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8277 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8278 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8279 // If the final type is not the same as the loaded type, this means that
8280 // we have to pad with zero. Create a zero extend for that.
8281 EVT FinalType = Inst->getValueType(0);
8282 if (SliceType != FinalType)
8284 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8288 /// \brief Check if this slice can be merged with an expensive cross register
8289 /// bank copy. E.g.,
8291 /// f = bitcast i32 i to float
8292 bool canMergeExpensiveCrossRegisterBankCopy() const {
8293 if (!Inst || !Inst->hasOneUse())
8295 SDNode *Use = *Inst->use_begin();
8296 if (Use->getOpcode() != ISD::BITCAST)
8298 assert(DAG && "Missing context");
8299 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8300 EVT ResVT = Use->getValueType(0);
8301 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8302 const TargetRegisterClass *ArgRC =
8303 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8304 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8307 // At this point, we know that we perform a cross-register-bank copy.
8308 // Check if it is expensive.
8309 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8310 // Assume bitcasts are cheap, unless both register classes do not
8311 // explicitly share a common sub class.
8312 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8315 // Check if it will be merged with the load.
8316 // 1. Check the alignment constraint.
8317 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8318 ResVT.getTypeForEVT(*DAG->getContext()));
8320 if (RequiredAlignment > getAlignment())
8323 // 2. Check that the load is a legal operation for that type.
8324 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8327 // 3. Check that we do not have a zext in the way.
8328 if (Inst->getValueType(0) != getLoadedType())
8336 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8337 /// \p UsedBits looks like 0..0 1..1 0..0.
8338 static bool areUsedBitsDense(const APInt &UsedBits) {
8339 // If all the bits are one, this is dense!
8340 if (UsedBits.isAllOnesValue())
8343 // Get rid of the unused bits on the right.
8344 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8345 // Get rid of the unused bits on the left.
8346 if (NarrowedUsedBits.countLeadingZeros())
8347 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8348 // Check that the chunk of bits is completely used.
8349 return NarrowedUsedBits.isAllOnesValue();
8352 /// \brief Check whether or not \p First and \p Second are next to each other
8353 /// in memory. This means that there is no hole between the bits loaded
8354 /// by \p First and the bits loaded by \p Second.
8355 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8356 const LoadedSlice &Second) {
8357 assert(First.Origin == Second.Origin && First.Origin &&
8358 "Unable to match different memory origins.");
8359 APInt UsedBits = First.getUsedBits();
8360 assert((UsedBits & Second.getUsedBits()) == 0 &&
8361 "Slices are not supposed to overlap.");
8362 UsedBits |= Second.getUsedBits();
8363 return areUsedBitsDense(UsedBits);
8366 /// \brief Adjust the \p GlobalLSCost according to the target
8367 /// paring capabilities and the layout of the slices.
8368 /// \pre \p GlobalLSCost should account for at least as many loads as
8369 /// there is in the slices in \p LoadedSlices.
8370 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8371 LoadedSlice::Cost &GlobalLSCost) {
8372 unsigned NumberOfSlices = LoadedSlices.size();
8373 // If there is less than 2 elements, no pairing is possible.
8374 if (NumberOfSlices < 2)
8377 // Sort the slices so that elements that are likely to be next to each
8378 // other in memory are next to each other in the list.
8379 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8380 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8381 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8382 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8384 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8385 // First (resp. Second) is the first (resp. Second) potentially candidate
8386 // to be placed in a paired load.
8387 const LoadedSlice *First = NULL;
8388 const LoadedSlice *Second = NULL;
8389 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8390 // Set the beginning of the pair.
8393 Second = &LoadedSlices[CurrSlice];
8395 // If First is NULL, it means we start a new pair.
8396 // Get to the next slice.
8400 EVT LoadedType = First->getLoadedType();
8402 // If the types of the slices are different, we cannot pair them.
8403 if (LoadedType != Second->getLoadedType())
8406 // Check if the target supplies paired loads for this type.
8407 unsigned RequiredAlignment = 0;
8408 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8409 // move to the next pair, this type is hopeless.
8413 // Check if we meet the alignment requirement.
8414 if (RequiredAlignment > First->getAlignment())
8417 // Check that both loads are next to each other in memory.
8418 if (!areSlicesNextToEachOther(*First, *Second))
8421 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8422 --GlobalLSCost.Loads;
8423 // Move to the next pair.
8428 /// \brief Check the profitability of all involved LoadedSlice.
8429 /// Currently, it is considered profitable if there is exactly two
8430 /// involved slices (1) which are (2) next to each other in memory, and
8431 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8433 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8434 /// the elements themselves.
8436 /// FIXME: When the cost model will be mature enough, we can relax
8437 /// constraints (1) and (2).
8438 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8439 const APInt &UsedBits, bool ForCodeSize) {
8440 unsigned NumberOfSlices = LoadedSlices.size();
8441 if (StressLoadSlicing)
8442 return NumberOfSlices > 1;
8445 if (NumberOfSlices != 2)
8449 if (!areUsedBitsDense(UsedBits))
8453 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8454 // The original code has one big load.
8456 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8457 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8458 // Accumulate the cost of all the slices.
8459 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8460 GlobalSlicingCost += SliceCost;
8462 // Account as cost in the original configuration the gain obtained
8463 // with the current slices.
8464 OrigCost.addSliceGain(LS);
8467 // If the target supports paired load, adjust the cost accordingly.
8468 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8469 return OrigCost > GlobalSlicingCost;
8472 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8473 /// operations, split it in the various pieces being extracted.
8475 /// This sort of thing is introduced by SROA.
8476 /// This slicing takes care not to insert overlapping loads.
8477 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8478 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8479 if (Level < AfterLegalizeDAG)
8482 LoadSDNode *LD = cast<LoadSDNode>(N);
8483 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8484 !LD->getValueType(0).isInteger())
8487 // Keep track of already used bits to detect overlapping values.
8488 // In that case, we will just abort the transformation.
8489 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8491 SmallVector<LoadedSlice, 4> LoadedSlices;
8493 // Check if this load is used as several smaller chunks of bits.
8494 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8495 // of computation for each trunc.
8496 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8497 UI != UIEnd; ++UI) {
8498 // Skip the uses of the chain.
8499 if (UI.getUse().getResNo() != 0)
8505 // Check if this is a trunc(lshr).
8506 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8507 isa<ConstantSDNode>(User->getOperand(1))) {
8508 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8509 User = *User->use_begin();
8512 // At this point, User is a Truncate, iff we encountered, trunc or
8514 if (User->getOpcode() != ISD::TRUNCATE)
8517 // The width of the type must be a power of 2 and greater than 8-bits.
8518 // Otherwise the load cannot be represented in LLVM IR.
8519 // Moreover, if we shifted with a non-8-bits multiple, the slice
8520 // will be across several bytes. We do not support that.
8521 unsigned Width = User->getValueSizeInBits(0);
8522 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8525 // Build the slice for this chain of computations.
8526 LoadedSlice LS(User, LD, Shift, &DAG);
8527 APInt CurrentUsedBits = LS.getUsedBits();
8529 // Check if this slice overlaps with another.
8530 if ((CurrentUsedBits & UsedBits) != 0)
8532 // Update the bits used globally.
8533 UsedBits |= CurrentUsedBits;
8535 // Check if the new slice would be legal.
8539 // Record the slice.
8540 LoadedSlices.push_back(LS);
8543 // Abort slicing if it does not seem to be profitable.
8544 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8549 // Rewrite each chain to use an independent load.
8550 // By construction, each chain can be represented by a unique load.
8552 // Prepare the argument for the new token factor for all the slices.
8553 SmallVector<SDValue, 8> ArgChains;
8554 for (SmallVectorImpl<LoadedSlice>::const_iterator
8555 LSIt = LoadedSlices.begin(),
8556 LSItEnd = LoadedSlices.end();
8557 LSIt != LSItEnd; ++LSIt) {
8558 SDValue SliceInst = LSIt->loadSlice();
8559 CombineTo(LSIt->Inst, SliceInst, true);
8560 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8561 SliceInst = SliceInst.getOperand(0);
8562 assert(SliceInst->getOpcode() == ISD::LOAD &&
8563 "It takes more than a zext to get to the loaded slice!!");
8564 ArgChains.push_back(SliceInst.getValue(1));
8567 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8568 &ArgChains[0], ArgChains.size());
8569 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8573 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8574 /// load is having specific bytes cleared out. If so, return the byte size
8575 /// being masked out and the shift amount.
8576 static std::pair<unsigned, unsigned>
8577 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8578 std::pair<unsigned, unsigned> Result(0, 0);
8580 // Check for the structure we're looking for.
8581 if (V->getOpcode() != ISD::AND ||
8582 !isa<ConstantSDNode>(V->getOperand(1)) ||
8583 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8586 // Check the chain and pointer.
8587 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8588 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8590 // The store should be chained directly to the load or be an operand of a
8592 if (LD == Chain.getNode())
8594 else if (Chain->getOpcode() != ISD::TokenFactor)
8595 return Result; // Fail.
8598 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8599 if (Chain->getOperand(i).getNode() == LD) {
8603 if (!isOk) return Result;
8606 // This only handles simple types.
8607 if (V.getValueType() != MVT::i16 &&
8608 V.getValueType() != MVT::i32 &&
8609 V.getValueType() != MVT::i64)
8612 // Check the constant mask. Invert it so that the bits being masked out are
8613 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8614 // follow the sign bit for uniformity.
8615 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8616 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8617 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8618 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8619 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8620 if (NotMaskLZ == 64) return Result; // All zero mask.
8622 // See if we have a continuous run of bits. If so, we have 0*1+0*
8623 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8626 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8627 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8628 NotMaskLZ -= 64-V.getValueSizeInBits();
8630 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8631 switch (MaskedBytes) {
8635 default: return Result; // All one mask, or 5-byte mask.
8638 // Verify that the first bit starts at a multiple of mask so that the access
8639 // is aligned the same as the access width.
8640 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8642 Result.first = MaskedBytes;
8643 Result.second = NotMaskTZ/8;
8648 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8649 /// provides a value as specified by MaskInfo. If so, replace the specified
8650 /// store with a narrower store of truncated IVal.
8652 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8653 SDValue IVal, StoreSDNode *St,
8655 unsigned NumBytes = MaskInfo.first;
8656 unsigned ByteShift = MaskInfo.second;
8657 SelectionDAG &DAG = DC->getDAG();
8659 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8660 // that uses this. If not, this is not a replacement.
8661 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8662 ByteShift*8, (ByteShift+NumBytes)*8);
8663 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8665 // Check that it is legal on the target to do this. It is legal if the new
8666 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8668 MVT VT = MVT::getIntegerVT(NumBytes*8);
8669 if (!DC->isTypeLegal(VT))
8672 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8673 // shifted by ByteShift and truncated down to NumBytes.
8675 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8676 DAG.getConstant(ByteShift*8,
8677 DC->getShiftAmountTy(IVal.getValueType())));
8679 // Figure out the offset for the store and the alignment of the access.
8681 unsigned NewAlign = St->getAlignment();
8683 if (DAG.getTargetLoweringInfo().isLittleEndian())
8684 StOffset = ByteShift;
8686 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8688 SDValue Ptr = St->getBasePtr();
8690 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8691 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8692 NewAlign = MinAlign(NewAlign, StOffset);
8695 // Truncate down to the new size.
8696 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8699 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8700 St->getPointerInfo().getWithOffset(StOffset),
8701 false, false, NewAlign).getNode();
8705 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8706 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8707 /// of the loaded bits, try narrowing the load and store if it would end up
8708 /// being a win for performance or code size.
8709 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8710 StoreSDNode *ST = cast<StoreSDNode>(N);
8711 if (ST->isVolatile())
8714 SDValue Chain = ST->getChain();
8715 SDValue Value = ST->getValue();
8716 SDValue Ptr = ST->getBasePtr();
8717 EVT VT = Value.getValueType();
8719 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8722 unsigned Opc = Value.getOpcode();
8724 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8725 // is a byte mask indicating a consecutive number of bytes, check to see if
8726 // Y is known to provide just those bytes. If so, we try to replace the
8727 // load + replace + store sequence with a single (narrower) store, which makes
8729 if (Opc == ISD::OR) {
8730 std::pair<unsigned, unsigned> MaskedLoad;
8731 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8732 if (MaskedLoad.first)
8733 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8734 Value.getOperand(1), ST,this))
8735 return SDValue(NewST, 0);
8737 // Or is commutative, so try swapping X and Y.
8738 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8739 if (MaskedLoad.first)
8740 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8741 Value.getOperand(0), ST,this))
8742 return SDValue(NewST, 0);
8745 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8746 Value.getOperand(1).getOpcode() != ISD::Constant)
8749 SDValue N0 = Value.getOperand(0);
8750 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8751 Chain == SDValue(N0.getNode(), 1)) {
8752 LoadSDNode *LD = cast<LoadSDNode>(N0);
8753 if (LD->getBasePtr() != Ptr ||
8754 LD->getPointerInfo().getAddrSpace() !=
8755 ST->getPointerInfo().getAddrSpace())
8758 // Find the type to narrow it the load / op / store to.
8759 SDValue N1 = Value.getOperand(1);
8760 unsigned BitWidth = N1.getValueSizeInBits();
8761 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8762 if (Opc == ISD::AND)
8763 Imm ^= APInt::getAllOnesValue(BitWidth);
8764 if (Imm == 0 || Imm.isAllOnesValue())
8766 unsigned ShAmt = Imm.countTrailingZeros();
8767 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8768 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8769 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8770 while (NewBW < BitWidth &&
8771 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8772 TLI.isNarrowingProfitable(VT, NewVT))) {
8773 NewBW = NextPowerOf2(NewBW);
8774 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8776 if (NewBW >= BitWidth)
8779 // If the lsb changed does not start at the type bitwidth boundary,
8780 // start at the previous one.
8782 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8783 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8784 std::min(BitWidth, ShAmt + NewBW));
8785 if ((Imm & Mask) == Imm) {
8786 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8787 if (Opc == ISD::AND)
8788 NewImm ^= APInt::getAllOnesValue(NewBW);
8789 uint64_t PtrOff = ShAmt / 8;
8790 // For big endian targets, we need to adjust the offset to the pointer to
8791 // load the correct bytes.
8792 if (TLI.isBigEndian())
8793 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8795 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8796 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8797 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8800 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8801 Ptr.getValueType(), Ptr,
8802 DAG.getConstant(PtrOff, Ptr.getValueType()));
8803 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8804 LD->getChain(), NewPtr,
8805 LD->getPointerInfo().getWithOffset(PtrOff),
8806 LD->isVolatile(), LD->isNonTemporal(),
8807 LD->isInvariant(), NewAlign,
8809 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8810 DAG.getConstant(NewImm, NewVT));
8811 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8813 ST->getPointerInfo().getWithOffset(PtrOff),
8814 false, false, NewAlign);
8816 AddToWorkList(NewPtr.getNode());
8817 AddToWorkList(NewLD.getNode());
8818 AddToWorkList(NewVal.getNode());
8819 WorkListRemover DeadNodes(*this);
8820 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8829 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8830 /// if the load value isn't used by any other operations, then consider
8831 /// transforming the pair to integer load / store operations if the target
8832 /// deems the transformation profitable.
8833 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8834 StoreSDNode *ST = cast<StoreSDNode>(N);
8835 SDValue Chain = ST->getChain();
8836 SDValue Value = ST->getValue();
8837 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8838 Value.hasOneUse() &&
8839 Chain == SDValue(Value.getNode(), 1)) {
8840 LoadSDNode *LD = cast<LoadSDNode>(Value);
8841 EVT VT = LD->getMemoryVT();
8842 if (!VT.isFloatingPoint() ||
8843 VT != ST->getMemoryVT() ||
8844 LD->isNonTemporal() ||
8845 ST->isNonTemporal() ||
8846 LD->getPointerInfo().getAddrSpace() != 0 ||
8847 ST->getPointerInfo().getAddrSpace() != 0)
8850 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8851 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8852 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8853 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8854 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8857 unsigned LDAlign = LD->getAlignment();
8858 unsigned STAlign = ST->getAlignment();
8859 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8860 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8861 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8864 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8865 LD->getChain(), LD->getBasePtr(),
8866 LD->getPointerInfo(),
8867 false, false, false, LDAlign);
8869 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8870 NewLD, ST->getBasePtr(),
8871 ST->getPointerInfo(),
8872 false, false, STAlign);
8874 AddToWorkList(NewLD.getNode());
8875 AddToWorkList(NewST.getNode());
8876 WorkListRemover DeadNodes(*this);
8877 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8885 /// Helper struct to parse and store a memory address as base + index + offset.
8886 /// We ignore sign extensions when it is safe to do so.
8887 /// The following two expressions are not equivalent. To differentiate we need
8888 /// to store whether there was a sign extension involved in the index
8890 /// (load (i64 add (i64 copyfromreg %c)
8891 /// (i64 signextend (add (i8 load %index)
8895 /// (load (i64 add (i64 copyfromreg %c)
8896 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8898 struct BaseIndexOffset {
8902 bool IsIndexSignExt;
8904 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8906 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8907 bool IsIndexSignExt) :
8908 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8910 bool equalBaseIndex(const BaseIndexOffset &Other) {
8911 return Other.Base == Base && Other.Index == Index &&
8912 Other.IsIndexSignExt == IsIndexSignExt;
8915 /// Parses tree in Ptr for base, index, offset addresses.
8916 static BaseIndexOffset match(SDValue Ptr) {
8917 bool IsIndexSignExt = false;
8919 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8920 // instruction, then it could be just the BASE or everything else we don't
8921 // know how to handle. Just use Ptr as BASE and give up.
8922 if (Ptr->getOpcode() != ISD::ADD)
8923 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8925 // We know that we have at least an ADD instruction. Try to pattern match
8926 // the simple case of BASE + OFFSET.
8927 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8928 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8929 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8933 // Inside a loop the current BASE pointer is calculated using an ADD and a
8934 // MUL instruction. In this case Ptr is the actual BASE pointer.
8935 // (i64 add (i64 %array_ptr)
8936 // (i64 mul (i64 %induction_var)
8937 // (i64 %element_size)))
8938 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8939 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8941 // Look at Base + Index + Offset cases.
8942 SDValue Base = Ptr->getOperand(0);
8943 SDValue IndexOffset = Ptr->getOperand(1);
8945 // Skip signextends.
8946 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8947 IndexOffset = IndexOffset->getOperand(0);
8948 IsIndexSignExt = true;
8951 // Either the case of Base + Index (no offset) or something else.
8952 if (IndexOffset->getOpcode() != ISD::ADD)
8953 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8955 // Now we have the case of Base + Index + offset.
8956 SDValue Index = IndexOffset->getOperand(0);
8957 SDValue Offset = IndexOffset->getOperand(1);
8959 if (!isa<ConstantSDNode>(Offset))
8960 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8962 // Ignore signextends.
8963 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8964 Index = Index->getOperand(0);
8965 IsIndexSignExt = true;
8966 } else IsIndexSignExt = false;
8968 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8969 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8973 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8974 /// is located in a sequence of memory operations connected by a chain.
8976 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8977 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8978 // Ptr to the mem node.
8979 LSBaseSDNode *MemNode;
8980 // Offset from the base ptr.
8981 int64_t OffsetFromBase;
8982 // What is the sequence number of this mem node.
8983 // Lowest mem operand in the DAG starts at zero.
8984 unsigned SequenceNum;
8987 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8988 EVT MemVT = St->getMemoryVT();
8989 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8990 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8991 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8993 // Don't merge vectors into wider inputs.
8994 if (MemVT.isVector() || !MemVT.isSimple())
8997 // Perform an early exit check. Do not bother looking at stored values that
8998 // are not constants or loads.
8999 SDValue StoredVal = St->getValue();
9000 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9001 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9005 // Only look at ends of store sequences.
9006 SDValue Chain = SDValue(St, 1);
9007 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9010 // This holds the base pointer, index, and the offset in bytes from the base
9012 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9014 // We must have a base and an offset.
9015 if (!BasePtr.Base.getNode())
9018 // Do not handle stores to undef base pointers.
9019 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9022 // Save the LoadSDNodes that we find in the chain.
9023 // We need to make sure that these nodes do not interfere with
9024 // any of the store nodes.
9025 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9027 // Save the StoreSDNodes that we find in the chain.
9028 SmallVector<MemOpLink, 8> StoreNodes;
9030 // Walk up the chain and look for nodes with offsets from the same
9031 // base pointer. Stop when reaching an instruction with a different kind
9032 // or instruction which has a different base pointer.
9034 StoreSDNode *Index = St;
9036 // If the chain has more than one use, then we can't reorder the mem ops.
9037 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9040 // Find the base pointer and offset for this memory node.
9041 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9043 // Check that the base pointer is the same as the original one.
9044 if (!Ptr.equalBaseIndex(BasePtr))
9047 // Check that the alignment is the same.
9048 if (Index->getAlignment() != St->getAlignment())
9051 // The memory operands must not be volatile.
9052 if (Index->isVolatile() || Index->isIndexed())
9056 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9057 if (St->isTruncatingStore())
9060 // The stored memory type must be the same.
9061 if (Index->getMemoryVT() != MemVT)
9064 // We do not allow unaligned stores because we want to prevent overriding
9066 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9069 // We found a potential memory operand to merge.
9070 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9072 // Find the next memory operand in the chain. If the next operand in the
9073 // chain is a store then move up and continue the scan with the next
9074 // memory operand. If the next operand is a load save it and use alias
9075 // information to check if it interferes with anything.
9076 SDNode *NextInChain = Index->getChain().getNode();
9078 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9079 // We found a store node. Use it for the next iteration.
9082 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9083 if (Ldn->isVolatile()) {
9088 // Save the load node for later. Continue the scan.
9089 AliasLoadNodes.push_back(Ldn);
9090 NextInChain = Ldn->getChain().getNode();
9099 // Check if there is anything to merge.
9100 if (StoreNodes.size() < 2)
9103 // Sort the memory operands according to their distance from the base pointer.
9104 std::sort(StoreNodes.begin(), StoreNodes.end(),
9105 [](MemOpLink LHS, MemOpLink RHS) {
9106 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9107 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9108 LHS.SequenceNum > RHS.SequenceNum);
9111 // Scan the memory operations on the chain and find the first non-consecutive
9112 // store memory address.
9113 unsigned LastConsecutiveStore = 0;
9114 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9115 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9117 // Check that the addresses are consecutive starting from the second
9118 // element in the list of stores.
9120 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9121 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9126 // Check if this store interferes with any of the loads that we found.
9127 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9128 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9132 // We found a load that alias with this store. Stop the sequence.
9136 // Mark this node as useful.
9137 LastConsecutiveStore = i;
9140 // The node with the lowest store address.
9141 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9143 // Store the constants into memory as one consecutive store.
9145 unsigned LastLegalType = 0;
9146 unsigned LastLegalVectorType = 0;
9147 bool NonZero = false;
9148 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9149 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9150 SDValue StoredVal = St->getValue();
9152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9153 NonZero |= !C->isNullValue();
9154 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9155 NonZero |= !C->getConstantFPValue()->isNullValue();
9161 // Find a legal type for the constant store.
9162 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9163 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9164 if (TLI.isTypeLegal(StoreTy))
9165 LastLegalType = i+1;
9166 // Or check whether a truncstore is legal.
9167 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9168 TargetLowering::TypePromoteInteger) {
9169 EVT LegalizedStoredValueTy =
9170 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9171 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9172 LastLegalType = i+1;
9175 // Find a legal type for the vector store.
9176 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9177 if (TLI.isTypeLegal(Ty))
9178 LastLegalVectorType = i + 1;
9181 // We only use vectors if the constant is known to be zero and the
9182 // function is not marked with the noimplicitfloat attribute.
9183 if (NonZero || NoVectors)
9184 LastLegalVectorType = 0;
9186 // Check if we found a legal integer type to store.
9187 if (LastLegalType == 0 && LastLegalVectorType == 0)
9190 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9191 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9193 // Make sure we have something to merge.
9197 unsigned EarliestNodeUsed = 0;
9198 for (unsigned i=0; i < NumElem; ++i) {
9199 // Find a chain for the new wide-store operand. Notice that some
9200 // of the store nodes that we found may not be selected for inclusion
9201 // in the wide store. The chain we use needs to be the chain of the
9202 // earliest store node which is *used* and replaced by the wide store.
9203 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9204 EarliestNodeUsed = i;
9207 // The earliest Node in the DAG.
9208 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9209 SDLoc DL(StoreNodes[0].MemNode);
9213 // Find a legal type for the vector store.
9214 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9215 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9216 StoredVal = DAG.getConstant(0, Ty);
9218 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9219 APInt StoreInt(StoreBW, 0);
9221 // Construct a single integer constant which is made of the smaller
9223 bool IsLE = TLI.isLittleEndian();
9224 for (unsigned i = 0; i < NumElem ; ++i) {
9225 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9226 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9227 SDValue Val = St->getValue();
9228 StoreInt<<=ElementSizeBytes*8;
9229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9230 StoreInt|=C->getAPIntValue().zext(StoreBW);
9231 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9232 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9234 assert(false && "Invalid constant element type");
9238 // Create the new Load and Store operations.
9239 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9240 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9243 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9244 FirstInChain->getBasePtr(),
9245 FirstInChain->getPointerInfo(),
9247 FirstInChain->getAlignment());
9249 // Replace the first store with the new store
9250 CombineTo(EarliestOp, NewStore);
9251 // Erase all other stores.
9252 for (unsigned i = 0; i < NumElem ; ++i) {
9253 if (StoreNodes[i].MemNode == EarliestOp)
9255 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9256 // ReplaceAllUsesWith will replace all uses that existed when it was
9257 // called, but graph optimizations may cause new ones to appear. For
9258 // example, the case in pr14333 looks like
9260 // St's chain -> St -> another store -> X
9262 // And the only difference from St to the other store is the chain.
9263 // When we change it's chain to be St's chain they become identical,
9264 // get CSEed and the net result is that X is now a use of St.
9265 // Since we know that St is redundant, just iterate.
9266 while (!St->use_empty())
9267 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9268 removeFromWorkList(St);
9275 // Below we handle the case of multiple consecutive stores that
9276 // come from multiple consecutive loads. We merge them into a single
9277 // wide load and a single wide store.
9279 // Look for load nodes which are used by the stored values.
9280 SmallVector<MemOpLink, 8> LoadNodes;
9282 // Find acceptable loads. Loads need to have the same chain (token factor),
9283 // must not be zext, volatile, indexed, and they must be consecutive.
9284 BaseIndexOffset LdBasePtr;
9285 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9286 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9287 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9290 // Loads must only have one use.
9291 if (!Ld->hasNUsesOfValue(1, 0))
9294 // Check that the alignment is the same as the stores.
9295 if (Ld->getAlignment() != St->getAlignment())
9298 // The memory operands must not be volatile.
9299 if (Ld->isVolatile() || Ld->isIndexed())
9302 // We do not accept ext loads.
9303 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9306 // The stored memory type must be the same.
9307 if (Ld->getMemoryVT() != MemVT)
9310 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9311 // If this is not the first ptr that we check.
9312 if (LdBasePtr.Base.getNode()) {
9313 // The base ptr must be the same.
9314 if (!LdPtr.equalBaseIndex(LdBasePtr))
9317 // Check that all other base pointers are the same as this one.
9321 // We found a potential memory operand to merge.
9322 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9325 if (LoadNodes.size() < 2)
9328 // Scan the memory operations on the chain and find the first non-consecutive
9329 // load memory address. These variables hold the index in the store node
9331 unsigned LastConsecutiveLoad = 0;
9332 // This variable refers to the size and not index in the array.
9333 unsigned LastLegalVectorType = 0;
9334 unsigned LastLegalIntegerType = 0;
9335 StartAddress = LoadNodes[0].OffsetFromBase;
9336 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9337 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9338 // All loads much share the same chain.
9339 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9342 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9343 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9345 LastConsecutiveLoad = i;
9347 // Find a legal type for the vector store.
9348 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9349 if (TLI.isTypeLegal(StoreTy))
9350 LastLegalVectorType = i + 1;
9352 // Find a legal type for the integer store.
9353 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9354 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9355 if (TLI.isTypeLegal(StoreTy))
9356 LastLegalIntegerType = i + 1;
9357 // Or check whether a truncstore and extload is legal.
9358 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9359 TargetLowering::TypePromoteInteger) {
9360 EVT LegalizedStoredValueTy =
9361 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9362 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9363 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9364 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9365 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9366 LastLegalIntegerType = i+1;
9370 // Only use vector types if the vector type is larger than the integer type.
9371 // If they are the same, use integers.
9372 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9373 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9375 // We add +1 here because the LastXXX variables refer to location while
9376 // the NumElem refers to array/index size.
9377 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9378 NumElem = std::min(LastLegalType, NumElem);
9383 // The earliest Node in the DAG.
9384 unsigned EarliestNodeUsed = 0;
9385 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9386 for (unsigned i=1; i<NumElem; ++i) {
9387 // Find a chain for the new wide-store operand. Notice that some
9388 // of the store nodes that we found may not be selected for inclusion
9389 // in the wide store. The chain we use needs to be the chain of the
9390 // earliest store node which is *used* and replaced by the wide store.
9391 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9392 EarliestNodeUsed = i;
9395 // Find if it is better to use vectors or integers to load and store
9399 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9401 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9402 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9405 SDLoc LoadDL(LoadNodes[0].MemNode);
9406 SDLoc StoreDL(StoreNodes[0].MemNode);
9408 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9409 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9410 FirstLoad->getChain(),
9411 FirstLoad->getBasePtr(),
9412 FirstLoad->getPointerInfo(),
9413 false, false, false,
9414 FirstLoad->getAlignment());
9416 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9417 FirstInChain->getBasePtr(),
9418 FirstInChain->getPointerInfo(), false, false,
9419 FirstInChain->getAlignment());
9421 // Replace one of the loads with the new load.
9422 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9423 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9424 SDValue(NewLoad.getNode(), 1));
9426 // Remove the rest of the load chains.
9427 for (unsigned i = 1; i < NumElem ; ++i) {
9428 // Replace all chain users of the old load nodes with the chain of the new
9430 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9431 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9434 // Replace the first store with the new store.
9435 CombineTo(EarliestOp, NewStore);
9436 // Erase all other stores.
9437 for (unsigned i = 0; i < NumElem ; ++i) {
9438 // Remove all Store nodes.
9439 if (StoreNodes[i].MemNode == EarliestOp)
9441 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9442 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9443 removeFromWorkList(St);
9450 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9451 StoreSDNode *ST = cast<StoreSDNode>(N);
9452 SDValue Chain = ST->getChain();
9453 SDValue Value = ST->getValue();
9454 SDValue Ptr = ST->getBasePtr();
9456 // If this is a store of a bit convert, store the input value if the
9457 // resultant store does not need a higher alignment than the original.
9458 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9459 ST->isUnindexed()) {
9460 unsigned OrigAlign = ST->getAlignment();
9461 EVT SVT = Value.getOperand(0).getValueType();
9462 unsigned Align = TLI.getDataLayout()->
9463 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9464 if (Align <= OrigAlign &&
9465 ((!LegalOperations && !ST->isVolatile()) ||
9466 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9467 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9468 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9469 ST->isNonTemporal(), OrigAlign,
9473 // Turn 'store undef, Ptr' -> nothing.
9474 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9477 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9478 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9479 // NOTE: If the original store is volatile, this transform must not increase
9480 // the number of stores. For example, on x86-32 an f64 can be stored in one
9481 // processor operation but an i64 (which is not legal) requires two. So the
9482 // transform should not be done in this case.
9483 if (Value.getOpcode() != ISD::TargetConstantFP) {
9485 switch (CFP->getSimpleValueType(0).SimpleTy) {
9486 default: llvm_unreachable("Unknown FP type");
9487 case MVT::f16: // We don't do this for these yet.
9493 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9494 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9495 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9496 bitcastToAPInt().getZExtValue(), MVT::i32);
9497 return DAG.getStore(Chain, SDLoc(N), Tmp,
9498 Ptr, ST->getMemOperand());
9502 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9503 !ST->isVolatile()) ||
9504 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9505 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9506 getZExtValue(), MVT::i64);
9507 return DAG.getStore(Chain, SDLoc(N), Tmp,
9508 Ptr, ST->getMemOperand());
9511 if (!ST->isVolatile() &&
9512 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9513 // Many FP stores are not made apparent until after legalize, e.g. for
9514 // argument passing. Since this is so common, custom legalize the
9515 // 64-bit integer store into two 32-bit stores.
9516 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9517 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9518 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9519 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9521 unsigned Alignment = ST->getAlignment();
9522 bool isVolatile = ST->isVolatile();
9523 bool isNonTemporal = ST->isNonTemporal();
9524 const MDNode *TBAAInfo = ST->getTBAAInfo();
9526 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9527 Ptr, ST->getPointerInfo(),
9528 isVolatile, isNonTemporal,
9529 ST->getAlignment(), TBAAInfo);
9530 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9531 DAG.getConstant(4, Ptr.getValueType()));
9532 Alignment = MinAlign(Alignment, 4U);
9533 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9534 Ptr, ST->getPointerInfo().getWithOffset(4),
9535 isVolatile, isNonTemporal,
9536 Alignment, TBAAInfo);
9537 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9546 // Try to infer better alignment information than the store already has.
9547 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9548 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9549 if (Align > ST->getAlignment())
9550 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9551 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9552 ST->isVolatile(), ST->isNonTemporal(), Align,
9557 // Try transforming a pair floating point load / store ops to integer
9558 // load / store ops.
9559 SDValue NewST = TransformFPLoadStorePair(N);
9560 if (NewST.getNode())
9563 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9564 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9566 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9567 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9570 if (UseAA && ST->isUnindexed()) {
9571 // Walk up chain skipping non-aliasing memory nodes.
9572 SDValue BetterChain = FindBetterChain(N, Chain);
9574 // If there is a better chain.
9575 if (Chain != BetterChain) {
9578 // Replace the chain to avoid dependency.
9579 if (ST->isTruncatingStore()) {
9580 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9581 ST->getMemoryVT(), ST->getMemOperand());
9583 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9584 ST->getMemOperand());
9587 // Create token to keep both nodes around.
9588 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9589 MVT::Other, Chain, ReplStore);
9591 // Make sure the new and old chains are cleaned up.
9592 AddToWorkList(Token.getNode());
9594 // Don't add users to work list.
9595 return CombineTo(N, Token, false);
9599 // Try transforming N to an indexed store.
9600 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9601 return SDValue(N, 0);
9603 // FIXME: is there such a thing as a truncating indexed store?
9604 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9605 Value.getValueType().isInteger()) {
9606 // See if we can simplify the input to this truncstore with knowledge that
9607 // only the low bits are being used. For example:
9608 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9610 GetDemandedBits(Value,
9611 APInt::getLowBitsSet(
9612 Value.getValueType().getScalarType().getSizeInBits(),
9613 ST->getMemoryVT().getScalarType().getSizeInBits()));
9614 AddToWorkList(Value.getNode());
9615 if (Shorter.getNode())
9616 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9617 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9619 // Otherwise, see if we can simplify the operation with
9620 // SimplifyDemandedBits, which only works if the value has a single use.
9621 if (SimplifyDemandedBits(Value,
9622 APInt::getLowBitsSet(
9623 Value.getValueType().getScalarType().getSizeInBits(),
9624 ST->getMemoryVT().getScalarType().getSizeInBits())))
9625 return SDValue(N, 0);
9628 // If this is a load followed by a store to the same location, then the store
9630 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9631 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9632 ST->isUnindexed() && !ST->isVolatile() &&
9633 // There can't be any side effects between the load and store, such as
9635 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9636 // The store is dead, remove it.
9641 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9642 // truncating store. We can do this even if this is already a truncstore.
9643 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9644 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9645 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9646 ST->getMemoryVT())) {
9647 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9648 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9651 // Only perform this optimization before the types are legal, because we
9652 // don't want to perform this optimization on every DAGCombine invocation.
9654 bool EverChanged = false;
9657 // There can be multiple store sequences on the same chain.
9658 // Keep trying to merge store sequences until we are unable to do so
9659 // or until we merge the last store on the chain.
9660 bool Changed = MergeConsecutiveStores(ST);
9661 EverChanged |= Changed;
9662 if (!Changed) break;
9663 } while (ST->getOpcode() != ISD::DELETED_NODE);
9666 return SDValue(N, 0);
9669 return ReduceLoadOpStoreWidth(N);
9672 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9673 SDValue InVec = N->getOperand(0);
9674 SDValue InVal = N->getOperand(1);
9675 SDValue EltNo = N->getOperand(2);
9678 // If the inserted element is an UNDEF, just use the input vector.
9679 if (InVal.getOpcode() == ISD::UNDEF)
9682 EVT VT = InVec.getValueType();
9684 // If we can't generate a legal BUILD_VECTOR, exit
9685 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9688 // Check that we know which element is being inserted
9689 if (!isa<ConstantSDNode>(EltNo))
9691 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9693 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9694 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9696 SmallVector<SDValue, 8> Ops;
9697 // Do not combine these two vectors if the output vector will not replace
9698 // the input vector.
9699 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9700 Ops.append(InVec.getNode()->op_begin(),
9701 InVec.getNode()->op_end());
9702 } else if (InVec.getOpcode() == ISD::UNDEF) {
9703 unsigned NElts = VT.getVectorNumElements();
9704 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9709 // Insert the element
9710 if (Elt < Ops.size()) {
9711 // All the operands of BUILD_VECTOR must have the same type;
9712 // we enforce that here.
9713 EVT OpVT = Ops[0].getValueType();
9714 if (InVal.getValueType() != OpVT)
9715 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9716 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9717 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9721 // Return the new vector
9722 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9723 VT, &Ops[0], Ops.size());
9726 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9727 // (vextract (scalar_to_vector val, 0) -> val
9728 SDValue InVec = N->getOperand(0);
9729 EVT VT = InVec.getValueType();
9730 EVT NVT = N->getValueType(0);
9732 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9733 // Check if the result type doesn't match the inserted element type. A
9734 // SCALAR_TO_VECTOR may truncate the inserted element and the
9735 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9736 SDValue InOp = InVec.getOperand(0);
9737 if (InOp.getValueType() != NVT) {
9738 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9739 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9744 SDValue EltNo = N->getOperand(1);
9745 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9747 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9748 // We only perform this optimization before the op legalization phase because
9749 // we may introduce new vector instructions which are not backed by TD
9750 // patterns. For example on AVX, extracting elements from a wide vector
9751 // without using extract_subvector. However, if we can find an underlying
9752 // scalar value, then we can always use that.
9753 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9755 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9756 int NumElem = VT.getVectorNumElements();
9757 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9758 // Find the new index to extract from.
9759 int OrigElt = SVOp->getMaskElt(Elt);
9761 // Extracting an undef index is undef.
9763 return DAG.getUNDEF(NVT);
9765 // Select the right vector half to extract from.
9767 if (OrigElt < NumElem) {
9768 SVInVec = InVec->getOperand(0);
9770 SVInVec = InVec->getOperand(1);
9774 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9775 SDValue InOp = SVInVec.getOperand(OrigElt);
9776 if (InOp.getValueType() != NVT) {
9777 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9778 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9784 // FIXME: We should handle recursing on other vector shuffles and
9785 // scalar_to_vector here as well.
9787 if (!LegalOperations) {
9788 EVT IndexTy = TLI.getVectorIdxTy();
9789 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9790 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9794 // Perform only after legalization to ensure build_vector / vector_shuffle
9795 // optimizations have already been done.
9796 if (!LegalOperations) return SDValue();
9798 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9799 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9800 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9803 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9804 bool NewLoad = false;
9805 bool BCNumEltsChanged = false;
9806 EVT ExtVT = VT.getVectorElementType();
9809 // If the result of load has to be truncated, then it's not necessarily
9811 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9814 if (InVec.getOpcode() == ISD::BITCAST) {
9815 // Don't duplicate a load with other uses.
9816 if (!InVec.hasOneUse())
9819 EVT BCVT = InVec.getOperand(0).getValueType();
9820 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9822 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9823 BCNumEltsChanged = true;
9824 InVec = InVec.getOperand(0);
9825 ExtVT = BCVT.getVectorElementType();
9829 LoadSDNode *LN0 = NULL;
9830 const ShuffleVectorSDNode *SVN = NULL;
9831 if (ISD::isNormalLoad(InVec.getNode())) {
9832 LN0 = cast<LoadSDNode>(InVec);
9833 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9834 InVec.getOperand(0).getValueType() == ExtVT &&
9835 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9836 // Don't duplicate a load with other uses.
9837 if (!InVec.hasOneUse())
9840 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9841 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9842 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9844 // (load $addr+1*size)
9846 // Don't duplicate a load with other uses.
9847 if (!InVec.hasOneUse())
9850 // If the bit convert changed the number of elements, it is unsafe
9851 // to examine the mask.
9852 if (BCNumEltsChanged)
9855 // Select the input vector, guarding against out of range extract vector.
9856 unsigned NumElems = VT.getVectorNumElements();
9857 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9858 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9860 if (InVec.getOpcode() == ISD::BITCAST) {
9861 // Don't duplicate a load with other uses.
9862 if (!InVec.hasOneUse())
9865 InVec = InVec.getOperand(0);
9867 if (ISD::isNormalLoad(InVec.getNode())) {
9868 LN0 = cast<LoadSDNode>(InVec);
9869 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9873 // Make sure we found a non-volatile load and the extractelement is
9875 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9878 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9880 return DAG.getUNDEF(LVT);
9882 unsigned Align = LN0->getAlignment();
9884 // Check the resultant load doesn't need a higher alignment than the
9888 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9890 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9896 SDValue NewPtr = LN0->getBasePtr();
9897 unsigned PtrOff = 0;
9900 PtrOff = LVT.getSizeInBits() * Elt / 8;
9901 EVT PtrType = NewPtr.getValueType();
9902 if (TLI.isBigEndian())
9903 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9904 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9905 DAG.getConstant(PtrOff, PtrType));
9908 // The replacement we need to do here is a little tricky: we need to
9909 // replace an extractelement of a load with a load.
9910 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9911 // Note that this replacement assumes that the extractvalue is the only
9912 // use of the load; that's okay because we don't want to perform this
9913 // transformation in other cases anyway.
9916 if (NVT.bitsGT(LVT)) {
9917 // If the result type of vextract is wider than the load, then issue an
9918 // extending load instead.
9919 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9920 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9921 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9922 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9923 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9924 Align, LN0->getTBAAInfo());
9925 Chain = Load.getValue(1);
9927 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9928 LN0->getPointerInfo().getWithOffset(PtrOff),
9929 LN0->isVolatile(), LN0->isNonTemporal(),
9930 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9931 Chain = Load.getValue(1);
9932 if (NVT.bitsLT(LVT))
9933 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9935 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9937 WorkListRemover DeadNodes(*this);
9938 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9939 SDValue To[] = { Load, Chain };
9940 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9941 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9942 // worklist explicitly as well.
9943 AddToWorkList(Load.getNode());
9944 AddUsersToWorkList(Load.getNode()); // Add users too
9945 // Make sure to revisit this node to clean it up; it will usually be dead.
9947 return SDValue(N, 0);
9953 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9954 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9955 // We perform this optimization post type-legalization because
9956 // the type-legalizer often scalarizes integer-promoted vectors.
9957 // Performing this optimization before may create bit-casts which
9958 // will be type-legalized to complex code sequences.
9959 // We perform this optimization only before the operation legalizer because we
9960 // may introduce illegal operations.
9961 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9964 unsigned NumInScalars = N->getNumOperands();
9966 EVT VT = N->getValueType(0);
9968 // Check to see if this is a BUILD_VECTOR of a bunch of values
9969 // which come from any_extend or zero_extend nodes. If so, we can create
9970 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9971 // optimizations. We do not handle sign-extend because we can't fill the sign
9973 EVT SourceType = MVT::Other;
9974 bool AllAnyExt = true;
9976 for (unsigned i = 0; i != NumInScalars; ++i) {
9977 SDValue In = N->getOperand(i);
9978 // Ignore undef inputs.
9979 if (In.getOpcode() == ISD::UNDEF) continue;
9981 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9982 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9984 // Abort if the element is not an extension.
9985 if (!ZeroExt && !AnyExt) {
9986 SourceType = MVT::Other;
9990 // The input is a ZeroExt or AnyExt. Check the original type.
9991 EVT InTy = In.getOperand(0).getValueType();
9993 // Check that all of the widened source types are the same.
9994 if (SourceType == MVT::Other)
9997 else if (InTy != SourceType) {
9998 // Multiple income types. Abort.
9999 SourceType = MVT::Other;
10003 // Check if all of the extends are ANY_EXTENDs.
10004 AllAnyExt &= AnyExt;
10007 // In order to have valid types, all of the inputs must be extended from the
10008 // same source type and all of the inputs must be any or zero extend.
10009 // Scalar sizes must be a power of two.
10010 EVT OutScalarTy = VT.getScalarType();
10011 bool ValidTypes = SourceType != MVT::Other &&
10012 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10013 isPowerOf2_32(SourceType.getSizeInBits());
10015 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10016 // turn into a single shuffle instruction.
10020 bool isLE = TLI.isLittleEndian();
10021 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10022 assert(ElemRatio > 1 && "Invalid element size ratio");
10023 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10024 DAG.getConstant(0, SourceType);
10026 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10027 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10029 // Populate the new build_vector
10030 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10031 SDValue Cast = N->getOperand(i);
10032 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10033 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10034 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10036 if (Cast.getOpcode() == ISD::UNDEF)
10037 In = DAG.getUNDEF(SourceType);
10039 In = Cast->getOperand(0);
10040 unsigned Index = isLE ? (i * ElemRatio) :
10041 (i * ElemRatio + (ElemRatio - 1));
10043 assert(Index < Ops.size() && "Invalid index");
10047 // The type of the new BUILD_VECTOR node.
10048 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10049 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10050 "Invalid vector size");
10051 // Check if the new vector type is legal.
10052 if (!isTypeLegal(VecVT)) return SDValue();
10054 // Make the new BUILD_VECTOR.
10055 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10057 // The new BUILD_VECTOR node has the potential to be further optimized.
10058 AddToWorkList(BV.getNode());
10059 // Bitcast to the desired type.
10060 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10063 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10064 EVT VT = N->getValueType(0);
10066 unsigned NumInScalars = N->getNumOperands();
10069 EVT SrcVT = MVT::Other;
10070 unsigned Opcode = ISD::DELETED_NODE;
10071 unsigned NumDefs = 0;
10073 for (unsigned i = 0; i != NumInScalars; ++i) {
10074 SDValue In = N->getOperand(i);
10075 unsigned Opc = In.getOpcode();
10077 if (Opc == ISD::UNDEF)
10080 // If all scalar values are floats and converted from integers.
10081 if (Opcode == ISD::DELETED_NODE &&
10082 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10089 EVT InVT = In.getOperand(0).getValueType();
10091 // If all scalar values are typed differently, bail out. It's chosen to
10092 // simplify BUILD_VECTOR of integer types.
10093 if (SrcVT == MVT::Other)
10100 // If the vector has just one element defined, it's not worth to fold it into
10101 // a vectorized one.
10105 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10106 && "Should only handle conversion from integer to float.");
10107 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10109 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10111 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10114 SmallVector<SDValue, 8> Opnds;
10115 for (unsigned i = 0; i != NumInScalars; ++i) {
10116 SDValue In = N->getOperand(i);
10118 if (In.getOpcode() == ISD::UNDEF)
10119 Opnds.push_back(DAG.getUNDEF(SrcVT));
10121 Opnds.push_back(In.getOperand(0));
10123 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10124 &Opnds[0], Opnds.size());
10125 AddToWorkList(BV.getNode());
10127 return DAG.getNode(Opcode, dl, VT, BV);
10130 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10131 unsigned NumInScalars = N->getNumOperands();
10133 EVT VT = N->getValueType(0);
10135 // A vector built entirely of undefs is undef.
10136 if (ISD::allOperandsUndef(N))
10137 return DAG.getUNDEF(VT);
10139 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10143 V = reduceBuildVecConvertToConvertBuildVec(N);
10147 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10148 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10149 // at most two distinct vectors, turn this into a shuffle node.
10151 // May only combine to shuffle after legalize if shuffle is legal.
10152 if (LegalOperations &&
10153 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10156 SDValue VecIn1, VecIn2;
10157 for (unsigned i = 0; i != NumInScalars; ++i) {
10158 // Ignore undef inputs.
10159 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10161 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10162 // constant index, bail out.
10163 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10164 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10165 VecIn1 = VecIn2 = SDValue(0, 0);
10169 // We allow up to two distinct input vectors.
10170 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10171 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10174 if (VecIn1.getNode() == 0) {
10175 VecIn1 = ExtractedFromVec;
10176 } else if (VecIn2.getNode() == 0) {
10177 VecIn2 = ExtractedFromVec;
10179 // Too many inputs.
10180 VecIn1 = VecIn2 = SDValue(0, 0);
10185 // If everything is good, we can make a shuffle operation.
10186 if (VecIn1.getNode()) {
10187 SmallVector<int, 8> Mask;
10188 for (unsigned i = 0; i != NumInScalars; ++i) {
10189 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10190 Mask.push_back(-1);
10194 // If extracting from the first vector, just use the index directly.
10195 SDValue Extract = N->getOperand(i);
10196 SDValue ExtVal = Extract.getOperand(1);
10197 if (Extract.getOperand(0) == VecIn1) {
10198 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10199 if (ExtIndex > VT.getVectorNumElements())
10202 Mask.push_back(ExtIndex);
10206 // Otherwise, use InIdx + VecSize
10207 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10208 Mask.push_back(Idx+NumInScalars);
10211 // We can't generate a shuffle node with mismatched input and output types.
10212 // Attempt to transform a single input vector to the correct type.
10213 if ((VT != VecIn1.getValueType())) {
10214 // We don't support shuffeling between TWO values of different types.
10215 if (VecIn2.getNode() != 0)
10218 // We only support widening of vectors which are half the size of the
10219 // output registers. For example XMM->YMM widening on X86 with AVX.
10220 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10223 // If the input vector type has a different base type to the output
10224 // vector type, bail out.
10225 if (VecIn1.getValueType().getVectorElementType() !=
10226 VT.getVectorElementType())
10229 // Widen the input vector by adding undef values.
10230 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10231 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10234 // If VecIn2 is unused then change it to undef.
10235 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10237 // Check that we were able to transform all incoming values to the same
10239 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10240 VecIn1.getValueType() != VT)
10243 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10244 if (!isTypeLegal(VT))
10247 // Return the new VECTOR_SHUFFLE node.
10251 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10257 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10258 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10259 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10260 // inputs come from at most two distinct vectors, turn this into a shuffle
10263 // If we only have one input vector, we don't need to do any concatenation.
10264 if (N->getNumOperands() == 1)
10265 return N->getOperand(0);
10267 // Check if all of the operands are undefs.
10268 EVT VT = N->getValueType(0);
10269 if (ISD::allOperandsUndef(N))
10270 return DAG.getUNDEF(VT);
10272 // Optimize concat_vectors where one of the vectors is undef.
10273 if (N->getNumOperands() == 2 &&
10274 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10275 SDValue In = N->getOperand(0);
10276 assert(In.getValueType().isVector() && "Must concat vectors");
10278 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10279 if (In->getOpcode() == ISD::BITCAST &&
10280 !In->getOperand(0)->getValueType(0).isVector()) {
10281 SDValue Scalar = In->getOperand(0);
10282 EVT SclTy = Scalar->getValueType(0);
10284 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10287 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10288 VT.getSizeInBits() / SclTy.getSizeInBits());
10289 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10292 SDLoc dl = SDLoc(N);
10293 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10294 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10298 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10299 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10300 if (N->getNumOperands() == 2 &&
10301 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10302 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10303 EVT VT = N->getValueType(0);
10304 SDValue N0 = N->getOperand(0);
10305 SDValue N1 = N->getOperand(1);
10306 SmallVector<SDValue, 8> Opnds;
10307 unsigned BuildVecNumElts = N0.getNumOperands();
10309 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10310 Opnds.push_back(N0.getOperand(i));
10311 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10312 Opnds.push_back(N1.getOperand(i));
10314 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10318 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10319 // nodes often generate nop CONCAT_VECTOR nodes.
10320 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10321 // place the incoming vectors at the exact same location.
10322 SDValue SingleSource = SDValue();
10323 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10325 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10326 SDValue Op = N->getOperand(i);
10328 if (Op.getOpcode() == ISD::UNDEF)
10331 // Check if this is the identity extract:
10332 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10335 // Find the single incoming vector for the extract_subvector.
10336 if (SingleSource.getNode()) {
10337 if (Op.getOperand(0) != SingleSource)
10340 SingleSource = Op.getOperand(0);
10342 // Check the source type is the same as the type of the result.
10343 // If not, this concat may extend the vector, so we can not
10344 // optimize it away.
10345 if (SingleSource.getValueType() != N->getValueType(0))
10349 unsigned IdentityIndex = i * PartNumElem;
10350 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10351 // The extract index must be constant.
10355 // Check that we are reading from the identity index.
10356 if (CS->getZExtValue() != IdentityIndex)
10360 if (SingleSource.getNode())
10361 return SingleSource;
10366 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10367 EVT NVT = N->getValueType(0);
10368 SDValue V = N->getOperand(0);
10370 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10372 // (extract_subvec (concat V1, V2, ...), i)
10375 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10377 if (V->getOperand(0).getValueType() != NVT)
10379 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10380 unsigned NumElems = NVT.getVectorNumElements();
10381 assert((Idx % NumElems) == 0 &&
10382 "IDX in concat is not a multiple of the result vector length.");
10383 return V->getOperand(Idx / NumElems);
10387 if (V->getOpcode() == ISD::BITCAST)
10388 V = V.getOperand(0);
10390 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10392 // Handle only simple case where vector being inserted and vector
10393 // being extracted are of same type, and are half size of larger vectors.
10394 EVT BigVT = V->getOperand(0).getValueType();
10395 EVT SmallVT = V->getOperand(1).getValueType();
10396 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10399 // Only handle cases where both indexes are constants with the same type.
10400 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10401 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10403 if (InsIdx && ExtIdx &&
10404 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10405 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10407 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10409 // indices are equal or bit offsets are equal => V1
10410 // otherwise => (extract_subvec V1, ExtIdx)
10411 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10412 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10413 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10414 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10415 DAG.getNode(ISD::BITCAST, dl,
10416 N->getOperand(0).getValueType(),
10417 V->getOperand(0)), N->getOperand(1));
10424 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10425 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10426 EVT VT = N->getValueType(0);
10427 unsigned NumElts = VT.getVectorNumElements();
10429 SDValue N0 = N->getOperand(0);
10430 SDValue N1 = N->getOperand(1);
10431 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10433 SmallVector<SDValue, 4> Ops;
10434 EVT ConcatVT = N0.getOperand(0).getValueType();
10435 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10436 unsigned NumConcats = NumElts / NumElemsPerConcat;
10438 // Look at every vector that's inserted. We're looking for exact
10439 // subvector-sized copies from a concatenated vector
10440 for (unsigned I = 0; I != NumConcats; ++I) {
10441 // Make sure we're dealing with a copy.
10442 unsigned Begin = I * NumElemsPerConcat;
10443 bool AllUndef = true, NoUndef = true;
10444 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10445 if (SVN->getMaskElt(J) >= 0)
10452 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10455 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10456 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10459 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10460 if (FirstElt < N0.getNumOperands())
10461 Ops.push_back(N0.getOperand(FirstElt));
10463 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10465 } else if (AllUndef) {
10466 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10467 } else { // Mixed with general masks and undefs, can't do optimization.
10472 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10476 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10477 EVT VT = N->getValueType(0);
10478 unsigned NumElts = VT.getVectorNumElements();
10480 SDValue N0 = N->getOperand(0);
10481 SDValue N1 = N->getOperand(1);
10483 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10485 // Canonicalize shuffle undef, undef -> undef
10486 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10487 return DAG.getUNDEF(VT);
10489 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10491 // Canonicalize shuffle v, v -> v, undef
10493 SmallVector<int, 8> NewMask;
10494 for (unsigned i = 0; i != NumElts; ++i) {
10495 int Idx = SVN->getMaskElt(i);
10496 if (Idx >= (int)NumElts) Idx -= NumElts;
10497 NewMask.push_back(Idx);
10499 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10503 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10504 if (N0.getOpcode() == ISD::UNDEF) {
10505 SmallVector<int, 8> NewMask;
10506 for (unsigned i = 0; i != NumElts; ++i) {
10507 int Idx = SVN->getMaskElt(i);
10509 if (Idx >= (int)NumElts)
10512 Idx = -1; // remove reference to lhs
10514 NewMask.push_back(Idx);
10516 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10520 // Remove references to rhs if it is undef
10521 if (N1.getOpcode() == ISD::UNDEF) {
10522 bool Changed = false;
10523 SmallVector<int, 8> NewMask;
10524 for (unsigned i = 0; i != NumElts; ++i) {
10525 int Idx = SVN->getMaskElt(i);
10526 if (Idx >= (int)NumElts) {
10530 NewMask.push_back(Idx);
10533 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10536 // If it is a splat, check if the argument vector is another splat or a
10537 // build_vector with all scalar elements the same.
10538 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10539 SDNode *V = N0.getNode();
10541 // If this is a bit convert that changes the element type of the vector but
10542 // not the number of vector elements, look through it. Be careful not to
10543 // look though conversions that change things like v4f32 to v2f64.
10544 if (V->getOpcode() == ISD::BITCAST) {
10545 SDValue ConvInput = V->getOperand(0);
10546 if (ConvInput.getValueType().isVector() &&
10547 ConvInput.getValueType().getVectorNumElements() == NumElts)
10548 V = ConvInput.getNode();
10551 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10552 assert(V->getNumOperands() == NumElts &&
10553 "BUILD_VECTOR has wrong number of operands");
10555 bool AllSame = true;
10556 for (unsigned i = 0; i != NumElts; ++i) {
10557 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10558 Base = V->getOperand(i);
10562 // Splat of <u, u, u, u>, return <u, u, u, u>
10563 if (!Base.getNode())
10565 for (unsigned i = 0; i != NumElts; ++i) {
10566 if (V->getOperand(i) != Base) {
10571 // Splat of <x, x, x, x>, return <x, x, x, x>
10577 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10578 Level < AfterLegalizeVectorOps &&
10579 (N1.getOpcode() == ISD::UNDEF ||
10580 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10581 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10582 SDValue V = partitionShuffleOfConcats(N, DAG);
10588 // If this shuffle node is simply a swizzle of another shuffle node,
10589 // and it reverses the swizzle of the previous shuffle then we can
10590 // optimize shuffle(shuffle(x, undef), undef) -> x.
10591 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10592 N1.getOpcode() == ISD::UNDEF) {
10594 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10596 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10597 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10600 // The incoming shuffle must be of the same type as the result of the
10601 // current shuffle.
10602 assert(OtherSV->getOperand(0).getValueType() == VT &&
10603 "Shuffle types don't match");
10605 for (unsigned i = 0; i != NumElts; ++i) {
10606 int Idx = SVN->getMaskElt(i);
10607 assert(Idx < (int)NumElts && "Index references undef operand");
10608 // Next, this index comes from the first value, which is the incoming
10609 // shuffle. Adopt the incoming index.
10611 Idx = OtherSV->getMaskElt(Idx);
10613 // The combined shuffle must map each index to itself.
10614 if (Idx >= 0 && (unsigned)Idx != i)
10618 return OtherSV->getOperand(0);
10624 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10625 SDValue N0 = N->getOperand(0);
10626 SDValue N2 = N->getOperand(2);
10628 // If the input vector is a concatenation, and the insert replaces
10629 // one of the halves, we can optimize into a single concat_vectors.
10630 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10631 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10632 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10633 EVT VT = N->getValueType(0);
10635 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10636 // (concat_vectors Z, Y)
10638 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10639 N->getOperand(1), N0.getOperand(1));
10641 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10642 // (concat_vectors X, Z)
10643 if (InsIdx == VT.getVectorNumElements()/2)
10644 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10645 N0.getOperand(0), N->getOperand(1));
10651 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10652 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10653 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10654 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10655 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10656 EVT VT = N->getValueType(0);
10658 SDValue LHS = N->getOperand(0);
10659 SDValue RHS = N->getOperand(1);
10660 if (N->getOpcode() == ISD::AND) {
10661 if (RHS.getOpcode() == ISD::BITCAST)
10662 RHS = RHS.getOperand(0);
10663 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10664 SmallVector<int, 8> Indices;
10665 unsigned NumElts = RHS.getNumOperands();
10666 for (unsigned i = 0; i != NumElts; ++i) {
10667 SDValue Elt = RHS.getOperand(i);
10668 if (!isa<ConstantSDNode>(Elt))
10671 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10672 Indices.push_back(i);
10673 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10674 Indices.push_back(NumElts);
10679 // Let's see if the target supports this vector_shuffle.
10680 EVT RVT = RHS.getValueType();
10681 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10684 // Return the new VECTOR_SHUFFLE node.
10685 EVT EltVT = RVT.getVectorElementType();
10686 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10687 DAG.getConstant(0, EltVT));
10688 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10689 RVT, &ZeroOps[0], ZeroOps.size());
10690 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10691 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10692 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10699 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10700 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10701 assert(N->getValueType(0).isVector() &&
10702 "SimplifyVBinOp only works on vectors!");
10704 SDValue LHS = N->getOperand(0);
10705 SDValue RHS = N->getOperand(1);
10706 SDValue Shuffle = XformToShuffleWithZero(N);
10707 if (Shuffle.getNode()) return Shuffle;
10709 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10711 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10712 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10713 // Check if both vectors are constants. If not bail out.
10714 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10715 cast<BuildVectorSDNode>(RHS)->isConstant()))
10718 SmallVector<SDValue, 8> Ops;
10719 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10720 SDValue LHSOp = LHS.getOperand(i);
10721 SDValue RHSOp = RHS.getOperand(i);
10723 // Can't fold divide by zero.
10724 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10725 N->getOpcode() == ISD::FDIV) {
10726 if ((RHSOp.getOpcode() == ISD::Constant &&
10727 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10728 (RHSOp.getOpcode() == ISD::ConstantFP &&
10729 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10733 EVT VT = LHSOp.getValueType();
10734 EVT RVT = RHSOp.getValueType();
10736 // Integer BUILD_VECTOR operands may have types larger than the element
10737 // size (e.g., when the element type is not legal). Prior to type
10738 // legalization, the types may not match between the two BUILD_VECTORS.
10739 // Truncate one of the operands to make them match.
10740 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10741 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10743 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10747 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10749 if (FoldOp.getOpcode() != ISD::UNDEF &&
10750 FoldOp.getOpcode() != ISD::Constant &&
10751 FoldOp.getOpcode() != ISD::ConstantFP)
10753 Ops.push_back(FoldOp);
10754 AddToWorkList(FoldOp.getNode());
10757 if (Ops.size() == LHS.getNumOperands())
10758 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10759 LHS.getValueType(), &Ops[0], Ops.size());
10765 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10766 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10767 assert(N->getValueType(0).isVector() &&
10768 "SimplifyVUnaryOp only works on vectors!");
10770 SDValue N0 = N->getOperand(0);
10772 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10775 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10776 SmallVector<SDValue, 8> Ops;
10777 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10778 SDValue Op = N0.getOperand(i);
10779 if (Op.getOpcode() != ISD::UNDEF &&
10780 Op.getOpcode() != ISD::ConstantFP)
10782 EVT EltVT = Op.getValueType();
10783 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10784 if (FoldOp.getOpcode() != ISD::UNDEF &&
10785 FoldOp.getOpcode() != ISD::ConstantFP)
10787 Ops.push_back(FoldOp);
10788 AddToWorkList(FoldOp.getNode());
10791 if (Ops.size() != N0.getNumOperands())
10794 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10795 N0.getValueType(), &Ops[0], Ops.size());
10798 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10799 SDValue N1, SDValue N2){
10800 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10802 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10803 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10805 // If we got a simplified select_cc node back from SimplifySelectCC, then
10806 // break it down into a new SETCC node, and a new SELECT node, and then return
10807 // the SELECT node, since we were called with a SELECT node.
10808 if (SCC.getNode()) {
10809 // Check to see if we got a select_cc back (to turn into setcc/select).
10810 // Otherwise, just return whatever node we got back, like fabs.
10811 if (SCC.getOpcode() == ISD::SELECT_CC) {
10812 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10814 SCC.getOperand(0), SCC.getOperand(1),
10815 SCC.getOperand(4));
10816 AddToWorkList(SETCC.getNode());
10817 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10818 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10826 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10827 /// are the two values being selected between, see if we can simplify the
10828 /// select. Callers of this should assume that TheSelect is deleted if this
10829 /// returns true. As such, they should return the appropriate thing (e.g. the
10830 /// node) back to the top-level of the DAG combiner loop to avoid it being
10832 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10835 // Cannot simplify select with vector condition
10836 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10838 // If this is a select from two identical things, try to pull the operation
10839 // through the select.
10840 if (LHS.getOpcode() != RHS.getOpcode() ||
10841 !LHS.hasOneUse() || !RHS.hasOneUse())
10844 // If this is a load and the token chain is identical, replace the select
10845 // of two loads with a load through a select of the address to load from.
10846 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10847 // constants have been dropped into the constant pool.
10848 if (LHS.getOpcode() == ISD::LOAD) {
10849 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10850 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10852 // Token chains must be identical.
10853 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10854 // Do not let this transformation reduce the number of volatile loads.
10855 LLD->isVolatile() || RLD->isVolatile() ||
10856 // If this is an EXTLOAD, the VT's must match.
10857 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10858 // If this is an EXTLOAD, the kind of extension must match.
10859 (LLD->getExtensionType() != RLD->getExtensionType() &&
10860 // The only exception is if one of the extensions is anyext.
10861 LLD->getExtensionType() != ISD::EXTLOAD &&
10862 RLD->getExtensionType() != ISD::EXTLOAD) ||
10863 // FIXME: this discards src value information. This is
10864 // over-conservative. It would be beneficial to be able to remember
10865 // both potential memory locations. Since we are discarding
10866 // src value info, don't do the transformation if the memory
10867 // locations are not in the default address space.
10868 LLD->getPointerInfo().getAddrSpace() != 0 ||
10869 RLD->getPointerInfo().getAddrSpace() != 0 ||
10870 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10871 LLD->getBasePtr().getValueType()))
10874 // Check that the select condition doesn't reach either load. If so,
10875 // folding this will induce a cycle into the DAG. If not, this is safe to
10876 // xform, so create a select of the addresses.
10878 if (TheSelect->getOpcode() == ISD::SELECT) {
10879 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10880 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10881 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10883 // The loads must not depend on one another.
10884 if (LLD->isPredecessorOf(RLD) ||
10885 RLD->isPredecessorOf(LLD))
10887 Addr = DAG.getSelect(SDLoc(TheSelect),
10888 LLD->getBasePtr().getValueType(),
10889 TheSelect->getOperand(0), LLD->getBasePtr(),
10890 RLD->getBasePtr());
10891 } else { // Otherwise SELECT_CC
10892 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10893 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10895 if ((LLD->hasAnyUseOfValue(1) &&
10896 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10897 (RLD->hasAnyUseOfValue(1) &&
10898 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10901 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10902 LLD->getBasePtr().getValueType(),
10903 TheSelect->getOperand(0),
10904 TheSelect->getOperand(1),
10905 LLD->getBasePtr(), RLD->getBasePtr(),
10906 TheSelect->getOperand(4));
10910 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10911 Load = DAG.getLoad(TheSelect->getValueType(0),
10913 // FIXME: Discards pointer and TBAA info.
10914 LLD->getChain(), Addr, MachinePointerInfo(),
10915 LLD->isVolatile(), LLD->isNonTemporal(),
10916 LLD->isInvariant(), LLD->getAlignment());
10918 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10919 RLD->getExtensionType() : LLD->getExtensionType(),
10921 TheSelect->getValueType(0),
10922 // FIXME: Discards pointer and TBAA info.
10923 LLD->getChain(), Addr, MachinePointerInfo(),
10924 LLD->getMemoryVT(), LLD->isVolatile(),
10925 LLD->isNonTemporal(), LLD->getAlignment());
10928 // Users of the select now use the result of the load.
10929 CombineTo(TheSelect, Load);
10931 // Users of the old loads now use the new load's chain. We know the
10932 // old-load value is dead now.
10933 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10934 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10941 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10942 /// where 'cond' is the comparison specified by CC.
10943 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10944 SDValue N2, SDValue N3,
10945 ISD::CondCode CC, bool NotExtCompare) {
10946 // (x ? y : y) -> y.
10947 if (N2 == N3) return N2;
10949 EVT VT = N2.getValueType();
10950 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10951 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10952 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10954 // Determine if the condition we're dealing with is constant
10955 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10956 N0, N1, CC, DL, false);
10957 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10958 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10960 // fold select_cc true, x, y -> x
10961 if (SCCC && !SCCC->isNullValue())
10963 // fold select_cc false, x, y -> y
10964 if (SCCC && SCCC->isNullValue())
10967 // Check to see if we can simplify the select into an fabs node
10968 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10969 // Allow either -0.0 or 0.0
10970 if (CFP->getValueAPF().isZero()) {
10971 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10972 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10973 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10974 N2 == N3.getOperand(0))
10975 return DAG.getNode(ISD::FABS, DL, VT, N0);
10977 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10978 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10979 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10980 N2.getOperand(0) == N3)
10981 return DAG.getNode(ISD::FABS, DL, VT, N3);
10985 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10986 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10987 // in it. This is a win when the constant is not otherwise available because
10988 // it replaces two constant pool loads with one. We only do this if the FP
10989 // type is known to be legal, because if it isn't, then we are before legalize
10990 // types an we want the other legalization to happen first (e.g. to avoid
10991 // messing with soft float) and if the ConstantFP is not legal, because if
10992 // it is legal, we may not need to store the FP constant in a constant pool.
10993 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10994 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10995 if (TLI.isTypeLegal(N2.getValueType()) &&
10996 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10997 TargetLowering::Legal) &&
10998 // If both constants have multiple uses, then we won't need to do an
10999 // extra load, they are likely around in registers for other users.
11000 (TV->hasOneUse() || FV->hasOneUse())) {
11001 Constant *Elts[] = {
11002 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11003 const_cast<ConstantFP*>(TV->getConstantFPValue())
11005 Type *FPTy = Elts[0]->getType();
11006 const DataLayout &TD = *TLI.getDataLayout();
11008 // Create a ConstantArray of the two constants.
11009 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11010 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11011 TD.getPrefTypeAlignment(FPTy));
11012 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11014 // Get the offsets to the 0 and 1 element of the array so that we can
11015 // select between them.
11016 SDValue Zero = DAG.getIntPtrConstant(0);
11017 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11018 SDValue One = DAG.getIntPtrConstant(EltSize);
11020 SDValue Cond = DAG.getSetCC(DL,
11021 getSetCCResultType(N0.getValueType()),
11023 AddToWorkList(Cond.getNode());
11024 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11026 AddToWorkList(CstOffset.getNode());
11027 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11029 AddToWorkList(CPIdx.getNode());
11030 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11031 MachinePointerInfo::getConstantPool(), false,
11032 false, false, Alignment);
11037 // Check to see if we can perform the "gzip trick", transforming
11038 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11039 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11040 (N1C->isNullValue() || // (a < 0) ? b : 0
11041 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11042 EVT XType = N0.getValueType();
11043 EVT AType = N2.getValueType();
11044 if (XType.bitsGE(AType)) {
11045 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11046 // single-bit constant.
11047 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11048 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11049 ShCtV = XType.getSizeInBits()-ShCtV-1;
11050 SDValue ShCt = DAG.getConstant(ShCtV,
11051 getShiftAmountTy(N0.getValueType()));
11052 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11054 AddToWorkList(Shift.getNode());
11056 if (XType.bitsGT(AType)) {
11057 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11058 AddToWorkList(Shift.getNode());
11061 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11064 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11066 DAG.getConstant(XType.getSizeInBits()-1,
11067 getShiftAmountTy(N0.getValueType())));
11068 AddToWorkList(Shift.getNode());
11070 if (XType.bitsGT(AType)) {
11071 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11072 AddToWorkList(Shift.getNode());
11075 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11079 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11080 // where y is has a single bit set.
11081 // A plaintext description would be, we can turn the SELECT_CC into an AND
11082 // when the condition can be materialized as an all-ones register. Any
11083 // single bit-test can be materialized as an all-ones register with
11084 // shift-left and shift-right-arith.
11085 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11086 N0->getValueType(0) == VT &&
11087 N1C && N1C->isNullValue() &&
11088 N2C && N2C->isNullValue()) {
11089 SDValue AndLHS = N0->getOperand(0);
11090 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11091 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11092 // Shift the tested bit over the sign bit.
11093 APInt AndMask = ConstAndRHS->getAPIntValue();
11095 DAG.getConstant(AndMask.countLeadingZeros(),
11096 getShiftAmountTy(AndLHS.getValueType()));
11097 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11099 // Now arithmetic right shift it all the way over, so the result is either
11100 // all-ones, or zero.
11102 DAG.getConstant(AndMask.getBitWidth()-1,
11103 getShiftAmountTy(Shl.getValueType()));
11104 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11106 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11110 // fold select C, 16, 0 -> shl C, 4
11111 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11112 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11113 TargetLowering::ZeroOrOneBooleanContent) {
11115 // If the caller doesn't want us to simplify this into a zext of a compare,
11117 if (NotExtCompare && N2C->getAPIntValue() == 1)
11120 // Get a SetCC of the condition
11121 // NOTE: Don't create a SETCC if it's not legal on this target.
11122 if (!LegalOperations ||
11123 TLI.isOperationLegal(ISD::SETCC,
11124 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11126 // cast from setcc result type to select result type
11128 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11130 if (N2.getValueType().bitsLT(SCC.getValueType()))
11131 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11132 N2.getValueType());
11134 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11135 N2.getValueType(), SCC);
11137 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11138 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11139 N2.getValueType(), SCC);
11142 AddToWorkList(SCC.getNode());
11143 AddToWorkList(Temp.getNode());
11145 if (N2C->getAPIntValue() == 1)
11148 // shl setcc result by log2 n2c
11149 return DAG.getNode(
11150 ISD::SHL, DL, N2.getValueType(), Temp,
11151 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11152 getShiftAmountTy(Temp.getValueType())));
11156 // Check to see if this is the equivalent of setcc
11157 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11158 // otherwise, go ahead with the folds.
11159 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11160 EVT XType = N0.getValueType();
11161 if (!LegalOperations ||
11162 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11163 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11164 if (Res.getValueType() != VT)
11165 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11169 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11170 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11171 (!LegalOperations ||
11172 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11173 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11174 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11175 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11176 getShiftAmountTy(Ctlz.getValueType())));
11178 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11179 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11180 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11181 XType, DAG.getConstant(0, XType), N0);
11182 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11183 return DAG.getNode(ISD::SRL, DL, XType,
11184 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11185 DAG.getConstant(XType.getSizeInBits()-1,
11186 getShiftAmountTy(XType)));
11188 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11189 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11190 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11191 DAG.getConstant(XType.getSizeInBits()-1,
11192 getShiftAmountTy(N0.getValueType())));
11193 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11197 // Check to see if this is an integer abs.
11198 // select_cc setg[te] X, 0, X, -X ->
11199 // select_cc setgt X, -1, X, -X ->
11200 // select_cc setl[te] X, 0, -X, X ->
11201 // select_cc setlt X, 1, -X, X ->
11202 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11204 ConstantSDNode *SubC = NULL;
11205 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11206 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11207 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11208 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11209 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11210 (N1C->isOne() && CC == ISD::SETLT)) &&
11211 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11212 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11214 EVT XType = N0.getValueType();
11215 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11216 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11218 DAG.getConstant(XType.getSizeInBits()-1,
11219 getShiftAmountTy(N0.getValueType())));
11220 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11222 AddToWorkList(Shift.getNode());
11223 AddToWorkList(Add.getNode());
11224 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11231 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11232 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11233 SDValue N1, ISD::CondCode Cond,
11234 SDLoc DL, bool foldBooleans) {
11235 TargetLowering::DAGCombinerInfo
11236 DagCombineInfo(DAG, Level, false, this);
11237 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11240 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11241 /// return a DAG expression to select that will generate the same value by
11242 /// multiplying by a magic number. See:
11243 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11244 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11245 std::vector<SDNode*> Built;
11246 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11248 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11250 AddToWorkList(*ii);
11254 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11255 /// return a DAG expression to select that will generate the same value by
11256 /// multiplying by a magic number. See:
11257 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11258 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11259 std::vector<SDNode*> Built;
11260 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11262 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11264 AddToWorkList(*ii);
11268 /// FindBaseOffset - Return true if base is a frame index, which is known not
11269 // to alias with anything but itself. Provides base object and offset as
11271 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11272 const GlobalValue *&GV, const void *&CV) {
11273 // Assume it is a primitive operation.
11274 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11276 // If it's an adding a simple constant then integrate the offset.
11277 if (Base.getOpcode() == ISD::ADD) {
11278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11279 Base = Base.getOperand(0);
11280 Offset += C->getZExtValue();
11284 // Return the underlying GlobalValue, and update the Offset. Return false
11285 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11286 // by multiple nodes with different offsets.
11287 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11288 GV = G->getGlobal();
11289 Offset += G->getOffset();
11293 // Return the underlying Constant value, and update the Offset. Return false
11294 // for ConstantSDNodes since the same constant pool entry may be represented
11295 // by multiple nodes with different offsets.
11296 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11297 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11298 : (const void *)C->getConstVal();
11299 Offset += C->getOffset();
11302 // If it's any of the following then it can't alias with anything but itself.
11303 return isa<FrameIndexSDNode>(Base);
11306 /// isAlias - Return true if there is any possibility that the two addresses
11308 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11309 const Value *SrcValue1, int SrcValueOffset1,
11310 unsigned SrcValueAlign1,
11311 const MDNode *TBAAInfo1,
11312 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11313 const Value *SrcValue2, int SrcValueOffset2,
11314 unsigned SrcValueAlign2,
11315 const MDNode *TBAAInfo2) const {
11316 // If they are the same then they must be aliases.
11317 if (Ptr1 == Ptr2) return true;
11319 // If they are both volatile then they cannot be reordered.
11320 if (IsVolatile1 && IsVolatile2) return true;
11322 // Gather base node and offset information.
11323 SDValue Base1, Base2;
11324 int64_t Offset1, Offset2;
11325 const GlobalValue *GV1, *GV2;
11326 const void *CV1, *CV2;
11327 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11328 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11330 // If they have a same base address then check to see if they overlap.
11331 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11332 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11334 // It is possible for different frame indices to alias each other, mostly
11335 // when tail call optimization reuses return address slots for arguments.
11336 // To catch this case, look up the actual index of frame indices to compute
11337 // the real alias relationship.
11338 if (isFrameIndex1 && isFrameIndex2) {
11339 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11340 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11341 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11342 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11345 // Otherwise, if we know what the bases are, and they aren't identical, then
11346 // we know they cannot alias.
11347 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11350 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11351 // compared to the size and offset of the access, we may be able to prove they
11352 // do not alias. This check is conservative for now to catch cases created by
11353 // splitting vector types.
11354 if ((SrcValueAlign1 == SrcValueAlign2) &&
11355 (SrcValueOffset1 != SrcValueOffset2) &&
11356 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11357 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11358 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11360 // There is no overlap between these relatively aligned accesses of similar
11361 // size, return no alias.
11362 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11366 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11367 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11369 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11370 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11373 if (UseAA && SrcValue1 && SrcValue2) {
11374 // Use alias analysis information.
11375 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11376 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11377 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11378 AliasAnalysis::AliasResult AAResult =
11379 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11380 UseTBAA ? TBAAInfo1 : 0),
11381 AliasAnalysis::Location(SrcValue2, Overlap2,
11382 UseTBAA ? TBAAInfo2 : 0));
11383 if (AAResult == AliasAnalysis::NoAlias)
11387 // Otherwise we have to assume they alias.
11391 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11392 SDValue Ptr0, Ptr1;
11393 int64_t Size0, Size1;
11394 bool IsVolatile0, IsVolatile1;
11395 const Value *SrcValue0, *SrcValue1;
11396 int SrcValueOffset0, SrcValueOffset1;
11397 unsigned SrcValueAlign0, SrcValueAlign1;
11398 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11399 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11400 SrcValueAlign0, SrcTBAAInfo0);
11401 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11402 SrcValueAlign1, SrcTBAAInfo1);
11403 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11404 SrcValueAlign0, SrcTBAAInfo0,
11405 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11406 SrcValueAlign1, SrcTBAAInfo1);
11409 /// FindAliasInfo - Extracts the relevant alias information from the memory
11410 /// node. Returns true if the operand was a nonvolatile load.
11411 bool DAGCombiner::FindAliasInfo(SDNode *N,
11412 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11413 const Value *&SrcValue,
11414 int &SrcValueOffset,
11415 unsigned &SrcValueAlign,
11416 const MDNode *&TBAAInfo) const {
11417 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11419 Ptr = LS->getBasePtr();
11420 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11421 IsVolatile = LS->isVolatile();
11422 SrcValue = LS->getSrcValue();
11423 SrcValueOffset = LS->getSrcValueOffset();
11424 SrcValueAlign = LS->getOriginalAlignment();
11425 TBAAInfo = LS->getTBAAInfo();
11426 return isa<LoadSDNode>(LS) && !IsVolatile;
11429 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11430 /// looking for aliasing nodes and adding them to the Aliases vector.
11431 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11432 SmallVectorImpl<SDValue> &Aliases) {
11433 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11434 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11436 // Get alias information for node.
11440 const Value *SrcValue;
11441 int SrcValueOffset;
11442 unsigned SrcValueAlign;
11443 const MDNode *SrcTBAAInfo;
11444 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11445 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11448 Chains.push_back(OriginalChain);
11449 unsigned Depth = 0;
11451 // Look at each chain and determine if it is an alias. If so, add it to the
11452 // aliases list. If not, then continue up the chain looking for the next
11454 while (!Chains.empty()) {
11455 SDValue Chain = Chains.back();
11458 // For TokenFactor nodes, look at each operand and only continue up the
11459 // chain until we find two aliases. If we've seen two aliases, assume we'll
11460 // find more and revert to original chain since the xform is unlikely to be
11463 // FIXME: The depth check could be made to return the last non-aliasing
11464 // chain we found before we hit a tokenfactor rather than the original
11466 if (Depth > 6 || Aliases.size() == 2) {
11468 Aliases.push_back(OriginalChain);
11472 // Don't bother if we've been before.
11473 if (!Visited.insert(Chain.getNode()))
11476 switch (Chain.getOpcode()) {
11477 case ISD::EntryToken:
11478 // Entry token is ideal chain operand, but handled in FindBetterChain.
11483 // Get alias information for Chain.
11487 const Value *OpSrcValue;
11488 int OpSrcValueOffset;
11489 unsigned OpSrcValueAlign;
11490 const MDNode *OpSrcTBAAInfo;
11491 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11492 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11496 // If chain is alias then stop here.
11497 if (!(IsLoad && IsOpLoad) &&
11498 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11499 SrcValueAlign, SrcTBAAInfo,
11500 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11501 OpSrcValueAlign, OpSrcTBAAInfo)) {
11502 Aliases.push_back(Chain);
11504 // Look further up the chain.
11505 Chains.push_back(Chain.getOperand(0));
11511 case ISD::TokenFactor:
11512 // We have to check each of the operands of the token factor for "small"
11513 // token factors, so we queue them up. Adding the operands to the queue
11514 // (stack) in reverse order maintains the original order and increases the
11515 // likelihood that getNode will find a matching token factor (CSE.)
11516 if (Chain.getNumOperands() > 16) {
11517 Aliases.push_back(Chain);
11520 for (unsigned n = Chain.getNumOperands(); n;)
11521 Chains.push_back(Chain.getOperand(--n));
11526 // For all other instructions we will just have to take what we can get.
11527 Aliases.push_back(Chain);
11532 // We need to be careful here to also search for aliases through the
11533 // value operand of a store, etc. Consider the following situation:
11535 // L1 = load Token1, %52
11536 // S1 = store Token1, L1, %51
11537 // L2 = load Token1, %52+8
11538 // S2 = store Token1, L2, %51+8
11539 // Token2 = Token(S1, S2)
11540 // L3 = load Token2, %53
11541 // S3 = store Token2, L3, %52
11542 // L4 = load Token2, %53+8
11543 // S4 = store Token2, L4, %52+8
11544 // If we search for aliases of S3 (which loads address %52), and we look
11545 // only through the chain, then we'll miss the trivial dependence on L1
11546 // (which also loads from %52). We then might change all loads and
11547 // stores to use Token1 as their chain operand, which could result in
11548 // copying %53 into %52 before copying %52 into %51 (which should
11551 // The problem is, however, that searching for such data dependencies
11552 // can become expensive, and the cost is not directly related to the
11553 // chain depth. Instead, we'll rule out such configurations here by
11554 // insisting that we've visited all chain users (except for users
11555 // of the original chain, which is not necessary). When doing this,
11556 // we need to look through nodes we don't care about (otherwise, things
11557 // like register copies will interfere with trivial cases).
11559 SmallVector<const SDNode *, 16> Worklist;
11560 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11561 IE = Visited.end(); I != IE; ++I)
11562 if (*I != OriginalChain.getNode())
11563 Worklist.push_back(*I);
11565 while (!Worklist.empty()) {
11566 const SDNode *M = Worklist.pop_back_val();
11568 // We have already visited M, and want to make sure we've visited any uses
11569 // of M that we care about. For uses that we've not visisted, and don't
11570 // care about, queue them to the worklist.
11572 for (SDNode::use_iterator UI = M->use_begin(),
11573 UIE = M->use_end(); UI != UIE; ++UI)
11574 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11575 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11576 // We've not visited this use, and we care about it (it could have an
11577 // ordering dependency with the original node).
11579 Aliases.push_back(OriginalChain);
11583 // We've not visited this use, but we don't care about it. Mark it as
11584 // visited and enqueue it to the worklist.
11585 Worklist.push_back(*UI);
11590 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11591 /// for a better chain (aliasing node.)
11592 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11593 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11595 // Accumulate all the aliases to this node.
11596 GatherAllAliases(N, OldChain, Aliases);
11598 // If no operands then chain to entry token.
11599 if (Aliases.size() == 0)
11600 return DAG.getEntryNode();
11602 // If a single operand then chain to it. We don't need to revisit it.
11603 if (Aliases.size() == 1)
11606 // Construct a custom tailored token factor.
11607 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11608 &Aliases[0], Aliases.size());
11611 // SelectionDAG::Combine - This is the entry point for the file.
11613 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11614 CodeGenOpt::Level OptLevel) {
11615 /// run - This is the main entry point to this class.
11617 DAGCombiner(*this, AA, OptLevel).Run(Level);