1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 // 1. Stack coloring does not update TBAA when merging allocas
61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 // Because BasicAA does not handle inttoptr, we'll often miss basic type
63 // punning idioms that we need to catch so we don't miscompile real-world
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
76 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 // Worklist of all of the nodes that need to be simplified.
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
113 SmallVector<SDNode*, 64> WorkListOrder;
115 // AA - Used for DAG load/store alias analysis.
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
130 SDValue visit(SDNode *N);
133 /// AddToWorkList - Add to the work list making sure its instance is at the
134 /// back (next to be processed.)
135 void AddToWorkList(SDNode *N) {
136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
140 /// removeFromWorkList - remove all instances of N from the worklist.
142 void removeFromWorkList(SDNode *N) {
143 WorkListContents.erase(N);
146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150 return CombineTo(N, &Res, 1, AddTo);
153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
155 SDValue To[] = { Res0, Res1 };
156 return CombineTo(N, To, 2, AddTo);
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
163 /// SimplifyDemandedBits - Check the specified integer node value to see if
164 /// it can be simplified or if things it uses can be simplified by bit
165 /// propagation. If so, return true.
166 bool SimplifyDemandedBits(SDValue Op) {
167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
169 return SimplifyDemandedBits(Op, Demanded);
172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
176 bool SliceUpLoad(SDNode *N);
178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182 SDValue PromoteIntBinOp(SDValue Op);
183 SDValue PromoteIntShiftOp(SDValue Op);
184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189 ISD::NodeType ExtType);
191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
194 SDValue combine(SDNode *N);
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
208 SDValue visitSUBC(SDNode *N);
209 SDValue visitADDE(SDNode *N);
210 SDValue visitSUBE(SDNode *N);
211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
228 SDValue SimplifyVUnaryOp(SDNode *N);
229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitRotate(SDNode *N);
233 SDValue visitCTLZ(SDNode *N);
234 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
235 SDValue visitCTTZ(SDNode *N);
236 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
237 SDValue visitCTPOP(SDNode *N);
238 SDValue visitSELECT(SDNode *N);
239 SDValue visitVSELECT(SDNode *N);
240 SDValue visitSELECT_CC(SDNode *N);
241 SDValue visitSETCC(SDNode *N);
242 SDValue visitSIGN_EXTEND(SDNode *N);
243 SDValue visitZERO_EXTEND(SDNode *N);
244 SDValue visitANY_EXTEND(SDNode *N);
245 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246 SDValue visitTRUNCATE(SDNode *N);
247 SDValue visitBITCAST(SDNode *N);
248 SDValue visitBUILD_PAIR(SDNode *N);
249 SDValue visitFADD(SDNode *N);
250 SDValue visitFSUB(SDNode *N);
251 SDValue visitFMUL(SDNode *N);
252 SDValue visitFMA(SDNode *N);
253 SDValue visitFDIV(SDNode *N);
254 SDValue visitFREM(SDNode *N);
255 SDValue visitFCOPYSIGN(SDNode *N);
256 SDValue visitSINT_TO_FP(SDNode *N);
257 SDValue visitUINT_TO_FP(SDNode *N);
258 SDValue visitFP_TO_SINT(SDNode *N);
259 SDValue visitFP_TO_UINT(SDNode *N);
260 SDValue visitFP_ROUND(SDNode *N);
261 SDValue visitFP_ROUND_INREG(SDNode *N);
262 SDValue visitFP_EXTEND(SDNode *N);
263 SDValue visitFNEG(SDNode *N);
264 SDValue visitFABS(SDNode *N);
265 SDValue visitFCEIL(SDNode *N);
266 SDValue visitFTRUNC(SDNode *N);
267 SDValue visitFFLOOR(SDNode *N);
268 SDValue visitBRCOND(SDNode *N);
269 SDValue visitBR_CC(SDNode *N);
270 SDValue visitLOAD(SDNode *N);
271 SDValue visitSTORE(SDNode *N);
272 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274 SDValue visitBUILD_VECTOR(SDNode *N);
275 SDValue visitCONCAT_VECTORS(SDNode *N);
276 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
277 SDValue visitVECTOR_SHUFFLE(SDNode *N);
278 SDValue visitINSERT_SUBVECTOR(SDNode *N);
280 SDValue XformToShuffleWithZero(SDNode *N);
281 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
283 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
285 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
287 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
289 SDValue N3, ISD::CondCode CC,
290 bool NotExtCompare = false);
291 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
292 SDLoc DL, bool foldBooleans = true);
293 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
295 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
296 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
297 SDValue BuildSDIV(SDNode *N);
298 SDValue BuildUDIV(SDNode *N);
299 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300 bool DemandHighBits = true);
301 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
302 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303 SDValue InnerPos, SDValue InnerNeg,
304 unsigned PosOpcode, unsigned NegOpcode,
306 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
307 SDValue ReduceLoadWidth(SDNode *N);
308 SDValue ReduceLoadOpStoreWidth(SDNode *N);
309 SDValue TransformFPLoadStorePair(SDNode *N);
310 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
311 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
313 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
315 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316 /// looking for aliasing nodes and adding them to the Aliases vector.
317 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
318 SmallVectorImpl<SDValue> &Aliases);
320 /// isAlias - Return true if there is any possibility that the two addresses
322 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
323 const Value *SrcValue1, int SrcValueOffset1,
324 unsigned SrcValueAlign1,
325 const MDNode *TBAAInfo1,
326 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
327 const Value *SrcValue2, int SrcValueOffset2,
328 unsigned SrcValueAlign2,
329 const MDNode *TBAAInfo2) const;
331 /// isAlias - Return true if there is any possibility that the two addresses
333 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
335 /// FindAliasInfo - Extracts the relevant alias information from the memory
336 /// node. Returns true if the operand was a load.
337 bool FindAliasInfo(SDNode *N,
338 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
339 const Value *&SrcValue, int &SrcValueOffset,
340 unsigned &SrcValueAlignment,
341 const MDNode *&TBAAInfo) const;
343 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
344 /// looking for a better chain (aliasing node.)
345 SDValue FindBetterChain(SDNode *N, SDValue Chain);
347 /// Merge consecutive store operations into a wide store.
348 /// This optimization uses wide integers or vectors when possible.
349 /// \return True if some memory operations were changed.
350 bool MergeConsecutiveStores(StoreSDNode *N);
352 /// \brief Try to transform a truncation where C is a constant:
353 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
355 /// \p N needs to be a truncation and its first operand an AND. Other
356 /// requirements are checked by the function (e.g. that trunc is
357 /// single-use) and if missed an empty SDValue is returned.
358 SDValue distributeTruncateThroughAnd(SDNode *N);
361 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
362 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364 AttributeSet FnAttrs =
365 DAG.getMachineFunction().getFunction()->getAttributes();
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368 Attribute::OptimizeForSize) ||
369 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
372 /// Run - runs the dag combiner on all nodes in the work list
373 void Run(CombineLevel AtLevel);
375 SelectionDAG &getDAG() const { return DAG; }
377 /// getShiftAmountTy - Returns a type large enough to hold any valid
378 /// shift amount - before type legalization these can be huge.
379 EVT getShiftAmountTy(EVT LHSTy) {
380 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381 if (LHSTy.isVector())
383 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384 : TLI.getPointerTy();
387 /// isTypeLegal - This method returns true if we are running before type
388 /// legalization or if the specified VT is legal.
389 bool isTypeLegal(const EVT &VT) {
390 if (!LegalTypes) return true;
391 return TLI.isTypeLegal(VT);
394 /// getSetCCResultType - Convenience wrapper around
395 /// TargetLowering::getSetCCResultType
396 EVT getSetCCResultType(EVT VT) const {
397 return TLI.getSetCCResultType(*DAG.getContext(), VT);
404 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
405 /// nodes from the worklist.
406 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
409 explicit WorkListRemover(DAGCombiner &dc)
410 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
412 void NodeDeleted(SDNode *N, SDNode *E) override {
413 DC.removeFromWorkList(N);
418 //===----------------------------------------------------------------------===//
419 // TargetLowering::DAGCombinerInfo implementation
420 //===----------------------------------------------------------------------===//
422 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423 ((DAGCombiner*)DC)->AddToWorkList(N);
426 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427 ((DAGCombiner*)DC)->removeFromWorkList(N);
430 SDValue TargetLowering::DAGCombinerInfo::
431 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
441 SDValue TargetLowering::DAGCombinerInfo::
442 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
446 void TargetLowering::DAGCombinerInfo::
447 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
455 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
456 /// specified expression for the same cost as the expression itself, or 2 if we
457 /// can compute the negated form more cheaply than the expression itself.
458 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
459 const TargetLowering &TLI,
460 const TargetOptions *Options,
461 unsigned Depth = 0) {
462 // fneg is removable even if it has multiple uses.
463 if (Op.getOpcode() == ISD::FNEG) return 2;
465 // Don't allow anything with multiple uses.
466 if (!Op.hasOneUse()) return 0;
468 // Don't recurse exponentially.
469 if (Depth > 6) return 0;
471 switch (Op.getOpcode()) {
472 default: return false;
473 case ISD::ConstantFP:
474 // Don't invert constant FP values after legalize. The negated constant
475 // isn't necessarily legal.
476 return LegalOperations ? 0 : 1;
478 // FIXME: determine better conditions for this xform.
479 if (!Options->UnsafeFPMath) return 0;
481 // After operation legalization, it might not be legal to create new FSUBs.
482 if (LegalOperations &&
483 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
486 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
487 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
490 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
491 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
494 // We can't turn -(A-B) into B-A when we honor signed zeros.
495 if (!Options->UnsafeFPMath) return 0;
497 // fold (fneg (fsub A, B)) -> (fsub B, A)
502 if (Options->HonorSignDependentRoundingFPMath()) return 0;
504 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
505 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
509 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
515 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
520 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
521 /// returns the newly negated expression.
522 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
523 bool LegalOperations, unsigned Depth = 0) {
524 // fneg is removable even if it has multiple uses.
525 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
527 // Don't allow anything with multiple uses.
528 assert(Op.hasOneUse() && "Unknown reuse!");
530 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
531 switch (Op.getOpcode()) {
532 default: llvm_unreachable("Unknown code");
533 case ISD::ConstantFP: {
534 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
536 return DAG.getConstantFP(V, Op.getValueType());
539 // FIXME: determine better conditions for this xform.
540 assert(DAG.getTarget().Options.UnsafeFPMath);
542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
544 DAG.getTargetLoweringInfo(),
545 &DAG.getTarget().Options, Depth+1))
546 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
547 GetNegatedExpression(Op.getOperand(0), DAG,
548 LegalOperations, Depth+1),
550 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
551 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
552 GetNegatedExpression(Op.getOperand(1), DAG,
553 LegalOperations, Depth+1),
556 // We can't turn -(A-B) into B-A when we honor signed zeros.
557 assert(DAG.getTarget().Options.UnsafeFPMath);
559 // fold (fneg (fsub 0, B)) -> B
560 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
561 if (N0CFP->getValueAPF().isZero())
562 return Op.getOperand(1);
564 // fold (fneg (fsub A, B)) -> (fsub B, A)
565 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
566 Op.getOperand(1), Op.getOperand(0));
570 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
572 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
573 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
574 DAG.getTargetLoweringInfo(),
575 &DAG.getTarget().Options, Depth+1))
576 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
577 GetNegatedExpression(Op.getOperand(0), DAG,
578 LegalOperations, Depth+1),
581 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
582 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(1), DAG,
585 LegalOperations, Depth+1));
589 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
590 GetNegatedExpression(Op.getOperand(0), DAG,
591 LegalOperations, Depth+1));
593 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
594 GetNegatedExpression(Op.getOperand(0), DAG,
595 LegalOperations, Depth+1),
601 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
602 // that selects between the values 1 and 0, making it equivalent to a setcc.
603 // Also, set the incoming LHS, RHS, and CC references to the appropriate
604 // nodes based on the type of node we are checking. This simplifies life a
605 // bit for the callers.
606 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
608 if (N.getOpcode() == ISD::SETCC) {
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(2);
614 if (N.getOpcode() == ISD::SELECT_CC &&
615 N.getOperand(2).getOpcode() == ISD::Constant &&
616 N.getOperand(3).getOpcode() == ISD::Constant &&
617 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
618 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
619 LHS = N.getOperand(0);
620 RHS = N.getOperand(1);
621 CC = N.getOperand(4);
627 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
628 // one use. If this is true, it allows the users to invert the operation for
629 // free when it is profitable to do so.
630 static bool isOneUseSetCC(SDValue N) {
632 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
637 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
638 /// elements are all the same constant or undefined.
639 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
640 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
645 unsigned SplatBitSize;
647 EVT EltVT = N->getValueType(0).getVectorElementType();
648 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
650 EltVT.getSizeInBits() >= SplatBitSize);
653 // \brief Returns the SDNode if it is a constant BuildVector or constant.
654 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
655 if (isa<ConstantSDNode>(N))
657 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
658 if(BV && BV->isConstant())
663 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
665 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
666 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
669 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
670 return BV->isConstantSplat();
675 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
676 SDValue N0, SDValue N1) {
677 EVT VT = N0.getValueType();
678 if (N0.getOpcode() == Opc) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
680 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
681 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
682 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
683 if (!OpNode.getNode())
685 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
687 if (N0.hasOneUse()) {
688 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
690 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
691 if (!OpNode.getNode())
693 AddToWorkList(OpNode.getNode());
694 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
699 if (N1.getOpcode() == Opc) {
700 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
701 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
702 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
703 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
704 if (!OpNode.getNode())
706 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
708 if (N1.hasOneUse()) {
709 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
711 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
712 if (!OpNode.getNode())
714 AddToWorkList(OpNode.getNode());
715 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
723 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
725 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
727 DEBUG(dbgs() << "\nReplacing.1 ";
729 dbgs() << "\nWith: ";
730 To[0].getNode()->dump(&DAG);
731 dbgs() << " and " << NumTo-1 << " other values\n";
732 for (unsigned i = 0, e = NumTo; i != e; ++i)
733 assert((!To[i].getNode() ||
734 N->getValueType(i) == To[i].getValueType()) &&
735 "Cannot combine value to value of different type!"));
736 WorkListRemover DeadNodes(*this);
737 DAG.ReplaceAllUsesWith(N, To);
739 // Push the new nodes and any users onto the worklist
740 for (unsigned i = 0, e = NumTo; i != e; ++i) {
741 if (To[i].getNode()) {
742 AddToWorkList(To[i].getNode());
743 AddUsersToWorkList(To[i].getNode());
748 // Finally, if the node is now dead, remove it from the graph. The node
749 // may not be dead if the replacement process recursively simplified to
750 // something else needing this node.
751 if (N->use_empty()) {
752 // Nodes can be reintroduced into the worklist. Make sure we do not
753 // process a node that has been replaced.
754 removeFromWorkList(N);
756 // Finally, since the node is now dead, remove it from the graph.
759 return SDValue(N, 0);
763 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
764 // Replace all uses. If any nodes become isomorphic to other nodes and
765 // are deleted, make sure to remove them from our worklist.
766 WorkListRemover DeadNodes(*this);
767 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
769 // Push the new node and any (possibly new) users onto the worklist.
770 AddToWorkList(TLO.New.getNode());
771 AddUsersToWorkList(TLO.New.getNode());
773 // Finally, if the node is now dead, remove it from the graph. The node
774 // may not be dead if the replacement process recursively simplified to
775 // something else needing this node.
776 if (TLO.Old.getNode()->use_empty()) {
777 removeFromWorkList(TLO.Old.getNode());
779 // If the operands of this node are only used by the node, they will now
780 // be dead. Make sure to visit them first to delete dead nodes early.
781 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
782 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
783 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
785 DAG.DeleteNode(TLO.Old.getNode());
789 /// SimplifyDemandedBits - Check the specified integer node value to see if
790 /// it can be simplified or if things it uses can be simplified by bit
791 /// propagation. If so, return true.
792 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
793 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
794 APInt KnownZero, KnownOne;
795 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
799 AddToWorkList(Op.getNode());
801 // Replace the old value with the new one.
803 DEBUG(dbgs() << "\nReplacing.2 ";
804 TLO.Old.getNode()->dump(&DAG);
805 dbgs() << "\nWith: ";
806 TLO.New.getNode()->dump(&DAG);
809 CommitTargetLoweringOpt(TLO);
813 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
815 EVT VT = Load->getValueType(0);
816 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
818 DEBUG(dbgs() << "\nReplacing.9 ";
820 dbgs() << "\nWith: ";
821 Trunc.getNode()->dump(&DAG);
823 WorkListRemover DeadNodes(*this);
824 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
825 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
826 removeFromWorkList(Load);
827 DAG.DeleteNode(Load);
828 AddToWorkList(Trunc.getNode());
831 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
834 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
835 EVT MemVT = LD->getMemoryVT();
836 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
837 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
839 : LD->getExtensionType();
841 return DAG.getExtLoad(ExtType, dl, PVT,
842 LD->getChain(), LD->getBasePtr(),
843 MemVT, LD->getMemOperand());
846 unsigned Opc = Op.getOpcode();
849 case ISD::AssertSext:
850 return DAG.getNode(ISD::AssertSext, dl, PVT,
851 SExtPromoteOperand(Op.getOperand(0), PVT),
853 case ISD::AssertZext:
854 return DAG.getNode(ISD::AssertZext, dl, PVT,
855 ZExtPromoteOperand(Op.getOperand(0), PVT),
857 case ISD::Constant: {
859 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
860 return DAG.getNode(ExtOpc, dl, PVT, Op);
864 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
866 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
869 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
870 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
872 EVT OldVT = Op.getValueType();
874 bool Replace = false;
875 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
876 if (NewOp.getNode() == 0)
878 AddToWorkList(NewOp.getNode());
881 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
883 DAG.getValueType(OldVT));
886 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
887 EVT OldVT = Op.getValueType();
889 bool Replace = false;
890 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
891 if (NewOp.getNode() == 0)
893 AddToWorkList(NewOp.getNode());
896 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
897 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
900 /// PromoteIntBinOp - Promote the specified integer binary operation if the
901 /// target indicates it is beneficial. e.g. On x86, it's usually better to
902 /// promote i16 operations to i32 since i16 instructions are longer.
903 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
904 if (!LegalOperations)
907 EVT VT = Op.getValueType();
908 if (VT.isVector() || !VT.isInteger())
911 // If operation type is 'undesirable', e.g. i16 on x86, consider
913 unsigned Opc = Op.getOpcode();
914 if (TLI.isTypeDesirableForOp(Opc, VT))
918 // Consult target whether it is a good idea to promote this operation and
919 // what's the right type to promote it to.
920 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
921 assert(PVT != VT && "Don't know what type to promote to!");
923 bool Replace0 = false;
924 SDValue N0 = Op.getOperand(0);
925 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926 if (NN0.getNode() == 0)
929 bool Replace1 = false;
930 SDValue N1 = Op.getOperand(1);
935 NN1 = PromoteOperand(N1, PVT, Replace1);
936 if (NN1.getNode() == 0)
940 AddToWorkList(NN0.getNode());
942 AddToWorkList(NN1.getNode());
945 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
947 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
949 DEBUG(dbgs() << "\nPromoting ";
950 Op.getNode()->dump(&DAG));
952 return DAG.getNode(ISD::TRUNCATE, dl, VT,
953 DAG.getNode(Opc, dl, PVT, NN0, NN1));
958 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
959 /// target indicates it is beneficial. e.g. On x86, it's usually better to
960 /// promote i16 operations to i32 since i16 instructions are longer.
961 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
962 if (!LegalOperations)
965 EVT VT = Op.getValueType();
966 if (VT.isVector() || !VT.isInteger())
969 // If operation type is 'undesirable', e.g. i16 on x86, consider
971 unsigned Opc = Op.getOpcode();
972 if (TLI.isTypeDesirableForOp(Opc, VT))
976 // Consult target whether it is a good idea to promote this operation and
977 // what's the right type to promote it to.
978 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979 assert(PVT != VT && "Don't know what type to promote to!");
981 bool Replace = false;
982 SDValue N0 = Op.getOperand(0);
984 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
985 else if (Opc == ISD::SRL)
986 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
988 N0 = PromoteOperand(N0, PVT, Replace);
989 if (N0.getNode() == 0)
992 AddToWorkList(N0.getNode());
994 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
996 DEBUG(dbgs() << "\nPromoting ";
997 Op.getNode()->dump(&DAG));
999 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1000 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1005 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1006 if (!LegalOperations)
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1024 // fold (aext (aext x)) -> (aext x)
1025 // fold (aext (zext x)) -> (zext x)
1026 // fold (aext (sext x)) -> (sext x)
1027 DEBUG(dbgs() << "\nPromoting ";
1028 Op.getNode()->dump(&DAG));
1029 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1034 bool DAGCombiner::PromoteLoad(SDValue Op) {
1035 if (!LegalOperations)
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1055 SDNode *N = Op.getNode();
1056 LoadSDNode *LD = cast<LoadSDNode>(N);
1057 EVT MemVT = LD->getMemoryVT();
1058 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1059 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1061 : LD->getExtensionType();
1062 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1063 LD->getChain(), LD->getBasePtr(),
1064 MemVT, LD->getMemOperand());
1065 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1067 DEBUG(dbgs() << "\nPromoting ";
1070 Result.getNode()->dump(&DAG);
1072 WorkListRemover DeadNodes(*this);
1073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1075 removeFromWorkList(N);
1077 AddToWorkList(Result.getNode());
1084 //===----------------------------------------------------------------------===//
1085 // Main DAG Combiner implementation
1086 //===----------------------------------------------------------------------===//
1088 void DAGCombiner::Run(CombineLevel AtLevel) {
1089 // set the instance variables, so that the various visit routines may use it.
1091 LegalOperations = Level >= AfterLegalizeVectorOps;
1092 LegalTypes = Level >= AfterLegalizeTypes;
1094 // Add all the dag nodes to the worklist.
1095 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1096 E = DAG.allnodes_end(); I != E; ++I)
1099 // Create a dummy node (which is not added to allnodes), that adds a reference
1100 // to the root node, preventing it from being deleted, and tracking any
1101 // changes of the root.
1102 HandleSDNode Dummy(DAG.getRoot());
1104 // The root of the dag may dangle to deleted nodes until the dag combiner is
1105 // done. Set it to null to avoid confusion.
1106 DAG.setRoot(SDValue());
1108 // while the worklist isn't empty, find a node and
1109 // try and combine it.
1110 while (!WorkListContents.empty()) {
1112 // The WorkListOrder holds the SDNodes in order, but it may contain
1114 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1115 // worklist *should* contain, and check the node we want to visit is should
1116 // actually be visited.
1118 N = WorkListOrder.pop_back_val();
1119 } while (!WorkListContents.erase(N));
1121 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1122 // N is deleted from the DAG, since they too may now be dead or may have a
1123 // reduced number of uses, allowing other xforms.
1124 if (N->use_empty() && N != &Dummy) {
1125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1126 AddToWorkList(N->getOperand(i).getNode());
1132 SDValue RV = combine(N);
1134 if (RV.getNode() == 0)
1139 // If we get back the same node we passed in, rather than a new node or
1140 // zero, we know that the node must have defined multiple values and
1141 // CombineTo was used. Since CombineTo takes care of the worklist
1142 // mechanics for us, we have no work to do in this case.
1143 if (RV.getNode() == N)
1146 assert(N->getOpcode() != ISD::DELETED_NODE &&
1147 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1148 "Node was deleted but visit returned new node!");
1150 DEBUG(dbgs() << "\nReplacing.3 ";
1152 dbgs() << "\nWith: ";
1153 RV.getNode()->dump(&DAG);
1156 // Transfer debug value.
1157 DAG.TransferDbgValues(SDValue(N, 0), RV);
1158 WorkListRemover DeadNodes(*this);
1159 if (N->getNumValues() == RV.getNode()->getNumValues())
1160 DAG.ReplaceAllUsesWith(N, RV.getNode());
1162 assert(N->getValueType(0) == RV.getValueType() &&
1163 N->getNumValues() == 1 && "Type mismatch");
1165 DAG.ReplaceAllUsesWith(N, &OpV);
1168 // Push the new node and any users onto the worklist
1169 AddToWorkList(RV.getNode());
1170 AddUsersToWorkList(RV.getNode());
1172 // Add any uses of the old node to the worklist in case this node is the
1173 // last one that uses them. They may become dead after this node is
1175 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1176 AddToWorkList(N->getOperand(i).getNode());
1178 // Finally, if the node is now dead, remove it from the graph. The node
1179 // may not be dead if the replacement process recursively simplified to
1180 // something else needing this node.
1181 if (N->use_empty()) {
1182 // Nodes can be reintroduced into the worklist. Make sure we do not
1183 // process a node that has been replaced.
1184 removeFromWorkList(N);
1186 // Finally, since the node is now dead, remove it from the graph.
1191 // If the root changed (e.g. it was a dead load, update the root).
1192 DAG.setRoot(Dummy.getValue());
1193 DAG.RemoveDeadNodes();
1196 SDValue DAGCombiner::visit(SDNode *N) {
1197 switch (N->getOpcode()) {
1199 case ISD::TokenFactor: return visitTokenFactor(N);
1200 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1201 case ISD::ADD: return visitADD(N);
1202 case ISD::SUB: return visitSUB(N);
1203 case ISD::ADDC: return visitADDC(N);
1204 case ISD::SUBC: return visitSUBC(N);
1205 case ISD::ADDE: return visitADDE(N);
1206 case ISD::SUBE: return visitSUBE(N);
1207 case ISD::MUL: return visitMUL(N);
1208 case ISD::SDIV: return visitSDIV(N);
1209 case ISD::UDIV: return visitUDIV(N);
1210 case ISD::SREM: return visitSREM(N);
1211 case ISD::UREM: return visitUREM(N);
1212 case ISD::MULHU: return visitMULHU(N);
1213 case ISD::MULHS: return visitMULHS(N);
1214 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1215 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1216 case ISD::SMULO: return visitSMULO(N);
1217 case ISD::UMULO: return visitUMULO(N);
1218 case ISD::SDIVREM: return visitSDIVREM(N);
1219 case ISD::UDIVREM: return visitUDIVREM(N);
1220 case ISD::AND: return visitAND(N);
1221 case ISD::OR: return visitOR(N);
1222 case ISD::XOR: return visitXOR(N);
1223 case ISD::SHL: return visitSHL(N);
1224 case ISD::SRA: return visitSRA(N);
1225 case ISD::SRL: return visitSRL(N);
1227 case ISD::ROTL: return visitRotate(N);
1228 case ISD::CTLZ: return visitCTLZ(N);
1229 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1230 case ISD::CTTZ: return visitCTTZ(N);
1231 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1232 case ISD::CTPOP: return visitCTPOP(N);
1233 case ISD::SELECT: return visitSELECT(N);
1234 case ISD::VSELECT: return visitVSELECT(N);
1235 case ISD::SELECT_CC: return visitSELECT_CC(N);
1236 case ISD::SETCC: return visitSETCC(N);
1237 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1238 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1239 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1240 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1241 case ISD::TRUNCATE: return visitTRUNCATE(N);
1242 case ISD::BITCAST: return visitBITCAST(N);
1243 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1244 case ISD::FADD: return visitFADD(N);
1245 case ISD::FSUB: return visitFSUB(N);
1246 case ISD::FMUL: return visitFMUL(N);
1247 case ISD::FMA: return visitFMA(N);
1248 case ISD::FDIV: return visitFDIV(N);
1249 case ISD::FREM: return visitFREM(N);
1250 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1251 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1252 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1253 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1254 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1255 case ISD::FP_ROUND: return visitFP_ROUND(N);
1256 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1257 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1258 case ISD::FNEG: return visitFNEG(N);
1259 case ISD::FABS: return visitFABS(N);
1260 case ISD::FFLOOR: return visitFFLOOR(N);
1261 case ISD::FCEIL: return visitFCEIL(N);
1262 case ISD::FTRUNC: return visitFTRUNC(N);
1263 case ISD::BRCOND: return visitBRCOND(N);
1264 case ISD::BR_CC: return visitBR_CC(N);
1265 case ISD::LOAD: return visitLOAD(N);
1266 case ISD::STORE: return visitSTORE(N);
1267 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1268 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1269 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1270 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1271 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1272 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1273 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1278 SDValue DAGCombiner::combine(SDNode *N) {
1279 SDValue RV = visit(N);
1281 // If nothing happened, try a target-specific DAG combine.
1282 if (RV.getNode() == 0) {
1283 assert(N->getOpcode() != ISD::DELETED_NODE &&
1284 "Node was deleted but visit returned NULL!");
1286 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1287 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1289 // Expose the DAG combiner to the target combiner impls.
1290 TargetLowering::DAGCombinerInfo
1291 DagCombineInfo(DAG, Level, false, this);
1293 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1297 // If nothing happened still, try promoting the operation.
1298 if (RV.getNode() == 0) {
1299 switch (N->getOpcode()) {
1307 RV = PromoteIntBinOp(SDValue(N, 0));
1312 RV = PromoteIntShiftOp(SDValue(N, 0));
1314 case ISD::SIGN_EXTEND:
1315 case ISD::ZERO_EXTEND:
1316 case ISD::ANY_EXTEND:
1317 RV = PromoteExtend(SDValue(N, 0));
1320 if (PromoteLoad(SDValue(N, 0)))
1326 // If N is a commutative binary node, try commuting it to enable more
1328 if (RV.getNode() == 0 &&
1329 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1330 N->getNumValues() == 1) {
1331 SDValue N0 = N->getOperand(0);
1332 SDValue N1 = N->getOperand(1);
1334 // Constant operands are canonicalized to RHS.
1335 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1336 SDValue Ops[] = { N1, N0 };
1337 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1340 return SDValue(CSENode, 0);
1347 /// getInputChainForNode - Given a node, return its input chain if it has one,
1348 /// otherwise return a null sd operand.
1349 static SDValue getInputChainForNode(SDNode *N) {
1350 if (unsigned NumOps = N->getNumOperands()) {
1351 if (N->getOperand(0).getValueType() == MVT::Other)
1352 return N->getOperand(0);
1353 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1354 return N->getOperand(NumOps-1);
1355 for (unsigned i = 1; i < NumOps-1; ++i)
1356 if (N->getOperand(i).getValueType() == MVT::Other)
1357 return N->getOperand(i);
1362 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1363 // If N has two operands, where one has an input chain equal to the other,
1364 // the 'other' chain is redundant.
1365 if (N->getNumOperands() == 2) {
1366 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1367 return N->getOperand(0);
1368 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1369 return N->getOperand(1);
1372 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1373 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1374 SmallPtrSet<SDNode*, 16> SeenOps;
1375 bool Changed = false; // If we should replace this token factor.
1377 // Start out with this token factor.
1380 // Iterate through token factors. The TFs grows when new token factors are
1382 for (unsigned i = 0; i < TFs.size(); ++i) {
1383 SDNode *TF = TFs[i];
1385 // Check each of the operands.
1386 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1387 SDValue Op = TF->getOperand(i);
1389 switch (Op.getOpcode()) {
1390 case ISD::EntryToken:
1391 // Entry tokens don't need to be added to the list. They are
1396 case ISD::TokenFactor:
1397 if (Op.hasOneUse() &&
1398 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1399 // Queue up for processing.
1400 TFs.push_back(Op.getNode());
1401 // Clean up in case the token factor is removed.
1402 AddToWorkList(Op.getNode());
1409 // Only add if it isn't already in the list.
1410 if (SeenOps.insert(Op.getNode()))
1421 // If we've change things around then replace token factor.
1424 // The entry token is the only possible outcome.
1425 Result = DAG.getEntryNode();
1427 // New and improved token factor.
1428 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1429 MVT::Other, &Ops[0], Ops.size());
1432 // Don't add users to work list.
1433 return CombineTo(N, Result, false);
1439 /// MERGE_VALUES can always be eliminated.
1440 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1441 WorkListRemover DeadNodes(*this);
1442 // Replacing results may cause a different MERGE_VALUES to suddenly
1443 // be CSE'd with N, and carry its uses with it. Iterate until no
1444 // uses remain, to ensure that the node can be safely deleted.
1445 // First add the users of this node to the work list so that they
1446 // can be tried again once they have new operands.
1447 AddUsersToWorkList(N);
1449 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1451 } while (!N->use_empty());
1452 removeFromWorkList(N);
1454 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1458 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1459 SelectionDAG &DAG) {
1460 EVT VT = N0.getValueType();
1461 SDValue N00 = N0.getOperand(0);
1462 SDValue N01 = N0.getOperand(1);
1463 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1465 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1466 isa<ConstantSDNode>(N00.getOperand(1))) {
1467 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1468 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1469 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1470 N00.getOperand(0), N01),
1471 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1472 N00.getOperand(1), N01));
1473 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1479 SDValue DAGCombiner::visitADD(SDNode *N) {
1480 SDValue N0 = N->getOperand(0);
1481 SDValue N1 = N->getOperand(1);
1482 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1483 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1484 EVT VT = N0.getValueType();
1487 if (VT.isVector()) {
1488 SDValue FoldedVOp = SimplifyVBinOp(N);
1489 if (FoldedVOp.getNode()) return FoldedVOp;
1491 // fold (add x, 0) -> x, vector edition
1492 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1494 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1498 // fold (add x, undef) -> undef
1499 if (N0.getOpcode() == ISD::UNDEF)
1501 if (N1.getOpcode() == ISD::UNDEF)
1503 // fold (add c1, c2) -> c1+c2
1505 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1506 // canonicalize constant to RHS
1508 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1509 // fold (add x, 0) -> x
1510 if (N1C && N1C->isNullValue())
1512 // fold (add Sym, c) -> Sym+c
1513 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1514 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1515 GA->getOpcode() == ISD::GlobalAddress)
1516 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1518 (uint64_t)N1C->getSExtValue());
1519 // fold ((c1-A)+c2) -> (c1+c2)-A
1520 if (N1C && N0.getOpcode() == ISD::SUB)
1521 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1522 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1523 DAG.getConstant(N1C->getAPIntValue()+
1524 N0C->getAPIntValue(), VT),
1527 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1528 if (RADD.getNode() != 0)
1530 // fold ((0-A) + B) -> B-A
1531 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1532 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1534 // fold (A + (0-B)) -> A-B
1535 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1536 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1537 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1538 // fold (A+(B-A)) -> B
1539 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1540 return N1.getOperand(0);
1541 // fold ((B-A)+A) -> B
1542 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1543 return N0.getOperand(0);
1544 // fold (A+(B-(A+C))) to (B-C)
1545 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1546 N0 == N1.getOperand(1).getOperand(0))
1547 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1548 N1.getOperand(1).getOperand(1));
1549 // fold (A+(B-(C+A))) to (B-C)
1550 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1551 N0 == N1.getOperand(1).getOperand(1))
1552 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1553 N1.getOperand(1).getOperand(0));
1554 // fold (A+((B-A)+or-C)) to (B+or-C)
1555 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1556 N1.getOperand(0).getOpcode() == ISD::SUB &&
1557 N0 == N1.getOperand(0).getOperand(1))
1558 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1559 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1561 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1562 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1563 SDValue N00 = N0.getOperand(0);
1564 SDValue N01 = N0.getOperand(1);
1565 SDValue N10 = N1.getOperand(0);
1566 SDValue N11 = N1.getOperand(1);
1568 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1571 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1574 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1575 return SDValue(N, 0);
1577 // fold (a+b) -> (a|b) iff a and b share no bits.
1578 if (VT.isInteger() && !VT.isVector()) {
1579 APInt LHSZero, LHSOne;
1580 APInt RHSZero, RHSOne;
1581 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1583 if (LHSZero.getBoolValue()) {
1584 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1586 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1587 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1588 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1589 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1590 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1595 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1596 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1597 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1598 if (Result.getNode()) return Result;
1600 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1601 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1602 if (Result.getNode()) return Result;
1605 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1606 if (N1.getOpcode() == ISD::SHL &&
1607 N1.getOperand(0).getOpcode() == ISD::SUB)
1608 if (ConstantSDNode *C =
1609 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1610 if (C->getAPIntValue() == 0)
1611 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1612 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1613 N1.getOperand(0).getOperand(1),
1615 if (N0.getOpcode() == ISD::SHL &&
1616 N0.getOperand(0).getOpcode() == ISD::SUB)
1617 if (ConstantSDNode *C =
1618 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1619 if (C->getAPIntValue() == 0)
1620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1621 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1622 N0.getOperand(0).getOperand(1),
1625 if (N1.getOpcode() == ISD::AND) {
1626 SDValue AndOp0 = N1.getOperand(0);
1627 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1628 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1629 unsigned DestBits = VT.getScalarType().getSizeInBits();
1631 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1632 // and similar xforms where the inner op is either ~0 or 0.
1633 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1635 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1639 // add (sext i1), X -> sub X, (zext i1)
1640 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1641 N0.getOperand(0).getValueType() == MVT::i1 &&
1642 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1644 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1645 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1651 SDValue DAGCombiner::visitADDC(SDNode *N) {
1652 SDValue N0 = N->getOperand(0);
1653 SDValue N1 = N->getOperand(1);
1654 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1656 EVT VT = N0.getValueType();
1658 // If the flag result is dead, turn this into an ADD.
1659 if (!N->hasAnyUseOfValue(1))
1660 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1661 DAG.getNode(ISD::CARRY_FALSE,
1662 SDLoc(N), MVT::Glue));
1664 // canonicalize constant to RHS.
1666 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1668 // fold (addc x, 0) -> x + no carry out
1669 if (N1C && N1C->isNullValue())
1670 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1671 SDLoc(N), MVT::Glue));
1673 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1674 APInt LHSZero, LHSOne;
1675 APInt RHSZero, RHSOne;
1676 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1678 if (LHSZero.getBoolValue()) {
1679 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1681 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1682 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1683 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1684 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1685 DAG.getNode(ISD::CARRY_FALSE,
1686 SDLoc(N), MVT::Glue));
1692 SDValue DAGCombiner::visitADDE(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
1695 SDValue CarryIn = N->getOperand(2);
1696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1699 // canonicalize constant to RHS
1701 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1704 // fold (adde x, y, false) -> (addc x, y)
1705 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1706 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1711 // Since it may not be valid to emit a fold to zero for vector initializers
1712 // check if we can before folding.
1713 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1715 bool LegalOperations, bool LegalTypes) {
1717 return DAG.getConstant(0, VT);
1718 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1719 return DAG.getConstant(0, VT);
1723 SDValue DAGCombiner::visitSUB(SDNode *N) {
1724 SDValue N0 = N->getOperand(0);
1725 SDValue N1 = N->getOperand(1);
1726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1728 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1729 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1730 EVT VT = N0.getValueType();
1733 if (VT.isVector()) {
1734 SDValue FoldedVOp = SimplifyVBinOp(N);
1735 if (FoldedVOp.getNode()) return FoldedVOp;
1737 // fold (sub x, 0) -> x, vector edition
1738 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1742 // fold (sub x, x) -> 0
1743 // FIXME: Refactor this and xor and other similar operations together.
1745 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1746 // fold (sub c1, c2) -> c1-c2
1748 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1749 // fold (sub x, c) -> (add x, -c)
1751 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1752 DAG.getConstant(-N1C->getAPIntValue(), VT));
1753 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1754 if (N0C && N0C->isAllOnesValue())
1755 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1756 // fold A-(A-B) -> B
1757 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1758 return N1.getOperand(1);
1759 // fold (A+B)-A -> B
1760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1761 return N0.getOperand(1);
1762 // fold (A+B)-B -> A
1763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1764 return N0.getOperand(0);
1765 // fold C2-(A+C1) -> (C2-C1)-A
1766 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1767 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1769 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1772 // fold ((A+(B+or-C))-B) -> A+or-C
1773 if (N0.getOpcode() == ISD::ADD &&
1774 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1775 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1776 N0.getOperand(1).getOperand(0) == N1)
1777 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1778 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1779 // fold ((A+(C+B))-B) -> A+C
1780 if (N0.getOpcode() == ISD::ADD &&
1781 N0.getOperand(1).getOpcode() == ISD::ADD &&
1782 N0.getOperand(1).getOperand(1) == N1)
1783 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1784 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1785 // fold ((A-(B-C))-C) -> A-B
1786 if (N0.getOpcode() == ISD::SUB &&
1787 N0.getOperand(1).getOpcode() == ISD::SUB &&
1788 N0.getOperand(1).getOperand(1) == N1)
1789 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1790 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1792 // If either operand of a sub is undef, the result is undef
1793 if (N0.getOpcode() == ISD::UNDEF)
1795 if (N1.getOpcode() == ISD::UNDEF)
1798 // If the relocation model supports it, consider symbol offsets.
1799 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1800 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1801 // fold (sub Sym, c) -> Sym-c
1802 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1803 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1805 (uint64_t)N1C->getSExtValue());
1806 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1807 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1808 if (GA->getGlobal() == GB->getGlobal())
1809 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1816 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1817 SDValue N0 = N->getOperand(0);
1818 SDValue N1 = N->getOperand(1);
1819 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1820 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1821 EVT VT = N0.getValueType();
1823 // If the flag result is dead, turn this into an SUB.
1824 if (!N->hasAnyUseOfValue(1))
1825 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1826 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829 // fold (subc x, x) -> 0 + no borrow
1831 return CombineTo(N, DAG.getConstant(0, VT),
1832 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835 // fold (subc x, 0) -> x + no borrow
1836 if (N1C && N1C->isNullValue())
1837 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1841 if (N0C && N0C->isAllOnesValue())
1842 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1843 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1849 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1850 SDValue N0 = N->getOperand(0);
1851 SDValue N1 = N->getOperand(1);
1852 SDValue CarryIn = N->getOperand(2);
1854 // fold (sube x, y, false) -> (subc x, y)
1855 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1856 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1861 SDValue DAGCombiner::visitMUL(SDNode *N) {
1862 SDValue N0 = N->getOperand(0);
1863 SDValue N1 = N->getOperand(1);
1864 EVT VT = N0.getValueType();
1866 // fold (mul x, undef) -> 0
1867 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1868 return DAG.getConstant(0, VT);
1870 bool N0IsConst = false;
1871 bool N1IsConst = false;
1872 APInt ConstValue0, ConstValue1;
1874 if (VT.isVector()) {
1875 SDValue FoldedVOp = SimplifyVBinOp(N);
1876 if (FoldedVOp.getNode()) return FoldedVOp;
1878 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1879 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1881 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1882 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1884 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1885 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1889 // fold (mul c1, c2) -> c1*c2
1890 if (N0IsConst && N1IsConst)
1891 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1893 // canonicalize constant to RHS
1894 if (N0IsConst && !N1IsConst)
1895 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1896 // fold (mul x, 0) -> 0
1897 if (N1IsConst && ConstValue1 == 0)
1899 // We require a splat of the entire scalar bit width for non-contiguous
1902 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1903 // fold (mul x, 1) -> x
1904 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1906 // fold (mul x, -1) -> 0-x
1907 if (N1IsConst && ConstValue1.isAllOnesValue())
1908 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1909 DAG.getConstant(0, VT), N0);
1910 // fold (mul x, (1 << c)) -> x << c
1911 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1912 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1913 DAG.getConstant(ConstValue1.logBase2(),
1914 getShiftAmountTy(N0.getValueType())));
1915 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1916 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1917 unsigned Log2Val = (-ConstValue1).logBase2();
1918 // FIXME: If the input is something that is easily negated (e.g. a
1919 // single-use add), we should put the negate there.
1920 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1921 DAG.getConstant(0, VT),
1922 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1923 DAG.getConstant(Log2Val,
1924 getShiftAmountTy(N0.getValueType()))));
1928 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1929 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1)))) {
1932 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1933 N1, N0.getOperand(1));
1934 AddToWorkList(C3.getNode());
1935 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1936 N0.getOperand(0), C3);
1939 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1942 SDValue Sh(0,0), Y(0,0);
1943 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1944 if (N0.getOpcode() == ISD::SHL &&
1945 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1946 isa<ConstantSDNode>(N0.getOperand(1))) &&
1947 N0.getNode()->hasOneUse()) {
1949 } else if (N1.getOpcode() == ISD::SHL &&
1950 isa<ConstantSDNode>(N1.getOperand(1)) &&
1951 N1.getNode()->hasOneUse()) {
1956 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1957 Sh.getOperand(0), Y);
1958 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1959 Mul, Sh.getOperand(1));
1963 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1964 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1965 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966 isa<ConstantSDNode>(N0.getOperand(1))))
1967 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1968 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1969 N0.getOperand(0), N1),
1970 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1971 N0.getOperand(1), N1));
1974 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1975 if (RMUL.getNode() != 0)
1981 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1982 SDValue N0 = N->getOperand(0);
1983 SDValue N1 = N->getOperand(1);
1984 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1985 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1986 EVT VT = N->getValueType(0);
1989 if (VT.isVector()) {
1990 SDValue FoldedVOp = SimplifyVBinOp(N);
1991 if (FoldedVOp.getNode()) return FoldedVOp;
1994 // fold (sdiv c1, c2) -> c1/c2
1995 if (N0C && N1C && !N1C->isNullValue())
1996 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1997 // fold (sdiv X, 1) -> X
1998 if (N1C && N1C->getAPIntValue() == 1LL)
2000 // fold (sdiv X, -1) -> 0-X
2001 if (N1C && N1C->isAllOnesValue())
2002 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2003 DAG.getConstant(0, VT), N0);
2004 // If we know the sign bits of both operands are zero, strength reduce to a
2005 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2006 if (!VT.isVector()) {
2007 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2008 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2011 // fold (sdiv X, pow2) -> simple ops after legalize
2012 if (N1C && !N1C->isNullValue() &&
2013 (N1C->getAPIntValue().isPowerOf2() ||
2014 (-N1C->getAPIntValue()).isPowerOf2())) {
2015 // If dividing by powers of two is cheap, then don't perform the following
2017 if (TLI.isPow2DivCheap())
2020 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2022 // Splat the sign bit into the register
2023 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2024 DAG.getConstant(VT.getSizeInBits()-1,
2025 getShiftAmountTy(N0.getValueType())));
2026 AddToWorkList(SGN.getNode());
2028 // Add (N0 < 0) ? abs2 - 1 : 0;
2029 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2030 DAG.getConstant(VT.getSizeInBits() - lg2,
2031 getShiftAmountTy(SGN.getValueType())));
2032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2033 AddToWorkList(SRL.getNode());
2034 AddToWorkList(ADD.getNode()); // Divide by pow2
2035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2038 // If we're dividing by a positive value, we're done. Otherwise, we must
2039 // negate the result.
2040 if (N1C->getAPIntValue().isNonNegative())
2043 AddToWorkList(SRA.getNode());
2044 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2045 DAG.getConstant(0, VT), SRA);
2048 // if integer divide is expensive and we satisfy the requirements, emit an
2049 // alternate sequence.
2050 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2051 SDValue Op = BuildSDIV(N);
2052 if (Op.getNode()) return Op;
2056 if (N0.getOpcode() == ISD::UNDEF)
2057 return DAG.getConstant(0, VT);
2058 // X / undef -> undef
2059 if (N1.getOpcode() == ISD::UNDEF)
2065 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2066 SDValue N0 = N->getOperand(0);
2067 SDValue N1 = N->getOperand(1);
2068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2070 EVT VT = N->getValueType(0);
2073 if (VT.isVector()) {
2074 SDValue FoldedVOp = SimplifyVBinOp(N);
2075 if (FoldedVOp.getNode()) return FoldedVOp;
2078 // fold (udiv c1, c2) -> c1/c2
2079 if (N0C && N1C && !N1C->isNullValue())
2080 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2081 // fold (udiv x, (1 << c)) -> x >>u c
2082 if (N1C && N1C->getAPIntValue().isPowerOf2())
2083 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2084 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2085 getShiftAmountTy(N0.getValueType())));
2086 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2087 if (N1.getOpcode() == ISD::SHL) {
2088 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2089 if (SHC->getAPIntValue().isPowerOf2()) {
2090 EVT ADDVT = N1.getOperand(1).getValueType();
2091 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2093 DAG.getConstant(SHC->getAPIntValue()
2096 AddToWorkList(Add.getNode());
2097 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2101 // fold (udiv x, c) -> alternate
2102 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2103 SDValue Op = BuildUDIV(N);
2104 if (Op.getNode()) return Op;
2108 if (N0.getOpcode() == ISD::UNDEF)
2109 return DAG.getConstant(0, VT);
2110 // X / undef -> undef
2111 if (N1.getOpcode() == ISD::UNDEF)
2117 SDValue DAGCombiner::visitSREM(SDNode *N) {
2118 SDValue N0 = N->getOperand(0);
2119 SDValue N1 = N->getOperand(1);
2120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2122 EVT VT = N->getValueType(0);
2124 // fold (srem c1, c2) -> c1%c2
2125 if (N0C && N1C && !N1C->isNullValue())
2126 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2127 // If we know the sign bits of both operands are zero, strength reduce to a
2128 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2129 if (!VT.isVector()) {
2130 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2131 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2134 // If X/C can be simplified by the division-by-constant logic, lower
2135 // X%C to the equivalent of X-X/C*C.
2136 if (N1C && !N1C->isNullValue()) {
2137 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2138 AddToWorkList(Div.getNode());
2139 SDValue OptimizedDiv = combine(Div.getNode());
2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2144 AddToWorkList(Mul.getNode());
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X % undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2159 SDValue DAGCombiner::visitUREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
2162 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2164 EVT VT = N->getValueType(0);
2166 // fold (urem c1, c2) -> c1%c2
2167 if (N0C && N1C && !N1C->isNullValue())
2168 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2169 // fold (urem x, pow2) -> (and x, pow2-1)
2170 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2171 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2172 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2173 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2174 if (N1.getOpcode() == ISD::SHL) {
2175 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2176 if (SHC->getAPIntValue().isPowerOf2()) {
2178 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2179 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2181 AddToWorkList(Add.getNode());
2182 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
2189 if (N1C && !N1C->isNullValue()) {
2190 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2191 AddToWorkList(Div.getNode());
2192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2197 AddToWorkList(Mul.getNode());
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2212 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
2215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2216 EVT VT = N->getValueType(0);
2219 // fold (mulhs x, 0) -> 0
2220 if (N1C && N1C->isNullValue())
2222 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2223 if (N1C && N1C->getAPIntValue() == 1)
2224 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2225 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2226 getShiftAmountTy(N0.getValueType())));
2227 // fold (mulhs x, undef) -> 0
2228 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2229 return DAG.getConstant(0, VT);
2231 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2233 if (VT.isSimple() && !VT.isVector()) {
2234 MVT Simple = VT.getSimpleVT();
2235 unsigned SimpleSize = Simple.getSizeInBits();
2236 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2237 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2238 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2239 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2240 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2241 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2242 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2243 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2250 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2251 SDValue N0 = N->getOperand(0);
2252 SDValue N1 = N->getOperand(1);
2253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2254 EVT VT = N->getValueType(0);
2257 // fold (mulhu x, 0) -> 0
2258 if (N1C && N1C->isNullValue())
2260 // fold (mulhu x, 1) -> 0
2261 if (N1C && N1C->getAPIntValue() == 1)
2262 return DAG.getConstant(0, N0.getValueType());
2263 // fold (mulhu x, undef) -> 0
2264 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2265 return DAG.getConstant(0, VT);
2267 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2269 if (VT.isSimple() && !VT.isVector()) {
2270 MVT Simple = VT.getSimpleVT();
2271 unsigned SimpleSize = Simple.getSizeInBits();
2272 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2273 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2274 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2275 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2276 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2277 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2278 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2279 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2286 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2287 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2288 /// that are being performed. Return true if a simplification was made.
2290 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2292 // If the high half is not needed, just compute the low half.
2293 bool HiExists = N->hasAnyUseOfValue(1);
2295 (!LegalOperations ||
2296 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2297 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2298 N->op_begin(), N->getNumOperands());
2299 return CombineTo(N, Res, Res);
2302 // If the low half is not needed, just compute the high half.
2303 bool LoExists = N->hasAnyUseOfValue(0);
2305 (!LegalOperations ||
2306 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2307 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2308 N->op_begin(), N->getNumOperands());
2309 return CombineTo(N, Res, Res);
2312 // If both halves are used, return as it is.
2313 if (LoExists && HiExists)
2316 // If the two computed results can be simplified separately, separate them.
2318 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2319 N->op_begin(), N->getNumOperands());
2320 AddToWorkList(Lo.getNode());
2321 SDValue LoOpt = combine(Lo.getNode());
2322 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2323 (!LegalOperations ||
2324 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2325 return CombineTo(N, LoOpt, LoOpt);
2329 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2330 N->op_begin(), N->getNumOperands());
2331 AddToWorkList(Hi.getNode());
2332 SDValue HiOpt = combine(Hi.getNode());
2333 if (HiOpt.getNode() && HiOpt != Hi &&
2334 (!LegalOperations ||
2335 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2336 return CombineTo(N, HiOpt, HiOpt);
2342 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2343 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2344 if (Res.getNode()) return Res;
2346 EVT VT = N->getValueType(0);
2349 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2351 if (VT.isSimple() && !VT.isVector()) {
2352 MVT Simple = VT.getSimpleVT();
2353 unsigned SimpleSize = Simple.getSizeInBits();
2354 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2357 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2358 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2359 // Compute the high part as N1.
2360 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2361 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2362 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2363 // Compute the low part as N0.
2364 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2365 return CombineTo(N, Lo, Hi);
2372 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2373 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2374 if (Res.getNode()) return Res;
2376 EVT VT = N->getValueType(0);
2379 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2381 if (VT.isSimple() && !VT.isVector()) {
2382 MVT Simple = VT.getSimpleVT();
2383 unsigned SimpleSize = Simple.getSizeInBits();
2384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2385 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2386 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2387 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2388 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2389 // Compute the high part as N1.
2390 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2391 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2392 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2393 // Compute the low part as N0.
2394 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2395 return CombineTo(N, Lo, Hi);
2402 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2403 // (smulo x, 2) -> (saddo x, x)
2404 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2405 if (C2->getAPIntValue() == 2)
2406 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2407 N->getOperand(0), N->getOperand(0));
2412 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2413 // (umulo x, 2) -> (uaddo x, x)
2414 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2415 if (C2->getAPIntValue() == 2)
2416 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2417 N->getOperand(0), N->getOperand(0));
2422 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2423 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2424 if (Res.getNode()) return Res;
2429 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2430 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2431 if (Res.getNode()) return Res;
2436 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2437 /// two operands of the same opcode, try to simplify it.
2438 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2439 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2440 EVT VT = N0.getValueType();
2441 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2443 // Bail early if none of these transforms apply.
2444 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2446 // For each of OP in AND/OR/XOR:
2447 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2448 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2449 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2450 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2452 // do not sink logical op inside of a vector extend, since it may combine
2454 EVT Op0VT = N0.getOperand(0).getValueType();
2455 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2456 N0.getOpcode() == ISD::SIGN_EXTEND ||
2457 // Avoid infinite looping with PromoteIntBinOp.
2458 (N0.getOpcode() == ISD::ANY_EXTEND &&
2459 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2460 (N0.getOpcode() == ISD::TRUNCATE &&
2461 (!TLI.isZExtFree(VT, Op0VT) ||
2462 !TLI.isTruncateFree(Op0VT, VT)) &&
2463 TLI.isTypeLegal(Op0VT))) &&
2465 Op0VT == N1.getOperand(0).getValueType() &&
2466 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2467 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2468 N0.getOperand(0).getValueType(),
2469 N0.getOperand(0), N1.getOperand(0));
2470 AddToWorkList(ORNode.getNode());
2471 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2474 // For each of OP in SHL/SRL/SRA/AND...
2475 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2476 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2477 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2478 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2479 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2480 N0.getOperand(1) == N1.getOperand(1)) {
2481 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2482 N0.getOperand(0).getValueType(),
2483 N0.getOperand(0), N1.getOperand(0));
2484 AddToWorkList(ORNode.getNode());
2485 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2486 ORNode, N0.getOperand(1));
2489 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2490 // Only perform this optimization after type legalization and before
2491 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2492 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2493 // we don't want to undo this promotion.
2494 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2496 if ((N0.getOpcode() == ISD::BITCAST ||
2497 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2498 Level == AfterLegalizeTypes) {
2499 SDValue In0 = N0.getOperand(0);
2500 SDValue In1 = N1.getOperand(0);
2501 EVT In0Ty = In0.getValueType();
2502 EVT In1Ty = In1.getValueType();
2504 // If both incoming values are integers, and the original types are the
2506 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2507 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2508 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2509 AddToWorkList(Op.getNode());
2514 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2515 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2516 // If both shuffles use the same mask, and both shuffle within a single
2517 // vector, then it is worthwhile to move the swizzle after the operation.
2518 // The type-legalizer generates this pattern when loading illegal
2519 // vector types from memory. In many cases this allows additional shuffle
2521 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2522 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2523 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2524 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2525 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2527 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2528 "Inputs to shuffles are not the same type");
2530 unsigned NumElts = VT.getVectorNumElements();
2532 // Check that both shuffles use the same mask. The masks are known to be of
2533 // the same length because the result vector type is the same.
2534 bool SameMask = true;
2535 for (unsigned i = 0; i != NumElts; ++i) {
2536 int Idx0 = SVN0->getMaskElt(i);
2537 int Idx1 = SVN1->getMaskElt(i);
2545 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2546 N0.getOperand(0), N1.getOperand(0));
2547 AddToWorkList(Op.getNode());
2548 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2549 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2556 SDValue DAGCombiner::visitAND(SDNode *N) {
2557 SDValue N0 = N->getOperand(0);
2558 SDValue N1 = N->getOperand(1);
2559 SDValue LL, LR, RL, RR, CC0, CC1;
2560 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2562 EVT VT = N1.getValueType();
2563 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2566 if (VT.isVector()) {
2567 SDValue FoldedVOp = SimplifyVBinOp(N);
2568 if (FoldedVOp.getNode()) return FoldedVOp;
2570 // fold (and x, 0) -> 0, vector edition
2571 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2573 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2576 // fold (and x, -1) -> x, vector edition
2577 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2579 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2583 // fold (and x, undef) -> 0
2584 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2585 return DAG.getConstant(0, VT);
2586 // fold (and c1, c2) -> c1&c2
2588 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2589 // canonicalize constant to RHS
2591 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2592 // fold (and x, -1) -> x
2593 if (N1C && N1C->isAllOnesValue())
2595 // if (and x, c) is known to be zero, return 0
2596 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2597 APInt::getAllOnesValue(BitWidth)))
2598 return DAG.getConstant(0, VT);
2600 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2601 if (RAND.getNode() != 0)
2603 // fold (and (or x, C), D) -> D if (C & D) == D
2604 if (N1C && N0.getOpcode() == ISD::OR)
2605 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2606 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2608 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2609 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2610 SDValue N0Op0 = N0.getOperand(0);
2611 APInt Mask = ~N1C->getAPIntValue();
2612 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2613 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2614 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2615 N0.getValueType(), N0Op0);
2617 // Replace uses of the AND with uses of the Zero extend node.
2620 // We actually want to replace all uses of the any_extend with the
2621 // zero_extend, to avoid duplicating things. This will later cause this
2622 // AND to be folded.
2623 CombineTo(N0.getNode(), Zext);
2624 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2627 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2628 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2629 // already be zero by virtue of the width of the base type of the load.
2631 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2633 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2634 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2635 N0.getOpcode() == ISD::LOAD) {
2636 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2637 N0 : N0.getOperand(0) );
2639 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2640 // This can be a pure constant or a vector splat, in which case we treat the
2641 // vector as a scalar and use the splat value.
2642 APInt Constant = APInt::getNullValue(1);
2643 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2644 Constant = C->getAPIntValue();
2645 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2646 APInt SplatValue, SplatUndef;
2647 unsigned SplatBitSize;
2649 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2650 SplatBitSize, HasAnyUndefs);
2652 // Undef bits can contribute to a possible optimisation if set, so
2654 SplatValue |= SplatUndef;
2656 // The splat value may be something like "0x00FFFFFF", which means 0 for
2657 // the first vector value and FF for the rest, repeating. We need a mask
2658 // that will apply equally to all members of the vector, so AND all the
2659 // lanes of the constant together.
2660 EVT VT = Vector->getValueType(0);
2661 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2663 // If the splat value has been compressed to a bitlength lower
2664 // than the size of the vector lane, we need to re-expand it to
2666 if (BitWidth > SplatBitSize)
2667 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2668 SplatBitSize < BitWidth;
2669 SplatBitSize = SplatBitSize * 2)
2670 SplatValue |= SplatValue.shl(SplatBitSize);
2672 Constant = APInt::getAllOnesValue(BitWidth);
2673 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2674 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2678 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2679 // actually legal and isn't going to get expanded, else this is a false
2681 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2682 Load->getMemoryVT());
2684 // Resize the constant to the same size as the original memory access before
2685 // extension. If it is still the AllOnesValue then this AND is completely
2688 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2691 switch (Load->getExtensionType()) {
2692 default: B = false; break;
2693 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2695 case ISD::NON_EXTLOAD: B = true; break;
2698 if (B && Constant.isAllOnesValue()) {
2699 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2700 // preserve semantics once we get rid of the AND.
2701 SDValue NewLoad(Load, 0);
2702 if (Load->getExtensionType() == ISD::EXTLOAD) {
2703 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2704 Load->getValueType(0), SDLoc(Load),
2705 Load->getChain(), Load->getBasePtr(),
2706 Load->getOffset(), Load->getMemoryVT(),
2707 Load->getMemOperand());
2708 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2709 if (Load->getNumValues() == 3) {
2710 // PRE/POST_INC loads have 3 values.
2711 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2712 NewLoad.getValue(2) };
2713 CombineTo(Load, To, 3, true);
2715 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2719 // Fold the AND away, taking care not to fold to the old load node if we
2721 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2723 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2726 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2727 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2728 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2729 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2731 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2732 LL.getValueType().isInteger()) {
2733 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2734 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2735 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2736 LR.getValueType(), LL, RL);
2737 AddToWorkList(ORNode.getNode());
2738 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2740 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2741 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2742 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2743 LR.getValueType(), LL, RL);
2744 AddToWorkList(ANDNode.getNode());
2745 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2747 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2748 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2749 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2750 LR.getValueType(), LL, RL);
2751 AddToWorkList(ORNode.getNode());
2752 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2755 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2756 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2757 Op0 == Op1 && LL.getValueType().isInteger() &&
2758 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2759 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2760 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2761 cast<ConstantSDNode>(RR)->isNullValue()))) {
2762 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2763 LL, DAG.getConstant(1, LL.getValueType()));
2764 AddToWorkList(ADDNode.getNode());
2765 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2766 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2768 // canonicalize equivalent to ll == rl
2769 if (LL == RR && LR == RL) {
2770 Op1 = ISD::getSetCCSwappedOperands(Op1);
2773 if (LL == RL && LR == RR) {
2774 bool isInteger = LL.getValueType().isInteger();
2775 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2776 if (Result != ISD::SETCC_INVALID &&
2777 (!LegalOperations ||
2778 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2779 TLI.isOperationLegal(ISD::SETCC,
2780 getSetCCResultType(N0.getSimpleValueType())))))
2781 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2786 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2787 if (N0.getOpcode() == N1.getOpcode()) {
2788 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2789 if (Tmp.getNode()) return Tmp;
2792 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2793 // fold (and (sra)) -> (and (srl)) when possible.
2794 if (!VT.isVector() &&
2795 SimplifyDemandedBits(SDValue(N, 0)))
2796 return SDValue(N, 0);
2798 // fold (zext_inreg (extload x)) -> (zextload x)
2799 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2800 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2801 EVT MemVT = LN0->getMemoryVT();
2802 // If we zero all the possible extended bits, then we can turn this into
2803 // a zextload if we are running before legalize or the operation is legal.
2804 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2805 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2806 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2807 ((!LegalOperations && !LN0->isVolatile()) ||
2808 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2809 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2810 LN0->getChain(), LN0->getBasePtr(),
2811 MemVT, LN0->getMemOperand());
2813 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2814 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2817 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2818 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2821 EVT MemVT = LN0->getMemoryVT();
2822 // If we zero all the possible extended bits, then we can turn this into
2823 // a zextload if we are running before legalize or the operation is legal.
2824 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2825 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2826 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2827 ((!LegalOperations && !LN0->isVolatile()) ||
2828 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2829 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2830 LN0->getChain(), LN0->getBasePtr(),
2831 MemVT, LN0->getMemOperand());
2833 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2838 // fold (and (load x), 255) -> (zextload x, i8)
2839 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2840 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2841 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2842 (N0.getOpcode() == ISD::ANY_EXTEND &&
2843 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2844 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2845 LoadSDNode *LN0 = HasAnyExt
2846 ? cast<LoadSDNode>(N0.getOperand(0))
2847 : cast<LoadSDNode>(N0);
2848 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2849 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2850 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2851 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2852 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2853 EVT LoadedVT = LN0->getMemoryVT();
2855 if (ExtVT == LoadedVT &&
2856 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2857 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2860 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2861 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2862 LN0->getMemOperand());
2864 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2868 // Do not change the width of a volatile load.
2869 // Do not generate loads of non-round integer types since these can
2870 // be expensive (and would be wrong if the type is not byte sized).
2871 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2872 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2873 EVT PtrType = LN0->getOperand(1).getValueType();
2875 unsigned Alignment = LN0->getAlignment();
2876 SDValue NewPtr = LN0->getBasePtr();
2878 // For big endian targets, we need to add an offset to the pointer
2879 // to load the correct bytes. For little endian systems, we merely
2880 // need to read fewer bytes from the same pointer.
2881 if (TLI.isBigEndian()) {
2882 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2883 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2884 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2885 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2886 NewPtr, DAG.getConstant(PtrOff, PtrType));
2887 Alignment = MinAlign(Alignment, PtrOff);
2890 AddToWorkList(NewPtr.getNode());
2892 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2895 LN0->getChain(), NewPtr,
2896 LN0->getPointerInfo(),
2897 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2898 Alignment, LN0->getTBAAInfo());
2900 CombineTo(LN0, Load, Load.getValue(1));
2901 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2907 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2908 VT.getSizeInBits() <= 64) {
2909 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2910 APInt ADDC = ADDI->getAPIntValue();
2911 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2912 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2913 // immediate for an add, but it is legal if its top c2 bits are set,
2914 // transform the ADD so the immediate doesn't need to be materialized
2916 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2917 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2918 SRLI->getZExtValue());
2919 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2921 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2923 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2924 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2925 CombineTo(N0.getNode(), NewAdd);
2926 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2934 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2935 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2936 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2937 N0.getOperand(1), false);
2938 if (BSwap.getNode())
2945 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2947 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2948 bool DemandHighBits) {
2949 if (!LegalOperations)
2952 EVT VT = N->getValueType(0);
2953 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2955 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2958 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2959 bool LookPassAnd0 = false;
2960 bool LookPassAnd1 = false;
2961 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2963 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2965 if (N0.getOpcode() == ISD::AND) {
2966 if (!N0.getNode()->hasOneUse())
2968 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2969 if (!N01C || N01C->getZExtValue() != 0xFF00)
2971 N0 = N0.getOperand(0);
2972 LookPassAnd0 = true;
2975 if (N1.getOpcode() == ISD::AND) {
2976 if (!N1.getNode()->hasOneUse())
2978 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2979 if (!N11C || N11C->getZExtValue() != 0xFF)
2981 N1 = N1.getOperand(0);
2982 LookPassAnd1 = true;
2985 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2987 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2989 if (!N0.getNode()->hasOneUse() ||
2990 !N1.getNode()->hasOneUse())
2993 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2994 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2997 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3000 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3001 SDValue N00 = N0->getOperand(0);
3002 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3003 if (!N00.getNode()->hasOneUse())
3005 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3006 if (!N001C || N001C->getZExtValue() != 0xFF)
3008 N00 = N00.getOperand(0);
3009 LookPassAnd0 = true;
3012 SDValue N10 = N1->getOperand(0);
3013 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3014 if (!N10.getNode()->hasOneUse())
3016 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3017 if (!N101C || N101C->getZExtValue() != 0xFF00)
3019 N10 = N10.getOperand(0);
3020 LookPassAnd1 = true;
3026 // Make sure everything beyond the low halfword gets set to zero since the SRL
3027 // 16 will clear the top bits.
3028 unsigned OpSizeInBits = VT.getSizeInBits();
3029 if (DemandHighBits && OpSizeInBits > 16) {
3030 // If the left-shift isn't masked out then the only way this is a bswap is
3031 // if all bits beyond the low 8 are 0. In that case the entire pattern
3032 // reduces to a left shift anyway: leave it for other parts of the combiner.
3036 // However, if the right shift isn't masked out then it might be because
3037 // it's not needed. See if we can spot that too.
3038 if (!LookPassAnd1 &&
3039 !DAG.MaskedValueIsZero(
3040 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3044 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3045 if (OpSizeInBits > 16)
3046 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3047 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3051 /// isBSwapHWordElement - Return true if the specified node is an element
3052 /// that makes up a 32-bit packed halfword byteswap. i.e.
3053 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3054 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3055 if (!N.getNode()->hasOneUse())
3058 unsigned Opc = N.getOpcode();
3059 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3062 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3067 switch (N1C->getZExtValue()) {
3070 case 0xFF: Num = 0; break;
3071 case 0xFF00: Num = 1; break;
3072 case 0xFF0000: Num = 2; break;
3073 case 0xFF000000: Num = 3; break;
3076 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3077 SDValue N0 = N.getOperand(0);
3078 if (Opc == ISD::AND) {
3079 if (Num == 0 || Num == 2) {
3081 // (x >> 8) & 0xff0000
3082 if (N0.getOpcode() != ISD::SRL)
3084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3085 if (!C || C->getZExtValue() != 8)
3088 // (x << 8) & 0xff00
3089 // (x << 8) & 0xff000000
3090 if (N0.getOpcode() != ISD::SHL)
3092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3093 if (!C || C->getZExtValue() != 8)
3096 } else if (Opc == ISD::SHL) {
3098 // (x & 0xff0000) << 8
3099 if (Num != 0 && Num != 2)
3101 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3102 if (!C || C->getZExtValue() != 8)
3104 } else { // Opc == ISD::SRL
3105 // (x & 0xff00) >> 8
3106 // (x & 0xff000000) >> 8
3107 if (Num != 1 && Num != 3)
3109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3110 if (!C || C->getZExtValue() != 8)
3117 Parts[Num] = N0.getOperand(0).getNode();
3121 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3122 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3123 /// => (rotl (bswap x), 16)
3124 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3125 if (!LegalOperations)
3128 EVT VT = N->getValueType(0);
3131 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3134 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3136 // (or (or (and), (and)), (or (and), (and)))
3137 // (or (or (or (and), (and)), (and)), (and))
3138 if (N0.getOpcode() != ISD::OR)
3140 SDValue N00 = N0.getOperand(0);
3141 SDValue N01 = N0.getOperand(1);
3143 if (N1.getOpcode() == ISD::OR &&
3144 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3145 // (or (or (and), (and)), (or (and), (and)))
3146 SDValue N000 = N00.getOperand(0);
3147 if (!isBSwapHWordElement(N000, Parts))
3150 SDValue N001 = N00.getOperand(1);
3151 if (!isBSwapHWordElement(N001, Parts))
3153 SDValue N010 = N01.getOperand(0);
3154 if (!isBSwapHWordElement(N010, Parts))
3156 SDValue N011 = N01.getOperand(1);
3157 if (!isBSwapHWordElement(N011, Parts))
3160 // (or (or (or (and), (and)), (and)), (and))
3161 if (!isBSwapHWordElement(N1, Parts))
3163 if (!isBSwapHWordElement(N01, Parts))
3165 if (N00.getOpcode() != ISD::OR)
3167 SDValue N000 = N00.getOperand(0);
3168 if (!isBSwapHWordElement(N000, Parts))
3170 SDValue N001 = N00.getOperand(1);
3171 if (!isBSwapHWordElement(N001, Parts))
3175 // Make sure the parts are all coming from the same node.
3176 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3179 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3180 SDValue(Parts[0],0));
3182 // Result of the bswap should be rotated by 16. If it's not legal, then
3183 // do (x << 16) | (x >> 16).
3184 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3185 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3186 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3187 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3188 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3189 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3190 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3191 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3194 SDValue DAGCombiner::visitOR(SDNode *N) {
3195 SDValue N0 = N->getOperand(0);
3196 SDValue N1 = N->getOperand(1);
3197 SDValue LL, LR, RL, RR, CC0, CC1;
3198 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3199 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3200 EVT VT = N1.getValueType();
3203 if (VT.isVector()) {
3204 SDValue FoldedVOp = SimplifyVBinOp(N);
3205 if (FoldedVOp.getNode()) return FoldedVOp;
3207 // fold (or x, 0) -> x, vector edition
3208 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3210 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3213 // fold (or x, -1) -> -1, vector edition
3214 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3216 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3219 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3220 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3221 // Do this only if the resulting shuffle is legal.
3222 if (isa<ShuffleVectorSDNode>(N0) &&
3223 isa<ShuffleVectorSDNode>(N1) &&
3224 N0->getOperand(1) == N1->getOperand(1) &&
3225 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3226 bool CanFold = true;
3227 unsigned NumElts = VT.getVectorNumElements();
3228 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3229 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3230 // We construct two shuffle masks:
3231 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3232 // and N1 as the second operand.
3233 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3234 // and N0 as the second operand.
3235 // We do this because OR is commutable and therefore there might be
3236 // two ways to fold this node into a shuffle.
3237 SmallVector<int,4> Mask1;
3238 SmallVector<int,4> Mask2;
3240 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3241 int M0 = SV0->getMaskElt(i);
3242 int M1 = SV1->getMaskElt(i);
3244 // Both shuffle indexes are undef. Propagate Undef.
3245 if (M0 < 0 && M1 < 0) {
3246 Mask1.push_back(M0);
3247 Mask2.push_back(M0);
3251 if (M0 < 0 || M1 < 0 ||
3252 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3253 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3258 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3259 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3263 // Fold this sequence only if the resulting shuffle is 'legal'.
3264 if (TLI.isShuffleMaskLegal(Mask1, VT))
3265 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3266 N1->getOperand(0), &Mask1[0]);
3267 if (TLI.isShuffleMaskLegal(Mask2, VT))
3268 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3269 N0->getOperand(0), &Mask2[0]);
3274 // fold (or x, undef) -> -1
3275 if (!LegalOperations &&
3276 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3277 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3278 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3280 // fold (or c1, c2) -> c1|c2
3282 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3283 // canonicalize constant to RHS
3285 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3286 // fold (or x, 0) -> x
3287 if (N1C && N1C->isNullValue())
3289 // fold (or x, -1) -> -1
3290 if (N1C && N1C->isAllOnesValue())
3292 // fold (or x, c) -> c iff (x & ~c) == 0
3293 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3296 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3297 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3298 if (BSwap.getNode() != 0)
3300 BSwap = MatchBSwapHWordLow(N, N0, N1);
3301 if (BSwap.getNode() != 0)
3305 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3306 if (ROR.getNode() != 0)
3308 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3309 // iff (c1 & c2) == 0.
3310 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3311 isa<ConstantSDNode>(N0.getOperand(1))) {
3312 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3313 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3314 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3318 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3319 N0.getOperand(0), N1), COR);
3322 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3323 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3324 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3325 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3327 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3328 LL.getValueType().isInteger()) {
3329 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3330 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3331 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3332 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3333 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3334 LR.getValueType(), LL, RL);
3335 AddToWorkList(ORNode.getNode());
3336 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3338 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3339 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3340 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3341 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3342 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3343 LR.getValueType(), LL, RL);
3344 AddToWorkList(ANDNode.getNode());
3345 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3348 // canonicalize equivalent to ll == rl
3349 if (LL == RR && LR == RL) {
3350 Op1 = ISD::getSetCCSwappedOperands(Op1);
3353 if (LL == RL && LR == RR) {
3354 bool isInteger = LL.getValueType().isInteger();
3355 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3356 if (Result != ISD::SETCC_INVALID &&
3357 (!LegalOperations ||
3358 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3359 TLI.isOperationLegal(ISD::SETCC,
3360 getSetCCResultType(N0.getValueType())))))
3361 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3366 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3367 if (N0.getOpcode() == N1.getOpcode()) {
3368 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3369 if (Tmp.getNode()) return Tmp;
3372 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3373 if (N0.getOpcode() == ISD::AND &&
3374 N1.getOpcode() == ISD::AND &&
3375 N0.getOperand(1).getOpcode() == ISD::Constant &&
3376 N1.getOperand(1).getOpcode() == ISD::Constant &&
3377 // Don't increase # computations.
3378 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3379 // We can only do this xform if we know that bits from X that are set in C2
3380 // but not in C1 are already zero. Likewise for Y.
3381 const APInt &LHSMask =
3382 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3383 const APInt &RHSMask =
3384 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3386 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3387 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3388 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3389 N0.getOperand(0), N1.getOperand(0));
3390 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3391 DAG.getConstant(LHSMask | RHSMask, VT));
3395 // See if this is some rotate idiom.
3396 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3397 return SDValue(Rot, 0);
3399 // Simplify the operands using demanded-bits information.
3400 if (!VT.isVector() &&
3401 SimplifyDemandedBits(SDValue(N, 0)))
3402 return SDValue(N, 0);
3407 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3408 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3409 if (Op.getOpcode() == ISD::AND) {
3410 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3411 Mask = Op.getOperand(1);
3412 Op = Op.getOperand(0);
3418 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3426 // Return true if we can prove that, whenever Neg and Pos are both in the
3427 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3428 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3430 // (or (shift1 X, Neg), (shift2 X, Pos))
3432 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3433 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3434 // to consider shift amounts with defined behavior.
3435 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3436 // If OpSize is a power of 2 then:
3438 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3439 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3441 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3442 // for the stronger condition:
3444 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3446 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3447 // we can just replace Neg with Neg' for the rest of the function.
3449 // In other cases we check for the even stronger condition:
3451 // Neg == OpSize - Pos [B]
3453 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3454 // behavior if Pos == 0 (and consequently Neg == OpSize).
3456 // We could actually use [A] whenever OpSize is a power of 2, but the
3457 // only extra cases that it would match are those uninteresting ones
3458 // where Neg and Pos are never in range at the same time. E.g. for
3459 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3460 // as well as (sub 32, Pos), but:
3462 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3464 // always invokes undefined behavior for 32-bit X.
3466 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3467 unsigned MaskLoBits = 0;
3468 if (Neg.getOpcode() == ISD::AND &&
3469 isPowerOf2_64(OpSize) &&
3470 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3471 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3472 Neg = Neg.getOperand(0);
3473 MaskLoBits = Log2_64(OpSize);
3476 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3477 if (Neg.getOpcode() != ISD::SUB)
3479 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3482 SDValue NegOp1 = Neg.getOperand(1);
3484 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3485 // Pos'. The truncation is redundant for the purpose of the equality.
3487 Pos.getOpcode() == ISD::AND &&
3488 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3489 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3490 Pos = Pos.getOperand(0);
3492 // The condition we need is now:
3494 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3496 // If NegOp1 == Pos then we need:
3498 // OpSize & Mask == NegC & Mask
3500 // (because "x & Mask" is a truncation and distributes through subtraction).
3503 Width = NegC->getAPIntValue();
3504 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3505 // Then the condition we want to prove becomes:
3507 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3509 // which, again because "x & Mask" is a truncation, becomes:
3511 // NegC & Mask == (OpSize - PosC) & Mask
3512 // OpSize & Mask == (NegC + PosC) & Mask
3513 else if (Pos.getOpcode() == ISD::ADD &&
3514 Pos.getOperand(0) == NegOp1 &&
3515 Pos.getOperand(1).getOpcode() == ISD::Constant)
3516 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3517 NegC->getAPIntValue());
3521 // Now we just need to check that OpSize & Mask == Width & Mask.
3523 // Opsize & Mask is 0 since Mask is Opsize - 1.
3524 return Width.getLoBits(MaskLoBits) == 0;
3525 return Width == OpSize;
3528 // A subroutine of MatchRotate used once we have found an OR of two opposite
3529 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3530 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3531 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3532 // Neg with outer conversions stripped away.
3533 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3534 SDValue Neg, SDValue InnerPos,
3535 SDValue InnerNeg, unsigned PosOpcode,
3536 unsigned NegOpcode, SDLoc DL) {
3537 // fold (or (shl x, (*ext y)),
3538 // (srl x, (*ext (sub 32, y)))) ->
3539 // (rotl x, y) or (rotr x, (sub 32, y))
3541 // fold (or (shl x, (*ext (sub 32, y))),
3542 // (srl x, (*ext y))) ->
3543 // (rotr x, y) or (rotl x, (sub 32, y))
3544 EVT VT = Shifted.getValueType();
3545 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3546 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3547 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3548 HasPos ? Pos : Neg).getNode();
3551 // fold (or (shl (*ext x), (*ext y)),
3552 // (srl (*ext x), (*ext (sub 32, y)))) ->
3553 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3555 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3556 // (srl (*ext x), (*ext y))) ->
3557 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3558 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3559 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3560 SDValue InnerShifted = Shifted.getOperand(0);
3561 EVT InnerVT = InnerShifted.getValueType();
3562 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3563 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3564 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3565 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3566 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3567 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3575 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3576 // idioms for rotate, and if the target supports rotation instructions, generate
3578 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3579 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3580 EVT VT = LHS.getValueType();
3581 if (!TLI.isTypeLegal(VT)) return 0;
3583 // The target must have at least one rotate flavor.
3584 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3585 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3586 if (!HasROTL && !HasROTR) return 0;
3588 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3589 SDValue LHSShift; // The shift.
3590 SDValue LHSMask; // AND value if any.
3591 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3592 return 0; // Not part of a rotate.
3594 SDValue RHSShift; // The shift.
3595 SDValue RHSMask; // AND value if any.
3596 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3597 return 0; // Not part of a rotate.
3599 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3600 return 0; // Not shifting the same value.
3602 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3603 return 0; // Shifts must disagree.
3605 // Canonicalize shl to left side in a shl/srl pair.
3606 if (RHSShift.getOpcode() == ISD::SHL) {
3607 std::swap(LHS, RHS);
3608 std::swap(LHSShift, RHSShift);
3609 std::swap(LHSMask , RHSMask );
3612 unsigned OpSizeInBits = VT.getSizeInBits();
3613 SDValue LHSShiftArg = LHSShift.getOperand(0);
3614 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3615 SDValue RHSShiftArg = RHSShift.getOperand(0);
3616 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3618 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3619 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3620 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3621 RHSShiftAmt.getOpcode() == ISD::Constant) {
3622 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3623 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3624 if ((LShVal + RShVal) != OpSizeInBits)
3627 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3628 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3630 // If there is an AND of either shifted operand, apply it to the result.
3631 if (LHSMask.getNode() || RHSMask.getNode()) {
3632 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3634 if (LHSMask.getNode()) {
3635 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3636 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3638 if (RHSMask.getNode()) {
3639 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3640 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3643 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3646 return Rot.getNode();
3649 // If there is a mask here, and we have a variable shift, we can't be sure
3650 // that we're masking out the right stuff.
3651 if (LHSMask.getNode() || RHSMask.getNode())
3654 // If the shift amount is sign/zext/any-extended just peel it off.
3655 SDValue LExtOp0 = LHSShiftAmt;
3656 SDValue RExtOp0 = RHSShiftAmt;
3657 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3658 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3659 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3660 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3661 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3662 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3663 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3664 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3665 LExtOp0 = LHSShiftAmt.getOperand(0);
3666 RExtOp0 = RHSShiftAmt.getOperand(0);
3669 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3670 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3674 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3675 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3682 SDValue DAGCombiner::visitXOR(SDNode *N) {
3683 SDValue N0 = N->getOperand(0);
3684 SDValue N1 = N->getOperand(1);
3685 SDValue LHS, RHS, CC;
3686 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3688 EVT VT = N0.getValueType();
3691 if (VT.isVector()) {
3692 SDValue FoldedVOp = SimplifyVBinOp(N);
3693 if (FoldedVOp.getNode()) return FoldedVOp;
3695 // fold (xor x, 0) -> x, vector edition
3696 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3698 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3702 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3703 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3704 return DAG.getConstant(0, VT);
3705 // fold (xor x, undef) -> undef
3706 if (N0.getOpcode() == ISD::UNDEF)
3708 if (N1.getOpcode() == ISD::UNDEF)
3710 // fold (xor c1, c2) -> c1^c2
3712 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3713 // canonicalize constant to RHS
3715 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3716 // fold (xor x, 0) -> x
3717 if (N1C && N1C->isNullValue())
3720 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3721 if (RXOR.getNode() != 0)
3724 // fold !(x cc y) -> (x !cc y)
3725 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3726 bool isInt = LHS.getValueType().isInteger();
3727 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3730 if (!LegalOperations ||
3731 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3732 switch (N0.getOpcode()) {
3734 llvm_unreachable("Unhandled SetCC Equivalent!");
3736 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3737 case ISD::SELECT_CC:
3738 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3739 N0.getOperand(3), NotCC);
3744 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3745 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3746 N0.getNode()->hasOneUse() &&
3747 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3748 SDValue V = N0.getOperand(0);
3749 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3750 DAG.getConstant(1, V.getValueType()));
3751 AddToWorkList(V.getNode());
3752 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3755 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3756 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3757 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3758 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3759 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3760 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3761 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3762 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3763 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3764 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3767 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3768 if (N1C && N1C->isAllOnesValue() &&
3769 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3770 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3771 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3772 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3773 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3774 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3775 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3776 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3779 // fold (xor (and x, y), y) -> (and (not x), y)
3780 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3781 N0->getOperand(1) == N1) {
3782 SDValue X = N0->getOperand(0);
3783 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3784 AddToWorkList(NotX.getNode());
3785 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3787 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3788 if (N1C && N0.getOpcode() == ISD::XOR) {
3789 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3790 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3792 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3793 DAG.getConstant(N1C->getAPIntValue() ^
3794 N00C->getAPIntValue(), VT));
3796 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3797 DAG.getConstant(N1C->getAPIntValue() ^
3798 N01C->getAPIntValue(), VT));
3800 // fold (xor x, x) -> 0
3802 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3804 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3805 if (N0.getOpcode() == N1.getOpcode()) {
3806 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3807 if (Tmp.getNode()) return Tmp;
3810 // Simplify the expression using non-local knowledge.
3811 if (!VT.isVector() &&
3812 SimplifyDemandedBits(SDValue(N, 0)))
3813 return SDValue(N, 0);
3818 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3819 /// the shift amount is a constant.
3820 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3821 // We can't and shouldn't fold opaque constants.
3822 if (Amt->isOpaque())
3825 SDNode *LHS = N->getOperand(0).getNode();
3826 if (!LHS->hasOneUse()) return SDValue();
3828 // We want to pull some binops through shifts, so that we have (and (shift))
3829 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3830 // thing happens with address calculations, so it's important to canonicalize
3832 bool HighBitSet = false; // Can we transform this if the high bit is set?
3834 switch (LHS->getOpcode()) {
3835 default: return SDValue();
3838 HighBitSet = false; // We can only transform sra if the high bit is clear.
3841 HighBitSet = true; // We can only transform sra if the high bit is set.
3844 if (N->getOpcode() != ISD::SHL)
3845 return SDValue(); // only shl(add) not sr[al](add).
3846 HighBitSet = false; // We can only transform sra if the high bit is clear.
3850 // We require the RHS of the binop to be a constant and not opaque as well.
3851 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3852 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3854 // FIXME: disable this unless the input to the binop is a shift by a constant.
3855 // If it is not a shift, it pessimizes some common cases like:
3857 // void foo(int *X, int i) { X[i & 1235] = 1; }
3858 // int bar(int *X, int i) { return X[i & 255]; }
3859 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3860 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3861 BinOpLHSVal->getOpcode() != ISD::SRA &&
3862 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3863 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3866 EVT VT = N->getValueType(0);
3868 // If this is a signed shift right, and the high bit is modified by the
3869 // logical operation, do not perform the transformation. The highBitSet
3870 // boolean indicates the value of the high bit of the constant which would
3871 // cause it to be modified for this operation.
3872 if (N->getOpcode() == ISD::SRA) {
3873 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3874 if (BinOpRHSSignSet != HighBitSet)
3878 // Fold the constants, shifting the binop RHS by the shift amount.
3879 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3881 LHS->getOperand(1), N->getOperand(1));
3882 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3884 // Create the new shift.
3885 SDValue NewShift = DAG.getNode(N->getOpcode(),
3886 SDLoc(LHS->getOperand(0)),
3887 VT, LHS->getOperand(0), N->getOperand(1));
3889 // Create the new binop.
3890 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3893 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3894 assert(N->getOpcode() == ISD::TRUNCATE);
3895 assert(N->getOperand(0).getOpcode() == ISD::AND);
3897 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3898 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3899 SDValue N01 = N->getOperand(0).getOperand(1);
3901 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3902 EVT TruncVT = N->getValueType(0);
3903 SDValue N00 = N->getOperand(0).getOperand(0);
3904 APInt TruncC = N01C->getAPIntValue();
3905 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3907 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3908 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3909 DAG.getConstant(TruncC, TruncVT));
3916 SDValue DAGCombiner::visitRotate(SDNode *N) {
3917 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3918 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3919 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3920 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3921 if (NewOp1.getNode())
3922 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3923 N->getOperand(0), NewOp1);
3928 SDValue DAGCombiner::visitSHL(SDNode *N) {
3929 SDValue N0 = N->getOperand(0);
3930 SDValue N1 = N->getOperand(1);
3931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3933 EVT VT = N0.getValueType();
3934 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3937 if (VT.isVector()) {
3938 SDValue FoldedVOp = SimplifyVBinOp(N);
3939 if (FoldedVOp.getNode()) return FoldedVOp;
3941 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3942 // If setcc produces all-one true value then:
3943 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3944 if (N1CV && N1CV->isConstant()) {
3945 if (N0.getOpcode() == ISD::AND &&
3946 TLI.getBooleanContents(true) ==
3947 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3948 SDValue N00 = N0->getOperand(0);
3949 SDValue N01 = N0->getOperand(1);
3950 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3952 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3953 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3955 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3958 N1C = isConstOrConstSplat(N1);
3963 // fold (shl c1, c2) -> c1<<c2
3965 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3966 // fold (shl 0, x) -> 0
3967 if (N0C && N0C->isNullValue())
3969 // fold (shl x, c >= size(x)) -> undef
3970 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3971 return DAG.getUNDEF(VT);
3972 // fold (shl x, 0) -> x
3973 if (N1C && N1C->isNullValue())
3975 // fold (shl undef, x) -> 0
3976 if (N0.getOpcode() == ISD::UNDEF)
3977 return DAG.getConstant(0, VT);
3978 // if (shl x, c) is known to be zero, return 0
3979 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3980 APInt::getAllOnesValue(OpSizeInBits)))
3981 return DAG.getConstant(0, VT);
3982 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3983 if (N1.getOpcode() == ISD::TRUNCATE &&
3984 N1.getOperand(0).getOpcode() == ISD::AND) {
3985 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3986 if (NewOp1.getNode())
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3990 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3991 return SDValue(N, 0);
3993 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3994 if (N1C && N0.getOpcode() == ISD::SHL) {
3995 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3996 uint64_t c1 = N0C1->getZExtValue();
3997 uint64_t c2 = N1C->getZExtValue();
3998 if (c1 + c2 >= OpSizeInBits)
3999 return DAG.getConstant(0, VT);
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4001 DAG.getConstant(c1 + c2, N1.getValueType()));
4005 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4006 // For this to be valid, the second form must not preserve any of the bits
4007 // that are shifted out by the inner shift in the first form. This means
4008 // the outer shift size must be >= the number of bits added by the ext.
4009 // As a corollary, we don't care what kind of ext it is.
4010 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4011 N0.getOpcode() == ISD::ANY_EXTEND ||
4012 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4013 N0.getOperand(0).getOpcode() == ISD::SHL) {
4014 SDValue N0Op0 = N0.getOperand(0);
4015 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4016 uint64_t c1 = N0Op0C1->getZExtValue();
4017 uint64_t c2 = N1C->getZExtValue();
4018 EVT InnerShiftVT = N0Op0.getValueType();
4019 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4020 if (c2 >= OpSizeInBits - InnerShiftSize) {
4021 if (c1 + c2 >= OpSizeInBits)
4022 return DAG.getConstant(0, VT);
4023 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4024 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4025 N0Op0->getOperand(0)),
4026 DAG.getConstant(c1 + c2, N1.getValueType()));
4031 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4032 // Only fold this if the inner zext has no other uses to avoid increasing
4033 // the total number of instructions.
4034 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4035 N0.getOperand(0).getOpcode() == ISD::SRL) {
4036 SDValue N0Op0 = N0.getOperand(0);
4037 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4038 uint64_t c1 = N0Op0C1->getZExtValue();
4039 if (c1 < VT.getScalarSizeInBits()) {
4040 uint64_t c2 = N1C->getZExtValue();
4042 SDValue NewOp0 = N0.getOperand(0);
4043 EVT CountVT = NewOp0.getOperand(1).getValueType();
4044 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4045 NewOp0, DAG.getConstant(c2, CountVT));
4046 AddToWorkList(NewSHL.getNode());
4047 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4053 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4054 // (and (srl x, (sub c1, c2), MASK)
4055 // Only fold this if the inner shift has no other uses -- if it does, folding
4056 // this will increase the total number of instructions.
4057 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4058 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4059 uint64_t c1 = N0C1->getZExtValue();
4060 if (c1 < OpSizeInBits) {
4061 uint64_t c2 = N1C->getZExtValue();
4062 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4065 Mask = Mask.shl(c2 - c1);
4066 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4067 DAG.getConstant(c2 - c1, N1.getValueType()));
4069 Mask = Mask.lshr(c1 - c2);
4070 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4071 DAG.getConstant(c1 - c2, N1.getValueType()));
4073 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4074 DAG.getConstant(Mask, VT));
4078 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4079 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4080 unsigned BitSize = VT.getScalarSizeInBits();
4081 SDValue HiBitsMask =
4082 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4083 BitSize - N1C->getZExtValue()), VT);
4084 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4089 SDValue NewSHL = visitShiftByConstant(N, N1C);
4090 if (NewSHL.getNode())
4097 SDValue DAGCombiner::visitSRA(SDNode *N) {
4098 SDValue N0 = N->getOperand(0);
4099 SDValue N1 = N->getOperand(1);
4100 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4102 EVT VT = N0.getValueType();
4103 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4106 if (VT.isVector()) {
4107 SDValue FoldedVOp = SimplifyVBinOp(N);
4108 if (FoldedVOp.getNode()) return FoldedVOp;
4110 N1C = isConstOrConstSplat(N1);
4113 // fold (sra c1, c2) -> (sra c1, c2)
4115 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4116 // fold (sra 0, x) -> 0
4117 if (N0C && N0C->isNullValue())
4119 // fold (sra -1, x) -> -1
4120 if (N0C && N0C->isAllOnesValue())
4122 // fold (sra x, (setge c, size(x))) -> undef
4123 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4124 return DAG.getUNDEF(VT);
4125 // fold (sra x, 0) -> x
4126 if (N1C && N1C->isNullValue())
4128 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4130 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4131 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4132 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4134 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4135 ExtVT, VT.getVectorNumElements());
4136 if ((!LegalOperations ||
4137 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4138 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4139 N0.getOperand(0), DAG.getValueType(ExtVT));
4142 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4143 if (N1C && N0.getOpcode() == ISD::SRA) {
4144 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4145 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4146 if (Sum >= OpSizeInBits)
4147 Sum = OpSizeInBits - 1;
4148 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4149 DAG.getConstant(Sum, N1.getValueType()));
4153 // fold (sra (shl X, m), (sub result_size, n))
4154 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4155 // result_size - n != m.
4156 // If truncate is free for the target sext(shl) is likely to result in better
4158 if (N0.getOpcode() == ISD::SHL && N1C) {
4159 // Get the two constanst of the shifts, CN0 = m, CN = n.
4160 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4162 LLVMContext &Ctx = *DAG.getContext();
4163 // Determine what the truncate's result bitsize and type would be.
4164 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4167 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4169 // Determine the residual right-shift amount.
4170 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4172 // If the shift is not a no-op (in which case this should be just a sign
4173 // extend already), the truncated to type is legal, sign_extend is legal
4174 // on that type, and the truncate to that type is both legal and free,
4175 // perform the transform.
4176 if ((ShiftAmt > 0) &&
4177 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4178 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4179 TLI.isTruncateFree(VT, TruncVT)) {
4181 SDValue Amt = DAG.getConstant(ShiftAmt,
4182 getShiftAmountTy(N0.getOperand(0).getValueType()));
4183 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4184 N0.getOperand(0), Amt);
4185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4187 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4188 N->getValueType(0), Trunc);
4193 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4194 if (N1.getOpcode() == ISD::TRUNCATE &&
4195 N1.getOperand(0).getOpcode() == ISD::AND) {
4196 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4197 if (NewOp1.getNode())
4198 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4201 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4202 // if c1 is equal to the number of bits the trunc removes
4203 if (N0.getOpcode() == ISD::TRUNCATE &&
4204 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4205 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4206 N0.getOperand(0).hasOneUse() &&
4207 N0.getOperand(0).getOperand(1).hasOneUse() &&
4209 SDValue N0Op0 = N0.getOperand(0);
4210 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4211 unsigned LargeShiftVal = LargeShift->getZExtValue();
4212 EVT LargeVT = N0Op0.getValueType();
4214 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4216 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4217 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4218 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4219 N0Op0.getOperand(0), Amt);
4220 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4225 // Simplify, based on bits shifted out of the LHS.
4226 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4227 return SDValue(N, 0);
4230 // If the sign bit is known to be zero, switch this to a SRL.
4231 if (DAG.SignBitIsZero(N0))
4232 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4235 SDValue NewSRA = visitShiftByConstant(N, N1C);
4236 if (NewSRA.getNode())
4243 SDValue DAGCombiner::visitSRL(SDNode *N) {
4244 SDValue N0 = N->getOperand(0);
4245 SDValue N1 = N->getOperand(1);
4246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4248 EVT VT = N0.getValueType();
4249 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4252 if (VT.isVector()) {
4253 SDValue FoldedVOp = SimplifyVBinOp(N);
4254 if (FoldedVOp.getNode()) return FoldedVOp;
4256 N1C = isConstOrConstSplat(N1);
4259 // fold (srl c1, c2) -> c1 >>u c2
4261 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4262 // fold (srl 0, x) -> 0
4263 if (N0C && N0C->isNullValue())
4265 // fold (srl x, c >= size(x)) -> undef
4266 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4267 return DAG.getUNDEF(VT);
4268 // fold (srl x, 0) -> x
4269 if (N1C && N1C->isNullValue())
4271 // if (srl x, c) is known to be zero, return 0
4272 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4273 APInt::getAllOnesValue(OpSizeInBits)))
4274 return DAG.getConstant(0, VT);
4276 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4277 if (N1C && N0.getOpcode() == ISD::SRL) {
4278 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4279 uint64_t c1 = N01C->getZExtValue();
4280 uint64_t c2 = N1C->getZExtValue();
4281 if (c1 + c2 >= OpSizeInBits)
4282 return DAG.getConstant(0, VT);
4283 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4284 DAG.getConstant(c1 + c2, N1.getValueType()));
4288 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4289 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4290 N0.getOperand(0).getOpcode() == ISD::SRL &&
4291 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4293 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
4295 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4296 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4297 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4298 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4299 if (c1 + OpSizeInBits == InnerShiftSize) {
4300 if (c1 + c2 >= InnerShiftSize)
4301 return DAG.getConstant(0, VT);
4302 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4303 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4304 N0.getOperand(0)->getOperand(0),
4305 DAG.getConstant(c1 + c2, ShiftCountVT)));
4309 // fold (srl (shl x, c), c) -> (and x, cst2)
4310 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4311 unsigned BitSize = N0.getScalarValueSizeInBits();
4312 if (BitSize <= 64) {
4313 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4314 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4315 DAG.getConstant(~0ULL >> ShAmt, VT));
4319 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4320 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4321 // Shifting in all undef bits?
4322 EVT SmallVT = N0.getOperand(0).getValueType();
4323 unsigned BitSize = SmallVT.getScalarSizeInBits();
4324 if (N1C->getZExtValue() >= BitSize)
4325 return DAG.getUNDEF(VT);
4327 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4328 uint64_t ShiftAmt = N1C->getZExtValue();
4329 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4331 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4332 AddToWorkList(SmallShift.getNode());
4333 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4334 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4335 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4336 DAG.getConstant(Mask, VT));
4340 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4341 // bit, which is unmodified by sra.
4342 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4343 if (N0.getOpcode() == ISD::SRA)
4344 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4347 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4348 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4349 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4350 APInt KnownZero, KnownOne;
4351 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4353 // If any of the input bits are KnownOne, then the input couldn't be all
4354 // zeros, thus the result of the srl will always be zero.
4355 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4357 // If all of the bits input the to ctlz node are known to be zero, then
4358 // the result of the ctlz is "32" and the result of the shift is one.
4359 APInt UnknownBits = ~KnownZero;
4360 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4362 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4363 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4364 // Okay, we know that only that the single bit specified by UnknownBits
4365 // could be set on input to the CTLZ node. If this bit is set, the SRL
4366 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4367 // to an SRL/XOR pair, which is likely to simplify more.
4368 unsigned ShAmt = UnknownBits.countTrailingZeros();
4369 SDValue Op = N0.getOperand(0);
4372 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4373 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4374 AddToWorkList(Op.getNode());
4377 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4378 Op, DAG.getConstant(1, VT));
4382 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4383 if (N1.getOpcode() == ISD::TRUNCATE &&
4384 N1.getOperand(0).getOpcode() == ISD::AND) {
4385 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4386 if (NewOp1.getNode())
4387 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4390 // fold operands of srl based on knowledge that the low bits are not
4392 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4393 return SDValue(N, 0);
4396 SDValue NewSRL = visitShiftByConstant(N, N1C);
4397 if (NewSRL.getNode())
4401 // Attempt to convert a srl of a load into a narrower zero-extending load.
4402 SDValue NarrowLoad = ReduceLoadWidth(N);
4403 if (NarrowLoad.getNode())
4406 // Here is a common situation. We want to optimize:
4409 // %b = and i32 %a, 2
4410 // %c = srl i32 %b, 1
4411 // brcond i32 %c ...
4417 // %c = setcc eq %b, 0
4420 // However when after the source operand of SRL is optimized into AND, the SRL
4421 // itself may not be optimized further. Look for it and add the BRCOND into
4423 if (N->hasOneUse()) {
4424 SDNode *Use = *N->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4427 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4428 // Also look pass the truncate.
4429 Use = *Use->use_begin();
4430 if (Use->getOpcode() == ISD::BRCOND)
4438 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4439 SDValue N0 = N->getOperand(0);
4440 EVT VT = N->getValueType(0);
4442 // fold (ctlz c1) -> c2
4443 if (isa<ConstantSDNode>(N0))
4444 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4448 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4449 SDValue N0 = N->getOperand(0);
4450 EVT VT = N->getValueType(0);
4452 // fold (ctlz_zero_undef c1) -> c2
4453 if (isa<ConstantSDNode>(N0))
4454 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4458 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4459 SDValue N0 = N->getOperand(0);
4460 EVT VT = N->getValueType(0);
4462 // fold (cttz c1) -> c2
4463 if (isa<ConstantSDNode>(N0))
4464 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4468 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4469 SDValue N0 = N->getOperand(0);
4470 EVT VT = N->getValueType(0);
4472 // fold (cttz_zero_undef c1) -> c2
4473 if (isa<ConstantSDNode>(N0))
4474 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4478 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4479 SDValue N0 = N->getOperand(0);
4480 EVT VT = N->getValueType(0);
4482 // fold (ctpop c1) -> c2
4483 if (isa<ConstantSDNode>(N0))
4484 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4488 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 SDValue N2 = N->getOperand(2);
4492 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4495 EVT VT = N->getValueType(0);
4496 EVT VT0 = N0.getValueType();
4498 // fold (select C, X, X) -> X
4501 // fold (select true, X, Y) -> X
4502 if (N0C && !N0C->isNullValue())
4504 // fold (select false, X, Y) -> Y
4505 if (N0C && N0C->isNullValue())
4507 // fold (select C, 1, X) -> (or C, X)
4508 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4509 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4510 // fold (select C, 0, 1) -> (xor C, 1)
4511 if (VT.isInteger() &&
4514 TLI.getBooleanContents(false) ==
4515 TargetLowering::ZeroOrOneBooleanContent)) &&
4516 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4519 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4520 N0, DAG.getConstant(1, VT0));
4521 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4522 N0, DAG.getConstant(1, VT0));
4523 AddToWorkList(XORNode.getNode());
4525 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4528 // fold (select C, 0, X) -> (and (not C), X)
4529 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4530 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4531 AddToWorkList(NOTNode.getNode());
4532 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4534 // fold (select C, X, 1) -> (or (not C), X)
4535 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4536 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4537 AddToWorkList(NOTNode.getNode());
4538 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4540 // fold (select C, X, 0) -> (and C, X)
4541 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4543 // fold (select X, X, Y) -> (or X, Y)
4544 // fold (select X, 1, Y) -> (or X, Y)
4545 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4546 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4547 // fold (select X, Y, X) -> (and X, Y)
4548 // fold (select X, Y, 0) -> (and X, Y)
4549 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4550 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4552 // If we can fold this based on the true/false value, do so.
4553 if (SimplifySelectOps(N, N1, N2))
4554 return SDValue(N, 0); // Don't revisit N.
4556 // fold selects based on a setcc into other things, such as min/max/abs
4557 if (N0.getOpcode() == ISD::SETCC) {
4559 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4560 // having to say they don't support SELECT_CC on every type the DAG knows
4561 // about, since there is no way to mark an opcode illegal at all value types
4562 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4563 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4564 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4565 N0.getOperand(0), N0.getOperand(1),
4566 N1, N2, N0.getOperand(2));
4567 return SimplifySelect(SDLoc(N), N0, N1, N2);
4574 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4577 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4579 // Split the inputs.
4580 SDValue Lo, Hi, LL, LH, RL, RH;
4581 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4582 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4584 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4585 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4587 return std::make_pair(Lo, Hi);
4590 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 SDValue N1 = N->getOperand(1);
4593 SDValue N2 = N->getOperand(2);
4596 // Canonicalize integer abs.
4597 // vselect (setg[te] X, 0), X, -X ->
4598 // vselect (setgt X, -1), X, -X ->
4599 // vselect (setl[te] X, 0), -X, X ->
4600 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4601 if (N0.getOpcode() == ISD::SETCC) {
4602 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4603 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4605 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4607 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4608 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4609 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4610 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4611 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4612 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4613 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4616 EVT VT = LHS.getValueType();
4617 SDValue Shift = DAG.getNode(
4618 ISD::SRA, DL, VT, LHS,
4619 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4620 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4621 AddToWorkList(Shift.getNode());
4622 AddToWorkList(Add.getNode());
4623 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4627 // If the VSELECT result requires splitting and the mask is provided by a
4628 // SETCC, then split both nodes and its operands before legalization. This
4629 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4630 // and enables future optimizations (e.g. min/max pattern matching on X86).
4631 if (N0.getOpcode() == ISD::SETCC) {
4632 EVT VT = N->getValueType(0);
4634 // Check if any splitting is required.
4635 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4636 TargetLowering::TypeSplitVector)
4639 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4640 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4641 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4642 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4644 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4645 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4647 // Add the new VSELECT nodes to the work list in case they need to be split
4649 AddToWorkList(Lo.getNode());
4650 AddToWorkList(Hi.getNode());
4652 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4655 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4656 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4658 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4659 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4665 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4666 SDValue N0 = N->getOperand(0);
4667 SDValue N1 = N->getOperand(1);
4668 SDValue N2 = N->getOperand(2);
4669 SDValue N3 = N->getOperand(3);
4670 SDValue N4 = N->getOperand(4);
4671 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4673 // fold select_cc lhs, rhs, x, x, cc -> x
4677 // Determine if the condition we're dealing with is constant
4678 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4679 N0, N1, CC, SDLoc(N), false);
4680 if (SCC.getNode()) {
4681 AddToWorkList(SCC.getNode());
4683 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4684 if (!SCCC->isNullValue())
4685 return N2; // cond always true -> true val
4687 return N3; // cond always false -> false val
4690 // Fold to a simpler select_cc
4691 if (SCC.getOpcode() == ISD::SETCC)
4692 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4693 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4697 // If we can fold this based on the true/false value, do so.
4698 if (SimplifySelectOps(N, N2, N3))
4699 return SDValue(N, 0); // Don't revisit N.
4701 // fold select_cc into other things, such as min/max/abs
4702 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4705 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4706 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4707 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4711 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4712 // dag node into a ConstantSDNode or a build_vector of constants.
4713 // This function is called by the DAGCombiner when visiting sext/zext/aext
4714 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4715 // Vector extends are not folded if operations are legal; this is to
4716 // avoid introducing illegal build_vector dag nodes.
4717 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4718 SelectionDAG &DAG, bool LegalTypes,
4719 bool LegalOperations) {
4720 unsigned Opcode = N->getOpcode();
4721 SDValue N0 = N->getOperand(0);
4722 EVT VT = N->getValueType(0);
4724 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4725 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4727 // fold (sext c1) -> c1
4728 // fold (zext c1) -> c1
4729 // fold (aext c1) -> c1
4730 if (isa<ConstantSDNode>(N0))
4731 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4733 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4734 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4735 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4736 EVT SVT = VT.getScalarType();
4737 if (!(VT.isVector() &&
4738 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4739 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4742 // We can fold this node into a build_vector.
4743 unsigned VTBits = SVT.getSizeInBits();
4744 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4745 unsigned ShAmt = VTBits - EVTBits;
4746 SmallVector<SDValue, 8> Elts;
4747 unsigned NumElts = N0->getNumOperands();
4750 for (unsigned i=0; i != NumElts; ++i) {
4751 SDValue Op = N0->getOperand(i);
4752 if (Op->getOpcode() == ISD::UNDEF) {
4753 Elts.push_back(DAG.getUNDEF(SVT));
4757 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4758 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4759 if (Opcode == ISD::SIGN_EXTEND)
4760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4763 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4767 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4770 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4771 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4772 // transformation. Returns true if extension are possible and the above
4773 // mentioned transformation is profitable.
4774 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4776 SmallVectorImpl<SDNode *> &ExtendNodes,
4777 const TargetLowering &TLI) {
4778 bool HasCopyToRegUses = false;
4779 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4780 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4781 UE = N0.getNode()->use_end();
4786 if (UI.getUse().getResNo() != N0.getResNo())
4788 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4789 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4790 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4791 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4792 // Sign bits will be lost after a zext.
4795 for (unsigned i = 0; i != 2; ++i) {
4796 SDValue UseOp = User->getOperand(i);
4799 if (!isa<ConstantSDNode>(UseOp))
4804 ExtendNodes.push_back(User);
4807 // If truncates aren't free and there are users we can't
4808 // extend, it isn't worthwhile.
4811 // Remember if this value is live-out.
4812 if (User->getOpcode() == ISD::CopyToReg)
4813 HasCopyToRegUses = true;
4816 if (HasCopyToRegUses) {
4817 bool BothLiveOut = false;
4818 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4820 SDUse &Use = UI.getUse();
4821 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4827 // Both unextended and extended values are live out. There had better be
4828 // a good reason for the transformation.
4829 return ExtendNodes.size();
4834 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4835 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4836 ISD::NodeType ExtType) {
4837 // Extend SetCC uses if necessary.
4838 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4839 SDNode *SetCC = SetCCs[i];
4840 SmallVector<SDValue, 4> Ops;
4842 for (unsigned j = 0; j != 2; ++j) {
4843 SDValue SOp = SetCC->getOperand(j);
4845 Ops.push_back(ExtLoad);
4847 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4850 Ops.push_back(SetCC->getOperand(2));
4851 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4852 &Ops[0], Ops.size()));
4856 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4857 SDValue N0 = N->getOperand(0);
4858 EVT VT = N->getValueType(0);
4860 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4862 return SDValue(Res, 0);
4864 // fold (sext (sext x)) -> (sext x)
4865 // fold (sext (aext x)) -> (sext x)
4866 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4867 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4870 if (N0.getOpcode() == ISD::TRUNCATE) {
4871 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4872 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4873 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4874 if (NarrowLoad.getNode()) {
4875 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4876 if (NarrowLoad.getNode() != N0.getNode()) {
4877 CombineTo(N0.getNode(), NarrowLoad);
4878 // CombineTo deleted the truncate, if needed, but not what's under it.
4881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4884 // See if the value being truncated is already sign extended. If so, just
4885 // eliminate the trunc/sext pair.
4886 SDValue Op = N0.getOperand(0);
4887 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4888 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4889 unsigned DestBits = VT.getScalarType().getSizeInBits();
4890 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4892 if (OpBits == DestBits) {
4893 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4894 // bits, it is already ready.
4895 if (NumSignBits > DestBits-MidBits)
4897 } else if (OpBits < DestBits) {
4898 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4899 // bits, just sext from i32.
4900 if (NumSignBits > OpBits-MidBits)
4901 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4903 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4904 // bits, just truncate to i32.
4905 if (NumSignBits > OpBits-MidBits)
4906 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4909 // fold (sext (truncate x)) -> (sextinreg x).
4910 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4911 N0.getValueType())) {
4912 if (OpBits < DestBits)
4913 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4914 else if (OpBits > DestBits)
4915 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4917 DAG.getValueType(N0.getValueType()));
4921 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4922 // None of the supported targets knows how to perform load and sign extend
4923 // on vectors in one instruction. We only perform this transformation on
4925 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4926 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4927 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4928 bool DoXform = true;
4929 SmallVector<SDNode*, 4> SetCCs;
4930 if (!N0.hasOneUse())
4931 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4936 LN0->getBasePtr(), N0.getValueType(),
4937 LN0->getMemOperand());
4938 CombineTo(N, ExtLoad);
4939 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4940 N0.getValueType(), ExtLoad);
4941 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4942 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4948 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4949 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4950 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4951 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4953 EVT MemVT = LN0->getMemoryVT();
4954 if ((!LegalOperations && !LN0->isVolatile()) ||
4955 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4956 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4958 LN0->getBasePtr(), MemVT,
4959 LN0->getMemOperand());
4960 CombineTo(N, ExtLoad);
4961 CombineTo(N0.getNode(),
4962 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4963 N0.getValueType(), ExtLoad),
4964 ExtLoad.getValue(1));
4965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4969 // fold (sext (and/or/xor (load x), cst)) ->
4970 // (and/or/xor (sextload x), (sext cst))
4971 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4972 N0.getOpcode() == ISD::XOR) &&
4973 isa<LoadSDNode>(N0.getOperand(0)) &&
4974 N0.getOperand(1).getOpcode() == ISD::Constant &&
4975 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4976 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4977 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4978 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4979 bool DoXform = true;
4980 SmallVector<SDNode*, 4> SetCCs;
4981 if (!N0.hasOneUse())
4982 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4986 LN0->getChain(), LN0->getBasePtr(),
4988 LN0->getMemOperand());
4989 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4990 Mask = Mask.sext(VT.getSizeInBits());
4991 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4992 ExtLoad, DAG.getConstant(Mask, VT));
4993 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4994 SDLoc(N0.getOperand(0)),
4995 N0.getOperand(0).getValueType(), ExtLoad);
4997 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4998 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5005 if (N0.getOpcode() == ISD::SETCC) {
5006 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5007 // Only do this before legalize for now.
5008 if (VT.isVector() && !LegalOperations &&
5009 TLI.getBooleanContents(true) ==
5010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5011 EVT N0VT = N0.getOperand(0).getValueType();
5012 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5013 // of the same size as the compared operands. Only optimize sext(setcc())
5014 // if this is the case.
5015 EVT SVT = getSetCCResultType(N0VT);
5017 // We know that the # elements of the results is the same as the
5018 // # elements of the compare (and the # elements of the compare result
5019 // for that matter). Check to see that they are the same size. If so,
5020 // we know that the element size of the sext'd result matches the
5021 // element size of the compare operands.
5022 if (VT.getSizeInBits() == SVT.getSizeInBits())
5023 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5025 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5027 // If the desired elements are smaller or larger than the source
5028 // elements we can use a matching integer vector type and then
5029 // truncate/sign extend
5030 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5031 if (SVT == MatchingVectorType) {
5032 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5033 N0.getOperand(0), N0.getOperand(1),
5034 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5035 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5039 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5040 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5042 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5044 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5045 NegOne, DAG.getConstant(0, VT),
5046 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5047 if (SCC.getNode()) return SCC;
5049 if (!VT.isVector()) {
5050 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5051 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5053 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5054 SDValue SetCC = DAG.getSetCC(DL,
5056 N0.getOperand(0), N0.getOperand(1), CC);
5057 EVT SelectVT = getSetCCResultType(VT);
5058 return DAG.getSelect(DL, VT,
5059 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5060 NegOne, DAG.getConstant(0, VT));
5066 // fold (sext x) -> (zext x) if the sign bit is known zero.
5067 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5068 DAG.SignBitIsZero(N0))
5069 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5074 // isTruncateOf - If N is a truncate of some other value, return true, record
5075 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5076 // This function computes KnownZero to avoid a duplicated call to
5077 // ComputeMaskedBits in the caller.
5078 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5081 if (N->getOpcode() == ISD::TRUNCATE) {
5082 Op = N->getOperand(0);
5083 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5087 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5088 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5091 SDValue Op0 = N->getOperand(0);
5092 SDValue Op1 = N->getOperand(1);
5093 assert(Op0.getValueType() == Op1.getValueType());
5095 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5096 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5097 if (COp0 && COp0->isNullValue())
5099 else if (COp1 && COp1->isNullValue())
5104 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5106 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5112 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5113 SDValue N0 = N->getOperand(0);
5114 EVT VT = N->getValueType(0);
5116 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5118 return SDValue(Res, 0);
5120 // fold (zext (zext x)) -> (zext x)
5121 // fold (zext (aext x)) -> (zext x)
5122 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5123 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5126 // fold (zext (truncate x)) -> (zext x) or
5127 // (zext (truncate x)) -> (truncate x)
5128 // This is valid when the truncated bits of x are already zero.
5129 // FIXME: We should extend this to work for vectors too.
5132 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5133 APInt TruncatedBits =
5134 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5135 APInt(Op.getValueSizeInBits(), 0) :
5136 APInt::getBitsSet(Op.getValueSizeInBits(),
5137 N0.getValueSizeInBits(),
5138 std::min(Op.getValueSizeInBits(),
5139 VT.getSizeInBits()));
5140 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5141 if (VT.bitsGT(Op.getValueType()))
5142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5143 if (VT.bitsLT(Op.getValueType()))
5144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5150 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5151 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5152 if (N0.getOpcode() == ISD::TRUNCATE) {
5153 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5154 if (NarrowLoad.getNode()) {
5155 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5156 if (NarrowLoad.getNode() != N0.getNode()) {
5157 CombineTo(N0.getNode(), NarrowLoad);
5158 // CombineTo deleted the truncate, if needed, but not what's under it.
5161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5165 // fold (zext (truncate x)) -> (and x, mask)
5166 if (N0.getOpcode() == ISD::TRUNCATE &&
5167 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5169 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5170 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5171 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5172 if (NarrowLoad.getNode()) {
5173 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5174 if (NarrowLoad.getNode() != N0.getNode()) {
5175 CombineTo(N0.getNode(), NarrowLoad);
5176 // CombineTo deleted the truncate, if needed, but not what's under it.
5179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5182 SDValue Op = N0.getOperand(0);
5183 if (Op.getValueType().bitsLT(VT)) {
5184 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5185 AddToWorkList(Op.getNode());
5186 } else if (Op.getValueType().bitsGT(VT)) {
5187 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5188 AddToWorkList(Op.getNode());
5190 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5191 N0.getValueType().getScalarType());
5194 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5195 // if either of the casts is not free.
5196 if (N0.getOpcode() == ISD::AND &&
5197 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5198 N0.getOperand(1).getOpcode() == ISD::Constant &&
5199 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5200 N0.getValueType()) ||
5201 !TLI.isZExtFree(N0.getValueType(), VT))) {
5202 SDValue X = N0.getOperand(0).getOperand(0);
5203 if (X.getValueType().bitsLT(VT)) {
5204 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5205 } else if (X.getValueType().bitsGT(VT)) {
5206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5208 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5209 Mask = Mask.zext(VT.getSizeInBits());
5210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5211 X, DAG.getConstant(Mask, VT));
5214 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5215 // None of the supported targets knows how to perform load and vector_zext
5216 // on vectors in one instruction. We only perform this transformation on
5218 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5219 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5220 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5221 bool DoXform = true;
5222 SmallVector<SDNode*, 4> SetCCs;
5223 if (!N0.hasOneUse())
5224 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5227 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5229 LN0->getBasePtr(), N0.getValueType(),
5230 LN0->getMemOperand());
5231 CombineTo(N, ExtLoad);
5232 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5233 N0.getValueType(), ExtLoad);
5234 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5236 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5238 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5242 // fold (zext (and/or/xor (load x), cst)) ->
5243 // (and/or/xor (zextload x), (zext cst))
5244 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5245 N0.getOpcode() == ISD::XOR) &&
5246 isa<LoadSDNode>(N0.getOperand(0)) &&
5247 N0.getOperand(1).getOpcode() == ISD::Constant &&
5248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5249 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5250 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5251 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5252 bool DoXform = true;
5253 SmallVector<SDNode*, 4> SetCCs;
5254 if (!N0.hasOneUse())
5255 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5258 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5259 LN0->getChain(), LN0->getBasePtr(),
5261 LN0->getMemOperand());
5262 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5263 Mask = Mask.zext(VT.getSizeInBits());
5264 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5265 ExtLoad, DAG.getConstant(Mask, VT));
5266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5267 SDLoc(N0.getOperand(0)),
5268 N0.getOperand(0).getValueType(), ExtLoad);
5270 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5271 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5273 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5278 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5279 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5280 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5281 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5282 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5283 EVT MemVT = LN0->getMemoryVT();
5284 if ((!LegalOperations && !LN0->isVolatile()) ||
5285 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5286 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5288 LN0->getBasePtr(), MemVT,
5289 LN0->getMemOperand());
5290 CombineTo(N, ExtLoad);
5291 CombineTo(N0.getNode(),
5292 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5294 ExtLoad.getValue(1));
5295 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5299 if (N0.getOpcode() == ISD::SETCC) {
5300 if (!LegalOperations && VT.isVector() &&
5301 N0.getValueType().getVectorElementType() == MVT::i1) {
5302 EVT N0VT = N0.getOperand(0).getValueType();
5303 if (getSetCCResultType(N0VT) == N0.getValueType())
5306 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5307 // Only do this before legalize for now.
5308 EVT EltVT = VT.getVectorElementType();
5309 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5310 DAG.getConstant(1, EltVT));
5311 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5312 // We know that the # elements of the results is the same as the
5313 // # elements of the compare (and the # elements of the compare result
5314 // for that matter). Check to see that they are the same size. If so,
5315 // we know that the element size of the sext'd result matches the
5316 // element size of the compare operands.
5317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5318 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5320 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5321 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5322 &OneOps[0], OneOps.size()));
5324 // If the desired elements are smaller or larger than the source
5325 // elements we can use a matching integer vector type and then
5326 // truncate/sign extend
5327 EVT MatchingElementType =
5328 EVT::getIntegerVT(*DAG.getContext(),
5329 N0VT.getScalarType().getSizeInBits());
5330 EVT MatchingVectorType =
5331 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5332 N0VT.getVectorNumElements());
5334 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5336 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5337 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5338 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5339 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5340 &OneOps[0], OneOps.size()));
5343 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5345 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5346 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5348 if (SCC.getNode()) return SCC;
5351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5353 isa<ConstantSDNode>(N0.getOperand(1)) &&
5354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5356 SDValue ShAmt = N0.getOperand(1);
5357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5358 if (N0.getOpcode() == ISD::SHL) {
5359 SDValue InnerZExt = N0.getOperand(0);
5360 // If the original shl may be shifting out bits, do not perform this
5362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364 if (ShAmtVal > KnownZeroBits)
5370 // Ensure that the shift amount is wide enough for the shifted value.
5371 if (VT.getSizeInBits() >= 256)
5372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5374 return DAG.getNode(N0.getOpcode(), DL, VT,
5375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383 SDValue N0 = N->getOperand(0);
5384 EVT VT = N->getValueType(0);
5386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5388 return SDValue(Res, 0);
5390 // fold (aext (aext x)) -> (aext x)
5391 // fold (aext (zext x)) -> (zext x)
5392 // fold (aext (sext x)) -> (sext x)
5393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5394 N0.getOpcode() == ISD::ZERO_EXTEND ||
5395 N0.getOpcode() == ISD::SIGN_EXTEND)
5396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400 if (N0.getOpcode() == ISD::TRUNCATE) {
5401 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402 if (NarrowLoad.getNode()) {
5403 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404 if (NarrowLoad.getNode() != N0.getNode()) {
5405 CombineTo(N0.getNode(), NarrowLoad);
5406 // CombineTo deleted the truncate, if needed, but not what's under it.
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5413 // fold (aext (truncate x))
5414 if (N0.getOpcode() == ISD::TRUNCATE) {
5415 SDValue TruncOp = N0.getOperand(0);
5416 if (TruncOp.getValueType() == VT)
5417 return TruncOp; // x iff x size == zext size.
5418 if (TruncOp.getValueType().bitsGT(VT))
5419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5423 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424 // if the trunc is not free.
5425 if (N0.getOpcode() == ISD::AND &&
5426 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5427 N0.getOperand(1).getOpcode() == ISD::Constant &&
5428 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429 N0.getValueType())) {
5430 SDValue X = N0.getOperand(0).getOperand(0);
5431 if (X.getValueType().bitsLT(VT)) {
5432 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5433 } else if (X.getValueType().bitsGT(VT)) {
5434 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5436 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5437 Mask = Mask.zext(VT.getSizeInBits());
5438 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5439 X, DAG.getConstant(Mask, VT));
5442 // fold (aext (load x)) -> (aext (truncate (extload x)))
5443 // None of the supported targets knows how to perform load and any_ext
5444 // on vectors in one instruction. We only perform this transformation on
5446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5447 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5448 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5449 bool DoXform = true;
5450 SmallVector<SDNode*, 4> SetCCs;
5451 if (!N0.hasOneUse())
5452 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5454 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5455 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5457 LN0->getBasePtr(), N0.getValueType(),
5458 LN0->getMemOperand());
5459 CombineTo(N, ExtLoad);
5460 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5461 N0.getValueType(), ExtLoad);
5462 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5463 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5469 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5470 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5471 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5472 if (N0.getOpcode() == ISD::LOAD &&
5473 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5475 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5476 EVT MemVT = LN0->getMemoryVT();
5477 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5478 VT, LN0->getChain(), LN0->getBasePtr(),
5479 MemVT, LN0->getMemOperand());
5480 CombineTo(N, ExtLoad);
5481 CombineTo(N0.getNode(),
5482 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5483 N0.getValueType(), ExtLoad),
5484 ExtLoad.getValue(1));
5485 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5488 if (N0.getOpcode() == ISD::SETCC) {
5489 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5490 // Only do this before legalize for now.
5491 if (VT.isVector() && !LegalOperations) {
5492 EVT N0VT = N0.getOperand(0).getValueType();
5493 // We know that the # elements of the results is the same as the
5494 // # elements of the compare (and the # elements of the compare result
5495 // for that matter). Check to see that they are the same size. If so,
5496 // we know that the element size of the sext'd result matches the
5497 // element size of the compare operands.
5498 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5499 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5501 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5502 // If the desired elements are smaller or larger than the source
5503 // elements we can use a matching integer vector type and then
5504 // truncate/sign extend
5506 EVT MatchingElementType =
5507 EVT::getIntegerVT(*DAG.getContext(),
5508 N0VT.getScalarType().getSizeInBits());
5509 EVT MatchingVectorType =
5510 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5511 N0VT.getVectorNumElements());
5513 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5515 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5516 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5520 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5522 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5523 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5524 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5532 /// GetDemandedBits - See if the specified operand can be simplified with the
5533 /// knowledge that only the bits specified by Mask are used. If so, return the
5534 /// simpler operand, otherwise return a null SDValue.
5535 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5536 switch (V.getOpcode()) {
5538 case ISD::Constant: {
5539 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5540 assert(CV != 0 && "Const value should be ConstSDNode.");
5541 const APInt &CVal = CV->getAPIntValue();
5542 APInt NewVal = CVal & Mask;
5544 return DAG.getConstant(NewVal, V.getValueType());
5549 // If the LHS or RHS don't contribute bits to the or, drop them.
5550 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5551 return V.getOperand(1);
5552 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5553 return V.getOperand(0);
5556 // Only look at single-use SRLs.
5557 if (!V.getNode()->hasOneUse())
5559 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5560 // See if we can recursively simplify the LHS.
5561 unsigned Amt = RHSC->getZExtValue();
5563 // Watch out for shift count overflow though.
5564 if (Amt >= Mask.getBitWidth()) break;
5565 APInt NewMask = Mask << Amt;
5566 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5567 if (SimplifyLHS.getNode())
5568 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5569 SimplifyLHS, V.getOperand(1));
5575 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5576 /// bits and then truncated to a narrower type and where N is a multiple
5577 /// of number of bits of the narrower type, transform it to a narrower load
5578 /// from address + N / num of bits of new type. If the result is to be
5579 /// extended, also fold the extension to form a extending load.
5580 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5581 unsigned Opc = N->getOpcode();
5583 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5584 SDValue N0 = N->getOperand(0);
5585 EVT VT = N->getValueType(0);
5588 // This transformation isn't valid for vector loads.
5592 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5594 if (Opc == ISD::SIGN_EXTEND_INREG) {
5595 ExtType = ISD::SEXTLOAD;
5596 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5597 } else if (Opc == ISD::SRL) {
5598 // Another special-case: SRL is basically zero-extending a narrower value.
5599 ExtType = ISD::ZEXTLOAD;
5601 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5602 if (!N01) return SDValue();
5603 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5604 VT.getSizeInBits() - N01->getZExtValue());
5606 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5609 unsigned EVTBits = ExtVT.getSizeInBits();
5611 // Do not generate loads of non-round integer types since these can
5612 // be expensive (and would be wrong if the type is not byte sized).
5613 if (!ExtVT.isRound())
5617 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5618 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5619 ShAmt = N01->getZExtValue();
5620 // Is the shift amount a multiple of size of VT?
5621 if ((ShAmt & (EVTBits-1)) == 0) {
5622 N0 = N0.getOperand(0);
5623 // Is the load width a multiple of size of VT?
5624 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5628 // At this point, we must have a load or else we can't do the transform.
5629 if (!isa<LoadSDNode>(N0)) return SDValue();
5631 // Because a SRL must be assumed to *need* to zero-extend the high bits
5632 // (as opposed to anyext the high bits), we can't combine the zextload
5633 // lowering of SRL and an sextload.
5634 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5637 // If the shift amount is larger than the input type then we're not
5638 // accessing any of the loaded bytes. If the load was a zextload/extload
5639 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5640 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5645 // If the load is shifted left (and the result isn't shifted back right),
5646 // we can fold the truncate through the shift.
5647 unsigned ShLeftAmt = 0;
5648 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5649 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5650 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5651 ShLeftAmt = N01->getZExtValue();
5652 N0 = N0.getOperand(0);
5656 // If we haven't found a load, we can't narrow it. Don't transform one with
5657 // multiple uses, this would require adding a new load.
5658 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5661 // Don't change the width of a volatile load.
5662 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5663 if (LN0->isVolatile())
5666 // Verify that we are actually reducing a load width here.
5667 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5670 // For the transform to be legal, the load must produce only two values
5671 // (the value loaded and the chain). Don't transform a pre-increment
5672 // load, for example, which produces an extra value. Otherwise the
5673 // transformation is not equivalent, and the downstream logic to replace
5674 // uses gets things wrong.
5675 if (LN0->getNumValues() > 2)
5678 // If the load that we're shrinking is an extload and we're not just
5679 // discarding the extension we can't simply shrink the load. Bail.
5680 // TODO: It would be possible to merge the extensions in some cases.
5681 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5682 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5685 EVT PtrType = N0.getOperand(1).getValueType();
5687 if (PtrType == MVT::Untyped || PtrType.isExtended())
5688 // It's not possible to generate a constant of extended or untyped type.
5691 // For big endian targets, we need to adjust the offset to the pointer to
5692 // load the correct bytes.
5693 if (TLI.isBigEndian()) {
5694 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5695 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5696 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5699 uint64_t PtrOff = ShAmt / 8;
5700 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5701 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5702 PtrType, LN0->getBasePtr(),
5703 DAG.getConstant(PtrOff, PtrType));
5704 AddToWorkList(NewPtr.getNode());
5707 if (ExtType == ISD::NON_EXTLOAD)
5708 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5709 LN0->getPointerInfo().getWithOffset(PtrOff),
5710 LN0->isVolatile(), LN0->isNonTemporal(),
5711 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5713 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5714 LN0->getPointerInfo().getWithOffset(PtrOff),
5715 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5716 NewAlign, LN0->getTBAAInfo());
5718 // Replace the old load's chain with the new load's chain.
5719 WorkListRemover DeadNodes(*this);
5720 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5722 // Shift the result left, if we've swallowed a left shift.
5723 SDValue Result = Load;
5724 if (ShLeftAmt != 0) {
5725 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5726 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5728 // If the shift amount is as large as the result size (but, presumably,
5729 // no larger than the source) then the useful bits of the result are
5730 // zero; we can't simply return the shortened shift, because the result
5731 // of that operation is undefined.
5732 if (ShLeftAmt >= VT.getSizeInBits())
5733 Result = DAG.getConstant(0, VT);
5735 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5736 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5739 // Return the new loaded value.
5743 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5744 SDValue N0 = N->getOperand(0);
5745 SDValue N1 = N->getOperand(1);
5746 EVT VT = N->getValueType(0);
5747 EVT EVT = cast<VTSDNode>(N1)->getVT();
5748 unsigned VTBits = VT.getScalarType().getSizeInBits();
5749 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5751 // fold (sext_in_reg c1) -> c1
5752 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5753 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5755 // If the input is already sign extended, just drop the extension.
5756 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5759 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5760 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5761 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5762 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5763 N0.getOperand(0), N1);
5765 // fold (sext_in_reg (sext x)) -> (sext x)
5766 // fold (sext_in_reg (aext x)) -> (sext x)
5767 // if x is small enough.
5768 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5769 SDValue N00 = N0.getOperand(0);
5770 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5771 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5772 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5775 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5776 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5777 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5779 // fold operands of sext_in_reg based on knowledge that the top bits are not
5781 if (SimplifyDemandedBits(SDValue(N, 0)))
5782 return SDValue(N, 0);
5784 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5785 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5786 SDValue NarrowLoad = ReduceLoadWidth(N);
5787 if (NarrowLoad.getNode())
5790 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5791 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5792 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5793 if (N0.getOpcode() == ISD::SRL) {
5794 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5795 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5796 // We can turn this into an SRA iff the input to the SRL is already sign
5798 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5799 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5800 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5801 N0.getOperand(0), N0.getOperand(1));
5805 // fold (sext_inreg (extload x)) -> (sextload x)
5806 if (ISD::isEXTLoad(N0.getNode()) &&
5807 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5808 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5809 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5810 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5811 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5812 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5814 LN0->getBasePtr(), EVT,
5815 LN0->getMemOperand());
5816 CombineTo(N, ExtLoad);
5817 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5818 AddToWorkList(ExtLoad.getNode());
5819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5821 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5822 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5824 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5825 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5826 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5827 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5828 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5830 LN0->getBasePtr(), EVT,
5831 LN0->getMemOperand());
5832 CombineTo(N, ExtLoad);
5833 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5837 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5838 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5839 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5840 N0.getOperand(1), false);
5841 if (BSwap.getNode() != 0)
5842 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5846 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5847 // into a build_vector.
5848 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5849 SmallVector<SDValue, 8> Elts;
5850 unsigned NumElts = N0->getNumOperands();
5851 unsigned ShAmt = VTBits - EVTBits;
5853 for (unsigned i = 0; i != NumElts; ++i) {
5854 SDValue Op = N0->getOperand(i);
5855 if (Op->getOpcode() == ISD::UNDEF) {
5860 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5861 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5862 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5863 Op.getValueType()));
5866 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5872 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5873 SDValue N0 = N->getOperand(0);
5874 EVT VT = N->getValueType(0);
5875 bool isLE = TLI.isLittleEndian();
5878 if (N0.getValueType() == N->getValueType(0))
5880 // fold (truncate c1) -> c1
5881 if (isa<ConstantSDNode>(N0))
5882 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5883 // fold (truncate (truncate x)) -> (truncate x)
5884 if (N0.getOpcode() == ISD::TRUNCATE)
5885 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5886 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5887 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5888 N0.getOpcode() == ISD::SIGN_EXTEND ||
5889 N0.getOpcode() == ISD::ANY_EXTEND) {
5890 if (N0.getOperand(0).getValueType().bitsLT(VT))
5891 // if the source is smaller than the dest, we still need an extend
5892 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5894 if (N0.getOperand(0).getValueType().bitsGT(VT))
5895 // if the source is larger than the dest, than we just need the truncate
5896 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5897 // if the source and dest are the same type, we can drop both the extend
5898 // and the truncate.
5899 return N0.getOperand(0);
5902 // Fold extract-and-trunc into a narrow extract. For example:
5903 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5904 // i32 y = TRUNCATE(i64 x)
5906 // v16i8 b = BITCAST (v2i64 val)
5907 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5909 // Note: We only run this optimization after type legalization (which often
5910 // creates this pattern) and before operation legalization after which
5911 // we need to be more careful about the vector instructions that we generate.
5912 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5913 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5915 EVT VecTy = N0.getOperand(0).getValueType();
5916 EVT ExTy = N0.getValueType();
5917 EVT TrTy = N->getValueType(0);
5919 unsigned NumElem = VecTy.getVectorNumElements();
5920 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5922 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5923 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5925 SDValue EltNo = N0->getOperand(1);
5926 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5927 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5928 EVT IndexTy = TLI.getVectorIdxTy();
5929 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5931 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5932 NVT, N0.getOperand(0));
5934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5936 DAG.getConstant(Index, IndexTy));
5940 // Fold a series of buildvector, bitcast, and truncate if possible.
5942 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5943 // (2xi32 (buildvector x, y)).
5944 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5945 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5946 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5947 N0.getOperand(0).hasOneUse()) {
5949 SDValue BuildVect = N0.getOperand(0);
5950 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5951 EVT TruncVecEltTy = VT.getVectorElementType();
5953 // Check that the element types match.
5954 if (BuildVectEltTy == TruncVecEltTy) {
5955 // Now we only need to compute the offset of the truncated elements.
5956 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5957 unsigned TruncVecNumElts = VT.getVectorNumElements();
5958 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5960 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5961 "Invalid number of elements");
5963 SmallVector<SDValue, 8> Opnds;
5964 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5965 Opnds.push_back(BuildVect.getOperand(i));
5967 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5972 // See if we can simplify the input to this truncate through knowledge that
5973 // only the low bits are being used.
5974 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5975 // Currently we only perform this optimization on scalars because vectors
5976 // may have different active low bits.
5977 if (!VT.isVector()) {
5979 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5980 VT.getSizeInBits()));
5981 if (Shorter.getNode())
5982 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5984 // fold (truncate (load x)) -> (smaller load x)
5985 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5986 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5987 SDValue Reduced = ReduceLoadWidth(N);
5988 if (Reduced.getNode())
5990 // Handle the case where the load remains an extending load even
5991 // after truncation.
5992 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5993 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5994 if (!LN0->isVolatile() &&
5995 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5996 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5997 VT, LN0->getChain(), LN0->getBasePtr(),
5999 LN0->getMemOperand());
6000 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6005 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6006 // where ... are all 'undef'.
6007 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6008 SmallVector<EVT, 8> VTs;
6011 unsigned NumDefs = 0;
6013 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6014 SDValue X = N0.getOperand(i);
6015 if (X.getOpcode() != ISD::UNDEF) {
6020 // Stop if more than one members are non-undef.
6023 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6024 VT.getVectorElementType(),
6025 X.getValueType().getVectorNumElements()));
6029 return DAG.getUNDEF(VT);
6032 assert(V.getNode() && "The single defined operand is empty!");
6033 SmallVector<SDValue, 8> Opnds;
6034 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6036 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6039 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6040 AddToWorkList(NV.getNode());
6041 Opnds.push_back(NV);
6043 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6044 &Opnds[0], Opnds.size());
6048 // Simplify the operands using demanded-bits information.
6049 if (!VT.isVector() &&
6050 SimplifyDemandedBits(SDValue(N, 0)))
6051 return SDValue(N, 0);
6056 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6057 SDValue Elt = N->getOperand(i);
6058 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6059 return Elt.getNode();
6060 return Elt.getOperand(Elt.getResNo()).getNode();
6063 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6064 /// if load locations are consecutive.
6065 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6066 assert(N->getOpcode() == ISD::BUILD_PAIR);
6068 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6069 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6070 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6071 LD1->getAddressSpace() != LD2->getAddressSpace())
6073 EVT LD1VT = LD1->getValueType(0);
6075 if (ISD::isNON_EXTLoad(LD2) &&
6077 // If both are volatile this would reduce the number of volatile loads.
6078 // If one is volatile it might be ok, but play conservative and bail out.
6079 !LD1->isVolatile() &&
6080 !LD2->isVolatile() &&
6081 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6082 unsigned Align = LD1->getAlignment();
6083 unsigned NewAlign = TLI.getDataLayout()->
6084 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6086 if (NewAlign <= Align &&
6087 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6088 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6089 LD1->getBasePtr(), LD1->getPointerInfo(),
6090 false, false, false, Align);
6096 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6097 SDValue N0 = N->getOperand(0);
6098 EVT VT = N->getValueType(0);
6100 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6101 // Only do this before legalize, since afterward the target may be depending
6102 // on the bitconvert.
6103 // First check to see if this is all constant.
6105 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6107 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6109 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6110 assert(!DestEltVT.isVector() &&
6111 "Element type of vector ValueType must not be vector!");
6113 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6116 // If the input is a constant, let getNode fold it.
6117 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6118 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6119 if (Res.getNode() != N) {
6120 if (!LegalOperations ||
6121 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6124 // Folding it resulted in an illegal node, and it's too late to
6125 // do that. Clean up the old node and forego the transformation.
6126 // Ideally this won't happen very often, because instcombine
6127 // and the earlier dagcombine runs (where illegal nodes are
6128 // permitted) should have folded most of them already.
6129 DAG.DeleteNode(Res.getNode());
6133 // (conv (conv x, t1), t2) -> (conv x, t2)
6134 if (N0.getOpcode() == ISD::BITCAST)
6135 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6138 // fold (conv (load x)) -> (load (conv*)x)
6139 // If the resultant load doesn't need a higher alignment than the original!
6140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6141 // Do not change the width of a volatile load.
6142 !cast<LoadSDNode>(N0)->isVolatile() &&
6143 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6144 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6146 unsigned Align = TLI.getDataLayout()->
6147 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6148 unsigned OrigAlign = LN0->getAlignment();
6150 if (Align <= OrigAlign) {
6151 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6152 LN0->getBasePtr(), LN0->getPointerInfo(),
6153 LN0->isVolatile(), LN0->isNonTemporal(),
6154 LN0->isInvariant(), OrigAlign,
6155 LN0->getTBAAInfo());
6157 CombineTo(N0.getNode(),
6158 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6159 N0.getValueType(), Load),
6165 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6166 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6167 // This often reduces constant pool loads.
6168 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6169 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6170 N0.getNode()->hasOneUse() && VT.isInteger() &&
6171 !VT.isVector() && !N0.getValueType().isVector()) {
6172 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6174 AddToWorkList(NewConv.getNode());
6176 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6177 if (N0.getOpcode() == ISD::FNEG)
6178 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6179 NewConv, DAG.getConstant(SignBit, VT));
6180 assert(N0.getOpcode() == ISD::FABS);
6181 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6182 NewConv, DAG.getConstant(~SignBit, VT));
6185 // fold (bitconvert (fcopysign cst, x)) ->
6186 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6187 // Note that we don't handle (copysign x, cst) because this can always be
6188 // folded to an fneg or fabs.
6189 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6190 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6191 VT.isInteger() && !VT.isVector()) {
6192 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6193 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6194 if (isTypeLegal(IntXVT)) {
6195 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6196 IntXVT, N0.getOperand(1));
6197 AddToWorkList(X.getNode());
6199 // If X has a different width than the result/lhs, sext it or truncate it.
6200 unsigned VTWidth = VT.getSizeInBits();
6201 if (OrigXWidth < VTWidth) {
6202 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6203 AddToWorkList(X.getNode());
6204 } else if (OrigXWidth > VTWidth) {
6205 // To get the sign bit in the right place, we have to shift it right
6206 // before truncating.
6207 X = DAG.getNode(ISD::SRL, SDLoc(X),
6208 X.getValueType(), X,
6209 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6210 AddToWorkList(X.getNode());
6211 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6212 AddToWorkList(X.getNode());
6215 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6216 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6217 X, DAG.getConstant(SignBit, VT));
6218 AddToWorkList(X.getNode());
6220 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6221 VT, N0.getOperand(0));
6222 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6223 Cst, DAG.getConstant(~SignBit, VT));
6224 AddToWorkList(Cst.getNode());
6226 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6230 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6231 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6232 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6233 if (CombineLD.getNode())
6240 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6241 EVT VT = N->getValueType(0);
6242 return CombineConsecutiveLoads(N, VT);
6245 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6246 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6247 /// destination element value type.
6248 SDValue DAGCombiner::
6249 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6250 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6252 // If this is already the right type, we're done.
6253 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6255 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6256 unsigned DstBitSize = DstEltVT.getSizeInBits();
6258 // If this is a conversion of N elements of one type to N elements of another
6259 // type, convert each element. This handles FP<->INT cases.
6260 if (SrcBitSize == DstBitSize) {
6261 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6262 BV->getValueType(0).getVectorNumElements());
6264 // Due to the FP element handling below calling this routine recursively,
6265 // we can end up with a scalar-to-vector node here.
6266 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6267 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6268 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6269 DstEltVT, BV->getOperand(0)));
6271 SmallVector<SDValue, 8> Ops;
6272 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6273 SDValue Op = BV->getOperand(i);
6274 // If the vector element type is not legal, the BUILD_VECTOR operands
6275 // are promoted and implicitly truncated. Make that explicit here.
6276 if (Op.getValueType() != SrcEltVT)
6277 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6278 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6280 AddToWorkList(Ops.back().getNode());
6282 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6283 &Ops[0], Ops.size());
6286 // Otherwise, we're growing or shrinking the elements. To avoid having to
6287 // handle annoying details of growing/shrinking FP values, we convert them to
6289 if (SrcEltVT.isFloatingPoint()) {
6290 // Convert the input float vector to a int vector where the elements are the
6292 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6293 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6294 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6298 // Now we know the input is an integer vector. If the output is a FP type,
6299 // convert to integer first, then to FP of the right size.
6300 if (DstEltVT.isFloatingPoint()) {
6301 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6302 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6303 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6305 // Next, convert to FP elements of the same size.
6306 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6309 // Okay, we know the src/dst types are both integers of differing types.
6310 // Handling growing first.
6311 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6312 if (SrcBitSize < DstBitSize) {
6313 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6315 SmallVector<SDValue, 8> Ops;
6316 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6317 i += NumInputsPerOutput) {
6318 bool isLE = TLI.isLittleEndian();
6319 APInt NewBits = APInt(DstBitSize, 0);
6320 bool EltIsUndef = true;
6321 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6322 // Shift the previously computed bits over.
6323 NewBits <<= SrcBitSize;
6324 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6325 if (Op.getOpcode() == ISD::UNDEF) continue;
6328 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6329 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6333 Ops.push_back(DAG.getUNDEF(DstEltVT));
6335 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6338 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6339 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6340 &Ops[0], Ops.size());
6343 // Finally, this must be the case where we are shrinking elements: each input
6344 // turns into multiple outputs.
6345 bool isS2V = ISD::isScalarToVector(BV);
6346 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6347 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6348 NumOutputsPerInput*BV->getNumOperands());
6349 SmallVector<SDValue, 8> Ops;
6351 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6352 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6353 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6354 Ops.push_back(DAG.getUNDEF(DstEltVT));
6358 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6359 getAPIntValue().zextOrTrunc(SrcBitSize);
6361 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6362 APInt ThisVal = OpVal.trunc(DstBitSize);
6363 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6364 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6365 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6366 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6368 OpVal = OpVal.lshr(DstBitSize);
6371 // For big endian targets, swap the order of the pieces of each element.
6372 if (TLI.isBigEndian())
6373 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6376 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6377 &Ops[0], Ops.size());
6380 SDValue DAGCombiner::visitFADD(SDNode *N) {
6381 SDValue N0 = N->getOperand(0);
6382 SDValue N1 = N->getOperand(1);
6383 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6384 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6385 EVT VT = N->getValueType(0);
6388 if (VT.isVector()) {
6389 SDValue FoldedVOp = SimplifyVBinOp(N);
6390 if (FoldedVOp.getNode()) return FoldedVOp;
6393 // fold (fadd c1, c2) -> c1 + c2
6395 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6396 // canonicalize constant to RHS
6397 if (N0CFP && !N1CFP)
6398 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6399 // fold (fadd A, 0) -> A
6400 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6401 N1CFP->getValueAPF().isZero())
6403 // fold (fadd A, (fneg B)) -> (fsub A, B)
6404 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6405 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6406 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6407 GetNegatedExpression(N1, DAG, LegalOperations));
6408 // fold (fadd (fneg A), B) -> (fsub B, A)
6409 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6410 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6411 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6412 GetNegatedExpression(N0, DAG, LegalOperations));
6414 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6415 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6416 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6417 isa<ConstantFPSDNode>(N0.getOperand(1)))
6418 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6419 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6420 N0.getOperand(1), N1));
6422 // No FP constant should be created after legalization as Instruction
6423 // Selection pass has hard time in dealing with FP constant.
6425 // We don't need test this condition for transformation like following, as
6426 // the DAG being transformed implies it is legal to take FP constant as
6429 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6431 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6433 // If allow, fold (fadd (fneg x), x) -> 0.0
6434 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6435 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6436 return DAG.getConstantFP(0.0, VT);
6438 // If allow, fold (fadd x, (fneg x)) -> 0.0
6439 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6440 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6441 return DAG.getConstantFP(0.0, VT);
6443 // In unsafe math mode, we can fold chains of FADD's of the same value
6444 // into multiplications. This transform is not safe in general because
6445 // we are reducing the number of rounding steps.
6446 if (DAG.getTarget().Options.UnsafeFPMath &&
6447 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6449 if (N0.getOpcode() == ISD::FMUL) {
6450 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6451 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6453 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6454 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6455 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6457 DAG.getConstantFP(1.0, VT));
6458 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6462 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6463 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6464 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6466 DAG.getConstantFP(1.0, VT));
6467 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6471 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6472 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6473 N1.getOperand(0) == N1.getOperand(1) &&
6474 N0.getOperand(1) == N1.getOperand(0)) {
6475 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6477 DAG.getConstantFP(2.0, VT));
6478 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6479 N0.getOperand(1), NewCFP);
6482 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6483 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6484 N1.getOperand(0) == N1.getOperand(1) &&
6485 N0.getOperand(0) == N1.getOperand(0)) {
6486 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6488 DAG.getConstantFP(2.0, VT));
6489 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6490 N0.getOperand(0), NewCFP);
6494 if (N1.getOpcode() == ISD::FMUL) {
6495 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6496 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6498 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6499 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6500 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6502 DAG.getConstantFP(1.0, VT));
6503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6507 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6508 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6509 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6511 DAG.getConstantFP(1.0, VT));
6512 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6517 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6518 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6519 N0.getOperand(0) == N0.getOperand(1) &&
6520 N1.getOperand(1) == N0.getOperand(0)) {
6521 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6523 DAG.getConstantFP(2.0, VT));
6524 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6525 N1.getOperand(1), NewCFP);
6528 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6529 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6530 N0.getOperand(0) == N0.getOperand(1) &&
6531 N1.getOperand(0) == N0.getOperand(0)) {
6532 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6534 DAG.getConstantFP(2.0, VT));
6535 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6536 N1.getOperand(0), NewCFP);
6540 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6541 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6542 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6543 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6544 (N0.getOperand(0) == N1))
6545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6546 N1, DAG.getConstantFP(3.0, VT));
6549 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6550 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6551 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6552 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6553 N1.getOperand(0) == N0)
6554 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6555 N0, DAG.getConstantFP(3.0, VT));
6558 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6559 if (AllowNewFpConst &&
6560 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6561 N0.getOperand(0) == N0.getOperand(1) &&
6562 N1.getOperand(0) == N1.getOperand(1) &&
6563 N0.getOperand(0) == N1.getOperand(0))
6564 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6566 DAG.getConstantFP(4.0, VT));
6569 // FADD -> FMA combines:
6570 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6571 DAG.getTarget().Options.UnsafeFPMath) &&
6572 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6573 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6575 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6576 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6577 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6578 N0.getOperand(0), N0.getOperand(1), N1);
6580 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6581 // Note: Commutes FADD operands.
6582 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6583 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6584 N1.getOperand(0), N1.getOperand(1), N0);
6590 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6591 SDValue N0 = N->getOperand(0);
6592 SDValue N1 = N->getOperand(1);
6593 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6594 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6595 EVT VT = N->getValueType(0);
6599 if (VT.isVector()) {
6600 SDValue FoldedVOp = SimplifyVBinOp(N);
6601 if (FoldedVOp.getNode()) return FoldedVOp;
6604 // fold (fsub c1, c2) -> c1-c2
6606 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6607 // fold (fsub A, 0) -> A
6608 if (DAG.getTarget().Options.UnsafeFPMath &&
6609 N1CFP && N1CFP->getValueAPF().isZero())
6611 // fold (fsub 0, B) -> -B
6612 if (DAG.getTarget().Options.UnsafeFPMath &&
6613 N0CFP && N0CFP->getValueAPF().isZero()) {
6614 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6615 return GetNegatedExpression(N1, DAG, LegalOperations);
6616 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6617 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6619 // fold (fsub A, (fneg B)) -> (fadd A, B)
6620 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6621 return DAG.getNode(ISD::FADD, dl, VT, N0,
6622 GetNegatedExpression(N1, DAG, LegalOperations));
6624 // If 'unsafe math' is enabled, fold
6625 // (fsub x, x) -> 0.0 &
6626 // (fsub x, (fadd x, y)) -> (fneg y) &
6627 // (fsub x, (fadd y, x)) -> (fneg y)
6628 if (DAG.getTarget().Options.UnsafeFPMath) {
6630 return DAG.getConstantFP(0.0f, VT);
6632 if (N1.getOpcode() == ISD::FADD) {
6633 SDValue N10 = N1->getOperand(0);
6634 SDValue N11 = N1->getOperand(1);
6636 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6637 &DAG.getTarget().Options))
6638 return GetNegatedExpression(N11, DAG, LegalOperations);
6640 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6641 &DAG.getTarget().Options))
6642 return GetNegatedExpression(N10, DAG, LegalOperations);
6646 // FSUB -> FMA combines:
6647 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6648 DAG.getTarget().Options.UnsafeFPMath) &&
6649 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6650 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6652 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6653 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6654 return DAG.getNode(ISD::FMA, dl, VT,
6655 N0.getOperand(0), N0.getOperand(1),
6656 DAG.getNode(ISD::FNEG, dl, VT, N1));
6658 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6659 // Note: Commutes FSUB operands.
6660 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6661 return DAG.getNode(ISD::FMA, dl, VT,
6662 DAG.getNode(ISD::FNEG, dl, VT,
6664 N1.getOperand(1), N0);
6666 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6667 if (N0.getOpcode() == ISD::FNEG &&
6668 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6669 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6670 SDValue N00 = N0.getOperand(0).getOperand(0);
6671 SDValue N01 = N0.getOperand(0).getOperand(1);
6672 return DAG.getNode(ISD::FMA, dl, VT,
6673 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6674 DAG.getNode(ISD::FNEG, dl, VT, N1));
6681 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6682 SDValue N0 = N->getOperand(0);
6683 SDValue N1 = N->getOperand(1);
6684 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6685 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6686 EVT VT = N->getValueType(0);
6687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6690 if (VT.isVector()) {
6691 SDValue FoldedVOp = SimplifyVBinOp(N);
6692 if (FoldedVOp.getNode()) return FoldedVOp;
6695 // fold (fmul c1, c2) -> c1*c2
6697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6698 // canonicalize constant to RHS
6699 if (N0CFP && !N1CFP)
6700 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6701 // fold (fmul A, 0) -> 0
6702 if (DAG.getTarget().Options.UnsafeFPMath &&
6703 N1CFP && N1CFP->getValueAPF().isZero())
6705 // fold (fmul A, 0) -> 0, vector edition.
6706 if (DAG.getTarget().Options.UnsafeFPMath &&
6707 ISD::isBuildVectorAllZeros(N1.getNode()))
6709 // fold (fmul A, 1.0) -> A
6710 if (N1CFP && N1CFP->isExactlyValue(1.0))
6712 // fold (fmul X, 2.0) -> (fadd X, X)
6713 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6714 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6715 // fold (fmul X, -1.0) -> (fneg X)
6716 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6717 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6718 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6720 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6721 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6722 &DAG.getTarget().Options)) {
6723 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6724 &DAG.getTarget().Options)) {
6725 // Both can be negated for free, check to see if at least one is cheaper
6727 if (LHSNeg == 2 || RHSNeg == 2)
6728 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6729 GetNegatedExpression(N0, DAG, LegalOperations),
6730 GetNegatedExpression(N1, DAG, LegalOperations));
6734 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6735 if (DAG.getTarget().Options.UnsafeFPMath &&
6736 N1CFP && N0.getOpcode() == ISD::FMUL &&
6737 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6738 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6739 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6740 N0.getOperand(1), N1));
6745 SDValue DAGCombiner::visitFMA(SDNode *N) {
6746 SDValue N0 = N->getOperand(0);
6747 SDValue N1 = N->getOperand(1);
6748 SDValue N2 = N->getOperand(2);
6749 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6750 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6751 EVT VT = N->getValueType(0);
6754 if (DAG.getTarget().Options.UnsafeFPMath) {
6755 if (N0CFP && N0CFP->isZero())
6757 if (N1CFP && N1CFP->isZero())
6760 if (N0CFP && N0CFP->isExactlyValue(1.0))
6761 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6762 if (N1CFP && N1CFP->isExactlyValue(1.0))
6763 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6765 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6766 if (N0CFP && !N1CFP)
6767 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6769 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6770 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6771 N2.getOpcode() == ISD::FMUL &&
6772 N0 == N2.getOperand(0) &&
6773 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6774 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6775 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6779 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6780 if (DAG.getTarget().Options.UnsafeFPMath &&
6781 N0.getOpcode() == ISD::FMUL && N1CFP &&
6782 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6783 return DAG.getNode(ISD::FMA, dl, VT,
6785 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6789 // (fma x, 1, y) -> (fadd x, y)
6790 // (fma x, -1, y) -> (fadd (fneg x), y)
6792 if (N1CFP->isExactlyValue(1.0))
6793 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6795 if (N1CFP->isExactlyValue(-1.0) &&
6796 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6797 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6798 AddToWorkList(RHSNeg.getNode());
6799 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6803 // (fma x, c, x) -> (fmul x, (c+1))
6804 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6805 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6806 DAG.getNode(ISD::FADD, dl, VT,
6807 N1, DAG.getConstantFP(1.0, VT)));
6809 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6810 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6811 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6812 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6813 DAG.getNode(ISD::FADD, dl, VT,
6814 N1, DAG.getConstantFP(-1.0, VT)));
6820 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6821 SDValue N0 = N->getOperand(0);
6822 SDValue N1 = N->getOperand(1);
6823 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6824 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6825 EVT VT = N->getValueType(0);
6826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6829 if (VT.isVector()) {
6830 SDValue FoldedVOp = SimplifyVBinOp(N);
6831 if (FoldedVOp.getNode()) return FoldedVOp;
6834 // fold (fdiv c1, c2) -> c1/c2
6836 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6838 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6839 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6840 // Compute the reciprocal 1.0 / c2.
6841 APFloat N1APF = N1CFP->getValueAPF();
6842 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6843 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6844 // Only do the transform if the reciprocal is a legal fp immediate that
6845 // isn't too nasty (eg NaN, denormal, ...).
6846 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6847 (!LegalOperations ||
6848 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6849 // backend)... we should handle this gracefully after Legalize.
6850 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6851 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6852 TLI.isFPImmLegal(Recip, VT)))
6853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6854 DAG.getConstantFP(Recip, VT));
6857 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6858 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6859 &DAG.getTarget().Options)) {
6860 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6861 &DAG.getTarget().Options)) {
6862 // Both can be negated for free, check to see if at least one is cheaper
6864 if (LHSNeg == 2 || RHSNeg == 2)
6865 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6866 GetNegatedExpression(N0, DAG, LegalOperations),
6867 GetNegatedExpression(N1, DAG, LegalOperations));
6874 SDValue DAGCombiner::visitFREM(SDNode *N) {
6875 SDValue N0 = N->getOperand(0);
6876 SDValue N1 = N->getOperand(1);
6877 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6878 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6879 EVT VT = N->getValueType(0);
6881 // fold (frem c1, c2) -> fmod(c1,c2)
6883 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6888 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
6890 SDValue N1 = N->getOperand(1);
6891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6892 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6893 EVT VT = N->getValueType(0);
6895 if (N0CFP && N1CFP) // Constant fold
6896 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6899 const APFloat& V = N1CFP->getValueAPF();
6900 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6901 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6902 if (!V.isNegative()) {
6903 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6904 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6906 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6907 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6908 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6912 // copysign(fabs(x), y) -> copysign(x, y)
6913 // copysign(fneg(x), y) -> copysign(x, y)
6914 // copysign(copysign(x,z), y) -> copysign(x, y)
6915 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6916 N0.getOpcode() == ISD::FCOPYSIGN)
6917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6918 N0.getOperand(0), N1);
6920 // copysign(x, abs(y)) -> abs(x)
6921 if (N1.getOpcode() == ISD::FABS)
6922 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6924 // copysign(x, copysign(y,z)) -> copysign(x, z)
6925 if (N1.getOpcode() == ISD::FCOPYSIGN)
6926 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6927 N0, N1.getOperand(1));
6929 // copysign(x, fp_extend(y)) -> copysign(x, y)
6930 // copysign(x, fp_round(y)) -> copysign(x, y)
6931 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6932 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6933 N0, N1.getOperand(0));
6938 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6939 SDValue N0 = N->getOperand(0);
6940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6941 EVT VT = N->getValueType(0);
6942 EVT OpVT = N0.getValueType();
6944 // fold (sint_to_fp c1) -> c1fp
6946 // ...but only if the target supports immediate floating-point values
6947 (!LegalOperations ||
6948 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6949 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6951 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6952 // but UINT_TO_FP is legal on this target, try to convert.
6953 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6954 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6955 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6956 if (DAG.SignBitIsZero(N0))
6957 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6960 // The next optimizations are desirable only if SELECT_CC can be lowered.
6961 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6962 // having to say they don't support SELECT_CC on every type the DAG knows
6963 // about, since there is no way to mark an opcode illegal at all value types
6964 // (See also visitSELECT)
6965 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6966 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6967 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6969 (!LegalOperations ||
6970 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6972 { N0.getOperand(0), N0.getOperand(1),
6973 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6975 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6978 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6979 // (select_cc x, y, 1.0, 0.0,, cc)
6980 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6981 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6982 (!LegalOperations ||
6983 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6985 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6986 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6987 N0.getOperand(0).getOperand(2) };
6988 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6995 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6996 SDValue N0 = N->getOperand(0);
6997 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6998 EVT VT = N->getValueType(0);
6999 EVT OpVT = N0.getValueType();
7001 // fold (uint_to_fp c1) -> c1fp
7003 // ...but only if the target supports immediate floating-point values
7004 (!LegalOperations ||
7005 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7006 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7008 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7009 // but SINT_TO_FP is legal on this target, try to convert.
7010 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7011 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7012 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7013 if (DAG.SignBitIsZero(N0))
7014 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7017 // The next optimizations are desirable only if SELECT_CC can be lowered.
7018 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7019 // having to say they don't support SELECT_CC on every type the DAG knows
7020 // about, since there is no way to mark an opcode illegal at all value types
7021 // (See also visitSELECT)
7022 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7023 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7025 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7026 (!LegalOperations ||
7027 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7029 { N0.getOperand(0), N0.getOperand(1),
7030 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7032 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7039 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7040 SDValue N0 = N->getOperand(0);
7041 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7042 EVT VT = N->getValueType(0);
7044 // fold (fp_to_sint c1fp) -> c1
7046 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7051 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7052 SDValue N0 = N->getOperand(0);
7053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7054 EVT VT = N->getValueType(0);
7056 // fold (fp_to_uint c1fp) -> c1
7058 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7063 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7064 SDValue N0 = N->getOperand(0);
7065 SDValue N1 = N->getOperand(1);
7066 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7067 EVT VT = N->getValueType(0);
7069 // fold (fp_round c1fp) -> c1fp
7071 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7073 // fold (fp_round (fp_extend x)) -> x
7074 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7075 return N0.getOperand(0);
7077 // fold (fp_round (fp_round x)) -> (fp_round x)
7078 if (N0.getOpcode() == ISD::FP_ROUND) {
7079 // This is a value preserving truncation if both round's are.
7080 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7081 N0.getNode()->getConstantOperandVal(1) == 1;
7082 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7083 DAG.getIntPtrConstant(IsTrunc));
7086 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7087 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7088 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7089 N0.getOperand(0), N1);
7090 AddToWorkList(Tmp.getNode());
7091 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7092 Tmp, N0.getOperand(1));
7098 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7099 SDValue N0 = N->getOperand(0);
7100 EVT VT = N->getValueType(0);
7101 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7104 // fold (fp_round_inreg c1fp) -> c1fp
7105 if (N0CFP && isTypeLegal(EVT)) {
7106 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7107 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7113 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7114 SDValue N0 = N->getOperand(0);
7115 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7116 EVT VT = N->getValueType(0);
7118 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7119 if (N->hasOneUse() &&
7120 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7123 // fold (fp_extend c1fp) -> c1fp
7125 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7127 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7129 if (N0.getOpcode() == ISD::FP_ROUND
7130 && N0.getNode()->getConstantOperandVal(1) == 1) {
7131 SDValue In = N0.getOperand(0);
7132 if (In.getValueType() == VT) return In;
7133 if (VT.bitsLT(In.getValueType()))
7134 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7135 In, N0.getOperand(1));
7136 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7139 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7141 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7142 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7143 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7144 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7146 LN0->getBasePtr(), N0.getValueType(),
7147 LN0->getMemOperand());
7148 CombineTo(N, ExtLoad);
7149 CombineTo(N0.getNode(),
7150 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7151 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7152 ExtLoad.getValue(1));
7153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7159 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7160 SDValue N0 = N->getOperand(0);
7161 EVT VT = N->getValueType(0);
7163 if (VT.isVector()) {
7164 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7165 if (FoldedVOp.getNode()) return FoldedVOp;
7168 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7169 &DAG.getTarget().Options))
7170 return GetNegatedExpression(N0, DAG, LegalOperations);
7172 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7173 // constant pool values.
7174 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7176 N0.getNode()->hasOneUse() &&
7177 N0.getOperand(0).getValueType().isInteger()) {
7178 SDValue Int = N0.getOperand(0);
7179 EVT IntVT = Int.getValueType();
7180 if (IntVT.isInteger() && !IntVT.isVector()) {
7181 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7182 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7183 AddToWorkList(Int.getNode());
7184 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7189 // (fneg (fmul c, x)) -> (fmul -c, x)
7190 if (N0.getOpcode() == ISD::FMUL) {
7191 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7193 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7195 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7202 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7203 SDValue N0 = N->getOperand(0);
7204 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7205 EVT VT = N->getValueType(0);
7207 // fold (fceil c1) -> fceil(c1)
7209 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7214 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7215 SDValue N0 = N->getOperand(0);
7216 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7217 EVT VT = N->getValueType(0);
7219 // fold (ftrunc c1) -> ftrunc(c1)
7221 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7226 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7227 SDValue N0 = N->getOperand(0);
7228 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7229 EVT VT = N->getValueType(0);
7231 // fold (ffloor c1) -> ffloor(c1)
7233 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7238 SDValue DAGCombiner::visitFABS(SDNode *N) {
7239 SDValue N0 = N->getOperand(0);
7240 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7241 EVT VT = N->getValueType(0);
7243 if (VT.isVector()) {
7244 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7245 if (FoldedVOp.getNode()) return FoldedVOp;
7248 // fold (fabs c1) -> fabs(c1)
7250 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7251 // fold (fabs (fabs x)) -> (fabs x)
7252 if (N0.getOpcode() == ISD::FABS)
7253 return N->getOperand(0);
7254 // fold (fabs (fneg x)) -> (fabs x)
7255 // fold (fabs (fcopysign x, y)) -> (fabs x)
7256 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7257 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7259 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7260 // constant pool values.
7261 if (!TLI.isFAbsFree(VT) &&
7262 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7263 N0.getOperand(0).getValueType().isInteger() &&
7264 !N0.getOperand(0).getValueType().isVector()) {
7265 SDValue Int = N0.getOperand(0);
7266 EVT IntVT = Int.getValueType();
7267 if (IntVT.isInteger() && !IntVT.isVector()) {
7268 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7269 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7270 AddToWorkList(Int.getNode());
7271 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7272 N->getValueType(0), Int);
7279 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7280 SDValue Chain = N->getOperand(0);
7281 SDValue N1 = N->getOperand(1);
7282 SDValue N2 = N->getOperand(2);
7284 // If N is a constant we could fold this into a fallthrough or unconditional
7285 // branch. However that doesn't happen very often in normal code, because
7286 // Instcombine/SimplifyCFG should have handled the available opportunities.
7287 // If we did this folding here, it would be necessary to update the
7288 // MachineBasicBlock CFG, which is awkward.
7290 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7292 if (N1.getOpcode() == ISD::SETCC &&
7293 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7294 N1.getOperand(0).getValueType())) {
7295 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7296 Chain, N1.getOperand(2),
7297 N1.getOperand(0), N1.getOperand(1), N2);
7300 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7301 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7302 (N1.getOperand(0).hasOneUse() &&
7303 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7305 if (N1.getOpcode() == ISD::TRUNCATE) {
7306 // Look pass the truncate.
7307 Trunc = N1.getNode();
7308 N1 = N1.getOperand(0);
7311 // Match this pattern so that we can generate simpler code:
7314 // %b = and i32 %a, 2
7315 // %c = srl i32 %b, 1
7316 // brcond i32 %c ...
7321 // %b = and i32 %a, 2
7322 // %c = setcc eq %b, 0
7325 // This applies only when the AND constant value has one bit set and the
7326 // SRL constant is equal to the log2 of the AND constant. The back-end is
7327 // smart enough to convert the result into a TEST/JMP sequence.
7328 SDValue Op0 = N1.getOperand(0);
7329 SDValue Op1 = N1.getOperand(1);
7331 if (Op0.getOpcode() == ISD::AND &&
7332 Op1.getOpcode() == ISD::Constant) {
7333 SDValue AndOp1 = Op0.getOperand(1);
7335 if (AndOp1.getOpcode() == ISD::Constant) {
7336 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7338 if (AndConst.isPowerOf2() &&
7339 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7341 DAG.getSetCC(SDLoc(N),
7342 getSetCCResultType(Op0.getValueType()),
7343 Op0, DAG.getConstant(0, Op0.getValueType()),
7346 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7347 MVT::Other, Chain, SetCC, N2);
7348 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7349 // will convert it back to (X & C1) >> C2.
7350 CombineTo(N, NewBRCond, false);
7351 // Truncate is dead.
7353 removeFromWorkList(Trunc);
7354 DAG.DeleteNode(Trunc);
7356 // Replace the uses of SRL with SETCC
7357 WorkListRemover DeadNodes(*this);
7358 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7359 removeFromWorkList(N1.getNode());
7360 DAG.DeleteNode(N1.getNode());
7361 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7367 // Restore N1 if the above transformation doesn't match.
7368 N1 = N->getOperand(1);
7371 // Transform br(xor(x, y)) -> br(x != y)
7372 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7373 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7374 SDNode *TheXor = N1.getNode();
7375 SDValue Op0 = TheXor->getOperand(0);
7376 SDValue Op1 = TheXor->getOperand(1);
7377 if (Op0.getOpcode() == Op1.getOpcode()) {
7378 // Avoid missing important xor optimizations.
7379 SDValue Tmp = visitXOR(TheXor);
7380 if (Tmp.getNode()) {
7381 if (Tmp.getNode() != TheXor) {
7382 DEBUG(dbgs() << "\nReplacing.8 ";
7384 dbgs() << "\nWith: ";
7385 Tmp.getNode()->dump(&DAG);
7387 WorkListRemover DeadNodes(*this);
7388 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7389 removeFromWorkList(TheXor);
7390 DAG.DeleteNode(TheXor);
7391 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7392 MVT::Other, Chain, Tmp, N2);
7395 // visitXOR has changed XOR's operands or replaced the XOR completely,
7397 return SDValue(N, 0);
7401 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7403 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7404 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7405 Op0.getOpcode() == ISD::XOR) {
7406 TheXor = Op0.getNode();
7410 EVT SetCCVT = N1.getValueType();
7412 SetCCVT = getSetCCResultType(SetCCVT);
7413 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7416 Equal ? ISD::SETEQ : ISD::SETNE);
7417 // Replace the uses of XOR with SETCC
7418 WorkListRemover DeadNodes(*this);
7419 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7420 removeFromWorkList(N1.getNode());
7421 DAG.DeleteNode(N1.getNode());
7422 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7423 MVT::Other, Chain, SetCC, N2);
7430 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7432 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7433 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7434 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7436 // If N is a constant we could fold this into a fallthrough or unconditional
7437 // branch. However that doesn't happen very often in normal code, because
7438 // Instcombine/SimplifyCFG should have handled the available opportunities.
7439 // If we did this folding here, it would be necessary to update the
7440 // MachineBasicBlock CFG, which is awkward.
7442 // Use SimplifySetCC to simplify SETCC's.
7443 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7444 CondLHS, CondRHS, CC->get(), SDLoc(N),
7446 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7448 // fold to a simpler setcc
7449 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7450 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7451 N->getOperand(0), Simp.getOperand(2),
7452 Simp.getOperand(0), Simp.getOperand(1),
7458 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7459 /// uses N as its base pointer and that N may be folded in the load / store
7460 /// addressing mode.
7461 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7463 const TargetLowering &TLI) {
7465 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7466 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7468 VT = Use->getValueType(0);
7469 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7470 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7472 VT = ST->getValue().getValueType();
7476 TargetLowering::AddrMode AM;
7477 if (N->getOpcode() == ISD::ADD) {
7478 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7481 AM.BaseOffs = Offset->getSExtValue();
7485 } else if (N->getOpcode() == ISD::SUB) {
7486 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7489 AM.BaseOffs = -Offset->getSExtValue();
7496 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7499 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7500 /// pre-indexed load / store when the base pointer is an add or subtract
7501 /// and it has other uses besides the load / store. After the
7502 /// transformation, the new indexed load / store has effectively folded
7503 /// the add / subtract in and all of its other uses are redirected to the
7504 /// new load / store.
7505 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7506 if (Level < AfterLegalizeDAG)
7512 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7513 if (LD->isIndexed())
7515 VT = LD->getMemoryVT();
7516 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7517 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7519 Ptr = LD->getBasePtr();
7520 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7521 if (ST->isIndexed())
7523 VT = ST->getMemoryVT();
7524 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7525 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7527 Ptr = ST->getBasePtr();
7533 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7534 // out. There is no reason to make this a preinc/predec.
7535 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7536 Ptr.getNode()->hasOneUse())
7539 // Ask the target to do addressing mode selection.
7542 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7543 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7546 // Backends without true r+i pre-indexed forms may need to pass a
7547 // constant base with a variable offset so that constant coercion
7548 // will work with the patterns in canonical form.
7549 bool Swapped = false;
7550 if (isa<ConstantSDNode>(BasePtr)) {
7551 std::swap(BasePtr, Offset);
7555 // Don't create a indexed load / store with zero offset.
7556 if (isa<ConstantSDNode>(Offset) &&
7557 cast<ConstantSDNode>(Offset)->isNullValue())
7560 // Try turning it into a pre-indexed load / store except when:
7561 // 1) The new base ptr is a frame index.
7562 // 2) If N is a store and the new base ptr is either the same as or is a
7563 // predecessor of the value being stored.
7564 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7565 // that would create a cycle.
7566 // 4) All uses are load / store ops that use it as old base ptr.
7568 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7569 // (plus the implicit offset) to a register to preinc anyway.
7570 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7575 SDValue Val = cast<StoreSDNode>(N)->getValue();
7576 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7580 // If the offset is a constant, there may be other adds of constants that
7581 // can be folded with this one. We should do this to avoid having to keep
7582 // a copy of the original base pointer.
7583 SmallVector<SDNode *, 16> OtherUses;
7584 if (isa<ConstantSDNode>(Offset))
7585 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7586 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7588 if (Use == Ptr.getNode())
7591 if (Use->isPredecessorOf(N))
7594 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7599 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600 if (Op1.getNode() == BasePtr.getNode())
7601 std::swap(Op0, Op1);
7602 assert(Op0.getNode() == BasePtr.getNode() &&
7603 "Use of ADD/SUB but not an operand");
7605 if (!isa<ConstantSDNode>(Op1)) {
7610 // FIXME: In some cases, we can be smarter about this.
7611 if (Op1.getValueType() != Offset.getValueType()) {
7616 OtherUses.push_back(Use);
7620 std::swap(BasePtr, Offset);
7622 // Now check for #3 and #4.
7623 bool RealUse = false;
7625 // Caches for hasPredecessorHelper
7626 SmallPtrSet<const SDNode *, 32> Visited;
7627 SmallVector<const SDNode *, 16> Worklist;
7629 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7630 E = Ptr.getNode()->use_end(); I != E; ++I) {
7634 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7637 // If Ptr may be folded in addressing mode of other use, then it's
7638 // not profitable to do this transformation.
7639 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7648 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7649 BasePtr, Offset, AM);
7651 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7652 BasePtr, Offset, AM);
7655 DEBUG(dbgs() << "\nReplacing.4 ";
7657 dbgs() << "\nWith: ";
7658 Result.getNode()->dump(&DAG);
7660 WorkListRemover DeadNodes(*this);
7662 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7663 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7668 // Finally, since the node is now dead, remove it from the graph.
7672 std::swap(BasePtr, Offset);
7674 // Replace other uses of BasePtr that can be updated to use Ptr
7675 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7676 unsigned OffsetIdx = 1;
7677 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7679 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7680 BasePtr.getNode() && "Expected BasePtr operand");
7682 // We need to replace ptr0 in the following expression:
7683 // x0 * offset0 + y0 * ptr0 = t0
7685 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7687 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7688 // indexed load/store and the expresion that needs to be re-written.
7690 // Therefore, we have:
7691 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7693 ConstantSDNode *CN =
7694 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7696 APInt Offset0 = CN->getAPIntValue();
7697 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7699 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7700 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7701 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7702 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7704 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7706 APInt CNV = Offset0;
7707 if (X0 < 0) CNV = -CNV;
7708 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7709 else CNV = CNV - Offset1;
7711 // We can now generate the new expression.
7712 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7713 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7715 SDValue NewUse = DAG.getNode(Opcode,
7716 SDLoc(OtherUses[i]),
7717 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7718 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7719 removeFromWorkList(OtherUses[i]);
7720 DAG.DeleteNode(OtherUses[i]);
7723 // Replace the uses of Ptr with uses of the updated base value.
7724 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7725 removeFromWorkList(Ptr.getNode());
7726 DAG.DeleteNode(Ptr.getNode());
7731 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7732 /// add / sub of the base pointer node into a post-indexed load / store.
7733 /// The transformation folded the add / subtract into the new indexed
7734 /// load / store effectively and all of its uses are redirected to the
7735 /// new load / store.
7736 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7737 if (Level < AfterLegalizeDAG)
7743 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7744 if (LD->isIndexed())
7746 VT = LD->getMemoryVT();
7747 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7748 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7750 Ptr = LD->getBasePtr();
7751 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7752 if (ST->isIndexed())
7754 VT = ST->getMemoryVT();
7755 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7756 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7758 Ptr = ST->getBasePtr();
7764 if (Ptr.getNode()->hasOneUse())
7767 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7768 E = Ptr.getNode()->use_end(); I != E; ++I) {
7771 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7776 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7777 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7778 // Don't create a indexed load / store with zero offset.
7779 if (isa<ConstantSDNode>(Offset) &&
7780 cast<ConstantSDNode>(Offset)->isNullValue())
7783 // Try turning it into a post-indexed load / store except when
7784 // 1) All uses are load / store ops that use it as base ptr (and
7785 // it may be folded as addressing mmode).
7786 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7787 // nor a successor of N. Otherwise, if Op is folded that would
7790 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7794 bool TryNext = false;
7795 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7796 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7798 if (Use == Ptr.getNode())
7801 // If all the uses are load / store addresses, then don't do the
7803 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7804 bool RealUse = false;
7805 for (SDNode::use_iterator III = Use->use_begin(),
7806 EEE = Use->use_end(); III != EEE; ++III) {
7807 SDNode *UseUse = *III;
7808 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7823 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7824 SDValue Result = isLoad
7825 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7826 BasePtr, Offset, AM)
7827 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7828 BasePtr, Offset, AM);
7831 DEBUG(dbgs() << "\nReplacing.5 ";
7833 dbgs() << "\nWith: ";
7834 Result.getNode()->dump(&DAG);
7836 WorkListRemover DeadNodes(*this);
7838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7844 // Finally, since the node is now dead, remove it from the graph.
7847 // Replace the uses of Use with uses of the updated base value.
7848 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7849 Result.getValue(isLoad ? 1 : 0));
7850 removeFromWorkList(Op);
7860 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7861 LoadSDNode *LD = cast<LoadSDNode>(N);
7862 SDValue Chain = LD->getChain();
7863 SDValue Ptr = LD->getBasePtr();
7865 // If load is not volatile and there are no uses of the loaded value (and
7866 // the updated indexed value in case of indexed loads), change uses of the
7867 // chain value into uses of the chain input (i.e. delete the dead load).
7868 if (!LD->isVolatile()) {
7869 if (N->getValueType(1) == MVT::Other) {
7871 if (!N->hasAnyUseOfValue(0)) {
7872 // It's not safe to use the two value CombineTo variant here. e.g.
7873 // v1, chain2 = load chain1, loc
7874 // v2, chain3 = load chain2, loc
7876 // Now we replace use of chain2 with chain1. This makes the second load
7877 // isomorphic to the one we are deleting, and thus makes this load live.
7878 DEBUG(dbgs() << "\nReplacing.6 ";
7880 dbgs() << "\nWith chain: ";
7881 Chain.getNode()->dump(&DAG);
7883 WorkListRemover DeadNodes(*this);
7884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7886 if (N->use_empty()) {
7887 removeFromWorkList(N);
7891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7895 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7896 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7897 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7898 DEBUG(dbgs() << "\nReplacing.7 ";
7900 dbgs() << "\nWith: ";
7901 Undef.getNode()->dump(&DAG);
7902 dbgs() << " and 2 other values\n");
7903 WorkListRemover DeadNodes(*this);
7904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7905 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7906 DAG.getUNDEF(N->getValueType(1)));
7907 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7908 removeFromWorkList(N);
7910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7915 // If this load is directly stored, replace the load value with the stored
7917 // TODO: Handle store large -> read small portion.
7918 // TODO: Handle TRUNCSTORE/LOADEXT
7919 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7920 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7921 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7922 if (PrevST->getBasePtr() == Ptr &&
7923 PrevST->getValue().getValueType() == N->getValueType(0))
7924 return CombineTo(N, Chain.getOperand(1), Chain);
7928 // Try to infer better alignment information than the load already has.
7929 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7930 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7931 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7933 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7934 LD->getValueType(0),
7935 Chain, Ptr, LD->getPointerInfo(),
7937 LD->isVolatile(), LD->isNonTemporal(), Align,
7939 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7944 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7945 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7947 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7948 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7951 if (UseAA && LD->isUnindexed()) {
7952 // Walk up chain skipping non-aliasing memory nodes.
7953 SDValue BetterChain = FindBetterChain(N, Chain);
7955 // If there is a better chain.
7956 if (Chain != BetterChain) {
7959 // Replace the chain to void dependency.
7960 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7961 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7962 BetterChain, Ptr, LD->getMemOperand());
7964 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7965 LD->getValueType(0),
7966 BetterChain, Ptr, LD->getMemoryVT(),
7967 LD->getMemOperand());
7970 // Create token factor to keep old chain connected.
7971 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7972 MVT::Other, Chain, ReplLoad.getValue(1));
7974 // Make sure the new and old chains are cleaned up.
7975 AddToWorkList(Token.getNode());
7977 // Replace uses with load result and token factor. Don't add users
7979 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7983 // Try transforming N to an indexed load.
7984 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7985 return SDValue(N, 0);
7987 // Try to slice up N to more direct loads if the slices are mapped to
7988 // different register banks or pairing can take place.
7990 return SDValue(N, 0);
7996 /// \brief Helper structure used to slice a load in smaller loads.
7997 /// Basically a slice is obtained from the following sequence:
7998 /// Origin = load Ty1, Base
7999 /// Shift = srl Ty1 Origin, CstTy Amount
8000 /// Inst = trunc Shift to Ty2
8002 /// Then, it will be rewriten into:
8003 /// Slice = load SliceTy, Base + SliceOffset
8004 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8006 /// SliceTy is deduced from the number of bits that are actually used to
8008 struct LoadedSlice {
8009 /// \brief Helper structure used to compute the cost of a slice.
8011 /// Are we optimizing for code size.
8016 unsigned CrossRegisterBanksCopies;
8020 Cost(bool ForCodeSize = false)
8021 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8022 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8024 /// \brief Get the cost of one isolated slice.
8025 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8026 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8027 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8028 EVT TruncType = LS.Inst->getValueType(0);
8029 EVT LoadedType = LS.getLoadedType();
8030 if (TruncType != LoadedType &&
8031 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8035 /// \brief Account for slicing gain in the current cost.
8036 /// Slicing provide a few gains like removing a shift or a
8037 /// truncate. This method allows to grow the cost of the original
8038 /// load with the gain from this slice.
8039 void addSliceGain(const LoadedSlice &LS) {
8040 // Each slice saves a truncate.
8041 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8042 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8043 LS.Inst->getOperand(0).getValueType()))
8045 // If there is a shift amount, this slice gets rid of it.
8048 // If this slice can merge a cross register bank copy, account for it.
8049 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8050 ++CrossRegisterBanksCopies;
8053 Cost &operator+=(const Cost &RHS) {
8055 Truncates += RHS.Truncates;
8056 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8062 bool operator==(const Cost &RHS) const {
8063 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8064 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8065 ZExts == RHS.ZExts && Shift == RHS.Shift;
8068 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8070 bool operator<(const Cost &RHS) const {
8071 // Assume cross register banks copies are as expensive as loads.
8072 // FIXME: Do we want some more target hooks?
8073 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8074 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8075 // Unless we are optimizing for code size, consider the
8076 // expensive operation first.
8077 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8078 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8079 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8080 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8083 bool operator>(const Cost &RHS) const { return RHS < *this; }
8085 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8087 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8089 // The last instruction that represent the slice. This should be a
8090 // truncate instruction.
8092 // The original load instruction.
8094 // The right shift amount in bits from the original load.
8096 // The DAG from which Origin came from.
8097 // This is used to get some contextual information about legal types, etc.
8100 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8101 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8102 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8104 LoadedSlice(const LoadedSlice &LS)
8105 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8107 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8108 /// \return Result is \p BitWidth and has used bits set to 1 and
8109 /// not used bits set to 0.
8110 APInt getUsedBits() const {
8111 // Reproduce the trunc(lshr) sequence:
8112 // - Start from the truncated value.
8113 // - Zero extend to the desired bit width.
8115 assert(Origin && "No original load to compare against.");
8116 unsigned BitWidth = Origin->getValueSizeInBits(0);
8117 assert(Inst && "This slice is not bound to an instruction");
8118 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8119 "Extracted slice is bigger than the whole type!");
8120 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8121 UsedBits.setAllBits();
8122 UsedBits = UsedBits.zext(BitWidth);
8127 /// \brief Get the size of the slice to be loaded in bytes.
8128 unsigned getLoadedSize() const {
8129 unsigned SliceSize = getUsedBits().countPopulation();
8130 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8131 return SliceSize / 8;
8134 /// \brief Get the type that will be loaded for this slice.
8135 /// Note: This may not be the final type for the slice.
8136 EVT getLoadedType() const {
8137 assert(DAG && "Missing context");
8138 LLVMContext &Ctxt = *DAG->getContext();
8139 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8142 /// \brief Get the alignment of the load used for this slice.
8143 unsigned getAlignment() const {
8144 unsigned Alignment = Origin->getAlignment();
8145 unsigned Offset = getOffsetFromBase();
8147 Alignment = MinAlign(Alignment, Alignment + Offset);
8151 /// \brief Check if this slice can be rewritten with legal operations.
8152 bool isLegal() const {
8153 // An invalid slice is not legal.
8154 if (!Origin || !Inst || !DAG)
8157 // Offsets are for indexed load only, we do not handle that.
8158 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8161 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8163 // Check that the type is legal.
8164 EVT SliceType = getLoadedType();
8165 if (!TLI.isTypeLegal(SliceType))
8168 // Check that the load is legal for this type.
8169 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8172 // Check that the offset can be computed.
8173 // 1. Check its type.
8174 EVT PtrType = Origin->getBasePtr().getValueType();
8175 if (PtrType == MVT::Untyped || PtrType.isExtended())
8178 // 2. Check that it fits in the immediate.
8179 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8182 // 3. Check that the computation is legal.
8183 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8186 // Check that the zext is legal if it needs one.
8187 EVT TruncateType = Inst->getValueType(0);
8188 if (TruncateType != SliceType &&
8189 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8195 /// \brief Get the offset in bytes of this slice in the original chunk of
8197 /// \pre DAG != NULL.
8198 uint64_t getOffsetFromBase() const {
8199 assert(DAG && "Missing context.");
8201 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8202 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8203 uint64_t Offset = Shift / 8;
8204 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8205 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8206 "The size of the original loaded type is not a multiple of a"
8208 // If Offset is bigger than TySizeInBytes, it means we are loading all
8209 // zeros. This should have been optimized before in the process.
8210 assert(TySizeInBytes > Offset &&
8211 "Invalid shift amount for given loaded size");
8213 Offset = TySizeInBytes - Offset - getLoadedSize();
8217 /// \brief Generate the sequence of instructions to load the slice
8218 /// represented by this object and redirect the uses of this slice to
8219 /// this new sequence of instructions.
8220 /// \pre this->Inst && this->Origin are valid Instructions and this
8221 /// object passed the legal check: LoadedSlice::isLegal returned true.
8222 /// \return The last instruction of the sequence used to load the slice.
8223 SDValue loadSlice() const {
8224 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8225 const SDValue &OldBaseAddr = Origin->getBasePtr();
8226 SDValue BaseAddr = OldBaseAddr;
8227 // Get the offset in that chunk of bytes w.r.t. the endianess.
8228 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8229 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8231 // BaseAddr = BaseAddr + Offset.
8232 EVT ArithType = BaseAddr.getValueType();
8233 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8234 DAG->getConstant(Offset, ArithType));
8237 // Create the type of the loaded slice according to its size.
8238 EVT SliceType = getLoadedType();
8240 // Create the load for the slice.
8241 SDValue LastInst = DAG->getLoad(
8242 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8243 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8244 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8245 // If the final type is not the same as the loaded type, this means that
8246 // we have to pad with zero. Create a zero extend for that.
8247 EVT FinalType = Inst->getValueType(0);
8248 if (SliceType != FinalType)
8250 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8254 /// \brief Check if this slice can be merged with an expensive cross register
8255 /// bank copy. E.g.,
8257 /// f = bitcast i32 i to float
8258 bool canMergeExpensiveCrossRegisterBankCopy() const {
8259 if (!Inst || !Inst->hasOneUse())
8261 SDNode *Use = *Inst->use_begin();
8262 if (Use->getOpcode() != ISD::BITCAST)
8264 assert(DAG && "Missing context");
8265 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8266 EVT ResVT = Use->getValueType(0);
8267 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8268 const TargetRegisterClass *ArgRC =
8269 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8270 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8273 // At this point, we know that we perform a cross-register-bank copy.
8274 // Check if it is expensive.
8275 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8276 // Assume bitcasts are cheap, unless both register classes do not
8277 // explicitly share a common sub class.
8278 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8281 // Check if it will be merged with the load.
8282 // 1. Check the alignment constraint.
8283 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8284 ResVT.getTypeForEVT(*DAG->getContext()));
8286 if (RequiredAlignment > getAlignment())
8289 // 2. Check that the load is a legal operation for that type.
8290 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8293 // 3. Check that we do not have a zext in the way.
8294 if (Inst->getValueType(0) != getLoadedType())
8302 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8303 /// \p UsedBits looks like 0..0 1..1 0..0.
8304 static bool areUsedBitsDense(const APInt &UsedBits) {
8305 // If all the bits are one, this is dense!
8306 if (UsedBits.isAllOnesValue())
8309 // Get rid of the unused bits on the right.
8310 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8311 // Get rid of the unused bits on the left.
8312 if (NarrowedUsedBits.countLeadingZeros())
8313 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8314 // Check that the chunk of bits is completely used.
8315 return NarrowedUsedBits.isAllOnesValue();
8318 /// \brief Check whether or not \p First and \p Second are next to each other
8319 /// in memory. This means that there is no hole between the bits loaded
8320 /// by \p First and the bits loaded by \p Second.
8321 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8322 const LoadedSlice &Second) {
8323 assert(First.Origin == Second.Origin && First.Origin &&
8324 "Unable to match different memory origins.");
8325 APInt UsedBits = First.getUsedBits();
8326 assert((UsedBits & Second.getUsedBits()) == 0 &&
8327 "Slices are not supposed to overlap.");
8328 UsedBits |= Second.getUsedBits();
8329 return areUsedBitsDense(UsedBits);
8332 /// \brief Adjust the \p GlobalLSCost according to the target
8333 /// paring capabilities and the layout of the slices.
8334 /// \pre \p GlobalLSCost should account for at least as many loads as
8335 /// there is in the slices in \p LoadedSlices.
8336 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8337 LoadedSlice::Cost &GlobalLSCost) {
8338 unsigned NumberOfSlices = LoadedSlices.size();
8339 // If there is less than 2 elements, no pairing is possible.
8340 if (NumberOfSlices < 2)
8343 // Sort the slices so that elements that are likely to be next to each
8344 // other in memory are next to each other in the list.
8345 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8346 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8347 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8348 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8350 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8351 // First (resp. Second) is the first (resp. Second) potentially candidate
8352 // to be placed in a paired load.
8353 const LoadedSlice *First = NULL;
8354 const LoadedSlice *Second = NULL;
8355 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8356 // Set the beginning of the pair.
8359 Second = &LoadedSlices[CurrSlice];
8361 // If First is NULL, it means we start a new pair.
8362 // Get to the next slice.
8366 EVT LoadedType = First->getLoadedType();
8368 // If the types of the slices are different, we cannot pair them.
8369 if (LoadedType != Second->getLoadedType())
8372 // Check if the target supplies paired loads for this type.
8373 unsigned RequiredAlignment = 0;
8374 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8375 // move to the next pair, this type is hopeless.
8379 // Check if we meet the alignment requirement.
8380 if (RequiredAlignment > First->getAlignment())
8383 // Check that both loads are next to each other in memory.
8384 if (!areSlicesNextToEachOther(*First, *Second))
8387 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8388 --GlobalLSCost.Loads;
8389 // Move to the next pair.
8394 /// \brief Check the profitability of all involved LoadedSlice.
8395 /// Currently, it is considered profitable if there is exactly two
8396 /// involved slices (1) which are (2) next to each other in memory, and
8397 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8399 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8400 /// the elements themselves.
8402 /// FIXME: When the cost model will be mature enough, we can relax
8403 /// constraints (1) and (2).
8404 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8405 const APInt &UsedBits, bool ForCodeSize) {
8406 unsigned NumberOfSlices = LoadedSlices.size();
8407 if (StressLoadSlicing)
8408 return NumberOfSlices > 1;
8411 if (NumberOfSlices != 2)
8415 if (!areUsedBitsDense(UsedBits))
8419 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8420 // The original code has one big load.
8422 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8423 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8424 // Accumulate the cost of all the slices.
8425 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8426 GlobalSlicingCost += SliceCost;
8428 // Account as cost in the original configuration the gain obtained
8429 // with the current slices.
8430 OrigCost.addSliceGain(LS);
8433 // If the target supports paired load, adjust the cost accordingly.
8434 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8435 return OrigCost > GlobalSlicingCost;
8438 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8439 /// operations, split it in the various pieces being extracted.
8441 /// This sort of thing is introduced by SROA.
8442 /// This slicing takes care not to insert overlapping loads.
8443 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8444 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8445 if (Level < AfterLegalizeDAG)
8448 LoadSDNode *LD = cast<LoadSDNode>(N);
8449 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8450 !LD->getValueType(0).isInteger())
8453 // Keep track of already used bits to detect overlapping values.
8454 // In that case, we will just abort the transformation.
8455 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8457 SmallVector<LoadedSlice, 4> LoadedSlices;
8459 // Check if this load is used as several smaller chunks of bits.
8460 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8461 // of computation for each trunc.
8462 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8463 UI != UIEnd; ++UI) {
8464 // Skip the uses of the chain.
8465 if (UI.getUse().getResNo() != 0)
8471 // Check if this is a trunc(lshr).
8472 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8473 isa<ConstantSDNode>(User->getOperand(1))) {
8474 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8475 User = *User->use_begin();
8478 // At this point, User is a Truncate, iff we encountered, trunc or
8480 if (User->getOpcode() != ISD::TRUNCATE)
8483 // The width of the type must be a power of 2 and greater than 8-bits.
8484 // Otherwise the load cannot be represented in LLVM IR.
8485 // Moreover, if we shifted with a non-8-bits multiple, the slice
8486 // will be across several bytes. We do not support that.
8487 unsigned Width = User->getValueSizeInBits(0);
8488 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8491 // Build the slice for this chain of computations.
8492 LoadedSlice LS(User, LD, Shift, &DAG);
8493 APInt CurrentUsedBits = LS.getUsedBits();
8495 // Check if this slice overlaps with another.
8496 if ((CurrentUsedBits & UsedBits) != 0)
8498 // Update the bits used globally.
8499 UsedBits |= CurrentUsedBits;
8501 // Check if the new slice would be legal.
8505 // Record the slice.
8506 LoadedSlices.push_back(LS);
8509 // Abort slicing if it does not seem to be profitable.
8510 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8515 // Rewrite each chain to use an independent load.
8516 // By construction, each chain can be represented by a unique load.
8518 // Prepare the argument for the new token factor for all the slices.
8519 SmallVector<SDValue, 8> ArgChains;
8520 for (SmallVectorImpl<LoadedSlice>::const_iterator
8521 LSIt = LoadedSlices.begin(),
8522 LSItEnd = LoadedSlices.end();
8523 LSIt != LSItEnd; ++LSIt) {
8524 SDValue SliceInst = LSIt->loadSlice();
8525 CombineTo(LSIt->Inst, SliceInst, true);
8526 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8527 SliceInst = SliceInst.getOperand(0);
8528 assert(SliceInst->getOpcode() == ISD::LOAD &&
8529 "It takes more than a zext to get to the loaded slice!!");
8530 ArgChains.push_back(SliceInst.getValue(1));
8533 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8534 &ArgChains[0], ArgChains.size());
8535 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8539 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8540 /// load is having specific bytes cleared out. If so, return the byte size
8541 /// being masked out and the shift amount.
8542 static std::pair<unsigned, unsigned>
8543 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8544 std::pair<unsigned, unsigned> Result(0, 0);
8546 // Check for the structure we're looking for.
8547 if (V->getOpcode() != ISD::AND ||
8548 !isa<ConstantSDNode>(V->getOperand(1)) ||
8549 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8552 // Check the chain and pointer.
8553 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8554 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8556 // The store should be chained directly to the load or be an operand of a
8558 if (LD == Chain.getNode())
8560 else if (Chain->getOpcode() != ISD::TokenFactor)
8561 return Result; // Fail.
8564 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8565 if (Chain->getOperand(i).getNode() == LD) {
8569 if (!isOk) return Result;
8572 // This only handles simple types.
8573 if (V.getValueType() != MVT::i16 &&
8574 V.getValueType() != MVT::i32 &&
8575 V.getValueType() != MVT::i64)
8578 // Check the constant mask. Invert it so that the bits being masked out are
8579 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8580 // follow the sign bit for uniformity.
8581 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8582 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8583 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8584 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8585 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8586 if (NotMaskLZ == 64) return Result; // All zero mask.
8588 // See if we have a continuous run of bits. If so, we have 0*1+0*
8589 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8592 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8593 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8594 NotMaskLZ -= 64-V.getValueSizeInBits();
8596 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8597 switch (MaskedBytes) {
8601 default: return Result; // All one mask, or 5-byte mask.
8604 // Verify that the first bit starts at a multiple of mask so that the access
8605 // is aligned the same as the access width.
8606 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8608 Result.first = MaskedBytes;
8609 Result.second = NotMaskTZ/8;
8614 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8615 /// provides a value as specified by MaskInfo. If so, replace the specified
8616 /// store with a narrower store of truncated IVal.
8618 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8619 SDValue IVal, StoreSDNode *St,
8621 unsigned NumBytes = MaskInfo.first;
8622 unsigned ByteShift = MaskInfo.second;
8623 SelectionDAG &DAG = DC->getDAG();
8625 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8626 // that uses this. If not, this is not a replacement.
8627 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8628 ByteShift*8, (ByteShift+NumBytes)*8);
8629 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8631 // Check that it is legal on the target to do this. It is legal if the new
8632 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8634 MVT VT = MVT::getIntegerVT(NumBytes*8);
8635 if (!DC->isTypeLegal(VT))
8638 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8639 // shifted by ByteShift and truncated down to NumBytes.
8641 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8642 DAG.getConstant(ByteShift*8,
8643 DC->getShiftAmountTy(IVal.getValueType())));
8645 // Figure out the offset for the store and the alignment of the access.
8647 unsigned NewAlign = St->getAlignment();
8649 if (DAG.getTargetLoweringInfo().isLittleEndian())
8650 StOffset = ByteShift;
8652 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8654 SDValue Ptr = St->getBasePtr();
8656 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8657 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8658 NewAlign = MinAlign(NewAlign, StOffset);
8661 // Truncate down to the new size.
8662 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8665 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8666 St->getPointerInfo().getWithOffset(StOffset),
8667 false, false, NewAlign).getNode();
8671 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8672 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8673 /// of the loaded bits, try narrowing the load and store if it would end up
8674 /// being a win for performance or code size.
8675 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8676 StoreSDNode *ST = cast<StoreSDNode>(N);
8677 if (ST->isVolatile())
8680 SDValue Chain = ST->getChain();
8681 SDValue Value = ST->getValue();
8682 SDValue Ptr = ST->getBasePtr();
8683 EVT VT = Value.getValueType();
8685 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8688 unsigned Opc = Value.getOpcode();
8690 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8691 // is a byte mask indicating a consecutive number of bytes, check to see if
8692 // Y is known to provide just those bytes. If so, we try to replace the
8693 // load + replace + store sequence with a single (narrower) store, which makes
8695 if (Opc == ISD::OR) {
8696 std::pair<unsigned, unsigned> MaskedLoad;
8697 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8698 if (MaskedLoad.first)
8699 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8700 Value.getOperand(1), ST,this))
8701 return SDValue(NewST, 0);
8703 // Or is commutative, so try swapping X and Y.
8704 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8705 if (MaskedLoad.first)
8706 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8707 Value.getOperand(0), ST,this))
8708 return SDValue(NewST, 0);
8711 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8712 Value.getOperand(1).getOpcode() != ISD::Constant)
8715 SDValue N0 = Value.getOperand(0);
8716 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8717 Chain == SDValue(N0.getNode(), 1)) {
8718 LoadSDNode *LD = cast<LoadSDNode>(N0);
8719 if (LD->getBasePtr() != Ptr ||
8720 LD->getPointerInfo().getAddrSpace() !=
8721 ST->getPointerInfo().getAddrSpace())
8724 // Find the type to narrow it the load / op / store to.
8725 SDValue N1 = Value.getOperand(1);
8726 unsigned BitWidth = N1.getValueSizeInBits();
8727 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8728 if (Opc == ISD::AND)
8729 Imm ^= APInt::getAllOnesValue(BitWidth);
8730 if (Imm == 0 || Imm.isAllOnesValue())
8732 unsigned ShAmt = Imm.countTrailingZeros();
8733 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8734 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8735 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8736 while (NewBW < BitWidth &&
8737 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8738 TLI.isNarrowingProfitable(VT, NewVT))) {
8739 NewBW = NextPowerOf2(NewBW);
8740 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8742 if (NewBW >= BitWidth)
8745 // If the lsb changed does not start at the type bitwidth boundary,
8746 // start at the previous one.
8748 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8749 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8750 std::min(BitWidth, ShAmt + NewBW));
8751 if ((Imm & Mask) == Imm) {
8752 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8753 if (Opc == ISD::AND)
8754 NewImm ^= APInt::getAllOnesValue(NewBW);
8755 uint64_t PtrOff = ShAmt / 8;
8756 // For big endian targets, we need to adjust the offset to the pointer to
8757 // load the correct bytes.
8758 if (TLI.isBigEndian())
8759 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8761 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8762 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8763 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8766 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8767 Ptr.getValueType(), Ptr,
8768 DAG.getConstant(PtrOff, Ptr.getValueType()));
8769 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8770 LD->getChain(), NewPtr,
8771 LD->getPointerInfo().getWithOffset(PtrOff),
8772 LD->isVolatile(), LD->isNonTemporal(),
8773 LD->isInvariant(), NewAlign,
8775 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8776 DAG.getConstant(NewImm, NewVT));
8777 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8779 ST->getPointerInfo().getWithOffset(PtrOff),
8780 false, false, NewAlign);
8782 AddToWorkList(NewPtr.getNode());
8783 AddToWorkList(NewLD.getNode());
8784 AddToWorkList(NewVal.getNode());
8785 WorkListRemover DeadNodes(*this);
8786 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8795 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8796 /// if the load value isn't used by any other operations, then consider
8797 /// transforming the pair to integer load / store operations if the target
8798 /// deems the transformation profitable.
8799 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8800 StoreSDNode *ST = cast<StoreSDNode>(N);
8801 SDValue Chain = ST->getChain();
8802 SDValue Value = ST->getValue();
8803 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8804 Value.hasOneUse() &&
8805 Chain == SDValue(Value.getNode(), 1)) {
8806 LoadSDNode *LD = cast<LoadSDNode>(Value);
8807 EVT VT = LD->getMemoryVT();
8808 if (!VT.isFloatingPoint() ||
8809 VT != ST->getMemoryVT() ||
8810 LD->isNonTemporal() ||
8811 ST->isNonTemporal() ||
8812 LD->getPointerInfo().getAddrSpace() != 0 ||
8813 ST->getPointerInfo().getAddrSpace() != 0)
8816 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8817 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8818 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8819 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8820 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8823 unsigned LDAlign = LD->getAlignment();
8824 unsigned STAlign = ST->getAlignment();
8825 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8826 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8827 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8830 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8831 LD->getChain(), LD->getBasePtr(),
8832 LD->getPointerInfo(),
8833 false, false, false, LDAlign);
8835 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8836 NewLD, ST->getBasePtr(),
8837 ST->getPointerInfo(),
8838 false, false, STAlign);
8840 AddToWorkList(NewLD.getNode());
8841 AddToWorkList(NewST.getNode());
8842 WorkListRemover DeadNodes(*this);
8843 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8851 /// Helper struct to parse and store a memory address as base + index + offset.
8852 /// We ignore sign extensions when it is safe to do so.
8853 /// The following two expressions are not equivalent. To differentiate we need
8854 /// to store whether there was a sign extension involved in the index
8856 /// (load (i64 add (i64 copyfromreg %c)
8857 /// (i64 signextend (add (i8 load %index)
8861 /// (load (i64 add (i64 copyfromreg %c)
8862 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8864 struct BaseIndexOffset {
8868 bool IsIndexSignExt;
8870 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8872 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8873 bool IsIndexSignExt) :
8874 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8876 bool equalBaseIndex(const BaseIndexOffset &Other) {
8877 return Other.Base == Base && Other.Index == Index &&
8878 Other.IsIndexSignExt == IsIndexSignExt;
8881 /// Parses tree in Ptr for base, index, offset addresses.
8882 static BaseIndexOffset match(SDValue Ptr) {
8883 bool IsIndexSignExt = false;
8885 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8886 // instruction, then it could be just the BASE or everything else we don't
8887 // know how to handle. Just use Ptr as BASE and give up.
8888 if (Ptr->getOpcode() != ISD::ADD)
8889 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8891 // We know that we have at least an ADD instruction. Try to pattern match
8892 // the simple case of BASE + OFFSET.
8893 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8894 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8895 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8899 // Inside a loop the current BASE pointer is calculated using an ADD and a
8900 // MUL instruction. In this case Ptr is the actual BASE pointer.
8901 // (i64 add (i64 %array_ptr)
8902 // (i64 mul (i64 %induction_var)
8903 // (i64 %element_size)))
8904 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8905 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8907 // Look at Base + Index + Offset cases.
8908 SDValue Base = Ptr->getOperand(0);
8909 SDValue IndexOffset = Ptr->getOperand(1);
8911 // Skip signextends.
8912 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8913 IndexOffset = IndexOffset->getOperand(0);
8914 IsIndexSignExt = true;
8917 // Either the case of Base + Index (no offset) or something else.
8918 if (IndexOffset->getOpcode() != ISD::ADD)
8919 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8921 // Now we have the case of Base + Index + offset.
8922 SDValue Index = IndexOffset->getOperand(0);
8923 SDValue Offset = IndexOffset->getOperand(1);
8925 if (!isa<ConstantSDNode>(Offset))
8926 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8928 // Ignore signextends.
8929 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8930 Index = Index->getOperand(0);
8931 IsIndexSignExt = true;
8932 } else IsIndexSignExt = false;
8934 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8935 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8939 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8940 /// is located in a sequence of memory operations connected by a chain.
8942 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8943 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8944 // Ptr to the mem node.
8945 LSBaseSDNode *MemNode;
8946 // Offset from the base ptr.
8947 int64_t OffsetFromBase;
8948 // What is the sequence number of this mem node.
8949 // Lowest mem operand in the DAG starts at zero.
8950 unsigned SequenceNum;
8953 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8954 EVT MemVT = St->getMemoryVT();
8955 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8956 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8957 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8959 // Don't merge vectors into wider inputs.
8960 if (MemVT.isVector() || !MemVT.isSimple())
8963 // Perform an early exit check. Do not bother looking at stored values that
8964 // are not constants or loads.
8965 SDValue StoredVal = St->getValue();
8966 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8967 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8971 // Only look at ends of store sequences.
8972 SDValue Chain = SDValue(St, 1);
8973 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8976 // This holds the base pointer, index, and the offset in bytes from the base
8978 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8980 // We must have a base and an offset.
8981 if (!BasePtr.Base.getNode())
8984 // Do not handle stores to undef base pointers.
8985 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8988 // Save the LoadSDNodes that we find in the chain.
8989 // We need to make sure that these nodes do not interfere with
8990 // any of the store nodes.
8991 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8993 // Save the StoreSDNodes that we find in the chain.
8994 SmallVector<MemOpLink, 8> StoreNodes;
8996 // Walk up the chain and look for nodes with offsets from the same
8997 // base pointer. Stop when reaching an instruction with a different kind
8998 // or instruction which has a different base pointer.
9000 StoreSDNode *Index = St;
9002 // If the chain has more than one use, then we can't reorder the mem ops.
9003 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9006 // Find the base pointer and offset for this memory node.
9007 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9009 // Check that the base pointer is the same as the original one.
9010 if (!Ptr.equalBaseIndex(BasePtr))
9013 // Check that the alignment is the same.
9014 if (Index->getAlignment() != St->getAlignment())
9017 // The memory operands must not be volatile.
9018 if (Index->isVolatile() || Index->isIndexed())
9022 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9023 if (St->isTruncatingStore())
9026 // The stored memory type must be the same.
9027 if (Index->getMemoryVT() != MemVT)
9030 // We do not allow unaligned stores because we want to prevent overriding
9032 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9035 // We found a potential memory operand to merge.
9036 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9038 // Find the next memory operand in the chain. If the next operand in the
9039 // chain is a store then move up and continue the scan with the next
9040 // memory operand. If the next operand is a load save it and use alias
9041 // information to check if it interferes with anything.
9042 SDNode *NextInChain = Index->getChain().getNode();
9044 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9045 // We found a store node. Use it for the next iteration.
9048 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9049 if (Ldn->isVolatile()) {
9054 // Save the load node for later. Continue the scan.
9055 AliasLoadNodes.push_back(Ldn);
9056 NextInChain = Ldn->getChain().getNode();
9065 // Check if there is anything to merge.
9066 if (StoreNodes.size() < 2)
9069 // Sort the memory operands according to their distance from the base pointer.
9070 std::sort(StoreNodes.begin(), StoreNodes.end(),
9071 [](MemOpLink LHS, MemOpLink RHS) {
9072 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9073 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9074 LHS.SequenceNum > RHS.SequenceNum);
9077 // Scan the memory operations on the chain and find the first non-consecutive
9078 // store memory address.
9079 unsigned LastConsecutiveStore = 0;
9080 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9081 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9083 // Check that the addresses are consecutive starting from the second
9084 // element in the list of stores.
9086 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9087 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9092 // Check if this store interferes with any of the loads that we found.
9093 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9094 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9098 // We found a load that alias with this store. Stop the sequence.
9102 // Mark this node as useful.
9103 LastConsecutiveStore = i;
9106 // The node with the lowest store address.
9107 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9109 // Store the constants into memory as one consecutive store.
9111 unsigned LastLegalType = 0;
9112 unsigned LastLegalVectorType = 0;
9113 bool NonZero = false;
9114 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9115 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9116 SDValue StoredVal = St->getValue();
9118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9119 NonZero |= !C->isNullValue();
9120 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9121 NonZero |= !C->getConstantFPValue()->isNullValue();
9127 // Find a legal type for the constant store.
9128 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9129 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9130 if (TLI.isTypeLegal(StoreTy))
9131 LastLegalType = i+1;
9132 // Or check whether a truncstore is legal.
9133 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9134 TargetLowering::TypePromoteInteger) {
9135 EVT LegalizedStoredValueTy =
9136 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9137 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9138 LastLegalType = i+1;
9141 // Find a legal type for the vector store.
9142 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9143 if (TLI.isTypeLegal(Ty))
9144 LastLegalVectorType = i + 1;
9147 // We only use vectors if the constant is known to be zero and the
9148 // function is not marked with the noimplicitfloat attribute.
9149 if (NonZero || NoVectors)
9150 LastLegalVectorType = 0;
9152 // Check if we found a legal integer type to store.
9153 if (LastLegalType == 0 && LastLegalVectorType == 0)
9156 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9157 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9159 // Make sure we have something to merge.
9163 unsigned EarliestNodeUsed = 0;
9164 for (unsigned i=0; i < NumElem; ++i) {
9165 // Find a chain for the new wide-store operand. Notice that some
9166 // of the store nodes that we found may not be selected for inclusion
9167 // in the wide store. The chain we use needs to be the chain of the
9168 // earliest store node which is *used* and replaced by the wide store.
9169 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9170 EarliestNodeUsed = i;
9173 // The earliest Node in the DAG.
9174 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9175 SDLoc DL(StoreNodes[0].MemNode);
9179 // Find a legal type for the vector store.
9180 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9181 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9182 StoredVal = DAG.getConstant(0, Ty);
9184 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9185 APInt StoreInt(StoreBW, 0);
9187 // Construct a single integer constant which is made of the smaller
9189 bool IsLE = TLI.isLittleEndian();
9190 for (unsigned i = 0; i < NumElem ; ++i) {
9191 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9192 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9193 SDValue Val = St->getValue();
9194 StoreInt<<=ElementSizeBytes*8;
9195 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9196 StoreInt|=C->getAPIntValue().zext(StoreBW);
9197 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9198 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9200 assert(false && "Invalid constant element type");
9204 // Create the new Load and Store operations.
9205 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9206 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9209 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9210 FirstInChain->getBasePtr(),
9211 FirstInChain->getPointerInfo(),
9213 FirstInChain->getAlignment());
9215 // Replace the first store with the new store
9216 CombineTo(EarliestOp, NewStore);
9217 // Erase all other stores.
9218 for (unsigned i = 0; i < NumElem ; ++i) {
9219 if (StoreNodes[i].MemNode == EarliestOp)
9221 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9222 // ReplaceAllUsesWith will replace all uses that existed when it was
9223 // called, but graph optimizations may cause new ones to appear. For
9224 // example, the case in pr14333 looks like
9226 // St's chain -> St -> another store -> X
9228 // And the only difference from St to the other store is the chain.
9229 // When we change it's chain to be St's chain they become identical,
9230 // get CSEed and the net result is that X is now a use of St.
9231 // Since we know that St is redundant, just iterate.
9232 while (!St->use_empty())
9233 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9234 removeFromWorkList(St);
9241 // Below we handle the case of multiple consecutive stores that
9242 // come from multiple consecutive loads. We merge them into a single
9243 // wide load and a single wide store.
9245 // Look for load nodes which are used by the stored values.
9246 SmallVector<MemOpLink, 8> LoadNodes;
9248 // Find acceptable loads. Loads need to have the same chain (token factor),
9249 // must not be zext, volatile, indexed, and they must be consecutive.
9250 BaseIndexOffset LdBasePtr;
9251 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9252 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9253 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9256 // Loads must only have one use.
9257 if (!Ld->hasNUsesOfValue(1, 0))
9260 // Check that the alignment is the same as the stores.
9261 if (Ld->getAlignment() != St->getAlignment())
9264 // The memory operands must not be volatile.
9265 if (Ld->isVolatile() || Ld->isIndexed())
9268 // We do not accept ext loads.
9269 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9272 // The stored memory type must be the same.
9273 if (Ld->getMemoryVT() != MemVT)
9276 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9277 // If this is not the first ptr that we check.
9278 if (LdBasePtr.Base.getNode()) {
9279 // The base ptr must be the same.
9280 if (!LdPtr.equalBaseIndex(LdBasePtr))
9283 // Check that all other base pointers are the same as this one.
9287 // We found a potential memory operand to merge.
9288 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9291 if (LoadNodes.size() < 2)
9294 // Scan the memory operations on the chain and find the first non-consecutive
9295 // load memory address. These variables hold the index in the store node
9297 unsigned LastConsecutiveLoad = 0;
9298 // This variable refers to the size and not index in the array.
9299 unsigned LastLegalVectorType = 0;
9300 unsigned LastLegalIntegerType = 0;
9301 StartAddress = LoadNodes[0].OffsetFromBase;
9302 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9303 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9304 // All loads much share the same chain.
9305 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9308 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9309 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9311 LastConsecutiveLoad = i;
9313 // Find a legal type for the vector store.
9314 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9315 if (TLI.isTypeLegal(StoreTy))
9316 LastLegalVectorType = i + 1;
9318 // Find a legal type for the integer store.
9319 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9320 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9321 if (TLI.isTypeLegal(StoreTy))
9322 LastLegalIntegerType = i + 1;
9323 // Or check whether a truncstore and extload is legal.
9324 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9325 TargetLowering::TypePromoteInteger) {
9326 EVT LegalizedStoredValueTy =
9327 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9328 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9329 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9330 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9331 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9332 LastLegalIntegerType = i+1;
9336 // Only use vector types if the vector type is larger than the integer type.
9337 // If they are the same, use integers.
9338 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9339 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9341 // We add +1 here because the LastXXX variables refer to location while
9342 // the NumElem refers to array/index size.
9343 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9344 NumElem = std::min(LastLegalType, NumElem);
9349 // The earliest Node in the DAG.
9350 unsigned EarliestNodeUsed = 0;
9351 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9352 for (unsigned i=1; i<NumElem; ++i) {
9353 // Find a chain for the new wide-store operand. Notice that some
9354 // of the store nodes that we found may not be selected for inclusion
9355 // in the wide store. The chain we use needs to be the chain of the
9356 // earliest store node which is *used* and replaced by the wide store.
9357 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9358 EarliestNodeUsed = i;
9361 // Find if it is better to use vectors or integers to load and store
9365 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9367 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9368 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9371 SDLoc LoadDL(LoadNodes[0].MemNode);
9372 SDLoc StoreDL(StoreNodes[0].MemNode);
9374 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9375 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9376 FirstLoad->getChain(),
9377 FirstLoad->getBasePtr(),
9378 FirstLoad->getPointerInfo(),
9379 false, false, false,
9380 FirstLoad->getAlignment());
9382 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9383 FirstInChain->getBasePtr(),
9384 FirstInChain->getPointerInfo(), false, false,
9385 FirstInChain->getAlignment());
9387 // Replace one of the loads with the new load.
9388 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9389 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9390 SDValue(NewLoad.getNode(), 1));
9392 // Remove the rest of the load chains.
9393 for (unsigned i = 1; i < NumElem ; ++i) {
9394 // Replace all chain users of the old load nodes with the chain of the new
9396 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9397 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9400 // Replace the first store with the new store.
9401 CombineTo(EarliestOp, NewStore);
9402 // Erase all other stores.
9403 for (unsigned i = 0; i < NumElem ; ++i) {
9404 // Remove all Store nodes.
9405 if (StoreNodes[i].MemNode == EarliestOp)
9407 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9408 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9409 removeFromWorkList(St);
9416 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9417 StoreSDNode *ST = cast<StoreSDNode>(N);
9418 SDValue Chain = ST->getChain();
9419 SDValue Value = ST->getValue();
9420 SDValue Ptr = ST->getBasePtr();
9422 // If this is a store of a bit convert, store the input value if the
9423 // resultant store does not need a higher alignment than the original.
9424 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9425 ST->isUnindexed()) {
9426 unsigned OrigAlign = ST->getAlignment();
9427 EVT SVT = Value.getOperand(0).getValueType();
9428 unsigned Align = TLI.getDataLayout()->
9429 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9430 if (Align <= OrigAlign &&
9431 ((!LegalOperations && !ST->isVolatile()) ||
9432 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9433 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9434 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9435 ST->isNonTemporal(), OrigAlign,
9439 // Turn 'store undef, Ptr' -> nothing.
9440 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9443 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9444 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9445 // NOTE: If the original store is volatile, this transform must not increase
9446 // the number of stores. For example, on x86-32 an f64 can be stored in one
9447 // processor operation but an i64 (which is not legal) requires two. So the
9448 // transform should not be done in this case.
9449 if (Value.getOpcode() != ISD::TargetConstantFP) {
9451 switch (CFP->getSimpleValueType(0).SimpleTy) {
9452 default: llvm_unreachable("Unknown FP type");
9453 case MVT::f16: // We don't do this for these yet.
9459 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9460 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9461 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9462 bitcastToAPInt().getZExtValue(), MVT::i32);
9463 return DAG.getStore(Chain, SDLoc(N), Tmp,
9464 Ptr, ST->getMemOperand());
9468 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9469 !ST->isVolatile()) ||
9470 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9471 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9472 getZExtValue(), MVT::i64);
9473 return DAG.getStore(Chain, SDLoc(N), Tmp,
9474 Ptr, ST->getMemOperand());
9477 if (!ST->isVolatile() &&
9478 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9479 // Many FP stores are not made apparent until after legalize, e.g. for
9480 // argument passing. Since this is so common, custom legalize the
9481 // 64-bit integer store into two 32-bit stores.
9482 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9483 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9484 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9485 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9487 unsigned Alignment = ST->getAlignment();
9488 bool isVolatile = ST->isVolatile();
9489 bool isNonTemporal = ST->isNonTemporal();
9490 const MDNode *TBAAInfo = ST->getTBAAInfo();
9492 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9493 Ptr, ST->getPointerInfo(),
9494 isVolatile, isNonTemporal,
9495 ST->getAlignment(), TBAAInfo);
9496 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9497 DAG.getConstant(4, Ptr.getValueType()));
9498 Alignment = MinAlign(Alignment, 4U);
9499 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9500 Ptr, ST->getPointerInfo().getWithOffset(4),
9501 isVolatile, isNonTemporal,
9502 Alignment, TBAAInfo);
9503 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9512 // Try to infer better alignment information than the store already has.
9513 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9514 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9515 if (Align > ST->getAlignment())
9516 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9517 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9518 ST->isVolatile(), ST->isNonTemporal(), Align,
9523 // Try transforming a pair floating point load / store ops to integer
9524 // load / store ops.
9525 SDValue NewST = TransformFPLoadStorePair(N);
9526 if (NewST.getNode())
9529 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9530 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9532 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9533 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9536 if (UseAA && ST->isUnindexed()) {
9537 // Walk up chain skipping non-aliasing memory nodes.
9538 SDValue BetterChain = FindBetterChain(N, Chain);
9540 // If there is a better chain.
9541 if (Chain != BetterChain) {
9544 // Replace the chain to avoid dependency.
9545 if (ST->isTruncatingStore()) {
9546 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9547 ST->getMemoryVT(), ST->getMemOperand());
9549 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9550 ST->getMemOperand());
9553 // Create token to keep both nodes around.
9554 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9555 MVT::Other, Chain, ReplStore);
9557 // Make sure the new and old chains are cleaned up.
9558 AddToWorkList(Token.getNode());
9560 // Don't add users to work list.
9561 return CombineTo(N, Token, false);
9565 // Try transforming N to an indexed store.
9566 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9567 return SDValue(N, 0);
9569 // FIXME: is there such a thing as a truncating indexed store?
9570 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9571 Value.getValueType().isInteger()) {
9572 // See if we can simplify the input to this truncstore with knowledge that
9573 // only the low bits are being used. For example:
9574 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9576 GetDemandedBits(Value,
9577 APInt::getLowBitsSet(
9578 Value.getValueType().getScalarType().getSizeInBits(),
9579 ST->getMemoryVT().getScalarType().getSizeInBits()));
9580 AddToWorkList(Value.getNode());
9581 if (Shorter.getNode())
9582 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9583 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9585 // Otherwise, see if we can simplify the operation with
9586 // SimplifyDemandedBits, which only works if the value has a single use.
9587 if (SimplifyDemandedBits(Value,
9588 APInt::getLowBitsSet(
9589 Value.getValueType().getScalarType().getSizeInBits(),
9590 ST->getMemoryVT().getScalarType().getSizeInBits())))
9591 return SDValue(N, 0);
9594 // If this is a load followed by a store to the same location, then the store
9596 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9597 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9598 ST->isUnindexed() && !ST->isVolatile() &&
9599 // There can't be any side effects between the load and store, such as
9601 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9602 // The store is dead, remove it.
9607 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9608 // truncating store. We can do this even if this is already a truncstore.
9609 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9610 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9611 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9612 ST->getMemoryVT())) {
9613 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9614 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9617 // Only perform this optimization before the types are legal, because we
9618 // don't want to perform this optimization on every DAGCombine invocation.
9620 bool EverChanged = false;
9623 // There can be multiple store sequences on the same chain.
9624 // Keep trying to merge store sequences until we are unable to do so
9625 // or until we merge the last store on the chain.
9626 bool Changed = MergeConsecutiveStores(ST);
9627 EverChanged |= Changed;
9628 if (!Changed) break;
9629 } while (ST->getOpcode() != ISD::DELETED_NODE);
9632 return SDValue(N, 0);
9635 return ReduceLoadOpStoreWidth(N);
9638 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9639 SDValue InVec = N->getOperand(0);
9640 SDValue InVal = N->getOperand(1);
9641 SDValue EltNo = N->getOperand(2);
9644 // If the inserted element is an UNDEF, just use the input vector.
9645 if (InVal.getOpcode() == ISD::UNDEF)
9648 EVT VT = InVec.getValueType();
9650 // If we can't generate a legal BUILD_VECTOR, exit
9651 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9654 // Check that we know which element is being inserted
9655 if (!isa<ConstantSDNode>(EltNo))
9657 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9659 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9660 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9662 SmallVector<SDValue, 8> Ops;
9663 // Do not combine these two vectors if the output vector will not replace
9664 // the input vector.
9665 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9666 Ops.append(InVec.getNode()->op_begin(),
9667 InVec.getNode()->op_end());
9668 } else if (InVec.getOpcode() == ISD::UNDEF) {
9669 unsigned NElts = VT.getVectorNumElements();
9670 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9675 // Insert the element
9676 if (Elt < Ops.size()) {
9677 // All the operands of BUILD_VECTOR must have the same type;
9678 // we enforce that here.
9679 EVT OpVT = Ops[0].getValueType();
9680 if (InVal.getValueType() != OpVT)
9681 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9682 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9683 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9687 // Return the new vector
9688 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9689 VT, &Ops[0], Ops.size());
9692 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9693 // (vextract (scalar_to_vector val, 0) -> val
9694 SDValue InVec = N->getOperand(0);
9695 EVT VT = InVec.getValueType();
9696 EVT NVT = N->getValueType(0);
9698 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9699 // Check if the result type doesn't match the inserted element type. A
9700 // SCALAR_TO_VECTOR may truncate the inserted element and the
9701 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9702 SDValue InOp = InVec.getOperand(0);
9703 if (InOp.getValueType() != NVT) {
9704 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9705 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9710 SDValue EltNo = N->getOperand(1);
9711 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9713 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9714 // We only perform this optimization before the op legalization phase because
9715 // we may introduce new vector instructions which are not backed by TD
9716 // patterns. For example on AVX, extracting elements from a wide vector
9717 // without using extract_subvector.
9718 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9719 && ConstEltNo && !LegalOperations) {
9720 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9721 int NumElem = VT.getVectorNumElements();
9722 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9723 // Find the new index to extract from.
9724 int OrigElt = SVOp->getMaskElt(Elt);
9726 // Extracting an undef index is undef.
9728 return DAG.getUNDEF(NVT);
9730 // Select the right vector half to extract from.
9731 if (OrigElt < NumElem) {
9732 InVec = InVec->getOperand(0);
9734 InVec = InVec->getOperand(1);
9738 EVT IndexTy = TLI.getVectorIdxTy();
9739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9740 InVec, DAG.getConstant(OrigElt, IndexTy));
9743 // Perform only after legalization to ensure build_vector / vector_shuffle
9744 // optimizations have already been done.
9745 if (!LegalOperations) return SDValue();
9747 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9748 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9749 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9752 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9753 bool NewLoad = false;
9754 bool BCNumEltsChanged = false;
9755 EVT ExtVT = VT.getVectorElementType();
9758 // If the result of load has to be truncated, then it's not necessarily
9760 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9763 if (InVec.getOpcode() == ISD::BITCAST) {
9764 // Don't duplicate a load with other uses.
9765 if (!InVec.hasOneUse())
9768 EVT BCVT = InVec.getOperand(0).getValueType();
9769 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9771 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9772 BCNumEltsChanged = true;
9773 InVec = InVec.getOperand(0);
9774 ExtVT = BCVT.getVectorElementType();
9778 LoadSDNode *LN0 = NULL;
9779 const ShuffleVectorSDNode *SVN = NULL;
9780 if (ISD::isNormalLoad(InVec.getNode())) {
9781 LN0 = cast<LoadSDNode>(InVec);
9782 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9783 InVec.getOperand(0).getValueType() == ExtVT &&
9784 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9785 // Don't duplicate a load with other uses.
9786 if (!InVec.hasOneUse())
9789 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9790 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9791 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9793 // (load $addr+1*size)
9795 // Don't duplicate a load with other uses.
9796 if (!InVec.hasOneUse())
9799 // If the bit convert changed the number of elements, it is unsafe
9800 // to examine the mask.
9801 if (BCNumEltsChanged)
9804 // Select the input vector, guarding against out of range extract vector.
9805 unsigned NumElems = VT.getVectorNumElements();
9806 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9807 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9809 if (InVec.getOpcode() == ISD::BITCAST) {
9810 // Don't duplicate a load with other uses.
9811 if (!InVec.hasOneUse())
9814 InVec = InVec.getOperand(0);
9816 if (ISD::isNormalLoad(InVec.getNode())) {
9817 LN0 = cast<LoadSDNode>(InVec);
9818 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9822 // Make sure we found a non-volatile load and the extractelement is
9824 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9827 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9829 return DAG.getUNDEF(LVT);
9831 unsigned Align = LN0->getAlignment();
9833 // Check the resultant load doesn't need a higher alignment than the
9837 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9839 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9845 SDValue NewPtr = LN0->getBasePtr();
9846 unsigned PtrOff = 0;
9849 PtrOff = LVT.getSizeInBits() * Elt / 8;
9850 EVT PtrType = NewPtr.getValueType();
9851 if (TLI.isBigEndian())
9852 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9853 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9854 DAG.getConstant(PtrOff, PtrType));
9857 // The replacement we need to do here is a little tricky: we need to
9858 // replace an extractelement of a load with a load.
9859 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9860 // Note that this replacement assumes that the extractvalue is the only
9861 // use of the load; that's okay because we don't want to perform this
9862 // transformation in other cases anyway.
9865 if (NVT.bitsGT(LVT)) {
9866 // If the result type of vextract is wider than the load, then issue an
9867 // extending load instead.
9868 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9869 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9870 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9871 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9872 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9873 Align, LN0->getTBAAInfo());
9874 Chain = Load.getValue(1);
9876 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9877 LN0->getPointerInfo().getWithOffset(PtrOff),
9878 LN0->isVolatile(), LN0->isNonTemporal(),
9879 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9880 Chain = Load.getValue(1);
9881 if (NVT.bitsLT(LVT))
9882 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9884 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9886 WorkListRemover DeadNodes(*this);
9887 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9888 SDValue To[] = { Load, Chain };
9889 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9890 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9891 // worklist explicitly as well.
9892 AddToWorkList(Load.getNode());
9893 AddUsersToWorkList(Load.getNode()); // Add users too
9894 // Make sure to revisit this node to clean it up; it will usually be dead.
9896 return SDValue(N, 0);
9902 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9903 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9904 // We perform this optimization post type-legalization because
9905 // the type-legalizer often scalarizes integer-promoted vectors.
9906 // Performing this optimization before may create bit-casts which
9907 // will be type-legalized to complex code sequences.
9908 // We perform this optimization only before the operation legalizer because we
9909 // may introduce illegal operations.
9910 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9913 unsigned NumInScalars = N->getNumOperands();
9915 EVT VT = N->getValueType(0);
9917 // Check to see if this is a BUILD_VECTOR of a bunch of values
9918 // which come from any_extend or zero_extend nodes. If so, we can create
9919 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9920 // optimizations. We do not handle sign-extend because we can't fill the sign
9922 EVT SourceType = MVT::Other;
9923 bool AllAnyExt = true;
9925 for (unsigned i = 0; i != NumInScalars; ++i) {
9926 SDValue In = N->getOperand(i);
9927 // Ignore undef inputs.
9928 if (In.getOpcode() == ISD::UNDEF) continue;
9930 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9931 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9933 // Abort if the element is not an extension.
9934 if (!ZeroExt && !AnyExt) {
9935 SourceType = MVT::Other;
9939 // The input is a ZeroExt or AnyExt. Check the original type.
9940 EVT InTy = In.getOperand(0).getValueType();
9942 // Check that all of the widened source types are the same.
9943 if (SourceType == MVT::Other)
9946 else if (InTy != SourceType) {
9947 // Multiple income types. Abort.
9948 SourceType = MVT::Other;
9952 // Check if all of the extends are ANY_EXTENDs.
9953 AllAnyExt &= AnyExt;
9956 // In order to have valid types, all of the inputs must be extended from the
9957 // same source type and all of the inputs must be any or zero extend.
9958 // Scalar sizes must be a power of two.
9959 EVT OutScalarTy = VT.getScalarType();
9960 bool ValidTypes = SourceType != MVT::Other &&
9961 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9962 isPowerOf2_32(SourceType.getSizeInBits());
9964 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9965 // turn into a single shuffle instruction.
9969 bool isLE = TLI.isLittleEndian();
9970 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9971 assert(ElemRatio > 1 && "Invalid element size ratio");
9972 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9973 DAG.getConstant(0, SourceType);
9975 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9976 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9978 // Populate the new build_vector
9979 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9980 SDValue Cast = N->getOperand(i);
9981 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9982 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9983 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9985 if (Cast.getOpcode() == ISD::UNDEF)
9986 In = DAG.getUNDEF(SourceType);
9988 In = Cast->getOperand(0);
9989 unsigned Index = isLE ? (i * ElemRatio) :
9990 (i * ElemRatio + (ElemRatio - 1));
9992 assert(Index < Ops.size() && "Invalid index");
9996 // The type of the new BUILD_VECTOR node.
9997 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9998 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9999 "Invalid vector size");
10000 // Check if the new vector type is legal.
10001 if (!isTypeLegal(VecVT)) return SDValue();
10003 // Make the new BUILD_VECTOR.
10004 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10006 // The new BUILD_VECTOR node has the potential to be further optimized.
10007 AddToWorkList(BV.getNode());
10008 // Bitcast to the desired type.
10009 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10012 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10013 EVT VT = N->getValueType(0);
10015 unsigned NumInScalars = N->getNumOperands();
10018 EVT SrcVT = MVT::Other;
10019 unsigned Opcode = ISD::DELETED_NODE;
10020 unsigned NumDefs = 0;
10022 for (unsigned i = 0; i != NumInScalars; ++i) {
10023 SDValue In = N->getOperand(i);
10024 unsigned Opc = In.getOpcode();
10026 if (Opc == ISD::UNDEF)
10029 // If all scalar values are floats and converted from integers.
10030 if (Opcode == ISD::DELETED_NODE &&
10031 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10038 EVT InVT = In.getOperand(0).getValueType();
10040 // If all scalar values are typed differently, bail out. It's chosen to
10041 // simplify BUILD_VECTOR of integer types.
10042 if (SrcVT == MVT::Other)
10049 // If the vector has just one element defined, it's not worth to fold it into
10050 // a vectorized one.
10054 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10055 && "Should only handle conversion from integer to float.");
10056 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10060 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10063 SmallVector<SDValue, 8> Opnds;
10064 for (unsigned i = 0; i != NumInScalars; ++i) {
10065 SDValue In = N->getOperand(i);
10067 if (In.getOpcode() == ISD::UNDEF)
10068 Opnds.push_back(DAG.getUNDEF(SrcVT));
10070 Opnds.push_back(In.getOperand(0));
10072 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10073 &Opnds[0], Opnds.size());
10074 AddToWorkList(BV.getNode());
10076 return DAG.getNode(Opcode, dl, VT, BV);
10079 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10080 unsigned NumInScalars = N->getNumOperands();
10082 EVT VT = N->getValueType(0);
10084 // A vector built entirely of undefs is undef.
10085 if (ISD::allOperandsUndef(N))
10086 return DAG.getUNDEF(VT);
10088 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10092 V = reduceBuildVecConvertToConvertBuildVec(N);
10096 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10097 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10098 // at most two distinct vectors, turn this into a shuffle node.
10100 // May only combine to shuffle after legalize if shuffle is legal.
10101 if (LegalOperations &&
10102 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10105 SDValue VecIn1, VecIn2;
10106 for (unsigned i = 0; i != NumInScalars; ++i) {
10107 // Ignore undef inputs.
10108 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10110 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10111 // constant index, bail out.
10112 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10113 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10114 VecIn1 = VecIn2 = SDValue(0, 0);
10118 // We allow up to two distinct input vectors.
10119 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10120 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10123 if (VecIn1.getNode() == 0) {
10124 VecIn1 = ExtractedFromVec;
10125 } else if (VecIn2.getNode() == 0) {
10126 VecIn2 = ExtractedFromVec;
10128 // Too many inputs.
10129 VecIn1 = VecIn2 = SDValue(0, 0);
10134 // If everything is good, we can make a shuffle operation.
10135 if (VecIn1.getNode()) {
10136 SmallVector<int, 8> Mask;
10137 for (unsigned i = 0; i != NumInScalars; ++i) {
10138 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10139 Mask.push_back(-1);
10143 // If extracting from the first vector, just use the index directly.
10144 SDValue Extract = N->getOperand(i);
10145 SDValue ExtVal = Extract.getOperand(1);
10146 if (Extract.getOperand(0) == VecIn1) {
10147 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10148 if (ExtIndex > VT.getVectorNumElements())
10151 Mask.push_back(ExtIndex);
10155 // Otherwise, use InIdx + VecSize
10156 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10157 Mask.push_back(Idx+NumInScalars);
10160 // We can't generate a shuffle node with mismatched input and output types.
10161 // Attempt to transform a single input vector to the correct type.
10162 if ((VT != VecIn1.getValueType())) {
10163 // We don't support shuffeling between TWO values of different types.
10164 if (VecIn2.getNode() != 0)
10167 // We only support widening of vectors which are half the size of the
10168 // output registers. For example XMM->YMM widening on X86 with AVX.
10169 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10172 // If the input vector type has a different base type to the output
10173 // vector type, bail out.
10174 if (VecIn1.getValueType().getVectorElementType() !=
10175 VT.getVectorElementType())
10178 // Widen the input vector by adding undef values.
10179 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10180 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10183 // If VecIn2 is unused then change it to undef.
10184 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10186 // Check that we were able to transform all incoming values to the same
10188 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10189 VecIn1.getValueType() != VT)
10192 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10193 if (!isTypeLegal(VT))
10196 // Return the new VECTOR_SHUFFLE node.
10200 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10206 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10207 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10208 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10209 // inputs come from at most two distinct vectors, turn this into a shuffle
10212 // If we only have one input vector, we don't need to do any concatenation.
10213 if (N->getNumOperands() == 1)
10214 return N->getOperand(0);
10216 // Check if all of the operands are undefs.
10217 EVT VT = N->getValueType(0);
10218 if (ISD::allOperandsUndef(N))
10219 return DAG.getUNDEF(VT);
10221 // Optimize concat_vectors where one of the vectors is undef.
10222 if (N->getNumOperands() == 2 &&
10223 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10224 SDValue In = N->getOperand(0);
10225 assert(In.getValueType().isVector() && "Must concat vectors");
10227 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10228 if (In->getOpcode() == ISD::BITCAST &&
10229 !In->getOperand(0)->getValueType(0).isVector()) {
10230 SDValue Scalar = In->getOperand(0);
10231 EVT SclTy = Scalar->getValueType(0);
10233 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10236 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10237 VT.getSizeInBits() / SclTy.getSizeInBits());
10238 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10241 SDLoc dl = SDLoc(N);
10242 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10243 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10247 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10248 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10249 if (N->getNumOperands() == 2 &&
10250 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10251 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10252 EVT VT = N->getValueType(0);
10253 SDValue N0 = N->getOperand(0);
10254 SDValue N1 = N->getOperand(1);
10255 SmallVector<SDValue, 8> Opnds;
10256 unsigned BuildVecNumElts = N0.getNumOperands();
10258 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10259 Opnds.push_back(N0.getOperand(i));
10260 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10261 Opnds.push_back(N1.getOperand(i));
10263 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10267 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10268 // nodes often generate nop CONCAT_VECTOR nodes.
10269 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10270 // place the incoming vectors at the exact same location.
10271 SDValue SingleSource = SDValue();
10272 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10274 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10275 SDValue Op = N->getOperand(i);
10277 if (Op.getOpcode() == ISD::UNDEF)
10280 // Check if this is the identity extract:
10281 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10284 // Find the single incoming vector for the extract_subvector.
10285 if (SingleSource.getNode()) {
10286 if (Op.getOperand(0) != SingleSource)
10289 SingleSource = Op.getOperand(0);
10291 // Check the source type is the same as the type of the result.
10292 // If not, this concat may extend the vector, so we can not
10293 // optimize it away.
10294 if (SingleSource.getValueType() != N->getValueType(0))
10298 unsigned IdentityIndex = i * PartNumElem;
10299 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10300 // The extract index must be constant.
10304 // Check that we are reading from the identity index.
10305 if (CS->getZExtValue() != IdentityIndex)
10309 if (SingleSource.getNode())
10310 return SingleSource;
10315 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10316 EVT NVT = N->getValueType(0);
10317 SDValue V = N->getOperand(0);
10319 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10321 // (extract_subvec (concat V1, V2, ...), i)
10324 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10326 if (V->getOperand(0).getValueType() != NVT)
10328 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10329 unsigned NumElems = NVT.getVectorNumElements();
10330 assert((Idx % NumElems) == 0 &&
10331 "IDX in concat is not a multiple of the result vector length.");
10332 return V->getOperand(Idx / NumElems);
10336 if (V->getOpcode() == ISD::BITCAST)
10337 V = V.getOperand(0);
10339 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10341 // Handle only simple case where vector being inserted and vector
10342 // being extracted are of same type, and are half size of larger vectors.
10343 EVT BigVT = V->getOperand(0).getValueType();
10344 EVT SmallVT = V->getOperand(1).getValueType();
10345 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10348 // Only handle cases where both indexes are constants with the same type.
10349 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10350 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10352 if (InsIdx && ExtIdx &&
10353 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10354 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10356 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10358 // indices are equal or bit offsets are equal => V1
10359 // otherwise => (extract_subvec V1, ExtIdx)
10360 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10361 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10362 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10363 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10364 DAG.getNode(ISD::BITCAST, dl,
10365 N->getOperand(0).getValueType(),
10366 V->getOperand(0)), N->getOperand(1));
10373 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10374 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10375 EVT VT = N->getValueType(0);
10376 unsigned NumElts = VT.getVectorNumElements();
10378 SDValue N0 = N->getOperand(0);
10379 SDValue N1 = N->getOperand(1);
10380 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10382 SmallVector<SDValue, 4> Ops;
10383 EVT ConcatVT = N0.getOperand(0).getValueType();
10384 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10385 unsigned NumConcats = NumElts / NumElemsPerConcat;
10387 // Look at every vector that's inserted. We're looking for exact
10388 // subvector-sized copies from a concatenated vector
10389 for (unsigned I = 0; I != NumConcats; ++I) {
10390 // Make sure we're dealing with a copy.
10391 unsigned Begin = I * NumElemsPerConcat;
10392 bool AllUndef = true, NoUndef = true;
10393 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10394 if (SVN->getMaskElt(J) >= 0)
10401 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10404 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10405 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10408 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10409 if (FirstElt < N0.getNumOperands())
10410 Ops.push_back(N0.getOperand(FirstElt));
10412 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10414 } else if (AllUndef) {
10415 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10416 } else { // Mixed with general masks and undefs, can't do optimization.
10421 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10425 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10426 EVT VT = N->getValueType(0);
10427 unsigned NumElts = VT.getVectorNumElements();
10429 SDValue N0 = N->getOperand(0);
10430 SDValue N1 = N->getOperand(1);
10432 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10434 // Canonicalize shuffle undef, undef -> undef
10435 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10436 return DAG.getUNDEF(VT);
10438 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10440 // Canonicalize shuffle v, v -> v, undef
10442 SmallVector<int, 8> NewMask;
10443 for (unsigned i = 0; i != NumElts; ++i) {
10444 int Idx = SVN->getMaskElt(i);
10445 if (Idx >= (int)NumElts) Idx -= NumElts;
10446 NewMask.push_back(Idx);
10448 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10452 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10453 if (N0.getOpcode() == ISD::UNDEF) {
10454 SmallVector<int, 8> NewMask;
10455 for (unsigned i = 0; i != NumElts; ++i) {
10456 int Idx = SVN->getMaskElt(i);
10458 if (Idx >= (int)NumElts)
10461 Idx = -1; // remove reference to lhs
10463 NewMask.push_back(Idx);
10465 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10469 // Remove references to rhs if it is undef
10470 if (N1.getOpcode() == ISD::UNDEF) {
10471 bool Changed = false;
10472 SmallVector<int, 8> NewMask;
10473 for (unsigned i = 0; i != NumElts; ++i) {
10474 int Idx = SVN->getMaskElt(i);
10475 if (Idx >= (int)NumElts) {
10479 NewMask.push_back(Idx);
10482 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10485 // If it is a splat, check if the argument vector is another splat or a
10486 // build_vector with all scalar elements the same.
10487 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10488 SDNode *V = N0.getNode();
10490 // If this is a bit convert that changes the element type of the vector but
10491 // not the number of vector elements, look through it. Be careful not to
10492 // look though conversions that change things like v4f32 to v2f64.
10493 if (V->getOpcode() == ISD::BITCAST) {
10494 SDValue ConvInput = V->getOperand(0);
10495 if (ConvInput.getValueType().isVector() &&
10496 ConvInput.getValueType().getVectorNumElements() == NumElts)
10497 V = ConvInput.getNode();
10500 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10501 assert(V->getNumOperands() == NumElts &&
10502 "BUILD_VECTOR has wrong number of operands");
10504 bool AllSame = true;
10505 for (unsigned i = 0; i != NumElts; ++i) {
10506 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10507 Base = V->getOperand(i);
10511 // Splat of <u, u, u, u>, return <u, u, u, u>
10512 if (!Base.getNode())
10514 for (unsigned i = 0; i != NumElts; ++i) {
10515 if (V->getOperand(i) != Base) {
10520 // Splat of <x, x, x, x>, return <x, x, x, x>
10526 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10527 Level < AfterLegalizeVectorOps &&
10528 (N1.getOpcode() == ISD::UNDEF ||
10529 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10530 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10531 SDValue V = partitionShuffleOfConcats(N, DAG);
10537 // If this shuffle node is simply a swizzle of another shuffle node,
10538 // and it reverses the swizzle of the previous shuffle then we can
10539 // optimize shuffle(shuffle(x, undef), undef) -> x.
10540 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10541 N1.getOpcode() == ISD::UNDEF) {
10543 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10545 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10546 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10549 // The incoming shuffle must be of the same type as the result of the
10550 // current shuffle.
10551 assert(OtherSV->getOperand(0).getValueType() == VT &&
10552 "Shuffle types don't match");
10554 for (unsigned i = 0; i != NumElts; ++i) {
10555 int Idx = SVN->getMaskElt(i);
10556 assert(Idx < (int)NumElts && "Index references undef operand");
10557 // Next, this index comes from the first value, which is the incoming
10558 // shuffle. Adopt the incoming index.
10560 Idx = OtherSV->getMaskElt(Idx);
10562 // The combined shuffle must map each index to itself.
10563 if (Idx >= 0 && (unsigned)Idx != i)
10567 return OtherSV->getOperand(0);
10573 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10574 SDValue N0 = N->getOperand(0);
10575 SDValue N2 = N->getOperand(2);
10577 // If the input vector is a concatenation, and the insert replaces
10578 // one of the halves, we can optimize into a single concat_vectors.
10579 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10580 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10581 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10582 EVT VT = N->getValueType(0);
10584 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10585 // (concat_vectors Z, Y)
10587 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10588 N->getOperand(1), N0.getOperand(1));
10590 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10591 // (concat_vectors X, Z)
10592 if (InsIdx == VT.getVectorNumElements()/2)
10593 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10594 N0.getOperand(0), N->getOperand(1));
10600 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10601 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10602 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10603 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10604 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10605 EVT VT = N->getValueType(0);
10607 SDValue LHS = N->getOperand(0);
10608 SDValue RHS = N->getOperand(1);
10609 if (N->getOpcode() == ISD::AND) {
10610 if (RHS.getOpcode() == ISD::BITCAST)
10611 RHS = RHS.getOperand(0);
10612 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10613 SmallVector<int, 8> Indices;
10614 unsigned NumElts = RHS.getNumOperands();
10615 for (unsigned i = 0; i != NumElts; ++i) {
10616 SDValue Elt = RHS.getOperand(i);
10617 if (!isa<ConstantSDNode>(Elt))
10620 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10621 Indices.push_back(i);
10622 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10623 Indices.push_back(NumElts);
10628 // Let's see if the target supports this vector_shuffle.
10629 EVT RVT = RHS.getValueType();
10630 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10633 // Return the new VECTOR_SHUFFLE node.
10634 EVT EltVT = RVT.getVectorElementType();
10635 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10636 DAG.getConstant(0, EltVT));
10637 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10638 RVT, &ZeroOps[0], ZeroOps.size());
10639 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10640 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10641 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10648 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10649 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10650 assert(N->getValueType(0).isVector() &&
10651 "SimplifyVBinOp only works on vectors!");
10653 SDValue LHS = N->getOperand(0);
10654 SDValue RHS = N->getOperand(1);
10655 SDValue Shuffle = XformToShuffleWithZero(N);
10656 if (Shuffle.getNode()) return Shuffle;
10658 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10660 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10661 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10662 // Check if both vectors are constants. If not bail out.
10663 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10664 cast<BuildVectorSDNode>(RHS)->isConstant()))
10667 SmallVector<SDValue, 8> Ops;
10668 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10669 SDValue LHSOp = LHS.getOperand(i);
10670 SDValue RHSOp = RHS.getOperand(i);
10672 // Can't fold divide by zero.
10673 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10674 N->getOpcode() == ISD::FDIV) {
10675 if ((RHSOp.getOpcode() == ISD::Constant &&
10676 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10677 (RHSOp.getOpcode() == ISD::ConstantFP &&
10678 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10682 EVT VT = LHSOp.getValueType();
10683 EVT RVT = RHSOp.getValueType();
10685 // Integer BUILD_VECTOR operands may have types larger than the element
10686 // size (e.g., when the element type is not legal). Prior to type
10687 // legalization, the types may not match between the two BUILD_VECTORS.
10688 // Truncate one of the operands to make them match.
10689 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10690 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10692 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10696 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10698 if (FoldOp.getOpcode() != ISD::UNDEF &&
10699 FoldOp.getOpcode() != ISD::Constant &&
10700 FoldOp.getOpcode() != ISD::ConstantFP)
10702 Ops.push_back(FoldOp);
10703 AddToWorkList(FoldOp.getNode());
10706 if (Ops.size() == LHS.getNumOperands())
10707 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10708 LHS.getValueType(), &Ops[0], Ops.size());
10714 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10715 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10716 assert(N->getValueType(0).isVector() &&
10717 "SimplifyVUnaryOp only works on vectors!");
10719 SDValue N0 = N->getOperand(0);
10721 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10724 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10725 SmallVector<SDValue, 8> Ops;
10726 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10727 SDValue Op = N0.getOperand(i);
10728 if (Op.getOpcode() != ISD::UNDEF &&
10729 Op.getOpcode() != ISD::ConstantFP)
10731 EVT EltVT = Op.getValueType();
10732 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10733 if (FoldOp.getOpcode() != ISD::UNDEF &&
10734 FoldOp.getOpcode() != ISD::ConstantFP)
10736 Ops.push_back(FoldOp);
10737 AddToWorkList(FoldOp.getNode());
10740 if (Ops.size() != N0.getNumOperands())
10743 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10744 N0.getValueType(), &Ops[0], Ops.size());
10747 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10748 SDValue N1, SDValue N2){
10749 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10751 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10752 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10754 // If we got a simplified select_cc node back from SimplifySelectCC, then
10755 // break it down into a new SETCC node, and a new SELECT node, and then return
10756 // the SELECT node, since we were called with a SELECT node.
10757 if (SCC.getNode()) {
10758 // Check to see if we got a select_cc back (to turn into setcc/select).
10759 // Otherwise, just return whatever node we got back, like fabs.
10760 if (SCC.getOpcode() == ISD::SELECT_CC) {
10761 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10763 SCC.getOperand(0), SCC.getOperand(1),
10764 SCC.getOperand(4));
10765 AddToWorkList(SETCC.getNode());
10766 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10767 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10775 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10776 /// are the two values being selected between, see if we can simplify the
10777 /// select. Callers of this should assume that TheSelect is deleted if this
10778 /// returns true. As such, they should return the appropriate thing (e.g. the
10779 /// node) back to the top-level of the DAG combiner loop to avoid it being
10781 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10784 // Cannot simplify select with vector condition
10785 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10787 // If this is a select from two identical things, try to pull the operation
10788 // through the select.
10789 if (LHS.getOpcode() != RHS.getOpcode() ||
10790 !LHS.hasOneUse() || !RHS.hasOneUse())
10793 // If this is a load and the token chain is identical, replace the select
10794 // of two loads with a load through a select of the address to load from.
10795 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10796 // constants have been dropped into the constant pool.
10797 if (LHS.getOpcode() == ISD::LOAD) {
10798 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10799 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10801 // Token chains must be identical.
10802 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10803 // Do not let this transformation reduce the number of volatile loads.
10804 LLD->isVolatile() || RLD->isVolatile() ||
10805 // If this is an EXTLOAD, the VT's must match.
10806 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10807 // If this is an EXTLOAD, the kind of extension must match.
10808 (LLD->getExtensionType() != RLD->getExtensionType() &&
10809 // The only exception is if one of the extensions is anyext.
10810 LLD->getExtensionType() != ISD::EXTLOAD &&
10811 RLD->getExtensionType() != ISD::EXTLOAD) ||
10812 // FIXME: this discards src value information. This is
10813 // over-conservative. It would be beneficial to be able to remember
10814 // both potential memory locations. Since we are discarding
10815 // src value info, don't do the transformation if the memory
10816 // locations are not in the default address space.
10817 LLD->getPointerInfo().getAddrSpace() != 0 ||
10818 RLD->getPointerInfo().getAddrSpace() != 0 ||
10819 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10820 LLD->getBasePtr().getValueType()))
10823 // Check that the select condition doesn't reach either load. If so,
10824 // folding this will induce a cycle into the DAG. If not, this is safe to
10825 // xform, so create a select of the addresses.
10827 if (TheSelect->getOpcode() == ISD::SELECT) {
10828 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10829 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10830 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10832 // The loads must not depend on one another.
10833 if (LLD->isPredecessorOf(RLD) ||
10834 RLD->isPredecessorOf(LLD))
10836 Addr = DAG.getSelect(SDLoc(TheSelect),
10837 LLD->getBasePtr().getValueType(),
10838 TheSelect->getOperand(0), LLD->getBasePtr(),
10839 RLD->getBasePtr());
10840 } else { // Otherwise SELECT_CC
10841 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10842 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10844 if ((LLD->hasAnyUseOfValue(1) &&
10845 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10846 (RLD->hasAnyUseOfValue(1) &&
10847 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10850 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10851 LLD->getBasePtr().getValueType(),
10852 TheSelect->getOperand(0),
10853 TheSelect->getOperand(1),
10854 LLD->getBasePtr(), RLD->getBasePtr(),
10855 TheSelect->getOperand(4));
10859 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10860 Load = DAG.getLoad(TheSelect->getValueType(0),
10862 // FIXME: Discards pointer and TBAA info.
10863 LLD->getChain(), Addr, MachinePointerInfo(),
10864 LLD->isVolatile(), LLD->isNonTemporal(),
10865 LLD->isInvariant(), LLD->getAlignment());
10867 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10868 RLD->getExtensionType() : LLD->getExtensionType(),
10870 TheSelect->getValueType(0),
10871 // FIXME: Discards pointer and TBAA info.
10872 LLD->getChain(), Addr, MachinePointerInfo(),
10873 LLD->getMemoryVT(), LLD->isVolatile(),
10874 LLD->isNonTemporal(), LLD->getAlignment());
10877 // Users of the select now use the result of the load.
10878 CombineTo(TheSelect, Load);
10880 // Users of the old loads now use the new load's chain. We know the
10881 // old-load value is dead now.
10882 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10883 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10890 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10891 /// where 'cond' is the comparison specified by CC.
10892 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10893 SDValue N2, SDValue N3,
10894 ISD::CondCode CC, bool NotExtCompare) {
10895 // (x ? y : y) -> y.
10896 if (N2 == N3) return N2;
10898 EVT VT = N2.getValueType();
10899 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10900 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10901 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10903 // Determine if the condition we're dealing with is constant
10904 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10905 N0, N1, CC, DL, false);
10906 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10907 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10909 // fold select_cc true, x, y -> x
10910 if (SCCC && !SCCC->isNullValue())
10912 // fold select_cc false, x, y -> y
10913 if (SCCC && SCCC->isNullValue())
10916 // Check to see if we can simplify the select into an fabs node
10917 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10918 // Allow either -0.0 or 0.0
10919 if (CFP->getValueAPF().isZero()) {
10920 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10921 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10922 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10923 N2 == N3.getOperand(0))
10924 return DAG.getNode(ISD::FABS, DL, VT, N0);
10926 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10927 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10928 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10929 N2.getOperand(0) == N3)
10930 return DAG.getNode(ISD::FABS, DL, VT, N3);
10934 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10935 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10936 // in it. This is a win when the constant is not otherwise available because
10937 // it replaces two constant pool loads with one. We only do this if the FP
10938 // type is known to be legal, because if it isn't, then we are before legalize
10939 // types an we want the other legalization to happen first (e.g. to avoid
10940 // messing with soft float) and if the ConstantFP is not legal, because if
10941 // it is legal, we may not need to store the FP constant in a constant pool.
10942 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10943 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10944 if (TLI.isTypeLegal(N2.getValueType()) &&
10945 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10946 TargetLowering::Legal) &&
10947 // If both constants have multiple uses, then we won't need to do an
10948 // extra load, they are likely around in registers for other users.
10949 (TV->hasOneUse() || FV->hasOneUse())) {
10950 Constant *Elts[] = {
10951 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10952 const_cast<ConstantFP*>(TV->getConstantFPValue())
10954 Type *FPTy = Elts[0]->getType();
10955 const DataLayout &TD = *TLI.getDataLayout();
10957 // Create a ConstantArray of the two constants.
10958 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10959 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10960 TD.getPrefTypeAlignment(FPTy));
10961 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10963 // Get the offsets to the 0 and 1 element of the array so that we can
10964 // select between them.
10965 SDValue Zero = DAG.getIntPtrConstant(0);
10966 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10967 SDValue One = DAG.getIntPtrConstant(EltSize);
10969 SDValue Cond = DAG.getSetCC(DL,
10970 getSetCCResultType(N0.getValueType()),
10972 AddToWorkList(Cond.getNode());
10973 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10975 AddToWorkList(CstOffset.getNode());
10976 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10978 AddToWorkList(CPIdx.getNode());
10979 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10980 MachinePointerInfo::getConstantPool(), false,
10981 false, false, Alignment);
10986 // Check to see if we can perform the "gzip trick", transforming
10987 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10988 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10989 (N1C->isNullValue() || // (a < 0) ? b : 0
10990 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10991 EVT XType = N0.getValueType();
10992 EVT AType = N2.getValueType();
10993 if (XType.bitsGE(AType)) {
10994 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10995 // single-bit constant.
10996 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10997 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10998 ShCtV = XType.getSizeInBits()-ShCtV-1;
10999 SDValue ShCt = DAG.getConstant(ShCtV,
11000 getShiftAmountTy(N0.getValueType()));
11001 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11003 AddToWorkList(Shift.getNode());
11005 if (XType.bitsGT(AType)) {
11006 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11007 AddToWorkList(Shift.getNode());
11010 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11013 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11015 DAG.getConstant(XType.getSizeInBits()-1,
11016 getShiftAmountTy(N0.getValueType())));
11017 AddToWorkList(Shift.getNode());
11019 if (XType.bitsGT(AType)) {
11020 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11021 AddToWorkList(Shift.getNode());
11024 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11028 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11029 // where y is has a single bit set.
11030 // A plaintext description would be, we can turn the SELECT_CC into an AND
11031 // when the condition can be materialized as an all-ones register. Any
11032 // single bit-test can be materialized as an all-ones register with
11033 // shift-left and shift-right-arith.
11034 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11035 N0->getValueType(0) == VT &&
11036 N1C && N1C->isNullValue() &&
11037 N2C && N2C->isNullValue()) {
11038 SDValue AndLHS = N0->getOperand(0);
11039 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11040 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11041 // Shift the tested bit over the sign bit.
11042 APInt AndMask = ConstAndRHS->getAPIntValue();
11044 DAG.getConstant(AndMask.countLeadingZeros(),
11045 getShiftAmountTy(AndLHS.getValueType()));
11046 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11048 // Now arithmetic right shift it all the way over, so the result is either
11049 // all-ones, or zero.
11051 DAG.getConstant(AndMask.getBitWidth()-1,
11052 getShiftAmountTy(Shl.getValueType()));
11053 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11055 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11059 // fold select C, 16, 0 -> shl C, 4
11060 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11061 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11062 TargetLowering::ZeroOrOneBooleanContent) {
11064 // If the caller doesn't want us to simplify this into a zext of a compare,
11066 if (NotExtCompare && N2C->getAPIntValue() == 1)
11069 // Get a SetCC of the condition
11070 // NOTE: Don't create a SETCC if it's not legal on this target.
11071 if (!LegalOperations ||
11072 TLI.isOperationLegal(ISD::SETCC,
11073 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11075 // cast from setcc result type to select result type
11077 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11079 if (N2.getValueType().bitsLT(SCC.getValueType()))
11080 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11081 N2.getValueType());
11083 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11084 N2.getValueType(), SCC);
11086 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11088 N2.getValueType(), SCC);
11091 AddToWorkList(SCC.getNode());
11092 AddToWorkList(Temp.getNode());
11094 if (N2C->getAPIntValue() == 1)
11097 // shl setcc result by log2 n2c
11098 return DAG.getNode(
11099 ISD::SHL, DL, N2.getValueType(), Temp,
11100 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11101 getShiftAmountTy(Temp.getValueType())));
11105 // Check to see if this is the equivalent of setcc
11106 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11107 // otherwise, go ahead with the folds.
11108 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11109 EVT XType = N0.getValueType();
11110 if (!LegalOperations ||
11111 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11112 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11113 if (Res.getValueType() != VT)
11114 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11118 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11119 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11120 (!LegalOperations ||
11121 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11122 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11123 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11124 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11125 getShiftAmountTy(Ctlz.getValueType())));
11127 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11128 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11129 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11130 XType, DAG.getConstant(0, XType), N0);
11131 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11132 return DAG.getNode(ISD::SRL, DL, XType,
11133 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11134 DAG.getConstant(XType.getSizeInBits()-1,
11135 getShiftAmountTy(XType)));
11137 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11138 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11139 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11140 DAG.getConstant(XType.getSizeInBits()-1,
11141 getShiftAmountTy(N0.getValueType())));
11142 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11146 // Check to see if this is an integer abs.
11147 // select_cc setg[te] X, 0, X, -X ->
11148 // select_cc setgt X, -1, X, -X ->
11149 // select_cc setl[te] X, 0, -X, X ->
11150 // select_cc setlt X, 1, -X, X ->
11151 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11153 ConstantSDNode *SubC = NULL;
11154 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11155 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11156 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11157 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11158 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11159 (N1C->isOne() && CC == ISD::SETLT)) &&
11160 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11161 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11163 EVT XType = N0.getValueType();
11164 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11165 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11167 DAG.getConstant(XType.getSizeInBits()-1,
11168 getShiftAmountTy(N0.getValueType())));
11169 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11171 AddToWorkList(Shift.getNode());
11172 AddToWorkList(Add.getNode());
11173 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11180 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11181 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11182 SDValue N1, ISD::CondCode Cond,
11183 SDLoc DL, bool foldBooleans) {
11184 TargetLowering::DAGCombinerInfo
11185 DagCombineInfo(DAG, Level, false, this);
11186 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11189 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11190 /// return a DAG expression to select that will generate the same value by
11191 /// multiplying by a magic number. See:
11192 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11193 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11194 std::vector<SDNode*> Built;
11195 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11197 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11199 AddToWorkList(*ii);
11203 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11204 /// return a DAG expression to select that will generate the same value by
11205 /// multiplying by a magic number. See:
11206 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11207 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11208 std::vector<SDNode*> Built;
11209 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11211 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11213 AddToWorkList(*ii);
11217 /// FindBaseOffset - Return true if base is a frame index, which is known not
11218 // to alias with anything but itself. Provides base object and offset as
11220 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11221 const GlobalValue *&GV, const void *&CV) {
11222 // Assume it is a primitive operation.
11223 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11225 // If it's an adding a simple constant then integrate the offset.
11226 if (Base.getOpcode() == ISD::ADD) {
11227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11228 Base = Base.getOperand(0);
11229 Offset += C->getZExtValue();
11233 // Return the underlying GlobalValue, and update the Offset. Return false
11234 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11235 // by multiple nodes with different offsets.
11236 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11237 GV = G->getGlobal();
11238 Offset += G->getOffset();
11242 // Return the underlying Constant value, and update the Offset. Return false
11243 // for ConstantSDNodes since the same constant pool entry may be represented
11244 // by multiple nodes with different offsets.
11245 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11246 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11247 : (const void *)C->getConstVal();
11248 Offset += C->getOffset();
11251 // If it's any of the following then it can't alias with anything but itself.
11252 return isa<FrameIndexSDNode>(Base);
11255 /// isAlias - Return true if there is any possibility that the two addresses
11257 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11258 const Value *SrcValue1, int SrcValueOffset1,
11259 unsigned SrcValueAlign1,
11260 const MDNode *TBAAInfo1,
11261 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11262 const Value *SrcValue2, int SrcValueOffset2,
11263 unsigned SrcValueAlign2,
11264 const MDNode *TBAAInfo2) const {
11265 // If they are the same then they must be aliases.
11266 if (Ptr1 == Ptr2) return true;
11268 // If they are both volatile then they cannot be reordered.
11269 if (IsVolatile1 && IsVolatile2) return true;
11271 // Gather base node and offset information.
11272 SDValue Base1, Base2;
11273 int64_t Offset1, Offset2;
11274 const GlobalValue *GV1, *GV2;
11275 const void *CV1, *CV2;
11276 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11277 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11279 // If they have a same base address then check to see if they overlap.
11280 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11281 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11283 // It is possible for different frame indices to alias each other, mostly
11284 // when tail call optimization reuses return address slots for arguments.
11285 // To catch this case, look up the actual index of frame indices to compute
11286 // the real alias relationship.
11287 if (isFrameIndex1 && isFrameIndex2) {
11288 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11289 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11290 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11291 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11294 // Otherwise, if we know what the bases are, and they aren't identical, then
11295 // we know they cannot alias.
11296 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11299 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11300 // compared to the size and offset of the access, we may be able to prove they
11301 // do not alias. This check is conservative for now to catch cases created by
11302 // splitting vector types.
11303 if ((SrcValueAlign1 == SrcValueAlign2) &&
11304 (SrcValueOffset1 != SrcValueOffset2) &&
11305 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11306 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11307 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11309 // There is no overlap between these relatively aligned accesses of similar
11310 // size, return no alias.
11311 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11315 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11318 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11319 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11322 if (UseAA && SrcValue1 && SrcValue2) {
11323 // Use alias analysis information.
11324 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11325 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11326 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11327 AliasAnalysis::AliasResult AAResult =
11328 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11329 UseTBAA ? TBAAInfo1 : 0),
11330 AliasAnalysis::Location(SrcValue2, Overlap2,
11331 UseTBAA ? TBAAInfo2 : 0));
11332 if (AAResult == AliasAnalysis::NoAlias)
11336 // Otherwise we have to assume they alias.
11340 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11341 SDValue Ptr0, Ptr1;
11342 int64_t Size0, Size1;
11343 bool IsVolatile0, IsVolatile1;
11344 const Value *SrcValue0, *SrcValue1;
11345 int SrcValueOffset0, SrcValueOffset1;
11346 unsigned SrcValueAlign0, SrcValueAlign1;
11347 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11348 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11349 SrcValueAlign0, SrcTBAAInfo0);
11350 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11351 SrcValueAlign1, SrcTBAAInfo1);
11352 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11353 SrcValueAlign0, SrcTBAAInfo0,
11354 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11355 SrcValueAlign1, SrcTBAAInfo1);
11358 /// FindAliasInfo - Extracts the relevant alias information from the memory
11359 /// node. Returns true if the operand was a nonvolatile load.
11360 bool DAGCombiner::FindAliasInfo(SDNode *N,
11361 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11362 const Value *&SrcValue,
11363 int &SrcValueOffset,
11364 unsigned &SrcValueAlign,
11365 const MDNode *&TBAAInfo) const {
11366 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11368 Ptr = LS->getBasePtr();
11369 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11370 IsVolatile = LS->isVolatile();
11371 SrcValue = LS->getSrcValue();
11372 SrcValueOffset = LS->getSrcValueOffset();
11373 SrcValueAlign = LS->getOriginalAlignment();
11374 TBAAInfo = LS->getTBAAInfo();
11375 return isa<LoadSDNode>(LS) && !IsVolatile;
11378 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11379 /// looking for aliasing nodes and adding them to the Aliases vector.
11380 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11381 SmallVectorImpl<SDValue> &Aliases) {
11382 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11383 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11385 // Get alias information for node.
11389 const Value *SrcValue;
11390 int SrcValueOffset;
11391 unsigned SrcValueAlign;
11392 const MDNode *SrcTBAAInfo;
11393 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11394 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11397 Chains.push_back(OriginalChain);
11398 unsigned Depth = 0;
11400 // Look at each chain and determine if it is an alias. If so, add it to the
11401 // aliases list. If not, then continue up the chain looking for the next
11403 while (!Chains.empty()) {
11404 SDValue Chain = Chains.back();
11407 // For TokenFactor nodes, look at each operand and only continue up the
11408 // chain until we find two aliases. If we've seen two aliases, assume we'll
11409 // find more and revert to original chain since the xform is unlikely to be
11412 // FIXME: The depth check could be made to return the last non-aliasing
11413 // chain we found before we hit a tokenfactor rather than the original
11415 if (Depth > 6 || Aliases.size() == 2) {
11417 Aliases.push_back(OriginalChain);
11421 // Don't bother if we've been before.
11422 if (!Visited.insert(Chain.getNode()))
11425 switch (Chain.getOpcode()) {
11426 case ISD::EntryToken:
11427 // Entry token is ideal chain operand, but handled in FindBetterChain.
11432 // Get alias information for Chain.
11436 const Value *OpSrcValue;
11437 int OpSrcValueOffset;
11438 unsigned OpSrcValueAlign;
11439 const MDNode *OpSrcTBAAInfo;
11440 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11441 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11445 // If chain is alias then stop here.
11446 if (!(IsLoad && IsOpLoad) &&
11447 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11448 SrcValueAlign, SrcTBAAInfo,
11449 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11450 OpSrcValueAlign, OpSrcTBAAInfo)) {
11451 Aliases.push_back(Chain);
11453 // Look further up the chain.
11454 Chains.push_back(Chain.getOperand(0));
11460 case ISD::TokenFactor:
11461 // We have to check each of the operands of the token factor for "small"
11462 // token factors, so we queue them up. Adding the operands to the queue
11463 // (stack) in reverse order maintains the original order and increases the
11464 // likelihood that getNode will find a matching token factor (CSE.)
11465 if (Chain.getNumOperands() > 16) {
11466 Aliases.push_back(Chain);
11469 for (unsigned n = Chain.getNumOperands(); n;)
11470 Chains.push_back(Chain.getOperand(--n));
11475 // For all other instructions we will just have to take what we can get.
11476 Aliases.push_back(Chain);
11481 // We need to be careful here to also search for aliases through the
11482 // value operand of a store, etc. Consider the following situation:
11484 // L1 = load Token1, %52
11485 // S1 = store Token1, L1, %51
11486 // L2 = load Token1, %52+8
11487 // S2 = store Token1, L2, %51+8
11488 // Token2 = Token(S1, S2)
11489 // L3 = load Token2, %53
11490 // S3 = store Token2, L3, %52
11491 // L4 = load Token2, %53+8
11492 // S4 = store Token2, L4, %52+8
11493 // If we search for aliases of S3 (which loads address %52), and we look
11494 // only through the chain, then we'll miss the trivial dependence on L1
11495 // (which also loads from %52). We then might change all loads and
11496 // stores to use Token1 as their chain operand, which could result in
11497 // copying %53 into %52 before copying %52 into %51 (which should
11500 // The problem is, however, that searching for such data dependencies
11501 // can become expensive, and the cost is not directly related to the
11502 // chain depth. Instead, we'll rule out such configurations here by
11503 // insisting that we've visited all chain users (except for users
11504 // of the original chain, which is not necessary). When doing this,
11505 // we need to look through nodes we don't care about (otherwise, things
11506 // like register copies will interfere with trivial cases).
11508 SmallVector<const SDNode *, 16> Worklist;
11509 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11510 IE = Visited.end(); I != IE; ++I)
11511 if (*I != OriginalChain.getNode())
11512 Worklist.push_back(*I);
11514 while (!Worklist.empty()) {
11515 const SDNode *M = Worklist.pop_back_val();
11517 // We have already visited M, and want to make sure we've visited any uses
11518 // of M that we care about. For uses that we've not visisted, and don't
11519 // care about, queue them to the worklist.
11521 for (SDNode::use_iterator UI = M->use_begin(),
11522 UIE = M->use_end(); UI != UIE; ++UI)
11523 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11524 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11525 // We've not visited this use, and we care about it (it could have an
11526 // ordering dependency with the original node).
11528 Aliases.push_back(OriginalChain);
11532 // We've not visited this use, but we don't care about it. Mark it as
11533 // visited and enqueue it to the worklist.
11534 Worklist.push_back(*UI);
11539 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11540 /// for a better chain (aliasing node.)
11541 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11542 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11544 // Accumulate all the aliases to this node.
11545 GatherAllAliases(N, OldChain, Aliases);
11547 // If no operands then chain to entry token.
11548 if (Aliases.size() == 0)
11549 return DAG.getEntryNode();
11551 // If a single operand then chain to it. We don't need to revisit it.
11552 if (Aliases.size() == 1)
11555 // Construct a custom tailored token factor.
11556 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11557 &Aliases[0], Aliases.size());
11560 // SelectionDAG::Combine - This is the entry point for the file.
11562 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11563 CodeGenOpt::Level OptLevel) {
11564 /// run - This is the main entry point to this class.
11566 DAGCombiner(*this, AA, OptLevel).Run(Level);