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 visitCTLZ(SDNode *N);
233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234 SDValue visitCTTZ(SDNode *N);
235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
238 SDValue visitVSELECT(SDNode *N);
239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
246 SDValue visitBITCAST(SDNode *N);
247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
251 SDValue visitFMA(SDNode *N);
252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
279 SDValue XformToShuffleWithZero(SDNode *N);
280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288 SDValue N3, ISD::CondCode CC,
289 bool NotExtCompare = false);
290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291 SDLoc DL, bool foldBooleans = true);
292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306 SDValue ReduceLoadWidth(SDNode *N);
307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
308 SDValue TransformFPLoadStorePair(SDNode *N);
309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317 SmallVectorImpl<SDValue> &Aliases);
319 /// isAlias - Return true if there is any possibility that the two addresses
321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
322 const Value *SrcValue1, int SrcValueOffset1,
323 unsigned SrcValueAlign1,
324 const MDNode *TBAAInfo1,
325 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
326 const Value *SrcValue2, int SrcValueOffset2,
327 unsigned SrcValueAlign2,
328 const MDNode *TBAAInfo2) const;
330 /// isAlias - Return true if there is any possibility that the two addresses
332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
334 /// FindAliasInfo - Extracts the relevant alias information from the memory
335 /// node. Returns true if the operand was a load.
336 bool FindAliasInfo(SDNode *N,
337 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
338 const Value *&SrcValue, int &SrcValueOffset,
339 unsigned &SrcValueAlignment,
340 const MDNode *&TBAAInfo) const;
342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343 /// looking for a better chain (aliasing node.)
344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
352 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
353 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
354 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
355 AttributeSet FnAttrs =
356 DAG.getMachineFunction().getFunction()->getAttributes();
358 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
359 Attribute::OptimizeForSize) ||
360 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
363 /// Run - runs the dag combiner on all nodes in the work list
364 void Run(CombineLevel AtLevel);
366 SelectionDAG &getDAG() const { return DAG; }
368 /// getShiftAmountTy - Returns a type large enough to hold any valid
369 /// shift amount - before type legalization these can be huge.
370 EVT getShiftAmountTy(EVT LHSTy) {
371 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
372 if (LHSTy.isVector())
374 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
375 : TLI.getPointerTy();
378 /// isTypeLegal - This method returns true if we are running before type
379 /// legalization or if the specified VT is legal.
380 bool isTypeLegal(const EVT &VT) {
381 if (!LegalTypes) return true;
382 return TLI.isTypeLegal(VT);
385 /// getSetCCResultType - Convenience wrapper around
386 /// TargetLowering::getSetCCResultType
387 EVT getSetCCResultType(EVT VT) const {
388 return TLI.getSetCCResultType(*DAG.getContext(), VT);
395 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
396 /// nodes from the worklist.
397 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
400 explicit WorkListRemover(DAGCombiner &dc)
401 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
403 virtual void NodeDeleted(SDNode *N, SDNode *E) {
404 DC.removeFromWorkList(N);
409 //===----------------------------------------------------------------------===//
410 // TargetLowering::DAGCombinerInfo implementation
411 //===----------------------------------------------------------------------===//
413 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
414 ((DAGCombiner*)DC)->AddToWorkList(N);
417 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
418 ((DAGCombiner*)DC)->removeFromWorkList(N);
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
426 SDValue TargetLowering::DAGCombinerInfo::
427 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
432 SDValue TargetLowering::DAGCombinerInfo::
433 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
434 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
437 void TargetLowering::DAGCombinerInfo::
438 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
439 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
442 //===----------------------------------------------------------------------===//
444 //===----------------------------------------------------------------------===//
446 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
447 /// specified expression for the same cost as the expression itself, or 2 if we
448 /// can compute the negated form more cheaply than the expression itself.
449 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
450 const TargetLowering &TLI,
451 const TargetOptions *Options,
452 unsigned Depth = 0) {
453 // fneg is removable even if it has multiple uses.
454 if (Op.getOpcode() == ISD::FNEG) return 2;
456 // Don't allow anything with multiple uses.
457 if (!Op.hasOneUse()) return 0;
459 // Don't recurse exponentially.
460 if (Depth > 6) return 0;
462 switch (Op.getOpcode()) {
463 default: return false;
464 case ISD::ConstantFP:
465 // Don't invert constant FP values after legalize. The negated constant
466 // isn't necessarily legal.
467 return LegalOperations ? 0 : 1;
469 // FIXME: determine better conditions for this xform.
470 if (!Options->UnsafeFPMath) return 0;
472 // After operation legalization, it might not be legal to create new FSUBs.
473 if (LegalOperations &&
474 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
477 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
481 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
485 // We can't turn -(A-B) into B-A when we honor signed zeros.
486 if (!Options->UnsafeFPMath) return 0;
488 // fold (fneg (fsub A, B)) -> (fsub B, A)
493 if (Options->HonorSignDependentRoundingFPMath()) return 0;
495 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
496 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
500 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
506 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
511 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
512 /// returns the newly negated expression.
513 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
514 bool LegalOperations, unsigned Depth = 0) {
515 // fneg is removable even if it has multiple uses.
516 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
518 // Don't allow anything with multiple uses.
519 assert(Op.hasOneUse() && "Unknown reuse!");
521 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
522 switch (Op.getOpcode()) {
523 default: llvm_unreachable("Unknown code");
524 case ISD::ConstantFP: {
525 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
527 return DAG.getConstantFP(V, Op.getValueType());
530 // FIXME: determine better conditions for this xform.
531 assert(DAG.getTarget().Options.UnsafeFPMath);
533 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
534 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
535 DAG.getTargetLoweringInfo(),
536 &DAG.getTarget().Options, Depth+1))
537 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
538 GetNegatedExpression(Op.getOperand(0), DAG,
539 LegalOperations, Depth+1),
541 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
542 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
543 GetNegatedExpression(Op.getOperand(1), DAG,
544 LegalOperations, Depth+1),
547 // We can't turn -(A-B) into B-A when we honor signed zeros.
548 assert(DAG.getTarget().Options.UnsafeFPMath);
550 // fold (fneg (fsub 0, B)) -> B
551 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
552 if (N0CFP->getValueAPF().isZero())
553 return Op.getOperand(1);
555 // fold (fneg (fsub A, B)) -> (fsub B, A)
556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
557 Op.getOperand(1), Op.getOperand(0));
561 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
564 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
565 DAG.getTargetLoweringInfo(),
566 &DAG.getTarget().Options, Depth+1))
567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
568 GetNegatedExpression(Op.getOperand(0), DAG,
569 LegalOperations, Depth+1),
572 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
573 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
575 GetNegatedExpression(Op.getOperand(1), DAG,
576 LegalOperations, Depth+1));
580 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
581 GetNegatedExpression(Op.getOperand(0), DAG,
582 LegalOperations, Depth+1));
584 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
585 GetNegatedExpression(Op.getOperand(0), DAG,
586 LegalOperations, Depth+1),
592 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
593 // that selects between the values 1 and 0, making it equivalent to a setcc.
594 // Also, set the incoming LHS, RHS, and CC references to the appropriate
595 // nodes based on the type of node we are checking. This simplifies life a
596 // bit for the callers.
597 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
599 if (N.getOpcode() == ISD::SETCC) {
600 LHS = N.getOperand(0);
601 RHS = N.getOperand(1);
602 CC = N.getOperand(2);
605 if (N.getOpcode() == ISD::SELECT_CC &&
606 N.getOperand(2).getOpcode() == ISD::Constant &&
607 N.getOperand(3).getOpcode() == ISD::Constant &&
608 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
609 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
610 LHS = N.getOperand(0);
611 RHS = N.getOperand(1);
612 CC = N.getOperand(4);
618 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
619 // one use. If this is true, it allows the users to invert the operation for
620 // free when it is profitable to do so.
621 static bool isOneUseSetCC(SDValue N) {
623 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
628 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
629 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
630 if (isa<ConstantSDNode>(N))
632 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
633 if(BV && BV->isConstant())
638 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
639 SDValue N0, SDValue N1) {
640 EVT VT = N0.getValueType();
641 if (N0.getOpcode() == Opc) {
642 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
643 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
644 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
645 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
646 if (!OpNode.getNode())
648 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
650 if (N0.hasOneUse()) {
651 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
653 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
654 if (!OpNode.getNode())
656 AddToWorkList(OpNode.getNode());
657 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
662 if (N1.getOpcode() == Opc) {
663 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
664 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
665 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
666 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
667 if (!OpNode.getNode())
669 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
671 if (N1.hasOneUse()) {
672 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
674 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
675 if (!OpNode.getNode())
677 AddToWorkList(OpNode.getNode());
678 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
686 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
688 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
690 DEBUG(dbgs() << "\nReplacing.1 ";
692 dbgs() << "\nWith: ";
693 To[0].getNode()->dump(&DAG);
694 dbgs() << " and " << NumTo-1 << " other values\n";
695 for (unsigned i = 0, e = NumTo; i != e; ++i)
696 assert((!To[i].getNode() ||
697 N->getValueType(i) == To[i].getValueType()) &&
698 "Cannot combine value to value of different type!"));
699 WorkListRemover DeadNodes(*this);
700 DAG.ReplaceAllUsesWith(N, To);
702 // Push the new nodes and any users onto the worklist
703 for (unsigned i = 0, e = NumTo; i != e; ++i) {
704 if (To[i].getNode()) {
705 AddToWorkList(To[i].getNode());
706 AddUsersToWorkList(To[i].getNode());
711 // Finally, if the node is now dead, remove it from the graph. The node
712 // may not be dead if the replacement process recursively simplified to
713 // something else needing this node.
714 if (N->use_empty()) {
715 // Nodes can be reintroduced into the worklist. Make sure we do not
716 // process a node that has been replaced.
717 removeFromWorkList(N);
719 // Finally, since the node is now dead, remove it from the graph.
722 return SDValue(N, 0);
726 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
727 // Replace all uses. If any nodes become isomorphic to other nodes and
728 // are deleted, make sure to remove them from our worklist.
729 WorkListRemover DeadNodes(*this);
730 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
732 // Push the new node and any (possibly new) users onto the worklist.
733 AddToWorkList(TLO.New.getNode());
734 AddUsersToWorkList(TLO.New.getNode());
736 // Finally, if the node is now dead, remove it from the graph. The node
737 // may not be dead if the replacement process recursively simplified to
738 // something else needing this node.
739 if (TLO.Old.getNode()->use_empty()) {
740 removeFromWorkList(TLO.Old.getNode());
742 // If the operands of this node are only used by the node, they will now
743 // be dead. Make sure to visit them first to delete dead nodes early.
744 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
745 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
746 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
748 DAG.DeleteNode(TLO.Old.getNode());
752 /// SimplifyDemandedBits - Check the specified integer node value to see if
753 /// it can be simplified or if things it uses can be simplified by bit
754 /// propagation. If so, return true.
755 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
756 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
757 APInt KnownZero, KnownOne;
758 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
762 AddToWorkList(Op.getNode());
764 // Replace the old value with the new one.
766 DEBUG(dbgs() << "\nReplacing.2 ";
767 TLO.Old.getNode()->dump(&DAG);
768 dbgs() << "\nWith: ";
769 TLO.New.getNode()->dump(&DAG);
772 CommitTargetLoweringOpt(TLO);
776 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
778 EVT VT = Load->getValueType(0);
779 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
781 DEBUG(dbgs() << "\nReplacing.9 ";
783 dbgs() << "\nWith: ";
784 Trunc.getNode()->dump(&DAG);
786 WorkListRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
788 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
789 removeFromWorkList(Load);
790 DAG.DeleteNode(Load);
791 AddToWorkList(Trunc.getNode());
794 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
797 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
798 EVT MemVT = LD->getMemoryVT();
799 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
800 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
802 : LD->getExtensionType();
804 return DAG.getExtLoad(ExtType, dl, PVT,
805 LD->getChain(), LD->getBasePtr(),
806 MemVT, LD->getMemOperand());
809 unsigned Opc = Op.getOpcode();
812 case ISD::AssertSext:
813 return DAG.getNode(ISD::AssertSext, dl, PVT,
814 SExtPromoteOperand(Op.getOperand(0), PVT),
816 case ISD::AssertZext:
817 return DAG.getNode(ISD::AssertZext, dl, PVT,
818 ZExtPromoteOperand(Op.getOperand(0), PVT),
820 case ISD::Constant: {
822 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
823 return DAG.getNode(ExtOpc, dl, PVT, Op);
827 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
829 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
832 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
833 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
835 EVT OldVT = Op.getValueType();
837 bool Replace = false;
838 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
839 if (NewOp.getNode() == 0)
841 AddToWorkList(NewOp.getNode());
844 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
845 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
846 DAG.getValueType(OldVT));
849 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
850 EVT OldVT = Op.getValueType();
852 bool Replace = false;
853 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854 if (NewOp.getNode() == 0)
856 AddToWorkList(NewOp.getNode());
859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
863 /// PromoteIntBinOp - Promote the specified integer binary operation if the
864 /// target indicates it is beneficial. e.g. On x86, it's usually better to
865 /// promote i16 operations to i32 since i16 instructions are longer.
866 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
867 if (!LegalOperations)
870 EVT VT = Op.getValueType();
871 if (VT.isVector() || !VT.isInteger())
874 // If operation type is 'undesirable', e.g. i16 on x86, consider
876 unsigned Opc = Op.getOpcode();
877 if (TLI.isTypeDesirableForOp(Opc, VT))
881 // Consult target whether it is a good idea to promote this operation and
882 // what's the right type to promote it to.
883 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
884 assert(PVT != VT && "Don't know what type to promote to!");
886 bool Replace0 = false;
887 SDValue N0 = Op.getOperand(0);
888 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
889 if (NN0.getNode() == 0)
892 bool Replace1 = false;
893 SDValue N1 = Op.getOperand(1);
898 NN1 = PromoteOperand(N1, PVT, Replace1);
899 if (NN1.getNode() == 0)
903 AddToWorkList(NN0.getNode());
905 AddToWorkList(NN1.getNode());
908 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
910 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
912 DEBUG(dbgs() << "\nPromoting ";
913 Op.getNode()->dump(&DAG));
915 return DAG.getNode(ISD::TRUNCATE, dl, VT,
916 DAG.getNode(Opc, dl, PVT, NN0, NN1));
921 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
922 /// target indicates it is beneficial. e.g. On x86, it's usually better to
923 /// promote i16 operations to i32 since i16 instructions are longer.
924 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
925 if (!LegalOperations)
928 EVT VT = Op.getValueType();
929 if (VT.isVector() || !VT.isInteger())
932 // If operation type is 'undesirable', e.g. i16 on x86, consider
934 unsigned Opc = Op.getOpcode();
935 if (TLI.isTypeDesirableForOp(Opc, VT))
939 // Consult target whether it is a good idea to promote this operation and
940 // what's the right type to promote it to.
941 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
942 assert(PVT != VT && "Don't know what type to promote to!");
944 bool Replace = false;
945 SDValue N0 = Op.getOperand(0);
947 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
948 else if (Opc == ISD::SRL)
949 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
951 N0 = PromoteOperand(N0, PVT, Replace);
952 if (N0.getNode() == 0)
955 AddToWorkList(N0.getNode());
957 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
959 DEBUG(dbgs() << "\nPromoting ";
960 Op.getNode()->dump(&DAG));
962 return DAG.getNode(ISD::TRUNCATE, dl, VT,
963 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
968 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
969 if (!LegalOperations)
972 EVT VT = Op.getValueType();
973 if (VT.isVector() || !VT.isInteger())
976 // If operation type is 'undesirable', e.g. i16 on x86, consider
978 unsigned Opc = Op.getOpcode();
979 if (TLI.isTypeDesirableForOp(Opc, VT))
983 // Consult target whether it is a good idea to promote this operation and
984 // what's the right type to promote it to.
985 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
986 assert(PVT != VT && "Don't know what type to promote to!");
987 // fold (aext (aext x)) -> (aext x)
988 // fold (aext (zext x)) -> (zext x)
989 // fold (aext (sext x)) -> (sext x)
990 DEBUG(dbgs() << "\nPromoting ";
991 Op.getNode()->dump(&DAG));
992 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
997 bool DAGCombiner::PromoteLoad(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1018 SDNode *N = Op.getNode();
1019 LoadSDNode *LD = cast<LoadSDNode>(N);
1020 EVT MemVT = LD->getMemoryVT();
1021 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1022 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1024 : LD->getExtensionType();
1025 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1026 LD->getChain(), LD->getBasePtr(),
1027 MemVT, LD->getMemOperand());
1028 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1030 DEBUG(dbgs() << "\nPromoting ";
1033 Result.getNode()->dump(&DAG);
1035 WorkListRemover DeadNodes(*this);
1036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1037 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1038 removeFromWorkList(N);
1040 AddToWorkList(Result.getNode());
1047 //===----------------------------------------------------------------------===//
1048 // Main DAG Combiner implementation
1049 //===----------------------------------------------------------------------===//
1051 void DAGCombiner::Run(CombineLevel AtLevel) {
1052 // set the instance variables, so that the various visit routines may use it.
1054 LegalOperations = Level >= AfterLegalizeVectorOps;
1055 LegalTypes = Level >= AfterLegalizeTypes;
1057 // Add all the dag nodes to the worklist.
1058 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1059 E = DAG.allnodes_end(); I != E; ++I)
1062 // Create a dummy node (which is not added to allnodes), that adds a reference
1063 // to the root node, preventing it from being deleted, and tracking any
1064 // changes of the root.
1065 HandleSDNode Dummy(DAG.getRoot());
1067 // The root of the dag may dangle to deleted nodes until the dag combiner is
1068 // done. Set it to null to avoid confusion.
1069 DAG.setRoot(SDValue());
1071 // while the worklist isn't empty, find a node and
1072 // try and combine it.
1073 while (!WorkListContents.empty()) {
1075 // The WorkListOrder holds the SDNodes in order, but it may contain
1077 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1078 // worklist *should* contain, and check the node we want to visit is should
1079 // actually be visited.
1081 N = WorkListOrder.pop_back_val();
1082 } while (!WorkListContents.erase(N));
1084 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1085 // N is deleted from the DAG, since they too may now be dead or may have a
1086 // reduced number of uses, allowing other xforms.
1087 if (N->use_empty() && N != &Dummy) {
1088 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1089 AddToWorkList(N->getOperand(i).getNode());
1095 SDValue RV = combine(N);
1097 if (RV.getNode() == 0)
1102 // If we get back the same node we passed in, rather than a new node or
1103 // zero, we know that the node must have defined multiple values and
1104 // CombineTo was used. Since CombineTo takes care of the worklist
1105 // mechanics for us, we have no work to do in this case.
1106 if (RV.getNode() == N)
1109 assert(N->getOpcode() != ISD::DELETED_NODE &&
1110 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1111 "Node was deleted but visit returned new node!");
1113 DEBUG(dbgs() << "\nReplacing.3 ";
1115 dbgs() << "\nWith: ";
1116 RV.getNode()->dump(&DAG);
1119 // Transfer debug value.
1120 DAG.TransferDbgValues(SDValue(N, 0), RV);
1121 WorkListRemover DeadNodes(*this);
1122 if (N->getNumValues() == RV.getNode()->getNumValues())
1123 DAG.ReplaceAllUsesWith(N, RV.getNode());
1125 assert(N->getValueType(0) == RV.getValueType() &&
1126 N->getNumValues() == 1 && "Type mismatch");
1128 DAG.ReplaceAllUsesWith(N, &OpV);
1131 // Push the new node and any users onto the worklist
1132 AddToWorkList(RV.getNode());
1133 AddUsersToWorkList(RV.getNode());
1135 // Add any uses of the old node to the worklist in case this node is the
1136 // last one that uses them. They may become dead after this node is
1138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1139 AddToWorkList(N->getOperand(i).getNode());
1141 // Finally, if the node is now dead, remove it from the graph. The node
1142 // may not be dead if the replacement process recursively simplified to
1143 // something else needing this node.
1144 if (N->use_empty()) {
1145 // Nodes can be reintroduced into the worklist. Make sure we do not
1146 // process a node that has been replaced.
1147 removeFromWorkList(N);
1149 // Finally, since the node is now dead, remove it from the graph.
1154 // If the root changed (e.g. it was a dead load, update the root).
1155 DAG.setRoot(Dummy.getValue());
1156 DAG.RemoveDeadNodes();
1159 SDValue DAGCombiner::visit(SDNode *N) {
1160 switch (N->getOpcode()) {
1162 case ISD::TokenFactor: return visitTokenFactor(N);
1163 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1164 case ISD::ADD: return visitADD(N);
1165 case ISD::SUB: return visitSUB(N);
1166 case ISD::ADDC: return visitADDC(N);
1167 case ISD::SUBC: return visitSUBC(N);
1168 case ISD::ADDE: return visitADDE(N);
1169 case ISD::SUBE: return visitSUBE(N);
1170 case ISD::MUL: return visitMUL(N);
1171 case ISD::SDIV: return visitSDIV(N);
1172 case ISD::UDIV: return visitUDIV(N);
1173 case ISD::SREM: return visitSREM(N);
1174 case ISD::UREM: return visitUREM(N);
1175 case ISD::MULHU: return visitMULHU(N);
1176 case ISD::MULHS: return visitMULHS(N);
1177 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1178 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1179 case ISD::SMULO: return visitSMULO(N);
1180 case ISD::UMULO: return visitUMULO(N);
1181 case ISD::SDIVREM: return visitSDIVREM(N);
1182 case ISD::UDIVREM: return visitUDIVREM(N);
1183 case ISD::AND: return visitAND(N);
1184 case ISD::OR: return visitOR(N);
1185 case ISD::XOR: return visitXOR(N);
1186 case ISD::SHL: return visitSHL(N);
1187 case ISD::SRA: return visitSRA(N);
1188 case ISD::SRL: return visitSRL(N);
1189 case ISD::CTLZ: return visitCTLZ(N);
1190 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1191 case ISD::CTTZ: return visitCTTZ(N);
1192 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1193 case ISD::CTPOP: return visitCTPOP(N);
1194 case ISD::SELECT: return visitSELECT(N);
1195 case ISD::VSELECT: return visitVSELECT(N);
1196 case ISD::SELECT_CC: return visitSELECT_CC(N);
1197 case ISD::SETCC: return visitSETCC(N);
1198 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1199 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1200 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1201 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1202 case ISD::TRUNCATE: return visitTRUNCATE(N);
1203 case ISD::BITCAST: return visitBITCAST(N);
1204 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1205 case ISD::FADD: return visitFADD(N);
1206 case ISD::FSUB: return visitFSUB(N);
1207 case ISD::FMUL: return visitFMUL(N);
1208 case ISD::FMA: return visitFMA(N);
1209 case ISD::FDIV: return visitFDIV(N);
1210 case ISD::FREM: return visitFREM(N);
1211 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1212 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1213 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1214 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1215 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1216 case ISD::FP_ROUND: return visitFP_ROUND(N);
1217 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1218 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1219 case ISD::FNEG: return visitFNEG(N);
1220 case ISD::FABS: return visitFABS(N);
1221 case ISD::FFLOOR: return visitFFLOOR(N);
1222 case ISD::FCEIL: return visitFCEIL(N);
1223 case ISD::FTRUNC: return visitFTRUNC(N);
1224 case ISD::BRCOND: return visitBRCOND(N);
1225 case ISD::BR_CC: return visitBR_CC(N);
1226 case ISD::LOAD: return visitLOAD(N);
1227 case ISD::STORE: return visitSTORE(N);
1228 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1229 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1230 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1231 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1232 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1233 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1234 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1239 SDValue DAGCombiner::combine(SDNode *N) {
1240 SDValue RV = visit(N);
1242 // If nothing happened, try a target-specific DAG combine.
1243 if (RV.getNode() == 0) {
1244 assert(N->getOpcode() != ISD::DELETED_NODE &&
1245 "Node was deleted but visit returned NULL!");
1247 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1248 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1250 // Expose the DAG combiner to the target combiner impls.
1251 TargetLowering::DAGCombinerInfo
1252 DagCombineInfo(DAG, Level, false, this);
1254 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1258 // If nothing happened still, try promoting the operation.
1259 if (RV.getNode() == 0) {
1260 switch (N->getOpcode()) {
1268 RV = PromoteIntBinOp(SDValue(N, 0));
1273 RV = PromoteIntShiftOp(SDValue(N, 0));
1275 case ISD::SIGN_EXTEND:
1276 case ISD::ZERO_EXTEND:
1277 case ISD::ANY_EXTEND:
1278 RV = PromoteExtend(SDValue(N, 0));
1281 if (PromoteLoad(SDValue(N, 0)))
1287 // If N is a commutative binary node, try commuting it to enable more
1289 if (RV.getNode() == 0 &&
1290 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1291 N->getNumValues() == 1) {
1292 SDValue N0 = N->getOperand(0);
1293 SDValue N1 = N->getOperand(1);
1295 // Constant operands are canonicalized to RHS.
1296 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1297 SDValue Ops[] = { N1, N0 };
1298 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1301 return SDValue(CSENode, 0);
1308 /// getInputChainForNode - Given a node, return its input chain if it has one,
1309 /// otherwise return a null sd operand.
1310 static SDValue getInputChainForNode(SDNode *N) {
1311 if (unsigned NumOps = N->getNumOperands()) {
1312 if (N->getOperand(0).getValueType() == MVT::Other)
1313 return N->getOperand(0);
1314 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1315 return N->getOperand(NumOps-1);
1316 for (unsigned i = 1; i < NumOps-1; ++i)
1317 if (N->getOperand(i).getValueType() == MVT::Other)
1318 return N->getOperand(i);
1323 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1324 // If N has two operands, where one has an input chain equal to the other,
1325 // the 'other' chain is redundant.
1326 if (N->getNumOperands() == 2) {
1327 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1328 return N->getOperand(0);
1329 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1330 return N->getOperand(1);
1333 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1334 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1335 SmallPtrSet<SDNode*, 16> SeenOps;
1336 bool Changed = false; // If we should replace this token factor.
1338 // Start out with this token factor.
1341 // Iterate through token factors. The TFs grows when new token factors are
1343 for (unsigned i = 0; i < TFs.size(); ++i) {
1344 SDNode *TF = TFs[i];
1346 // Check each of the operands.
1347 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1348 SDValue Op = TF->getOperand(i);
1350 switch (Op.getOpcode()) {
1351 case ISD::EntryToken:
1352 // Entry tokens don't need to be added to the list. They are
1357 case ISD::TokenFactor:
1358 if (Op.hasOneUse() &&
1359 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1360 // Queue up for processing.
1361 TFs.push_back(Op.getNode());
1362 // Clean up in case the token factor is removed.
1363 AddToWorkList(Op.getNode());
1370 // Only add if it isn't already in the list.
1371 if (SeenOps.insert(Op.getNode()))
1382 // If we've change things around then replace token factor.
1385 // The entry token is the only possible outcome.
1386 Result = DAG.getEntryNode();
1388 // New and improved token factor.
1389 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1390 MVT::Other, &Ops[0], Ops.size());
1393 // Don't add users to work list.
1394 return CombineTo(N, Result, false);
1400 /// MERGE_VALUES can always be eliminated.
1401 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1402 WorkListRemover DeadNodes(*this);
1403 // Replacing results may cause a different MERGE_VALUES to suddenly
1404 // be CSE'd with N, and carry its uses with it. Iterate until no
1405 // uses remain, to ensure that the node can be safely deleted.
1406 // First add the users of this node to the work list so that they
1407 // can be tried again once they have new operands.
1408 AddUsersToWorkList(N);
1410 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1411 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1412 } while (!N->use_empty());
1413 removeFromWorkList(N);
1415 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1419 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1420 SelectionDAG &DAG) {
1421 EVT VT = N0.getValueType();
1422 SDValue N00 = N0.getOperand(0);
1423 SDValue N01 = N0.getOperand(1);
1424 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1426 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1427 isa<ConstantSDNode>(N00.getOperand(1))) {
1428 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1429 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1430 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1431 N00.getOperand(0), N01),
1432 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1433 N00.getOperand(1), N01));
1434 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1440 SDValue DAGCombiner::visitADD(SDNode *N) {
1441 SDValue N0 = N->getOperand(0);
1442 SDValue N1 = N->getOperand(1);
1443 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1445 EVT VT = N0.getValueType();
1448 if (VT.isVector()) {
1449 SDValue FoldedVOp = SimplifyVBinOp(N);
1450 if (FoldedVOp.getNode()) return FoldedVOp;
1452 // fold (add x, 0) -> x, vector edition
1453 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1455 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1459 // fold (add x, undef) -> undef
1460 if (N0.getOpcode() == ISD::UNDEF)
1462 if (N1.getOpcode() == ISD::UNDEF)
1464 // fold (add c1, c2) -> c1+c2
1466 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1467 // canonicalize constant to RHS
1469 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1470 // fold (add x, 0) -> x
1471 if (N1C && N1C->isNullValue())
1473 // fold (add Sym, c) -> Sym+c
1474 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1475 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1476 GA->getOpcode() == ISD::GlobalAddress)
1477 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1479 (uint64_t)N1C->getSExtValue());
1480 // fold ((c1-A)+c2) -> (c1+c2)-A
1481 if (N1C && N0.getOpcode() == ISD::SUB)
1482 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1483 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1484 DAG.getConstant(N1C->getAPIntValue()+
1485 N0C->getAPIntValue(), VT),
1488 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1489 if (RADD.getNode() != 0)
1491 // fold ((0-A) + B) -> B-A
1492 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1493 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1495 // fold (A + (0-B)) -> A-B
1496 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1497 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1498 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1499 // fold (A+(B-A)) -> B
1500 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1501 return N1.getOperand(0);
1502 // fold ((B-A)+A) -> B
1503 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1504 return N0.getOperand(0);
1505 // fold (A+(B-(A+C))) to (B-C)
1506 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1507 N0 == N1.getOperand(1).getOperand(0))
1508 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1509 N1.getOperand(1).getOperand(1));
1510 // fold (A+(B-(C+A))) to (B-C)
1511 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1512 N0 == N1.getOperand(1).getOperand(1))
1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1514 N1.getOperand(1).getOperand(0));
1515 // fold (A+((B-A)+or-C)) to (B+or-C)
1516 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1517 N1.getOperand(0).getOpcode() == ISD::SUB &&
1518 N0 == N1.getOperand(0).getOperand(1))
1519 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1520 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1522 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1523 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1524 SDValue N00 = N0.getOperand(0);
1525 SDValue N01 = N0.getOperand(1);
1526 SDValue N10 = N1.getOperand(0);
1527 SDValue N11 = N1.getOperand(1);
1529 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1530 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1531 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1532 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1535 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1536 return SDValue(N, 0);
1538 // fold (a+b) -> (a|b) iff a and b share no bits.
1539 if (VT.isInteger() && !VT.isVector()) {
1540 APInt LHSZero, LHSOne;
1541 APInt RHSZero, RHSOne;
1542 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1544 if (LHSZero.getBoolValue()) {
1545 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1547 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1548 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1549 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1550 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1551 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1556 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1557 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1558 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1559 if (Result.getNode()) return Result;
1561 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1562 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1563 if (Result.getNode()) return Result;
1566 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1567 if (N1.getOpcode() == ISD::SHL &&
1568 N1.getOperand(0).getOpcode() == ISD::SUB)
1569 if (ConstantSDNode *C =
1570 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1571 if (C->getAPIntValue() == 0)
1572 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1573 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1574 N1.getOperand(0).getOperand(1),
1576 if (N0.getOpcode() == ISD::SHL &&
1577 N0.getOperand(0).getOpcode() == ISD::SUB)
1578 if (ConstantSDNode *C =
1579 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1580 if (C->getAPIntValue() == 0)
1581 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1582 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1583 N0.getOperand(0).getOperand(1),
1586 if (N1.getOpcode() == ISD::AND) {
1587 SDValue AndOp0 = N1.getOperand(0);
1588 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1589 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1590 unsigned DestBits = VT.getScalarType().getSizeInBits();
1592 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1593 // and similar xforms where the inner op is either ~0 or 0.
1594 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1596 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1600 // add (sext i1), X -> sub X, (zext i1)
1601 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1602 N0.getOperand(0).getValueType() == MVT::i1 &&
1603 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1605 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1606 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1612 SDValue DAGCombiner::visitADDC(SDNode *N) {
1613 SDValue N0 = N->getOperand(0);
1614 SDValue N1 = N->getOperand(1);
1615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1617 EVT VT = N0.getValueType();
1619 // If the flag result is dead, turn this into an ADD.
1620 if (!N->hasAnyUseOfValue(1))
1621 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1622 DAG.getNode(ISD::CARRY_FALSE,
1623 SDLoc(N), MVT::Glue));
1625 // canonicalize constant to RHS.
1627 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1629 // fold (addc x, 0) -> x + no carry out
1630 if (N1C && N1C->isNullValue())
1631 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1632 SDLoc(N), MVT::Glue));
1634 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1635 APInt LHSZero, LHSOne;
1636 APInt RHSZero, RHSOne;
1637 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1639 if (LHSZero.getBoolValue()) {
1640 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1642 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1643 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1644 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1645 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1646 DAG.getNode(ISD::CARRY_FALSE,
1647 SDLoc(N), MVT::Glue));
1653 SDValue DAGCombiner::visitADDE(SDNode *N) {
1654 SDValue N0 = N->getOperand(0);
1655 SDValue N1 = N->getOperand(1);
1656 SDValue CarryIn = N->getOperand(2);
1657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1660 // canonicalize constant to RHS
1662 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1665 // fold (adde x, y, false) -> (addc x, y)
1666 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1667 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1672 // Since it may not be valid to emit a fold to zero for vector initializers
1673 // check if we can before folding.
1674 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1676 bool LegalOperations, bool LegalTypes) {
1678 return DAG.getConstant(0, VT);
1679 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1680 return DAG.getConstant(0, VT);
1684 SDValue DAGCombiner::visitSUB(SDNode *N) {
1685 SDValue N0 = N->getOperand(0);
1686 SDValue N1 = N->getOperand(1);
1687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1689 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1690 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1691 EVT VT = N0.getValueType();
1694 if (VT.isVector()) {
1695 SDValue FoldedVOp = SimplifyVBinOp(N);
1696 if (FoldedVOp.getNode()) return FoldedVOp;
1698 // fold (sub x, 0) -> x, vector edition
1699 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1703 // fold (sub x, x) -> 0
1704 // FIXME: Refactor this and xor and other similar operations together.
1706 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1707 // fold (sub c1, c2) -> c1-c2
1709 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1710 // fold (sub x, c) -> (add x, -c)
1712 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1713 DAG.getConstant(-N1C->getAPIntValue(), VT));
1714 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1715 if (N0C && N0C->isAllOnesValue())
1716 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1717 // fold A-(A-B) -> B
1718 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1719 return N1.getOperand(1);
1720 // fold (A+B)-A -> B
1721 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1722 return N0.getOperand(1);
1723 // fold (A+B)-B -> A
1724 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1725 return N0.getOperand(0);
1726 // fold C2-(A+C1) -> (C2-C1)-A
1727 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1728 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1730 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1733 // fold ((A+(B+or-C))-B) -> A+or-C
1734 if (N0.getOpcode() == ISD::ADD &&
1735 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1736 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1737 N0.getOperand(1).getOperand(0) == N1)
1738 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1739 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1740 // fold ((A+(C+B))-B) -> A+C
1741 if (N0.getOpcode() == ISD::ADD &&
1742 N0.getOperand(1).getOpcode() == ISD::ADD &&
1743 N0.getOperand(1).getOperand(1) == N1)
1744 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1745 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1746 // fold ((A-(B-C))-C) -> A-B
1747 if (N0.getOpcode() == ISD::SUB &&
1748 N0.getOperand(1).getOpcode() == ISD::SUB &&
1749 N0.getOperand(1).getOperand(1) == N1)
1750 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1751 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1753 // If either operand of a sub is undef, the result is undef
1754 if (N0.getOpcode() == ISD::UNDEF)
1756 if (N1.getOpcode() == ISD::UNDEF)
1759 // If the relocation model supports it, consider symbol offsets.
1760 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1761 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1762 // fold (sub Sym, c) -> Sym-c
1763 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1764 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1766 (uint64_t)N1C->getSExtValue());
1767 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1768 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1769 if (GA->getGlobal() == GB->getGlobal())
1770 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1777 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1778 SDValue N0 = N->getOperand(0);
1779 SDValue N1 = N->getOperand(1);
1780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1781 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1782 EVT VT = N0.getValueType();
1784 // If the flag result is dead, turn this into an SUB.
1785 if (!N->hasAnyUseOfValue(1))
1786 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1787 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1790 // fold (subc x, x) -> 0 + no borrow
1792 return CombineTo(N, DAG.getConstant(0, VT),
1793 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1796 // fold (subc x, 0) -> x + no borrow
1797 if (N1C && N1C->isNullValue())
1798 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1801 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1802 if (N0C && N0C->isAllOnesValue())
1803 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1804 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1810 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1811 SDValue N0 = N->getOperand(0);
1812 SDValue N1 = N->getOperand(1);
1813 SDValue CarryIn = N->getOperand(2);
1815 // fold (sube x, y, false) -> (subc x, y)
1816 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1817 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1822 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1823 /// elements are all the same constant or undefined.
1824 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1825 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1830 unsigned SplatBitSize;
1832 EVT EltVT = N->getValueType(0).getVectorElementType();
1833 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1835 EltVT.getSizeInBits() >= SplatBitSize);
1838 SDValue DAGCombiner::visitMUL(SDNode *N) {
1839 SDValue N0 = N->getOperand(0);
1840 SDValue N1 = N->getOperand(1);
1841 EVT VT = N0.getValueType();
1843 // fold (mul x, undef) -> 0
1844 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1845 return DAG.getConstant(0, VT);
1847 bool N0IsConst = false;
1848 bool N1IsConst = false;
1849 APInt ConstValue0, ConstValue1;
1851 if (VT.isVector()) {
1852 SDValue FoldedVOp = SimplifyVBinOp(N);
1853 if (FoldedVOp.getNode()) return FoldedVOp;
1855 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1858 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1859 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1861 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1862 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1866 // fold (mul c1, c2) -> c1*c2
1867 if (N0IsConst && N1IsConst)
1868 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1870 // canonicalize constant to RHS
1871 if (N0IsConst && !N1IsConst)
1872 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1873 // fold (mul x, 0) -> 0
1874 if (N1IsConst && ConstValue1 == 0)
1876 // We require a splat of the entire scalar bit width for non-contiguous
1879 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1880 // fold (mul x, 1) -> x
1881 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1883 // fold (mul x, -1) -> 0-x
1884 if (N1IsConst && ConstValue1.isAllOnesValue())
1885 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1886 DAG.getConstant(0, VT), N0);
1887 // fold (mul x, (1 << c)) -> x << c
1888 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1890 DAG.getConstant(ConstValue1.logBase2(),
1891 getShiftAmountTy(N0.getValueType())));
1892 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1893 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1894 unsigned Log2Val = (-ConstValue1).logBase2();
1895 // FIXME: If the input is something that is easily negated (e.g. a
1896 // single-use add), we should put the negate there.
1897 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1898 DAG.getConstant(0, VT),
1899 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1900 DAG.getConstant(Log2Val,
1901 getShiftAmountTy(N0.getValueType()))));
1905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1906 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1907 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908 isa<ConstantSDNode>(N0.getOperand(1)))) {
1909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910 N1, N0.getOperand(1));
1911 AddToWorkList(C3.getNode());
1912 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913 N0.getOperand(0), C3);
1916 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1919 SDValue Sh(0,0), Y(0,0);
1920 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1921 if (N0.getOpcode() == ISD::SHL &&
1922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923 isa<ConstantSDNode>(N0.getOperand(1))) &&
1924 N0.getNode()->hasOneUse()) {
1926 } else if (N1.getOpcode() == ISD::SHL &&
1927 isa<ConstantSDNode>(N1.getOperand(1)) &&
1928 N1.getNode()->hasOneUse()) {
1933 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1934 Sh.getOperand(0), Y);
1935 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1936 Mul, Sh.getOperand(1));
1940 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1941 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))))
1944 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1946 N0.getOperand(0), N1),
1947 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1948 N0.getOperand(1), N1));
1951 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1952 if (RMUL.getNode() != 0)
1958 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959 SDValue N0 = N->getOperand(0);
1960 SDValue N1 = N->getOperand(1);
1961 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1963 EVT VT = N->getValueType(0);
1966 if (VT.isVector()) {
1967 SDValue FoldedVOp = SimplifyVBinOp(N);
1968 if (FoldedVOp.getNode()) return FoldedVOp;
1971 // fold (sdiv c1, c2) -> c1/c2
1972 if (N0C && N1C && !N1C->isNullValue())
1973 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1974 // fold (sdiv X, 1) -> X
1975 if (N1C && N1C->getAPIntValue() == 1LL)
1977 // fold (sdiv X, -1) -> 0-X
1978 if (N1C && N1C->isAllOnesValue())
1979 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1980 DAG.getConstant(0, VT), N0);
1981 // If we know the sign bits of both operands are zero, strength reduce to a
1982 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1983 if (!VT.isVector()) {
1984 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1985 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1988 // fold (sdiv X, pow2) -> simple ops after legalize
1989 if (N1C && !N1C->isNullValue() &&
1990 (N1C->getAPIntValue().isPowerOf2() ||
1991 (-N1C->getAPIntValue()).isPowerOf2())) {
1992 // If dividing by powers of two is cheap, then don't perform the following
1994 if (TLI.isPow2DivCheap())
1997 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1999 // Splat the sign bit into the register
2000 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2001 DAG.getConstant(VT.getSizeInBits()-1,
2002 getShiftAmountTy(N0.getValueType())));
2003 AddToWorkList(SGN.getNode());
2005 // Add (N0 < 0) ? abs2 - 1 : 0;
2006 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2007 DAG.getConstant(VT.getSizeInBits() - lg2,
2008 getShiftAmountTy(SGN.getValueType())));
2009 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2010 AddToWorkList(SRL.getNode());
2011 AddToWorkList(ADD.getNode()); // Divide by pow2
2012 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2013 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2015 // If we're dividing by a positive value, we're done. Otherwise, we must
2016 // negate the result.
2017 if (N1C->getAPIntValue().isNonNegative())
2020 AddToWorkList(SRA.getNode());
2021 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2022 DAG.getConstant(0, VT), SRA);
2025 // if integer divide is expensive and we satisfy the requirements, emit an
2026 // alternate sequence.
2027 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2028 SDValue Op = BuildSDIV(N);
2029 if (Op.getNode()) return Op;
2033 if (N0.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, VT);
2035 // X / undef -> undef
2036 if (N1.getOpcode() == ISD::UNDEF)
2042 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2043 SDValue N0 = N->getOperand(0);
2044 SDValue N1 = N->getOperand(1);
2045 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2047 EVT VT = N->getValueType(0);
2050 if (VT.isVector()) {
2051 SDValue FoldedVOp = SimplifyVBinOp(N);
2052 if (FoldedVOp.getNode()) return FoldedVOp;
2055 // fold (udiv c1, c2) -> c1/c2
2056 if (N0C && N1C && !N1C->isNullValue())
2057 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2058 // fold (udiv x, (1 << c)) -> x >>u c
2059 if (N1C && N1C->getAPIntValue().isPowerOf2())
2060 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2061 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2062 getShiftAmountTy(N0.getValueType())));
2063 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2064 if (N1.getOpcode() == ISD::SHL) {
2065 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2066 if (SHC->getAPIntValue().isPowerOf2()) {
2067 EVT ADDVT = N1.getOperand(1).getValueType();
2068 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2070 DAG.getConstant(SHC->getAPIntValue()
2073 AddToWorkList(Add.getNode());
2074 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2078 // fold (udiv x, c) -> alternate
2079 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2080 SDValue Op = BuildUDIV(N);
2081 if (Op.getNode()) return Op;
2085 if (N0.getOpcode() == ISD::UNDEF)
2086 return DAG.getConstant(0, VT);
2087 // X / undef -> undef
2088 if (N1.getOpcode() == ISD::UNDEF)
2094 SDValue DAGCombiner::visitSREM(SDNode *N) {
2095 SDValue N0 = N->getOperand(0);
2096 SDValue N1 = N->getOperand(1);
2097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2099 EVT VT = N->getValueType(0);
2101 // fold (srem c1, c2) -> c1%c2
2102 if (N0C && N1C && !N1C->isNullValue())
2103 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2104 // If we know the sign bits of both operands are zero, strength reduce to a
2105 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2106 if (!VT.isVector()) {
2107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2111 // If X/C can be simplified by the division-by-constant logic, lower
2112 // X%C to the equivalent of X-X/C*C.
2113 if (N1C && !N1C->isNullValue()) {
2114 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2115 AddToWorkList(Div.getNode());
2116 SDValue OptimizedDiv = combine(Div.getNode());
2117 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2121 AddToWorkList(Mul.getNode());
2127 if (N0.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
2129 // X % undef -> undef
2130 if (N1.getOpcode() == ISD::UNDEF)
2136 SDValue DAGCombiner::visitUREM(SDNode *N) {
2137 SDValue N0 = N->getOperand(0);
2138 SDValue N1 = N->getOperand(1);
2139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2141 EVT VT = N->getValueType(0);
2143 // fold (urem c1, c2) -> c1%c2
2144 if (N0C && N1C && !N1C->isNullValue())
2145 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2146 // fold (urem x, pow2) -> (and x, pow2-1)
2147 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2149 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2150 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2151 if (N1.getOpcode() == ISD::SHL) {
2152 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2153 if (SHC->getAPIntValue().isPowerOf2()) {
2155 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2156 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2158 AddToWorkList(Add.getNode());
2159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2164 // If X/C can be simplified by the division-by-constant logic, lower
2165 // X%C to the equivalent of X-X/C*C.
2166 if (N1C && !N1C->isNullValue()) {
2167 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2168 AddToWorkList(Div.getNode());
2169 SDValue OptimizedDiv = combine(Div.getNode());
2170 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2171 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2173 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2174 AddToWorkList(Mul.getNode());
2180 if (N0.getOpcode() == ISD::UNDEF)
2181 return DAG.getConstant(0, VT);
2182 // X % undef -> undef
2183 if (N1.getOpcode() == ISD::UNDEF)
2189 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2190 SDValue N0 = N->getOperand(0);
2191 SDValue N1 = N->getOperand(1);
2192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2193 EVT VT = N->getValueType(0);
2196 // fold (mulhs x, 0) -> 0
2197 if (N1C && N1C->isNullValue())
2199 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2200 if (N1C && N1C->getAPIntValue() == 1)
2201 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2202 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2203 getShiftAmountTy(N0.getValueType())));
2204 // fold (mulhs x, undef) -> 0
2205 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2206 return DAG.getConstant(0, VT);
2208 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2210 if (VT.isSimple() && !VT.isVector()) {
2211 MVT Simple = VT.getSimpleVT();
2212 unsigned SimpleSize = Simple.getSizeInBits();
2213 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2214 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2215 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2216 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2217 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2218 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2219 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2220 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2227 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2228 SDValue N0 = N->getOperand(0);
2229 SDValue N1 = N->getOperand(1);
2230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2231 EVT VT = N->getValueType(0);
2234 // fold (mulhu x, 0) -> 0
2235 if (N1C && N1C->isNullValue())
2237 // fold (mulhu x, 1) -> 0
2238 if (N1C && N1C->getAPIntValue() == 1)
2239 return DAG.getConstant(0, N0.getValueType());
2240 // fold (mulhu x, undef) -> 0
2241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2242 return DAG.getConstant(0, VT);
2244 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2246 if (VT.isSimple() && !VT.isVector()) {
2247 MVT Simple = VT.getSimpleVT();
2248 unsigned SimpleSize = Simple.getSizeInBits();
2249 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2250 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2251 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2252 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2253 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2254 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2255 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2256 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2263 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2264 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2265 /// that are being performed. Return true if a simplification was made.
2267 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2269 // If the high half is not needed, just compute the low half.
2270 bool HiExists = N->hasAnyUseOfValue(1);
2272 (!LegalOperations ||
2273 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2274 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275 N->op_begin(), N->getNumOperands());
2276 return CombineTo(N, Res, Res);
2279 // If the low half is not needed, just compute the high half.
2280 bool LoExists = N->hasAnyUseOfValue(0);
2282 (!LegalOperations ||
2283 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2284 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2285 N->op_begin(), N->getNumOperands());
2286 return CombineTo(N, Res, Res);
2289 // If both halves are used, return as it is.
2290 if (LoExists && HiExists)
2293 // If the two computed results can be simplified separately, separate them.
2295 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296 N->op_begin(), N->getNumOperands());
2297 AddToWorkList(Lo.getNode());
2298 SDValue LoOpt = combine(Lo.getNode());
2299 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2300 (!LegalOperations ||
2301 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2302 return CombineTo(N, LoOpt, LoOpt);
2306 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2307 N->op_begin(), N->getNumOperands());
2308 AddToWorkList(Hi.getNode());
2309 SDValue HiOpt = combine(Hi.getNode());
2310 if (HiOpt.getNode() && HiOpt != Hi &&
2311 (!LegalOperations ||
2312 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2313 return CombineTo(N, HiOpt, HiOpt);
2319 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2321 if (Res.getNode()) return Res;
2323 EVT VT = N->getValueType(0);
2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2349 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2350 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2351 if (Res.getNode()) return Res;
2353 EVT VT = N->getValueType(0);
2356 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2358 if (VT.isSimple() && !VT.isVector()) {
2359 MVT Simple = VT.getSimpleVT();
2360 unsigned SimpleSize = Simple.getSizeInBits();
2361 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2362 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2363 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2364 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2365 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2366 // Compute the high part as N1.
2367 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2368 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2369 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2370 // Compute the low part as N0.
2371 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2372 return CombineTo(N, Lo, Hi);
2379 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2380 // (smulo x, 2) -> (saddo x, x)
2381 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2382 if (C2->getAPIntValue() == 2)
2383 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2384 N->getOperand(0), N->getOperand(0));
2389 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2390 // (umulo x, 2) -> (uaddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
2393 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2394 N->getOperand(0), N->getOperand(0));
2399 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2400 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2401 if (Res.getNode()) return Res;
2406 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2408 if (Res.getNode()) return Res;
2413 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2414 /// two operands of the same opcode, try to simplify it.
2415 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2416 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2417 EVT VT = N0.getValueType();
2418 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2420 // Bail early if none of these transforms apply.
2421 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2423 // For each of OP in AND/OR/XOR:
2424 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2425 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2426 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2427 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2429 // do not sink logical op inside of a vector extend, since it may combine
2431 EVT Op0VT = N0.getOperand(0).getValueType();
2432 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2433 N0.getOpcode() == ISD::SIGN_EXTEND ||
2434 // Avoid infinite looping with PromoteIntBinOp.
2435 (N0.getOpcode() == ISD::ANY_EXTEND &&
2436 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2437 (N0.getOpcode() == ISD::TRUNCATE &&
2438 (!TLI.isZExtFree(VT, Op0VT) ||
2439 !TLI.isTruncateFree(Op0VT, VT)) &&
2440 TLI.isTypeLegal(Op0VT))) &&
2442 Op0VT == N1.getOperand(0).getValueType() &&
2443 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2444 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2445 N0.getOperand(0).getValueType(),
2446 N0.getOperand(0), N1.getOperand(0));
2447 AddToWorkList(ORNode.getNode());
2448 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2451 // For each of OP in SHL/SRL/SRA/AND...
2452 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2453 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2454 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2455 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2456 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2457 N0.getOperand(1) == N1.getOperand(1)) {
2458 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2459 N0.getOperand(0).getValueType(),
2460 N0.getOperand(0), N1.getOperand(0));
2461 AddToWorkList(ORNode.getNode());
2462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2463 ORNode, N0.getOperand(1));
2466 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2467 // Only perform this optimization after type legalization and before
2468 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2469 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2470 // we don't want to undo this promotion.
2471 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2473 if ((N0.getOpcode() == ISD::BITCAST ||
2474 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2475 Level == AfterLegalizeTypes) {
2476 SDValue In0 = N0.getOperand(0);
2477 SDValue In1 = N1.getOperand(0);
2478 EVT In0Ty = In0.getValueType();
2479 EVT In1Ty = In1.getValueType();
2481 // If both incoming values are integers, and the original types are the
2483 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2484 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2485 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2486 AddToWorkList(Op.getNode());
2491 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2492 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2493 // If both shuffles use the same mask, and both shuffle within a single
2494 // vector, then it is worthwhile to move the swizzle after the operation.
2495 // The type-legalizer generates this pattern when loading illegal
2496 // vector types from memory. In many cases this allows additional shuffle
2498 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2499 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2500 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2501 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2502 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2504 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2505 "Inputs to shuffles are not the same type");
2507 unsigned NumElts = VT.getVectorNumElements();
2509 // Check that both shuffles use the same mask. The masks are known to be of
2510 // the same length because the result vector type is the same.
2511 bool SameMask = true;
2512 for (unsigned i = 0; i != NumElts; ++i) {
2513 int Idx0 = SVN0->getMaskElt(i);
2514 int Idx1 = SVN1->getMaskElt(i);
2522 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2523 N0.getOperand(0), N1.getOperand(0));
2524 AddToWorkList(Op.getNode());
2525 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2526 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2533 SDValue DAGCombiner::visitAND(SDNode *N) {
2534 SDValue N0 = N->getOperand(0);
2535 SDValue N1 = N->getOperand(1);
2536 SDValue LL, LR, RL, RR, CC0, CC1;
2537 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2538 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2539 EVT VT = N1.getValueType();
2540 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2543 if (VT.isVector()) {
2544 SDValue FoldedVOp = SimplifyVBinOp(N);
2545 if (FoldedVOp.getNode()) return FoldedVOp;
2547 // fold (and x, 0) -> 0, vector edition
2548 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2550 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2553 // fold (and x, -1) -> x, vector edition
2554 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2556 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2560 // fold (and x, undef) -> 0
2561 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2562 return DAG.getConstant(0, VT);
2563 // fold (and c1, c2) -> c1&c2
2565 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2566 // canonicalize constant to RHS
2568 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2569 // fold (and x, -1) -> x
2570 if (N1C && N1C->isAllOnesValue())
2572 // if (and x, c) is known to be zero, return 0
2573 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2574 APInt::getAllOnesValue(BitWidth)))
2575 return DAG.getConstant(0, VT);
2577 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2578 if (RAND.getNode() != 0)
2580 // fold (and (or x, C), D) -> D if (C & D) == D
2581 if (N1C && N0.getOpcode() == ISD::OR)
2582 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2583 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2585 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2586 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2587 SDValue N0Op0 = N0.getOperand(0);
2588 APInt Mask = ~N1C->getAPIntValue();
2589 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2590 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2591 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2592 N0.getValueType(), N0Op0);
2594 // Replace uses of the AND with uses of the Zero extend node.
2597 // We actually want to replace all uses of the any_extend with the
2598 // zero_extend, to avoid duplicating things. This will later cause this
2599 // AND to be folded.
2600 CombineTo(N0.getNode(), Zext);
2601 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2604 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2605 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2606 // already be zero by virtue of the width of the base type of the load.
2608 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2610 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2611 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2612 N0.getOpcode() == ISD::LOAD) {
2613 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2614 N0 : N0.getOperand(0) );
2616 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2617 // This can be a pure constant or a vector splat, in which case we treat the
2618 // vector as a scalar and use the splat value.
2619 APInt Constant = APInt::getNullValue(1);
2620 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2621 Constant = C->getAPIntValue();
2622 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2623 APInt SplatValue, SplatUndef;
2624 unsigned SplatBitSize;
2626 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2627 SplatBitSize, HasAnyUndefs);
2629 // Undef bits can contribute to a possible optimisation if set, so
2631 SplatValue |= SplatUndef;
2633 // The splat value may be something like "0x00FFFFFF", which means 0 for
2634 // the first vector value and FF for the rest, repeating. We need a mask
2635 // that will apply equally to all members of the vector, so AND all the
2636 // lanes of the constant together.
2637 EVT VT = Vector->getValueType(0);
2638 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2640 // If the splat value has been compressed to a bitlength lower
2641 // than the size of the vector lane, we need to re-expand it to
2643 if (BitWidth > SplatBitSize)
2644 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2645 SplatBitSize < BitWidth;
2646 SplatBitSize = SplatBitSize * 2)
2647 SplatValue |= SplatValue.shl(SplatBitSize);
2649 Constant = APInt::getAllOnesValue(BitWidth);
2650 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2651 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2655 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2656 // actually legal and isn't going to get expanded, else this is a false
2658 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2659 Load->getMemoryVT());
2661 // Resize the constant to the same size as the original memory access before
2662 // extension. If it is still the AllOnesValue then this AND is completely
2665 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2668 switch (Load->getExtensionType()) {
2669 default: B = false; break;
2670 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2672 case ISD::NON_EXTLOAD: B = true; break;
2675 if (B && Constant.isAllOnesValue()) {
2676 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2677 // preserve semantics once we get rid of the AND.
2678 SDValue NewLoad(Load, 0);
2679 if (Load->getExtensionType() == ISD::EXTLOAD) {
2680 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2681 Load->getValueType(0), SDLoc(Load),
2682 Load->getChain(), Load->getBasePtr(),
2683 Load->getOffset(), Load->getMemoryVT(),
2684 Load->getMemOperand());
2685 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2686 if (Load->getNumValues() == 3) {
2687 // PRE/POST_INC loads have 3 values.
2688 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2689 NewLoad.getValue(2) };
2690 CombineTo(Load, To, 3, true);
2692 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2696 // Fold the AND away, taking care not to fold to the old load node if we
2698 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2705 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2706 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2708 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2709 LL.getValueType().isInteger()) {
2710 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2711 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2712 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2713 LR.getValueType(), LL, RL);
2714 AddToWorkList(ORNode.getNode());
2715 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2717 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2718 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2719 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2720 LR.getValueType(), LL, RL);
2721 AddToWorkList(ANDNode.getNode());
2722 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2724 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2725 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2726 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2727 LR.getValueType(), LL, RL);
2728 AddToWorkList(ORNode.getNode());
2729 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2732 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2733 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2734 Op0 == Op1 && LL.getValueType().isInteger() &&
2735 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2736 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2737 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2738 cast<ConstantSDNode>(RR)->isNullValue()))) {
2739 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2740 LL, DAG.getConstant(1, LL.getValueType()));
2741 AddToWorkList(ADDNode.getNode());
2742 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2743 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2745 // canonicalize equivalent to ll == rl
2746 if (LL == RR && LR == RL) {
2747 Op1 = ISD::getSetCCSwappedOperands(Op1);
2750 if (LL == RL && LR == RR) {
2751 bool isInteger = LL.getValueType().isInteger();
2752 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2753 if (Result != ISD::SETCC_INVALID &&
2754 (!LegalOperations ||
2755 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2756 TLI.isOperationLegal(ISD::SETCC,
2757 getSetCCResultType(N0.getSimpleValueType())))))
2758 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2763 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2764 if (N0.getOpcode() == N1.getOpcode()) {
2765 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2766 if (Tmp.getNode()) return Tmp;
2769 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2770 // fold (and (sra)) -> (and (srl)) when possible.
2771 if (!VT.isVector() &&
2772 SimplifyDemandedBits(SDValue(N, 0)))
2773 return SDValue(N, 0);
2775 // fold (zext_inreg (extload x)) -> (zextload x)
2776 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2777 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2778 EVT MemVT = LN0->getMemoryVT();
2779 // If we zero all the possible extended bits, then we can turn this into
2780 // a zextload if we are running before legalize or the operation is legal.
2781 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2782 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2783 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2784 ((!LegalOperations && !LN0->isVolatile()) ||
2785 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2786 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2787 LN0->getChain(), LN0->getBasePtr(),
2788 MemVT, LN0->getMemOperand());
2790 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2791 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2794 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2795 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2797 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2798 EVT MemVT = LN0->getMemoryVT();
2799 // If we zero all the possible extended bits, then we can turn this into
2800 // a zextload if we are running before legalize or the operation is legal.
2801 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2802 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2803 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2804 ((!LegalOperations && !LN0->isVolatile()) ||
2805 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2806 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2807 LN0->getChain(), LN0->getBasePtr(),
2808 MemVT, LN0->getMemOperand());
2810 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2811 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2815 // fold (and (load x), 255) -> (zextload x, i8)
2816 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2817 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2818 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2819 (N0.getOpcode() == ISD::ANY_EXTEND &&
2820 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2821 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2822 LoadSDNode *LN0 = HasAnyExt
2823 ? cast<LoadSDNode>(N0.getOperand(0))
2824 : cast<LoadSDNode>(N0);
2825 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2826 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2827 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2828 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2829 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2830 EVT LoadedVT = LN0->getMemoryVT();
2832 if (ExtVT == LoadedVT &&
2833 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2834 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2837 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2838 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2839 LN0->getMemOperand());
2841 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2845 // Do not change the width of a volatile load.
2846 // Do not generate loads of non-round integer types since these can
2847 // be expensive (and would be wrong if the type is not byte sized).
2848 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2849 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2850 EVT PtrType = LN0->getOperand(1).getValueType();
2852 unsigned Alignment = LN0->getAlignment();
2853 SDValue NewPtr = LN0->getBasePtr();
2855 // For big endian targets, we need to add an offset to the pointer
2856 // to load the correct bytes. For little endian systems, we merely
2857 // need to read fewer bytes from the same pointer.
2858 if (TLI.isBigEndian()) {
2859 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2860 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2861 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2862 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2863 NewPtr, DAG.getConstant(PtrOff, PtrType));
2864 Alignment = MinAlign(Alignment, PtrOff);
2867 AddToWorkList(NewPtr.getNode());
2869 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2871 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2872 LN0->getChain(), NewPtr,
2873 LN0->getPointerInfo(),
2874 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2875 Alignment, LN0->getTBAAInfo());
2877 CombineTo(LN0, Load, Load.getValue(1));
2878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2884 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2885 VT.getSizeInBits() <= 64) {
2886 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2887 APInt ADDC = ADDI->getAPIntValue();
2888 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2889 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2890 // immediate for an add, but it is legal if its top c2 bits are set,
2891 // transform the ADD so the immediate doesn't need to be materialized
2893 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2894 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2895 SRLI->getZExtValue());
2896 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2898 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2900 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2901 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2902 CombineTo(N0.getNode(), NewAdd);
2903 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2911 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2912 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2913 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2914 N0.getOperand(1), false);
2915 if (BSwap.getNode())
2922 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2924 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2925 bool DemandHighBits) {
2926 if (!LegalOperations)
2929 EVT VT = N->getValueType(0);
2930 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2932 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2935 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2936 bool LookPassAnd0 = false;
2937 bool LookPassAnd1 = false;
2938 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2940 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2942 if (N0.getOpcode() == ISD::AND) {
2943 if (!N0.getNode()->hasOneUse())
2945 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2946 if (!N01C || N01C->getZExtValue() != 0xFF00)
2948 N0 = N0.getOperand(0);
2949 LookPassAnd0 = true;
2952 if (N1.getOpcode() == ISD::AND) {
2953 if (!N1.getNode()->hasOneUse())
2955 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2956 if (!N11C || N11C->getZExtValue() != 0xFF)
2958 N1 = N1.getOperand(0);
2959 LookPassAnd1 = true;
2962 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2964 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2966 if (!N0.getNode()->hasOneUse() ||
2967 !N1.getNode()->hasOneUse())
2970 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2971 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2974 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2977 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2978 SDValue N00 = N0->getOperand(0);
2979 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2980 if (!N00.getNode()->hasOneUse())
2982 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2983 if (!N001C || N001C->getZExtValue() != 0xFF)
2985 N00 = N00.getOperand(0);
2986 LookPassAnd0 = true;
2989 SDValue N10 = N1->getOperand(0);
2990 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2991 if (!N10.getNode()->hasOneUse())
2993 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2994 if (!N101C || N101C->getZExtValue() != 0xFF00)
2996 N10 = N10.getOperand(0);
2997 LookPassAnd1 = true;
3003 // Make sure everything beyond the low halfword gets set to zero since the SRL
3004 // 16 will clear the top bits.
3005 unsigned OpSizeInBits = VT.getSizeInBits();
3006 if (DemandHighBits && OpSizeInBits > 16) {
3007 // If the left-shift isn't masked out then the only way this is a bswap is
3008 // if all bits beyond the low 8 are 0. In that case the entire pattern
3009 // reduces to a left shift anyway: leave it for other parts of the combiner.
3013 // However, if the right shift isn't masked out then it might be because
3014 // it's not needed. See if we can spot that too.
3015 if (!LookPassAnd1 &&
3016 !DAG.MaskedValueIsZero(
3017 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3021 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3022 if (OpSizeInBits > 16)
3023 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3024 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3028 /// isBSwapHWordElement - Return true if the specified node is an element
3029 /// that makes up a 32-bit packed halfword byteswap. i.e.
3030 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3031 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3032 if (!N.getNode()->hasOneUse())
3035 unsigned Opc = N.getOpcode();
3036 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3039 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3044 switch (N1C->getZExtValue()) {
3047 case 0xFF: Num = 0; break;
3048 case 0xFF00: Num = 1; break;
3049 case 0xFF0000: Num = 2; break;
3050 case 0xFF000000: Num = 3; break;
3053 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3054 SDValue N0 = N.getOperand(0);
3055 if (Opc == ISD::AND) {
3056 if (Num == 0 || Num == 2) {
3058 // (x >> 8) & 0xff0000
3059 if (N0.getOpcode() != ISD::SRL)
3061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3062 if (!C || C->getZExtValue() != 8)
3065 // (x << 8) & 0xff00
3066 // (x << 8) & 0xff000000
3067 if (N0.getOpcode() != ISD::SHL)
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3073 } else if (Opc == ISD::SHL) {
3075 // (x & 0xff0000) << 8
3076 if (Num != 0 && Num != 2)
3078 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3079 if (!C || C->getZExtValue() != 8)
3081 } else { // Opc == ISD::SRL
3082 // (x & 0xff00) >> 8
3083 // (x & 0xff000000) >> 8
3084 if (Num != 1 && Num != 3)
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3094 Parts[Num] = N0.getOperand(0).getNode();
3098 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3099 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3100 /// => (rotl (bswap x), 16)
3101 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3102 if (!LegalOperations)
3105 EVT VT = N->getValueType(0);
3108 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3111 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3113 // (or (or (and), (and)), (or (and), (and)))
3114 // (or (or (or (and), (and)), (and)), (and))
3115 if (N0.getOpcode() != ISD::OR)
3117 SDValue N00 = N0.getOperand(0);
3118 SDValue N01 = N0.getOperand(1);
3120 if (N1.getOpcode() == ISD::OR &&
3121 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3122 // (or (or (and), (and)), (or (and), (and)))
3123 SDValue N000 = N00.getOperand(0);
3124 if (!isBSwapHWordElement(N000, Parts))
3127 SDValue N001 = N00.getOperand(1);
3128 if (!isBSwapHWordElement(N001, Parts))
3130 SDValue N010 = N01.getOperand(0);
3131 if (!isBSwapHWordElement(N010, Parts))
3133 SDValue N011 = N01.getOperand(1);
3134 if (!isBSwapHWordElement(N011, Parts))
3137 // (or (or (or (and), (and)), (and)), (and))
3138 if (!isBSwapHWordElement(N1, Parts))
3140 if (!isBSwapHWordElement(N01, Parts))
3142 if (N00.getOpcode() != ISD::OR)
3144 SDValue N000 = N00.getOperand(0);
3145 if (!isBSwapHWordElement(N000, Parts))
3147 SDValue N001 = N00.getOperand(1);
3148 if (!isBSwapHWordElement(N001, Parts))
3152 // Make sure the parts are all coming from the same node.
3153 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3156 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3157 SDValue(Parts[0],0));
3159 // Result of the bswap should be rotated by 16. If it's not legal, then
3160 // do (x << 16) | (x >> 16).
3161 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3162 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3163 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3164 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3165 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3166 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3167 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3168 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3171 SDValue DAGCombiner::visitOR(SDNode *N) {
3172 SDValue N0 = N->getOperand(0);
3173 SDValue N1 = N->getOperand(1);
3174 SDValue LL, LR, RL, RR, CC0, CC1;
3175 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3177 EVT VT = N1.getValueType();
3180 if (VT.isVector()) {
3181 SDValue FoldedVOp = SimplifyVBinOp(N);
3182 if (FoldedVOp.getNode()) return FoldedVOp;
3184 // fold (or x, 0) -> x, vector edition
3185 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3187 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3190 // fold (or x, -1) -> -1, vector edition
3191 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3193 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3197 // fold (or x, undef) -> -1
3198 if (!LegalOperations &&
3199 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3200 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3201 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3203 // fold (or c1, c2) -> c1|c2
3205 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3206 // canonicalize constant to RHS
3208 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3209 // fold (or x, 0) -> x
3210 if (N1C && N1C->isNullValue())
3212 // fold (or x, -1) -> -1
3213 if (N1C && N1C->isAllOnesValue())
3215 // fold (or x, c) -> c iff (x & ~c) == 0
3216 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3219 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3220 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3221 if (BSwap.getNode() != 0)
3223 BSwap = MatchBSwapHWordLow(N, N0, N1);
3224 if (BSwap.getNode() != 0)
3228 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3229 if (ROR.getNode() != 0)
3231 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3232 // iff (c1 & c2) == 0.
3233 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3234 isa<ConstantSDNode>(N0.getOperand(1))) {
3235 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3236 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3237 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3240 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3241 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3242 N0.getOperand(0), N1), COR);
3245 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3246 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3247 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3248 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3250 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3251 LL.getValueType().isInteger()) {
3252 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3253 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3254 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3255 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3256 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3257 LR.getValueType(), LL, RL);
3258 AddToWorkList(ORNode.getNode());
3259 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3261 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3262 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3263 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3264 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3265 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3266 LR.getValueType(), LL, RL);
3267 AddToWorkList(ANDNode.getNode());
3268 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3271 // canonicalize equivalent to ll == rl
3272 if (LL == RR && LR == RL) {
3273 Op1 = ISD::getSetCCSwappedOperands(Op1);
3276 if (LL == RL && LR == RR) {
3277 bool isInteger = LL.getValueType().isInteger();
3278 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3279 if (Result != ISD::SETCC_INVALID &&
3280 (!LegalOperations ||
3281 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3282 TLI.isOperationLegal(ISD::SETCC,
3283 getSetCCResultType(N0.getValueType())))))
3284 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3289 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3290 if (N0.getOpcode() == N1.getOpcode()) {
3291 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3292 if (Tmp.getNode()) return Tmp;
3295 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3296 if (N0.getOpcode() == ISD::AND &&
3297 N1.getOpcode() == ISD::AND &&
3298 N0.getOperand(1).getOpcode() == ISD::Constant &&
3299 N1.getOperand(1).getOpcode() == ISD::Constant &&
3300 // Don't increase # computations.
3301 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3302 // We can only do this xform if we know that bits from X that are set in C2
3303 // but not in C1 are already zero. Likewise for Y.
3304 const APInt &LHSMask =
3305 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3306 const APInt &RHSMask =
3307 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3309 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3310 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3311 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3312 N0.getOperand(0), N1.getOperand(0));
3313 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3314 DAG.getConstant(LHSMask | RHSMask, VT));
3318 // See if this is some rotate idiom.
3319 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3320 return SDValue(Rot, 0);
3322 // Simplify the operands using demanded-bits information.
3323 if (!VT.isVector() &&
3324 SimplifyDemandedBits(SDValue(N, 0)))
3325 return SDValue(N, 0);
3330 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3331 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3332 if (Op.getOpcode() == ISD::AND) {
3333 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3334 Mask = Op.getOperand(1);
3335 Op = Op.getOperand(0);
3341 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3349 // Return true if we can prove that, whenever Neg and Pos are both in the
3350 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3351 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3353 // (or (shift1 X, Neg), (shift2 X, Pos))
3355 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3356 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3357 // shift amounts with defined behavior.
3358 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3359 // If OpSize is a power of 2 then:
3361 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3362 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3364 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3365 // for the stronger condition:
3367 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3369 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3370 // we can just replace Neg with Neg' for the rest of the function.
3372 // In other cases we check for the even stronger condition:
3374 // Neg == OpSize - Pos [B]
3376 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3377 // behavior if Pos == 0 (and consequently Neg == OpSize).
3379 // We could actually use [A] whenever OpSize is a power of 2, but the
3380 // only extra cases that it would match are those uninteresting ones
3381 // where Neg and Pos are never in range at the same time. E.g. for
3382 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3383 // as well as (sub 32, Pos), but:
3385 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3387 // always invokes undefined behavior for 32-bit X.
3389 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3390 unsigned LoBits = 0;
3391 if (Neg.getOpcode() == ISD::AND &&
3392 isPowerOf2_64(OpSize) &&
3393 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3394 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3395 Neg = Neg.getOperand(0);
3396 LoBits = Log2_64(OpSize);
3399 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3400 if (Neg.getOpcode() != ISD::SUB)
3402 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3405 SDValue NegOp1 = Neg.getOperand(1);
3407 // The condition we need is now:
3409 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3411 // If NegOp1 == Pos then we need:
3413 // OpSize & Mask == NegC & Mask
3415 // (because "x & Mask" is a truncation and distributes through subtraction).
3418 Width = NegC->getAPIntValue();
3419 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3420 // Then the condition we want to prove becomes:
3422 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3424 // which, again because "x & Mask" is a truncation, becomes:
3426 // NegC & Mask == (OpSize - PosC) & Mask
3427 // OpSize & Mask == (NegC + PosC) & Mask
3428 else if (Pos.getOpcode() == ISD::ADD &&
3429 Pos.getOperand(0) == NegOp1 &&
3430 Pos.getOperand(1).getOpcode() == ISD::Constant)
3431 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3432 NegC->getAPIntValue());
3436 // Now we just need to check that OpSize & Mask == Width & Mask.
3438 return Width.getLoBits(LoBits) == 0;
3439 return Width == OpSize;
3442 // A subroutine of MatchRotate used once we have found an OR of two opposite
3443 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3444 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3445 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3446 // Neg with outer conversions stripped away.
3447 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3448 SDValue Neg, SDValue InnerPos,
3449 SDValue InnerNeg, unsigned PosOpcode,
3450 unsigned NegOpcode, SDLoc DL) {
3451 // fold (or (shl x, (*ext y)),
3452 // (srl x, (*ext (sub 32, y)))) ->
3453 // (rotl x, y) or (rotr x, (sub 32, y))
3455 // fold (or (shl x, (*ext (sub 32, y))),
3456 // (srl x, (*ext y))) ->
3457 // (rotr x, y) or (rotl x, (sub 32, y))
3458 EVT VT = Shifted.getValueType();
3459 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3460 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3461 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3462 HasPos ? Pos : Neg).getNode();
3465 // fold (or (shl (*ext x), (*ext y)),
3466 // (srl (*ext x), (*ext (sub 32, y)))) ->
3467 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3469 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3470 // (srl (*ext x), (*ext y))) ->
3471 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3472 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3473 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3474 SDValue InnerShifted = Shifted.getOperand(0);
3475 EVT InnerVT = InnerShifted.getValueType();
3476 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3477 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3478 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3479 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3480 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3481 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3489 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3490 // idioms for rotate, and if the target supports rotation instructions, generate
3492 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3493 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3494 EVT VT = LHS.getValueType();
3495 if (!TLI.isTypeLegal(VT)) return 0;
3497 // The target must have at least one rotate flavor.
3498 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3499 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3500 if (!HasROTL && !HasROTR) return 0;
3502 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3503 SDValue LHSShift; // The shift.
3504 SDValue LHSMask; // AND value if any.
3505 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3506 return 0; // Not part of a rotate.
3508 SDValue RHSShift; // The shift.
3509 SDValue RHSMask; // AND value if any.
3510 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3511 return 0; // Not part of a rotate.
3513 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3514 return 0; // Not shifting the same value.
3516 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3517 return 0; // Shifts must disagree.
3519 // Canonicalize shl to left side in a shl/srl pair.
3520 if (RHSShift.getOpcode() == ISD::SHL) {
3521 std::swap(LHS, RHS);
3522 std::swap(LHSShift, RHSShift);
3523 std::swap(LHSMask , RHSMask );
3526 unsigned OpSizeInBits = VT.getSizeInBits();
3527 SDValue LHSShiftArg = LHSShift.getOperand(0);
3528 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3529 SDValue RHSShiftArg = RHSShift.getOperand(0);
3530 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3532 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3533 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3534 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3535 RHSShiftAmt.getOpcode() == ISD::Constant) {
3536 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3537 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3538 if ((LShVal + RShVal) != OpSizeInBits)
3541 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3542 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3544 // If there is an AND of either shifted operand, apply it to the result.
3545 if (LHSMask.getNode() || RHSMask.getNode()) {
3546 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3548 if (LHSMask.getNode()) {
3549 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3550 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3552 if (RHSMask.getNode()) {
3553 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3554 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3557 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3560 return Rot.getNode();
3563 // If there is a mask here, and we have a variable shift, we can't be sure
3564 // that we're masking out the right stuff.
3565 if (LHSMask.getNode() || RHSMask.getNode())
3568 // If the shift amount is sign/zext/any-extended just peel it off.
3569 SDValue LExtOp0 = LHSShiftAmt;
3570 SDValue RExtOp0 = RHSShiftAmt;
3571 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3572 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3573 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3574 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3575 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3576 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3577 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3578 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3579 LExtOp0 = LHSShiftAmt.getOperand(0);
3580 RExtOp0 = RHSShiftAmt.getOperand(0);
3583 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3584 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3588 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3589 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3596 SDValue DAGCombiner::visitXOR(SDNode *N) {
3597 SDValue N0 = N->getOperand(0);
3598 SDValue N1 = N->getOperand(1);
3599 SDValue LHS, RHS, CC;
3600 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3601 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3602 EVT VT = N0.getValueType();
3605 if (VT.isVector()) {
3606 SDValue FoldedVOp = SimplifyVBinOp(N);
3607 if (FoldedVOp.getNode()) return FoldedVOp;
3609 // fold (xor x, 0) -> x, vector edition
3610 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3612 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3616 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3617 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3618 return DAG.getConstant(0, VT);
3619 // fold (xor x, undef) -> undef
3620 if (N0.getOpcode() == ISD::UNDEF)
3622 if (N1.getOpcode() == ISD::UNDEF)
3624 // fold (xor c1, c2) -> c1^c2
3626 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3627 // canonicalize constant to RHS
3629 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3630 // fold (xor x, 0) -> x
3631 if (N1C && N1C->isNullValue())
3634 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3635 if (RXOR.getNode() != 0)
3638 // fold !(x cc y) -> (x !cc y)
3639 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3640 bool isInt = LHS.getValueType().isInteger();
3641 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3644 if (!LegalOperations ||
3645 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3646 switch (N0.getOpcode()) {
3648 llvm_unreachable("Unhandled SetCC Equivalent!");
3650 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3651 case ISD::SELECT_CC:
3652 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3653 N0.getOperand(3), NotCC);
3658 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3659 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3660 N0.getNode()->hasOneUse() &&
3661 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3662 SDValue V = N0.getOperand(0);
3663 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3664 DAG.getConstant(1, V.getValueType()));
3665 AddToWorkList(V.getNode());
3666 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3669 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3670 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3671 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3672 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3673 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3674 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3675 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3676 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3677 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3678 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3681 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3682 if (N1C && N1C->isAllOnesValue() &&
3683 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3684 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3685 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3686 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3687 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3688 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3689 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3690 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3693 // fold (xor (and x, y), y) -> (and (not x), y)
3694 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3695 N0->getOperand(1) == N1) {
3696 SDValue X = N0->getOperand(0);
3697 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3698 AddToWorkList(NotX.getNode());
3699 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3701 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3702 if (N1C && N0.getOpcode() == ISD::XOR) {
3703 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3704 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3707 DAG.getConstant(N1C->getAPIntValue() ^
3708 N00C->getAPIntValue(), VT));
3710 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3711 DAG.getConstant(N1C->getAPIntValue() ^
3712 N01C->getAPIntValue(), VT));
3714 // fold (xor x, x) -> 0
3716 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3718 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3719 if (N0.getOpcode() == N1.getOpcode()) {
3720 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3721 if (Tmp.getNode()) return Tmp;
3724 // Simplify the expression using non-local knowledge.
3725 if (!VT.isVector() &&
3726 SimplifyDemandedBits(SDValue(N, 0)))
3727 return SDValue(N, 0);
3732 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3733 /// the shift amount is a constant.
3734 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3735 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3736 "Expected an ConstantSDNode operand.");
3737 // We can't and shouldn't fold opaque constants.
3738 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3741 SDNode *LHS = N->getOperand(0).getNode();
3742 if (!LHS->hasOneUse()) return SDValue();
3744 // We want to pull some binops through shifts, so that we have (and (shift))
3745 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3746 // thing happens with address calculations, so it's important to canonicalize
3748 bool HighBitSet = false; // Can we transform this if the high bit is set?
3750 switch (LHS->getOpcode()) {
3751 default: return SDValue();
3754 HighBitSet = false; // We can only transform sra if the high bit is clear.
3757 HighBitSet = true; // We can only transform sra if the high bit is set.
3760 if (N->getOpcode() != ISD::SHL)
3761 return SDValue(); // only shl(add) not sr[al](add).
3762 HighBitSet = false; // We can only transform sra if the high bit is clear.
3766 // We require the RHS of the binop to be a constant and not opaque as well.
3767 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3768 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3770 // FIXME: disable this unless the input to the binop is a shift by a constant.
3771 // If it is not a shift, it pessimizes some common cases like:
3773 // void foo(int *X, int i) { X[i & 1235] = 1; }
3774 // int bar(int *X, int i) { return X[i & 255]; }
3775 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3776 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3777 BinOpLHSVal->getOpcode() != ISD::SRA &&
3778 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3779 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3782 EVT VT = N->getValueType(0);
3784 // If this is a signed shift right, and the high bit is modified by the
3785 // logical operation, do not perform the transformation. The highBitSet
3786 // boolean indicates the value of the high bit of the constant which would
3787 // cause it to be modified for this operation.
3788 if (N->getOpcode() == ISD::SRA) {
3789 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3790 if (BinOpRHSSignSet != HighBitSet)
3794 // Fold the constants, shifting the binop RHS by the shift amount.
3795 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3797 LHS->getOperand(1), N->getOperand(1));
3798 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3800 // Create the new shift.
3801 SDValue NewShift = DAG.getNode(N->getOpcode(),
3802 SDLoc(LHS->getOperand(0)),
3803 VT, LHS->getOperand(0), N->getOperand(1));
3805 // Create the new binop.
3806 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3809 SDValue DAGCombiner::visitSHL(SDNode *N) {
3810 SDValue N0 = N->getOperand(0);
3811 SDValue N1 = N->getOperand(1);
3812 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3813 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3814 EVT VT = N0.getValueType();
3815 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3818 if (VT.isVector()) {
3819 SDValue FoldedVOp = SimplifyVBinOp(N);
3820 if (FoldedVOp.getNode()) return FoldedVOp;
3823 // fold (shl c1, c2) -> c1<<c2
3825 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3826 // fold (shl 0, x) -> 0
3827 if (N0C && N0C->isNullValue())
3829 // fold (shl x, c >= size(x)) -> undef
3830 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3831 return DAG.getUNDEF(VT);
3832 // fold (shl x, 0) -> x
3833 if (N1C && N1C->isNullValue())
3835 // fold (shl undef, x) -> 0
3836 if (N0.getOpcode() == ISD::UNDEF)
3837 return DAG.getConstant(0, VT);
3838 // if (shl x, c) is known to be zero, return 0
3839 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3840 APInt::getAllOnesValue(OpSizeInBits)))
3841 return DAG.getConstant(0, VT);
3842 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3843 if (N1.getOpcode() == ISD::TRUNCATE &&
3844 N1.getOperand(0).getOpcode() == ISD::AND &&
3845 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3846 SDValue N101 = N1.getOperand(0).getOperand(1);
3847 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3848 EVT TruncVT = N1.getValueType();
3849 SDValue N100 = N1.getOperand(0).getOperand(0);
3850 APInt TruncC = N101C->getAPIntValue();
3851 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3852 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3853 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3854 DAG.getNode(ISD::TRUNCATE,
3857 DAG.getConstant(TruncC, TruncVT)));
3861 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3862 return SDValue(N, 0);
3864 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3865 if (N1C && N0.getOpcode() == ISD::SHL &&
3866 N0.getOperand(1).getOpcode() == ISD::Constant) {
3867 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3868 uint64_t c2 = N1C->getZExtValue();
3869 if (c1 + c2 >= OpSizeInBits)
3870 return DAG.getConstant(0, VT);
3871 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3872 DAG.getConstant(c1 + c2, N1.getValueType()));
3875 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3876 // For this to be valid, the second form must not preserve any of the bits
3877 // that are shifted out by the inner shift in the first form. This means
3878 // the outer shift size must be >= the number of bits added by the ext.
3879 // As a corollary, we don't care what kind of ext it is.
3880 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3881 N0.getOpcode() == ISD::ANY_EXTEND ||
3882 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3883 N0.getOperand(0).getOpcode() == ISD::SHL &&
3884 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3886 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3887 uint64_t c2 = N1C->getZExtValue();
3888 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3889 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3890 if (c2 >= OpSizeInBits - InnerShiftSize) {
3891 if (c1 + c2 >= OpSizeInBits)
3892 return DAG.getConstant(0, VT);
3893 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3894 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3895 N0.getOperand(0)->getOperand(0)),
3896 DAG.getConstant(c1 + c2, N1.getValueType()));
3900 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3901 // Only fold this if the inner zext has no other uses to avoid increasing
3902 // the total number of instructions.
3903 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3904 N0.getOperand(0).getOpcode() == ISD::SRL &&
3905 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3907 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3908 if (c1 < VT.getSizeInBits()) {
3909 uint64_t c2 = N1C->getZExtValue();
3911 SDValue NewOp0 = N0.getOperand(0);
3912 EVT CountVT = NewOp0.getOperand(1).getValueType();
3913 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3914 NewOp0, DAG.getConstant(c2, CountVT));
3915 AddToWorkList(NewSHL.getNode());
3916 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3921 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3922 // (and (srl x, (sub c1, c2), MASK)
3923 // Only fold this if the inner shift has no other uses -- if it does, folding
3924 // this will increase the total number of instructions.
3925 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3926 N0.getOperand(1).getOpcode() == ISD::Constant) {
3927 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3928 if (c1 < VT.getSizeInBits()) {
3929 uint64_t c2 = N1C->getZExtValue();
3930 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3931 VT.getSizeInBits() - c1);
3934 Mask = Mask.shl(c2-c1);
3935 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3936 DAG.getConstant(c2-c1, N1.getValueType()));
3938 Mask = Mask.lshr(c1-c2);
3939 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3940 DAG.getConstant(c1-c2, N1.getValueType()));
3942 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3943 DAG.getConstant(Mask, VT));
3946 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3947 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3948 SDValue HiBitsMask =
3949 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3950 VT.getSizeInBits() -
3951 N1C->getZExtValue()),
3953 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3958 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3959 if (NewSHL.getNode())
3966 SDValue DAGCombiner::visitSRA(SDNode *N) {
3967 SDValue N0 = N->getOperand(0);
3968 SDValue N1 = N->getOperand(1);
3969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3971 EVT VT = N0.getValueType();
3972 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3975 if (VT.isVector()) {
3976 SDValue FoldedVOp = SimplifyVBinOp(N);
3977 if (FoldedVOp.getNode()) return FoldedVOp;
3980 // fold (sra c1, c2) -> (sra c1, c2)
3982 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3983 // fold (sra 0, x) -> 0
3984 if (N0C && N0C->isNullValue())
3986 // fold (sra -1, x) -> -1
3987 if (N0C && N0C->isAllOnesValue())
3989 // fold (sra x, (setge c, size(x))) -> undef
3990 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3991 return DAG.getUNDEF(VT);
3992 // fold (sra x, 0) -> x
3993 if (N1C && N1C->isNullValue())
3995 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3997 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3998 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3999 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4001 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4002 ExtVT, VT.getVectorNumElements());
4003 if ((!LegalOperations ||
4004 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4005 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4006 N0.getOperand(0), DAG.getValueType(ExtVT));
4009 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4010 if (N1C && N0.getOpcode() == ISD::SRA) {
4011 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4012 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4013 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
4014 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4015 DAG.getConstant(Sum, N1C->getValueType(0)));
4019 // fold (sra (shl X, m), (sub result_size, n))
4020 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4021 // result_size - n != m.
4022 // If truncate is free for the target sext(shl) is likely to result in better
4024 if (N0.getOpcode() == ISD::SHL) {
4025 // Get the two constanst of the shifts, CN0 = m, CN = n.
4026 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4028 // Determine what the truncate's result bitsize and type would be.
4030 EVT::getIntegerVT(*DAG.getContext(),
4031 OpSizeInBits - N1C->getZExtValue());
4032 // Determine the residual right-shift amount.
4033 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4035 // If the shift is not a no-op (in which case this should be just a sign
4036 // extend already), the truncated to type is legal, sign_extend is legal
4037 // on that type, and the truncate to that type is both legal and free,
4038 // perform the transform.
4039 if ((ShiftAmt > 0) &&
4040 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4041 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4042 TLI.isTruncateFree(VT, TruncVT)) {
4044 SDValue Amt = DAG.getConstant(ShiftAmt,
4045 getShiftAmountTy(N0.getOperand(0).getValueType()));
4046 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4047 N0.getOperand(0), Amt);
4048 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4050 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4051 N->getValueType(0), Trunc);
4056 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4057 if (N1.getOpcode() == ISD::TRUNCATE &&
4058 N1.getOperand(0).getOpcode() == ISD::AND &&
4059 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4060 SDValue N101 = N1.getOperand(0).getOperand(1);
4061 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4062 EVT TruncVT = N1.getValueType();
4063 SDValue N100 = N1.getOperand(0).getOperand(0);
4064 APInt TruncC = N101C->getAPIntValue();
4065 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4066 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4067 DAG.getNode(ISD::AND, SDLoc(N),
4069 DAG.getNode(ISD::TRUNCATE,
4072 DAG.getConstant(TruncC, TruncVT)));
4076 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4077 // if c1 is equal to the number of bits the trunc removes
4078 if (N0.getOpcode() == ISD::TRUNCATE &&
4079 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4080 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4081 N0.getOperand(0).hasOneUse() &&
4082 N0.getOperand(0).getOperand(1).hasOneUse() &&
4083 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4084 EVT LargeVT = N0.getOperand(0).getValueType();
4085 ConstantSDNode *LargeShiftAmt =
4086 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4088 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4089 LargeShiftAmt->getZExtValue()) {
4091 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4092 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4093 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4094 N0.getOperand(0).getOperand(0), Amt);
4095 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4099 // Simplify, based on bits shifted out of the LHS.
4100 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4101 return SDValue(N, 0);
4104 // If the sign bit is known to be zero, switch this to a SRL.
4105 if (DAG.SignBitIsZero(N0))
4106 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4109 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4110 if (NewSRA.getNode())
4117 SDValue DAGCombiner::visitSRL(SDNode *N) {
4118 SDValue N0 = N->getOperand(0);
4119 SDValue N1 = N->getOperand(1);
4120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4122 EVT VT = N0.getValueType();
4123 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4126 if (VT.isVector()) {
4127 SDValue FoldedVOp = SimplifyVBinOp(N);
4128 if (FoldedVOp.getNode()) return FoldedVOp;
4131 // fold (srl c1, c2) -> c1 >>u c2
4133 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4134 // fold (srl 0, x) -> 0
4135 if (N0C && N0C->isNullValue())
4137 // fold (srl x, c >= size(x)) -> undef
4138 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4139 return DAG.getUNDEF(VT);
4140 // fold (srl x, 0) -> x
4141 if (N1C && N1C->isNullValue())
4143 // if (srl x, c) is known to be zero, return 0
4144 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4145 APInt::getAllOnesValue(OpSizeInBits)))
4146 return DAG.getConstant(0, VT);
4148 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4149 if (N1C && N0.getOpcode() == ISD::SRL &&
4150 N0.getOperand(1).getOpcode() == ISD::Constant) {
4151 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4152 uint64_t c2 = N1C->getZExtValue();
4153 if (c1 + c2 >= OpSizeInBits)
4154 return DAG.getConstant(0, VT);
4155 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4156 DAG.getConstant(c1 + c2, N1.getValueType()));
4159 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4160 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4161 N0.getOperand(0).getOpcode() == ISD::SRL &&
4162 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4164 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4165 uint64_t c2 = N1C->getZExtValue();
4166 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4167 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4168 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4169 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4170 if (c1 + OpSizeInBits == InnerShiftSize) {
4171 if (c1 + c2 >= InnerShiftSize)
4172 return DAG.getConstant(0, VT);
4173 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4174 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4175 N0.getOperand(0)->getOperand(0),
4176 DAG.getConstant(c1 + c2, ShiftCountVT)));
4180 // fold (srl (shl x, c), c) -> (and x, cst2)
4181 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4182 N0.getValueSizeInBits() <= 64) {
4183 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4184 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4185 DAG.getConstant(~0ULL >> ShAmt, VT));
4188 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4189 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4190 // Shifting in all undef bits?
4191 EVT SmallVT = N0.getOperand(0).getValueType();
4192 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4193 return DAG.getUNDEF(VT);
4195 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4196 uint64_t ShiftAmt = N1C->getZExtValue();
4197 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4199 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4200 AddToWorkList(SmallShift.getNode());
4201 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4202 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4203 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4204 DAG.getConstant(Mask, VT));
4208 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4209 // bit, which is unmodified by sra.
4210 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4211 if (N0.getOpcode() == ISD::SRA)
4212 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4215 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4216 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4217 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4218 APInt KnownZero, KnownOne;
4219 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4221 // If any of the input bits are KnownOne, then the input couldn't be all
4222 // zeros, thus the result of the srl will always be zero.
4223 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4225 // If all of the bits input the to ctlz node are known to be zero, then
4226 // the result of the ctlz is "32" and the result of the shift is one.
4227 APInt UnknownBits = ~KnownZero;
4228 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4230 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4231 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4232 // Okay, we know that only that the single bit specified by UnknownBits
4233 // could be set on input to the CTLZ node. If this bit is set, the SRL
4234 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4235 // to an SRL/XOR pair, which is likely to simplify more.
4236 unsigned ShAmt = UnknownBits.countTrailingZeros();
4237 SDValue Op = N0.getOperand(0);
4240 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4241 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4242 AddToWorkList(Op.getNode());
4245 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4246 Op, DAG.getConstant(1, VT));
4250 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4251 if (N1.getOpcode() == ISD::TRUNCATE &&
4252 N1.getOperand(0).getOpcode() == ISD::AND &&
4253 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4254 SDValue N101 = N1.getOperand(0).getOperand(1);
4255 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4256 EVT TruncVT = N1.getValueType();
4257 SDValue N100 = N1.getOperand(0).getOperand(0);
4258 APInt TruncC = N101C->getAPIntValue();
4259 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4260 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4261 DAG.getNode(ISD::AND, SDLoc(N),
4263 DAG.getNode(ISD::TRUNCATE,
4266 DAG.getConstant(TruncC, TruncVT)));
4270 // fold operands of srl based on knowledge that the low bits are not
4272 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4273 return SDValue(N, 0);
4276 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4277 if (NewSRL.getNode())
4281 // Attempt to convert a srl of a load into a narrower zero-extending load.
4282 SDValue NarrowLoad = ReduceLoadWidth(N);
4283 if (NarrowLoad.getNode())
4286 // Here is a common situation. We want to optimize:
4289 // %b = and i32 %a, 2
4290 // %c = srl i32 %b, 1
4291 // brcond i32 %c ...
4297 // %c = setcc eq %b, 0
4300 // However when after the source operand of SRL is optimized into AND, the SRL
4301 // itself may not be optimized further. Look for it and add the BRCOND into
4303 if (N->hasOneUse()) {
4304 SDNode *Use = *N->use_begin();
4305 if (Use->getOpcode() == ISD::BRCOND)
4307 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4308 // Also look pass the truncate.
4309 Use = *Use->use_begin();
4310 if (Use->getOpcode() == ISD::BRCOND)
4318 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4319 SDValue N0 = N->getOperand(0);
4320 EVT VT = N->getValueType(0);
4322 // fold (ctlz c1) -> c2
4323 if (isa<ConstantSDNode>(N0))
4324 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4328 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4329 SDValue N0 = N->getOperand(0);
4330 EVT VT = N->getValueType(0);
4332 // fold (ctlz_zero_undef c1) -> c2
4333 if (isa<ConstantSDNode>(N0))
4334 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4338 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4339 SDValue N0 = N->getOperand(0);
4340 EVT VT = N->getValueType(0);
4342 // fold (cttz c1) -> c2
4343 if (isa<ConstantSDNode>(N0))
4344 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4348 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4349 SDValue N0 = N->getOperand(0);
4350 EVT VT = N->getValueType(0);
4352 // fold (cttz_zero_undef c1) -> c2
4353 if (isa<ConstantSDNode>(N0))
4354 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4358 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4359 SDValue N0 = N->getOperand(0);
4360 EVT VT = N->getValueType(0);
4362 // fold (ctpop c1) -> c2
4363 if (isa<ConstantSDNode>(N0))
4364 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4368 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4369 SDValue N0 = N->getOperand(0);
4370 SDValue N1 = N->getOperand(1);
4371 SDValue N2 = N->getOperand(2);
4372 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4373 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4374 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4375 EVT VT = N->getValueType(0);
4376 EVT VT0 = N0.getValueType();
4378 // fold (select C, X, X) -> X
4381 // fold (select true, X, Y) -> X
4382 if (N0C && !N0C->isNullValue())
4384 // fold (select false, X, Y) -> Y
4385 if (N0C && N0C->isNullValue())
4387 // fold (select C, 1, X) -> (or C, X)
4388 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4389 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4390 // fold (select C, 0, 1) -> (xor C, 1)
4391 if (VT.isInteger() &&
4394 TLI.getBooleanContents(false) ==
4395 TargetLowering::ZeroOrOneBooleanContent)) &&
4396 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4399 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4400 N0, DAG.getConstant(1, VT0));
4401 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4402 N0, DAG.getConstant(1, VT0));
4403 AddToWorkList(XORNode.getNode());
4405 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4406 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4408 // fold (select C, 0, X) -> (and (not C), X)
4409 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4410 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4411 AddToWorkList(NOTNode.getNode());
4412 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4414 // fold (select C, X, 1) -> (or (not C), X)
4415 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4416 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4417 AddToWorkList(NOTNode.getNode());
4418 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4420 // fold (select C, X, 0) -> (and C, X)
4421 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4422 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4423 // fold (select X, X, Y) -> (or X, Y)
4424 // fold (select X, 1, Y) -> (or X, Y)
4425 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4426 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4427 // fold (select X, Y, X) -> (and X, Y)
4428 // fold (select X, Y, 0) -> (and X, Y)
4429 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4430 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4432 // If we can fold this based on the true/false value, do so.
4433 if (SimplifySelectOps(N, N1, N2))
4434 return SDValue(N, 0); // Don't revisit N.
4436 // fold selects based on a setcc into other things, such as min/max/abs
4437 if (N0.getOpcode() == ISD::SETCC) {
4439 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4440 // having to say they don't support SELECT_CC on every type the DAG knows
4441 // about, since there is no way to mark an opcode illegal at all value types
4442 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4443 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4444 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4445 N0.getOperand(0), N0.getOperand(1),
4446 N1, N2, N0.getOperand(2));
4447 return SimplifySelect(SDLoc(N), N0, N1, N2);
4454 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4457 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4459 // Split the inputs.
4460 SDValue Lo, Hi, LL, LH, RL, RH;
4461 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4462 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4464 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4465 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4467 return std::make_pair(Lo, Hi);
4470 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4471 SDValue N0 = N->getOperand(0);
4472 SDValue N1 = N->getOperand(1);
4473 SDValue N2 = N->getOperand(2);
4476 // Canonicalize integer abs.
4477 // vselect (setg[te] X, 0), X, -X ->
4478 // vselect (setgt X, -1), X, -X ->
4479 // vselect (setl[te] X, 0), -X, X ->
4480 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4481 if (N0.getOpcode() == ISD::SETCC) {
4482 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4483 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4485 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4487 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4488 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4489 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4490 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4491 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4492 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4493 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4496 EVT VT = LHS.getValueType();
4497 SDValue Shift = DAG.getNode(
4498 ISD::SRA, DL, VT, LHS,
4499 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4500 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4501 AddToWorkList(Shift.getNode());
4502 AddToWorkList(Add.getNode());
4503 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4507 // If the VSELECT result requires splitting and the mask is provided by a
4508 // SETCC, then split both nodes and its operands before legalization. This
4509 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4510 // and enables future optimizations (e.g. min/max pattern matching on X86).
4511 if (N0.getOpcode() == ISD::SETCC) {
4512 EVT VT = N->getValueType(0);
4514 // Check if any splitting is required.
4515 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4516 TargetLowering::TypeSplitVector)
4519 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4520 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4521 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4522 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4524 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4525 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4527 // Add the new VSELECT nodes to the work list in case they need to be split
4529 AddToWorkList(Lo.getNode());
4530 AddToWorkList(Hi.getNode());
4532 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4535 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4536 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4538 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4539 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4545 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4546 SDValue N0 = N->getOperand(0);
4547 SDValue N1 = N->getOperand(1);
4548 SDValue N2 = N->getOperand(2);
4549 SDValue N3 = N->getOperand(3);
4550 SDValue N4 = N->getOperand(4);
4551 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4553 // fold select_cc lhs, rhs, x, x, cc -> x
4557 // Determine if the condition we're dealing with is constant
4558 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4559 N0, N1, CC, SDLoc(N), false);
4560 if (SCC.getNode()) {
4561 AddToWorkList(SCC.getNode());
4563 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4564 if (!SCCC->isNullValue())
4565 return N2; // cond always true -> true val
4567 return N3; // cond always false -> false val
4570 // Fold to a simpler select_cc
4571 if (SCC.getOpcode() == ISD::SETCC)
4572 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4573 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4577 // If we can fold this based on the true/false value, do so.
4578 if (SimplifySelectOps(N, N2, N3))
4579 return SDValue(N, 0); // Don't revisit N.
4581 // fold select_cc into other things, such as min/max/abs
4582 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4585 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4586 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4587 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4591 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4592 // dag node into a ConstantSDNode or a build_vector of constants.
4593 // This function is called by the DAGCombiner when visiting sext/zext/aext
4594 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4595 // Vector extends are not folded if operations are legal; this is to
4596 // avoid introducing illegal build_vector dag nodes.
4597 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4598 SelectionDAG &DAG, bool LegalTypes,
4599 bool LegalOperations) {
4600 unsigned Opcode = N->getOpcode();
4601 SDValue N0 = N->getOperand(0);
4602 EVT VT = N->getValueType(0);
4604 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4605 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4607 // fold (sext c1) -> c1
4608 // fold (zext c1) -> c1
4609 // fold (aext c1) -> c1
4610 if (isa<ConstantSDNode>(N0))
4611 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4613 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4614 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4615 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4616 EVT SVT = VT.getScalarType();
4617 if (!(VT.isVector() &&
4618 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4619 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4622 // We can fold this node into a build_vector.
4623 unsigned VTBits = SVT.getSizeInBits();
4624 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4625 unsigned ShAmt = VTBits - EVTBits;
4626 SmallVector<SDValue, 8> Elts;
4627 unsigned NumElts = N0->getNumOperands();
4630 for (unsigned i=0; i != NumElts; ++i) {
4631 SDValue Op = N0->getOperand(i);
4632 if (Op->getOpcode() == ISD::UNDEF) {
4633 Elts.push_back(DAG.getUNDEF(SVT));
4637 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4638 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4639 if (Opcode == ISD::SIGN_EXTEND)
4640 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4643 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4647 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4650 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4651 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4652 // transformation. Returns true if extension are possible and the above
4653 // mentioned transformation is profitable.
4654 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4656 SmallVectorImpl<SDNode *> &ExtendNodes,
4657 const TargetLowering &TLI) {
4658 bool HasCopyToRegUses = false;
4659 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4660 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4661 UE = N0.getNode()->use_end();
4666 if (UI.getUse().getResNo() != N0.getResNo())
4668 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4669 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4670 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4671 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4672 // Sign bits will be lost after a zext.
4675 for (unsigned i = 0; i != 2; ++i) {
4676 SDValue UseOp = User->getOperand(i);
4679 if (!isa<ConstantSDNode>(UseOp))
4684 ExtendNodes.push_back(User);
4687 // If truncates aren't free and there are users we can't
4688 // extend, it isn't worthwhile.
4691 // Remember if this value is live-out.
4692 if (User->getOpcode() == ISD::CopyToReg)
4693 HasCopyToRegUses = true;
4696 if (HasCopyToRegUses) {
4697 bool BothLiveOut = false;
4698 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4700 SDUse &Use = UI.getUse();
4701 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4707 // Both unextended and extended values are live out. There had better be
4708 // a good reason for the transformation.
4709 return ExtendNodes.size();
4714 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4715 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4716 ISD::NodeType ExtType) {
4717 // Extend SetCC uses if necessary.
4718 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4719 SDNode *SetCC = SetCCs[i];
4720 SmallVector<SDValue, 4> Ops;
4722 for (unsigned j = 0; j != 2; ++j) {
4723 SDValue SOp = SetCC->getOperand(j);
4725 Ops.push_back(ExtLoad);
4727 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4730 Ops.push_back(SetCC->getOperand(2));
4731 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4732 &Ops[0], Ops.size()));
4736 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4737 SDValue N0 = N->getOperand(0);
4738 EVT VT = N->getValueType(0);
4740 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4742 return SDValue(Res, 0);
4744 // fold (sext (sext x)) -> (sext x)
4745 // fold (sext (aext x)) -> (sext x)
4746 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4747 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4750 if (N0.getOpcode() == ISD::TRUNCATE) {
4751 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4752 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4753 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4754 if (NarrowLoad.getNode()) {
4755 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4756 if (NarrowLoad.getNode() != N0.getNode()) {
4757 CombineTo(N0.getNode(), NarrowLoad);
4758 // CombineTo deleted the truncate, if needed, but not what's under it.
4761 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4764 // See if the value being truncated is already sign extended. If so, just
4765 // eliminate the trunc/sext pair.
4766 SDValue Op = N0.getOperand(0);
4767 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4768 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4769 unsigned DestBits = VT.getScalarType().getSizeInBits();
4770 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4772 if (OpBits == DestBits) {
4773 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4774 // bits, it is already ready.
4775 if (NumSignBits > DestBits-MidBits)
4777 } else if (OpBits < DestBits) {
4778 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4779 // bits, just sext from i32.
4780 if (NumSignBits > OpBits-MidBits)
4781 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4783 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4784 // bits, just truncate to i32.
4785 if (NumSignBits > OpBits-MidBits)
4786 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4789 // fold (sext (truncate x)) -> (sextinreg x).
4790 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4791 N0.getValueType())) {
4792 if (OpBits < DestBits)
4793 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4794 else if (OpBits > DestBits)
4795 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4796 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4797 DAG.getValueType(N0.getValueType()));
4801 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4802 // None of the supported targets knows how to perform load and sign extend
4803 // on vectors in one instruction. We only perform this transformation on
4805 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4806 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4807 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4808 bool DoXform = true;
4809 SmallVector<SDNode*, 4> SetCCs;
4810 if (!N0.hasOneUse())
4811 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4814 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4816 LN0->getBasePtr(), N0.getValueType(),
4817 LN0->getMemOperand());
4818 CombineTo(N, ExtLoad);
4819 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4820 N0.getValueType(), ExtLoad);
4821 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4822 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4824 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4828 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4829 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4830 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4831 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4832 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4833 EVT MemVT = LN0->getMemoryVT();
4834 if ((!LegalOperations && !LN0->isVolatile()) ||
4835 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4836 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4838 LN0->getBasePtr(), MemVT,
4839 LN0->getMemOperand());
4840 CombineTo(N, ExtLoad);
4841 CombineTo(N0.getNode(),
4842 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4843 N0.getValueType(), ExtLoad),
4844 ExtLoad.getValue(1));
4845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4849 // fold (sext (and/or/xor (load x), cst)) ->
4850 // (and/or/xor (sextload x), (sext cst))
4851 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4852 N0.getOpcode() == ISD::XOR) &&
4853 isa<LoadSDNode>(N0.getOperand(0)) &&
4854 N0.getOperand(1).getOpcode() == ISD::Constant &&
4855 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4856 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4857 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4858 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4859 bool DoXform = true;
4860 SmallVector<SDNode*, 4> SetCCs;
4861 if (!N0.hasOneUse())
4862 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4865 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4866 LN0->getChain(), LN0->getBasePtr(),
4868 LN0->getMemOperand());
4869 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4870 Mask = Mask.sext(VT.getSizeInBits());
4871 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4872 ExtLoad, DAG.getConstant(Mask, VT));
4873 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4874 SDLoc(N0.getOperand(0)),
4875 N0.getOperand(0).getValueType(), ExtLoad);
4877 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4878 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4880 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4885 if (N0.getOpcode() == ISD::SETCC) {
4886 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4887 // Only do this before legalize for now.
4888 if (VT.isVector() && !LegalOperations &&
4889 TLI.getBooleanContents(true) ==
4890 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4891 EVT N0VT = N0.getOperand(0).getValueType();
4892 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4893 // of the same size as the compared operands. Only optimize sext(setcc())
4894 // if this is the case.
4895 EVT SVT = getSetCCResultType(N0VT);
4897 // We know that the # elements of the results is the same as the
4898 // # elements of the compare (and the # elements of the compare result
4899 // for that matter). Check to see that they are the same size. If so,
4900 // we know that the element size of the sext'd result matches the
4901 // element size of the compare operands.
4902 if (VT.getSizeInBits() == SVT.getSizeInBits())
4903 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4905 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4907 // If the desired elements are smaller or larger than the source
4908 // elements we can use a matching integer vector type and then
4909 // truncate/sign extend
4910 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4911 if (SVT == MatchingVectorType) {
4912 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4913 N0.getOperand(0), N0.getOperand(1),
4914 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4915 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4919 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
4920 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4922 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4924 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4925 NegOne, DAG.getConstant(0, VT),
4926 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4927 if (SCC.getNode()) return SCC;
4929 if (!VT.isVector()) {
4930 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4931 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
4933 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4934 SDValue SetCC = DAG.getSetCC(DL,
4936 N0.getOperand(0), N0.getOperand(1), CC);
4937 EVT SelectVT = getSetCCResultType(VT);
4938 return DAG.getSelect(DL, VT,
4939 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
4940 NegOne, DAG.getConstant(0, VT));
4946 // fold (sext x) -> (zext x) if the sign bit is known zero.
4947 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4948 DAG.SignBitIsZero(N0))
4949 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4954 // isTruncateOf - If N is a truncate of some other value, return true, record
4955 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4956 // This function computes KnownZero to avoid a duplicated call to
4957 // ComputeMaskedBits in the caller.
4958 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4961 if (N->getOpcode() == ISD::TRUNCATE) {
4962 Op = N->getOperand(0);
4963 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4967 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4968 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4971 SDValue Op0 = N->getOperand(0);
4972 SDValue Op1 = N->getOperand(1);
4973 assert(Op0.getValueType() == Op1.getValueType());
4975 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4976 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4977 if (COp0 && COp0->isNullValue())
4979 else if (COp1 && COp1->isNullValue())
4984 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4986 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4992 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4993 SDValue N0 = N->getOperand(0);
4994 EVT VT = N->getValueType(0);
4996 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4998 return SDValue(Res, 0);
5000 // fold (zext (zext x)) -> (zext x)
5001 // fold (zext (aext x)) -> (zext x)
5002 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5003 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5006 // fold (zext (truncate x)) -> (zext x) or
5007 // (zext (truncate x)) -> (truncate x)
5008 // This is valid when the truncated bits of x are already zero.
5009 // FIXME: We should extend this to work for vectors too.
5012 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5013 APInt TruncatedBits =
5014 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5015 APInt(Op.getValueSizeInBits(), 0) :
5016 APInt::getBitsSet(Op.getValueSizeInBits(),
5017 N0.getValueSizeInBits(),
5018 std::min(Op.getValueSizeInBits(),
5019 VT.getSizeInBits()));
5020 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5021 if (VT.bitsGT(Op.getValueType()))
5022 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5023 if (VT.bitsLT(Op.getValueType()))
5024 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5030 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5031 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5032 if (N0.getOpcode() == ISD::TRUNCATE) {
5033 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5034 if (NarrowLoad.getNode()) {
5035 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5036 if (NarrowLoad.getNode() != N0.getNode()) {
5037 CombineTo(N0.getNode(), NarrowLoad);
5038 // CombineTo deleted the truncate, if needed, but not what's under it.
5041 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5045 // fold (zext (truncate x)) -> (and x, mask)
5046 if (N0.getOpcode() == ISD::TRUNCATE &&
5047 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5049 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5050 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5051 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5052 if (NarrowLoad.getNode()) {
5053 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5054 if (NarrowLoad.getNode() != N0.getNode()) {
5055 CombineTo(N0.getNode(), NarrowLoad);
5056 // CombineTo deleted the truncate, if needed, but not what's under it.
5059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5062 SDValue Op = N0.getOperand(0);
5063 if (Op.getValueType().bitsLT(VT)) {
5064 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5065 AddToWorkList(Op.getNode());
5066 } else if (Op.getValueType().bitsGT(VT)) {
5067 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5068 AddToWorkList(Op.getNode());
5070 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5071 N0.getValueType().getScalarType());
5074 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5075 // if either of the casts is not free.
5076 if (N0.getOpcode() == ISD::AND &&
5077 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5078 N0.getOperand(1).getOpcode() == ISD::Constant &&
5079 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5080 N0.getValueType()) ||
5081 !TLI.isZExtFree(N0.getValueType(), VT))) {
5082 SDValue X = N0.getOperand(0).getOperand(0);
5083 if (X.getValueType().bitsLT(VT)) {
5084 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5085 } else if (X.getValueType().bitsGT(VT)) {
5086 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5088 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5089 Mask = Mask.zext(VT.getSizeInBits());
5090 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5091 X, DAG.getConstant(Mask, VT));
5094 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5095 // None of the supported targets knows how to perform load and vector_zext
5096 // on vectors in one instruction. We only perform this transformation on
5098 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5099 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5100 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5101 bool DoXform = true;
5102 SmallVector<SDNode*, 4> SetCCs;
5103 if (!N0.hasOneUse())
5104 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5106 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5107 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5109 LN0->getBasePtr(), N0.getValueType(),
5110 LN0->getMemOperand());
5111 CombineTo(N, ExtLoad);
5112 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5113 N0.getValueType(), ExtLoad);
5114 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5116 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5118 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5122 // fold (zext (and/or/xor (load x), cst)) ->
5123 // (and/or/xor (zextload x), (zext cst))
5124 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5125 N0.getOpcode() == ISD::XOR) &&
5126 isa<LoadSDNode>(N0.getOperand(0)) &&
5127 N0.getOperand(1).getOpcode() == ISD::Constant &&
5128 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5129 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5130 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5131 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5132 bool DoXform = true;
5133 SmallVector<SDNode*, 4> SetCCs;
5134 if (!N0.hasOneUse())
5135 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5138 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5139 LN0->getChain(), LN0->getBasePtr(),
5141 LN0->getMemOperand());
5142 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5143 Mask = Mask.zext(VT.getSizeInBits());
5144 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5145 ExtLoad, DAG.getConstant(Mask, VT));
5146 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5147 SDLoc(N0.getOperand(0)),
5148 N0.getOperand(0).getValueType(), ExtLoad);
5150 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5151 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5158 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5159 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5160 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5161 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5163 EVT MemVT = LN0->getMemoryVT();
5164 if ((!LegalOperations && !LN0->isVolatile()) ||
5165 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5166 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5168 LN0->getBasePtr(), MemVT,
5169 LN0->getMemOperand());
5170 CombineTo(N, ExtLoad);
5171 CombineTo(N0.getNode(),
5172 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5174 ExtLoad.getValue(1));
5175 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5179 if (N0.getOpcode() == ISD::SETCC) {
5180 if (!LegalOperations && VT.isVector() &&
5181 N0.getValueType().getVectorElementType() == MVT::i1) {
5182 EVT N0VT = N0.getOperand(0).getValueType();
5183 if (getSetCCResultType(N0VT) == N0.getValueType())
5186 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5187 // Only do this before legalize for now.
5188 EVT EltVT = VT.getVectorElementType();
5189 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5190 DAG.getConstant(1, EltVT));
5191 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5192 // We know that the # elements of the results is the same as the
5193 // # elements of the compare (and the # elements of the compare result
5194 // for that matter). Check to see that they are the same size. If so,
5195 // we know that the element size of the sext'd result matches the
5196 // element size of the compare operands.
5197 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5198 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5200 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5201 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5202 &OneOps[0], OneOps.size()));
5204 // If the desired elements are smaller or larger than the source
5205 // elements we can use a matching integer vector type and then
5206 // truncate/sign extend
5207 EVT MatchingElementType =
5208 EVT::getIntegerVT(*DAG.getContext(),
5209 N0VT.getScalarType().getSizeInBits());
5210 EVT MatchingVectorType =
5211 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5212 N0VT.getVectorNumElements());
5214 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5216 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5217 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5218 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5219 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5220 &OneOps[0], OneOps.size()));
5223 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5225 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5226 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5227 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5228 if (SCC.getNode()) return SCC;
5231 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5232 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5233 isa<ConstantSDNode>(N0.getOperand(1)) &&
5234 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5236 SDValue ShAmt = N0.getOperand(1);
5237 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5238 if (N0.getOpcode() == ISD::SHL) {
5239 SDValue InnerZExt = N0.getOperand(0);
5240 // If the original shl may be shifting out bits, do not perform this
5242 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5243 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5244 if (ShAmtVal > KnownZeroBits)
5250 // Ensure that the shift amount is wide enough for the shifted value.
5251 if (VT.getSizeInBits() >= 256)
5252 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5254 return DAG.getNode(N0.getOpcode(), DL, VT,
5255 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5262 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5263 SDValue N0 = N->getOperand(0);
5264 EVT VT = N->getValueType(0);
5266 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5268 return SDValue(Res, 0);
5270 // fold (aext (aext x)) -> (aext x)
5271 // fold (aext (zext x)) -> (zext x)
5272 // fold (aext (sext x)) -> (sext x)
5273 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5274 N0.getOpcode() == ISD::ZERO_EXTEND ||
5275 N0.getOpcode() == ISD::SIGN_EXTEND)
5276 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5278 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5279 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5280 if (N0.getOpcode() == ISD::TRUNCATE) {
5281 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5282 if (NarrowLoad.getNode()) {
5283 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5284 if (NarrowLoad.getNode() != N0.getNode()) {
5285 CombineTo(N0.getNode(), NarrowLoad);
5286 // CombineTo deleted the truncate, if needed, but not what's under it.
5289 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5293 // fold (aext (truncate x))
5294 if (N0.getOpcode() == ISD::TRUNCATE) {
5295 SDValue TruncOp = N0.getOperand(0);
5296 if (TruncOp.getValueType() == VT)
5297 return TruncOp; // x iff x size == zext size.
5298 if (TruncOp.getValueType().bitsGT(VT))
5299 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5300 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5303 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5304 // if the trunc is not free.
5305 if (N0.getOpcode() == ISD::AND &&
5306 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5307 N0.getOperand(1).getOpcode() == ISD::Constant &&
5308 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5309 N0.getValueType())) {
5310 SDValue X = N0.getOperand(0).getOperand(0);
5311 if (X.getValueType().bitsLT(VT)) {
5312 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5313 } else if (X.getValueType().bitsGT(VT)) {
5314 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5316 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5317 Mask = Mask.zext(VT.getSizeInBits());
5318 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5319 X, DAG.getConstant(Mask, VT));
5322 // fold (aext (load x)) -> (aext (truncate (extload x)))
5323 // None of the supported targets knows how to perform load and any_ext
5324 // on vectors in one instruction. We only perform this transformation on
5326 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5327 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5328 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5329 bool DoXform = true;
5330 SmallVector<SDNode*, 4> SetCCs;
5331 if (!N0.hasOneUse())
5332 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5334 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5335 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5337 LN0->getBasePtr(), N0.getValueType(),
5338 LN0->getMemOperand());
5339 CombineTo(N, ExtLoad);
5340 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5341 N0.getValueType(), ExtLoad);
5342 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5343 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5345 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5349 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5350 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5351 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5352 if (N0.getOpcode() == ISD::LOAD &&
5353 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5355 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5356 EVT MemVT = LN0->getMemoryVT();
5357 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5358 VT, LN0->getChain(), LN0->getBasePtr(),
5359 MemVT, LN0->getMemOperand());
5360 CombineTo(N, ExtLoad);
5361 CombineTo(N0.getNode(),
5362 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5363 N0.getValueType(), ExtLoad),
5364 ExtLoad.getValue(1));
5365 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5368 if (N0.getOpcode() == ISD::SETCC) {
5369 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5370 // Only do this before legalize for now.
5371 if (VT.isVector() && !LegalOperations) {
5372 EVT N0VT = N0.getOperand(0).getValueType();
5373 // We know that the # elements of the results is the same as the
5374 // # elements of the compare (and the # elements of the compare result
5375 // for that matter). Check to see that they are the same size. If so,
5376 // we know that the element size of the sext'd result matches the
5377 // element size of the compare operands.
5378 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5379 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5381 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5382 // If the desired elements are smaller or larger than the source
5383 // elements we can use a matching integer vector type and then
5384 // truncate/sign extend
5386 EVT MatchingElementType =
5387 EVT::getIntegerVT(*DAG.getContext(),
5388 N0VT.getScalarType().getSizeInBits());
5389 EVT MatchingVectorType =
5390 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5391 N0VT.getVectorNumElements());
5393 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5395 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5396 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5400 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5402 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5403 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5404 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5412 /// GetDemandedBits - See if the specified operand can be simplified with the
5413 /// knowledge that only the bits specified by Mask are used. If so, return the
5414 /// simpler operand, otherwise return a null SDValue.
5415 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5416 switch (V.getOpcode()) {
5418 case ISD::Constant: {
5419 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5420 assert(CV != 0 && "Const value should be ConstSDNode.");
5421 const APInt &CVal = CV->getAPIntValue();
5422 APInt NewVal = CVal & Mask;
5424 return DAG.getConstant(NewVal, V.getValueType());
5429 // If the LHS or RHS don't contribute bits to the or, drop them.
5430 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5431 return V.getOperand(1);
5432 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5433 return V.getOperand(0);
5436 // Only look at single-use SRLs.
5437 if (!V.getNode()->hasOneUse())
5439 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5440 // See if we can recursively simplify the LHS.
5441 unsigned Amt = RHSC->getZExtValue();
5443 // Watch out for shift count overflow though.
5444 if (Amt >= Mask.getBitWidth()) break;
5445 APInt NewMask = Mask << Amt;
5446 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5447 if (SimplifyLHS.getNode())
5448 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5449 SimplifyLHS, V.getOperand(1));
5455 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5456 /// bits and then truncated to a narrower type and where N is a multiple
5457 /// of number of bits of the narrower type, transform it to a narrower load
5458 /// from address + N / num of bits of new type. If the result is to be
5459 /// extended, also fold the extension to form a extending load.
5460 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5461 unsigned Opc = N->getOpcode();
5463 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5464 SDValue N0 = N->getOperand(0);
5465 EVT VT = N->getValueType(0);
5468 // This transformation isn't valid for vector loads.
5472 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5474 if (Opc == ISD::SIGN_EXTEND_INREG) {
5475 ExtType = ISD::SEXTLOAD;
5476 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5477 } else if (Opc == ISD::SRL) {
5478 // Another special-case: SRL is basically zero-extending a narrower value.
5479 ExtType = ISD::ZEXTLOAD;
5481 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5482 if (!N01) return SDValue();
5483 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5484 VT.getSizeInBits() - N01->getZExtValue());
5486 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5489 unsigned EVTBits = ExtVT.getSizeInBits();
5491 // Do not generate loads of non-round integer types since these can
5492 // be expensive (and would be wrong if the type is not byte sized).
5493 if (!ExtVT.isRound())
5497 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5498 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5499 ShAmt = N01->getZExtValue();
5500 // Is the shift amount a multiple of size of VT?
5501 if ((ShAmt & (EVTBits-1)) == 0) {
5502 N0 = N0.getOperand(0);
5503 // Is the load width a multiple of size of VT?
5504 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5508 // At this point, we must have a load or else we can't do the transform.
5509 if (!isa<LoadSDNode>(N0)) return SDValue();
5511 // Because a SRL must be assumed to *need* to zero-extend the high bits
5512 // (as opposed to anyext the high bits), we can't combine the zextload
5513 // lowering of SRL and an sextload.
5514 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5517 // If the shift amount is larger than the input type then we're not
5518 // accessing any of the loaded bytes. If the load was a zextload/extload
5519 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5520 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5525 // If the load is shifted left (and the result isn't shifted back right),
5526 // we can fold the truncate through the shift.
5527 unsigned ShLeftAmt = 0;
5528 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5529 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5530 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5531 ShLeftAmt = N01->getZExtValue();
5532 N0 = N0.getOperand(0);
5536 // If we haven't found a load, we can't narrow it. Don't transform one with
5537 // multiple uses, this would require adding a new load.
5538 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5541 // Don't change the width of a volatile load.
5542 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5543 if (LN0->isVolatile())
5546 // Verify that we are actually reducing a load width here.
5547 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5550 // For the transform to be legal, the load must produce only two values
5551 // (the value loaded and the chain). Don't transform a pre-increment
5552 // load, for example, which produces an extra value. Otherwise the
5553 // transformation is not equivalent, and the downstream logic to replace
5554 // uses gets things wrong.
5555 if (LN0->getNumValues() > 2)
5558 // If the load that we're shrinking is an extload and we're not just
5559 // discarding the extension we can't simply shrink the load. Bail.
5560 // TODO: It would be possible to merge the extensions in some cases.
5561 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5562 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5565 EVT PtrType = N0.getOperand(1).getValueType();
5567 if (PtrType == MVT::Untyped || PtrType.isExtended())
5568 // It's not possible to generate a constant of extended or untyped type.
5571 // For big endian targets, we need to adjust the offset to the pointer to
5572 // load the correct bytes.
5573 if (TLI.isBigEndian()) {
5574 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5575 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5576 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5579 uint64_t PtrOff = ShAmt / 8;
5580 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5581 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5582 PtrType, LN0->getBasePtr(),
5583 DAG.getConstant(PtrOff, PtrType));
5584 AddToWorkList(NewPtr.getNode());
5587 if (ExtType == ISD::NON_EXTLOAD)
5588 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5589 LN0->getPointerInfo().getWithOffset(PtrOff),
5590 LN0->isVolatile(), LN0->isNonTemporal(),
5591 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5593 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5594 LN0->getPointerInfo().getWithOffset(PtrOff),
5595 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5596 NewAlign, LN0->getTBAAInfo());
5598 // Replace the old load's chain with the new load's chain.
5599 WorkListRemover DeadNodes(*this);
5600 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5602 // Shift the result left, if we've swallowed a left shift.
5603 SDValue Result = Load;
5604 if (ShLeftAmt != 0) {
5605 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5606 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5608 // If the shift amount is as large as the result size (but, presumably,
5609 // no larger than the source) then the useful bits of the result are
5610 // zero; we can't simply return the shortened shift, because the result
5611 // of that operation is undefined.
5612 if (ShLeftAmt >= VT.getSizeInBits())
5613 Result = DAG.getConstant(0, VT);
5615 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5616 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5619 // Return the new loaded value.
5623 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5624 SDValue N0 = N->getOperand(0);
5625 SDValue N1 = N->getOperand(1);
5626 EVT VT = N->getValueType(0);
5627 EVT EVT = cast<VTSDNode>(N1)->getVT();
5628 unsigned VTBits = VT.getScalarType().getSizeInBits();
5629 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5631 // fold (sext_in_reg c1) -> c1
5632 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5633 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5635 // If the input is already sign extended, just drop the extension.
5636 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5639 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5640 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5641 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5642 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5643 N0.getOperand(0), N1);
5645 // fold (sext_in_reg (sext x)) -> (sext x)
5646 // fold (sext_in_reg (aext x)) -> (sext x)
5647 // if x is small enough.
5648 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5649 SDValue N00 = N0.getOperand(0);
5650 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5651 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5652 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5655 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5656 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5657 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5659 // fold operands of sext_in_reg based on knowledge that the top bits are not
5661 if (SimplifyDemandedBits(SDValue(N, 0)))
5662 return SDValue(N, 0);
5664 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5665 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5666 SDValue NarrowLoad = ReduceLoadWidth(N);
5667 if (NarrowLoad.getNode())
5670 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5671 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5672 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5673 if (N0.getOpcode() == ISD::SRL) {
5674 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5675 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5676 // We can turn this into an SRA iff the input to the SRL is already sign
5678 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5679 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5680 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5681 N0.getOperand(0), N0.getOperand(1));
5685 // fold (sext_inreg (extload x)) -> (sextload x)
5686 if (ISD::isEXTLoad(N0.getNode()) &&
5687 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5688 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5689 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5690 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5691 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5692 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5694 LN0->getBasePtr(), EVT,
5695 LN0->getMemOperand());
5696 CombineTo(N, ExtLoad);
5697 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5698 AddToWorkList(ExtLoad.getNode());
5699 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5701 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5702 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5704 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5705 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5706 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5707 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5708 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5710 LN0->getBasePtr(), EVT,
5711 LN0->getMemOperand());
5712 CombineTo(N, ExtLoad);
5713 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5714 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5717 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5718 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5719 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5720 N0.getOperand(1), false);
5721 if (BSwap.getNode() != 0)
5722 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5726 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5727 // into a build_vector.
5728 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5729 SmallVector<SDValue, 8> Elts;
5730 unsigned NumElts = N0->getNumOperands();
5731 unsigned ShAmt = VTBits - EVTBits;
5733 for (unsigned i = 0; i != NumElts; ++i) {
5734 SDValue Op = N0->getOperand(i);
5735 if (Op->getOpcode() == ISD::UNDEF) {
5740 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5741 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5742 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5743 Op.getValueType()));
5746 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5752 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5753 SDValue N0 = N->getOperand(0);
5754 EVT VT = N->getValueType(0);
5755 bool isLE = TLI.isLittleEndian();
5758 if (N0.getValueType() == N->getValueType(0))
5760 // fold (truncate c1) -> c1
5761 if (isa<ConstantSDNode>(N0))
5762 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5763 // fold (truncate (truncate x)) -> (truncate x)
5764 if (N0.getOpcode() == ISD::TRUNCATE)
5765 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5766 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5767 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5768 N0.getOpcode() == ISD::SIGN_EXTEND ||
5769 N0.getOpcode() == ISD::ANY_EXTEND) {
5770 if (N0.getOperand(0).getValueType().bitsLT(VT))
5771 // if the source is smaller than the dest, we still need an extend
5772 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5774 if (N0.getOperand(0).getValueType().bitsGT(VT))
5775 // if the source is larger than the dest, than we just need the truncate
5776 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5777 // if the source and dest are the same type, we can drop both the extend
5778 // and the truncate.
5779 return N0.getOperand(0);
5782 // Fold extract-and-trunc into a narrow extract. For example:
5783 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5784 // i32 y = TRUNCATE(i64 x)
5786 // v16i8 b = BITCAST (v2i64 val)
5787 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5789 // Note: We only run this optimization after type legalization (which often
5790 // creates this pattern) and before operation legalization after which
5791 // we need to be more careful about the vector instructions that we generate.
5792 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5793 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5795 EVT VecTy = N0.getOperand(0).getValueType();
5796 EVT ExTy = N0.getValueType();
5797 EVT TrTy = N->getValueType(0);
5799 unsigned NumElem = VecTy.getVectorNumElements();
5800 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5802 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5803 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5805 SDValue EltNo = N0->getOperand(1);
5806 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5807 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5808 EVT IndexTy = TLI.getVectorIdxTy();
5809 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5811 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5812 NVT, N0.getOperand(0));
5814 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5816 DAG.getConstant(Index, IndexTy));
5820 // Fold a series of buildvector, bitcast, and truncate if possible.
5822 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5823 // (2xi32 (buildvector x, y)).
5824 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5825 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5826 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5827 N0.getOperand(0).hasOneUse()) {
5829 SDValue BuildVect = N0.getOperand(0);
5830 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5831 EVT TruncVecEltTy = VT.getVectorElementType();
5833 // Check that the element types match.
5834 if (BuildVectEltTy == TruncVecEltTy) {
5835 // Now we only need to compute the offset of the truncated elements.
5836 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5837 unsigned TruncVecNumElts = VT.getVectorNumElements();
5838 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5840 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5841 "Invalid number of elements");
5843 SmallVector<SDValue, 8> Opnds;
5844 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5845 Opnds.push_back(BuildVect.getOperand(i));
5847 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5852 // See if we can simplify the input to this truncate through knowledge that
5853 // only the low bits are being used.
5854 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5855 // Currently we only perform this optimization on scalars because vectors
5856 // may have different active low bits.
5857 if (!VT.isVector()) {
5859 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5860 VT.getSizeInBits()));
5861 if (Shorter.getNode())
5862 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5864 // fold (truncate (load x)) -> (smaller load x)
5865 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5866 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5867 SDValue Reduced = ReduceLoadWidth(N);
5868 if (Reduced.getNode())
5870 // Handle the case where the load remains an extending load even
5871 // after truncation.
5872 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5873 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5874 if (!LN0->isVolatile() &&
5875 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5876 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5877 VT, LN0->getChain(), LN0->getBasePtr(),
5879 LN0->getMemOperand());
5880 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5885 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5886 // where ... are all 'undef'.
5887 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5888 SmallVector<EVT, 8> VTs;
5891 unsigned NumDefs = 0;
5893 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5894 SDValue X = N0.getOperand(i);
5895 if (X.getOpcode() != ISD::UNDEF) {
5900 // Stop if more than one members are non-undef.
5903 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5904 VT.getVectorElementType(),
5905 X.getValueType().getVectorNumElements()));
5909 return DAG.getUNDEF(VT);
5912 assert(V.getNode() && "The single defined operand is empty!");
5913 SmallVector<SDValue, 8> Opnds;
5914 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5916 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5919 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5920 AddToWorkList(NV.getNode());
5921 Opnds.push_back(NV);
5923 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5924 &Opnds[0], Opnds.size());
5928 // Simplify the operands using demanded-bits information.
5929 if (!VT.isVector() &&
5930 SimplifyDemandedBits(SDValue(N, 0)))
5931 return SDValue(N, 0);
5936 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5937 SDValue Elt = N->getOperand(i);
5938 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5939 return Elt.getNode();
5940 return Elt.getOperand(Elt.getResNo()).getNode();
5943 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5944 /// if load locations are consecutive.
5945 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5946 assert(N->getOpcode() == ISD::BUILD_PAIR);
5948 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5949 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5950 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5951 LD1->getPointerInfo().getAddrSpace() !=
5952 LD2->getPointerInfo().getAddrSpace())
5954 EVT LD1VT = LD1->getValueType(0);
5956 if (ISD::isNON_EXTLoad(LD2) &&
5958 // If both are volatile this would reduce the number of volatile loads.
5959 // If one is volatile it might be ok, but play conservative and bail out.
5960 !LD1->isVolatile() &&
5961 !LD2->isVolatile() &&
5962 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5963 unsigned Align = LD1->getAlignment();
5964 unsigned NewAlign = TLI.getDataLayout()->
5965 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5967 if (NewAlign <= Align &&
5968 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5969 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5970 LD1->getBasePtr(), LD1->getPointerInfo(),
5971 false, false, false, Align);
5977 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5978 SDValue N0 = N->getOperand(0);
5979 EVT VT = N->getValueType(0);
5981 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5982 // Only do this before legalize, since afterward the target may be depending
5983 // on the bitconvert.
5984 // First check to see if this is all constant.
5986 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5988 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5990 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5991 assert(!DestEltVT.isVector() &&
5992 "Element type of vector ValueType must not be vector!");
5994 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5997 // If the input is a constant, let getNode fold it.
5998 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5999 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6000 if (Res.getNode() != N) {
6001 if (!LegalOperations ||
6002 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6005 // Folding it resulted in an illegal node, and it's too late to
6006 // do that. Clean up the old node and forego the transformation.
6007 // Ideally this won't happen very often, because instcombine
6008 // and the earlier dagcombine runs (where illegal nodes are
6009 // permitted) should have folded most of them already.
6010 DAG.DeleteNode(Res.getNode());
6014 // (conv (conv x, t1), t2) -> (conv x, t2)
6015 if (N0.getOpcode() == ISD::BITCAST)
6016 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6019 // fold (conv (load x)) -> (load (conv*)x)
6020 // If the resultant load doesn't need a higher alignment than the original!
6021 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6022 // Do not change the width of a volatile load.
6023 !cast<LoadSDNode>(N0)->isVolatile() &&
6024 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6025 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6026 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6027 unsigned Align = TLI.getDataLayout()->
6028 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6029 unsigned OrigAlign = LN0->getAlignment();
6031 if (Align <= OrigAlign) {
6032 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6033 LN0->getBasePtr(), LN0->getPointerInfo(),
6034 LN0->isVolatile(), LN0->isNonTemporal(),
6035 LN0->isInvariant(), OrigAlign,
6036 LN0->getTBAAInfo());
6038 CombineTo(N0.getNode(),
6039 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6040 N0.getValueType(), Load),
6046 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6047 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6048 // This often reduces constant pool loads.
6049 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6050 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6051 N0.getNode()->hasOneUse() && VT.isInteger() &&
6052 !VT.isVector() && !N0.getValueType().isVector()) {
6053 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6055 AddToWorkList(NewConv.getNode());
6057 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6058 if (N0.getOpcode() == ISD::FNEG)
6059 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6060 NewConv, DAG.getConstant(SignBit, VT));
6061 assert(N0.getOpcode() == ISD::FABS);
6062 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6063 NewConv, DAG.getConstant(~SignBit, VT));
6066 // fold (bitconvert (fcopysign cst, x)) ->
6067 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6068 // Note that we don't handle (copysign x, cst) because this can always be
6069 // folded to an fneg or fabs.
6070 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6071 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6072 VT.isInteger() && !VT.isVector()) {
6073 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6074 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6075 if (isTypeLegal(IntXVT)) {
6076 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6077 IntXVT, N0.getOperand(1));
6078 AddToWorkList(X.getNode());
6080 // If X has a different width than the result/lhs, sext it or truncate it.
6081 unsigned VTWidth = VT.getSizeInBits();
6082 if (OrigXWidth < VTWidth) {
6083 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6084 AddToWorkList(X.getNode());
6085 } else if (OrigXWidth > VTWidth) {
6086 // To get the sign bit in the right place, we have to shift it right
6087 // before truncating.
6088 X = DAG.getNode(ISD::SRL, SDLoc(X),
6089 X.getValueType(), X,
6090 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6091 AddToWorkList(X.getNode());
6092 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6093 AddToWorkList(X.getNode());
6096 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6097 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6098 X, DAG.getConstant(SignBit, VT));
6099 AddToWorkList(X.getNode());
6101 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6102 VT, N0.getOperand(0));
6103 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6104 Cst, DAG.getConstant(~SignBit, VT));
6105 AddToWorkList(Cst.getNode());
6107 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6111 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6112 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6113 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6114 if (CombineLD.getNode())
6121 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6122 EVT VT = N->getValueType(0);
6123 return CombineConsecutiveLoads(N, VT);
6126 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6127 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6128 /// destination element value type.
6129 SDValue DAGCombiner::
6130 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6131 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6133 // If this is already the right type, we're done.
6134 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6136 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6137 unsigned DstBitSize = DstEltVT.getSizeInBits();
6139 // If this is a conversion of N elements of one type to N elements of another
6140 // type, convert each element. This handles FP<->INT cases.
6141 if (SrcBitSize == DstBitSize) {
6142 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6143 BV->getValueType(0).getVectorNumElements());
6145 // Due to the FP element handling below calling this routine recursively,
6146 // we can end up with a scalar-to-vector node here.
6147 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6148 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6149 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6150 DstEltVT, BV->getOperand(0)));
6152 SmallVector<SDValue, 8> Ops;
6153 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6154 SDValue Op = BV->getOperand(i);
6155 // If the vector element type is not legal, the BUILD_VECTOR operands
6156 // are promoted and implicitly truncated. Make that explicit here.
6157 if (Op.getValueType() != SrcEltVT)
6158 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6159 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6161 AddToWorkList(Ops.back().getNode());
6163 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6164 &Ops[0], Ops.size());
6167 // Otherwise, we're growing or shrinking the elements. To avoid having to
6168 // handle annoying details of growing/shrinking FP values, we convert them to
6170 if (SrcEltVT.isFloatingPoint()) {
6171 // Convert the input float vector to a int vector where the elements are the
6173 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6174 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6175 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6179 // Now we know the input is an integer vector. If the output is a FP type,
6180 // convert to integer first, then to FP of the right size.
6181 if (DstEltVT.isFloatingPoint()) {
6182 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6183 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6184 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6186 // Next, convert to FP elements of the same size.
6187 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6190 // Okay, we know the src/dst types are both integers of differing types.
6191 // Handling growing first.
6192 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6193 if (SrcBitSize < DstBitSize) {
6194 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6196 SmallVector<SDValue, 8> Ops;
6197 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6198 i += NumInputsPerOutput) {
6199 bool isLE = TLI.isLittleEndian();
6200 APInt NewBits = APInt(DstBitSize, 0);
6201 bool EltIsUndef = true;
6202 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6203 // Shift the previously computed bits over.
6204 NewBits <<= SrcBitSize;
6205 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6206 if (Op.getOpcode() == ISD::UNDEF) continue;
6209 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6210 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6214 Ops.push_back(DAG.getUNDEF(DstEltVT));
6216 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6219 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6220 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6221 &Ops[0], Ops.size());
6224 // Finally, this must be the case where we are shrinking elements: each input
6225 // turns into multiple outputs.
6226 bool isS2V = ISD::isScalarToVector(BV);
6227 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6228 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6229 NumOutputsPerInput*BV->getNumOperands());
6230 SmallVector<SDValue, 8> Ops;
6232 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6233 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6234 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6235 Ops.push_back(DAG.getUNDEF(DstEltVT));
6239 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6240 getAPIntValue().zextOrTrunc(SrcBitSize);
6242 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6243 APInt ThisVal = OpVal.trunc(DstBitSize);
6244 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6245 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6246 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6247 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6249 OpVal = OpVal.lshr(DstBitSize);
6252 // For big endian targets, swap the order of the pieces of each element.
6253 if (TLI.isBigEndian())
6254 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6257 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6258 &Ops[0], Ops.size());
6261 SDValue DAGCombiner::visitFADD(SDNode *N) {
6262 SDValue N0 = N->getOperand(0);
6263 SDValue N1 = N->getOperand(1);
6264 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6265 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6266 EVT VT = N->getValueType(0);
6269 if (VT.isVector()) {
6270 SDValue FoldedVOp = SimplifyVBinOp(N);
6271 if (FoldedVOp.getNode()) return FoldedVOp;
6274 // fold (fadd c1, c2) -> c1 + c2
6276 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6277 // canonicalize constant to RHS
6278 if (N0CFP && !N1CFP)
6279 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6280 // fold (fadd A, 0) -> A
6281 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6282 N1CFP->getValueAPF().isZero())
6284 // fold (fadd A, (fneg B)) -> (fsub A, B)
6285 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6286 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6287 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6288 GetNegatedExpression(N1, DAG, LegalOperations));
6289 // fold (fadd (fneg A), B) -> (fsub B, A)
6290 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6291 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6292 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6293 GetNegatedExpression(N0, DAG, LegalOperations));
6295 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6296 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6297 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6298 isa<ConstantFPSDNode>(N0.getOperand(1)))
6299 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6300 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6301 N0.getOperand(1), N1));
6303 // No FP constant should be created after legalization as Instruction
6304 // Selection pass has hard time in dealing with FP constant.
6306 // We don't need test this condition for transformation like following, as
6307 // the DAG being transformed implies it is legal to take FP constant as
6310 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6312 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6314 // If allow, fold (fadd (fneg x), x) -> 0.0
6315 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6316 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6317 return DAG.getConstantFP(0.0, VT);
6319 // If allow, fold (fadd x, (fneg x)) -> 0.0
6320 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6321 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6322 return DAG.getConstantFP(0.0, VT);
6324 // In unsafe math mode, we can fold chains of FADD's of the same value
6325 // into multiplications. This transform is not safe in general because
6326 // we are reducing the number of rounding steps.
6327 if (DAG.getTarget().Options.UnsafeFPMath &&
6328 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6330 if (N0.getOpcode() == ISD::FMUL) {
6331 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6332 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6334 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6335 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6336 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6338 DAG.getConstantFP(1.0, VT));
6339 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6343 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6344 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6345 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6347 DAG.getConstantFP(1.0, VT));
6348 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6352 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6353 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6354 N1.getOperand(0) == N1.getOperand(1) &&
6355 N0.getOperand(1) == N1.getOperand(0)) {
6356 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6358 DAG.getConstantFP(2.0, VT));
6359 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6360 N0.getOperand(1), NewCFP);
6363 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6364 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6365 N1.getOperand(0) == N1.getOperand(1) &&
6366 N0.getOperand(0) == N1.getOperand(0)) {
6367 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6369 DAG.getConstantFP(2.0, VT));
6370 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6371 N0.getOperand(0), NewCFP);
6375 if (N1.getOpcode() == ISD::FMUL) {
6376 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6377 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6379 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6380 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6381 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6383 DAG.getConstantFP(1.0, VT));
6384 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6388 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6389 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6390 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6392 DAG.getConstantFP(1.0, VT));
6393 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6398 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6399 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6400 N0.getOperand(0) == N0.getOperand(1) &&
6401 N1.getOperand(1) == N0.getOperand(0)) {
6402 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6404 DAG.getConstantFP(2.0, VT));
6405 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6406 N1.getOperand(1), NewCFP);
6409 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6410 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6411 N0.getOperand(0) == N0.getOperand(1) &&
6412 N1.getOperand(0) == N0.getOperand(0)) {
6413 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6415 DAG.getConstantFP(2.0, VT));
6416 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6417 N1.getOperand(0), NewCFP);
6421 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6422 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6423 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6424 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6425 (N0.getOperand(0) == N1))
6426 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6427 N1, DAG.getConstantFP(3.0, VT));
6430 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6431 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6432 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6433 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6434 N1.getOperand(0) == N0)
6435 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6436 N0, DAG.getConstantFP(3.0, VT));
6439 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6440 if (AllowNewFpConst &&
6441 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6442 N0.getOperand(0) == N0.getOperand(1) &&
6443 N1.getOperand(0) == N1.getOperand(1) &&
6444 N0.getOperand(0) == N1.getOperand(0))
6445 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6447 DAG.getConstantFP(4.0, VT));
6450 // FADD -> FMA combines:
6451 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6452 DAG.getTarget().Options.UnsafeFPMath) &&
6453 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6454 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6456 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6457 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6458 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6459 N0.getOperand(0), N0.getOperand(1), N1);
6461 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6462 // Note: Commutes FADD operands.
6463 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6464 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6465 N1.getOperand(0), N1.getOperand(1), N0);
6471 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6472 SDValue N0 = N->getOperand(0);
6473 SDValue N1 = N->getOperand(1);
6474 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6475 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6476 EVT VT = N->getValueType(0);
6480 if (VT.isVector()) {
6481 SDValue FoldedVOp = SimplifyVBinOp(N);
6482 if (FoldedVOp.getNode()) return FoldedVOp;
6485 // fold (fsub c1, c2) -> c1-c2
6487 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6488 // fold (fsub A, 0) -> A
6489 if (DAG.getTarget().Options.UnsafeFPMath &&
6490 N1CFP && N1CFP->getValueAPF().isZero())
6492 // fold (fsub 0, B) -> -B
6493 if (DAG.getTarget().Options.UnsafeFPMath &&
6494 N0CFP && N0CFP->getValueAPF().isZero()) {
6495 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6496 return GetNegatedExpression(N1, DAG, LegalOperations);
6497 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6498 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6500 // fold (fsub A, (fneg B)) -> (fadd A, B)
6501 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6502 return DAG.getNode(ISD::FADD, dl, VT, N0,
6503 GetNegatedExpression(N1, DAG, LegalOperations));
6505 // If 'unsafe math' is enabled, fold
6506 // (fsub x, x) -> 0.0 &
6507 // (fsub x, (fadd x, y)) -> (fneg y) &
6508 // (fsub x, (fadd y, x)) -> (fneg y)
6509 if (DAG.getTarget().Options.UnsafeFPMath) {
6511 return DAG.getConstantFP(0.0f, VT);
6513 if (N1.getOpcode() == ISD::FADD) {
6514 SDValue N10 = N1->getOperand(0);
6515 SDValue N11 = N1->getOperand(1);
6517 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6518 &DAG.getTarget().Options))
6519 return GetNegatedExpression(N11, DAG, LegalOperations);
6521 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6522 &DAG.getTarget().Options))
6523 return GetNegatedExpression(N10, DAG, LegalOperations);
6527 // FSUB -> FMA combines:
6528 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6529 DAG.getTarget().Options.UnsafeFPMath) &&
6530 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6531 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6533 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6534 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6535 return DAG.getNode(ISD::FMA, dl, VT,
6536 N0.getOperand(0), N0.getOperand(1),
6537 DAG.getNode(ISD::FNEG, dl, VT, N1));
6539 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6540 // Note: Commutes FSUB operands.
6541 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6542 return DAG.getNode(ISD::FMA, dl, VT,
6543 DAG.getNode(ISD::FNEG, dl, VT,
6545 N1.getOperand(1), N0);
6547 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6548 if (N0.getOpcode() == ISD::FNEG &&
6549 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6550 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6551 SDValue N00 = N0.getOperand(0).getOperand(0);
6552 SDValue N01 = N0.getOperand(0).getOperand(1);
6553 return DAG.getNode(ISD::FMA, dl, VT,
6554 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6555 DAG.getNode(ISD::FNEG, dl, VT, N1));
6562 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6563 SDValue N0 = N->getOperand(0);
6564 SDValue N1 = N->getOperand(1);
6565 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6566 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6567 EVT VT = N->getValueType(0);
6568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6571 if (VT.isVector()) {
6572 SDValue FoldedVOp = SimplifyVBinOp(N);
6573 if (FoldedVOp.getNode()) return FoldedVOp;
6576 // fold (fmul c1, c2) -> c1*c2
6578 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6579 // canonicalize constant to RHS
6580 if (N0CFP && !N1CFP)
6581 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6582 // fold (fmul A, 0) -> 0
6583 if (DAG.getTarget().Options.UnsafeFPMath &&
6584 N1CFP && N1CFP->getValueAPF().isZero())
6586 // fold (fmul A, 0) -> 0, vector edition.
6587 if (DAG.getTarget().Options.UnsafeFPMath &&
6588 ISD::isBuildVectorAllZeros(N1.getNode()))
6590 // fold (fmul A, 1.0) -> A
6591 if (N1CFP && N1CFP->isExactlyValue(1.0))
6593 // fold (fmul X, 2.0) -> (fadd X, X)
6594 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6595 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6596 // fold (fmul X, -1.0) -> (fneg X)
6597 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6598 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6599 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6601 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6602 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6603 &DAG.getTarget().Options)) {
6604 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6605 &DAG.getTarget().Options)) {
6606 // Both can be negated for free, check to see if at least one is cheaper
6608 if (LHSNeg == 2 || RHSNeg == 2)
6609 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6610 GetNegatedExpression(N0, DAG, LegalOperations),
6611 GetNegatedExpression(N1, DAG, LegalOperations));
6615 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6616 if (DAG.getTarget().Options.UnsafeFPMath &&
6617 N1CFP && N0.getOpcode() == ISD::FMUL &&
6618 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6619 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6620 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6621 N0.getOperand(1), N1));
6626 SDValue DAGCombiner::visitFMA(SDNode *N) {
6627 SDValue N0 = N->getOperand(0);
6628 SDValue N1 = N->getOperand(1);
6629 SDValue N2 = N->getOperand(2);
6630 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6631 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6632 EVT VT = N->getValueType(0);
6635 if (DAG.getTarget().Options.UnsafeFPMath) {
6636 if (N0CFP && N0CFP->isZero())
6638 if (N1CFP && N1CFP->isZero())
6641 if (N0CFP && N0CFP->isExactlyValue(1.0))
6642 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6643 if (N1CFP && N1CFP->isExactlyValue(1.0))
6644 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6646 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6647 if (N0CFP && !N1CFP)
6648 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6650 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6651 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6652 N2.getOpcode() == ISD::FMUL &&
6653 N0 == N2.getOperand(0) &&
6654 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6655 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6656 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6660 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6661 if (DAG.getTarget().Options.UnsafeFPMath &&
6662 N0.getOpcode() == ISD::FMUL && N1CFP &&
6663 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6664 return DAG.getNode(ISD::FMA, dl, VT,
6666 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6670 // (fma x, 1, y) -> (fadd x, y)
6671 // (fma x, -1, y) -> (fadd (fneg x), y)
6673 if (N1CFP->isExactlyValue(1.0))
6674 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6676 if (N1CFP->isExactlyValue(-1.0) &&
6677 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6678 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6679 AddToWorkList(RHSNeg.getNode());
6680 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6684 // (fma x, c, x) -> (fmul x, (c+1))
6685 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6686 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6687 DAG.getNode(ISD::FADD, dl, VT,
6688 N1, DAG.getConstantFP(1.0, VT)));
6690 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6691 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6692 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6693 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6694 DAG.getNode(ISD::FADD, dl, VT,
6695 N1, DAG.getConstantFP(-1.0, VT)));
6701 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6702 SDValue N0 = N->getOperand(0);
6703 SDValue N1 = N->getOperand(1);
6704 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6705 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6706 EVT VT = N->getValueType(0);
6707 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6710 if (VT.isVector()) {
6711 SDValue FoldedVOp = SimplifyVBinOp(N);
6712 if (FoldedVOp.getNode()) return FoldedVOp;
6715 // fold (fdiv c1, c2) -> c1/c2
6717 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6719 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6720 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6721 // Compute the reciprocal 1.0 / c2.
6722 APFloat N1APF = N1CFP->getValueAPF();
6723 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6724 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6725 // Only do the transform if the reciprocal is a legal fp immediate that
6726 // isn't too nasty (eg NaN, denormal, ...).
6727 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6728 (!LegalOperations ||
6729 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6730 // backend)... we should handle this gracefully after Legalize.
6731 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6732 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6733 TLI.isFPImmLegal(Recip, VT)))
6734 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6735 DAG.getConstantFP(Recip, VT));
6738 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6739 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6740 &DAG.getTarget().Options)) {
6741 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6742 &DAG.getTarget().Options)) {
6743 // Both can be negated for free, check to see if at least one is cheaper
6745 if (LHSNeg == 2 || RHSNeg == 2)
6746 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6747 GetNegatedExpression(N0, DAG, LegalOperations),
6748 GetNegatedExpression(N1, DAG, LegalOperations));
6755 SDValue DAGCombiner::visitFREM(SDNode *N) {
6756 SDValue N0 = N->getOperand(0);
6757 SDValue N1 = N->getOperand(1);
6758 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6759 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6760 EVT VT = N->getValueType(0);
6762 // fold (frem c1, c2) -> fmod(c1,c2)
6764 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6769 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6770 SDValue N0 = N->getOperand(0);
6771 SDValue N1 = N->getOperand(1);
6772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6773 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6774 EVT VT = N->getValueType(0);
6776 if (N0CFP && N1CFP) // Constant fold
6777 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6780 const APFloat& V = N1CFP->getValueAPF();
6781 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6782 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6783 if (!V.isNegative()) {
6784 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6785 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6787 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6788 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6789 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6793 // copysign(fabs(x), y) -> copysign(x, y)
6794 // copysign(fneg(x), y) -> copysign(x, y)
6795 // copysign(copysign(x,z), y) -> copysign(x, y)
6796 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6797 N0.getOpcode() == ISD::FCOPYSIGN)
6798 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6799 N0.getOperand(0), N1);
6801 // copysign(x, abs(y)) -> abs(x)
6802 if (N1.getOpcode() == ISD::FABS)
6803 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6805 // copysign(x, copysign(y,z)) -> copysign(x, z)
6806 if (N1.getOpcode() == ISD::FCOPYSIGN)
6807 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6808 N0, N1.getOperand(1));
6810 // copysign(x, fp_extend(y)) -> copysign(x, y)
6811 // copysign(x, fp_round(y)) -> copysign(x, y)
6812 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6813 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6814 N0, N1.getOperand(0));
6819 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6820 SDValue N0 = N->getOperand(0);
6821 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6822 EVT VT = N->getValueType(0);
6823 EVT OpVT = N0.getValueType();
6825 // fold (sint_to_fp c1) -> c1fp
6827 // ...but only if the target supports immediate floating-point values
6828 (!LegalOperations ||
6829 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6830 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6832 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6833 // but UINT_TO_FP is legal on this target, try to convert.
6834 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6835 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6836 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6837 if (DAG.SignBitIsZero(N0))
6838 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6841 // The next optimizations are desirable only if SELECT_CC can be lowered.
6842 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6843 // having to say they don't support SELECT_CC on every type the DAG knows
6844 // about, since there is no way to mark an opcode illegal at all value types
6845 // (See also visitSELECT)
6846 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6847 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6848 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6850 (!LegalOperations ||
6851 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6853 { N0.getOperand(0), N0.getOperand(1),
6854 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6856 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6859 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6860 // (select_cc x, y, 1.0, 0.0,, cc)
6861 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6862 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6863 (!LegalOperations ||
6864 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6866 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6867 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6868 N0.getOperand(0).getOperand(2) };
6869 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6876 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6877 SDValue N0 = N->getOperand(0);
6878 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6879 EVT VT = N->getValueType(0);
6880 EVT OpVT = N0.getValueType();
6882 // fold (uint_to_fp c1) -> c1fp
6884 // ...but only if the target supports immediate floating-point values
6885 (!LegalOperations ||
6886 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6887 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6889 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6890 // but SINT_TO_FP is legal on this target, try to convert.
6891 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6892 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6893 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6894 if (DAG.SignBitIsZero(N0))
6895 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6898 // The next optimizations are desirable only if SELECT_CC can be lowered.
6899 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6900 // having to say they don't support SELECT_CC on every type the DAG knows
6901 // about, since there is no way to mark an opcode illegal at all value types
6902 // (See also visitSELECT)
6903 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6904 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6906 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6907 (!LegalOperations ||
6908 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6910 { N0.getOperand(0), N0.getOperand(1),
6911 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6913 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6920 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6921 SDValue N0 = N->getOperand(0);
6922 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6923 EVT VT = N->getValueType(0);
6925 // fold (fp_to_sint c1fp) -> c1
6927 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6932 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6933 SDValue N0 = N->getOperand(0);
6934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6935 EVT VT = N->getValueType(0);
6937 // fold (fp_to_uint c1fp) -> c1
6939 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6944 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6945 SDValue N0 = N->getOperand(0);
6946 SDValue N1 = N->getOperand(1);
6947 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6948 EVT VT = N->getValueType(0);
6950 // fold (fp_round c1fp) -> c1fp
6952 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6954 // fold (fp_round (fp_extend x)) -> x
6955 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6956 return N0.getOperand(0);
6958 // fold (fp_round (fp_round x)) -> (fp_round x)
6959 if (N0.getOpcode() == ISD::FP_ROUND) {
6960 // This is a value preserving truncation if both round's are.
6961 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6962 N0.getNode()->getConstantOperandVal(1) == 1;
6963 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6964 DAG.getIntPtrConstant(IsTrunc));
6967 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6968 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6969 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6970 N0.getOperand(0), N1);
6971 AddToWorkList(Tmp.getNode());
6972 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6973 Tmp, N0.getOperand(1));
6979 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6980 SDValue N0 = N->getOperand(0);
6981 EVT VT = N->getValueType(0);
6982 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6983 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6985 // fold (fp_round_inreg c1fp) -> c1fp
6986 if (N0CFP && isTypeLegal(EVT)) {
6987 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6988 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6994 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6995 SDValue N0 = N->getOperand(0);
6996 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6997 EVT VT = N->getValueType(0);
6999 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7000 if (N->hasOneUse() &&
7001 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7004 // fold (fp_extend c1fp) -> c1fp
7006 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7008 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7010 if (N0.getOpcode() == ISD::FP_ROUND
7011 && N0.getNode()->getConstantOperandVal(1) == 1) {
7012 SDValue In = N0.getOperand(0);
7013 if (In.getValueType() == VT) return In;
7014 if (VT.bitsLT(In.getValueType()))
7015 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7016 In, N0.getOperand(1));
7017 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7020 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7021 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7022 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7023 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7024 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7025 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7027 LN0->getBasePtr(), N0.getValueType(),
7028 LN0->getMemOperand());
7029 CombineTo(N, ExtLoad);
7030 CombineTo(N0.getNode(),
7031 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7032 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7033 ExtLoad.getValue(1));
7034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7040 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7041 SDValue N0 = N->getOperand(0);
7042 EVT VT = N->getValueType(0);
7044 if (VT.isVector()) {
7045 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7046 if (FoldedVOp.getNode()) return FoldedVOp;
7049 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7050 &DAG.getTarget().Options))
7051 return GetNegatedExpression(N0, DAG, LegalOperations);
7053 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7054 // constant pool values.
7055 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7057 N0.getNode()->hasOneUse() &&
7058 N0.getOperand(0).getValueType().isInteger()) {
7059 SDValue Int = N0.getOperand(0);
7060 EVT IntVT = Int.getValueType();
7061 if (IntVT.isInteger() && !IntVT.isVector()) {
7062 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7063 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7064 AddToWorkList(Int.getNode());
7065 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7070 // (fneg (fmul c, x)) -> (fmul -c, x)
7071 if (N0.getOpcode() == ISD::FMUL) {
7072 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7074 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7076 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7083 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
7085 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7086 EVT VT = N->getValueType(0);
7088 // fold (fceil c1) -> fceil(c1)
7090 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7095 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7100 // fold (ftrunc c1) -> ftrunc(c1)
7102 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7107 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110 EVT VT = N->getValueType(0);
7112 // fold (ffloor c1) -> ffloor(c1)
7114 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7119 SDValue DAGCombiner::visitFABS(SDNode *N) {
7120 SDValue N0 = N->getOperand(0);
7121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7122 EVT VT = N->getValueType(0);
7124 if (VT.isVector()) {
7125 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7126 if (FoldedVOp.getNode()) return FoldedVOp;
7129 // fold (fabs c1) -> fabs(c1)
7131 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7132 // fold (fabs (fabs x)) -> (fabs x)
7133 if (N0.getOpcode() == ISD::FABS)
7134 return N->getOperand(0);
7135 // fold (fabs (fneg x)) -> (fabs x)
7136 // fold (fabs (fcopysign x, y)) -> (fabs x)
7137 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7138 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7140 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7141 // constant pool values.
7142 if (!TLI.isFAbsFree(VT) &&
7143 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7144 N0.getOperand(0).getValueType().isInteger() &&
7145 !N0.getOperand(0).getValueType().isVector()) {
7146 SDValue Int = N0.getOperand(0);
7147 EVT IntVT = Int.getValueType();
7148 if (IntVT.isInteger() && !IntVT.isVector()) {
7149 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7150 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7151 AddToWorkList(Int.getNode());
7152 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7153 N->getValueType(0), Int);
7160 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7161 SDValue Chain = N->getOperand(0);
7162 SDValue N1 = N->getOperand(1);
7163 SDValue N2 = N->getOperand(2);
7165 // If N is a constant we could fold this into a fallthrough or unconditional
7166 // branch. However that doesn't happen very often in normal code, because
7167 // Instcombine/SimplifyCFG should have handled the available opportunities.
7168 // If we did this folding here, it would be necessary to update the
7169 // MachineBasicBlock CFG, which is awkward.
7171 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7173 if (N1.getOpcode() == ISD::SETCC &&
7174 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7175 N1.getOperand(0).getValueType())) {
7176 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7177 Chain, N1.getOperand(2),
7178 N1.getOperand(0), N1.getOperand(1), N2);
7181 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7182 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7183 (N1.getOperand(0).hasOneUse() &&
7184 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7186 if (N1.getOpcode() == ISD::TRUNCATE) {
7187 // Look pass the truncate.
7188 Trunc = N1.getNode();
7189 N1 = N1.getOperand(0);
7192 // Match this pattern so that we can generate simpler code:
7195 // %b = and i32 %a, 2
7196 // %c = srl i32 %b, 1
7197 // brcond i32 %c ...
7202 // %b = and i32 %a, 2
7203 // %c = setcc eq %b, 0
7206 // This applies only when the AND constant value has one bit set and the
7207 // SRL constant is equal to the log2 of the AND constant. The back-end is
7208 // smart enough to convert the result into a TEST/JMP sequence.
7209 SDValue Op0 = N1.getOperand(0);
7210 SDValue Op1 = N1.getOperand(1);
7212 if (Op0.getOpcode() == ISD::AND &&
7213 Op1.getOpcode() == ISD::Constant) {
7214 SDValue AndOp1 = Op0.getOperand(1);
7216 if (AndOp1.getOpcode() == ISD::Constant) {
7217 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7219 if (AndConst.isPowerOf2() &&
7220 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7222 DAG.getSetCC(SDLoc(N),
7223 getSetCCResultType(Op0.getValueType()),
7224 Op0, DAG.getConstant(0, Op0.getValueType()),
7227 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7228 MVT::Other, Chain, SetCC, N2);
7229 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7230 // will convert it back to (X & C1) >> C2.
7231 CombineTo(N, NewBRCond, false);
7232 // Truncate is dead.
7234 removeFromWorkList(Trunc);
7235 DAG.DeleteNode(Trunc);
7237 // Replace the uses of SRL with SETCC
7238 WorkListRemover DeadNodes(*this);
7239 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7240 removeFromWorkList(N1.getNode());
7241 DAG.DeleteNode(N1.getNode());
7242 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7248 // Restore N1 if the above transformation doesn't match.
7249 N1 = N->getOperand(1);
7252 // Transform br(xor(x, y)) -> br(x != y)
7253 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7254 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7255 SDNode *TheXor = N1.getNode();
7256 SDValue Op0 = TheXor->getOperand(0);
7257 SDValue Op1 = TheXor->getOperand(1);
7258 if (Op0.getOpcode() == Op1.getOpcode()) {
7259 // Avoid missing important xor optimizations.
7260 SDValue Tmp = visitXOR(TheXor);
7261 if (Tmp.getNode()) {
7262 if (Tmp.getNode() != TheXor) {
7263 DEBUG(dbgs() << "\nReplacing.8 ";
7265 dbgs() << "\nWith: ";
7266 Tmp.getNode()->dump(&DAG);
7268 WorkListRemover DeadNodes(*this);
7269 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7270 removeFromWorkList(TheXor);
7271 DAG.DeleteNode(TheXor);
7272 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7273 MVT::Other, Chain, Tmp, N2);
7276 // visitXOR has changed XOR's operands or replaced the XOR completely,
7278 return SDValue(N, 0);
7282 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7284 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7285 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7286 Op0.getOpcode() == ISD::XOR) {
7287 TheXor = Op0.getNode();
7291 EVT SetCCVT = N1.getValueType();
7293 SetCCVT = getSetCCResultType(SetCCVT);
7294 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7297 Equal ? ISD::SETEQ : ISD::SETNE);
7298 // Replace the uses of XOR with SETCC
7299 WorkListRemover DeadNodes(*this);
7300 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7301 removeFromWorkList(N1.getNode());
7302 DAG.DeleteNode(N1.getNode());
7303 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7304 MVT::Other, Chain, SetCC, N2);
7311 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7313 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7314 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7315 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7317 // If N is a constant we could fold this into a fallthrough or unconditional
7318 // branch. However that doesn't happen very often in normal code, because
7319 // Instcombine/SimplifyCFG should have handled the available opportunities.
7320 // If we did this folding here, it would be necessary to update the
7321 // MachineBasicBlock CFG, which is awkward.
7323 // Use SimplifySetCC to simplify SETCC's.
7324 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7325 CondLHS, CondRHS, CC->get(), SDLoc(N),
7327 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7329 // fold to a simpler setcc
7330 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7331 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7332 N->getOperand(0), Simp.getOperand(2),
7333 Simp.getOperand(0), Simp.getOperand(1),
7339 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7340 /// uses N as its base pointer and that N may be folded in the load / store
7341 /// addressing mode.
7342 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7344 const TargetLowering &TLI) {
7346 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7347 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7349 VT = Use->getValueType(0);
7350 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7351 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7353 VT = ST->getValue().getValueType();
7357 TargetLowering::AddrMode AM;
7358 if (N->getOpcode() == ISD::ADD) {
7359 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7362 AM.BaseOffs = Offset->getSExtValue();
7366 } else if (N->getOpcode() == ISD::SUB) {
7367 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7370 AM.BaseOffs = -Offset->getSExtValue();
7377 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7380 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7381 /// pre-indexed load / store when the base pointer is an add or subtract
7382 /// and it has other uses besides the load / store. After the
7383 /// transformation, the new indexed load / store has effectively folded
7384 /// the add / subtract in and all of its other uses are redirected to the
7385 /// new load / store.
7386 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7387 if (Level < AfterLegalizeDAG)
7393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7394 if (LD->isIndexed())
7396 VT = LD->getMemoryVT();
7397 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7398 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7400 Ptr = LD->getBasePtr();
7401 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7402 if (ST->isIndexed())
7404 VT = ST->getMemoryVT();
7405 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7406 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7408 Ptr = ST->getBasePtr();
7414 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7415 // out. There is no reason to make this a preinc/predec.
7416 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7417 Ptr.getNode()->hasOneUse())
7420 // Ask the target to do addressing mode selection.
7423 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7424 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7427 // Backends without true r+i pre-indexed forms may need to pass a
7428 // constant base with a variable offset so that constant coercion
7429 // will work with the patterns in canonical form.
7430 bool Swapped = false;
7431 if (isa<ConstantSDNode>(BasePtr)) {
7432 std::swap(BasePtr, Offset);
7436 // Don't create a indexed load / store with zero offset.
7437 if (isa<ConstantSDNode>(Offset) &&
7438 cast<ConstantSDNode>(Offset)->isNullValue())
7441 // Try turning it into a pre-indexed load / store except when:
7442 // 1) The new base ptr is a frame index.
7443 // 2) If N is a store and the new base ptr is either the same as or is a
7444 // predecessor of the value being stored.
7445 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7446 // that would create a cycle.
7447 // 4) All uses are load / store ops that use it as old base ptr.
7449 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7450 // (plus the implicit offset) to a register to preinc anyway.
7451 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7456 SDValue Val = cast<StoreSDNode>(N)->getValue();
7457 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7461 // If the offset is a constant, there may be other adds of constants that
7462 // can be folded with this one. We should do this to avoid having to keep
7463 // a copy of the original base pointer.
7464 SmallVector<SDNode *, 16> OtherUses;
7465 if (isa<ConstantSDNode>(Offset))
7466 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7467 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7469 if (Use == Ptr.getNode())
7472 if (Use->isPredecessorOf(N))
7475 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7480 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7481 if (Op1.getNode() == BasePtr.getNode())
7482 std::swap(Op0, Op1);
7483 assert(Op0.getNode() == BasePtr.getNode() &&
7484 "Use of ADD/SUB but not an operand");
7486 if (!isa<ConstantSDNode>(Op1)) {
7491 // FIXME: In some cases, we can be smarter about this.
7492 if (Op1.getValueType() != Offset.getValueType()) {
7497 OtherUses.push_back(Use);
7501 std::swap(BasePtr, Offset);
7503 // Now check for #3 and #4.
7504 bool RealUse = false;
7506 // Caches for hasPredecessorHelper
7507 SmallPtrSet<const SDNode *, 32> Visited;
7508 SmallVector<const SDNode *, 16> Worklist;
7510 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7511 E = Ptr.getNode()->use_end(); I != E; ++I) {
7515 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7518 // If Ptr may be folded in addressing mode of other use, then it's
7519 // not profitable to do this transformation.
7520 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7529 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7530 BasePtr, Offset, AM);
7532 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7533 BasePtr, Offset, AM);
7536 DEBUG(dbgs() << "\nReplacing.4 ";
7538 dbgs() << "\nWith: ";
7539 Result.getNode()->dump(&DAG);
7541 WorkListRemover DeadNodes(*this);
7543 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7544 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7546 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7549 // Finally, since the node is now dead, remove it from the graph.
7553 std::swap(BasePtr, Offset);
7555 // Replace other uses of BasePtr that can be updated to use Ptr
7556 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7557 unsigned OffsetIdx = 1;
7558 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7560 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7561 BasePtr.getNode() && "Expected BasePtr operand");
7563 // We need to replace ptr0 in the following expression:
7564 // x0 * offset0 + y0 * ptr0 = t0
7566 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7568 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7569 // indexed load/store and the expresion that needs to be re-written.
7571 // Therefore, we have:
7572 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7574 ConstantSDNode *CN =
7575 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7577 APInt Offset0 = CN->getAPIntValue();
7578 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7580 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7581 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7582 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7583 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7585 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7587 APInt CNV = Offset0;
7588 if (X0 < 0) CNV = -CNV;
7589 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7590 else CNV = CNV - Offset1;
7592 // We can now generate the new expression.
7593 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7594 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7596 SDValue NewUse = DAG.getNode(Opcode,
7597 SDLoc(OtherUses[i]),
7598 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7599 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7600 removeFromWorkList(OtherUses[i]);
7601 DAG.DeleteNode(OtherUses[i]);
7604 // Replace the uses of Ptr with uses of the updated base value.
7605 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7606 removeFromWorkList(Ptr.getNode());
7607 DAG.DeleteNode(Ptr.getNode());
7612 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7613 /// add / sub of the base pointer node into a post-indexed load / store.
7614 /// The transformation folded the add / subtract into the new indexed
7615 /// load / store effectively and all of its uses are redirected to the
7616 /// new load / store.
7617 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7618 if (Level < AfterLegalizeDAG)
7624 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7625 if (LD->isIndexed())
7627 VT = LD->getMemoryVT();
7628 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7629 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7631 Ptr = LD->getBasePtr();
7632 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7633 if (ST->isIndexed())
7635 VT = ST->getMemoryVT();
7636 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7637 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7639 Ptr = ST->getBasePtr();
7645 if (Ptr.getNode()->hasOneUse())
7648 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7649 E = Ptr.getNode()->use_end(); I != E; ++I) {
7652 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7657 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7658 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7659 // Don't create a indexed load / store with zero offset.
7660 if (isa<ConstantSDNode>(Offset) &&
7661 cast<ConstantSDNode>(Offset)->isNullValue())
7664 // Try turning it into a post-indexed load / store except when
7665 // 1) All uses are load / store ops that use it as base ptr (and
7666 // it may be folded as addressing mmode).
7667 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7668 // nor a successor of N. Otherwise, if Op is folded that would
7671 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7675 bool TryNext = false;
7676 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7677 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7679 if (Use == Ptr.getNode())
7682 // If all the uses are load / store addresses, then don't do the
7684 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7685 bool RealUse = false;
7686 for (SDNode::use_iterator III = Use->use_begin(),
7687 EEE = Use->use_end(); III != EEE; ++III) {
7688 SDNode *UseUse = *III;
7689 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7704 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7705 SDValue Result = isLoad
7706 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7707 BasePtr, Offset, AM)
7708 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7709 BasePtr, Offset, AM);
7712 DEBUG(dbgs() << "\nReplacing.5 ";
7714 dbgs() << "\nWith: ";
7715 Result.getNode()->dump(&DAG);
7717 WorkListRemover DeadNodes(*this);
7719 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7720 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7722 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7725 // Finally, since the node is now dead, remove it from the graph.
7728 // Replace the uses of Use with uses of the updated base value.
7729 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7730 Result.getValue(isLoad ? 1 : 0));
7731 removeFromWorkList(Op);
7741 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7742 LoadSDNode *LD = cast<LoadSDNode>(N);
7743 SDValue Chain = LD->getChain();
7744 SDValue Ptr = LD->getBasePtr();
7746 // If load is not volatile and there are no uses of the loaded value (and
7747 // the updated indexed value in case of indexed loads), change uses of the
7748 // chain value into uses of the chain input (i.e. delete the dead load).
7749 if (!LD->isVolatile()) {
7750 if (N->getValueType(1) == MVT::Other) {
7752 if (!N->hasAnyUseOfValue(0)) {
7753 // It's not safe to use the two value CombineTo variant here. e.g.
7754 // v1, chain2 = load chain1, loc
7755 // v2, chain3 = load chain2, loc
7757 // Now we replace use of chain2 with chain1. This makes the second load
7758 // isomorphic to the one we are deleting, and thus makes this load live.
7759 DEBUG(dbgs() << "\nReplacing.6 ";
7761 dbgs() << "\nWith chain: ";
7762 Chain.getNode()->dump(&DAG);
7764 WorkListRemover DeadNodes(*this);
7765 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7767 if (N->use_empty()) {
7768 removeFromWorkList(N);
7772 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7776 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7777 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7778 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7779 DEBUG(dbgs() << "\nReplacing.7 ";
7781 dbgs() << "\nWith: ";
7782 Undef.getNode()->dump(&DAG);
7783 dbgs() << " and 2 other values\n");
7784 WorkListRemover DeadNodes(*this);
7785 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7786 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7787 DAG.getUNDEF(N->getValueType(1)));
7788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7789 removeFromWorkList(N);
7791 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7796 // If this load is directly stored, replace the load value with the stored
7798 // TODO: Handle store large -> read small portion.
7799 // TODO: Handle TRUNCSTORE/LOADEXT
7800 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7801 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7802 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7803 if (PrevST->getBasePtr() == Ptr &&
7804 PrevST->getValue().getValueType() == N->getValueType(0))
7805 return CombineTo(N, Chain.getOperand(1), Chain);
7809 // Try to infer better alignment information than the load already has.
7810 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7811 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7812 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7814 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7815 LD->getValueType(0),
7816 Chain, Ptr, LD->getPointerInfo(),
7818 LD->isVolatile(), LD->isNonTemporal(), Align,
7820 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7825 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7826 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7828 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7829 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7832 if (UseAA && LD->isUnindexed()) {
7833 // Walk up chain skipping non-aliasing memory nodes.
7834 SDValue BetterChain = FindBetterChain(N, Chain);
7836 // If there is a better chain.
7837 if (Chain != BetterChain) {
7840 // Replace the chain to void dependency.
7841 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7842 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7843 BetterChain, Ptr, LD->getMemOperand());
7845 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7846 LD->getValueType(0),
7847 BetterChain, Ptr, LD->getMemoryVT(),
7848 LD->getMemOperand());
7851 // Create token factor to keep old chain connected.
7852 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7853 MVT::Other, Chain, ReplLoad.getValue(1));
7855 // Make sure the new and old chains are cleaned up.
7856 AddToWorkList(Token.getNode());
7858 // Replace uses with load result and token factor. Don't add users
7860 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7864 // Try transforming N to an indexed load.
7865 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7866 return SDValue(N, 0);
7868 // Try to slice up N to more direct loads if the slices are mapped to
7869 // different register banks or pairing can take place.
7871 return SDValue(N, 0);
7877 /// \brief Helper structure used to slice a load in smaller loads.
7878 /// Basically a slice is obtained from the following sequence:
7879 /// Origin = load Ty1, Base
7880 /// Shift = srl Ty1 Origin, CstTy Amount
7881 /// Inst = trunc Shift to Ty2
7883 /// Then, it will be rewriten into:
7884 /// Slice = load SliceTy, Base + SliceOffset
7885 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7887 /// SliceTy is deduced from the number of bits that are actually used to
7889 struct LoadedSlice {
7890 /// \brief Helper structure used to compute the cost of a slice.
7892 /// Are we optimizing for code size.
7897 unsigned CrossRegisterBanksCopies;
7901 Cost(bool ForCodeSize = false)
7902 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7903 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7905 /// \brief Get the cost of one isolated slice.
7906 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7907 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7908 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7909 EVT TruncType = LS.Inst->getValueType(0);
7910 EVT LoadedType = LS.getLoadedType();
7911 if (TruncType != LoadedType &&
7912 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7916 /// \brief Account for slicing gain in the current cost.
7917 /// Slicing provide a few gains like removing a shift or a
7918 /// truncate. This method allows to grow the cost of the original
7919 /// load with the gain from this slice.
7920 void addSliceGain(const LoadedSlice &LS) {
7921 // Each slice saves a truncate.
7922 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7923 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7924 LS.Inst->getOperand(0).getValueType()))
7926 // If there is a shift amount, this slice gets rid of it.
7929 // If this slice can merge a cross register bank copy, account for it.
7930 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7931 ++CrossRegisterBanksCopies;
7934 Cost &operator+=(const Cost &RHS) {
7936 Truncates += RHS.Truncates;
7937 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7943 bool operator==(const Cost &RHS) const {
7944 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7945 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7946 ZExts == RHS.ZExts && Shift == RHS.Shift;
7949 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7951 bool operator<(const Cost &RHS) const {
7952 // Assume cross register banks copies are as expensive as loads.
7953 // FIXME: Do we want some more target hooks?
7954 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7955 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7956 // Unless we are optimizing for code size, consider the
7957 // expensive operation first.
7958 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7959 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7960 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7961 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7964 bool operator>(const Cost &RHS) const { return RHS < *this; }
7966 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7968 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7970 // The last instruction that represent the slice. This should be a
7971 // truncate instruction.
7973 // The original load instruction.
7975 // The right shift amount in bits from the original load.
7977 // The DAG from which Origin came from.
7978 // This is used to get some contextual information about legal types, etc.
7981 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7982 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7983 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7985 LoadedSlice(const LoadedSlice &LS)
7986 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7988 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7989 /// \return Result is \p BitWidth and has used bits set to 1 and
7990 /// not used bits set to 0.
7991 APInt getUsedBits() const {
7992 // Reproduce the trunc(lshr) sequence:
7993 // - Start from the truncated value.
7994 // - Zero extend to the desired bit width.
7996 assert(Origin && "No original load to compare against.");
7997 unsigned BitWidth = Origin->getValueSizeInBits(0);
7998 assert(Inst && "This slice is not bound to an instruction");
7999 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8000 "Extracted slice is bigger than the whole type!");
8001 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8002 UsedBits.setAllBits();
8003 UsedBits = UsedBits.zext(BitWidth);
8008 /// \brief Get the size of the slice to be loaded in bytes.
8009 unsigned getLoadedSize() const {
8010 unsigned SliceSize = getUsedBits().countPopulation();
8011 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8012 return SliceSize / 8;
8015 /// \brief Get the type that will be loaded for this slice.
8016 /// Note: This may not be the final type for the slice.
8017 EVT getLoadedType() const {
8018 assert(DAG && "Missing context");
8019 LLVMContext &Ctxt = *DAG->getContext();
8020 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8023 /// \brief Get the alignment of the load used for this slice.
8024 unsigned getAlignment() const {
8025 unsigned Alignment = Origin->getAlignment();
8026 unsigned Offset = getOffsetFromBase();
8028 Alignment = MinAlign(Alignment, Alignment + Offset);
8032 /// \brief Check if this slice can be rewritten with legal operations.
8033 bool isLegal() const {
8034 // An invalid slice is not legal.
8035 if (!Origin || !Inst || !DAG)
8038 // Offsets are for indexed load only, we do not handle that.
8039 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8042 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8044 // Check that the type is legal.
8045 EVT SliceType = getLoadedType();
8046 if (!TLI.isTypeLegal(SliceType))
8049 // Check that the load is legal for this type.
8050 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8053 // Check that the offset can be computed.
8054 // 1. Check its type.
8055 EVT PtrType = Origin->getBasePtr().getValueType();
8056 if (PtrType == MVT::Untyped || PtrType.isExtended())
8059 // 2. Check that it fits in the immediate.
8060 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8063 // 3. Check that the computation is legal.
8064 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8067 // Check that the zext is legal if it needs one.
8068 EVT TruncateType = Inst->getValueType(0);
8069 if (TruncateType != SliceType &&
8070 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8076 /// \brief Get the offset in bytes of this slice in the original chunk of
8078 /// \pre DAG != NULL.
8079 uint64_t getOffsetFromBase() const {
8080 assert(DAG && "Missing context.");
8082 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8083 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8084 uint64_t Offset = Shift / 8;
8085 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8086 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8087 "The size of the original loaded type is not a multiple of a"
8089 // If Offset is bigger than TySizeInBytes, it means we are loading all
8090 // zeros. This should have been optimized before in the process.
8091 assert(TySizeInBytes > Offset &&
8092 "Invalid shift amount for given loaded size");
8094 Offset = TySizeInBytes - Offset - getLoadedSize();
8098 /// \brief Generate the sequence of instructions to load the slice
8099 /// represented by this object and redirect the uses of this slice to
8100 /// this new sequence of instructions.
8101 /// \pre this->Inst && this->Origin are valid Instructions and this
8102 /// object passed the legal check: LoadedSlice::isLegal returned true.
8103 /// \return The last instruction of the sequence used to load the slice.
8104 SDValue loadSlice() const {
8105 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8106 const SDValue &OldBaseAddr = Origin->getBasePtr();
8107 SDValue BaseAddr = OldBaseAddr;
8108 // Get the offset in that chunk of bytes w.r.t. the endianess.
8109 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8110 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8112 // BaseAddr = BaseAddr + Offset.
8113 EVT ArithType = BaseAddr.getValueType();
8114 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8115 DAG->getConstant(Offset, ArithType));
8118 // Create the type of the loaded slice according to its size.
8119 EVT SliceType = getLoadedType();
8121 // Create the load for the slice.
8122 SDValue LastInst = DAG->getLoad(
8123 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8124 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8125 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8126 // If the final type is not the same as the loaded type, this means that
8127 // we have to pad with zero. Create a zero extend for that.
8128 EVT FinalType = Inst->getValueType(0);
8129 if (SliceType != FinalType)
8131 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8135 /// \brief Check if this slice can be merged with an expensive cross register
8136 /// bank copy. E.g.,
8138 /// f = bitcast i32 i to float
8139 bool canMergeExpensiveCrossRegisterBankCopy() const {
8140 if (!Inst || !Inst->hasOneUse())
8142 SDNode *Use = *Inst->use_begin();
8143 if (Use->getOpcode() != ISD::BITCAST)
8145 assert(DAG && "Missing context");
8146 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8147 EVT ResVT = Use->getValueType(0);
8148 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8149 const TargetRegisterClass *ArgRC =
8150 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8151 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8154 // At this point, we know that we perform a cross-register-bank copy.
8155 // Check if it is expensive.
8156 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8157 // Assume bitcasts are cheap, unless both register classes do not
8158 // explicitly share a common sub class.
8159 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8162 // Check if it will be merged with the load.
8163 // 1. Check the alignment constraint.
8164 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8165 ResVT.getTypeForEVT(*DAG->getContext()));
8167 if (RequiredAlignment > getAlignment())
8170 // 2. Check that the load is a legal operation for that type.
8171 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8174 // 3. Check that we do not have a zext in the way.
8175 if (Inst->getValueType(0) != getLoadedType())
8183 /// \brief Sorts LoadedSlice according to their offset.
8184 struct LoadedSliceSorter {
8185 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8186 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8187 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8191 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8192 /// \p UsedBits looks like 0..0 1..1 0..0.
8193 static bool areUsedBitsDense(const APInt &UsedBits) {
8194 // If all the bits are one, this is dense!
8195 if (UsedBits.isAllOnesValue())
8198 // Get rid of the unused bits on the right.
8199 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8200 // Get rid of the unused bits on the left.
8201 if (NarrowedUsedBits.countLeadingZeros())
8202 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8203 // Check that the chunk of bits is completely used.
8204 return NarrowedUsedBits.isAllOnesValue();
8207 /// \brief Check whether or not \p First and \p Second are next to each other
8208 /// in memory. This means that there is no hole between the bits loaded
8209 /// by \p First and the bits loaded by \p Second.
8210 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8211 const LoadedSlice &Second) {
8212 assert(First.Origin == Second.Origin && First.Origin &&
8213 "Unable to match different memory origins.");
8214 APInt UsedBits = First.getUsedBits();
8215 assert((UsedBits & Second.getUsedBits()) == 0 &&
8216 "Slices are not supposed to overlap.");
8217 UsedBits |= Second.getUsedBits();
8218 return areUsedBitsDense(UsedBits);
8221 /// \brief Adjust the \p GlobalLSCost according to the target
8222 /// paring capabilities and the layout of the slices.
8223 /// \pre \p GlobalLSCost should account for at least as many loads as
8224 /// there is in the slices in \p LoadedSlices.
8225 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8226 LoadedSlice::Cost &GlobalLSCost) {
8227 unsigned NumberOfSlices = LoadedSlices.size();
8228 // If there is less than 2 elements, no pairing is possible.
8229 if (NumberOfSlices < 2)
8232 // Sort the slices so that elements that are likely to be next to each
8233 // other in memory are next to each other in the list.
8234 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8235 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8236 // First (resp. Second) is the first (resp. Second) potentially candidate
8237 // to be placed in a paired load.
8238 const LoadedSlice *First = NULL;
8239 const LoadedSlice *Second = NULL;
8240 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8241 // Set the beginning of the pair.
8244 Second = &LoadedSlices[CurrSlice];
8246 // If First is NULL, it means we start a new pair.
8247 // Get to the next slice.
8251 EVT LoadedType = First->getLoadedType();
8253 // If the types of the slices are different, we cannot pair them.
8254 if (LoadedType != Second->getLoadedType())
8257 // Check if the target supplies paired loads for this type.
8258 unsigned RequiredAlignment = 0;
8259 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8260 // move to the next pair, this type is hopeless.
8264 // Check if we meet the alignment requirement.
8265 if (RequiredAlignment > First->getAlignment())
8268 // Check that both loads are next to each other in memory.
8269 if (!areSlicesNextToEachOther(*First, *Second))
8272 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8273 --GlobalLSCost.Loads;
8274 // Move to the next pair.
8279 /// \brief Check the profitability of all involved LoadedSlice.
8280 /// Currently, it is considered profitable if there is exactly two
8281 /// involved slices (1) which are (2) next to each other in memory, and
8282 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8284 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8285 /// the elements themselves.
8287 /// FIXME: When the cost model will be mature enough, we can relax
8288 /// constraints (1) and (2).
8289 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8290 const APInt &UsedBits, bool ForCodeSize) {
8291 unsigned NumberOfSlices = LoadedSlices.size();
8292 if (StressLoadSlicing)
8293 return NumberOfSlices > 1;
8296 if (NumberOfSlices != 2)
8300 if (!areUsedBitsDense(UsedBits))
8304 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8305 // The original code has one big load.
8307 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8308 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8309 // Accumulate the cost of all the slices.
8310 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8311 GlobalSlicingCost += SliceCost;
8313 // Account as cost in the original configuration the gain obtained
8314 // with the current slices.
8315 OrigCost.addSliceGain(LS);
8318 // If the target supports paired load, adjust the cost accordingly.
8319 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8320 return OrigCost > GlobalSlicingCost;
8323 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8324 /// operations, split it in the various pieces being extracted.
8326 /// This sort of thing is introduced by SROA.
8327 /// This slicing takes care not to insert overlapping loads.
8328 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8329 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8330 if (Level < AfterLegalizeDAG)
8333 LoadSDNode *LD = cast<LoadSDNode>(N);
8334 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8335 !LD->getValueType(0).isInteger())
8338 // Keep track of already used bits to detect overlapping values.
8339 // In that case, we will just abort the transformation.
8340 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8342 SmallVector<LoadedSlice, 4> LoadedSlices;
8344 // Check if this load is used as several smaller chunks of bits.
8345 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8346 // of computation for each trunc.
8347 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8348 UI != UIEnd; ++UI) {
8349 // Skip the uses of the chain.
8350 if (UI.getUse().getResNo() != 0)
8356 // Check if this is a trunc(lshr).
8357 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8358 isa<ConstantSDNode>(User->getOperand(1))) {
8359 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8360 User = *User->use_begin();
8363 // At this point, User is a Truncate, iff we encountered, trunc or
8365 if (User->getOpcode() != ISD::TRUNCATE)
8368 // The width of the type must be a power of 2 and greater than 8-bits.
8369 // Otherwise the load cannot be represented in LLVM IR.
8370 // Moreover, if we shifted with a non-8-bits multiple, the slice
8371 // will be across several bytes. We do not support that.
8372 unsigned Width = User->getValueSizeInBits(0);
8373 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8376 // Build the slice for this chain of computations.
8377 LoadedSlice LS(User, LD, Shift, &DAG);
8378 APInt CurrentUsedBits = LS.getUsedBits();
8380 // Check if this slice overlaps with another.
8381 if ((CurrentUsedBits & UsedBits) != 0)
8383 // Update the bits used globally.
8384 UsedBits |= CurrentUsedBits;
8386 // Check if the new slice would be legal.
8390 // Record the slice.
8391 LoadedSlices.push_back(LS);
8394 // Abort slicing if it does not seem to be profitable.
8395 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8400 // Rewrite each chain to use an independent load.
8401 // By construction, each chain can be represented by a unique load.
8403 // Prepare the argument for the new token factor for all the slices.
8404 SmallVector<SDValue, 8> ArgChains;
8405 for (SmallVectorImpl<LoadedSlice>::const_iterator
8406 LSIt = LoadedSlices.begin(),
8407 LSItEnd = LoadedSlices.end();
8408 LSIt != LSItEnd; ++LSIt) {
8409 SDValue SliceInst = LSIt->loadSlice();
8410 CombineTo(LSIt->Inst, SliceInst, true);
8411 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8412 SliceInst = SliceInst.getOperand(0);
8413 assert(SliceInst->getOpcode() == ISD::LOAD &&
8414 "It takes more than a zext to get to the loaded slice!!");
8415 ArgChains.push_back(SliceInst.getValue(1));
8418 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8419 &ArgChains[0], ArgChains.size());
8420 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8424 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8425 /// load is having specific bytes cleared out. If so, return the byte size
8426 /// being masked out and the shift amount.
8427 static std::pair<unsigned, unsigned>
8428 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8429 std::pair<unsigned, unsigned> Result(0, 0);
8431 // Check for the structure we're looking for.
8432 if (V->getOpcode() != ISD::AND ||
8433 !isa<ConstantSDNode>(V->getOperand(1)) ||
8434 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8437 // Check the chain and pointer.
8438 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8439 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8441 // The store should be chained directly to the load or be an operand of a
8443 if (LD == Chain.getNode())
8445 else if (Chain->getOpcode() != ISD::TokenFactor)
8446 return Result; // Fail.
8449 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8450 if (Chain->getOperand(i).getNode() == LD) {
8454 if (!isOk) return Result;
8457 // This only handles simple types.
8458 if (V.getValueType() != MVT::i16 &&
8459 V.getValueType() != MVT::i32 &&
8460 V.getValueType() != MVT::i64)
8463 // Check the constant mask. Invert it so that the bits being masked out are
8464 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8465 // follow the sign bit for uniformity.
8466 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8467 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8468 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8469 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8470 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8471 if (NotMaskLZ == 64) return Result; // All zero mask.
8473 // See if we have a continuous run of bits. If so, we have 0*1+0*
8474 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8477 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8478 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8479 NotMaskLZ -= 64-V.getValueSizeInBits();
8481 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8482 switch (MaskedBytes) {
8486 default: return Result; // All one mask, or 5-byte mask.
8489 // Verify that the first bit starts at a multiple of mask so that the access
8490 // is aligned the same as the access width.
8491 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8493 Result.first = MaskedBytes;
8494 Result.second = NotMaskTZ/8;
8499 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8500 /// provides a value as specified by MaskInfo. If so, replace the specified
8501 /// store with a narrower store of truncated IVal.
8503 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8504 SDValue IVal, StoreSDNode *St,
8506 unsigned NumBytes = MaskInfo.first;
8507 unsigned ByteShift = MaskInfo.second;
8508 SelectionDAG &DAG = DC->getDAG();
8510 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8511 // that uses this. If not, this is not a replacement.
8512 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8513 ByteShift*8, (ByteShift+NumBytes)*8);
8514 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8516 // Check that it is legal on the target to do this. It is legal if the new
8517 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8519 MVT VT = MVT::getIntegerVT(NumBytes*8);
8520 if (!DC->isTypeLegal(VT))
8523 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8524 // shifted by ByteShift and truncated down to NumBytes.
8526 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8527 DAG.getConstant(ByteShift*8,
8528 DC->getShiftAmountTy(IVal.getValueType())));
8530 // Figure out the offset for the store and the alignment of the access.
8532 unsigned NewAlign = St->getAlignment();
8534 if (DAG.getTargetLoweringInfo().isLittleEndian())
8535 StOffset = ByteShift;
8537 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8539 SDValue Ptr = St->getBasePtr();
8541 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8542 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8543 NewAlign = MinAlign(NewAlign, StOffset);
8546 // Truncate down to the new size.
8547 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8550 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8551 St->getPointerInfo().getWithOffset(StOffset),
8552 false, false, NewAlign).getNode();
8556 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8557 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8558 /// of the loaded bits, try narrowing the load and store if it would end up
8559 /// being a win for performance or code size.
8560 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8561 StoreSDNode *ST = cast<StoreSDNode>(N);
8562 if (ST->isVolatile())
8565 SDValue Chain = ST->getChain();
8566 SDValue Value = ST->getValue();
8567 SDValue Ptr = ST->getBasePtr();
8568 EVT VT = Value.getValueType();
8570 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8573 unsigned Opc = Value.getOpcode();
8575 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8576 // is a byte mask indicating a consecutive number of bytes, check to see if
8577 // Y is known to provide just those bytes. If so, we try to replace the
8578 // load + replace + store sequence with a single (narrower) store, which makes
8580 if (Opc == ISD::OR) {
8581 std::pair<unsigned, unsigned> MaskedLoad;
8582 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8583 if (MaskedLoad.first)
8584 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8585 Value.getOperand(1), ST,this))
8586 return SDValue(NewST, 0);
8588 // Or is commutative, so try swapping X and Y.
8589 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8590 if (MaskedLoad.first)
8591 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8592 Value.getOperand(0), ST,this))
8593 return SDValue(NewST, 0);
8596 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8597 Value.getOperand(1).getOpcode() != ISD::Constant)
8600 SDValue N0 = Value.getOperand(0);
8601 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8602 Chain == SDValue(N0.getNode(), 1)) {
8603 LoadSDNode *LD = cast<LoadSDNode>(N0);
8604 if (LD->getBasePtr() != Ptr ||
8605 LD->getPointerInfo().getAddrSpace() !=
8606 ST->getPointerInfo().getAddrSpace())
8609 // Find the type to narrow it the load / op / store to.
8610 SDValue N1 = Value.getOperand(1);
8611 unsigned BitWidth = N1.getValueSizeInBits();
8612 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8613 if (Opc == ISD::AND)
8614 Imm ^= APInt::getAllOnesValue(BitWidth);
8615 if (Imm == 0 || Imm.isAllOnesValue())
8617 unsigned ShAmt = Imm.countTrailingZeros();
8618 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8619 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8620 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8621 while (NewBW < BitWidth &&
8622 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8623 TLI.isNarrowingProfitable(VT, NewVT))) {
8624 NewBW = NextPowerOf2(NewBW);
8625 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8627 if (NewBW >= BitWidth)
8630 // If the lsb changed does not start at the type bitwidth boundary,
8631 // start at the previous one.
8633 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8634 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8635 std::min(BitWidth, ShAmt + NewBW));
8636 if ((Imm & Mask) == Imm) {
8637 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8638 if (Opc == ISD::AND)
8639 NewImm ^= APInt::getAllOnesValue(NewBW);
8640 uint64_t PtrOff = ShAmt / 8;
8641 // For big endian targets, we need to adjust the offset to the pointer to
8642 // load the correct bytes.
8643 if (TLI.isBigEndian())
8644 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8646 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8647 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8648 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8651 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8652 Ptr.getValueType(), Ptr,
8653 DAG.getConstant(PtrOff, Ptr.getValueType()));
8654 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8655 LD->getChain(), NewPtr,
8656 LD->getPointerInfo().getWithOffset(PtrOff),
8657 LD->isVolatile(), LD->isNonTemporal(),
8658 LD->isInvariant(), NewAlign,
8660 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8661 DAG.getConstant(NewImm, NewVT));
8662 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8664 ST->getPointerInfo().getWithOffset(PtrOff),
8665 false, false, NewAlign);
8667 AddToWorkList(NewPtr.getNode());
8668 AddToWorkList(NewLD.getNode());
8669 AddToWorkList(NewVal.getNode());
8670 WorkListRemover DeadNodes(*this);
8671 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8680 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8681 /// if the load value isn't used by any other operations, then consider
8682 /// transforming the pair to integer load / store operations if the target
8683 /// deems the transformation profitable.
8684 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8685 StoreSDNode *ST = cast<StoreSDNode>(N);
8686 SDValue Chain = ST->getChain();
8687 SDValue Value = ST->getValue();
8688 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8689 Value.hasOneUse() &&
8690 Chain == SDValue(Value.getNode(), 1)) {
8691 LoadSDNode *LD = cast<LoadSDNode>(Value);
8692 EVT VT = LD->getMemoryVT();
8693 if (!VT.isFloatingPoint() ||
8694 VT != ST->getMemoryVT() ||
8695 LD->isNonTemporal() ||
8696 ST->isNonTemporal() ||
8697 LD->getPointerInfo().getAddrSpace() != 0 ||
8698 ST->getPointerInfo().getAddrSpace() != 0)
8701 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8702 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8703 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8704 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8705 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8708 unsigned LDAlign = LD->getAlignment();
8709 unsigned STAlign = ST->getAlignment();
8710 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8711 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8712 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8715 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8716 LD->getChain(), LD->getBasePtr(),
8717 LD->getPointerInfo(),
8718 false, false, false, LDAlign);
8720 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8721 NewLD, ST->getBasePtr(),
8722 ST->getPointerInfo(),
8723 false, false, STAlign);
8725 AddToWorkList(NewLD.getNode());
8726 AddToWorkList(NewST.getNode());
8727 WorkListRemover DeadNodes(*this);
8728 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8736 /// Helper struct to parse and store a memory address as base + index + offset.
8737 /// We ignore sign extensions when it is safe to do so.
8738 /// The following two expressions are not equivalent. To differentiate we need
8739 /// to store whether there was a sign extension involved in the index
8741 /// (load (i64 add (i64 copyfromreg %c)
8742 /// (i64 signextend (add (i8 load %index)
8746 /// (load (i64 add (i64 copyfromreg %c)
8747 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8749 struct BaseIndexOffset {
8753 bool IsIndexSignExt;
8755 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8757 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8758 bool IsIndexSignExt) :
8759 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8761 bool equalBaseIndex(const BaseIndexOffset &Other) {
8762 return Other.Base == Base && Other.Index == Index &&
8763 Other.IsIndexSignExt == IsIndexSignExt;
8766 /// Parses tree in Ptr for base, index, offset addresses.
8767 static BaseIndexOffset match(SDValue Ptr) {
8768 bool IsIndexSignExt = false;
8770 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8771 // instruction, then it could be just the BASE or everything else we don't
8772 // know how to handle. Just use Ptr as BASE and give up.
8773 if (Ptr->getOpcode() != ISD::ADD)
8774 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8776 // We know that we have at least an ADD instruction. Try to pattern match
8777 // the simple case of BASE + OFFSET.
8778 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8779 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8780 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8784 // Inside a loop the current BASE pointer is calculated using an ADD and a
8785 // MUL instruction. In this case Ptr is the actual BASE pointer.
8786 // (i64 add (i64 %array_ptr)
8787 // (i64 mul (i64 %induction_var)
8788 // (i64 %element_size)))
8789 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8790 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8792 // Look at Base + Index + Offset cases.
8793 SDValue Base = Ptr->getOperand(0);
8794 SDValue IndexOffset = Ptr->getOperand(1);
8796 // Skip signextends.
8797 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8798 IndexOffset = IndexOffset->getOperand(0);
8799 IsIndexSignExt = true;
8802 // Either the case of Base + Index (no offset) or something else.
8803 if (IndexOffset->getOpcode() != ISD::ADD)
8804 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8806 // Now we have the case of Base + Index + offset.
8807 SDValue Index = IndexOffset->getOperand(0);
8808 SDValue Offset = IndexOffset->getOperand(1);
8810 if (!isa<ConstantSDNode>(Offset))
8811 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8813 // Ignore signextends.
8814 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8815 Index = Index->getOperand(0);
8816 IsIndexSignExt = true;
8817 } else IsIndexSignExt = false;
8819 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8820 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8824 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8825 /// is located in a sequence of memory operations connected by a chain.
8827 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8828 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8829 // Ptr to the mem node.
8830 LSBaseSDNode *MemNode;
8831 // Offset from the base ptr.
8832 int64_t OffsetFromBase;
8833 // What is the sequence number of this mem node.
8834 // Lowest mem operand in the DAG starts at zero.
8835 unsigned SequenceNum;
8838 /// Sorts store nodes in a link according to their offset from a shared
8840 struct ConsecutiveMemoryChainSorter {
8841 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8843 LHS.OffsetFromBase < RHS.OffsetFromBase ||
8844 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
8845 LHS.SequenceNum > RHS.SequenceNum);
8849 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8850 EVT MemVT = St->getMemoryVT();
8851 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8852 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8853 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8855 // Don't merge vectors into wider inputs.
8856 if (MemVT.isVector() || !MemVT.isSimple())
8859 // Perform an early exit check. Do not bother looking at stored values that
8860 // are not constants or loads.
8861 SDValue StoredVal = St->getValue();
8862 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8863 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8867 // Only look at ends of store sequences.
8868 SDValue Chain = SDValue(St, 1);
8869 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8872 // This holds the base pointer, index, and the offset in bytes from the base
8874 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8876 // We must have a base and an offset.
8877 if (!BasePtr.Base.getNode())
8880 // Do not handle stores to undef base pointers.
8881 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8884 // Save the LoadSDNodes that we find in the chain.
8885 // We need to make sure that these nodes do not interfere with
8886 // any of the store nodes.
8887 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8889 // Save the StoreSDNodes that we find in the chain.
8890 SmallVector<MemOpLink, 8> StoreNodes;
8892 // Walk up the chain and look for nodes with offsets from the same
8893 // base pointer. Stop when reaching an instruction with a different kind
8894 // or instruction which has a different base pointer.
8896 StoreSDNode *Index = St;
8898 // If the chain has more than one use, then we can't reorder the mem ops.
8899 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8902 // Find the base pointer and offset for this memory node.
8903 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8905 // Check that the base pointer is the same as the original one.
8906 if (!Ptr.equalBaseIndex(BasePtr))
8909 // Check that the alignment is the same.
8910 if (Index->getAlignment() != St->getAlignment())
8913 // The memory operands must not be volatile.
8914 if (Index->isVolatile() || Index->isIndexed())
8918 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8919 if (St->isTruncatingStore())
8922 // The stored memory type must be the same.
8923 if (Index->getMemoryVT() != MemVT)
8926 // We do not allow unaligned stores because we want to prevent overriding
8928 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8931 // We found a potential memory operand to merge.
8932 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8934 // Find the next memory operand in the chain. If the next operand in the
8935 // chain is a store then move up and continue the scan with the next
8936 // memory operand. If the next operand is a load save it and use alias
8937 // information to check if it interferes with anything.
8938 SDNode *NextInChain = Index->getChain().getNode();
8940 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8941 // We found a store node. Use it for the next iteration.
8944 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8945 if (Ldn->isVolatile()) {
8950 // Save the load node for later. Continue the scan.
8951 AliasLoadNodes.push_back(Ldn);
8952 NextInChain = Ldn->getChain().getNode();
8961 // Check if there is anything to merge.
8962 if (StoreNodes.size() < 2)
8965 // Sort the memory operands according to their distance from the base pointer.
8966 std::sort(StoreNodes.begin(), StoreNodes.end(),
8967 ConsecutiveMemoryChainSorter());
8969 // Scan the memory operations on the chain and find the first non-consecutive
8970 // store memory address.
8971 unsigned LastConsecutiveStore = 0;
8972 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8973 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8975 // Check that the addresses are consecutive starting from the second
8976 // element in the list of stores.
8978 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8979 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8984 // Check if this store interferes with any of the loads that we found.
8985 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8986 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8990 // We found a load that alias with this store. Stop the sequence.
8994 // Mark this node as useful.
8995 LastConsecutiveStore = i;
8998 // The node with the lowest store address.
8999 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9001 // Store the constants into memory as one consecutive store.
9003 unsigned LastLegalType = 0;
9004 unsigned LastLegalVectorType = 0;
9005 bool NonZero = false;
9006 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9007 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9008 SDValue StoredVal = St->getValue();
9010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9011 NonZero |= !C->isNullValue();
9012 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9013 NonZero |= !C->getConstantFPValue()->isNullValue();
9019 // Find a legal type for the constant store.
9020 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9021 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9022 if (TLI.isTypeLegal(StoreTy))
9023 LastLegalType = i+1;
9024 // Or check whether a truncstore is legal.
9025 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9026 TargetLowering::TypePromoteInteger) {
9027 EVT LegalizedStoredValueTy =
9028 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9029 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9030 LastLegalType = i+1;
9033 // Find a legal type for the vector store.
9034 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9035 if (TLI.isTypeLegal(Ty))
9036 LastLegalVectorType = i + 1;
9039 // We only use vectors if the constant is known to be zero and the
9040 // function is not marked with the noimplicitfloat attribute.
9041 if (NonZero || NoVectors)
9042 LastLegalVectorType = 0;
9044 // Check if we found a legal integer type to store.
9045 if (LastLegalType == 0 && LastLegalVectorType == 0)
9048 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9049 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9051 // Make sure we have something to merge.
9055 unsigned EarliestNodeUsed = 0;
9056 for (unsigned i=0; i < NumElem; ++i) {
9057 // Find a chain for the new wide-store operand. Notice that some
9058 // of the store nodes that we found may not be selected for inclusion
9059 // in the wide store. The chain we use needs to be the chain of the
9060 // earliest store node which is *used* and replaced by the wide store.
9061 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9062 EarliestNodeUsed = i;
9065 // The earliest Node in the DAG.
9066 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9067 SDLoc DL(StoreNodes[0].MemNode);
9071 // Find a legal type for the vector store.
9072 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9073 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9074 StoredVal = DAG.getConstant(0, Ty);
9076 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9077 APInt StoreInt(StoreBW, 0);
9079 // Construct a single integer constant which is made of the smaller
9081 bool IsLE = TLI.isLittleEndian();
9082 for (unsigned i = 0; i < NumElem ; ++i) {
9083 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9084 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9085 SDValue Val = St->getValue();
9086 StoreInt<<=ElementSizeBytes*8;
9087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9088 StoreInt|=C->getAPIntValue().zext(StoreBW);
9089 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9090 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9092 assert(false && "Invalid constant element type");
9096 // Create the new Load and Store operations.
9097 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9098 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9101 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9102 FirstInChain->getBasePtr(),
9103 FirstInChain->getPointerInfo(),
9105 FirstInChain->getAlignment());
9107 // Replace the first store with the new store
9108 CombineTo(EarliestOp, NewStore);
9109 // Erase all other stores.
9110 for (unsigned i = 0; i < NumElem ; ++i) {
9111 if (StoreNodes[i].MemNode == EarliestOp)
9113 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9114 // ReplaceAllUsesWith will replace all uses that existed when it was
9115 // called, but graph optimizations may cause new ones to appear. For
9116 // example, the case in pr14333 looks like
9118 // St's chain -> St -> another store -> X
9120 // And the only difference from St to the other store is the chain.
9121 // When we change it's chain to be St's chain they become identical,
9122 // get CSEed and the net result is that X is now a use of St.
9123 // Since we know that St is redundant, just iterate.
9124 while (!St->use_empty())
9125 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9126 removeFromWorkList(St);
9133 // Below we handle the case of multiple consecutive stores that
9134 // come from multiple consecutive loads. We merge them into a single
9135 // wide load and a single wide store.
9137 // Look for load nodes which are used by the stored values.
9138 SmallVector<MemOpLink, 8> LoadNodes;
9140 // Find acceptable loads. Loads need to have the same chain (token factor),
9141 // must not be zext, volatile, indexed, and they must be consecutive.
9142 BaseIndexOffset LdBasePtr;
9143 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9144 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9145 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9148 // Loads must only have one use.
9149 if (!Ld->hasNUsesOfValue(1, 0))
9152 // Check that the alignment is the same as the stores.
9153 if (Ld->getAlignment() != St->getAlignment())
9156 // The memory operands must not be volatile.
9157 if (Ld->isVolatile() || Ld->isIndexed())
9160 // We do not accept ext loads.
9161 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9164 // The stored memory type must be the same.
9165 if (Ld->getMemoryVT() != MemVT)
9168 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9169 // If this is not the first ptr that we check.
9170 if (LdBasePtr.Base.getNode()) {
9171 // The base ptr must be the same.
9172 if (!LdPtr.equalBaseIndex(LdBasePtr))
9175 // Check that all other base pointers are the same as this one.
9179 // We found a potential memory operand to merge.
9180 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9183 if (LoadNodes.size() < 2)
9186 // Scan the memory operations on the chain and find the first non-consecutive
9187 // load memory address. These variables hold the index in the store node
9189 unsigned LastConsecutiveLoad = 0;
9190 // This variable refers to the size and not index in the array.
9191 unsigned LastLegalVectorType = 0;
9192 unsigned LastLegalIntegerType = 0;
9193 StartAddress = LoadNodes[0].OffsetFromBase;
9194 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9195 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9196 // All loads much share the same chain.
9197 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9200 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9201 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9203 LastConsecutiveLoad = i;
9205 // Find a legal type for the vector store.
9206 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9207 if (TLI.isTypeLegal(StoreTy))
9208 LastLegalVectorType = i + 1;
9210 // Find a legal type for the integer store.
9211 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9212 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9213 if (TLI.isTypeLegal(StoreTy))
9214 LastLegalIntegerType = i + 1;
9215 // Or check whether a truncstore and extload is legal.
9216 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9217 TargetLowering::TypePromoteInteger) {
9218 EVT LegalizedStoredValueTy =
9219 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9220 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9221 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9222 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9223 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9224 LastLegalIntegerType = i+1;
9228 // Only use vector types if the vector type is larger than the integer type.
9229 // If they are the same, use integers.
9230 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9231 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9233 // We add +1 here because the LastXXX variables refer to location while
9234 // the NumElem refers to array/index size.
9235 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9236 NumElem = std::min(LastLegalType, NumElem);
9241 // The earliest Node in the DAG.
9242 unsigned EarliestNodeUsed = 0;
9243 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9244 for (unsigned i=1; i<NumElem; ++i) {
9245 // Find a chain for the new wide-store operand. Notice that some
9246 // of the store nodes that we found may not be selected for inclusion
9247 // in the wide store. The chain we use needs to be the chain of the
9248 // earliest store node which is *used* and replaced by the wide store.
9249 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9250 EarliestNodeUsed = i;
9253 // Find if it is better to use vectors or integers to load and store
9257 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9259 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9260 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9263 SDLoc LoadDL(LoadNodes[0].MemNode);
9264 SDLoc StoreDL(StoreNodes[0].MemNode);
9266 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9267 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9268 FirstLoad->getChain(),
9269 FirstLoad->getBasePtr(),
9270 FirstLoad->getPointerInfo(),
9271 false, false, false,
9272 FirstLoad->getAlignment());
9274 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9275 FirstInChain->getBasePtr(),
9276 FirstInChain->getPointerInfo(), false, false,
9277 FirstInChain->getAlignment());
9279 // Replace one of the loads with the new load.
9280 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9281 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9282 SDValue(NewLoad.getNode(), 1));
9284 // Remove the rest of the load chains.
9285 for (unsigned i = 1; i < NumElem ; ++i) {
9286 // Replace all chain users of the old load nodes with the chain of the new
9288 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9289 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9292 // Replace the first store with the new store.
9293 CombineTo(EarliestOp, NewStore);
9294 // Erase all other stores.
9295 for (unsigned i = 0; i < NumElem ; ++i) {
9296 // Remove all Store nodes.
9297 if (StoreNodes[i].MemNode == EarliestOp)
9299 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9300 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9301 removeFromWorkList(St);
9308 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9309 StoreSDNode *ST = cast<StoreSDNode>(N);
9310 SDValue Chain = ST->getChain();
9311 SDValue Value = ST->getValue();
9312 SDValue Ptr = ST->getBasePtr();
9314 // If this is a store of a bit convert, store the input value if the
9315 // resultant store does not need a higher alignment than the original.
9316 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9317 ST->isUnindexed()) {
9318 unsigned OrigAlign = ST->getAlignment();
9319 EVT SVT = Value.getOperand(0).getValueType();
9320 unsigned Align = TLI.getDataLayout()->
9321 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9322 if (Align <= OrigAlign &&
9323 ((!LegalOperations && !ST->isVolatile()) ||
9324 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9325 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9326 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9327 ST->isNonTemporal(), OrigAlign,
9331 // Turn 'store undef, Ptr' -> nothing.
9332 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9335 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9336 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9337 // NOTE: If the original store is volatile, this transform must not increase
9338 // the number of stores. For example, on x86-32 an f64 can be stored in one
9339 // processor operation but an i64 (which is not legal) requires two. So the
9340 // transform should not be done in this case.
9341 if (Value.getOpcode() != ISD::TargetConstantFP) {
9343 switch (CFP->getSimpleValueType(0).SimpleTy) {
9344 default: llvm_unreachable("Unknown FP type");
9345 case MVT::f16: // We don't do this for these yet.
9351 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9352 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9353 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9354 bitcastToAPInt().getZExtValue(), MVT::i32);
9355 return DAG.getStore(Chain, SDLoc(N), Tmp,
9356 Ptr, ST->getMemOperand());
9360 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9361 !ST->isVolatile()) ||
9362 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9363 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9364 getZExtValue(), MVT::i64);
9365 return DAG.getStore(Chain, SDLoc(N), Tmp,
9366 Ptr, ST->getMemOperand());
9369 if (!ST->isVolatile() &&
9370 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9371 // Many FP stores are not made apparent until after legalize, e.g. for
9372 // argument passing. Since this is so common, custom legalize the
9373 // 64-bit integer store into two 32-bit stores.
9374 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9375 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9376 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9377 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9379 unsigned Alignment = ST->getAlignment();
9380 bool isVolatile = ST->isVolatile();
9381 bool isNonTemporal = ST->isNonTemporal();
9382 const MDNode *TBAAInfo = ST->getTBAAInfo();
9384 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9385 Ptr, ST->getPointerInfo(),
9386 isVolatile, isNonTemporal,
9387 ST->getAlignment(), TBAAInfo);
9388 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9389 DAG.getConstant(4, Ptr.getValueType()));
9390 Alignment = MinAlign(Alignment, 4U);
9391 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9392 Ptr, ST->getPointerInfo().getWithOffset(4),
9393 isVolatile, isNonTemporal,
9394 Alignment, TBAAInfo);
9395 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9404 // Try to infer better alignment information than the store already has.
9405 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9406 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9407 if (Align > ST->getAlignment())
9408 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9409 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9410 ST->isVolatile(), ST->isNonTemporal(), Align,
9415 // Try transforming a pair floating point load / store ops to integer
9416 // load / store ops.
9417 SDValue NewST = TransformFPLoadStorePair(N);
9418 if (NewST.getNode())
9421 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9422 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9424 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9425 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9428 if (UseAA && ST->isUnindexed()) {
9429 // Walk up chain skipping non-aliasing memory nodes.
9430 SDValue BetterChain = FindBetterChain(N, Chain);
9432 // If there is a better chain.
9433 if (Chain != BetterChain) {
9436 // Replace the chain to avoid dependency.
9437 if (ST->isTruncatingStore()) {
9438 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9439 ST->getMemoryVT(), ST->getMemOperand());
9441 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9442 ST->getMemOperand());
9445 // Create token to keep both nodes around.
9446 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9447 MVT::Other, Chain, ReplStore);
9449 // Make sure the new and old chains are cleaned up.
9450 AddToWorkList(Token.getNode());
9452 // Don't add users to work list.
9453 return CombineTo(N, Token, false);
9457 // Try transforming N to an indexed store.
9458 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9459 return SDValue(N, 0);
9461 // FIXME: is there such a thing as a truncating indexed store?
9462 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9463 Value.getValueType().isInteger()) {
9464 // See if we can simplify the input to this truncstore with knowledge that
9465 // only the low bits are being used. For example:
9466 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9468 GetDemandedBits(Value,
9469 APInt::getLowBitsSet(
9470 Value.getValueType().getScalarType().getSizeInBits(),
9471 ST->getMemoryVT().getScalarType().getSizeInBits()));
9472 AddToWorkList(Value.getNode());
9473 if (Shorter.getNode())
9474 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9475 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9477 // Otherwise, see if we can simplify the operation with
9478 // SimplifyDemandedBits, which only works if the value has a single use.
9479 if (SimplifyDemandedBits(Value,
9480 APInt::getLowBitsSet(
9481 Value.getValueType().getScalarType().getSizeInBits(),
9482 ST->getMemoryVT().getScalarType().getSizeInBits())))
9483 return SDValue(N, 0);
9486 // If this is a load followed by a store to the same location, then the store
9488 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9489 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9490 ST->isUnindexed() && !ST->isVolatile() &&
9491 // There can't be any side effects between the load and store, such as
9493 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9494 // The store is dead, remove it.
9499 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9500 // truncating store. We can do this even if this is already a truncstore.
9501 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9502 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9503 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9504 ST->getMemoryVT())) {
9505 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9506 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9509 // Only perform this optimization before the types are legal, because we
9510 // don't want to perform this optimization on every DAGCombine invocation.
9512 bool EverChanged = false;
9515 // There can be multiple store sequences on the same chain.
9516 // Keep trying to merge store sequences until we are unable to do so
9517 // or until we merge the last store on the chain.
9518 bool Changed = MergeConsecutiveStores(ST);
9519 EverChanged |= Changed;
9520 if (!Changed) break;
9521 } while (ST->getOpcode() != ISD::DELETED_NODE);
9524 return SDValue(N, 0);
9527 return ReduceLoadOpStoreWidth(N);
9530 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9531 SDValue InVec = N->getOperand(0);
9532 SDValue InVal = N->getOperand(1);
9533 SDValue EltNo = N->getOperand(2);
9536 // If the inserted element is an UNDEF, just use the input vector.
9537 if (InVal.getOpcode() == ISD::UNDEF)
9540 EVT VT = InVec.getValueType();
9542 // If we can't generate a legal BUILD_VECTOR, exit
9543 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9546 // Check that we know which element is being inserted
9547 if (!isa<ConstantSDNode>(EltNo))
9549 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9551 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9552 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9554 SmallVector<SDValue, 8> Ops;
9555 // Do not combine these two vectors if the output vector will not replace
9556 // the input vector.
9557 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9558 Ops.append(InVec.getNode()->op_begin(),
9559 InVec.getNode()->op_end());
9560 } else if (InVec.getOpcode() == ISD::UNDEF) {
9561 unsigned NElts = VT.getVectorNumElements();
9562 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9567 // Insert the element
9568 if (Elt < Ops.size()) {
9569 // All the operands of BUILD_VECTOR must have the same type;
9570 // we enforce that here.
9571 EVT OpVT = Ops[0].getValueType();
9572 if (InVal.getValueType() != OpVT)
9573 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9574 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9575 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9579 // Return the new vector
9580 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9581 VT, &Ops[0], Ops.size());
9584 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9585 // (vextract (scalar_to_vector val, 0) -> val
9586 SDValue InVec = N->getOperand(0);
9587 EVT VT = InVec.getValueType();
9588 EVT NVT = N->getValueType(0);
9590 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9591 // Check if the result type doesn't match the inserted element type. A
9592 // SCALAR_TO_VECTOR may truncate the inserted element and the
9593 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9594 SDValue InOp = InVec.getOperand(0);
9595 if (InOp.getValueType() != NVT) {
9596 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9597 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9602 SDValue EltNo = N->getOperand(1);
9603 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9605 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9606 // We only perform this optimization before the op legalization phase because
9607 // we may introduce new vector instructions which are not backed by TD
9608 // patterns. For example on AVX, extracting elements from a wide vector
9609 // without using extract_subvector.
9610 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9611 && ConstEltNo && !LegalOperations) {
9612 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9613 int NumElem = VT.getVectorNumElements();
9614 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9615 // Find the new index to extract from.
9616 int OrigElt = SVOp->getMaskElt(Elt);
9618 // Extracting an undef index is undef.
9620 return DAG.getUNDEF(NVT);
9622 // Select the right vector half to extract from.
9623 if (OrigElt < NumElem) {
9624 InVec = InVec->getOperand(0);
9626 InVec = InVec->getOperand(1);
9630 EVT IndexTy = TLI.getVectorIdxTy();
9631 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9632 InVec, DAG.getConstant(OrigElt, IndexTy));
9635 // Perform only after legalization to ensure build_vector / vector_shuffle
9636 // optimizations have already been done.
9637 if (!LegalOperations) return SDValue();
9639 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9640 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9641 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9644 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9645 bool NewLoad = false;
9646 bool BCNumEltsChanged = false;
9647 EVT ExtVT = VT.getVectorElementType();
9650 // If the result of load has to be truncated, then it's not necessarily
9652 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9655 if (InVec.getOpcode() == ISD::BITCAST) {
9656 // Don't duplicate a load with other uses.
9657 if (!InVec.hasOneUse())
9660 EVT BCVT = InVec.getOperand(0).getValueType();
9661 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9663 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9664 BCNumEltsChanged = true;
9665 InVec = InVec.getOperand(0);
9666 ExtVT = BCVT.getVectorElementType();
9670 LoadSDNode *LN0 = NULL;
9671 const ShuffleVectorSDNode *SVN = NULL;
9672 if (ISD::isNormalLoad(InVec.getNode())) {
9673 LN0 = cast<LoadSDNode>(InVec);
9674 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9675 InVec.getOperand(0).getValueType() == ExtVT &&
9676 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9677 // Don't duplicate a load with other uses.
9678 if (!InVec.hasOneUse())
9681 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9682 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9683 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9685 // (load $addr+1*size)
9687 // Don't duplicate a load with other uses.
9688 if (!InVec.hasOneUse())
9691 // If the bit convert changed the number of elements, it is unsafe
9692 // to examine the mask.
9693 if (BCNumEltsChanged)
9696 // Select the input vector, guarding against out of range extract vector.
9697 unsigned NumElems = VT.getVectorNumElements();
9698 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9699 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9701 if (InVec.getOpcode() == ISD::BITCAST) {
9702 // Don't duplicate a load with other uses.
9703 if (!InVec.hasOneUse())
9706 InVec = InVec.getOperand(0);
9708 if (ISD::isNormalLoad(InVec.getNode())) {
9709 LN0 = cast<LoadSDNode>(InVec);
9710 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9714 // Make sure we found a non-volatile load and the extractelement is
9716 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9719 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9721 return DAG.getUNDEF(LVT);
9723 unsigned Align = LN0->getAlignment();
9725 // Check the resultant load doesn't need a higher alignment than the
9729 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9731 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9737 SDValue NewPtr = LN0->getBasePtr();
9738 unsigned PtrOff = 0;
9741 PtrOff = LVT.getSizeInBits() * Elt / 8;
9742 EVT PtrType = NewPtr.getValueType();
9743 if (TLI.isBigEndian())
9744 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9745 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9746 DAG.getConstant(PtrOff, PtrType));
9749 // The replacement we need to do here is a little tricky: we need to
9750 // replace an extractelement of a load with a load.
9751 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9752 // Note that this replacement assumes that the extractvalue is the only
9753 // use of the load; that's okay because we don't want to perform this
9754 // transformation in other cases anyway.
9757 if (NVT.bitsGT(LVT)) {
9758 // If the result type of vextract is wider than the load, then issue an
9759 // extending load instead.
9760 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9761 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9762 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9763 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9764 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9765 Align, LN0->getTBAAInfo());
9766 Chain = Load.getValue(1);
9768 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9769 LN0->getPointerInfo().getWithOffset(PtrOff),
9770 LN0->isVolatile(), LN0->isNonTemporal(),
9771 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9772 Chain = Load.getValue(1);
9773 if (NVT.bitsLT(LVT))
9774 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9776 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9778 WorkListRemover DeadNodes(*this);
9779 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9780 SDValue To[] = { Load, Chain };
9781 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9782 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9783 // worklist explicitly as well.
9784 AddToWorkList(Load.getNode());
9785 AddUsersToWorkList(Load.getNode()); // Add users too
9786 // Make sure to revisit this node to clean it up; it will usually be dead.
9788 return SDValue(N, 0);
9794 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9795 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9796 // We perform this optimization post type-legalization because
9797 // the type-legalizer often scalarizes integer-promoted vectors.
9798 // Performing this optimization before may create bit-casts which
9799 // will be type-legalized to complex code sequences.
9800 // We perform this optimization only before the operation legalizer because we
9801 // may introduce illegal operations.
9802 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9805 unsigned NumInScalars = N->getNumOperands();
9807 EVT VT = N->getValueType(0);
9809 // Check to see if this is a BUILD_VECTOR of a bunch of values
9810 // which come from any_extend or zero_extend nodes. If so, we can create
9811 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9812 // optimizations. We do not handle sign-extend because we can't fill the sign
9814 EVT SourceType = MVT::Other;
9815 bool AllAnyExt = true;
9817 for (unsigned i = 0; i != NumInScalars; ++i) {
9818 SDValue In = N->getOperand(i);
9819 // Ignore undef inputs.
9820 if (In.getOpcode() == ISD::UNDEF) continue;
9822 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9823 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9825 // Abort if the element is not an extension.
9826 if (!ZeroExt && !AnyExt) {
9827 SourceType = MVT::Other;
9831 // The input is a ZeroExt or AnyExt. Check the original type.
9832 EVT InTy = In.getOperand(0).getValueType();
9834 // Check that all of the widened source types are the same.
9835 if (SourceType == MVT::Other)
9838 else if (InTy != SourceType) {
9839 // Multiple income types. Abort.
9840 SourceType = MVT::Other;
9844 // Check if all of the extends are ANY_EXTENDs.
9845 AllAnyExt &= AnyExt;
9848 // In order to have valid types, all of the inputs must be extended from the
9849 // same source type and all of the inputs must be any or zero extend.
9850 // Scalar sizes must be a power of two.
9851 EVT OutScalarTy = VT.getScalarType();
9852 bool ValidTypes = SourceType != MVT::Other &&
9853 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9854 isPowerOf2_32(SourceType.getSizeInBits());
9856 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9857 // turn into a single shuffle instruction.
9861 bool isLE = TLI.isLittleEndian();
9862 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9863 assert(ElemRatio > 1 && "Invalid element size ratio");
9864 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9865 DAG.getConstant(0, SourceType);
9867 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9868 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9870 // Populate the new build_vector
9871 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9872 SDValue Cast = N->getOperand(i);
9873 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9874 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9875 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9877 if (Cast.getOpcode() == ISD::UNDEF)
9878 In = DAG.getUNDEF(SourceType);
9880 In = Cast->getOperand(0);
9881 unsigned Index = isLE ? (i * ElemRatio) :
9882 (i * ElemRatio + (ElemRatio - 1));
9884 assert(Index < Ops.size() && "Invalid index");
9888 // The type of the new BUILD_VECTOR node.
9889 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9890 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9891 "Invalid vector size");
9892 // Check if the new vector type is legal.
9893 if (!isTypeLegal(VecVT)) return SDValue();
9895 // Make the new BUILD_VECTOR.
9896 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9898 // The new BUILD_VECTOR node has the potential to be further optimized.
9899 AddToWorkList(BV.getNode());
9900 // Bitcast to the desired type.
9901 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9904 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9905 EVT VT = N->getValueType(0);
9907 unsigned NumInScalars = N->getNumOperands();
9910 EVT SrcVT = MVT::Other;
9911 unsigned Opcode = ISD::DELETED_NODE;
9912 unsigned NumDefs = 0;
9914 for (unsigned i = 0; i != NumInScalars; ++i) {
9915 SDValue In = N->getOperand(i);
9916 unsigned Opc = In.getOpcode();
9918 if (Opc == ISD::UNDEF)
9921 // If all scalar values are floats and converted from integers.
9922 if (Opcode == ISD::DELETED_NODE &&
9923 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9930 EVT InVT = In.getOperand(0).getValueType();
9932 // If all scalar values are typed differently, bail out. It's chosen to
9933 // simplify BUILD_VECTOR of integer types.
9934 if (SrcVT == MVT::Other)
9941 // If the vector has just one element defined, it's not worth to fold it into
9942 // a vectorized one.
9946 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9947 && "Should only handle conversion from integer to float.");
9948 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9950 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9952 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9955 SmallVector<SDValue, 8> Opnds;
9956 for (unsigned i = 0; i != NumInScalars; ++i) {
9957 SDValue In = N->getOperand(i);
9959 if (In.getOpcode() == ISD::UNDEF)
9960 Opnds.push_back(DAG.getUNDEF(SrcVT));
9962 Opnds.push_back(In.getOperand(0));
9964 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9965 &Opnds[0], Opnds.size());
9966 AddToWorkList(BV.getNode());
9968 return DAG.getNode(Opcode, dl, VT, BV);
9971 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9972 unsigned NumInScalars = N->getNumOperands();
9974 EVT VT = N->getValueType(0);
9976 // A vector built entirely of undefs is undef.
9977 if (ISD::allOperandsUndef(N))
9978 return DAG.getUNDEF(VT);
9980 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9984 V = reduceBuildVecConvertToConvertBuildVec(N);
9988 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9989 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9990 // at most two distinct vectors, turn this into a shuffle node.
9992 // May only combine to shuffle after legalize if shuffle is legal.
9993 if (LegalOperations &&
9994 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9997 SDValue VecIn1, VecIn2;
9998 for (unsigned i = 0; i != NumInScalars; ++i) {
9999 // Ignore undef inputs.
10000 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10002 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10003 // constant index, bail out.
10004 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10005 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10006 VecIn1 = VecIn2 = SDValue(0, 0);
10010 // We allow up to two distinct input vectors.
10011 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10012 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10015 if (VecIn1.getNode() == 0) {
10016 VecIn1 = ExtractedFromVec;
10017 } else if (VecIn2.getNode() == 0) {
10018 VecIn2 = ExtractedFromVec;
10020 // Too many inputs.
10021 VecIn1 = VecIn2 = SDValue(0, 0);
10026 // If everything is good, we can make a shuffle operation.
10027 if (VecIn1.getNode()) {
10028 SmallVector<int, 8> Mask;
10029 for (unsigned i = 0; i != NumInScalars; ++i) {
10030 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10031 Mask.push_back(-1);
10035 // If extracting from the first vector, just use the index directly.
10036 SDValue Extract = N->getOperand(i);
10037 SDValue ExtVal = Extract.getOperand(1);
10038 if (Extract.getOperand(0) == VecIn1) {
10039 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10040 if (ExtIndex > VT.getVectorNumElements())
10043 Mask.push_back(ExtIndex);
10047 // Otherwise, use InIdx + VecSize
10048 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10049 Mask.push_back(Idx+NumInScalars);
10052 // We can't generate a shuffle node with mismatched input and output types.
10053 // Attempt to transform a single input vector to the correct type.
10054 if ((VT != VecIn1.getValueType())) {
10055 // We don't support shuffeling between TWO values of different types.
10056 if (VecIn2.getNode() != 0)
10059 // We only support widening of vectors which are half the size of the
10060 // output registers. For example XMM->YMM widening on X86 with AVX.
10061 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10064 // If the input vector type has a different base type to the output
10065 // vector type, bail out.
10066 if (VecIn1.getValueType().getVectorElementType() !=
10067 VT.getVectorElementType())
10070 // Widen the input vector by adding undef values.
10071 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10072 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10075 // If VecIn2 is unused then change it to undef.
10076 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10078 // Check that we were able to transform all incoming values to the same
10080 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10081 VecIn1.getValueType() != VT)
10084 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10085 if (!isTypeLegal(VT))
10088 // Return the new VECTOR_SHUFFLE node.
10092 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10098 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10099 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10100 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10101 // inputs come from at most two distinct vectors, turn this into a shuffle
10104 // If we only have one input vector, we don't need to do any concatenation.
10105 if (N->getNumOperands() == 1)
10106 return N->getOperand(0);
10108 // Check if all of the operands are undefs.
10109 EVT VT = N->getValueType(0);
10110 if (ISD::allOperandsUndef(N))
10111 return DAG.getUNDEF(VT);
10113 // Optimize concat_vectors where one of the vectors is undef.
10114 if (N->getNumOperands() == 2 &&
10115 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10116 SDValue In = N->getOperand(0);
10117 assert(In.getValueType().isVector() && "Must concat vectors");
10119 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10120 if (In->getOpcode() == ISD::BITCAST &&
10121 !In->getOperand(0)->getValueType(0).isVector()) {
10122 SDValue Scalar = In->getOperand(0);
10123 EVT SclTy = Scalar->getValueType(0);
10125 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10128 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10129 VT.getSizeInBits() / SclTy.getSizeInBits());
10130 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10133 SDLoc dl = SDLoc(N);
10134 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10135 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10139 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10140 // nodes often generate nop CONCAT_VECTOR nodes.
10141 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10142 // place the incoming vectors at the exact same location.
10143 SDValue SingleSource = SDValue();
10144 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10147 SDValue Op = N->getOperand(i);
10149 if (Op.getOpcode() == ISD::UNDEF)
10152 // Check if this is the identity extract:
10153 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10156 // Find the single incoming vector for the extract_subvector.
10157 if (SingleSource.getNode()) {
10158 if (Op.getOperand(0) != SingleSource)
10161 SingleSource = Op.getOperand(0);
10163 // Check the source type is the same as the type of the result.
10164 // If not, this concat may extend the vector, so we can not
10165 // optimize it away.
10166 if (SingleSource.getValueType() != N->getValueType(0))
10170 unsigned IdentityIndex = i * PartNumElem;
10171 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10172 // The extract index must be constant.
10176 // Check that we are reading from the identity index.
10177 if (CS->getZExtValue() != IdentityIndex)
10181 if (SingleSource.getNode())
10182 return SingleSource;
10187 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10188 EVT NVT = N->getValueType(0);
10189 SDValue V = N->getOperand(0);
10191 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10193 // (extract_subvec (concat V1, V2, ...), i)
10196 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10198 if (V->getOperand(0).getValueType() != NVT)
10200 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10201 unsigned NumElems = NVT.getVectorNumElements();
10202 assert((Idx % NumElems) == 0 &&
10203 "IDX in concat is not a multiple of the result vector length.");
10204 return V->getOperand(Idx / NumElems);
10208 if (V->getOpcode() == ISD::BITCAST)
10209 V = V.getOperand(0);
10211 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10213 // Handle only simple case where vector being inserted and vector
10214 // being extracted are of same type, and are half size of larger vectors.
10215 EVT BigVT = V->getOperand(0).getValueType();
10216 EVT SmallVT = V->getOperand(1).getValueType();
10217 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10220 // Only handle cases where both indexes are constants with the same type.
10221 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10222 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10224 if (InsIdx && ExtIdx &&
10225 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10226 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10228 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10230 // indices are equal or bit offsets are equal => V1
10231 // otherwise => (extract_subvec V1, ExtIdx)
10232 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10233 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10234 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10235 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10236 DAG.getNode(ISD::BITCAST, dl,
10237 N->getOperand(0).getValueType(),
10238 V->getOperand(0)), N->getOperand(1));
10245 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10246 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10247 EVT VT = N->getValueType(0);
10248 unsigned NumElts = VT.getVectorNumElements();
10250 SDValue N0 = N->getOperand(0);
10251 SDValue N1 = N->getOperand(1);
10252 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10254 SmallVector<SDValue, 4> Ops;
10255 EVT ConcatVT = N0.getOperand(0).getValueType();
10256 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10257 unsigned NumConcats = NumElts / NumElemsPerConcat;
10259 // Look at every vector that's inserted. We're looking for exact
10260 // subvector-sized copies from a concatenated vector
10261 for (unsigned I = 0; I != NumConcats; ++I) {
10262 // Make sure we're dealing with a copy.
10263 unsigned Begin = I * NumElemsPerConcat;
10264 bool AllUndef = true, NoUndef = true;
10265 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10266 if (SVN->getMaskElt(J) >= 0)
10273 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10276 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10277 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10280 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10281 if (FirstElt < N0.getNumOperands())
10282 Ops.push_back(N0.getOperand(FirstElt));
10284 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10286 } else if (AllUndef) {
10287 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10288 } else { // Mixed with general masks and undefs, can't do optimization.
10293 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10297 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10298 EVT VT = N->getValueType(0);
10299 unsigned NumElts = VT.getVectorNumElements();
10301 SDValue N0 = N->getOperand(0);
10302 SDValue N1 = N->getOperand(1);
10304 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10306 // Canonicalize shuffle undef, undef -> undef
10307 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10308 return DAG.getUNDEF(VT);
10310 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10312 // Canonicalize shuffle v, v -> v, undef
10314 SmallVector<int, 8> NewMask;
10315 for (unsigned i = 0; i != NumElts; ++i) {
10316 int Idx = SVN->getMaskElt(i);
10317 if (Idx >= (int)NumElts) Idx -= NumElts;
10318 NewMask.push_back(Idx);
10320 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10324 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10325 if (N0.getOpcode() == ISD::UNDEF) {
10326 SmallVector<int, 8> NewMask;
10327 for (unsigned i = 0; i != NumElts; ++i) {
10328 int Idx = SVN->getMaskElt(i);
10330 if (Idx >= (int)NumElts)
10333 Idx = -1; // remove reference to lhs
10335 NewMask.push_back(Idx);
10337 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10341 // Remove references to rhs if it is undef
10342 if (N1.getOpcode() == ISD::UNDEF) {
10343 bool Changed = false;
10344 SmallVector<int, 8> NewMask;
10345 for (unsigned i = 0; i != NumElts; ++i) {
10346 int Idx = SVN->getMaskElt(i);
10347 if (Idx >= (int)NumElts) {
10351 NewMask.push_back(Idx);
10354 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10357 // If it is a splat, check if the argument vector is another splat or a
10358 // build_vector with all scalar elements the same.
10359 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10360 SDNode *V = N0.getNode();
10362 // If this is a bit convert that changes the element type of the vector but
10363 // not the number of vector elements, look through it. Be careful not to
10364 // look though conversions that change things like v4f32 to v2f64.
10365 if (V->getOpcode() == ISD::BITCAST) {
10366 SDValue ConvInput = V->getOperand(0);
10367 if (ConvInput.getValueType().isVector() &&
10368 ConvInput.getValueType().getVectorNumElements() == NumElts)
10369 V = ConvInput.getNode();
10372 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10373 assert(V->getNumOperands() == NumElts &&
10374 "BUILD_VECTOR has wrong number of operands");
10376 bool AllSame = true;
10377 for (unsigned i = 0; i != NumElts; ++i) {
10378 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10379 Base = V->getOperand(i);
10383 // Splat of <u, u, u, u>, return <u, u, u, u>
10384 if (!Base.getNode())
10386 for (unsigned i = 0; i != NumElts; ++i) {
10387 if (V->getOperand(i) != Base) {
10392 // Splat of <x, x, x, x>, return <x, x, x, x>
10398 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10399 Level < AfterLegalizeVectorOps &&
10400 (N1.getOpcode() == ISD::UNDEF ||
10401 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10402 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10403 SDValue V = partitionShuffleOfConcats(N, DAG);
10409 // If this shuffle node is simply a swizzle of another shuffle node,
10410 // and it reverses the swizzle of the previous shuffle then we can
10411 // optimize shuffle(shuffle(x, undef), undef) -> x.
10412 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10413 N1.getOpcode() == ISD::UNDEF) {
10415 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10417 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10418 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10421 // The incoming shuffle must be of the same type as the result of the
10422 // current shuffle.
10423 assert(OtherSV->getOperand(0).getValueType() == VT &&
10424 "Shuffle types don't match");
10426 for (unsigned i = 0; i != NumElts; ++i) {
10427 int Idx = SVN->getMaskElt(i);
10428 assert(Idx < (int)NumElts && "Index references undef operand");
10429 // Next, this index comes from the first value, which is the incoming
10430 // shuffle. Adopt the incoming index.
10432 Idx = OtherSV->getMaskElt(Idx);
10434 // The combined shuffle must map each index to itself.
10435 if (Idx >= 0 && (unsigned)Idx != i)
10439 return OtherSV->getOperand(0);
10445 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10446 SDValue N0 = N->getOperand(0);
10447 SDValue N2 = N->getOperand(2);
10449 // If the input vector is a concatenation, and the insert replaces
10450 // one of the halves, we can optimize into a single concat_vectors.
10451 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10452 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10453 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10454 EVT VT = N->getValueType(0);
10456 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10457 // (concat_vectors Z, Y)
10459 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10460 N->getOperand(1), N0.getOperand(1));
10462 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10463 // (concat_vectors X, Z)
10464 if (InsIdx == VT.getVectorNumElements()/2)
10465 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10466 N0.getOperand(0), N->getOperand(1));
10472 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10473 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10474 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10475 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10476 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10477 EVT VT = N->getValueType(0);
10479 SDValue LHS = N->getOperand(0);
10480 SDValue RHS = N->getOperand(1);
10481 if (N->getOpcode() == ISD::AND) {
10482 if (RHS.getOpcode() == ISD::BITCAST)
10483 RHS = RHS.getOperand(0);
10484 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10485 SmallVector<int, 8> Indices;
10486 unsigned NumElts = RHS.getNumOperands();
10487 for (unsigned i = 0; i != NumElts; ++i) {
10488 SDValue Elt = RHS.getOperand(i);
10489 if (!isa<ConstantSDNode>(Elt))
10492 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10493 Indices.push_back(i);
10494 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10495 Indices.push_back(NumElts);
10500 // Let's see if the target supports this vector_shuffle.
10501 EVT RVT = RHS.getValueType();
10502 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10505 // Return the new VECTOR_SHUFFLE node.
10506 EVT EltVT = RVT.getVectorElementType();
10507 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10508 DAG.getConstant(0, EltVT));
10509 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10510 RVT, &ZeroOps[0], ZeroOps.size());
10511 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10512 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10513 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10520 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10521 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10522 assert(N->getValueType(0).isVector() &&
10523 "SimplifyVBinOp only works on vectors!");
10525 SDValue LHS = N->getOperand(0);
10526 SDValue RHS = N->getOperand(1);
10527 SDValue Shuffle = XformToShuffleWithZero(N);
10528 if (Shuffle.getNode()) return Shuffle;
10530 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10532 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10533 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10534 // Check if both vectors are constants. If not bail out.
10535 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10536 cast<BuildVectorSDNode>(RHS)->isConstant()))
10539 SmallVector<SDValue, 8> Ops;
10540 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10541 SDValue LHSOp = LHS.getOperand(i);
10542 SDValue RHSOp = RHS.getOperand(i);
10544 // Can't fold divide by zero.
10545 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10546 N->getOpcode() == ISD::FDIV) {
10547 if ((RHSOp.getOpcode() == ISD::Constant &&
10548 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10549 (RHSOp.getOpcode() == ISD::ConstantFP &&
10550 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10554 EVT VT = LHSOp.getValueType();
10555 EVT RVT = RHSOp.getValueType();
10557 // Integer BUILD_VECTOR operands may have types larger than the element
10558 // size (e.g., when the element type is not legal). Prior to type
10559 // legalization, the types may not match between the two BUILD_VECTORS.
10560 // Truncate one of the operands to make them match.
10561 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10562 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10564 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10568 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10570 if (FoldOp.getOpcode() != ISD::UNDEF &&
10571 FoldOp.getOpcode() != ISD::Constant &&
10572 FoldOp.getOpcode() != ISD::ConstantFP)
10574 Ops.push_back(FoldOp);
10575 AddToWorkList(FoldOp.getNode());
10578 if (Ops.size() == LHS.getNumOperands())
10579 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10580 LHS.getValueType(), &Ops[0], Ops.size());
10586 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10587 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10588 assert(N->getValueType(0).isVector() &&
10589 "SimplifyVUnaryOp only works on vectors!");
10591 SDValue N0 = N->getOperand(0);
10593 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10596 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10597 SmallVector<SDValue, 8> Ops;
10598 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10599 SDValue Op = N0.getOperand(i);
10600 if (Op.getOpcode() != ISD::UNDEF &&
10601 Op.getOpcode() != ISD::ConstantFP)
10603 EVT EltVT = Op.getValueType();
10604 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10605 if (FoldOp.getOpcode() != ISD::UNDEF &&
10606 FoldOp.getOpcode() != ISD::ConstantFP)
10608 Ops.push_back(FoldOp);
10609 AddToWorkList(FoldOp.getNode());
10612 if (Ops.size() != N0.getNumOperands())
10615 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10616 N0.getValueType(), &Ops[0], Ops.size());
10619 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10620 SDValue N1, SDValue N2){
10621 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10623 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10624 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10626 // If we got a simplified select_cc node back from SimplifySelectCC, then
10627 // break it down into a new SETCC node, and a new SELECT node, and then return
10628 // the SELECT node, since we were called with a SELECT node.
10629 if (SCC.getNode()) {
10630 // Check to see if we got a select_cc back (to turn into setcc/select).
10631 // Otherwise, just return whatever node we got back, like fabs.
10632 if (SCC.getOpcode() == ISD::SELECT_CC) {
10633 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10635 SCC.getOperand(0), SCC.getOperand(1),
10636 SCC.getOperand(4));
10637 AddToWorkList(SETCC.getNode());
10638 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10639 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10647 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10648 /// are the two values being selected between, see if we can simplify the
10649 /// select. Callers of this should assume that TheSelect is deleted if this
10650 /// returns true. As such, they should return the appropriate thing (e.g. the
10651 /// node) back to the top-level of the DAG combiner loop to avoid it being
10653 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10656 // Cannot simplify select with vector condition
10657 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10659 // If this is a select from two identical things, try to pull the operation
10660 // through the select.
10661 if (LHS.getOpcode() != RHS.getOpcode() ||
10662 !LHS.hasOneUse() || !RHS.hasOneUse())
10665 // If this is a load and the token chain is identical, replace the select
10666 // of two loads with a load through a select of the address to load from.
10667 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10668 // constants have been dropped into the constant pool.
10669 if (LHS.getOpcode() == ISD::LOAD) {
10670 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10671 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10673 // Token chains must be identical.
10674 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10675 // Do not let this transformation reduce the number of volatile loads.
10676 LLD->isVolatile() || RLD->isVolatile() ||
10677 // If this is an EXTLOAD, the VT's must match.
10678 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10679 // If this is an EXTLOAD, the kind of extension must match.
10680 (LLD->getExtensionType() != RLD->getExtensionType() &&
10681 // The only exception is if one of the extensions is anyext.
10682 LLD->getExtensionType() != ISD::EXTLOAD &&
10683 RLD->getExtensionType() != ISD::EXTLOAD) ||
10684 // FIXME: this discards src value information. This is
10685 // over-conservative. It would be beneficial to be able to remember
10686 // both potential memory locations. Since we are discarding
10687 // src value info, don't do the transformation if the memory
10688 // locations are not in the default address space.
10689 LLD->getPointerInfo().getAddrSpace() != 0 ||
10690 RLD->getPointerInfo().getAddrSpace() != 0 ||
10691 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10692 LLD->getBasePtr().getValueType()))
10695 // Check that the select condition doesn't reach either load. If so,
10696 // folding this will induce a cycle into the DAG. If not, this is safe to
10697 // xform, so create a select of the addresses.
10699 if (TheSelect->getOpcode() == ISD::SELECT) {
10700 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10701 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10702 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10704 // The loads must not depend on one another.
10705 if (LLD->isPredecessorOf(RLD) ||
10706 RLD->isPredecessorOf(LLD))
10708 Addr = DAG.getSelect(SDLoc(TheSelect),
10709 LLD->getBasePtr().getValueType(),
10710 TheSelect->getOperand(0), LLD->getBasePtr(),
10711 RLD->getBasePtr());
10712 } else { // Otherwise SELECT_CC
10713 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10714 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10716 if ((LLD->hasAnyUseOfValue(1) &&
10717 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10718 (RLD->hasAnyUseOfValue(1) &&
10719 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10722 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10723 LLD->getBasePtr().getValueType(),
10724 TheSelect->getOperand(0),
10725 TheSelect->getOperand(1),
10726 LLD->getBasePtr(), RLD->getBasePtr(),
10727 TheSelect->getOperand(4));
10731 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10732 Load = DAG.getLoad(TheSelect->getValueType(0),
10734 // FIXME: Discards pointer and TBAA info.
10735 LLD->getChain(), Addr, MachinePointerInfo(),
10736 LLD->isVolatile(), LLD->isNonTemporal(),
10737 LLD->isInvariant(), LLD->getAlignment());
10739 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10740 RLD->getExtensionType() : LLD->getExtensionType(),
10742 TheSelect->getValueType(0),
10743 // FIXME: Discards pointer and TBAA info.
10744 LLD->getChain(), Addr, MachinePointerInfo(),
10745 LLD->getMemoryVT(), LLD->isVolatile(),
10746 LLD->isNonTemporal(), LLD->getAlignment());
10749 // Users of the select now use the result of the load.
10750 CombineTo(TheSelect, Load);
10752 // Users of the old loads now use the new load's chain. We know the
10753 // old-load value is dead now.
10754 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10755 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10762 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10763 /// where 'cond' is the comparison specified by CC.
10764 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10765 SDValue N2, SDValue N3,
10766 ISD::CondCode CC, bool NotExtCompare) {
10767 // (x ? y : y) -> y.
10768 if (N2 == N3) return N2;
10770 EVT VT = N2.getValueType();
10771 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10772 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10773 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10775 // Determine if the condition we're dealing with is constant
10776 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10777 N0, N1, CC, DL, false);
10778 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10779 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10781 // fold select_cc true, x, y -> x
10782 if (SCCC && !SCCC->isNullValue())
10784 // fold select_cc false, x, y -> y
10785 if (SCCC && SCCC->isNullValue())
10788 // Check to see if we can simplify the select into an fabs node
10789 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10790 // Allow either -0.0 or 0.0
10791 if (CFP->getValueAPF().isZero()) {
10792 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10793 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10794 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10795 N2 == N3.getOperand(0))
10796 return DAG.getNode(ISD::FABS, DL, VT, N0);
10798 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10799 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10800 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10801 N2.getOperand(0) == N3)
10802 return DAG.getNode(ISD::FABS, DL, VT, N3);
10806 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10807 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10808 // in it. This is a win when the constant is not otherwise available because
10809 // it replaces two constant pool loads with one. We only do this if the FP
10810 // type is known to be legal, because if it isn't, then we are before legalize
10811 // types an we want the other legalization to happen first (e.g. to avoid
10812 // messing with soft float) and if the ConstantFP is not legal, because if
10813 // it is legal, we may not need to store the FP constant in a constant pool.
10814 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10815 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10816 if (TLI.isTypeLegal(N2.getValueType()) &&
10817 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10818 TargetLowering::Legal) &&
10819 // If both constants have multiple uses, then we won't need to do an
10820 // extra load, they are likely around in registers for other users.
10821 (TV->hasOneUse() || FV->hasOneUse())) {
10822 Constant *Elts[] = {
10823 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10824 const_cast<ConstantFP*>(TV->getConstantFPValue())
10826 Type *FPTy = Elts[0]->getType();
10827 const DataLayout &TD = *TLI.getDataLayout();
10829 // Create a ConstantArray of the two constants.
10830 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10831 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10832 TD.getPrefTypeAlignment(FPTy));
10833 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10835 // Get the offsets to the 0 and 1 element of the array so that we can
10836 // select between them.
10837 SDValue Zero = DAG.getIntPtrConstant(0);
10838 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10839 SDValue One = DAG.getIntPtrConstant(EltSize);
10841 SDValue Cond = DAG.getSetCC(DL,
10842 getSetCCResultType(N0.getValueType()),
10844 AddToWorkList(Cond.getNode());
10845 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10847 AddToWorkList(CstOffset.getNode());
10848 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10850 AddToWorkList(CPIdx.getNode());
10851 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10852 MachinePointerInfo::getConstantPool(), false,
10853 false, false, Alignment);
10858 // Check to see if we can perform the "gzip trick", transforming
10859 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10860 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10861 (N1C->isNullValue() || // (a < 0) ? b : 0
10862 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10863 EVT XType = N0.getValueType();
10864 EVT AType = N2.getValueType();
10865 if (XType.bitsGE(AType)) {
10866 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10867 // single-bit constant.
10868 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10869 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10870 ShCtV = XType.getSizeInBits()-ShCtV-1;
10871 SDValue ShCt = DAG.getConstant(ShCtV,
10872 getShiftAmountTy(N0.getValueType()));
10873 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10875 AddToWorkList(Shift.getNode());
10877 if (XType.bitsGT(AType)) {
10878 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10879 AddToWorkList(Shift.getNode());
10882 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10885 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10887 DAG.getConstant(XType.getSizeInBits()-1,
10888 getShiftAmountTy(N0.getValueType())));
10889 AddToWorkList(Shift.getNode());
10891 if (XType.bitsGT(AType)) {
10892 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10893 AddToWorkList(Shift.getNode());
10896 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10900 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10901 // where y is has a single bit set.
10902 // A plaintext description would be, we can turn the SELECT_CC into an AND
10903 // when the condition can be materialized as an all-ones register. Any
10904 // single bit-test can be materialized as an all-ones register with
10905 // shift-left and shift-right-arith.
10906 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10907 N0->getValueType(0) == VT &&
10908 N1C && N1C->isNullValue() &&
10909 N2C && N2C->isNullValue()) {
10910 SDValue AndLHS = N0->getOperand(0);
10911 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10912 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10913 // Shift the tested bit over the sign bit.
10914 APInt AndMask = ConstAndRHS->getAPIntValue();
10916 DAG.getConstant(AndMask.countLeadingZeros(),
10917 getShiftAmountTy(AndLHS.getValueType()));
10918 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10920 // Now arithmetic right shift it all the way over, so the result is either
10921 // all-ones, or zero.
10923 DAG.getConstant(AndMask.getBitWidth()-1,
10924 getShiftAmountTy(Shl.getValueType()));
10925 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10927 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10931 // fold select C, 16, 0 -> shl C, 4
10932 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10933 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10934 TargetLowering::ZeroOrOneBooleanContent) {
10936 // If the caller doesn't want us to simplify this into a zext of a compare,
10938 if (NotExtCompare && N2C->getAPIntValue() == 1)
10941 // Get a SetCC of the condition
10942 // NOTE: Don't create a SETCC if it's not legal on this target.
10943 if (!LegalOperations ||
10944 TLI.isOperationLegal(ISD::SETCC,
10945 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10947 // cast from setcc result type to select result type
10949 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10951 if (N2.getValueType().bitsLT(SCC.getValueType()))
10952 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10953 N2.getValueType());
10955 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10956 N2.getValueType(), SCC);
10958 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10959 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10960 N2.getValueType(), SCC);
10963 AddToWorkList(SCC.getNode());
10964 AddToWorkList(Temp.getNode());
10966 if (N2C->getAPIntValue() == 1)
10969 // shl setcc result by log2 n2c
10970 return DAG.getNode(
10971 ISD::SHL, DL, N2.getValueType(), Temp,
10972 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10973 getShiftAmountTy(Temp.getValueType())));
10977 // Check to see if this is the equivalent of setcc
10978 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10979 // otherwise, go ahead with the folds.
10980 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10981 EVT XType = N0.getValueType();
10982 if (!LegalOperations ||
10983 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10984 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10985 if (Res.getValueType() != VT)
10986 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10990 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10991 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10992 (!LegalOperations ||
10993 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10994 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10995 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10996 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10997 getShiftAmountTy(Ctlz.getValueType())));
10999 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11000 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11001 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11002 XType, DAG.getConstant(0, XType), N0);
11003 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11004 return DAG.getNode(ISD::SRL, DL, XType,
11005 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11006 DAG.getConstant(XType.getSizeInBits()-1,
11007 getShiftAmountTy(XType)));
11009 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11010 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11011 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11012 DAG.getConstant(XType.getSizeInBits()-1,
11013 getShiftAmountTy(N0.getValueType())));
11014 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11018 // Check to see if this is an integer abs.
11019 // select_cc setg[te] X, 0, X, -X ->
11020 // select_cc setgt X, -1, X, -X ->
11021 // select_cc setl[te] X, 0, -X, X ->
11022 // select_cc setlt X, 1, -X, X ->
11023 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11025 ConstantSDNode *SubC = NULL;
11026 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11027 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11028 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11029 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11030 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11031 (N1C->isOne() && CC == ISD::SETLT)) &&
11032 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11033 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11035 EVT XType = N0.getValueType();
11036 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11037 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11039 DAG.getConstant(XType.getSizeInBits()-1,
11040 getShiftAmountTy(N0.getValueType())));
11041 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11043 AddToWorkList(Shift.getNode());
11044 AddToWorkList(Add.getNode());
11045 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11052 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11053 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11054 SDValue N1, ISD::CondCode Cond,
11055 SDLoc DL, bool foldBooleans) {
11056 TargetLowering::DAGCombinerInfo
11057 DagCombineInfo(DAG, Level, false, this);
11058 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11061 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11062 /// return a DAG expression to select that will generate the same value by
11063 /// multiplying by a magic number. See:
11064 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11065 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11066 std::vector<SDNode*> Built;
11067 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11069 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11071 AddToWorkList(*ii);
11075 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11076 /// return a DAG expression to select that will generate the same value by
11077 /// multiplying by a magic number. See:
11078 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11079 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11080 std::vector<SDNode*> Built;
11081 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11083 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11085 AddToWorkList(*ii);
11089 /// FindBaseOffset - Return true if base is a frame index, which is known not
11090 // to alias with anything but itself. Provides base object and offset as
11092 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11093 const GlobalValue *&GV, const void *&CV) {
11094 // Assume it is a primitive operation.
11095 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11097 // If it's an adding a simple constant then integrate the offset.
11098 if (Base.getOpcode() == ISD::ADD) {
11099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11100 Base = Base.getOperand(0);
11101 Offset += C->getZExtValue();
11105 // Return the underlying GlobalValue, and update the Offset. Return false
11106 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11107 // by multiple nodes with different offsets.
11108 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11109 GV = G->getGlobal();
11110 Offset += G->getOffset();
11114 // Return the underlying Constant value, and update the Offset. Return false
11115 // for ConstantSDNodes since the same constant pool entry may be represented
11116 // by multiple nodes with different offsets.
11117 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11118 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11119 : (const void *)C->getConstVal();
11120 Offset += C->getOffset();
11123 // If it's any of the following then it can't alias with anything but itself.
11124 return isa<FrameIndexSDNode>(Base);
11127 /// isAlias - Return true if there is any possibility that the two addresses
11129 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11130 const Value *SrcValue1, int SrcValueOffset1,
11131 unsigned SrcValueAlign1,
11132 const MDNode *TBAAInfo1,
11133 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11134 const Value *SrcValue2, int SrcValueOffset2,
11135 unsigned SrcValueAlign2,
11136 const MDNode *TBAAInfo2) const {
11137 // If they are the same then they must be aliases.
11138 if (Ptr1 == Ptr2) return true;
11140 // If they are both volatile then they cannot be reordered.
11141 if (IsVolatile1 && IsVolatile2) return true;
11143 // Gather base node and offset information.
11144 SDValue Base1, Base2;
11145 int64_t Offset1, Offset2;
11146 const GlobalValue *GV1, *GV2;
11147 const void *CV1, *CV2;
11148 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11149 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11151 // If they have a same base address then check to see if they overlap.
11152 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11153 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11155 // It is possible for different frame indices to alias each other, mostly
11156 // when tail call optimization reuses return address slots for arguments.
11157 // To catch this case, look up the actual index of frame indices to compute
11158 // the real alias relationship.
11159 if (isFrameIndex1 && isFrameIndex2) {
11160 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11161 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11162 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11163 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11166 // Otherwise, if we know what the bases are, and they aren't identical, then
11167 // we know they cannot alias.
11168 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11171 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11172 // compared to the size and offset of the access, we may be able to prove they
11173 // do not alias. This check is conservative for now to catch cases created by
11174 // splitting vector types.
11175 if ((SrcValueAlign1 == SrcValueAlign2) &&
11176 (SrcValueOffset1 != SrcValueOffset2) &&
11177 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11178 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11179 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11181 // There is no overlap between these relatively aligned accesses of similar
11182 // size, return no alias.
11183 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11187 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11188 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11190 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11191 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11194 if (UseAA && SrcValue1 && SrcValue2) {
11195 // Use alias analysis information.
11196 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11197 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11198 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11199 AliasAnalysis::AliasResult AAResult =
11200 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11201 UseTBAA ? TBAAInfo1 : 0),
11202 AliasAnalysis::Location(SrcValue2, Overlap2,
11203 UseTBAA ? TBAAInfo2 : 0));
11204 if (AAResult == AliasAnalysis::NoAlias)
11208 // Otherwise we have to assume they alias.
11212 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11213 SDValue Ptr0, Ptr1;
11214 int64_t Size0, Size1;
11215 bool IsVolatile0, IsVolatile1;
11216 const Value *SrcValue0, *SrcValue1;
11217 int SrcValueOffset0, SrcValueOffset1;
11218 unsigned SrcValueAlign0, SrcValueAlign1;
11219 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11220 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11221 SrcValueAlign0, SrcTBAAInfo0);
11222 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11223 SrcValueAlign1, SrcTBAAInfo1);
11224 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11225 SrcValueAlign0, SrcTBAAInfo0,
11226 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11227 SrcValueAlign1, SrcTBAAInfo1);
11230 /// FindAliasInfo - Extracts the relevant alias information from the memory
11231 /// node. Returns true if the operand was a nonvolatile load.
11232 bool DAGCombiner::FindAliasInfo(SDNode *N,
11233 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11234 const Value *&SrcValue,
11235 int &SrcValueOffset,
11236 unsigned &SrcValueAlign,
11237 const MDNode *&TBAAInfo) const {
11238 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11240 Ptr = LS->getBasePtr();
11241 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11242 IsVolatile = LS->isVolatile();
11243 SrcValue = LS->getSrcValue();
11244 SrcValueOffset = LS->getSrcValueOffset();
11245 SrcValueAlign = LS->getOriginalAlignment();
11246 TBAAInfo = LS->getTBAAInfo();
11247 return isa<LoadSDNode>(LS) && !IsVolatile;
11250 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11251 /// looking for aliasing nodes and adding them to the Aliases vector.
11252 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11253 SmallVectorImpl<SDValue> &Aliases) {
11254 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11255 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11257 // Get alias information for node.
11261 const Value *SrcValue;
11262 int SrcValueOffset;
11263 unsigned SrcValueAlign;
11264 const MDNode *SrcTBAAInfo;
11265 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11266 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11269 Chains.push_back(OriginalChain);
11270 unsigned Depth = 0;
11272 // Look at each chain and determine if it is an alias. If so, add it to the
11273 // aliases list. If not, then continue up the chain looking for the next
11275 while (!Chains.empty()) {
11276 SDValue Chain = Chains.back();
11279 // For TokenFactor nodes, look at each operand and only continue up the
11280 // chain until we find two aliases. If we've seen two aliases, assume we'll
11281 // find more and revert to original chain since the xform is unlikely to be
11284 // FIXME: The depth check could be made to return the last non-aliasing
11285 // chain we found before we hit a tokenfactor rather than the original
11287 if (Depth > 6 || Aliases.size() == 2) {
11289 Aliases.push_back(OriginalChain);
11293 // Don't bother if we've been before.
11294 if (!Visited.insert(Chain.getNode()))
11297 switch (Chain.getOpcode()) {
11298 case ISD::EntryToken:
11299 // Entry token is ideal chain operand, but handled in FindBetterChain.
11304 // Get alias information for Chain.
11308 const Value *OpSrcValue;
11309 int OpSrcValueOffset;
11310 unsigned OpSrcValueAlign;
11311 const MDNode *OpSrcTBAAInfo;
11312 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11313 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11317 // If chain is alias then stop here.
11318 if (!(IsLoad && IsOpLoad) &&
11319 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11320 SrcValueAlign, SrcTBAAInfo,
11321 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11322 OpSrcValueAlign, OpSrcTBAAInfo)) {
11323 Aliases.push_back(Chain);
11325 // Look further up the chain.
11326 Chains.push_back(Chain.getOperand(0));
11332 case ISD::TokenFactor:
11333 // We have to check each of the operands of the token factor for "small"
11334 // token factors, so we queue them up. Adding the operands to the queue
11335 // (stack) in reverse order maintains the original order and increases the
11336 // likelihood that getNode will find a matching token factor (CSE.)
11337 if (Chain.getNumOperands() > 16) {
11338 Aliases.push_back(Chain);
11341 for (unsigned n = Chain.getNumOperands(); n;)
11342 Chains.push_back(Chain.getOperand(--n));
11347 // For all other instructions we will just have to take what we can get.
11348 Aliases.push_back(Chain);
11353 // We need to be careful here to also search for aliases through the
11354 // value operand of a store, etc. Consider the following situation:
11356 // L1 = load Token1, %52
11357 // S1 = store Token1, L1, %51
11358 // L2 = load Token1, %52+8
11359 // S2 = store Token1, L2, %51+8
11360 // Token2 = Token(S1, S2)
11361 // L3 = load Token2, %53
11362 // S3 = store Token2, L3, %52
11363 // L4 = load Token2, %53+8
11364 // S4 = store Token2, L4, %52+8
11365 // If we search for aliases of S3 (which loads address %52), and we look
11366 // only through the chain, then we'll miss the trivial dependence on L1
11367 // (which also loads from %52). We then might change all loads and
11368 // stores to use Token1 as their chain operand, which could result in
11369 // copying %53 into %52 before copying %52 into %51 (which should
11372 // The problem is, however, that searching for such data dependencies
11373 // can become expensive, and the cost is not directly related to the
11374 // chain depth. Instead, we'll rule out such configurations here by
11375 // insisting that we've visited all chain users (except for users
11376 // of the original chain, which is not necessary). When doing this,
11377 // we need to look through nodes we don't care about (otherwise, things
11378 // like register copies will interfere with trivial cases).
11380 SmallVector<const SDNode *, 16> Worklist;
11381 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11382 IE = Visited.end(); I != IE; ++I)
11383 if (*I != OriginalChain.getNode())
11384 Worklist.push_back(*I);
11386 while (!Worklist.empty()) {
11387 const SDNode *M = Worklist.pop_back_val();
11389 // We have already visited M, and want to make sure we've visited any uses
11390 // of M that we care about. For uses that we've not visisted, and don't
11391 // care about, queue them to the worklist.
11393 for (SDNode::use_iterator UI = M->use_begin(),
11394 UIE = M->use_end(); UI != UIE; ++UI)
11395 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11396 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11397 // We've not visited this use, and we care about it (it could have an
11398 // ordering dependency with the original node).
11400 Aliases.push_back(OriginalChain);
11404 // We've not visited this use, but we don't care about it. Mark it as
11405 // visited and enqueue it to the worklist.
11406 Worklist.push_back(*UI);
11411 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11412 /// for a better chain (aliasing node.)
11413 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11414 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11416 // Accumulate all the aliases to this node.
11417 GatherAllAliases(N, OldChain, Aliases);
11419 // If no operands then chain to entry token.
11420 if (Aliases.size() == 0)
11421 return DAG.getEntryNode();
11423 // If a single operand then chain to it. We don't need to revisit it.
11424 if (Aliases.size() == 1)
11427 // Construct a custom tailored token factor.
11428 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11429 &Aliases[0], Aliases.size());
11432 // SelectionDAG::Combine - This is the entry point for the file.
11434 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11435 CodeGenOpt::Level OptLevel) {
11436 /// run - This is the main entry point to this class.
11438 DAGCombiner(*this, AA, OptLevel).Run(Level);