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/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NodesCombined , "Number of dag nodes combined");
41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
44 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 CombinerAA("combiner-alias-analysis", cl::Hidden,
49 cl::desc("Turn on alias analysis during testing"));
52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53 cl::desc("Include global information in alias analysis"));
55 //------------------------------ DAGCombiner ---------------------------------//
59 const TargetLowering &TLI;
61 CodeGenOpt::Level OptLevel;
65 // Worklist of all of the nodes that need to be simplified.
67 // This has the semantics that when adding to the worklist,
68 // the item added must be next to be processed. It should
69 // also only appear once. The naive approach to this takes
72 // To reduce the insert/remove time to logarithmic, we use
73 // a set and a vector to maintain our worklist.
75 // The set contains the items on the worklist, but does not
76 // maintain the order they should be visited.
78 // The vector maintains the order nodes should be visited, but may
79 // contain duplicate or removed nodes. When choosing a node to
80 // visit, we pop off the order stack until we find an item that is
81 // also in the contents set. All operations are O(log N).
82 SmallPtrSet<SDNode*, 64> WorkListContents;
83 SmallVector<SDNode*, 64> WorkListOrder;
85 // AA - Used for DAG load/store alias analysis.
88 /// AddUsersToWorkList - When an instruction is simplified, add all users of
89 /// the instruction to the work lists because they might get more simplified
92 void AddUsersToWorkList(SDNode *N) {
93 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
98 /// visit - call the node-specific routine that knows how to fold each
99 /// particular type of node.
100 SDValue visit(SDNode *N);
103 /// AddToWorkList - Add to the work list making sure its instance is at the
104 /// back (next to be processed.)
105 void AddToWorkList(SDNode *N) {
106 WorkListContents.insert(N);
107 WorkListOrder.push_back(N);
110 /// removeFromWorkList - remove all instances of N from the worklist.
112 void removeFromWorkList(SDNode *N) {
113 WorkListContents.erase(N);
116 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
119 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
120 return CombineTo(N, &Res, 1, AddTo);
123 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
125 SDValue To[] = { Res0, Res1 };
126 return CombineTo(N, To, 2, AddTo);
129 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
133 /// SimplifyDemandedBits - Check the specified integer node value to see if
134 /// it can be simplified or if things it uses can be simplified by bit
135 /// propagation. If so, return true.
136 bool SimplifyDemandedBits(SDValue Op) {
137 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
138 APInt Demanded = APInt::getAllOnesValue(BitWidth);
139 return SimplifyDemandedBits(Op, Demanded);
142 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
144 bool CombineToPreIndexedLoadStore(SDNode *N);
145 bool CombineToPostIndexedLoadStore(SDNode *N);
147 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
148 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
149 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
150 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
151 SDValue PromoteIntBinOp(SDValue Op);
152 SDValue PromoteIntShiftOp(SDValue Op);
153 SDValue PromoteExtend(SDValue Op);
154 bool PromoteLoad(SDValue Op);
156 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
157 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
158 ISD::NodeType ExtType);
160 /// combine - call the node-specific routine that knows how to fold each
161 /// particular type of node. If that doesn't do anything, try the
162 /// target-specific DAG combines.
163 SDValue combine(SDNode *N);
165 // Visitation implementation - Implement dag node combining for different
166 // node types. The semantics are as follows:
168 // SDValue.getNode() == 0 - No change was made
169 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
170 // otherwise - N should be replaced by the returned Operand.
172 SDValue visitTokenFactor(SDNode *N);
173 SDValue visitMERGE_VALUES(SDNode *N);
174 SDValue visitADD(SDNode *N);
175 SDValue visitSUB(SDNode *N);
176 SDValue visitADDC(SDNode *N);
177 SDValue visitSUBC(SDNode *N);
178 SDValue visitADDE(SDNode *N);
179 SDValue visitSUBE(SDNode *N);
180 SDValue visitMUL(SDNode *N);
181 SDValue visitSDIV(SDNode *N);
182 SDValue visitUDIV(SDNode *N);
183 SDValue visitSREM(SDNode *N);
184 SDValue visitUREM(SDNode *N);
185 SDValue visitMULHU(SDNode *N);
186 SDValue visitMULHS(SDNode *N);
187 SDValue visitSMUL_LOHI(SDNode *N);
188 SDValue visitUMUL_LOHI(SDNode *N);
189 SDValue visitSMULO(SDNode *N);
190 SDValue visitUMULO(SDNode *N);
191 SDValue visitSDIVREM(SDNode *N);
192 SDValue visitUDIVREM(SDNode *N);
193 SDValue visitAND(SDNode *N);
194 SDValue visitOR(SDNode *N);
195 SDValue visitXOR(SDNode *N);
196 SDValue SimplifyVBinOp(SDNode *N);
197 SDValue visitSHL(SDNode *N);
198 SDValue visitSRA(SDNode *N);
199 SDValue visitSRL(SDNode *N);
200 SDValue visitCTLZ(SDNode *N);
201 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
202 SDValue visitCTTZ(SDNode *N);
203 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
204 SDValue visitCTPOP(SDNode *N);
205 SDValue visitSELECT(SDNode *N);
206 SDValue visitSELECT_CC(SDNode *N);
207 SDValue visitSETCC(SDNode *N);
208 SDValue visitSIGN_EXTEND(SDNode *N);
209 SDValue visitZERO_EXTEND(SDNode *N);
210 SDValue visitANY_EXTEND(SDNode *N);
211 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
212 SDValue visitTRUNCATE(SDNode *N);
213 SDValue visitBITCAST(SDNode *N);
214 SDValue visitBUILD_PAIR(SDNode *N);
215 SDValue visitFADD(SDNode *N);
216 SDValue visitFSUB(SDNode *N);
217 SDValue visitFMUL(SDNode *N);
218 SDValue visitFMA(SDNode *N);
219 SDValue visitFDIV(SDNode *N);
220 SDValue visitFREM(SDNode *N);
221 SDValue visitFCOPYSIGN(SDNode *N);
222 SDValue visitSINT_TO_FP(SDNode *N);
223 SDValue visitUINT_TO_FP(SDNode *N);
224 SDValue visitFP_TO_SINT(SDNode *N);
225 SDValue visitFP_TO_UINT(SDNode *N);
226 SDValue visitFP_ROUND(SDNode *N);
227 SDValue visitFP_ROUND_INREG(SDNode *N);
228 SDValue visitFP_EXTEND(SDNode *N);
229 SDValue visitFNEG(SDNode *N);
230 SDValue visitFABS(SDNode *N);
231 SDValue visitFCEIL(SDNode *N);
232 SDValue visitFTRUNC(SDNode *N);
233 SDValue visitFFLOOR(SDNode *N);
234 SDValue visitBRCOND(SDNode *N);
235 SDValue visitBR_CC(SDNode *N);
236 SDValue visitLOAD(SDNode *N);
237 SDValue visitSTORE(SDNode *N);
238 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
239 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
240 SDValue visitBUILD_VECTOR(SDNode *N);
241 SDValue visitCONCAT_VECTORS(SDNode *N);
242 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
243 SDValue visitVECTOR_SHUFFLE(SDNode *N);
244 SDValue visitMEMBARRIER(SDNode *N);
246 SDValue XformToShuffleWithZero(SDNode *N);
247 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
249 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
251 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
252 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
253 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
254 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
255 SDValue N3, ISD::CondCode CC,
256 bool NotExtCompare = false);
257 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
258 DebugLoc DL, bool foldBooleans = true);
259 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
261 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
262 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
263 SDValue BuildSDIV(SDNode *N);
264 SDValue BuildUDIV(SDNode *N);
265 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
266 bool DemandHighBits = true);
267 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
268 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
269 SDValue ReduceLoadWidth(SDNode *N);
270 SDValue ReduceLoadOpStoreWidth(SDNode *N);
271 SDValue TransformFPLoadStorePair(SDNode *N);
273 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
275 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
276 /// looking for aliasing nodes and adding them to the Aliases vector.
277 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
278 SmallVector<SDValue, 8> &Aliases);
280 /// isAlias - Return true if there is any possibility that the two addresses
282 bool isAlias(SDValue Ptr1, int64_t Size1,
283 const Value *SrcValue1, int SrcValueOffset1,
284 unsigned SrcValueAlign1,
285 const MDNode *TBAAInfo1,
286 SDValue Ptr2, int64_t Size2,
287 const Value *SrcValue2, int SrcValueOffset2,
288 unsigned SrcValueAlign2,
289 const MDNode *TBAAInfo2) const;
291 /// FindAliasInfo - Extracts the relevant alias information from the memory
292 /// node. Returns true if the operand was a load.
293 bool FindAliasInfo(SDNode *N,
294 SDValue &Ptr, int64_t &Size,
295 const Value *&SrcValue, int &SrcValueOffset,
296 unsigned &SrcValueAlignment,
297 const MDNode *&TBAAInfo) const;
299 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
300 /// looking for a better chain (aliasing node.)
301 SDValue FindBetterChain(SDNode *N, SDValue Chain);
304 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
305 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
306 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
308 /// Run - runs the dag combiner on all nodes in the work list
309 void Run(CombineLevel AtLevel);
311 SelectionDAG &getDAG() const { return DAG; }
313 /// getShiftAmountTy - Returns a type large enough to hold any valid
314 /// shift amount - before type legalization these can be huge.
315 EVT getShiftAmountTy(EVT LHSTy) {
316 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
319 /// isTypeLegal - This method returns true if we are running before type
320 /// legalization or if the specified VT is legal.
321 bool isTypeLegal(const EVT &VT) {
322 if (!LegalTypes) return true;
323 return TLI.isTypeLegal(VT);
330 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
331 /// nodes from the worklist.
332 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
335 explicit WorkListRemover(DAGCombiner &dc)
336 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
338 virtual void NodeDeleted(SDNode *N, SDNode *E) {
339 DC.removeFromWorkList(N);
344 //===----------------------------------------------------------------------===//
345 // TargetLowering::DAGCombinerInfo implementation
346 //===----------------------------------------------------------------------===//
348 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
349 ((DAGCombiner*)DC)->AddToWorkList(N);
352 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
353 ((DAGCombiner*)DC)->removeFromWorkList(N);
356 SDValue TargetLowering::DAGCombinerInfo::
357 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
358 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
361 SDValue TargetLowering::DAGCombinerInfo::
362 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
363 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
367 SDValue TargetLowering::DAGCombinerInfo::
368 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
369 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
372 void TargetLowering::DAGCombinerInfo::
373 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
374 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
377 //===----------------------------------------------------------------------===//
379 //===----------------------------------------------------------------------===//
381 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
382 /// specified expression for the same cost as the expression itself, or 2 if we
383 /// can compute the negated form more cheaply than the expression itself.
384 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
385 const TargetLowering &TLI,
386 const TargetOptions *Options,
387 unsigned Depth = 0) {
388 // No compile time optimizations on this type.
389 if (Op.getValueType() == MVT::ppcf128)
392 // fneg is removable even if it has multiple uses.
393 if (Op.getOpcode() == ISD::FNEG) return 2;
395 // Don't allow anything with multiple uses.
396 if (!Op.hasOneUse()) return 0;
398 // Don't recurse exponentially.
399 if (Depth > 6) return 0;
401 switch (Op.getOpcode()) {
402 default: return false;
403 case ISD::ConstantFP:
404 // Don't invert constant FP values after legalize. The negated constant
405 // isn't necessarily legal.
406 return LegalOperations ? 0 : 1;
408 // FIXME: determine better conditions for this xform.
409 if (!Options->UnsafeFPMath) return 0;
411 // After operation legalization, it might not be legal to create new FSUBs.
412 if (LegalOperations &&
413 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
416 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
417 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
420 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
421 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
424 // We can't turn -(A-B) into B-A when we honor signed zeros.
425 if (!Options->UnsafeFPMath) return 0;
427 // fold (fneg (fsub A, B)) -> (fsub B, A)
432 if (Options->HonorSignDependentRoundingFPMath()) return 0;
434 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
435 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
439 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
445 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
450 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
451 /// returns the newly negated expression.
452 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
453 bool LegalOperations, unsigned Depth = 0) {
454 // fneg is removable even if it has multiple uses.
455 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
457 // Don't allow anything with multiple uses.
458 assert(Op.hasOneUse() && "Unknown reuse!");
460 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
461 switch (Op.getOpcode()) {
462 default: llvm_unreachable("Unknown code");
463 case ISD::ConstantFP: {
464 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
466 return DAG.getConstantFP(V, Op.getValueType());
469 // FIXME: determine better conditions for this xform.
470 assert(DAG.getTarget().Options.UnsafeFPMath);
472 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
473 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
474 DAG.getTargetLoweringInfo(),
475 &DAG.getTarget().Options, Depth+1))
476 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
477 GetNegatedExpression(Op.getOperand(0), DAG,
478 LegalOperations, Depth+1),
480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
482 GetNegatedExpression(Op.getOperand(1), DAG,
483 LegalOperations, Depth+1),
486 // We can't turn -(A-B) into B-A when we honor signed zeros.
487 assert(DAG.getTarget().Options.UnsafeFPMath);
489 // fold (fneg (fsub 0, B)) -> B
490 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
491 if (N0CFP->getValueAPF().isZero())
492 return Op.getOperand(1);
494 // fold (fneg (fsub A, B)) -> (fsub B, A)
495 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
496 Op.getOperand(1), Op.getOperand(0));
500 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
502 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
503 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
504 DAG.getTargetLoweringInfo(),
505 &DAG.getTarget().Options, Depth+1))
506 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
507 GetNegatedExpression(Op.getOperand(0), DAG,
508 LegalOperations, Depth+1),
511 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
512 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
514 GetNegatedExpression(Op.getOperand(1), DAG,
515 LegalOperations, Depth+1));
519 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
520 GetNegatedExpression(Op.getOperand(0), DAG,
521 LegalOperations, Depth+1));
523 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
524 GetNegatedExpression(Op.getOperand(0), DAG,
525 LegalOperations, Depth+1),
531 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
532 // that selects between the values 1 and 0, making it equivalent to a setcc.
533 // Also, set the incoming LHS, RHS, and CC references to the appropriate
534 // nodes based on the type of node we are checking. This simplifies life a
535 // bit for the callers.
536 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
538 if (N.getOpcode() == ISD::SETCC) {
539 LHS = N.getOperand(0);
540 RHS = N.getOperand(1);
541 CC = N.getOperand(2);
544 if (N.getOpcode() == ISD::SELECT_CC &&
545 N.getOperand(2).getOpcode() == ISD::Constant &&
546 N.getOperand(3).getOpcode() == ISD::Constant &&
547 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
548 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
549 LHS = N.getOperand(0);
550 RHS = N.getOperand(1);
551 CC = N.getOperand(4);
557 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
558 // one use. If this is true, it allows the users to invert the operation for
559 // free when it is profitable to do so.
560 static bool isOneUseSetCC(SDValue N) {
562 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
567 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
568 SDValue N0, SDValue N1) {
569 EVT VT = N0.getValueType();
570 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
571 if (isa<ConstantSDNode>(N1)) {
572 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
574 DAG.FoldConstantArithmetic(Opc, VT,
575 cast<ConstantSDNode>(N0.getOperand(1)),
576 cast<ConstantSDNode>(N1));
577 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
579 if (N0.hasOneUse()) {
580 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
581 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
582 N0.getOperand(0), N1);
583 AddToWorkList(OpNode.getNode());
584 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
588 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
589 if (isa<ConstantSDNode>(N0)) {
590 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
592 DAG.FoldConstantArithmetic(Opc, VT,
593 cast<ConstantSDNode>(N1.getOperand(1)),
594 cast<ConstantSDNode>(N0));
595 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
597 if (N1.hasOneUse()) {
598 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
599 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
600 N1.getOperand(0), N0);
601 AddToWorkList(OpNode.getNode());
602 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
609 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
611 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
613 DEBUG(dbgs() << "\nReplacing.1 ";
615 dbgs() << "\nWith: ";
616 To[0].getNode()->dump(&DAG);
617 dbgs() << " and " << NumTo-1 << " other values\n";
618 for (unsigned i = 0, e = NumTo; i != e; ++i)
619 assert((!To[i].getNode() ||
620 N->getValueType(i) == To[i].getValueType()) &&
621 "Cannot combine value to value of different type!"));
622 WorkListRemover DeadNodes(*this);
623 DAG.ReplaceAllUsesWith(N, To);
625 // Push the new nodes and any users onto the worklist
626 for (unsigned i = 0, e = NumTo; i != e; ++i) {
627 if (To[i].getNode()) {
628 AddToWorkList(To[i].getNode());
629 AddUsersToWorkList(To[i].getNode());
634 // Finally, if the node is now dead, remove it from the graph. The node
635 // may not be dead if the replacement process recursively simplified to
636 // something else needing this node.
637 if (N->use_empty()) {
638 // Nodes can be reintroduced into the worklist. Make sure we do not
639 // process a node that has been replaced.
640 removeFromWorkList(N);
642 // Finally, since the node is now dead, remove it from the graph.
645 return SDValue(N, 0);
649 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
650 // Replace all uses. If any nodes become isomorphic to other nodes and
651 // are deleted, make sure to remove them from our worklist.
652 WorkListRemover DeadNodes(*this);
653 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
655 // Push the new node and any (possibly new) users onto the worklist.
656 AddToWorkList(TLO.New.getNode());
657 AddUsersToWorkList(TLO.New.getNode());
659 // Finally, if the node is now dead, remove it from the graph. The node
660 // may not be dead if the replacement process recursively simplified to
661 // something else needing this node.
662 if (TLO.Old.getNode()->use_empty()) {
663 removeFromWorkList(TLO.Old.getNode());
665 // If the operands of this node are only used by the node, they will now
666 // be dead. Make sure to visit them first to delete dead nodes early.
667 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
668 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
669 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
671 DAG.DeleteNode(TLO.Old.getNode());
675 /// SimplifyDemandedBits - Check the specified integer node value to see if
676 /// it can be simplified or if things it uses can be simplified by bit
677 /// propagation. If so, return true.
678 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
679 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
680 APInt KnownZero, KnownOne;
681 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
685 AddToWorkList(Op.getNode());
687 // Replace the old value with the new one.
689 DEBUG(dbgs() << "\nReplacing.2 ";
690 TLO.Old.getNode()->dump(&DAG);
691 dbgs() << "\nWith: ";
692 TLO.New.getNode()->dump(&DAG);
695 CommitTargetLoweringOpt(TLO);
699 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
700 DebugLoc dl = Load->getDebugLoc();
701 EVT VT = Load->getValueType(0);
702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
704 DEBUG(dbgs() << "\nReplacing.9 ";
706 dbgs() << "\nWith: ";
707 Trunc.getNode()->dump(&DAG);
709 WorkListRemover DeadNodes(*this);
710 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
711 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
712 removeFromWorkList(Load);
713 DAG.DeleteNode(Load);
714 AddToWorkList(Trunc.getNode());
717 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
719 DebugLoc dl = Op.getDebugLoc();
720 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
721 EVT MemVT = LD->getMemoryVT();
722 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
723 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
725 : LD->getExtensionType();
727 return DAG.getExtLoad(ExtType, dl, PVT,
728 LD->getChain(), LD->getBasePtr(),
729 LD->getPointerInfo(),
730 MemVT, LD->isVolatile(),
731 LD->isNonTemporal(), LD->getAlignment());
734 unsigned Opc = Op.getOpcode();
737 case ISD::AssertSext:
738 return DAG.getNode(ISD::AssertSext, dl, PVT,
739 SExtPromoteOperand(Op.getOperand(0), PVT),
741 case ISD::AssertZext:
742 return DAG.getNode(ISD::AssertZext, dl, PVT,
743 ZExtPromoteOperand(Op.getOperand(0), PVT),
745 case ISD::Constant: {
747 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
748 return DAG.getNode(ExtOpc, dl, PVT, Op);
752 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
754 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
757 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
758 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
760 EVT OldVT = Op.getValueType();
761 DebugLoc dl = Op.getDebugLoc();
762 bool Replace = false;
763 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
764 if (NewOp.getNode() == 0)
766 AddToWorkList(NewOp.getNode());
769 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
770 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
771 DAG.getValueType(OldVT));
774 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
775 EVT OldVT = Op.getValueType();
776 DebugLoc dl = Op.getDebugLoc();
777 bool Replace = false;
778 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
779 if (NewOp.getNode() == 0)
781 AddToWorkList(NewOp.getNode());
784 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
785 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
788 /// PromoteIntBinOp - Promote the specified integer binary operation if the
789 /// target indicates it is beneficial. e.g. On x86, it's usually better to
790 /// promote i16 operations to i32 since i16 instructions are longer.
791 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
792 if (!LegalOperations)
795 EVT VT = Op.getValueType();
796 if (VT.isVector() || !VT.isInteger())
799 // If operation type is 'undesirable', e.g. i16 on x86, consider
801 unsigned Opc = Op.getOpcode();
802 if (TLI.isTypeDesirableForOp(Opc, VT))
806 // Consult target whether it is a good idea to promote this operation and
807 // what's the right type to promote it to.
808 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
809 assert(PVT != VT && "Don't know what type to promote to!");
811 bool Replace0 = false;
812 SDValue N0 = Op.getOperand(0);
813 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
814 if (NN0.getNode() == 0)
817 bool Replace1 = false;
818 SDValue N1 = Op.getOperand(1);
823 NN1 = PromoteOperand(N1, PVT, Replace1);
824 if (NN1.getNode() == 0)
828 AddToWorkList(NN0.getNode());
830 AddToWorkList(NN1.getNode());
833 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
835 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
837 DEBUG(dbgs() << "\nPromoting ";
838 Op.getNode()->dump(&DAG));
839 DebugLoc dl = Op.getDebugLoc();
840 return DAG.getNode(ISD::TRUNCATE, dl, VT,
841 DAG.getNode(Opc, dl, PVT, NN0, NN1));
846 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
847 /// target indicates it is beneficial. e.g. On x86, it's usually better to
848 /// promote i16 operations to i32 since i16 instructions are longer.
849 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
850 if (!LegalOperations)
853 EVT VT = Op.getValueType();
854 if (VT.isVector() || !VT.isInteger())
857 // If operation type is 'undesirable', e.g. i16 on x86, consider
859 unsigned Opc = Op.getOpcode();
860 if (TLI.isTypeDesirableForOp(Opc, VT))
864 // Consult target whether it is a good idea to promote this operation and
865 // what's the right type to promote it to.
866 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
867 assert(PVT != VT && "Don't know what type to promote to!");
869 bool Replace = false;
870 SDValue N0 = Op.getOperand(0);
872 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
873 else if (Opc == ISD::SRL)
874 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
876 N0 = PromoteOperand(N0, PVT, Replace);
877 if (N0.getNode() == 0)
880 AddToWorkList(N0.getNode());
882 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
884 DEBUG(dbgs() << "\nPromoting ";
885 Op.getNode()->dump(&DAG));
886 DebugLoc dl = Op.getDebugLoc();
887 return DAG.getNode(ISD::TRUNCATE, dl, VT,
888 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
893 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
894 if (!LegalOperations)
897 EVT VT = Op.getValueType();
898 if (VT.isVector() || !VT.isInteger())
901 // If operation type is 'undesirable', e.g. i16 on x86, consider
903 unsigned Opc = Op.getOpcode();
904 if (TLI.isTypeDesirableForOp(Opc, VT))
908 // Consult target whether it is a good idea to promote this operation and
909 // what's the right type to promote it to.
910 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
911 assert(PVT != VT && "Don't know what type to promote to!");
912 // fold (aext (aext x)) -> (aext x)
913 // fold (aext (zext x)) -> (zext x)
914 // fold (aext (sext x)) -> (sext x)
915 DEBUG(dbgs() << "\nPromoting ";
916 Op.getNode()->dump(&DAG));
917 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
922 bool DAGCombiner::PromoteLoad(SDValue Op) {
923 if (!LegalOperations)
926 EVT VT = Op.getValueType();
927 if (VT.isVector() || !VT.isInteger())
930 // If operation type is 'undesirable', e.g. i16 on x86, consider
932 unsigned Opc = Op.getOpcode();
933 if (TLI.isTypeDesirableForOp(Opc, VT))
937 // Consult target whether it is a good idea to promote this operation and
938 // what's the right type to promote it to.
939 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
940 assert(PVT != VT && "Don't know what type to promote to!");
942 DebugLoc dl = Op.getDebugLoc();
943 SDNode *N = Op.getNode();
944 LoadSDNode *LD = cast<LoadSDNode>(N);
945 EVT MemVT = LD->getMemoryVT();
946 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
947 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
949 : LD->getExtensionType();
950 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
951 LD->getChain(), LD->getBasePtr(),
952 LD->getPointerInfo(),
953 MemVT, LD->isVolatile(),
954 LD->isNonTemporal(), LD->getAlignment());
955 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
957 DEBUG(dbgs() << "\nPromoting ";
960 Result.getNode()->dump(&DAG);
962 WorkListRemover DeadNodes(*this);
963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
964 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
965 removeFromWorkList(N);
967 AddToWorkList(Result.getNode());
974 //===----------------------------------------------------------------------===//
975 // Main DAG Combiner implementation
976 //===----------------------------------------------------------------------===//
978 void DAGCombiner::Run(CombineLevel AtLevel) {
979 // set the instance variables, so that the various visit routines may use it.
981 LegalOperations = Level >= AfterLegalizeVectorOps;
982 LegalTypes = Level >= AfterLegalizeTypes;
984 // Add all the dag nodes to the worklist.
985 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
986 E = DAG.allnodes_end(); I != E; ++I)
989 // Create a dummy node (which is not added to allnodes), that adds a reference
990 // to the root node, preventing it from being deleted, and tracking any
991 // changes of the root.
992 HandleSDNode Dummy(DAG.getRoot());
994 // The root of the dag may dangle to deleted nodes until the dag combiner is
995 // done. Set it to null to avoid confusion.
996 DAG.setRoot(SDValue());
998 // while the worklist isn't empty, find a node and
999 // try and combine it.
1000 while (!WorkListContents.empty()) {
1002 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1003 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1004 // worklist *should* contain, and check the node we want to visit is should
1005 // actually be visited.
1007 N = WorkListOrder.pop_back_val();
1008 } while (!WorkListContents.erase(N));
1010 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1011 // N is deleted from the DAG, since they too may now be dead or may have a
1012 // reduced number of uses, allowing other xforms.
1013 if (N->use_empty() && N != &Dummy) {
1014 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1015 AddToWorkList(N->getOperand(i).getNode());
1021 SDValue RV = combine(N);
1023 if (RV.getNode() == 0)
1028 // If we get back the same node we passed in, rather than a new node or
1029 // zero, we know that the node must have defined multiple values and
1030 // CombineTo was used. Since CombineTo takes care of the worklist
1031 // mechanics for us, we have no work to do in this case.
1032 if (RV.getNode() == N)
1035 assert(N->getOpcode() != ISD::DELETED_NODE &&
1036 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1037 "Node was deleted but visit returned new node!");
1039 DEBUG(dbgs() << "\nReplacing.3 ";
1041 dbgs() << "\nWith: ";
1042 RV.getNode()->dump(&DAG);
1045 // Transfer debug value.
1046 DAG.TransferDbgValues(SDValue(N, 0), RV);
1047 WorkListRemover DeadNodes(*this);
1048 if (N->getNumValues() == RV.getNode()->getNumValues())
1049 DAG.ReplaceAllUsesWith(N, RV.getNode());
1051 assert(N->getValueType(0) == RV.getValueType() &&
1052 N->getNumValues() == 1 && "Type mismatch");
1054 DAG.ReplaceAllUsesWith(N, &OpV);
1057 // Push the new node and any users onto the worklist
1058 AddToWorkList(RV.getNode());
1059 AddUsersToWorkList(RV.getNode());
1061 // Add any uses of the old node to the worklist in case this node is the
1062 // last one that uses them. They may become dead after this node is
1064 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1065 AddToWorkList(N->getOperand(i).getNode());
1067 // Finally, if the node is now dead, remove it from the graph. The node
1068 // may not be dead if the replacement process recursively simplified to
1069 // something else needing this node.
1070 if (N->use_empty()) {
1071 // Nodes can be reintroduced into the worklist. Make sure we do not
1072 // process a node that has been replaced.
1073 removeFromWorkList(N);
1075 // Finally, since the node is now dead, remove it from the graph.
1080 // If the root changed (e.g. it was a dead load, update the root).
1081 DAG.setRoot(Dummy.getValue());
1082 DAG.RemoveDeadNodes();
1085 SDValue DAGCombiner::visit(SDNode *N) {
1086 switch (N->getOpcode()) {
1088 case ISD::TokenFactor: return visitTokenFactor(N);
1089 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1090 case ISD::ADD: return visitADD(N);
1091 case ISD::SUB: return visitSUB(N);
1092 case ISD::ADDC: return visitADDC(N);
1093 case ISD::SUBC: return visitSUBC(N);
1094 case ISD::ADDE: return visitADDE(N);
1095 case ISD::SUBE: return visitSUBE(N);
1096 case ISD::MUL: return visitMUL(N);
1097 case ISD::SDIV: return visitSDIV(N);
1098 case ISD::UDIV: return visitUDIV(N);
1099 case ISD::SREM: return visitSREM(N);
1100 case ISD::UREM: return visitUREM(N);
1101 case ISD::MULHU: return visitMULHU(N);
1102 case ISD::MULHS: return visitMULHS(N);
1103 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1104 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1105 case ISD::SMULO: return visitSMULO(N);
1106 case ISD::UMULO: return visitUMULO(N);
1107 case ISD::SDIVREM: return visitSDIVREM(N);
1108 case ISD::UDIVREM: return visitUDIVREM(N);
1109 case ISD::AND: return visitAND(N);
1110 case ISD::OR: return visitOR(N);
1111 case ISD::XOR: return visitXOR(N);
1112 case ISD::SHL: return visitSHL(N);
1113 case ISD::SRA: return visitSRA(N);
1114 case ISD::SRL: return visitSRL(N);
1115 case ISD::CTLZ: return visitCTLZ(N);
1116 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1117 case ISD::CTTZ: return visitCTTZ(N);
1118 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1119 case ISD::CTPOP: return visitCTPOP(N);
1120 case ISD::SELECT: return visitSELECT(N);
1121 case ISD::SELECT_CC: return visitSELECT_CC(N);
1122 case ISD::SETCC: return visitSETCC(N);
1123 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1124 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1125 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1126 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1127 case ISD::TRUNCATE: return visitTRUNCATE(N);
1128 case ISD::BITCAST: return visitBITCAST(N);
1129 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1130 case ISD::FADD: return visitFADD(N);
1131 case ISD::FSUB: return visitFSUB(N);
1132 case ISD::FMUL: return visitFMUL(N);
1133 case ISD::FMA: return visitFMA(N);
1134 case ISD::FDIV: return visitFDIV(N);
1135 case ISD::FREM: return visitFREM(N);
1136 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1137 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1138 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1139 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1140 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1141 case ISD::FP_ROUND: return visitFP_ROUND(N);
1142 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1143 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1144 case ISD::FNEG: return visitFNEG(N);
1145 case ISD::FABS: return visitFABS(N);
1146 case ISD::FFLOOR: return visitFFLOOR(N);
1147 case ISD::FCEIL: return visitFCEIL(N);
1148 case ISD::FTRUNC: return visitFTRUNC(N);
1149 case ISD::BRCOND: return visitBRCOND(N);
1150 case ISD::BR_CC: return visitBR_CC(N);
1151 case ISD::LOAD: return visitLOAD(N);
1152 case ISD::STORE: return visitSTORE(N);
1153 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1154 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1155 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1156 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1157 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1158 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1159 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1164 SDValue DAGCombiner::combine(SDNode *N) {
1165 SDValue RV = visit(N);
1167 // If nothing happened, try a target-specific DAG combine.
1168 if (RV.getNode() == 0) {
1169 assert(N->getOpcode() != ISD::DELETED_NODE &&
1170 "Node was deleted but visit returned NULL!");
1172 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1173 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1175 // Expose the DAG combiner to the target combiner impls.
1176 TargetLowering::DAGCombinerInfo
1177 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1179 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1183 // If nothing happened still, try promoting the operation.
1184 if (RV.getNode() == 0) {
1185 switch (N->getOpcode()) {
1193 RV = PromoteIntBinOp(SDValue(N, 0));
1198 RV = PromoteIntShiftOp(SDValue(N, 0));
1200 case ISD::SIGN_EXTEND:
1201 case ISD::ZERO_EXTEND:
1202 case ISD::ANY_EXTEND:
1203 RV = PromoteExtend(SDValue(N, 0));
1206 if (PromoteLoad(SDValue(N, 0)))
1212 // If N is a commutative binary node, try commuting it to enable more
1214 if (RV.getNode() == 0 &&
1215 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1216 N->getNumValues() == 1) {
1217 SDValue N0 = N->getOperand(0);
1218 SDValue N1 = N->getOperand(1);
1220 // Constant operands are canonicalized to RHS.
1221 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1222 SDValue Ops[] = { N1, N0 };
1223 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1226 return SDValue(CSENode, 0);
1233 /// getInputChainForNode - Given a node, return its input chain if it has one,
1234 /// otherwise return a null sd operand.
1235 static SDValue getInputChainForNode(SDNode *N) {
1236 if (unsigned NumOps = N->getNumOperands()) {
1237 if (N->getOperand(0).getValueType() == MVT::Other)
1238 return N->getOperand(0);
1239 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1240 return N->getOperand(NumOps-1);
1241 for (unsigned i = 1; i < NumOps-1; ++i)
1242 if (N->getOperand(i).getValueType() == MVT::Other)
1243 return N->getOperand(i);
1248 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1249 // If N has two operands, where one has an input chain equal to the other,
1250 // the 'other' chain is redundant.
1251 if (N->getNumOperands() == 2) {
1252 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1253 return N->getOperand(0);
1254 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1255 return N->getOperand(1);
1258 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1259 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1260 SmallPtrSet<SDNode*, 16> SeenOps;
1261 bool Changed = false; // If we should replace this token factor.
1263 // Start out with this token factor.
1266 // Iterate through token factors. The TFs grows when new token factors are
1268 for (unsigned i = 0; i < TFs.size(); ++i) {
1269 SDNode *TF = TFs[i];
1271 // Check each of the operands.
1272 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1273 SDValue Op = TF->getOperand(i);
1275 switch (Op.getOpcode()) {
1276 case ISD::EntryToken:
1277 // Entry tokens don't need to be added to the list. They are
1282 case ISD::TokenFactor:
1283 if (Op.hasOneUse() &&
1284 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1285 // Queue up for processing.
1286 TFs.push_back(Op.getNode());
1287 // Clean up in case the token factor is removed.
1288 AddToWorkList(Op.getNode());
1295 // Only add if it isn't already in the list.
1296 if (SeenOps.insert(Op.getNode()))
1307 // If we've change things around then replace token factor.
1310 // The entry token is the only possible outcome.
1311 Result = DAG.getEntryNode();
1313 // New and improved token factor.
1314 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1315 MVT::Other, &Ops[0], Ops.size());
1318 // Don't add users to work list.
1319 return CombineTo(N, Result, false);
1325 /// MERGE_VALUES can always be eliminated.
1326 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1327 WorkListRemover DeadNodes(*this);
1328 // Replacing results may cause a different MERGE_VALUES to suddenly
1329 // be CSE'd with N, and carry its uses with it. Iterate until no
1330 // uses remain, to ensure that the node can be safely deleted.
1331 // First add the users of this node to the work list so that they
1332 // can be tried again once they have new operands.
1333 AddUsersToWorkList(N);
1335 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1336 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1337 } while (!N->use_empty());
1338 removeFromWorkList(N);
1340 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1344 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1345 SelectionDAG &DAG) {
1346 EVT VT = N0.getValueType();
1347 SDValue N00 = N0.getOperand(0);
1348 SDValue N01 = N0.getOperand(1);
1349 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1351 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1352 isa<ConstantSDNode>(N00.getOperand(1))) {
1353 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1354 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1355 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1356 N00.getOperand(0), N01),
1357 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1358 N00.getOperand(1), N01));
1359 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1365 SDValue DAGCombiner::visitADD(SDNode *N) {
1366 SDValue N0 = N->getOperand(0);
1367 SDValue N1 = N->getOperand(1);
1368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1370 EVT VT = N0.getValueType();
1373 if (VT.isVector()) {
1374 SDValue FoldedVOp = SimplifyVBinOp(N);
1375 if (FoldedVOp.getNode()) return FoldedVOp;
1378 // fold (add x, undef) -> undef
1379 if (N0.getOpcode() == ISD::UNDEF)
1381 if (N1.getOpcode() == ISD::UNDEF)
1383 // fold (add c1, c2) -> c1+c2
1385 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1386 // canonicalize constant to RHS
1388 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1389 // fold (add x, 0) -> x
1390 if (N1C && N1C->isNullValue())
1392 // fold (add Sym, c) -> Sym+c
1393 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1394 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1395 GA->getOpcode() == ISD::GlobalAddress)
1396 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1398 (uint64_t)N1C->getSExtValue());
1399 // fold ((c1-A)+c2) -> (c1+c2)-A
1400 if (N1C && N0.getOpcode() == ISD::SUB)
1401 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1402 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1403 DAG.getConstant(N1C->getAPIntValue()+
1404 N0C->getAPIntValue(), VT),
1407 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1408 if (RADD.getNode() != 0)
1410 // fold ((0-A) + B) -> B-A
1411 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1412 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1413 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1414 // fold (A + (0-B)) -> A-B
1415 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1416 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1417 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1418 // fold (A+(B-A)) -> B
1419 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1420 return N1.getOperand(0);
1421 // fold ((B-A)+A) -> B
1422 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1423 return N0.getOperand(0);
1424 // fold (A+(B-(A+C))) to (B-C)
1425 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1426 N0 == N1.getOperand(1).getOperand(0))
1427 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1428 N1.getOperand(1).getOperand(1));
1429 // fold (A+(B-(C+A))) to (B-C)
1430 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1431 N0 == N1.getOperand(1).getOperand(1))
1432 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1433 N1.getOperand(1).getOperand(0));
1434 // fold (A+((B-A)+or-C)) to (B+or-C)
1435 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1436 N1.getOperand(0).getOpcode() == ISD::SUB &&
1437 N0 == N1.getOperand(0).getOperand(1))
1438 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1439 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1441 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1442 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1443 SDValue N00 = N0.getOperand(0);
1444 SDValue N01 = N0.getOperand(1);
1445 SDValue N10 = N1.getOperand(0);
1446 SDValue N11 = N1.getOperand(1);
1448 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1449 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1450 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1451 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1454 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1455 return SDValue(N, 0);
1457 // fold (a+b) -> (a|b) iff a and b share no bits.
1458 if (VT.isInteger() && !VT.isVector()) {
1459 APInt LHSZero, LHSOne;
1460 APInt RHSZero, RHSOne;
1461 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1463 if (LHSZero.getBoolValue()) {
1464 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1466 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1467 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1468 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1469 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1473 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1474 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1475 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1476 if (Result.getNode()) return Result;
1478 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1479 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1480 if (Result.getNode()) return Result;
1483 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1484 if (N1.getOpcode() == ISD::SHL &&
1485 N1.getOperand(0).getOpcode() == ISD::SUB)
1486 if (ConstantSDNode *C =
1487 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1488 if (C->getAPIntValue() == 0)
1489 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1490 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1491 N1.getOperand(0).getOperand(1),
1493 if (N0.getOpcode() == ISD::SHL &&
1494 N0.getOperand(0).getOpcode() == ISD::SUB)
1495 if (ConstantSDNode *C =
1496 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1497 if (C->getAPIntValue() == 0)
1498 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1499 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1500 N0.getOperand(0).getOperand(1),
1503 if (N1.getOpcode() == ISD::AND) {
1504 SDValue AndOp0 = N1.getOperand(0);
1505 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1506 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1507 unsigned DestBits = VT.getScalarType().getSizeInBits();
1509 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1510 // and similar xforms where the inner op is either ~0 or 0.
1511 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1512 DebugLoc DL = N->getDebugLoc();
1513 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1517 // add (sext i1), X -> sub X, (zext i1)
1518 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1519 N0.getOperand(0).getValueType() == MVT::i1 &&
1520 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1521 DebugLoc DL = N->getDebugLoc();
1522 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1523 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1529 SDValue DAGCombiner::visitADDC(SDNode *N) {
1530 SDValue N0 = N->getOperand(0);
1531 SDValue N1 = N->getOperand(1);
1532 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1533 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1534 EVT VT = N0.getValueType();
1536 // If the flag result is dead, turn this into an ADD.
1537 if (!N->hasAnyUseOfValue(1))
1538 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1539 DAG.getNode(ISD::CARRY_FALSE,
1540 N->getDebugLoc(), MVT::Glue));
1542 // canonicalize constant to RHS.
1544 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1546 // fold (addc x, 0) -> x + no carry out
1547 if (N1C && N1C->isNullValue())
1548 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1549 N->getDebugLoc(), MVT::Glue));
1551 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1552 APInt LHSZero, LHSOne;
1553 APInt RHSZero, RHSOne;
1554 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1556 if (LHSZero.getBoolValue()) {
1557 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1559 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1560 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1561 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1562 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1563 DAG.getNode(ISD::CARRY_FALSE,
1564 N->getDebugLoc(), MVT::Glue));
1570 SDValue DAGCombiner::visitADDE(SDNode *N) {
1571 SDValue N0 = N->getOperand(0);
1572 SDValue N1 = N->getOperand(1);
1573 SDValue CarryIn = N->getOperand(2);
1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1577 // canonicalize constant to RHS
1579 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1582 // fold (adde x, y, false) -> (addc x, y)
1583 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1584 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1589 // Since it may not be valid to emit a fold to zero for vector initializers
1590 // check if we can before folding.
1591 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1592 SelectionDAG &DAG, bool LegalOperations) {
1593 if (!VT.isVector()) {
1594 return DAG.getConstant(0, VT);
1596 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1597 // Produce a vector of zeros.
1598 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1599 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1600 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1601 &Ops[0], Ops.size());
1606 SDValue DAGCombiner::visitSUB(SDNode *N) {
1607 SDValue N0 = N->getOperand(0);
1608 SDValue N1 = N->getOperand(1);
1609 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1610 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1611 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1612 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1613 EVT VT = N0.getValueType();
1616 if (VT.isVector()) {
1617 SDValue FoldedVOp = SimplifyVBinOp(N);
1618 if (FoldedVOp.getNode()) return FoldedVOp;
1621 // fold (sub x, x) -> 0
1622 // FIXME: Refactor this and xor and other similar operations together.
1624 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1625 // fold (sub c1, c2) -> c1-c2
1627 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1628 // fold (sub x, c) -> (add x, -c)
1630 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1631 DAG.getConstant(-N1C->getAPIntValue(), VT));
1632 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1633 if (N0C && N0C->isAllOnesValue())
1634 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1635 // fold A-(A-B) -> B
1636 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1637 return N1.getOperand(1);
1638 // fold (A+B)-A -> B
1639 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1640 return N0.getOperand(1);
1641 // fold (A+B)-B -> A
1642 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1643 return N0.getOperand(0);
1644 // fold C2-(A+C1) -> (C2-C1)-A
1645 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1646 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1647 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1650 // fold ((A+(B+or-C))-B) -> A+or-C
1651 if (N0.getOpcode() == ISD::ADD &&
1652 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1653 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1654 N0.getOperand(1).getOperand(0) == N1)
1655 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1656 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1657 // fold ((A+(C+B))-B) -> A+C
1658 if (N0.getOpcode() == ISD::ADD &&
1659 N0.getOperand(1).getOpcode() == ISD::ADD &&
1660 N0.getOperand(1).getOperand(1) == N1)
1661 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1662 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1663 // fold ((A-(B-C))-C) -> A-B
1664 if (N0.getOpcode() == ISD::SUB &&
1665 N0.getOperand(1).getOpcode() == ISD::SUB &&
1666 N0.getOperand(1).getOperand(1) == N1)
1667 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1668 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1670 // If either operand of a sub is undef, the result is undef
1671 if (N0.getOpcode() == ISD::UNDEF)
1673 if (N1.getOpcode() == ISD::UNDEF)
1676 // If the relocation model supports it, consider symbol offsets.
1677 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1678 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1679 // fold (sub Sym, c) -> Sym-c
1680 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1681 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1683 (uint64_t)N1C->getSExtValue());
1684 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1685 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1686 if (GA->getGlobal() == GB->getGlobal())
1687 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1694 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1695 SDValue N0 = N->getOperand(0);
1696 SDValue N1 = N->getOperand(1);
1697 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1698 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1699 EVT VT = N0.getValueType();
1701 // If the flag result is dead, turn this into an SUB.
1702 if (!N->hasAnyUseOfValue(1))
1703 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1704 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1707 // fold (subc x, x) -> 0 + no borrow
1709 return CombineTo(N, DAG.getConstant(0, VT),
1710 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1713 // fold (subc x, 0) -> x + no borrow
1714 if (N1C && N1C->isNullValue())
1715 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1718 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1719 if (N0C && N0C->isAllOnesValue())
1720 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1721 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1727 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1728 SDValue N0 = N->getOperand(0);
1729 SDValue N1 = N->getOperand(1);
1730 SDValue CarryIn = N->getOperand(2);
1732 // fold (sube x, y, false) -> (subc x, y)
1733 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1734 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1739 SDValue DAGCombiner::visitMUL(SDNode *N) {
1740 SDValue N0 = N->getOperand(0);
1741 SDValue N1 = N->getOperand(1);
1742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1743 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1744 EVT VT = N0.getValueType();
1747 if (VT.isVector()) {
1748 SDValue FoldedVOp = SimplifyVBinOp(N);
1749 if (FoldedVOp.getNode()) return FoldedVOp;
1752 // fold (mul x, undef) -> 0
1753 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1754 return DAG.getConstant(0, VT);
1755 // fold (mul c1, c2) -> c1*c2
1757 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1758 // canonicalize constant to RHS
1760 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1761 // fold (mul x, 0) -> 0
1762 if (N1C && N1C->isNullValue())
1764 // fold (mul x, -1) -> 0-x
1765 if (N1C && N1C->isAllOnesValue())
1766 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1767 DAG.getConstant(0, VT), N0);
1768 // fold (mul x, (1 << c)) -> x << c
1769 if (N1C && N1C->getAPIntValue().isPowerOf2())
1770 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1771 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1772 getShiftAmountTy(N0.getValueType())));
1773 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1774 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1775 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1776 // FIXME: If the input is something that is easily negated (e.g. a
1777 // single-use add), we should put the negate there.
1778 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1779 DAG.getConstant(0, VT),
1780 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1781 DAG.getConstant(Log2Val,
1782 getShiftAmountTy(N0.getValueType()))));
1784 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1785 if (N1C && N0.getOpcode() == ISD::SHL &&
1786 isa<ConstantSDNode>(N0.getOperand(1))) {
1787 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1788 N1, N0.getOperand(1));
1789 AddToWorkList(C3.getNode());
1790 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1791 N0.getOperand(0), C3);
1794 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1797 SDValue Sh(0,0), Y(0,0);
1798 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1799 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1800 N0.getNode()->hasOneUse()) {
1802 } else if (N1.getOpcode() == ISD::SHL &&
1803 isa<ConstantSDNode>(N1.getOperand(1)) &&
1804 N1.getNode()->hasOneUse()) {
1809 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1810 Sh.getOperand(0), Y);
1811 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1812 Mul, Sh.getOperand(1));
1816 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1817 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1818 isa<ConstantSDNode>(N0.getOperand(1)))
1819 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1820 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1821 N0.getOperand(0), N1),
1822 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1823 N0.getOperand(1), N1));
1826 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1827 if (RMUL.getNode() != 0)
1833 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1834 SDValue N0 = N->getOperand(0);
1835 SDValue N1 = N->getOperand(1);
1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1838 EVT VT = N->getValueType(0);
1841 if (VT.isVector()) {
1842 SDValue FoldedVOp = SimplifyVBinOp(N);
1843 if (FoldedVOp.getNode()) return FoldedVOp;
1846 // fold (sdiv c1, c2) -> c1/c2
1847 if (N0C && N1C && !N1C->isNullValue())
1848 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1849 // fold (sdiv X, 1) -> X
1850 if (N1C && N1C->getAPIntValue() == 1LL)
1852 // fold (sdiv X, -1) -> 0-X
1853 if (N1C && N1C->isAllOnesValue())
1854 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1855 DAG.getConstant(0, VT), N0);
1856 // If we know the sign bits of both operands are zero, strength reduce to a
1857 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1858 if (!VT.isVector()) {
1859 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1860 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1863 // fold (sdiv X, pow2) -> simple ops after legalize
1864 if (N1C && !N1C->isNullValue() &&
1865 (N1C->getAPIntValue().isPowerOf2() ||
1866 (-N1C->getAPIntValue()).isPowerOf2())) {
1867 // If dividing by powers of two is cheap, then don't perform the following
1869 if (TLI.isPow2DivCheap())
1872 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1874 // Splat the sign bit into the register
1875 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1876 DAG.getConstant(VT.getSizeInBits()-1,
1877 getShiftAmountTy(N0.getValueType())));
1878 AddToWorkList(SGN.getNode());
1880 // Add (N0 < 0) ? abs2 - 1 : 0;
1881 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1882 DAG.getConstant(VT.getSizeInBits() - lg2,
1883 getShiftAmountTy(SGN.getValueType())));
1884 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1885 AddToWorkList(SRL.getNode());
1886 AddToWorkList(ADD.getNode()); // Divide by pow2
1887 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1888 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1890 // If we're dividing by a positive value, we're done. Otherwise, we must
1891 // negate the result.
1892 if (N1C->getAPIntValue().isNonNegative())
1895 AddToWorkList(SRA.getNode());
1896 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1897 DAG.getConstant(0, VT), SRA);
1900 // if integer divide is expensive and we satisfy the requirements, emit an
1901 // alternate sequence.
1902 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1903 SDValue Op = BuildSDIV(N);
1904 if (Op.getNode()) return Op;
1908 if (N0.getOpcode() == ISD::UNDEF)
1909 return DAG.getConstant(0, VT);
1910 // X / undef -> undef
1911 if (N1.getOpcode() == ISD::UNDEF)
1917 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1918 SDValue N0 = N->getOperand(0);
1919 SDValue N1 = N->getOperand(1);
1920 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1921 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1922 EVT VT = N->getValueType(0);
1925 if (VT.isVector()) {
1926 SDValue FoldedVOp = SimplifyVBinOp(N);
1927 if (FoldedVOp.getNode()) return FoldedVOp;
1930 // fold (udiv c1, c2) -> c1/c2
1931 if (N0C && N1C && !N1C->isNullValue())
1932 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1933 // fold (udiv x, (1 << c)) -> x >>u c
1934 if (N1C && N1C->getAPIntValue().isPowerOf2())
1935 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1936 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1937 getShiftAmountTy(N0.getValueType())));
1938 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1939 if (N1.getOpcode() == ISD::SHL) {
1940 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1941 if (SHC->getAPIntValue().isPowerOf2()) {
1942 EVT ADDVT = N1.getOperand(1).getValueType();
1943 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1945 DAG.getConstant(SHC->getAPIntValue()
1948 AddToWorkList(Add.getNode());
1949 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1953 // fold (udiv x, c) -> alternate
1954 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1955 SDValue Op = BuildUDIV(N);
1956 if (Op.getNode()) return Op;
1960 if (N0.getOpcode() == ISD::UNDEF)
1961 return DAG.getConstant(0, VT);
1962 // X / undef -> undef
1963 if (N1.getOpcode() == ISD::UNDEF)
1969 SDValue DAGCombiner::visitSREM(SDNode *N) {
1970 SDValue N0 = N->getOperand(0);
1971 SDValue N1 = N->getOperand(1);
1972 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1974 EVT VT = N->getValueType(0);
1976 // fold (srem c1, c2) -> c1%c2
1977 if (N0C && N1C && !N1C->isNullValue())
1978 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1979 // If we know the sign bits of both operands are zero, strength reduce to a
1980 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1981 if (!VT.isVector()) {
1982 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1983 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1986 // If X/C can be simplified by the division-by-constant logic, lower
1987 // X%C to the equivalent of X-X/C*C.
1988 if (N1C && !N1C->isNullValue()) {
1989 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1990 AddToWorkList(Div.getNode());
1991 SDValue OptimizedDiv = combine(Div.getNode());
1992 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1993 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1995 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1996 AddToWorkList(Mul.getNode());
2002 if (N0.getOpcode() == ISD::UNDEF)
2003 return DAG.getConstant(0, VT);
2004 // X % undef -> undef
2005 if (N1.getOpcode() == ISD::UNDEF)
2011 SDValue DAGCombiner::visitUREM(SDNode *N) {
2012 SDValue N0 = N->getOperand(0);
2013 SDValue N1 = N->getOperand(1);
2014 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2015 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2016 EVT VT = N->getValueType(0);
2018 // fold (urem c1, c2) -> c1%c2
2019 if (N0C && N1C && !N1C->isNullValue())
2020 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2021 // fold (urem x, pow2) -> (and x, pow2-1)
2022 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2023 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2024 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2025 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2026 if (N1.getOpcode() == ISD::SHL) {
2027 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2028 if (SHC->getAPIntValue().isPowerOf2()) {
2030 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2031 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2033 AddToWorkList(Add.getNode());
2034 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2039 // If X/C can be simplified by the division-by-constant logic, lower
2040 // X%C to the equivalent of X-X/C*C.
2041 if (N1C && !N1C->isNullValue()) {
2042 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2043 AddToWorkList(Div.getNode());
2044 SDValue OptimizedDiv = combine(Div.getNode());
2045 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2046 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2048 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2049 AddToWorkList(Mul.getNode());
2055 if (N0.getOpcode() == ISD::UNDEF)
2056 return DAG.getConstant(0, VT);
2057 // X % undef -> undef
2058 if (N1.getOpcode() == ISD::UNDEF)
2064 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
2067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2068 EVT VT = N->getValueType(0);
2069 DebugLoc DL = N->getDebugLoc();
2071 // fold (mulhs x, 0) -> 0
2072 if (N1C && N1C->isNullValue())
2074 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2075 if (N1C && N1C->getAPIntValue() == 1)
2076 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2077 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2078 getShiftAmountTy(N0.getValueType())));
2079 // fold (mulhs x, undef) -> 0
2080 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2081 return DAG.getConstant(0, VT);
2083 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2085 if (VT.isSimple() && !VT.isVector()) {
2086 MVT Simple = VT.getSimpleVT();
2087 unsigned SimpleSize = Simple.getSizeInBits();
2088 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2089 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2090 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2091 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2092 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2093 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2094 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2095 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2102 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2103 SDValue N0 = N->getOperand(0);
2104 SDValue N1 = N->getOperand(1);
2105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2106 EVT VT = N->getValueType(0);
2107 DebugLoc DL = N->getDebugLoc();
2109 // fold (mulhu x, 0) -> 0
2110 if (N1C && N1C->isNullValue())
2112 // fold (mulhu x, 1) -> 0
2113 if (N1C && N1C->getAPIntValue() == 1)
2114 return DAG.getConstant(0, N0.getValueType());
2115 // fold (mulhu x, undef) -> 0
2116 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2117 return DAG.getConstant(0, VT);
2119 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2121 if (VT.isSimple() && !VT.isVector()) {
2122 MVT Simple = VT.getSimpleVT();
2123 unsigned SimpleSize = Simple.getSizeInBits();
2124 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2125 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2126 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2127 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2128 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2129 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2130 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2131 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2138 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2139 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2140 /// that are being performed. Return true if a simplification was made.
2142 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2144 // If the high half is not needed, just compute the low half.
2145 bool HiExists = N->hasAnyUseOfValue(1);
2147 (!LegalOperations ||
2148 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2149 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2150 N->op_begin(), N->getNumOperands());
2151 return CombineTo(N, Res, Res);
2154 // If the low half is not needed, just compute the high half.
2155 bool LoExists = N->hasAnyUseOfValue(0);
2157 (!LegalOperations ||
2158 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2159 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2160 N->op_begin(), N->getNumOperands());
2161 return CombineTo(N, Res, Res);
2164 // If both halves are used, return as it is.
2165 if (LoExists && HiExists)
2168 // If the two computed results can be simplified separately, separate them.
2170 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2171 N->op_begin(), N->getNumOperands());
2172 AddToWorkList(Lo.getNode());
2173 SDValue LoOpt = combine(Lo.getNode());
2174 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2175 (!LegalOperations ||
2176 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2177 return CombineTo(N, LoOpt, LoOpt);
2181 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2182 N->op_begin(), N->getNumOperands());
2183 AddToWorkList(Hi.getNode());
2184 SDValue HiOpt = combine(Hi.getNode());
2185 if (HiOpt.getNode() && HiOpt != Hi &&
2186 (!LegalOperations ||
2187 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2188 return CombineTo(N, HiOpt, HiOpt);
2194 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2195 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2196 if (Res.getNode()) return Res;
2198 EVT VT = N->getValueType(0);
2199 DebugLoc DL = N->getDebugLoc();
2201 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2203 if (VT.isSimple() && !VT.isVector()) {
2204 MVT Simple = VT.getSimpleVT();
2205 unsigned SimpleSize = Simple.getSizeInBits();
2206 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2207 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2208 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2209 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2210 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2211 // Compute the high part as N1.
2212 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2213 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2214 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2215 // Compute the low part as N0.
2216 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2217 return CombineTo(N, Lo, Hi);
2224 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2225 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2226 if (Res.getNode()) return Res;
2228 EVT VT = N->getValueType(0);
2229 DebugLoc DL = N->getDebugLoc();
2231 // If the type twice as wide is legal, transform the mulhu 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 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2239 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2240 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2241 // Compute the high part as N1.
2242 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2243 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2244 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2245 // Compute the low part as N0.
2246 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2247 return CombineTo(N, Lo, Hi);
2254 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2255 // (smulo x, 2) -> (saddo x, x)
2256 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2257 if (C2->getAPIntValue() == 2)
2258 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2259 N->getOperand(0), N->getOperand(0));
2264 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2265 // (umulo x, 2) -> (uaddo x, x)
2266 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2267 if (C2->getAPIntValue() == 2)
2268 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2269 N->getOperand(0), N->getOperand(0));
2274 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2275 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2276 if (Res.getNode()) return Res;
2281 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2282 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2283 if (Res.getNode()) return Res;
2288 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2289 /// two operands of the same opcode, try to simplify it.
2290 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2291 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2292 EVT VT = N0.getValueType();
2293 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2295 // Bail early if none of these transforms apply.
2296 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2298 // For each of OP in AND/OR/XOR:
2299 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2300 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2301 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2302 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2304 // do not sink logical op inside of a vector extend, since it may combine
2306 EVT Op0VT = N0.getOperand(0).getValueType();
2307 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2308 N0.getOpcode() == ISD::SIGN_EXTEND ||
2309 // Avoid infinite looping with PromoteIntBinOp.
2310 (N0.getOpcode() == ISD::ANY_EXTEND &&
2311 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2312 (N0.getOpcode() == ISD::TRUNCATE &&
2313 (!TLI.isZExtFree(VT, Op0VT) ||
2314 !TLI.isTruncateFree(Op0VT, VT)) &&
2315 TLI.isTypeLegal(Op0VT))) &&
2317 Op0VT == N1.getOperand(0).getValueType() &&
2318 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2319 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2320 N0.getOperand(0).getValueType(),
2321 N0.getOperand(0), N1.getOperand(0));
2322 AddToWorkList(ORNode.getNode());
2323 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2326 // For each of OP in SHL/SRL/SRA/AND...
2327 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2328 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2329 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2330 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2331 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2332 N0.getOperand(1) == N1.getOperand(1)) {
2333 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2334 N0.getOperand(0).getValueType(),
2335 N0.getOperand(0), N1.getOperand(0));
2336 AddToWorkList(ORNode.getNode());
2337 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2338 ORNode, N0.getOperand(1));
2341 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2342 // Only perform this optimization after type legalization and before
2343 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2344 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2345 // we don't want to undo this promotion.
2346 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2348 if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR)
2349 && Level == AfterLegalizeTypes) {
2350 SDValue In0 = N0.getOperand(0);
2351 SDValue In1 = N1.getOperand(0);
2352 EVT In0Ty = In0.getValueType();
2353 EVT In1Ty = In1.getValueType();
2354 // If both incoming values are integers, and the original types are the same.
2355 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2356 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1);
2357 SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op);
2358 AddToWorkList(Op.getNode());
2363 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2364 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2365 // If both shuffles use the same mask, and both shuffle within a single
2366 // vector, then it is worthwhile to move the swizzle after the operation.
2367 // The type-legalizer generates this pattern when loading illegal
2368 // vector types from memory. In many cases this allows additional shuffle
2370 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2371 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2372 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2373 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2374 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2376 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2377 "Inputs to shuffles are not the same type");
2379 unsigned NumElts = VT.getVectorNumElements();
2381 // Check that both shuffles use the same mask. The masks are known to be of
2382 // the same length because the result vector type is the same.
2383 bool SameMask = true;
2384 for (unsigned i = 0; i != NumElts; ++i) {
2385 int Idx0 = SVN0->getMaskElt(i);
2386 int Idx1 = SVN1->getMaskElt(i);
2394 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2395 N0.getOperand(0), N1.getOperand(0));
2396 AddToWorkList(Op.getNode());
2397 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2398 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2405 SDValue DAGCombiner::visitAND(SDNode *N) {
2406 SDValue N0 = N->getOperand(0);
2407 SDValue N1 = N->getOperand(1);
2408 SDValue LL, LR, RL, RR, CC0, CC1;
2409 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2411 EVT VT = N1.getValueType();
2412 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2415 if (VT.isVector()) {
2416 SDValue FoldedVOp = SimplifyVBinOp(N);
2417 if (FoldedVOp.getNode()) return FoldedVOp;
2420 // fold (and x, undef) -> 0
2421 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2422 return DAG.getConstant(0, VT);
2423 // fold (and c1, c2) -> c1&c2
2425 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2426 // canonicalize constant to RHS
2428 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2429 // fold (and x, -1) -> x
2430 if (N1C && N1C->isAllOnesValue())
2432 // if (and x, c) is known to be zero, return 0
2433 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2434 APInt::getAllOnesValue(BitWidth)))
2435 return DAG.getConstant(0, VT);
2437 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2438 if (RAND.getNode() != 0)
2440 // fold (and (or x, C), D) -> D if (C & D) == D
2441 if (N1C && N0.getOpcode() == ISD::OR)
2442 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2443 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2445 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2446 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2447 SDValue N0Op0 = N0.getOperand(0);
2448 APInt Mask = ~N1C->getAPIntValue();
2449 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2450 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2451 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2452 N0.getValueType(), N0Op0);
2454 // Replace uses of the AND with uses of the Zero extend node.
2457 // We actually want to replace all uses of the any_extend with the
2458 // zero_extend, to avoid duplicating things. This will later cause this
2459 // AND to be folded.
2460 CombineTo(N0.getNode(), Zext);
2461 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2464 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2465 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2466 // already be zero by virtue of the width of the base type of the load.
2468 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2470 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2471 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2472 N0.getOpcode() == ISD::LOAD) {
2473 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2474 N0 : N0.getOperand(0) );
2476 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2477 // This can be a pure constant or a vector splat, in which case we treat the
2478 // vector as a scalar and use the splat value.
2479 APInt Constant = APInt::getNullValue(1);
2480 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2481 Constant = C->getAPIntValue();
2482 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2483 APInt SplatValue, SplatUndef;
2484 unsigned SplatBitSize;
2486 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2487 SplatBitSize, HasAnyUndefs);
2489 // Undef bits can contribute to a possible optimisation if set, so
2491 SplatValue |= SplatUndef;
2493 // The splat value may be something like "0x00FFFFFF", which means 0 for
2494 // the first vector value and FF for the rest, repeating. We need a mask
2495 // that will apply equally to all members of the vector, so AND all the
2496 // lanes of the constant together.
2497 EVT VT = Vector->getValueType(0);
2498 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2499 Constant = APInt::getAllOnesValue(BitWidth);
2500 for (unsigned i = 0, n = VT.getVectorNumElements(); i < n; ++i)
2501 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2505 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2506 // actually legal and isn't going to get expanded, else this is a false
2508 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2509 Load->getMemoryVT());
2511 // Resize the constant to the same size as the original memory access before
2512 // extension. If it is still the AllOnesValue then this AND is completely
2515 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2518 switch (Load->getExtensionType()) {
2519 default: B = false; break;
2520 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2522 case ISD::NON_EXTLOAD: B = true; break;
2525 if (B && Constant.isAllOnesValue()) {
2526 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2527 // preserve semantics once we get rid of the AND.
2528 SDValue NewLoad(Load, 0);
2529 if (Load->getExtensionType() == ISD::EXTLOAD) {
2530 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2531 Load->getValueType(0), Load->getDebugLoc(),
2532 Load->getChain(), Load->getBasePtr(),
2533 Load->getOffset(), Load->getMemoryVT(),
2534 Load->getMemOperand());
2535 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2536 if (Load->getNumValues() == 3) {
2537 // PRE/POST_INC loads have 3 values.
2538 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2539 NewLoad.getValue(2) };
2540 CombineTo(Load, To, 3, true);
2542 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2546 // Fold the AND away, taking care not to fold to the old load node if we
2548 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2550 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2553 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2554 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2555 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2556 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2558 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2559 LL.getValueType().isInteger()) {
2560 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2561 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2562 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2563 LR.getValueType(), LL, RL);
2564 AddToWorkList(ORNode.getNode());
2565 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2567 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2568 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2569 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2570 LR.getValueType(), LL, RL);
2571 AddToWorkList(ANDNode.getNode());
2572 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2574 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2575 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2576 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2577 LR.getValueType(), LL, RL);
2578 AddToWorkList(ORNode.getNode());
2579 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2582 // canonicalize equivalent to ll == rl
2583 if (LL == RR && LR == RL) {
2584 Op1 = ISD::getSetCCSwappedOperands(Op1);
2587 if (LL == RL && LR == RR) {
2588 bool isInteger = LL.getValueType().isInteger();
2589 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2590 if (Result != ISD::SETCC_INVALID &&
2591 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2592 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2597 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2598 if (N0.getOpcode() == N1.getOpcode()) {
2599 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2600 if (Tmp.getNode()) return Tmp;
2603 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2604 // fold (and (sra)) -> (and (srl)) when possible.
2605 if (!VT.isVector() &&
2606 SimplifyDemandedBits(SDValue(N, 0)))
2607 return SDValue(N, 0);
2609 // fold (zext_inreg (extload x)) -> (zextload x)
2610 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2611 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2612 EVT MemVT = LN0->getMemoryVT();
2613 // If we zero all the possible extended bits, then we can turn this into
2614 // a zextload if we are running before legalize or the operation is legal.
2615 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2616 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2617 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2618 ((!LegalOperations && !LN0->isVolatile()) ||
2619 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2620 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2621 LN0->getChain(), LN0->getBasePtr(),
2622 LN0->getPointerInfo(), MemVT,
2623 LN0->isVolatile(), LN0->isNonTemporal(),
2624 LN0->getAlignment());
2626 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2630 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2631 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2633 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2634 EVT MemVT = LN0->getMemoryVT();
2635 // If we zero all the possible extended bits, then we can turn this into
2636 // a zextload if we are running before legalize or the operation is legal.
2637 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2638 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2639 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2640 ((!LegalOperations && !LN0->isVolatile()) ||
2641 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2642 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2644 LN0->getBasePtr(), LN0->getPointerInfo(),
2646 LN0->isVolatile(), LN0->isNonTemporal(),
2647 LN0->getAlignment());
2649 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2650 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2654 // fold (and (load x), 255) -> (zextload x, i8)
2655 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2656 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2657 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2658 (N0.getOpcode() == ISD::ANY_EXTEND &&
2659 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2660 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2661 LoadSDNode *LN0 = HasAnyExt
2662 ? cast<LoadSDNode>(N0.getOperand(0))
2663 : cast<LoadSDNode>(N0);
2664 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2665 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2666 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2667 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2668 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2669 EVT LoadedVT = LN0->getMemoryVT();
2671 if (ExtVT == LoadedVT &&
2672 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2673 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2676 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2677 LN0->getChain(), LN0->getBasePtr(),
2678 LN0->getPointerInfo(),
2679 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2680 LN0->getAlignment());
2682 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2683 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2686 // Do not change the width of a volatile load.
2687 // Do not generate loads of non-round integer types since these can
2688 // be expensive (and would be wrong if the type is not byte sized).
2689 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2690 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2691 EVT PtrType = LN0->getOperand(1).getValueType();
2693 unsigned Alignment = LN0->getAlignment();
2694 SDValue NewPtr = LN0->getBasePtr();
2696 // For big endian targets, we need to add an offset to the pointer
2697 // to load the correct bytes. For little endian systems, we merely
2698 // need to read fewer bytes from the same pointer.
2699 if (TLI.isBigEndian()) {
2700 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2701 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2702 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2703 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2704 NewPtr, DAG.getConstant(PtrOff, PtrType));
2705 Alignment = MinAlign(Alignment, PtrOff);
2708 AddToWorkList(NewPtr.getNode());
2710 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2712 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2713 LN0->getChain(), NewPtr,
2714 LN0->getPointerInfo(),
2715 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2718 CombineTo(LN0, Load, Load.getValue(1));
2719 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2725 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2726 VT.getSizeInBits() <= 64) {
2727 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2728 APInt ADDC = ADDI->getAPIntValue();
2729 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2730 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2731 // immediate for an add, but it is legal if its top c2 bits are set,
2732 // transform the ADD so the immediate doesn't need to be materialized
2734 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2735 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2736 SRLI->getZExtValue());
2737 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2739 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2741 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2742 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2743 CombineTo(N0.getNode(), NewAdd);
2744 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2756 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2758 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2759 bool DemandHighBits) {
2760 if (!LegalOperations)
2763 EVT VT = N->getValueType(0);
2764 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2766 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2769 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2770 bool LookPassAnd0 = false;
2771 bool LookPassAnd1 = false;
2772 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2774 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2776 if (N0.getOpcode() == ISD::AND) {
2777 if (!N0.getNode()->hasOneUse())
2779 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2780 if (!N01C || N01C->getZExtValue() != 0xFF00)
2782 N0 = N0.getOperand(0);
2783 LookPassAnd0 = true;
2786 if (N1.getOpcode() == ISD::AND) {
2787 if (!N1.getNode()->hasOneUse())
2789 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2790 if (!N11C || N11C->getZExtValue() != 0xFF)
2792 N1 = N1.getOperand(0);
2793 LookPassAnd1 = true;
2796 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2798 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2800 if (!N0.getNode()->hasOneUse() ||
2801 !N1.getNode()->hasOneUse())
2804 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2805 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2808 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2811 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2812 SDValue N00 = N0->getOperand(0);
2813 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2814 if (!N00.getNode()->hasOneUse())
2816 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2817 if (!N001C || N001C->getZExtValue() != 0xFF)
2819 N00 = N00.getOperand(0);
2820 LookPassAnd0 = true;
2823 SDValue N10 = N1->getOperand(0);
2824 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2825 if (!N10.getNode()->hasOneUse())
2827 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2828 if (!N101C || N101C->getZExtValue() != 0xFF00)
2830 N10 = N10.getOperand(0);
2831 LookPassAnd1 = true;
2837 // Make sure everything beyond the low halfword is zero since the SRL 16
2838 // will clear the top bits.
2839 unsigned OpSizeInBits = VT.getSizeInBits();
2840 if (DemandHighBits && OpSizeInBits > 16 &&
2841 (!LookPassAnd0 || !LookPassAnd1) &&
2842 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2845 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2846 if (OpSizeInBits > 16)
2847 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2848 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2852 /// isBSwapHWordElement - Return true if the specified node is an element
2853 /// that makes up a 32-bit packed halfword byteswap. i.e.
2854 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2855 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2856 if (!N.getNode()->hasOneUse())
2859 unsigned Opc = N.getOpcode();
2860 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2868 switch (N1C->getZExtValue()) {
2871 case 0xFF: Num = 0; break;
2872 case 0xFF00: Num = 1; break;
2873 case 0xFF0000: Num = 2; break;
2874 case 0xFF000000: Num = 3; break;
2877 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2878 SDValue N0 = N.getOperand(0);
2879 if (Opc == ISD::AND) {
2880 if (Num == 0 || Num == 2) {
2882 // (x >> 8) & 0xff0000
2883 if (N0.getOpcode() != ISD::SRL)
2885 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2886 if (!C || C->getZExtValue() != 8)
2889 // (x << 8) & 0xff00
2890 // (x << 8) & 0xff000000
2891 if (N0.getOpcode() != ISD::SHL)
2893 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2894 if (!C || C->getZExtValue() != 8)
2897 } else if (Opc == ISD::SHL) {
2899 // (x & 0xff0000) << 8
2900 if (Num != 0 && Num != 2)
2902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2903 if (!C || C->getZExtValue() != 8)
2905 } else { // Opc == ISD::SRL
2906 // (x & 0xff00) >> 8
2907 // (x & 0xff000000) >> 8
2908 if (Num != 1 && Num != 3)
2910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2911 if (!C || C->getZExtValue() != 8)
2918 Parts[Num] = N0.getOperand(0).getNode();
2922 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2923 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2924 /// => (rotl (bswap x), 16)
2925 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2926 if (!LegalOperations)
2929 EVT VT = N->getValueType(0);
2932 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2935 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2937 // (or (or (and), (and)), (or (and), (and)))
2938 // (or (or (or (and), (and)), (and)), (and))
2939 if (N0.getOpcode() != ISD::OR)
2941 SDValue N00 = N0.getOperand(0);
2942 SDValue N01 = N0.getOperand(1);
2944 if (N1.getOpcode() == ISD::OR) {
2945 // (or (or (and), (and)), (or (and), (and)))
2946 SDValue N000 = N00.getOperand(0);
2947 if (!isBSwapHWordElement(N000, Parts))
2950 SDValue N001 = N00.getOperand(1);
2951 if (!isBSwapHWordElement(N001, Parts))
2953 SDValue N010 = N01.getOperand(0);
2954 if (!isBSwapHWordElement(N010, Parts))
2956 SDValue N011 = N01.getOperand(1);
2957 if (!isBSwapHWordElement(N011, Parts))
2960 // (or (or (or (and), (and)), (and)), (and))
2961 if (!isBSwapHWordElement(N1, Parts))
2963 if (!isBSwapHWordElement(N01, Parts))
2965 if (N00.getOpcode() != ISD::OR)
2967 SDValue N000 = N00.getOperand(0);
2968 if (!isBSwapHWordElement(N000, Parts))
2970 SDValue N001 = N00.getOperand(1);
2971 if (!isBSwapHWordElement(N001, Parts))
2975 // Make sure the parts are all coming from the same node.
2976 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2979 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2980 SDValue(Parts[0],0));
2982 // Result of the bswap should be rotated by 16. If it's not legal, than
2983 // do (x << 16) | (x >> 16).
2984 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2985 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2986 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2987 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2988 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2989 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2990 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2991 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2994 SDValue DAGCombiner::visitOR(SDNode *N) {
2995 SDValue N0 = N->getOperand(0);
2996 SDValue N1 = N->getOperand(1);
2997 SDValue LL, LR, RL, RR, CC0, CC1;
2998 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2999 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3000 EVT VT = N1.getValueType();
3003 if (VT.isVector()) {
3004 SDValue FoldedVOp = SimplifyVBinOp(N);
3005 if (FoldedVOp.getNode()) return FoldedVOp;
3008 // fold (or x, undef) -> -1
3009 if (!LegalOperations &&
3010 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3011 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3012 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3014 // fold (or c1, c2) -> c1|c2
3016 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3017 // canonicalize constant to RHS
3019 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3020 // fold (or x, 0) -> x
3021 if (N1C && N1C->isNullValue())
3023 // fold (or x, -1) -> -1
3024 if (N1C && N1C->isAllOnesValue())
3026 // fold (or x, c) -> c iff (x & ~c) == 0
3027 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3030 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3031 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3032 if (BSwap.getNode() != 0)
3034 BSwap = MatchBSwapHWordLow(N, N0, N1);
3035 if (BSwap.getNode() != 0)
3039 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3040 if (ROR.getNode() != 0)
3042 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3043 // iff (c1 & c2) == 0.
3044 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3045 isa<ConstantSDNode>(N0.getOperand(1))) {
3046 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3047 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3048 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3049 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3050 N0.getOperand(0), N1),
3051 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3053 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3054 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3055 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3056 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3058 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3059 LL.getValueType().isInteger()) {
3060 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3061 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3062 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3063 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3064 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3065 LR.getValueType(), LL, RL);
3066 AddToWorkList(ORNode.getNode());
3067 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3069 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3070 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3071 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3072 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3073 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3074 LR.getValueType(), LL, RL);
3075 AddToWorkList(ANDNode.getNode());
3076 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3079 // canonicalize equivalent to ll == rl
3080 if (LL == RR && LR == RL) {
3081 Op1 = ISD::getSetCCSwappedOperands(Op1);
3084 if (LL == RL && LR == RR) {
3085 bool isInteger = LL.getValueType().isInteger();
3086 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3087 if (Result != ISD::SETCC_INVALID &&
3088 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3089 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3094 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3095 if (N0.getOpcode() == N1.getOpcode()) {
3096 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3097 if (Tmp.getNode()) return Tmp;
3100 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3101 if (N0.getOpcode() == ISD::AND &&
3102 N1.getOpcode() == ISD::AND &&
3103 N0.getOperand(1).getOpcode() == ISD::Constant &&
3104 N1.getOperand(1).getOpcode() == ISD::Constant &&
3105 // Don't increase # computations.
3106 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3107 // We can only do this xform if we know that bits from X that are set in C2
3108 // but not in C1 are already zero. Likewise for Y.
3109 const APInt &LHSMask =
3110 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3111 const APInt &RHSMask =
3112 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3114 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3115 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3116 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3117 N0.getOperand(0), N1.getOperand(0));
3118 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3119 DAG.getConstant(LHSMask | RHSMask, VT));
3123 // See if this is some rotate idiom.
3124 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3125 return SDValue(Rot, 0);
3127 // Simplify the operands using demanded-bits information.
3128 if (!VT.isVector() &&
3129 SimplifyDemandedBits(SDValue(N, 0)))
3130 return SDValue(N, 0);
3135 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3136 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3137 if (Op.getOpcode() == ISD::AND) {
3138 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3139 Mask = Op.getOperand(1);
3140 Op = Op.getOperand(0);
3146 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3154 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3155 // idioms for rotate, and if the target supports rotation instructions, generate
3157 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3158 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3159 EVT VT = LHS.getValueType();
3160 if (!TLI.isTypeLegal(VT)) return 0;
3162 // The target must have at least one rotate flavor.
3163 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3164 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3165 if (!HasROTL && !HasROTR) return 0;
3167 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3168 SDValue LHSShift; // The shift.
3169 SDValue LHSMask; // AND value if any.
3170 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3171 return 0; // Not part of a rotate.
3173 SDValue RHSShift; // The shift.
3174 SDValue RHSMask; // AND value if any.
3175 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3176 return 0; // Not part of a rotate.
3178 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3179 return 0; // Not shifting the same value.
3181 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3182 return 0; // Shifts must disagree.
3184 // Canonicalize shl to left side in a shl/srl pair.
3185 if (RHSShift.getOpcode() == ISD::SHL) {
3186 std::swap(LHS, RHS);
3187 std::swap(LHSShift, RHSShift);
3188 std::swap(LHSMask , RHSMask );
3191 unsigned OpSizeInBits = VT.getSizeInBits();
3192 SDValue LHSShiftArg = LHSShift.getOperand(0);
3193 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3194 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3196 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3197 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3198 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3199 RHSShiftAmt.getOpcode() == ISD::Constant) {
3200 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3201 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3202 if ((LShVal + RShVal) != OpSizeInBits)
3207 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
3209 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
3211 // If there is an AND of either shifted operand, apply it to the result.
3212 if (LHSMask.getNode() || RHSMask.getNode()) {
3213 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3215 if (LHSMask.getNode()) {
3216 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3217 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3219 if (RHSMask.getNode()) {
3220 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3221 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3224 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3227 return Rot.getNode();
3230 // If there is a mask here, and we have a variable shift, we can't be sure
3231 // that we're masking out the right stuff.
3232 if (LHSMask.getNode() || RHSMask.getNode())
3235 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3236 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3237 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3238 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3239 if (ConstantSDNode *SUBC =
3240 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3241 if (SUBC->getAPIntValue() == OpSizeInBits) {
3243 return DAG.getNode(ISD::ROTL, DL, VT,
3244 LHSShiftArg, LHSShiftAmt).getNode();
3246 return DAG.getNode(ISD::ROTR, DL, VT,
3247 LHSShiftArg, RHSShiftAmt).getNode();
3252 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3253 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3254 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3255 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3256 if (ConstantSDNode *SUBC =
3257 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3258 if (SUBC->getAPIntValue() == OpSizeInBits) {
3260 return DAG.getNode(ISD::ROTR, DL, VT,
3261 LHSShiftArg, RHSShiftAmt).getNode();
3263 return DAG.getNode(ISD::ROTL, DL, VT,
3264 LHSShiftArg, LHSShiftAmt).getNode();
3269 // Look for sign/zext/any-extended or truncate cases:
3270 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3271 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3272 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3273 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3274 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3275 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3276 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3277 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3278 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3279 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3280 if (RExtOp0.getOpcode() == ISD::SUB &&
3281 RExtOp0.getOperand(1) == LExtOp0) {
3282 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3284 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3285 // (rotr x, (sub 32, y))
3286 if (ConstantSDNode *SUBC =
3287 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3288 if (SUBC->getAPIntValue() == OpSizeInBits) {
3289 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3291 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3294 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3295 RExtOp0 == LExtOp0.getOperand(1)) {
3296 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3298 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3299 // (rotl x, (sub 32, y))
3300 if (ConstantSDNode *SUBC =
3301 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3302 if (SUBC->getAPIntValue() == OpSizeInBits) {
3303 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3305 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3314 SDValue DAGCombiner::visitXOR(SDNode *N) {
3315 SDValue N0 = N->getOperand(0);
3316 SDValue N1 = N->getOperand(1);
3317 SDValue LHS, RHS, CC;
3318 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3320 EVT VT = N0.getValueType();
3323 if (VT.isVector()) {
3324 SDValue FoldedVOp = SimplifyVBinOp(N);
3325 if (FoldedVOp.getNode()) return FoldedVOp;
3328 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3329 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3330 return DAG.getConstant(0, VT);
3331 // fold (xor x, undef) -> undef
3332 if (N0.getOpcode() == ISD::UNDEF)
3334 if (N1.getOpcode() == ISD::UNDEF)
3336 // fold (xor c1, c2) -> c1^c2
3338 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3339 // canonicalize constant to RHS
3341 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3342 // fold (xor x, 0) -> x
3343 if (N1C && N1C->isNullValue())
3346 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3347 if (RXOR.getNode() != 0)
3350 // fold !(x cc y) -> (x !cc y)
3351 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3352 bool isInt = LHS.getValueType().isInteger();
3353 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3356 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3357 switch (N0.getOpcode()) {
3359 llvm_unreachable("Unhandled SetCC Equivalent!");
3361 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3362 case ISD::SELECT_CC:
3363 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3364 N0.getOperand(3), NotCC);
3369 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3370 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3371 N0.getNode()->hasOneUse() &&
3372 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3373 SDValue V = N0.getOperand(0);
3374 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3375 DAG.getConstant(1, V.getValueType()));
3376 AddToWorkList(V.getNode());
3377 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3380 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3381 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3382 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3383 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3384 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3385 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3386 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3387 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3388 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3389 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3392 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3393 if (N1C && N1C->isAllOnesValue() &&
3394 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3395 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3396 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3397 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3398 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3399 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3400 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3401 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3404 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3405 if (N1C && N0.getOpcode() == ISD::XOR) {
3406 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3407 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3409 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3410 DAG.getConstant(N1C->getAPIntValue() ^
3411 N00C->getAPIntValue(), VT));
3413 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3414 DAG.getConstant(N1C->getAPIntValue() ^
3415 N01C->getAPIntValue(), VT));
3417 // fold (xor x, x) -> 0
3419 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3421 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3422 if (N0.getOpcode() == N1.getOpcode()) {
3423 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3424 if (Tmp.getNode()) return Tmp;
3427 // Simplify the expression using non-local knowledge.
3428 if (!VT.isVector() &&
3429 SimplifyDemandedBits(SDValue(N, 0)))
3430 return SDValue(N, 0);
3435 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3436 /// the shift amount is a constant.
3437 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3438 SDNode *LHS = N->getOperand(0).getNode();
3439 if (!LHS->hasOneUse()) return SDValue();
3441 // We want to pull some binops through shifts, so that we have (and (shift))
3442 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3443 // thing happens with address calculations, so it's important to canonicalize
3445 bool HighBitSet = false; // Can we transform this if the high bit is set?
3447 switch (LHS->getOpcode()) {
3448 default: return SDValue();
3451 HighBitSet = false; // We can only transform sra if the high bit is clear.
3454 HighBitSet = true; // We can only transform sra if the high bit is set.
3457 if (N->getOpcode() != ISD::SHL)
3458 return SDValue(); // only shl(add) not sr[al](add).
3459 HighBitSet = false; // We can only transform sra if the high bit is clear.
3463 // We require the RHS of the binop to be a constant as well.
3464 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3465 if (!BinOpCst) return SDValue();
3467 // FIXME: disable this unless the input to the binop is a shift by a constant.
3468 // If it is not a shift, it pessimizes some common cases like:
3470 // void foo(int *X, int i) { X[i & 1235] = 1; }
3471 // int bar(int *X, int i) { return X[i & 255]; }
3472 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3473 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3474 BinOpLHSVal->getOpcode() != ISD::SRA &&
3475 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3476 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3479 EVT VT = N->getValueType(0);
3481 // If this is a signed shift right, and the high bit is modified by the
3482 // logical operation, do not perform the transformation. The highBitSet
3483 // boolean indicates the value of the high bit of the constant which would
3484 // cause it to be modified for this operation.
3485 if (N->getOpcode() == ISD::SRA) {
3486 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3487 if (BinOpRHSSignSet != HighBitSet)
3491 // Fold the constants, shifting the binop RHS by the shift amount.
3492 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3494 LHS->getOperand(1), N->getOperand(1));
3496 // Create the new shift.
3497 SDValue NewShift = DAG.getNode(N->getOpcode(),
3498 LHS->getOperand(0).getDebugLoc(),
3499 VT, LHS->getOperand(0), N->getOperand(1));
3501 // Create the new binop.
3502 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3505 SDValue DAGCombiner::visitSHL(SDNode *N) {
3506 SDValue N0 = N->getOperand(0);
3507 SDValue N1 = N->getOperand(1);
3508 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3510 EVT VT = N0.getValueType();
3511 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3513 // fold (shl c1, c2) -> c1<<c2
3515 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3516 // fold (shl 0, x) -> 0
3517 if (N0C && N0C->isNullValue())
3519 // fold (shl x, c >= size(x)) -> undef
3520 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3521 return DAG.getUNDEF(VT);
3522 // fold (shl x, 0) -> x
3523 if (N1C && N1C->isNullValue())
3525 // fold (shl undef, x) -> 0
3526 if (N0.getOpcode() == ISD::UNDEF)
3527 return DAG.getConstant(0, VT);
3528 // if (shl x, c) is known to be zero, return 0
3529 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3530 APInt::getAllOnesValue(OpSizeInBits)))
3531 return DAG.getConstant(0, VT);
3532 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3533 if (N1.getOpcode() == ISD::TRUNCATE &&
3534 N1.getOperand(0).getOpcode() == ISD::AND &&
3535 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3536 SDValue N101 = N1.getOperand(0).getOperand(1);
3537 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3538 EVT TruncVT = N1.getValueType();
3539 SDValue N100 = N1.getOperand(0).getOperand(0);
3540 APInt TruncC = N101C->getAPIntValue();
3541 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3542 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3543 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3544 DAG.getNode(ISD::TRUNCATE,
3547 DAG.getConstant(TruncC, TruncVT)));
3551 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3552 return SDValue(N, 0);
3554 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3555 if (N1C && N0.getOpcode() == ISD::SHL &&
3556 N0.getOperand(1).getOpcode() == ISD::Constant) {
3557 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3558 uint64_t c2 = N1C->getZExtValue();
3559 if (c1 + c2 >= OpSizeInBits)
3560 return DAG.getConstant(0, VT);
3561 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3562 DAG.getConstant(c1 + c2, N1.getValueType()));
3565 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3566 // For this to be valid, the second form must not preserve any of the bits
3567 // that are shifted out by the inner shift in the first form. This means
3568 // the outer shift size must be >= the number of bits added by the ext.
3569 // As a corollary, we don't care what kind of ext it is.
3570 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3571 N0.getOpcode() == ISD::ANY_EXTEND ||
3572 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3573 N0.getOperand(0).getOpcode() == ISD::SHL &&
3574 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3576 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3577 uint64_t c2 = N1C->getZExtValue();
3578 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3579 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3580 if (c2 >= OpSizeInBits - InnerShiftSize) {
3581 if (c1 + c2 >= OpSizeInBits)
3582 return DAG.getConstant(0, VT);
3583 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3584 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3585 N0.getOperand(0)->getOperand(0)),
3586 DAG.getConstant(c1 + c2, N1.getValueType()));
3590 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3591 // (and (srl x, (sub c1, c2), MASK)
3592 // Only fold this if the inner shift has no other uses -- if it does, folding
3593 // this will increase the total number of instructions.
3594 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3595 N0.getOperand(1).getOpcode() == ISD::Constant) {
3596 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3597 if (c1 < VT.getSizeInBits()) {
3598 uint64_t c2 = N1C->getZExtValue();
3599 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3600 VT.getSizeInBits() - c1);
3603 Mask = Mask.shl(c2-c1);
3604 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3605 DAG.getConstant(c2-c1, N1.getValueType()));
3607 Mask = Mask.lshr(c1-c2);
3608 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3609 DAG.getConstant(c1-c2, N1.getValueType()));
3611 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3612 DAG.getConstant(Mask, VT));
3615 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3616 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3617 SDValue HiBitsMask =
3618 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3619 VT.getSizeInBits() -
3620 N1C->getZExtValue()),
3622 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3627 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3628 if (NewSHL.getNode())
3635 SDValue DAGCombiner::visitSRA(SDNode *N) {
3636 SDValue N0 = N->getOperand(0);
3637 SDValue N1 = N->getOperand(1);
3638 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3639 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3640 EVT VT = N0.getValueType();
3641 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3643 // fold (sra c1, c2) -> (sra c1, c2)
3645 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3646 // fold (sra 0, x) -> 0
3647 if (N0C && N0C->isNullValue())
3649 // fold (sra -1, x) -> -1
3650 if (N0C && N0C->isAllOnesValue())
3652 // fold (sra x, (setge c, size(x))) -> undef
3653 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3654 return DAG.getUNDEF(VT);
3655 // fold (sra x, 0) -> x
3656 if (N1C && N1C->isNullValue())
3658 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3660 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3661 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3662 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3664 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3665 ExtVT, VT.getVectorNumElements());
3666 if ((!LegalOperations ||
3667 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3668 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3669 N0.getOperand(0), DAG.getValueType(ExtVT));
3672 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3673 if (N1C && N0.getOpcode() == ISD::SRA) {
3674 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3675 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3676 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3677 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3678 DAG.getConstant(Sum, N1C->getValueType(0)));
3682 // fold (sra (shl X, m), (sub result_size, n))
3683 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3684 // result_size - n != m.
3685 // If truncate is free for the target sext(shl) is likely to result in better
3687 if (N0.getOpcode() == ISD::SHL) {
3688 // Get the two constanst of the shifts, CN0 = m, CN = n.
3689 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3691 // Determine what the truncate's result bitsize and type would be.
3693 EVT::getIntegerVT(*DAG.getContext(),
3694 OpSizeInBits - N1C->getZExtValue());
3695 // Determine the residual right-shift amount.
3696 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3698 // If the shift is not a no-op (in which case this should be just a sign
3699 // extend already), the truncated to type is legal, sign_extend is legal
3700 // on that type, and the truncate to that type is both legal and free,
3701 // perform the transform.
3702 if ((ShiftAmt > 0) &&
3703 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3704 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3705 TLI.isTruncateFree(VT, TruncVT)) {
3707 SDValue Amt = DAG.getConstant(ShiftAmt,
3708 getShiftAmountTy(N0.getOperand(0).getValueType()));
3709 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3710 N0.getOperand(0), Amt);
3711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3713 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3714 N->getValueType(0), Trunc);
3719 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3720 if (N1.getOpcode() == ISD::TRUNCATE &&
3721 N1.getOperand(0).getOpcode() == ISD::AND &&
3722 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3723 SDValue N101 = N1.getOperand(0).getOperand(1);
3724 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3725 EVT TruncVT = N1.getValueType();
3726 SDValue N100 = N1.getOperand(0).getOperand(0);
3727 APInt TruncC = N101C->getAPIntValue();
3728 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3729 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3730 DAG.getNode(ISD::AND, N->getDebugLoc(),
3732 DAG.getNode(ISD::TRUNCATE,
3735 DAG.getConstant(TruncC, TruncVT)));
3739 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3740 // if c1 is equal to the number of bits the trunc removes
3741 if (N0.getOpcode() == ISD::TRUNCATE &&
3742 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3743 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3744 N0.getOperand(0).hasOneUse() &&
3745 N0.getOperand(0).getOperand(1).hasOneUse() &&
3746 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3747 EVT LargeVT = N0.getOperand(0).getValueType();
3748 ConstantSDNode *LargeShiftAmt =
3749 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3751 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3752 LargeShiftAmt->getZExtValue()) {
3754 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3755 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3756 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3757 N0.getOperand(0).getOperand(0), Amt);
3758 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3762 // Simplify, based on bits shifted out of the LHS.
3763 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3764 return SDValue(N, 0);
3767 // If the sign bit is known to be zero, switch this to a SRL.
3768 if (DAG.SignBitIsZero(N0))
3769 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3772 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3773 if (NewSRA.getNode())
3780 SDValue DAGCombiner::visitSRL(SDNode *N) {
3781 SDValue N0 = N->getOperand(0);
3782 SDValue N1 = N->getOperand(1);
3783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3785 EVT VT = N0.getValueType();
3786 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3788 // fold (srl c1, c2) -> c1 >>u c2
3790 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3791 // fold (srl 0, x) -> 0
3792 if (N0C && N0C->isNullValue())
3794 // fold (srl x, c >= size(x)) -> undef
3795 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3796 return DAG.getUNDEF(VT);
3797 // fold (srl x, 0) -> x
3798 if (N1C && N1C->isNullValue())
3800 // if (srl x, c) is known to be zero, return 0
3801 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3802 APInt::getAllOnesValue(OpSizeInBits)))
3803 return DAG.getConstant(0, VT);
3805 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3806 if (N1C && N0.getOpcode() == ISD::SRL &&
3807 N0.getOperand(1).getOpcode() == ISD::Constant) {
3808 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3809 uint64_t c2 = N1C->getZExtValue();
3810 if (c1 + c2 >= OpSizeInBits)
3811 return DAG.getConstant(0, VT);
3812 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3813 DAG.getConstant(c1 + c2, N1.getValueType()));
3816 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3817 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3818 N0.getOperand(0).getOpcode() == ISD::SRL &&
3819 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3821 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3822 uint64_t c2 = N1C->getZExtValue();
3823 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3824 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3825 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3826 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3827 if (c1 + OpSizeInBits == InnerShiftSize) {
3828 if (c1 + c2 >= InnerShiftSize)
3829 return DAG.getConstant(0, VT);
3830 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3831 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3832 N0.getOperand(0)->getOperand(0),
3833 DAG.getConstant(c1 + c2, ShiftCountVT)));
3837 // fold (srl (shl x, c), c) -> (and x, cst2)
3838 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3839 N0.getValueSizeInBits() <= 64) {
3840 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3841 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3842 DAG.getConstant(~0ULL >> ShAmt, VT));
3846 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3847 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3848 // Shifting in all undef bits?
3849 EVT SmallVT = N0.getOperand(0).getValueType();
3850 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3851 return DAG.getUNDEF(VT);
3853 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3854 uint64_t ShiftAmt = N1C->getZExtValue();
3855 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3857 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3858 AddToWorkList(SmallShift.getNode());
3859 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3863 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3864 // bit, which is unmodified by sra.
3865 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3866 if (N0.getOpcode() == ISD::SRA)
3867 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3870 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3871 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3872 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3873 APInt KnownZero, KnownOne;
3874 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3876 // If any of the input bits are KnownOne, then the input couldn't be all
3877 // zeros, thus the result of the srl will always be zero.
3878 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3880 // If all of the bits input the to ctlz node are known to be zero, then
3881 // the result of the ctlz is "32" and the result of the shift is one.
3882 APInt UnknownBits = ~KnownZero;
3883 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3885 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3886 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3887 // Okay, we know that only that the single bit specified by UnknownBits
3888 // could be set on input to the CTLZ node. If this bit is set, the SRL
3889 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3890 // to an SRL/XOR pair, which is likely to simplify more.
3891 unsigned ShAmt = UnknownBits.countTrailingZeros();
3892 SDValue Op = N0.getOperand(0);
3895 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3896 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3897 AddToWorkList(Op.getNode());
3900 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3901 Op, DAG.getConstant(1, VT));
3905 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3906 if (N1.getOpcode() == ISD::TRUNCATE &&
3907 N1.getOperand(0).getOpcode() == ISD::AND &&
3908 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3909 SDValue N101 = N1.getOperand(0).getOperand(1);
3910 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3911 EVT TruncVT = N1.getValueType();
3912 SDValue N100 = N1.getOperand(0).getOperand(0);
3913 APInt TruncC = N101C->getAPIntValue();
3914 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3915 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3916 DAG.getNode(ISD::AND, N->getDebugLoc(),
3918 DAG.getNode(ISD::TRUNCATE,
3921 DAG.getConstant(TruncC, TruncVT)));
3925 // fold operands of srl based on knowledge that the low bits are not
3927 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3928 return SDValue(N, 0);
3931 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3932 if (NewSRL.getNode())
3936 // Attempt to convert a srl of a load into a narrower zero-extending load.
3937 SDValue NarrowLoad = ReduceLoadWidth(N);
3938 if (NarrowLoad.getNode())
3941 // Here is a common situation. We want to optimize:
3944 // %b = and i32 %a, 2
3945 // %c = srl i32 %b, 1
3946 // brcond i32 %c ...
3952 // %c = setcc eq %b, 0
3955 // However when after the source operand of SRL is optimized into AND, the SRL
3956 // itself may not be optimized further. Look for it and add the BRCOND into
3958 if (N->hasOneUse()) {
3959 SDNode *Use = *N->use_begin();
3960 if (Use->getOpcode() == ISD::BRCOND)
3962 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3963 // Also look pass the truncate.
3964 Use = *Use->use_begin();
3965 if (Use->getOpcode() == ISD::BRCOND)
3973 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3974 SDValue N0 = N->getOperand(0);
3975 EVT VT = N->getValueType(0);
3977 // fold (ctlz c1) -> c2
3978 if (isa<ConstantSDNode>(N0))
3979 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3983 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3984 SDValue N0 = N->getOperand(0);
3985 EVT VT = N->getValueType(0);
3987 // fold (ctlz_zero_undef c1) -> c2
3988 if (isa<ConstantSDNode>(N0))
3989 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3993 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3994 SDValue N0 = N->getOperand(0);
3995 EVT VT = N->getValueType(0);
3997 // fold (cttz c1) -> c2
3998 if (isa<ConstantSDNode>(N0))
3999 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4003 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4004 SDValue N0 = N->getOperand(0);
4005 EVT VT = N->getValueType(0);
4007 // fold (cttz_zero_undef c1) -> c2
4008 if (isa<ConstantSDNode>(N0))
4009 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4013 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4014 SDValue N0 = N->getOperand(0);
4015 EVT VT = N->getValueType(0);
4017 // fold (ctpop c1) -> c2
4018 if (isa<ConstantSDNode>(N0))
4019 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4023 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4024 SDValue N0 = N->getOperand(0);
4025 SDValue N1 = N->getOperand(1);
4026 SDValue N2 = N->getOperand(2);
4027 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4028 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4029 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4030 EVT VT = N->getValueType(0);
4031 EVT VT0 = N0.getValueType();
4033 // fold (select C, X, X) -> X
4036 // fold (select true, X, Y) -> X
4037 if (N0C && !N0C->isNullValue())
4039 // fold (select false, X, Y) -> Y
4040 if (N0C && N0C->isNullValue())
4042 // fold (select C, 1, X) -> (or C, X)
4043 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4044 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4045 // fold (select C, 0, 1) -> (xor C, 1)
4046 if (VT.isInteger() &&
4049 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
4050 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4053 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4054 N0, DAG.getConstant(1, VT0));
4055 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4056 N0, DAG.getConstant(1, VT0));
4057 AddToWorkList(XORNode.getNode());
4059 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4060 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4062 // fold (select C, 0, X) -> (and (not C), X)
4063 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4064 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4065 AddToWorkList(NOTNode.getNode());
4066 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4068 // fold (select C, X, 1) -> (or (not C), X)
4069 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4070 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4071 AddToWorkList(NOTNode.getNode());
4072 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4074 // fold (select C, X, 0) -> (and C, X)
4075 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4076 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4077 // fold (select X, X, Y) -> (or X, Y)
4078 // fold (select X, 1, Y) -> (or X, Y)
4079 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4080 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4081 // fold (select X, Y, X) -> (and X, Y)
4082 // fold (select X, Y, 0) -> (and X, Y)
4083 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4084 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4086 // If we can fold this based on the true/false value, do so.
4087 if (SimplifySelectOps(N, N1, N2))
4088 return SDValue(N, 0); // Don't revisit N.
4090 // fold selects based on a setcc into other things, such as min/max/abs
4091 if (N0.getOpcode() == ISD::SETCC) {
4093 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4094 // having to say they don't support SELECT_CC on every type the DAG knows
4095 // about, since there is no way to mark an opcode illegal at all value types
4096 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4097 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4098 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4099 N0.getOperand(0), N0.getOperand(1),
4100 N1, N2, N0.getOperand(2));
4101 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4107 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4108 SDValue N0 = N->getOperand(0);
4109 SDValue N1 = N->getOperand(1);
4110 SDValue N2 = N->getOperand(2);
4111 SDValue N3 = N->getOperand(3);
4112 SDValue N4 = N->getOperand(4);
4113 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4115 // fold select_cc lhs, rhs, x, x, cc -> x
4119 // Determine if the condition we're dealing with is constant
4120 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4121 N0, N1, CC, N->getDebugLoc(), false);
4122 if (SCC.getNode()) AddToWorkList(SCC.getNode());
4124 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4125 if (!SCCC->isNullValue())
4126 return N2; // cond always true -> true val
4128 return N3; // cond always false -> false val
4131 // Fold to a simpler select_cc
4132 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4133 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4134 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4137 // If we can fold this based on the true/false value, do so.
4138 if (SimplifySelectOps(N, N2, N3))
4139 return SDValue(N, 0); // Don't revisit N.
4141 // fold select_cc into other things, such as min/max/abs
4142 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4145 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4146 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4147 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4151 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4152 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4153 // transformation. Returns true if extension are possible and the above
4154 // mentioned transformation is profitable.
4155 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4157 SmallVector<SDNode*, 4> &ExtendNodes,
4158 const TargetLowering &TLI) {
4159 bool HasCopyToRegUses = false;
4160 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4161 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4162 UE = N0.getNode()->use_end();
4167 if (UI.getUse().getResNo() != N0.getResNo())
4169 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4170 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4171 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4172 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4173 // Sign bits will be lost after a zext.
4176 for (unsigned i = 0; i != 2; ++i) {
4177 SDValue UseOp = User->getOperand(i);
4180 if (!isa<ConstantSDNode>(UseOp))
4185 ExtendNodes.push_back(User);
4188 // If truncates aren't free and there are users we can't
4189 // extend, it isn't worthwhile.
4192 // Remember if this value is live-out.
4193 if (User->getOpcode() == ISD::CopyToReg)
4194 HasCopyToRegUses = true;
4197 if (HasCopyToRegUses) {
4198 bool BothLiveOut = false;
4199 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4201 SDUse &Use = UI.getUse();
4202 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4208 // Both unextended and extended values are live out. There had better be
4209 // a good reason for the transformation.
4210 return ExtendNodes.size();
4215 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4216 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4217 ISD::NodeType ExtType) {
4218 // Extend SetCC uses if necessary.
4219 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4220 SDNode *SetCC = SetCCs[i];
4221 SmallVector<SDValue, 4> Ops;
4223 for (unsigned j = 0; j != 2; ++j) {
4224 SDValue SOp = SetCC->getOperand(j);
4226 Ops.push_back(ExtLoad);
4228 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4231 Ops.push_back(SetCC->getOperand(2));
4232 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4233 &Ops[0], Ops.size()));
4237 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4238 SDValue N0 = N->getOperand(0);
4239 EVT VT = N->getValueType(0);
4241 // fold (sext c1) -> c1
4242 if (isa<ConstantSDNode>(N0))
4243 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4245 // fold (sext (sext x)) -> (sext x)
4246 // fold (sext (aext x)) -> (sext x)
4247 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4248 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4251 if (N0.getOpcode() == ISD::TRUNCATE) {
4252 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4253 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4254 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4255 if (NarrowLoad.getNode()) {
4256 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4257 if (NarrowLoad.getNode() != N0.getNode()) {
4258 CombineTo(N0.getNode(), NarrowLoad);
4259 // CombineTo deleted the truncate, if needed, but not what's under it.
4262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4265 // See if the value being truncated is already sign extended. If so, just
4266 // eliminate the trunc/sext pair.
4267 SDValue Op = N0.getOperand(0);
4268 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4269 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4270 unsigned DestBits = VT.getScalarType().getSizeInBits();
4271 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4273 if (OpBits == DestBits) {
4274 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4275 // bits, it is already ready.
4276 if (NumSignBits > DestBits-MidBits)
4278 } else if (OpBits < DestBits) {
4279 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4280 // bits, just sext from i32.
4281 if (NumSignBits > OpBits-MidBits)
4282 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4284 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4285 // bits, just truncate to i32.
4286 if (NumSignBits > OpBits-MidBits)
4287 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4290 // fold (sext (truncate x)) -> (sextinreg x).
4291 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4292 N0.getValueType())) {
4293 if (OpBits < DestBits)
4294 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4295 else if (OpBits > DestBits)
4296 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4297 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4298 DAG.getValueType(N0.getValueType()));
4302 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4303 // None of the supported targets knows how to perform load and sign extend
4304 // on vectors in one instruction. We only perform this transformation on
4306 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4307 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4308 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4309 bool DoXform = true;
4310 SmallVector<SDNode*, 4> SetCCs;
4311 if (!N0.hasOneUse())
4312 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4314 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4315 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4317 LN0->getBasePtr(), LN0->getPointerInfo(),
4319 LN0->isVolatile(), LN0->isNonTemporal(),
4320 LN0->getAlignment());
4321 CombineTo(N, ExtLoad);
4322 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4323 N0.getValueType(), ExtLoad);
4324 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4325 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4327 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4331 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4332 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4333 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4334 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4335 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4336 EVT MemVT = LN0->getMemoryVT();
4337 if ((!LegalOperations && !LN0->isVolatile()) ||
4338 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4339 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4341 LN0->getBasePtr(), LN0->getPointerInfo(),
4343 LN0->isVolatile(), LN0->isNonTemporal(),
4344 LN0->getAlignment());
4345 CombineTo(N, ExtLoad);
4346 CombineTo(N0.getNode(),
4347 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4348 N0.getValueType(), ExtLoad),
4349 ExtLoad.getValue(1));
4350 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4354 // fold (sext (and/or/xor (load x), cst)) ->
4355 // (and/or/xor (sextload x), (sext cst))
4356 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4357 N0.getOpcode() == ISD::XOR) &&
4358 isa<LoadSDNode>(N0.getOperand(0)) &&
4359 N0.getOperand(1).getOpcode() == ISD::Constant &&
4360 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4361 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4362 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4363 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4364 bool DoXform = true;
4365 SmallVector<SDNode*, 4> SetCCs;
4366 if (!N0.hasOneUse())
4367 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4370 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4371 LN0->getChain(), LN0->getBasePtr(),
4372 LN0->getPointerInfo(),
4375 LN0->isNonTemporal(),
4376 LN0->getAlignment());
4377 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4378 Mask = Mask.sext(VT.getSizeInBits());
4379 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4380 ExtLoad, DAG.getConstant(Mask, VT));
4381 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4382 N0.getOperand(0).getDebugLoc(),
4383 N0.getOperand(0).getValueType(), ExtLoad);
4385 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4386 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4388 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4393 if (N0.getOpcode() == ISD::SETCC) {
4394 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4395 // Only do this before legalize for now.
4396 if (VT.isVector() && !LegalOperations) {
4397 EVT N0VT = N0.getOperand(0).getValueType();
4398 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4399 // of the same size as the compared operands. Only optimize sext(setcc())
4400 // if this is the case.
4401 EVT SVT = TLI.getSetCCResultType(N0VT);
4403 // We know that the # elements of the results is the same as the
4404 // # elements of the compare (and the # elements of the compare result
4405 // for that matter). Check to see that they are the same size. If so,
4406 // we know that the element size of the sext'd result matches the
4407 // element size of the compare operands.
4408 if (VT.getSizeInBits() == SVT.getSizeInBits())
4409 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4411 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4412 // If the desired elements are smaller or larger than the source
4413 // elements we can use a matching integer vector type and then
4414 // truncate/sign extend
4416 EVT MatchingElementType =
4417 EVT::getIntegerVT(*DAG.getContext(),
4418 N0VT.getScalarType().getSizeInBits());
4419 EVT MatchingVectorType =
4420 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4421 N0VT.getVectorNumElements());
4423 if (SVT == MatchingVectorType) {
4424 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4425 N0.getOperand(0), N0.getOperand(1),
4426 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4427 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4432 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4433 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4435 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4437 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4438 NegOne, DAG.getConstant(0, VT),
4439 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4440 if (SCC.getNode()) return SCC;
4441 if (!LegalOperations ||
4442 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4443 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4444 DAG.getSetCC(N->getDebugLoc(),
4445 TLI.getSetCCResultType(VT),
4446 N0.getOperand(0), N0.getOperand(1),
4447 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4448 NegOne, DAG.getConstant(0, VT));
4451 // fold (sext x) -> (zext x) if the sign bit is known zero.
4452 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4453 DAG.SignBitIsZero(N0))
4454 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4459 // isTruncateOf - If N is a truncate of some other value, return true, record
4460 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4461 // This function computes KnownZero to avoid a duplicated call to
4462 // ComputeMaskedBits in the caller.
4463 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4466 if (N->getOpcode() == ISD::TRUNCATE) {
4467 Op = N->getOperand(0);
4468 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4472 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4473 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4476 SDValue Op0 = N->getOperand(0);
4477 SDValue Op1 = N->getOperand(1);
4478 assert(Op0.getValueType() == Op1.getValueType());
4480 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4481 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4482 if (COp0 && COp0->isNullValue())
4484 else if (COp1 && COp1->isNullValue())
4489 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4491 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4497 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4498 SDValue N0 = N->getOperand(0);
4499 EVT VT = N->getValueType(0);
4501 // fold (zext c1) -> c1
4502 if (isa<ConstantSDNode>(N0))
4503 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4504 // fold (zext (zext x)) -> (zext x)
4505 // fold (zext (aext x)) -> (zext x)
4506 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4507 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4510 // fold (zext (truncate x)) -> (zext x) or
4511 // (zext (truncate x)) -> (truncate x)
4512 // This is valid when the truncated bits of x are already zero.
4513 // FIXME: We should extend this to work for vectors too.
4516 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4517 APInt TruncatedBits =
4518 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4519 APInt(Op.getValueSizeInBits(), 0) :
4520 APInt::getBitsSet(Op.getValueSizeInBits(),
4521 N0.getValueSizeInBits(),
4522 std::min(Op.getValueSizeInBits(),
4523 VT.getSizeInBits()));
4524 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4525 if (VT.bitsGT(Op.getValueType()))
4526 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4527 if (VT.bitsLT(Op.getValueType()))
4528 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4534 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4535 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4536 if (N0.getOpcode() == ISD::TRUNCATE) {
4537 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4538 if (NarrowLoad.getNode()) {
4539 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4540 if (NarrowLoad.getNode() != N0.getNode()) {
4541 CombineTo(N0.getNode(), NarrowLoad);
4542 // CombineTo deleted the truncate, if needed, but not what's under it.
4545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4549 // fold (zext (truncate x)) -> (and x, mask)
4550 if (N0.getOpcode() == ISD::TRUNCATE &&
4551 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4553 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4554 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4555 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4556 if (NarrowLoad.getNode()) {
4557 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4558 if (NarrowLoad.getNode() != N0.getNode()) {
4559 CombineTo(N0.getNode(), NarrowLoad);
4560 // CombineTo deleted the truncate, if needed, but not what's under it.
4563 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4566 SDValue Op = N0.getOperand(0);
4567 if (Op.getValueType().bitsLT(VT)) {
4568 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4569 AddToWorkList(Op.getNode());
4570 } else if (Op.getValueType().bitsGT(VT)) {
4571 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4572 AddToWorkList(Op.getNode());
4574 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4575 N0.getValueType().getScalarType());
4578 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4579 // if either of the casts is not free.
4580 if (N0.getOpcode() == ISD::AND &&
4581 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4582 N0.getOperand(1).getOpcode() == ISD::Constant &&
4583 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4584 N0.getValueType()) ||
4585 !TLI.isZExtFree(N0.getValueType(), VT))) {
4586 SDValue X = N0.getOperand(0).getOperand(0);
4587 if (X.getValueType().bitsLT(VT)) {
4588 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4589 } else if (X.getValueType().bitsGT(VT)) {
4590 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4593 Mask = Mask.zext(VT.getSizeInBits());
4594 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4595 X, DAG.getConstant(Mask, VT));
4598 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4599 // None of the supported targets knows how to perform load and vector_zext
4600 // on vectors in one instruction. We only perform this transformation on
4602 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4603 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4604 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4605 bool DoXform = true;
4606 SmallVector<SDNode*, 4> SetCCs;
4607 if (!N0.hasOneUse())
4608 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4611 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4613 LN0->getBasePtr(), LN0->getPointerInfo(),
4615 LN0->isVolatile(), LN0->isNonTemporal(),
4616 LN0->getAlignment());
4617 CombineTo(N, ExtLoad);
4618 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4619 N0.getValueType(), ExtLoad);
4620 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4622 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4624 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4628 // fold (zext (and/or/xor (load x), cst)) ->
4629 // (and/or/xor (zextload x), (zext cst))
4630 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4631 N0.getOpcode() == ISD::XOR) &&
4632 isa<LoadSDNode>(N0.getOperand(0)) &&
4633 N0.getOperand(1).getOpcode() == ISD::Constant &&
4634 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4635 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4636 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4637 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4638 bool DoXform = true;
4639 SmallVector<SDNode*, 4> SetCCs;
4640 if (!N0.hasOneUse())
4641 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4644 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4645 LN0->getChain(), LN0->getBasePtr(),
4646 LN0->getPointerInfo(),
4649 LN0->isNonTemporal(),
4650 LN0->getAlignment());
4651 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4652 Mask = Mask.zext(VT.getSizeInBits());
4653 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4654 ExtLoad, DAG.getConstant(Mask, VT));
4655 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4656 N0.getOperand(0).getDebugLoc(),
4657 N0.getOperand(0).getValueType(), ExtLoad);
4659 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4660 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4662 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4667 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4668 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4669 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4670 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4671 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4672 EVT MemVT = LN0->getMemoryVT();
4673 if ((!LegalOperations && !LN0->isVolatile()) ||
4674 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4675 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4677 LN0->getBasePtr(), LN0->getPointerInfo(),
4679 LN0->isVolatile(), LN0->isNonTemporal(),
4680 LN0->getAlignment());
4681 CombineTo(N, ExtLoad);
4682 CombineTo(N0.getNode(),
4683 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4685 ExtLoad.getValue(1));
4686 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4690 if (N0.getOpcode() == ISD::SETCC) {
4691 if (!LegalOperations && VT.isVector()) {
4692 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4693 // Only do this before legalize for now.
4694 EVT N0VT = N0.getOperand(0).getValueType();
4695 EVT EltVT = VT.getVectorElementType();
4696 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4697 DAG.getConstant(1, EltVT));
4698 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4699 // We know that the # elements of the results is the same as the
4700 // # elements of the compare (and the # elements of the compare result
4701 // for that matter). Check to see that they are the same size. If so,
4702 // we know that the element size of the sext'd result matches the
4703 // element size of the compare operands.
4704 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4705 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4707 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4708 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4709 &OneOps[0], OneOps.size()));
4711 // If the desired elements are smaller or larger than the source
4712 // elements we can use a matching integer vector type and then
4713 // truncate/sign extend
4714 EVT MatchingElementType =
4715 EVT::getIntegerVT(*DAG.getContext(),
4716 N0VT.getScalarType().getSizeInBits());
4717 EVT MatchingVectorType =
4718 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4719 N0VT.getVectorNumElements());
4721 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4723 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4724 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4725 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4726 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4727 &OneOps[0], OneOps.size()));
4730 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4732 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4733 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4735 if (SCC.getNode()) return SCC;
4738 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4739 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4740 isa<ConstantSDNode>(N0.getOperand(1)) &&
4741 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4743 SDValue ShAmt = N0.getOperand(1);
4744 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4745 if (N0.getOpcode() == ISD::SHL) {
4746 SDValue InnerZExt = N0.getOperand(0);
4747 // If the original shl may be shifting out bits, do not perform this
4749 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4750 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4751 if (ShAmtVal > KnownZeroBits)
4755 DebugLoc DL = N->getDebugLoc();
4757 // Ensure that the shift amount is wide enough for the shifted value.
4758 if (VT.getSizeInBits() >= 256)
4759 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4761 return DAG.getNode(N0.getOpcode(), DL, VT,
4762 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4769 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4770 SDValue N0 = N->getOperand(0);
4771 EVT VT = N->getValueType(0);
4773 // fold (aext c1) -> c1
4774 if (isa<ConstantSDNode>(N0))
4775 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4776 // fold (aext (aext x)) -> (aext x)
4777 // fold (aext (zext x)) -> (zext x)
4778 // fold (aext (sext x)) -> (sext x)
4779 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4780 N0.getOpcode() == ISD::ZERO_EXTEND ||
4781 N0.getOpcode() == ISD::SIGN_EXTEND)
4782 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4784 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4785 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4786 if (N0.getOpcode() == ISD::TRUNCATE) {
4787 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4788 if (NarrowLoad.getNode()) {
4789 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4790 if (NarrowLoad.getNode() != N0.getNode()) {
4791 CombineTo(N0.getNode(), NarrowLoad);
4792 // CombineTo deleted the truncate, if needed, but not what's under it.
4795 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4799 // fold (aext (truncate x))
4800 if (N0.getOpcode() == ISD::TRUNCATE) {
4801 SDValue TruncOp = N0.getOperand(0);
4802 if (TruncOp.getValueType() == VT)
4803 return TruncOp; // x iff x size == zext size.
4804 if (TruncOp.getValueType().bitsGT(VT))
4805 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4806 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4809 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4810 // if the trunc is not free.
4811 if (N0.getOpcode() == ISD::AND &&
4812 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4813 N0.getOperand(1).getOpcode() == ISD::Constant &&
4814 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4815 N0.getValueType())) {
4816 SDValue X = N0.getOperand(0).getOperand(0);
4817 if (X.getValueType().bitsLT(VT)) {
4818 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4819 } else if (X.getValueType().bitsGT(VT)) {
4820 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4822 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4823 Mask = Mask.zext(VT.getSizeInBits());
4824 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4825 X, DAG.getConstant(Mask, VT));
4828 // fold (aext (load x)) -> (aext (truncate (extload x)))
4829 // None of the supported targets knows how to perform load and any_ext
4830 // on vectors in one instruction. We only perform this transformation on
4832 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4833 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4834 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4835 bool DoXform = true;
4836 SmallVector<SDNode*, 4> SetCCs;
4837 if (!N0.hasOneUse())
4838 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4840 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4841 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4843 LN0->getBasePtr(), LN0->getPointerInfo(),
4845 LN0->isVolatile(), LN0->isNonTemporal(),
4846 LN0->getAlignment());
4847 CombineTo(N, ExtLoad);
4848 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4849 N0.getValueType(), ExtLoad);
4850 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4851 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4853 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4857 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4858 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4859 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4860 if (N0.getOpcode() == ISD::LOAD &&
4861 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4863 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4864 EVT MemVT = LN0->getMemoryVT();
4865 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4866 VT, LN0->getChain(), LN0->getBasePtr(),
4867 LN0->getPointerInfo(), MemVT,
4868 LN0->isVolatile(), LN0->isNonTemporal(),
4869 LN0->getAlignment());
4870 CombineTo(N, ExtLoad);
4871 CombineTo(N0.getNode(),
4872 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4873 N0.getValueType(), ExtLoad),
4874 ExtLoad.getValue(1));
4875 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4878 if (N0.getOpcode() == ISD::SETCC) {
4879 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4880 // Only do this before legalize for now.
4881 if (VT.isVector() && !LegalOperations) {
4882 EVT N0VT = N0.getOperand(0).getValueType();
4883 // We know that the # elements of the results is the same as the
4884 // # elements of the compare (and the # elements of the compare result
4885 // for that matter). Check to see that they are the same size. If so,
4886 // we know that the element size of the sext'd result matches the
4887 // element size of the compare operands.
4888 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4889 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4891 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4892 // If the desired elements are smaller or larger than the source
4893 // elements we can use a matching integer vector type and then
4894 // truncate/sign extend
4896 EVT MatchingElementType =
4897 EVT::getIntegerVT(*DAG.getContext(),
4898 N0VT.getScalarType().getSizeInBits());
4899 EVT MatchingVectorType =
4900 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4901 N0VT.getVectorNumElements());
4903 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4905 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4906 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4910 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4912 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4913 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4914 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4922 /// GetDemandedBits - See if the specified operand can be simplified with the
4923 /// knowledge that only the bits specified by Mask are used. If so, return the
4924 /// simpler operand, otherwise return a null SDValue.
4925 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4926 switch (V.getOpcode()) {
4928 case ISD::Constant: {
4929 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4930 assert(CV != 0 && "Const value should be ConstSDNode.");
4931 const APInt &CVal = CV->getAPIntValue();
4932 APInt NewVal = CVal & Mask;
4933 if (NewVal != CVal) {
4934 return DAG.getConstant(NewVal, V.getValueType());
4940 // If the LHS or RHS don't contribute bits to the or, drop them.
4941 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4942 return V.getOperand(1);
4943 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4944 return V.getOperand(0);
4947 // Only look at single-use SRLs.
4948 if (!V.getNode()->hasOneUse())
4950 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4951 // See if we can recursively simplify the LHS.
4952 unsigned Amt = RHSC->getZExtValue();
4954 // Watch out for shift count overflow though.
4955 if (Amt >= Mask.getBitWidth()) break;
4956 APInt NewMask = Mask << Amt;
4957 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4958 if (SimplifyLHS.getNode())
4959 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4960 SimplifyLHS, V.getOperand(1));
4966 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4967 /// bits and then truncated to a narrower type and where N is a multiple
4968 /// of number of bits of the narrower type, transform it to a narrower load
4969 /// from address + N / num of bits of new type. If the result is to be
4970 /// extended, also fold the extension to form a extending load.
4971 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4972 unsigned Opc = N->getOpcode();
4974 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4975 SDValue N0 = N->getOperand(0);
4976 EVT VT = N->getValueType(0);
4979 // This transformation isn't valid for vector loads.
4983 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4985 if (Opc == ISD::SIGN_EXTEND_INREG) {
4986 ExtType = ISD::SEXTLOAD;
4987 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4988 } else if (Opc == ISD::SRL) {
4989 // Another special-case: SRL is basically zero-extending a narrower value.
4990 ExtType = ISD::ZEXTLOAD;
4992 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4993 if (!N01) return SDValue();
4994 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4995 VT.getSizeInBits() - N01->getZExtValue());
4997 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5000 unsigned EVTBits = ExtVT.getSizeInBits();
5002 // Do not generate loads of non-round integer types since these can
5003 // be expensive (and would be wrong if the type is not byte sized).
5004 if (!ExtVT.isRound())
5008 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5009 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5010 ShAmt = N01->getZExtValue();
5011 // Is the shift amount a multiple of size of VT?
5012 if ((ShAmt & (EVTBits-1)) == 0) {
5013 N0 = N0.getOperand(0);
5014 // Is the load width a multiple of size of VT?
5015 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5019 // At this point, we must have a load or else we can't do the transform.
5020 if (!isa<LoadSDNode>(N0)) return SDValue();
5022 // If the shift amount is larger than the input type then we're not
5023 // accessing any of the loaded bytes. If the load was a zextload/extload
5024 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5025 // If the load was a sextload then the result is a splat of the sign bit
5026 // of the extended byte. This is not worth optimizing for.
5027 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5032 // If the load is shifted left (and the result isn't shifted back right),
5033 // we can fold the truncate through the shift.
5034 unsigned ShLeftAmt = 0;
5035 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5036 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5037 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5038 ShLeftAmt = N01->getZExtValue();
5039 N0 = N0.getOperand(0);
5043 // If we haven't found a load, we can't narrow it. Don't transform one with
5044 // multiple uses, this would require adding a new load.
5045 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
5046 // Don't change the width of a volatile load.
5047 cast<LoadSDNode>(N0)->isVolatile())
5050 // Verify that we are actually reducing a load width here.
5051 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5054 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5055 EVT PtrType = N0.getOperand(1).getValueType();
5057 if (PtrType == MVT::Untyped || PtrType.isExtended())
5058 // It's not possible to generate a constant of extended or untyped type.
5061 // For big endian targets, we need to adjust the offset to the pointer to
5062 // load the correct bytes.
5063 if (TLI.isBigEndian()) {
5064 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5065 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5066 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5069 uint64_t PtrOff = ShAmt / 8;
5070 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5071 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5072 PtrType, LN0->getBasePtr(),
5073 DAG.getConstant(PtrOff, PtrType));
5074 AddToWorkList(NewPtr.getNode());
5077 if (ExtType == ISD::NON_EXTLOAD)
5078 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5079 LN0->getPointerInfo().getWithOffset(PtrOff),
5080 LN0->isVolatile(), LN0->isNonTemporal(),
5081 LN0->isInvariant(), NewAlign);
5083 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5084 LN0->getPointerInfo().getWithOffset(PtrOff),
5085 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5088 // Replace the old load's chain with the new load's chain.
5089 WorkListRemover DeadNodes(*this);
5090 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5092 // Shift the result left, if we've swallowed a left shift.
5093 SDValue Result = Load;
5094 if (ShLeftAmt != 0) {
5095 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5096 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5098 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5099 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5102 // Return the new loaded value.
5106 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5107 SDValue N0 = N->getOperand(0);
5108 SDValue N1 = N->getOperand(1);
5109 EVT VT = N->getValueType(0);
5110 EVT EVT = cast<VTSDNode>(N1)->getVT();
5111 unsigned VTBits = VT.getScalarType().getSizeInBits();
5112 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5114 // fold (sext_in_reg c1) -> c1
5115 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5116 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5118 // If the input is already sign extended, just drop the extension.
5119 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5122 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5123 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5124 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5125 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5126 N0.getOperand(0), N1);
5129 // fold (sext_in_reg (sext x)) -> (sext x)
5130 // fold (sext_in_reg (aext x)) -> (sext x)
5131 // if x is small enough.
5132 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5133 SDValue N00 = N0.getOperand(0);
5134 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5135 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5136 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5139 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5140 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5141 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5143 // fold operands of sext_in_reg based on knowledge that the top bits are not
5145 if (SimplifyDemandedBits(SDValue(N, 0)))
5146 return SDValue(N, 0);
5148 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5149 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5150 SDValue NarrowLoad = ReduceLoadWidth(N);
5151 if (NarrowLoad.getNode())
5154 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5155 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5156 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5157 if (N0.getOpcode() == ISD::SRL) {
5158 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5159 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5160 // We can turn this into an SRA iff the input to the SRL is already sign
5162 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5163 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5164 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5165 N0.getOperand(0), N0.getOperand(1));
5169 // fold (sext_inreg (extload x)) -> (sextload x)
5170 if (ISD::isEXTLoad(N0.getNode()) &&
5171 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5172 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5173 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5174 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5175 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5176 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5178 LN0->getBasePtr(), LN0->getPointerInfo(),
5180 LN0->isVolatile(), LN0->isNonTemporal(),
5181 LN0->getAlignment());
5182 CombineTo(N, ExtLoad);
5183 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5184 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5186 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5187 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5189 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5190 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5191 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5192 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5193 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5195 LN0->getBasePtr(), LN0->getPointerInfo(),
5197 LN0->isVolatile(), LN0->isNonTemporal(),
5198 LN0->getAlignment());
5199 CombineTo(N, ExtLoad);
5200 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5201 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5204 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5205 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5206 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5207 N0.getOperand(1), false);
5208 if (BSwap.getNode() != 0)
5209 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5216 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5217 SDValue N0 = N->getOperand(0);
5218 EVT VT = N->getValueType(0);
5219 bool isLE = TLI.isLittleEndian();
5222 if (N0.getValueType() == N->getValueType(0))
5224 // fold (truncate c1) -> c1
5225 if (isa<ConstantSDNode>(N0))
5226 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5227 // fold (truncate (truncate x)) -> (truncate x)
5228 if (N0.getOpcode() == ISD::TRUNCATE)
5229 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5230 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5231 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5232 N0.getOpcode() == ISD::SIGN_EXTEND ||
5233 N0.getOpcode() == ISD::ANY_EXTEND) {
5234 if (N0.getOperand(0).getValueType().bitsLT(VT))
5235 // if the source is smaller than the dest, we still need an extend
5236 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5238 else if (N0.getOperand(0).getValueType().bitsGT(VT))
5239 // if the source is larger than the dest, than we just need the truncate
5240 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5242 // if the source and dest are the same type, we can drop both the extend
5243 // and the truncate.
5244 return N0.getOperand(0);
5247 // Fold extract-and-trunc into a narrow extract. For example:
5248 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5249 // i32 y = TRUNCATE(i64 x)
5251 // v16i8 b = BITCAST (v2i64 val)
5252 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5254 // Note: We only run this optimization after type legalization (which often
5255 // creates this pattern) and before operation legalization after which
5256 // we need to be more careful about the vector instructions that we generate.
5257 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5258 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5260 EVT VecTy = N0.getOperand(0).getValueType();
5261 EVT ExTy = N0.getValueType();
5262 EVT TrTy = N->getValueType(0);
5264 unsigned NumElem = VecTy.getVectorNumElements();
5265 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5267 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5268 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5270 SDValue EltNo = N0->getOperand(1);
5271 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5272 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5273 EVT IndexTy = N0->getOperand(1).getValueType();
5274 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5276 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5277 NVT, N0.getOperand(0));
5279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5280 N->getDebugLoc(), TrTy, V,
5281 DAG.getConstant(Index, IndexTy));
5285 // See if we can simplify the input to this truncate through knowledge that
5286 // only the low bits are being used.
5287 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5288 // Currently we only perform this optimization on scalars because vectors
5289 // may have different active low bits.
5290 if (!VT.isVector()) {
5292 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5293 VT.getSizeInBits()));
5294 if (Shorter.getNode())
5295 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5297 // fold (truncate (load x)) -> (smaller load x)
5298 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5299 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5300 SDValue Reduced = ReduceLoadWidth(N);
5301 if (Reduced.getNode())
5305 // Simplify the operands using demanded-bits information.
5306 if (!VT.isVector() &&
5307 SimplifyDemandedBits(SDValue(N, 0)))
5308 return SDValue(N, 0);
5313 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5314 SDValue Elt = N->getOperand(i);
5315 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5316 return Elt.getNode();
5317 return Elt.getOperand(Elt.getResNo()).getNode();
5320 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5321 /// if load locations are consecutive.
5322 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5323 assert(N->getOpcode() == ISD::BUILD_PAIR);
5325 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5326 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5327 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5328 LD1->getPointerInfo().getAddrSpace() !=
5329 LD2->getPointerInfo().getAddrSpace())
5331 EVT LD1VT = LD1->getValueType(0);
5333 if (ISD::isNON_EXTLoad(LD2) &&
5335 // If both are volatile this would reduce the number of volatile loads.
5336 // If one is volatile it might be ok, but play conservative and bail out.
5337 !LD1->isVolatile() &&
5338 !LD2->isVolatile() &&
5339 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5340 unsigned Align = LD1->getAlignment();
5341 unsigned NewAlign = TLI.getTargetData()->
5342 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5344 if (NewAlign <= Align &&
5345 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5346 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5347 LD1->getBasePtr(), LD1->getPointerInfo(),
5348 false, false, false, Align);
5354 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5355 SDValue N0 = N->getOperand(0);
5356 EVT VT = N->getValueType(0);
5358 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5359 // Only do this before legalize, since afterward the target may be depending
5360 // on the bitconvert.
5361 // First check to see if this is all constant.
5363 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5365 bool isSimple = true;
5366 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5367 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5368 N0.getOperand(i).getOpcode() != ISD::Constant &&
5369 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5374 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5375 assert(!DestEltVT.isVector() &&
5376 "Element type of vector ValueType must not be vector!");
5378 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5381 // If the input is a constant, let getNode fold it.
5382 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5383 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5384 if (Res.getNode() != N) {
5385 if (!LegalOperations ||
5386 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5389 // Folding it resulted in an illegal node, and it's too late to
5390 // do that. Clean up the old node and forego the transformation.
5391 // Ideally this won't happen very often, because instcombine
5392 // and the earlier dagcombine runs (where illegal nodes are
5393 // permitted) should have folded most of them already.
5394 DAG.DeleteNode(Res.getNode());
5398 // (conv (conv x, t1), t2) -> (conv x, t2)
5399 if (N0.getOpcode() == ISD::BITCAST)
5400 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5403 // fold (conv (load x)) -> (load (conv*)x)
5404 // If the resultant load doesn't need a higher alignment than the original!
5405 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5406 // Do not change the width of a volatile load.
5407 !cast<LoadSDNode>(N0)->isVolatile() &&
5408 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5409 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5410 unsigned Align = TLI.getTargetData()->
5411 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5412 unsigned OrigAlign = LN0->getAlignment();
5414 if (Align <= OrigAlign) {
5415 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5416 LN0->getBasePtr(), LN0->getPointerInfo(),
5417 LN0->isVolatile(), LN0->isNonTemporal(),
5418 LN0->isInvariant(), OrigAlign);
5420 CombineTo(N0.getNode(),
5421 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5422 N0.getValueType(), Load),
5428 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5429 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5430 // This often reduces constant pool loads.
5431 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5432 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5433 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5434 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5436 AddToWorkList(NewConv.getNode());
5438 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5439 if (N0.getOpcode() == ISD::FNEG)
5440 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5441 NewConv, DAG.getConstant(SignBit, VT));
5442 assert(N0.getOpcode() == ISD::FABS);
5443 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5444 NewConv, DAG.getConstant(~SignBit, VT));
5447 // fold (bitconvert (fcopysign cst, x)) ->
5448 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5449 // Note that we don't handle (copysign x, cst) because this can always be
5450 // folded to an fneg or fabs.
5451 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5452 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5453 VT.isInteger() && !VT.isVector()) {
5454 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5455 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5456 if (isTypeLegal(IntXVT)) {
5457 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5458 IntXVT, N0.getOperand(1));
5459 AddToWorkList(X.getNode());
5461 // If X has a different width than the result/lhs, sext it or truncate it.
5462 unsigned VTWidth = VT.getSizeInBits();
5463 if (OrigXWidth < VTWidth) {
5464 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5465 AddToWorkList(X.getNode());
5466 } else if (OrigXWidth > VTWidth) {
5467 // To get the sign bit in the right place, we have to shift it right
5468 // before truncating.
5469 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5470 X.getValueType(), X,
5471 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5472 AddToWorkList(X.getNode());
5473 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5474 AddToWorkList(X.getNode());
5477 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5478 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5479 X, DAG.getConstant(SignBit, VT));
5480 AddToWorkList(X.getNode());
5482 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5483 VT, N0.getOperand(0));
5484 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5485 Cst, DAG.getConstant(~SignBit, VT));
5486 AddToWorkList(Cst.getNode());
5488 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5492 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5493 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5494 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5495 if (CombineLD.getNode())
5502 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5503 EVT VT = N->getValueType(0);
5504 return CombineConsecutiveLoads(N, VT);
5507 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5508 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5509 /// destination element value type.
5510 SDValue DAGCombiner::
5511 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5512 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5514 // If this is already the right type, we're done.
5515 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5517 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5518 unsigned DstBitSize = DstEltVT.getSizeInBits();
5520 // If this is a conversion of N elements of one type to N elements of another
5521 // type, convert each element. This handles FP<->INT cases.
5522 if (SrcBitSize == DstBitSize) {
5523 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5524 BV->getValueType(0).getVectorNumElements());
5526 // Due to the FP element handling below calling this routine recursively,
5527 // we can end up with a scalar-to-vector node here.
5528 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5529 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5530 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5531 DstEltVT, BV->getOperand(0)));
5533 SmallVector<SDValue, 8> Ops;
5534 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5535 SDValue Op = BV->getOperand(i);
5536 // If the vector element type is not legal, the BUILD_VECTOR operands
5537 // are promoted and implicitly truncated. Make that explicit here.
5538 if (Op.getValueType() != SrcEltVT)
5539 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5540 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5542 AddToWorkList(Ops.back().getNode());
5544 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5545 &Ops[0], Ops.size());
5548 // Otherwise, we're growing or shrinking the elements. To avoid having to
5549 // handle annoying details of growing/shrinking FP values, we convert them to
5551 if (SrcEltVT.isFloatingPoint()) {
5552 // Convert the input float vector to a int vector where the elements are the
5554 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5555 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5556 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5560 // Now we know the input is an integer vector. If the output is a FP type,
5561 // convert to integer first, then to FP of the right size.
5562 if (DstEltVT.isFloatingPoint()) {
5563 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5564 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5565 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5567 // Next, convert to FP elements of the same size.
5568 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5571 // Okay, we know the src/dst types are both integers of differing types.
5572 // Handling growing first.
5573 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5574 if (SrcBitSize < DstBitSize) {
5575 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5577 SmallVector<SDValue, 8> Ops;
5578 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5579 i += NumInputsPerOutput) {
5580 bool isLE = TLI.isLittleEndian();
5581 APInt NewBits = APInt(DstBitSize, 0);
5582 bool EltIsUndef = true;
5583 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5584 // Shift the previously computed bits over.
5585 NewBits <<= SrcBitSize;
5586 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5587 if (Op.getOpcode() == ISD::UNDEF) continue;
5590 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5591 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5595 Ops.push_back(DAG.getUNDEF(DstEltVT));
5597 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5600 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5601 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5602 &Ops[0], Ops.size());
5605 // Finally, this must be the case where we are shrinking elements: each input
5606 // turns into multiple outputs.
5607 bool isS2V = ISD::isScalarToVector(BV);
5608 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5609 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5610 NumOutputsPerInput*BV->getNumOperands());
5611 SmallVector<SDValue, 8> Ops;
5613 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5614 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5615 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5616 Ops.push_back(DAG.getUNDEF(DstEltVT));
5620 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5621 getAPIntValue().zextOrTrunc(SrcBitSize);
5623 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5624 APInt ThisVal = OpVal.trunc(DstBitSize);
5625 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5626 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5627 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5628 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5630 OpVal = OpVal.lshr(DstBitSize);
5633 // For big endian targets, swap the order of the pieces of each element.
5634 if (TLI.isBigEndian())
5635 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5638 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5639 &Ops[0], Ops.size());
5642 SDValue DAGCombiner::visitFADD(SDNode *N) {
5643 SDValue N0 = N->getOperand(0);
5644 SDValue N1 = N->getOperand(1);
5645 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5646 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5647 EVT VT = N->getValueType(0);
5650 if (VT.isVector()) {
5651 SDValue FoldedVOp = SimplifyVBinOp(N);
5652 if (FoldedVOp.getNode()) return FoldedVOp;
5655 // fold (fadd c1, c2) -> c1 + c2
5656 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5657 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5658 // canonicalize constant to RHS
5659 if (N0CFP && !N1CFP)
5660 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5661 // fold (fadd A, 0) -> A
5662 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5663 N1CFP->getValueAPF().isZero())
5665 // fold (fadd A, (fneg B)) -> (fsub A, B)
5666 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5667 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5668 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5669 GetNegatedExpression(N1, DAG, LegalOperations));
5670 // fold (fadd (fneg A), B) -> (fsub B, A)
5671 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5672 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5673 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5674 GetNegatedExpression(N0, DAG, LegalOperations));
5676 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5677 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5678 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5679 isa<ConstantFPSDNode>(N0.getOperand(1)))
5680 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5681 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5682 N0.getOperand(1), N1));
5684 // FADD -> FMA combines:
5685 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5686 DAG.getTarget().Options.UnsafeFPMath) &&
5687 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5688 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5690 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5691 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5692 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5693 N0.getOperand(0), N0.getOperand(1), N1);
5696 // fold (fadd x, (fmul y, z)) -> (fma x, y, z)
5697 // Note: Commutes FADD operands.
5698 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5699 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5700 N1.getOperand(0), N1.getOperand(1), N0);
5707 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5708 SDValue N0 = N->getOperand(0);
5709 SDValue N1 = N->getOperand(1);
5710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5711 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5712 EVT VT = N->getValueType(0);
5713 DebugLoc dl = N->getDebugLoc();
5716 if (VT.isVector()) {
5717 SDValue FoldedVOp = SimplifyVBinOp(N);
5718 if (FoldedVOp.getNode()) return FoldedVOp;
5721 // fold (fsub c1, c2) -> c1-c2
5722 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5723 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5724 // fold (fsub A, 0) -> A
5725 if (DAG.getTarget().Options.UnsafeFPMath &&
5726 N1CFP && N1CFP->getValueAPF().isZero())
5728 // fold (fsub 0, B) -> -B
5729 if (DAG.getTarget().Options.UnsafeFPMath &&
5730 N0CFP && N0CFP->getValueAPF().isZero()) {
5731 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5732 return GetNegatedExpression(N1, DAG, LegalOperations);
5733 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5734 return DAG.getNode(ISD::FNEG, dl, VT, N1);
5736 // fold (fsub A, (fneg B)) -> (fadd A, B)
5737 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5738 return DAG.getNode(ISD::FADD, dl, VT, N0,
5739 GetNegatedExpression(N1, DAG, LegalOperations));
5741 // If 'unsafe math' is enabled, fold
5742 // (fsub x, x) -> 0.0 &
5743 // (fsub x, (fadd x, y)) -> (fneg y) &
5744 // (fsub x, (fadd y, x)) -> (fneg y)
5745 if (DAG.getTarget().Options.UnsafeFPMath) {
5747 return DAG.getConstantFP(0.0f, VT);
5749 if (N1.getOpcode() == ISD::FADD) {
5750 SDValue N10 = N1->getOperand(0);
5751 SDValue N11 = N1->getOperand(1);
5753 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5754 &DAG.getTarget().Options))
5755 return GetNegatedExpression(N11, DAG, LegalOperations);
5756 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5757 &DAG.getTarget().Options))
5758 return GetNegatedExpression(N10, DAG, LegalOperations);
5762 // FSUB -> FMA combines:
5763 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5764 DAG.getTarget().Options.UnsafeFPMath) &&
5765 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5766 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5768 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
5769 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5770 return DAG.getNode(ISD::FMA, dl, VT,
5771 N0.getOperand(0), N0.getOperand(1),
5772 DAG.getNode(ISD::FNEG, dl, VT, N1));
5775 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
5776 // Note: Commutes FSUB operands.
5777 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5778 return DAG.getNode(ISD::FMA, dl, VT,
5779 DAG.getNode(ISD::FNEG, dl, VT,
5781 N1.getOperand(1), N0);
5784 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
5785 if (N0.getOpcode() == ISD::FNEG &&
5786 N0.getOperand(0).getOpcode() == ISD::FMUL &&
5787 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
5788 SDValue N00 = N0.getOperand(0).getOperand(0);
5789 SDValue N01 = N0.getOperand(0).getOperand(1);
5790 return DAG.getNode(ISD::FMA, dl, VT,
5791 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
5792 DAG.getNode(ISD::FNEG, dl, VT, N1));
5799 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5800 SDValue N0 = N->getOperand(0);
5801 SDValue N1 = N->getOperand(1);
5802 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5803 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5804 EVT VT = N->getValueType(0);
5805 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5808 if (VT.isVector()) {
5809 SDValue FoldedVOp = SimplifyVBinOp(N);
5810 if (FoldedVOp.getNode()) return FoldedVOp;
5813 // fold (fmul c1, c2) -> c1*c2
5814 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5815 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5816 // canonicalize constant to RHS
5817 if (N0CFP && !N1CFP)
5818 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5819 // fold (fmul A, 0) -> 0
5820 if (DAG.getTarget().Options.UnsafeFPMath &&
5821 N1CFP && N1CFP->getValueAPF().isZero())
5823 // fold (fmul A, 0) -> 0, vector edition.
5824 if (DAG.getTarget().Options.UnsafeFPMath &&
5825 ISD::isBuildVectorAllZeros(N1.getNode()))
5827 // fold (fmul A, 1.0) -> A
5828 if (N1CFP && N1CFP->isExactlyValue(1.0))
5830 // fold (fmul X, 2.0) -> (fadd X, X)
5831 if (N1CFP && N1CFP->isExactlyValue(+2.0))
5832 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5833 // fold (fmul X, -1.0) -> (fneg X)
5834 if (N1CFP && N1CFP->isExactlyValue(-1.0))
5835 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5836 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5838 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5839 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5840 &DAG.getTarget().Options)) {
5841 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5842 &DAG.getTarget().Options)) {
5843 // Both can be negated for free, check to see if at least one is cheaper
5845 if (LHSNeg == 2 || RHSNeg == 2)
5846 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5847 GetNegatedExpression(N0, DAG, LegalOperations),
5848 GetNegatedExpression(N1, DAG, LegalOperations));
5852 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5853 if (DAG.getTarget().Options.UnsafeFPMath &&
5854 N1CFP && N0.getOpcode() == ISD::FMUL &&
5855 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5856 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5857 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5858 N0.getOperand(1), N1));
5863 SDValue DAGCombiner::visitFMA(SDNode *N) {
5864 SDValue N0 = N->getOperand(0);
5865 SDValue N1 = N->getOperand(1);
5866 SDValue N2 = N->getOperand(2);
5867 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5868 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5869 EVT VT = N->getValueType(0);
5871 if (N0CFP && N0CFP->isExactlyValue(1.0))
5872 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
5873 if (N1CFP && N1CFP->isExactlyValue(1.0))
5874 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
5876 // Canonicalize (fma c, x, y) -> (fma x, c, y)
5877 if (N0CFP && !N1CFP)
5878 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
5883 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5884 SDValue N0 = N->getOperand(0);
5885 SDValue N1 = N->getOperand(1);
5886 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5887 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5888 EVT VT = N->getValueType(0);
5889 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5892 if (VT.isVector()) {
5893 SDValue FoldedVOp = SimplifyVBinOp(N);
5894 if (FoldedVOp.getNode()) return FoldedVOp;
5897 // fold (fdiv c1, c2) -> c1/c2
5898 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5899 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5901 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
5902 if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
5903 // Compute the reciprocal 1.0 / c2.
5904 APFloat N1APF = N1CFP->getValueAPF();
5905 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
5906 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
5907 // Only do the transform if the reciprocal is a legal fp immediate that
5908 // isn't too nasty (eg NaN, denormal, ...).
5909 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
5910 (!LegalOperations ||
5911 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
5912 // backend)... we should handle this gracefully after Legalize.
5913 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
5914 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
5915 TLI.isFPImmLegal(Recip, VT)))
5916 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
5917 DAG.getConstantFP(Recip, VT));
5920 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5921 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5922 &DAG.getTarget().Options)) {
5923 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5924 &DAG.getTarget().Options)) {
5925 // Both can be negated for free, check to see if at least one is cheaper
5927 if (LHSNeg == 2 || RHSNeg == 2)
5928 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5929 GetNegatedExpression(N0, DAG, LegalOperations),
5930 GetNegatedExpression(N1, DAG, LegalOperations));
5937 SDValue DAGCombiner::visitFREM(SDNode *N) {
5938 SDValue N0 = N->getOperand(0);
5939 SDValue N1 = N->getOperand(1);
5940 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5941 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5942 EVT VT = N->getValueType(0);
5944 // fold (frem c1, c2) -> fmod(c1,c2)
5945 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5946 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5951 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5952 SDValue N0 = N->getOperand(0);
5953 SDValue N1 = N->getOperand(1);
5954 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5955 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5956 EVT VT = N->getValueType(0);
5958 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5959 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5962 const APFloat& V = N1CFP->getValueAPF();
5963 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5964 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5965 if (!V.isNegative()) {
5966 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5967 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5969 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5970 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5971 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5975 // copysign(fabs(x), y) -> copysign(x, y)
5976 // copysign(fneg(x), y) -> copysign(x, y)
5977 // copysign(copysign(x,z), y) -> copysign(x, y)
5978 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5979 N0.getOpcode() == ISD::FCOPYSIGN)
5980 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5981 N0.getOperand(0), N1);
5983 // copysign(x, abs(y)) -> abs(x)
5984 if (N1.getOpcode() == ISD::FABS)
5985 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5987 // copysign(x, copysign(y,z)) -> copysign(x, z)
5988 if (N1.getOpcode() == ISD::FCOPYSIGN)
5989 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5990 N0, N1.getOperand(1));
5992 // copysign(x, fp_extend(y)) -> copysign(x, y)
5993 // copysign(x, fp_round(y)) -> copysign(x, y)
5994 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5995 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5996 N0, N1.getOperand(0));
6001 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6002 SDValue N0 = N->getOperand(0);
6003 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6004 EVT VT = N->getValueType(0);
6005 EVT OpVT = N0.getValueType();
6007 // fold (sint_to_fp c1) -> c1fp
6008 if (N0C && OpVT != MVT::ppcf128 &&
6009 // ...but only if the target supports immediate floating-point values
6010 (!LegalOperations ||
6011 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6012 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6014 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6015 // but UINT_TO_FP is legal on this target, try to convert.
6016 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6017 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6018 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6019 if (DAG.SignBitIsZero(N0))
6020 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6023 // The next optimizations are desireable only if SELECT_CC can be lowered.
6024 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6025 // having to say they don't support SELECT_CC on every type the DAG knows
6026 // about, since there is no way to mark an opcode illegal at all value types
6027 // (See also visitSELECT)
6028 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6029 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6030 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6032 (!LegalOperations ||
6033 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6035 { N0.getOperand(0), N0.getOperand(1),
6036 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6038 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6041 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6042 // (select_cc x, y, 1.0, 0.0,, cc)
6043 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6044 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6045 (!LegalOperations ||
6046 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6048 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6049 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6050 N0.getOperand(0).getOperand(2) };
6051 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6058 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6059 SDValue N0 = N->getOperand(0);
6060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6061 EVT VT = N->getValueType(0);
6062 EVT OpVT = N0.getValueType();
6064 // fold (uint_to_fp c1) -> c1fp
6065 if (N0C && OpVT != MVT::ppcf128 &&
6066 // ...but only if the target supports immediate floating-point values
6067 (!LegalOperations ||
6068 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6069 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6071 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6072 // but SINT_TO_FP is legal on this target, try to convert.
6073 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6074 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6075 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6076 if (DAG.SignBitIsZero(N0))
6077 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6080 // The next optimizations are desireable only if SELECT_CC can be lowered.
6081 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6082 // having to say they don't support SELECT_CC on every type the DAG knows
6083 // about, since there is no way to mark an opcode illegal at all value types
6084 // (See also visitSELECT)
6085 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6086 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6088 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6089 (!LegalOperations ||
6090 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6092 { N0.getOperand(0), N0.getOperand(1),
6093 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6095 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6102 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6103 SDValue N0 = N->getOperand(0);
6104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6105 EVT VT = N->getValueType(0);
6107 // fold (fp_to_sint c1fp) -> c1
6109 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6114 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6115 SDValue N0 = N->getOperand(0);
6116 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6117 EVT VT = N->getValueType(0);
6119 // fold (fp_to_uint c1fp) -> c1
6120 if (N0CFP && VT != MVT::ppcf128)
6121 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6126 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6127 SDValue N0 = N->getOperand(0);
6128 SDValue N1 = N->getOperand(1);
6129 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6130 EVT VT = N->getValueType(0);
6132 // fold (fp_round c1fp) -> c1fp
6133 if (N0CFP && N0.getValueType() != MVT::ppcf128)
6134 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6136 // fold (fp_round (fp_extend x)) -> x
6137 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6138 return N0.getOperand(0);
6140 // fold (fp_round (fp_round x)) -> (fp_round x)
6141 if (N0.getOpcode() == ISD::FP_ROUND) {
6142 // This is a value preserving truncation if both round's are.
6143 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6144 N0.getNode()->getConstantOperandVal(1) == 1;
6145 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6146 DAG.getIntPtrConstant(IsTrunc));
6149 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6150 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6151 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6152 N0.getOperand(0), N1);
6153 AddToWorkList(Tmp.getNode());
6154 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6155 Tmp, N0.getOperand(1));
6161 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6162 SDValue N0 = N->getOperand(0);
6163 EVT VT = N->getValueType(0);
6164 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6165 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6167 // fold (fp_round_inreg c1fp) -> c1fp
6168 if (N0CFP && isTypeLegal(EVT)) {
6169 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6170 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6176 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6177 SDValue N0 = N->getOperand(0);
6178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6179 EVT VT = N->getValueType(0);
6181 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6182 if (N->hasOneUse() &&
6183 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6186 // fold (fp_extend c1fp) -> c1fp
6187 if (N0CFP && VT != MVT::ppcf128)
6188 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6190 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6192 if (N0.getOpcode() == ISD::FP_ROUND
6193 && N0.getNode()->getConstantOperandVal(1) == 1) {
6194 SDValue In = N0.getOperand(0);
6195 if (In.getValueType() == VT) return In;
6196 if (VT.bitsLT(In.getValueType()))
6197 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6198 In, N0.getOperand(1));
6199 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6202 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6203 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6204 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6205 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6206 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6207 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6209 LN0->getBasePtr(), LN0->getPointerInfo(),
6211 LN0->isVolatile(), LN0->isNonTemporal(),
6212 LN0->getAlignment());
6213 CombineTo(N, ExtLoad);
6214 CombineTo(N0.getNode(),
6215 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6216 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6217 ExtLoad.getValue(1));
6218 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6224 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6225 SDValue N0 = N->getOperand(0);
6226 EVT VT = N->getValueType(0);
6228 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6229 &DAG.getTarget().Options))
6230 return GetNegatedExpression(N0, DAG, LegalOperations);
6232 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6233 // constant pool values.
6234 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6236 N0.getNode()->hasOneUse() &&
6237 N0.getOperand(0).getValueType().isInteger()) {
6238 SDValue Int = N0.getOperand(0);
6239 EVT IntVT = Int.getValueType();
6240 if (IntVT.isInteger() && !IntVT.isVector()) {
6241 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6242 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6243 AddToWorkList(Int.getNode());
6244 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6252 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6253 SDValue N0 = N->getOperand(0);
6254 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6255 EVT VT = N->getValueType(0);
6257 // fold (fceil c1) -> fceil(c1)
6258 if (N0CFP && VT != MVT::ppcf128)
6259 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6264 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6265 SDValue N0 = N->getOperand(0);
6266 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6267 EVT VT = N->getValueType(0);
6269 // fold (ftrunc c1) -> ftrunc(c1)
6270 if (N0CFP && VT != MVT::ppcf128)
6271 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6276 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6277 SDValue N0 = N->getOperand(0);
6278 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6279 EVT VT = N->getValueType(0);
6281 // fold (ffloor c1) -> ffloor(c1)
6282 if (N0CFP && VT != MVT::ppcf128)
6283 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6288 SDValue DAGCombiner::visitFABS(SDNode *N) {
6289 SDValue N0 = N->getOperand(0);
6290 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6291 EVT VT = N->getValueType(0);
6293 // fold (fabs c1) -> fabs(c1)
6294 if (N0CFP && VT != MVT::ppcf128)
6295 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6296 // fold (fabs (fabs x)) -> (fabs x)
6297 if (N0.getOpcode() == ISD::FABS)
6298 return N->getOperand(0);
6299 // fold (fabs (fneg x)) -> (fabs x)
6300 // fold (fabs (fcopysign x, y)) -> (fabs x)
6301 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6302 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6304 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6305 // constant pool values.
6306 if (!TLI.isFAbsFree(VT) &&
6307 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6308 N0.getOperand(0).getValueType().isInteger() &&
6309 !N0.getOperand(0).getValueType().isVector()) {
6310 SDValue Int = N0.getOperand(0);
6311 EVT IntVT = Int.getValueType();
6312 if (IntVT.isInteger() && !IntVT.isVector()) {
6313 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6314 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6315 AddToWorkList(Int.getNode());
6316 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6317 N->getValueType(0), Int);
6324 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6325 SDValue Chain = N->getOperand(0);
6326 SDValue N1 = N->getOperand(1);
6327 SDValue N2 = N->getOperand(2);
6329 // If N is a constant we could fold this into a fallthrough or unconditional
6330 // branch. However that doesn't happen very often in normal code, because
6331 // Instcombine/SimplifyCFG should have handled the available opportunities.
6332 // If we did this folding here, it would be necessary to update the
6333 // MachineBasicBlock CFG, which is awkward.
6335 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6337 if (N1.getOpcode() == ISD::SETCC &&
6338 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6339 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6340 Chain, N1.getOperand(2),
6341 N1.getOperand(0), N1.getOperand(1), N2);
6344 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6345 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6346 (N1.getOperand(0).hasOneUse() &&
6347 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6349 if (N1.getOpcode() == ISD::TRUNCATE) {
6350 // Look pass the truncate.
6351 Trunc = N1.getNode();
6352 N1 = N1.getOperand(0);
6355 // Match this pattern so that we can generate simpler code:
6358 // %b = and i32 %a, 2
6359 // %c = srl i32 %b, 1
6360 // brcond i32 %c ...
6365 // %b = and i32 %a, 2
6366 // %c = setcc eq %b, 0
6369 // This applies only when the AND constant value has one bit set and the
6370 // SRL constant is equal to the log2 of the AND constant. The back-end is
6371 // smart enough to convert the result into a TEST/JMP sequence.
6372 SDValue Op0 = N1.getOperand(0);
6373 SDValue Op1 = N1.getOperand(1);
6375 if (Op0.getOpcode() == ISD::AND &&
6376 Op1.getOpcode() == ISD::Constant) {
6377 SDValue AndOp1 = Op0.getOperand(1);
6379 if (AndOp1.getOpcode() == ISD::Constant) {
6380 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6382 if (AndConst.isPowerOf2() &&
6383 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6385 DAG.getSetCC(N->getDebugLoc(),
6386 TLI.getSetCCResultType(Op0.getValueType()),
6387 Op0, DAG.getConstant(0, Op0.getValueType()),
6390 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6391 MVT::Other, Chain, SetCC, N2);
6392 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6393 // will convert it back to (X & C1) >> C2.
6394 CombineTo(N, NewBRCond, false);
6395 // Truncate is dead.
6397 removeFromWorkList(Trunc);
6398 DAG.DeleteNode(Trunc);
6400 // Replace the uses of SRL with SETCC
6401 WorkListRemover DeadNodes(*this);
6402 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6403 removeFromWorkList(N1.getNode());
6404 DAG.DeleteNode(N1.getNode());
6405 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6411 // Restore N1 if the above transformation doesn't match.
6412 N1 = N->getOperand(1);
6415 // Transform br(xor(x, y)) -> br(x != y)
6416 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6417 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6418 SDNode *TheXor = N1.getNode();
6419 SDValue Op0 = TheXor->getOperand(0);
6420 SDValue Op1 = TheXor->getOperand(1);
6421 if (Op0.getOpcode() == Op1.getOpcode()) {
6422 // Avoid missing important xor optimizations.
6423 SDValue Tmp = visitXOR(TheXor);
6424 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6425 DEBUG(dbgs() << "\nReplacing.8 ";
6427 dbgs() << "\nWith: ";
6428 Tmp.getNode()->dump(&DAG);
6430 WorkListRemover DeadNodes(*this);
6431 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6432 removeFromWorkList(TheXor);
6433 DAG.DeleteNode(TheXor);
6434 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6435 MVT::Other, Chain, Tmp, N2);
6439 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6441 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6442 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6443 Op0.getOpcode() == ISD::XOR) {
6444 TheXor = Op0.getNode();
6448 EVT SetCCVT = N1.getValueType();
6450 SetCCVT = TLI.getSetCCResultType(SetCCVT);
6451 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6454 Equal ? ISD::SETEQ : ISD::SETNE);
6455 // Replace the uses of XOR with SETCC
6456 WorkListRemover DeadNodes(*this);
6457 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6458 removeFromWorkList(N1.getNode());
6459 DAG.DeleteNode(N1.getNode());
6460 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6461 MVT::Other, Chain, SetCC, N2);
6468 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6470 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6471 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6472 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6474 // If N is a constant we could fold this into a fallthrough or unconditional
6475 // branch. However that doesn't happen very often in normal code, because
6476 // Instcombine/SimplifyCFG should have handled the available opportunities.
6477 // If we did this folding here, it would be necessary to update the
6478 // MachineBasicBlock CFG, which is awkward.
6480 // Use SimplifySetCC to simplify SETCC's.
6481 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6482 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6484 if (Simp.getNode()) AddToWorkList(Simp.getNode());
6486 // fold to a simpler setcc
6487 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6488 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6489 N->getOperand(0), Simp.getOperand(2),
6490 Simp.getOperand(0), Simp.getOperand(1),
6496 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6497 /// uses N as its base pointer and that N may be folded in the load / store
6498 /// addressing mode.
6499 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6501 const TargetLowering &TLI) {
6503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
6504 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6506 VT = Use->getValueType(0);
6507 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
6508 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6510 VT = ST->getValue().getValueType();
6514 TargetLowering::AddrMode AM;
6515 if (N->getOpcode() == ISD::ADD) {
6516 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6519 AM.BaseOffs = Offset->getSExtValue();
6523 } else if (N->getOpcode() == ISD::SUB) {
6524 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6527 AM.BaseOffs = -Offset->getSExtValue();
6534 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6537 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6538 /// pre-indexed load / store when the base pointer is an add or subtract
6539 /// and it has other uses besides the load / store. After the
6540 /// transformation, the new indexed load / store has effectively folded
6541 /// the add / subtract in and all of its other uses are redirected to the
6542 /// new load / store.
6543 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6544 if (Level < AfterLegalizeDAG)
6550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6551 if (LD->isIndexed())
6553 VT = LD->getMemoryVT();
6554 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6555 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6557 Ptr = LD->getBasePtr();
6558 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6559 if (ST->isIndexed())
6561 VT = ST->getMemoryVT();
6562 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6563 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6565 Ptr = ST->getBasePtr();
6571 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6572 // out. There is no reason to make this a preinc/predec.
6573 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6574 Ptr.getNode()->hasOneUse())
6577 // Ask the target to do addressing mode selection.
6580 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6581 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6583 // Don't create a indexed load / store with zero offset.
6584 if (isa<ConstantSDNode>(Offset) &&
6585 cast<ConstantSDNode>(Offset)->isNullValue())
6588 // Try turning it into a pre-indexed load / store except when:
6589 // 1) The new base ptr is a frame index.
6590 // 2) If N is a store and the new base ptr is either the same as or is a
6591 // predecessor of the value being stored.
6592 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6593 // that would create a cycle.
6594 // 4) All uses are load / store ops that use it as old base ptr.
6596 // Check #1. Preinc'ing a frame index would require copying the stack pointer
6597 // (plus the implicit offset) to a register to preinc anyway.
6598 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6603 SDValue Val = cast<StoreSDNode>(N)->getValue();
6604 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6608 // Now check for #3 and #4.
6609 bool RealUse = false;
6611 // Caches for hasPredecessorHelper
6612 SmallPtrSet<const SDNode *, 32> Visited;
6613 SmallVector<const SDNode *, 16> Worklist;
6615 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6616 E = Ptr.getNode()->use_end(); I != E; ++I) {
6620 if (N->hasPredecessorHelper(Use, Visited, Worklist))
6623 // If Ptr may be folded in addressing mode of other use, then it's
6624 // not profitable to do this transformation.
6625 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6634 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6635 BasePtr, Offset, AM);
6637 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6638 BasePtr, Offset, AM);
6641 DEBUG(dbgs() << "\nReplacing.4 ";
6643 dbgs() << "\nWith: ";
6644 Result.getNode()->dump(&DAG);
6646 WorkListRemover DeadNodes(*this);
6648 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6654 // Finally, since the node is now dead, remove it from the graph.
6657 // Replace the uses of Ptr with uses of the updated base value.
6658 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6659 removeFromWorkList(Ptr.getNode());
6660 DAG.DeleteNode(Ptr.getNode());
6665 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6666 /// add / sub of the base pointer node into a post-indexed load / store.
6667 /// The transformation folded the add / subtract into the new indexed
6668 /// load / store effectively and all of its uses are redirected to the
6669 /// new load / store.
6670 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6671 if (Level < AfterLegalizeDAG)
6677 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6678 if (LD->isIndexed())
6680 VT = LD->getMemoryVT();
6681 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6682 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6684 Ptr = LD->getBasePtr();
6685 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6686 if (ST->isIndexed())
6688 VT = ST->getMemoryVT();
6689 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6690 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6692 Ptr = ST->getBasePtr();
6698 if (Ptr.getNode()->hasOneUse())
6701 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6702 E = Ptr.getNode()->use_end(); I != E; ++I) {
6705 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6710 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6711 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6712 // Don't create a indexed load / store with zero offset.
6713 if (isa<ConstantSDNode>(Offset) &&
6714 cast<ConstantSDNode>(Offset)->isNullValue())
6717 // Try turning it into a post-indexed load / store except when
6718 // 1) All uses are load / store ops that use it as base ptr (and
6719 // it may be folded as addressing mmode).
6720 // 2) Op must be independent of N, i.e. Op is neither a predecessor
6721 // nor a successor of N. Otherwise, if Op is folded that would
6724 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6728 bool TryNext = false;
6729 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6730 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6732 if (Use == Ptr.getNode())
6735 // If all the uses are load / store addresses, then don't do the
6737 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6738 bool RealUse = false;
6739 for (SDNode::use_iterator III = Use->use_begin(),
6740 EEE = Use->use_end(); III != EEE; ++III) {
6741 SDNode *UseUse = *III;
6742 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
6757 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6758 SDValue Result = isLoad
6759 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6760 BasePtr, Offset, AM)
6761 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6762 BasePtr, Offset, AM);
6765 DEBUG(dbgs() << "\nReplacing.5 ";
6767 dbgs() << "\nWith: ";
6768 Result.getNode()->dump(&DAG);
6770 WorkListRemover DeadNodes(*this);
6772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6773 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6775 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6778 // Finally, since the node is now dead, remove it from the graph.
6781 // Replace the uses of Use with uses of the updated base value.
6782 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6783 Result.getValue(isLoad ? 1 : 0));
6784 removeFromWorkList(Op);
6794 SDValue DAGCombiner::visitLOAD(SDNode *N) {
6795 LoadSDNode *LD = cast<LoadSDNode>(N);
6796 SDValue Chain = LD->getChain();
6797 SDValue Ptr = LD->getBasePtr();
6799 // If load is not volatile and there are no uses of the loaded value (and
6800 // the updated indexed value in case of indexed loads), change uses of the
6801 // chain value into uses of the chain input (i.e. delete the dead load).
6802 if (!LD->isVolatile()) {
6803 if (N->getValueType(1) == MVT::Other) {
6805 if (!N->hasAnyUseOfValue(0)) {
6806 // It's not safe to use the two value CombineTo variant here. e.g.
6807 // v1, chain2 = load chain1, loc
6808 // v2, chain3 = load chain2, loc
6810 // Now we replace use of chain2 with chain1. This makes the second load
6811 // isomorphic to the one we are deleting, and thus makes this load live.
6812 DEBUG(dbgs() << "\nReplacing.6 ";
6814 dbgs() << "\nWith chain: ";
6815 Chain.getNode()->dump(&DAG);
6817 WorkListRemover DeadNodes(*this);
6818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
6820 if (N->use_empty()) {
6821 removeFromWorkList(N);
6825 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6829 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6830 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
6831 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6832 DEBUG(dbgs() << "\nReplacing.7 ";
6834 dbgs() << "\nWith: ";
6835 Undef.getNode()->dump(&DAG);
6836 dbgs() << " and 2 other values\n");
6837 WorkListRemover DeadNodes(*this);
6838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
6839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6840 DAG.getUNDEF(N->getValueType(1)));
6841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
6842 removeFromWorkList(N);
6844 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6849 // If this load is directly stored, replace the load value with the stored
6851 // TODO: Handle store large -> read small portion.
6852 // TODO: Handle TRUNCSTORE/LOADEXT
6853 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6854 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6855 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6856 if (PrevST->getBasePtr() == Ptr &&
6857 PrevST->getValue().getValueType() == N->getValueType(0))
6858 return CombineTo(N, Chain.getOperand(1), Chain);
6862 // Try to infer better alignment information than the load already has.
6863 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6864 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6865 if (Align > LD->getAlignment())
6866 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6867 LD->getValueType(0),
6868 Chain, Ptr, LD->getPointerInfo(),
6870 LD->isVolatile(), LD->isNonTemporal(), Align);
6875 // Walk up chain skipping non-aliasing memory nodes.
6876 SDValue BetterChain = FindBetterChain(N, Chain);
6878 // If there is a better chain.
6879 if (Chain != BetterChain) {
6882 // Replace the chain to void dependency.
6883 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6884 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6885 BetterChain, Ptr, LD->getPointerInfo(),
6886 LD->isVolatile(), LD->isNonTemporal(),
6887 LD->isInvariant(), LD->getAlignment());
6889 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6890 LD->getValueType(0),
6891 BetterChain, Ptr, LD->getPointerInfo(),
6894 LD->isNonTemporal(),
6895 LD->getAlignment());
6898 // Create token factor to keep old chain connected.
6899 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6900 MVT::Other, Chain, ReplLoad.getValue(1));
6902 // Make sure the new and old chains are cleaned up.
6903 AddToWorkList(Token.getNode());
6905 // Replace uses with load result and token factor. Don't add users
6907 return CombineTo(N, ReplLoad.getValue(0), Token, false);
6911 // Try transforming N to an indexed load.
6912 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6913 return SDValue(N, 0);
6918 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6919 /// load is having specific bytes cleared out. If so, return the byte size
6920 /// being masked out and the shift amount.
6921 static std::pair<unsigned, unsigned>
6922 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6923 std::pair<unsigned, unsigned> Result(0, 0);
6925 // Check for the structure we're looking for.
6926 if (V->getOpcode() != ISD::AND ||
6927 !isa<ConstantSDNode>(V->getOperand(1)) ||
6928 !ISD::isNormalLoad(V->getOperand(0).getNode()))
6931 // Check the chain and pointer.
6932 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6933 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
6935 // The store should be chained directly to the load or be an operand of a
6937 if (LD == Chain.getNode())
6939 else if (Chain->getOpcode() != ISD::TokenFactor)
6940 return Result; // Fail.
6943 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6944 if (Chain->getOperand(i).getNode() == LD) {
6948 if (!isOk) return Result;
6951 // This only handles simple types.
6952 if (V.getValueType() != MVT::i16 &&
6953 V.getValueType() != MVT::i32 &&
6954 V.getValueType() != MVT::i64)
6957 // Check the constant mask. Invert it so that the bits being masked out are
6958 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
6959 // follow the sign bit for uniformity.
6960 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6961 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6962 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
6963 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6964 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
6965 if (NotMaskLZ == 64) return Result; // All zero mask.
6967 // See if we have a continuous run of bits. If so, we have 0*1+0*
6968 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6971 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6972 if (V.getValueType() != MVT::i64 && NotMaskLZ)
6973 NotMaskLZ -= 64-V.getValueSizeInBits();
6975 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6976 switch (MaskedBytes) {
6980 default: return Result; // All one mask, or 5-byte mask.
6983 // Verify that the first bit starts at a multiple of mask so that the access
6984 // is aligned the same as the access width.
6985 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6987 Result.first = MaskedBytes;
6988 Result.second = NotMaskTZ/8;
6993 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6994 /// provides a value as specified by MaskInfo. If so, replace the specified
6995 /// store with a narrower store of truncated IVal.
6997 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6998 SDValue IVal, StoreSDNode *St,
7000 unsigned NumBytes = MaskInfo.first;
7001 unsigned ByteShift = MaskInfo.second;
7002 SelectionDAG &DAG = DC->getDAG();
7004 // Check to see if IVal is all zeros in the part being masked in by the 'or'
7005 // that uses this. If not, this is not a replacement.
7006 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7007 ByteShift*8, (ByteShift+NumBytes)*8);
7008 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7010 // Check that it is legal on the target to do this. It is legal if the new
7011 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7013 MVT VT = MVT::getIntegerVT(NumBytes*8);
7014 if (!DC->isTypeLegal(VT))
7017 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
7018 // shifted by ByteShift and truncated down to NumBytes.
7020 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7021 DAG.getConstant(ByteShift*8,
7022 DC->getShiftAmountTy(IVal.getValueType())));
7024 // Figure out the offset for the store and the alignment of the access.
7026 unsigned NewAlign = St->getAlignment();
7028 if (DAG.getTargetLoweringInfo().isLittleEndian())
7029 StOffset = ByteShift;
7031 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7033 SDValue Ptr = St->getBasePtr();
7035 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7036 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7037 NewAlign = MinAlign(NewAlign, StOffset);
7040 // Truncate down to the new size.
7041 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7044 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7045 St->getPointerInfo().getWithOffset(StOffset),
7046 false, false, NewAlign).getNode();
7050 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7051 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7052 /// of the loaded bits, try narrowing the load and store if it would end up
7053 /// being a win for performance or code size.
7054 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7055 StoreSDNode *ST = cast<StoreSDNode>(N);
7056 if (ST->isVolatile())
7059 SDValue Chain = ST->getChain();
7060 SDValue Value = ST->getValue();
7061 SDValue Ptr = ST->getBasePtr();
7062 EVT VT = Value.getValueType();
7064 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7067 unsigned Opc = Value.getOpcode();
7069 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7070 // is a byte mask indicating a consecutive number of bytes, check to see if
7071 // Y is known to provide just those bytes. If so, we try to replace the
7072 // load + replace + store sequence with a single (narrower) store, which makes
7074 if (Opc == ISD::OR) {
7075 std::pair<unsigned, unsigned> MaskedLoad;
7076 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7077 if (MaskedLoad.first)
7078 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7079 Value.getOperand(1), ST,this))
7080 return SDValue(NewST, 0);
7082 // Or is commutative, so try swapping X and Y.
7083 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7084 if (MaskedLoad.first)
7085 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7086 Value.getOperand(0), ST,this))
7087 return SDValue(NewST, 0);
7090 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7091 Value.getOperand(1).getOpcode() != ISD::Constant)
7094 SDValue N0 = Value.getOperand(0);
7095 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7096 Chain == SDValue(N0.getNode(), 1)) {
7097 LoadSDNode *LD = cast<LoadSDNode>(N0);
7098 if (LD->getBasePtr() != Ptr ||
7099 LD->getPointerInfo().getAddrSpace() !=
7100 ST->getPointerInfo().getAddrSpace())
7103 // Find the type to narrow it the load / op / store to.
7104 SDValue N1 = Value.getOperand(1);
7105 unsigned BitWidth = N1.getValueSizeInBits();
7106 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7107 if (Opc == ISD::AND)
7108 Imm ^= APInt::getAllOnesValue(BitWidth);
7109 if (Imm == 0 || Imm.isAllOnesValue())
7111 unsigned ShAmt = Imm.countTrailingZeros();
7112 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7113 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7114 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7115 while (NewBW < BitWidth &&
7116 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7117 TLI.isNarrowingProfitable(VT, NewVT))) {
7118 NewBW = NextPowerOf2(NewBW);
7119 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7121 if (NewBW >= BitWidth)
7124 // If the lsb changed does not start at the type bitwidth boundary,
7125 // start at the previous one.
7127 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7128 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
7129 if ((Imm & Mask) == Imm) {
7130 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7131 if (Opc == ISD::AND)
7132 NewImm ^= APInt::getAllOnesValue(NewBW);
7133 uint64_t PtrOff = ShAmt / 8;
7134 // For big endian targets, we need to adjust the offset to the pointer to
7135 // load the correct bytes.
7136 if (TLI.isBigEndian())
7137 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7139 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7140 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7141 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
7144 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7145 Ptr.getValueType(), Ptr,
7146 DAG.getConstant(PtrOff, Ptr.getValueType()));
7147 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7148 LD->getChain(), NewPtr,
7149 LD->getPointerInfo().getWithOffset(PtrOff),
7150 LD->isVolatile(), LD->isNonTemporal(),
7151 LD->isInvariant(), NewAlign);
7152 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7153 DAG.getConstant(NewImm, NewVT));
7154 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7156 ST->getPointerInfo().getWithOffset(PtrOff),
7157 false, false, NewAlign);
7159 AddToWorkList(NewPtr.getNode());
7160 AddToWorkList(NewLD.getNode());
7161 AddToWorkList(NewVal.getNode());
7162 WorkListRemover DeadNodes(*this);
7163 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7172 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7173 /// if the load value isn't used by any other operations, then consider
7174 /// transforming the pair to integer load / store operations if the target
7175 /// deems the transformation profitable.
7176 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7177 StoreSDNode *ST = cast<StoreSDNode>(N);
7178 SDValue Chain = ST->getChain();
7179 SDValue Value = ST->getValue();
7180 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7181 Value.hasOneUse() &&
7182 Chain == SDValue(Value.getNode(), 1)) {
7183 LoadSDNode *LD = cast<LoadSDNode>(Value);
7184 EVT VT = LD->getMemoryVT();
7185 if (!VT.isFloatingPoint() ||
7186 VT != ST->getMemoryVT() ||
7187 LD->isNonTemporal() ||
7188 ST->isNonTemporal() ||
7189 LD->getPointerInfo().getAddrSpace() != 0 ||
7190 ST->getPointerInfo().getAddrSpace() != 0)
7193 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7194 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7195 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7196 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7197 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7200 unsigned LDAlign = LD->getAlignment();
7201 unsigned STAlign = ST->getAlignment();
7202 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7203 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
7204 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7207 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7208 LD->getChain(), LD->getBasePtr(),
7209 LD->getPointerInfo(),
7210 false, false, false, LDAlign);
7212 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7213 NewLD, ST->getBasePtr(),
7214 ST->getPointerInfo(),
7215 false, false, STAlign);
7217 AddToWorkList(NewLD.getNode());
7218 AddToWorkList(NewST.getNode());
7219 WorkListRemover DeadNodes(*this);
7220 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7228 SDValue DAGCombiner::visitSTORE(SDNode *N) {
7229 StoreSDNode *ST = cast<StoreSDNode>(N);
7230 SDValue Chain = ST->getChain();
7231 SDValue Value = ST->getValue();
7232 SDValue Ptr = ST->getBasePtr();
7234 // If this is a store of a bit convert, store the input value if the
7235 // resultant store does not need a higher alignment than the original.
7236 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7237 ST->isUnindexed()) {
7238 unsigned OrigAlign = ST->getAlignment();
7239 EVT SVT = Value.getOperand(0).getValueType();
7240 unsigned Align = TLI.getTargetData()->
7241 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7242 if (Align <= OrigAlign &&
7243 ((!LegalOperations && !ST->isVolatile()) ||
7244 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7245 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7246 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7247 ST->isNonTemporal(), OrigAlign);
7250 // Turn 'store undef, Ptr' -> nothing.
7251 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7254 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7255 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7256 // NOTE: If the original store is volatile, this transform must not increase
7257 // the number of stores. For example, on x86-32 an f64 can be stored in one
7258 // processor operation but an i64 (which is not legal) requires two. So the
7259 // transform should not be done in this case.
7260 if (Value.getOpcode() != ISD::TargetConstantFP) {
7262 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7263 default: llvm_unreachable("Unknown FP type");
7264 case MVT::f16: // We don't do this for these yet.
7270 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7271 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7272 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7273 bitcastToAPInt().getZExtValue(), MVT::i32);
7274 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7275 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7276 ST->isNonTemporal(), ST->getAlignment());
7280 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7281 !ST->isVolatile()) ||
7282 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7283 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7284 getZExtValue(), MVT::i64);
7285 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7286 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7287 ST->isNonTemporal(), ST->getAlignment());
7290 if (!ST->isVolatile() &&
7291 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7292 // Many FP stores are not made apparent until after legalize, e.g. for
7293 // argument passing. Since this is so common, custom legalize the
7294 // 64-bit integer store into two 32-bit stores.
7295 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7296 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7297 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7298 if (TLI.isBigEndian()) std::swap(Lo, Hi);
7300 unsigned Alignment = ST->getAlignment();
7301 bool isVolatile = ST->isVolatile();
7302 bool isNonTemporal = ST->isNonTemporal();
7304 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7305 Ptr, ST->getPointerInfo(),
7306 isVolatile, isNonTemporal,
7307 ST->getAlignment());
7308 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7309 DAG.getConstant(4, Ptr.getValueType()));
7310 Alignment = MinAlign(Alignment, 4U);
7311 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7312 Ptr, ST->getPointerInfo().getWithOffset(4),
7313 isVolatile, isNonTemporal,
7315 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7324 // Try to infer better alignment information than the store already has.
7325 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7326 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7327 if (Align > ST->getAlignment())
7328 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7329 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7330 ST->isVolatile(), ST->isNonTemporal(), Align);
7334 // Try transforming a pair floating point load / store ops to integer
7335 // load / store ops.
7336 SDValue NewST = TransformFPLoadStorePair(N);
7337 if (NewST.getNode())
7341 // Walk up chain skipping non-aliasing memory nodes.
7342 SDValue BetterChain = FindBetterChain(N, Chain);
7344 // If there is a better chain.
7345 if (Chain != BetterChain) {
7348 // Replace the chain to avoid dependency.
7349 if (ST->isTruncatingStore()) {
7350 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7351 ST->getPointerInfo(),
7352 ST->getMemoryVT(), ST->isVolatile(),
7353 ST->isNonTemporal(), ST->getAlignment());
7355 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7356 ST->getPointerInfo(),
7357 ST->isVolatile(), ST->isNonTemporal(),
7358 ST->getAlignment());
7361 // Create token to keep both nodes around.
7362 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7363 MVT::Other, Chain, ReplStore);
7365 // Make sure the new and old chains are cleaned up.
7366 AddToWorkList(Token.getNode());
7368 // Don't add users to work list.
7369 return CombineTo(N, Token, false);
7373 // Try transforming N to an indexed store.
7374 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7375 return SDValue(N, 0);
7377 // FIXME: is there such a thing as a truncating indexed store?
7378 if (ST->isTruncatingStore() && ST->isUnindexed() &&
7379 Value.getValueType().isInteger()) {
7380 // See if we can simplify the input to this truncstore with knowledge that
7381 // only the low bits are being used. For example:
7382 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
7384 GetDemandedBits(Value,
7385 APInt::getLowBitsSet(
7386 Value.getValueType().getScalarType().getSizeInBits(),
7387 ST->getMemoryVT().getScalarType().getSizeInBits()));
7388 AddToWorkList(Value.getNode());
7389 if (Shorter.getNode())
7390 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
7391 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7392 ST->isVolatile(), ST->isNonTemporal(),
7393 ST->getAlignment());
7395 // Otherwise, see if we can simplify the operation with
7396 // SimplifyDemandedBits, which only works if the value has a single use.
7397 if (SimplifyDemandedBits(Value,
7398 APInt::getLowBitsSet(
7399 Value.getValueType().getScalarType().getSizeInBits(),
7400 ST->getMemoryVT().getScalarType().getSizeInBits())))
7401 return SDValue(N, 0);
7404 // If this is a load followed by a store to the same location, then the store
7406 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
7407 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
7408 ST->isUnindexed() && !ST->isVolatile() &&
7409 // There can't be any side effects between the load and store, such as
7411 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
7412 // The store is dead, remove it.
7417 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
7418 // truncating store. We can do this even if this is already a truncstore.
7419 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
7420 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
7421 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
7422 ST->getMemoryVT())) {
7423 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7424 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7425 ST->isVolatile(), ST->isNonTemporal(),
7426 ST->getAlignment());
7429 return ReduceLoadOpStoreWidth(N);
7432 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
7433 SDValue InVec = N->getOperand(0);
7434 SDValue InVal = N->getOperand(1);
7435 SDValue EltNo = N->getOperand(2);
7436 DebugLoc dl = N->getDebugLoc();
7438 // If the inserted element is an UNDEF, just use the input vector.
7439 if (InVal.getOpcode() == ISD::UNDEF)
7442 EVT VT = InVec.getValueType();
7444 // If we can't generate a legal BUILD_VECTOR, exit
7445 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
7448 // Check that we know which element is being inserted
7449 if (!isa<ConstantSDNode>(EltNo))
7451 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7453 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
7454 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
7456 SmallVector<SDValue, 8> Ops;
7457 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
7458 Ops.append(InVec.getNode()->op_begin(),
7459 InVec.getNode()->op_end());
7460 } else if (InVec.getOpcode() == ISD::UNDEF) {
7461 unsigned NElts = VT.getVectorNumElements();
7462 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
7467 // Insert the element
7468 if (Elt < Ops.size()) {
7469 // All the operands of BUILD_VECTOR must have the same type;
7470 // we enforce that here.
7471 EVT OpVT = Ops[0].getValueType();
7472 if (InVal.getValueType() != OpVT)
7473 InVal = OpVT.bitsGT(InVal.getValueType()) ?
7474 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
7475 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
7479 // Return the new vector
7480 return DAG.getNode(ISD::BUILD_VECTOR, dl,
7481 VT, &Ops[0], Ops.size());
7484 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
7485 // (vextract (scalar_to_vector val, 0) -> val
7486 SDValue InVec = N->getOperand(0);
7487 EVT VT = InVec.getValueType();
7488 EVT NVT = N->getValueType(0);
7490 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7491 // Check if the result type doesn't match the inserted element type. A
7492 // SCALAR_TO_VECTOR may truncate the inserted element and the
7493 // EXTRACT_VECTOR_ELT may widen the extracted vector.
7494 SDValue InOp = InVec.getOperand(0);
7495 if (InOp.getValueType() != NVT) {
7496 assert(InOp.getValueType().isInteger() && NVT.isInteger());
7497 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
7502 SDValue EltNo = N->getOperand(1);
7503 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
7505 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
7506 // We only perform this optimization before the op legalization phase because
7507 // we may introduce new vector instructions which are not backed by TD patterns.
7508 // For example on AVX, extracting elements from a wide vector without using
7509 // extract_subvector.
7510 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
7511 && ConstEltNo && !LegalOperations) {
7512 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7513 int NumElem = VT.getVectorNumElements();
7514 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
7515 // Find the new index to extract from.
7516 int OrigElt = SVOp->getMaskElt(Elt);
7518 // Extracting an undef index is undef.
7520 return DAG.getUNDEF(NVT);
7522 // Select the right vector half to extract from.
7523 if (OrigElt < NumElem) {
7524 InVec = InVec->getOperand(0);
7526 InVec = InVec->getOperand(1);
7530 EVT IndexTy = N->getOperand(1).getValueType();
7531 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
7532 InVec, DAG.getConstant(OrigElt, IndexTy));
7535 // Perform only after legalization to ensure build_vector / vector_shuffle
7536 // optimizations have already been done.
7537 if (!LegalOperations) return SDValue();
7539 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
7540 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
7541 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
7544 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7545 bool NewLoad = false;
7546 bool BCNumEltsChanged = false;
7547 EVT ExtVT = VT.getVectorElementType();
7550 // If the result of load has to be truncated, then it's not necessarily
7552 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
7555 if (InVec.getOpcode() == ISD::BITCAST) {
7556 // Don't duplicate a load with other uses.
7557 if (!InVec.hasOneUse())
7560 EVT BCVT = InVec.getOperand(0).getValueType();
7561 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
7563 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
7564 BCNumEltsChanged = true;
7565 InVec = InVec.getOperand(0);
7566 ExtVT = BCVT.getVectorElementType();
7570 LoadSDNode *LN0 = NULL;
7571 const ShuffleVectorSDNode *SVN = NULL;
7572 if (ISD::isNormalLoad(InVec.getNode())) {
7573 LN0 = cast<LoadSDNode>(InVec);
7574 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7575 InVec.getOperand(0).getValueType() == ExtVT &&
7576 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
7577 // Don't duplicate a load with other uses.
7578 if (!InVec.hasOneUse())
7581 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
7582 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
7583 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
7585 // (load $addr+1*size)
7587 // Don't duplicate a load with other uses.
7588 if (!InVec.hasOneUse())
7591 // If the bit convert changed the number of elements, it is unsafe
7592 // to examine the mask.
7593 if (BCNumEltsChanged)
7596 // Select the input vector, guarding against out of range extract vector.
7597 unsigned NumElems = VT.getVectorNumElements();
7598 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
7599 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
7601 if (InVec.getOpcode() == ISD::BITCAST) {
7602 // Don't duplicate a load with other uses.
7603 if (!InVec.hasOneUse())
7606 InVec = InVec.getOperand(0);
7608 if (ISD::isNormalLoad(InVec.getNode())) {
7609 LN0 = cast<LoadSDNode>(InVec);
7610 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
7614 // Make sure we found a non-volatile load and the extractelement is
7616 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
7619 // If Idx was -1 above, Elt is going to be -1, so just return undef.
7621 return DAG.getUNDEF(LVT);
7623 unsigned Align = LN0->getAlignment();
7625 // Check the resultant load doesn't need a higher alignment than the
7629 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
7631 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
7637 SDValue NewPtr = LN0->getBasePtr();
7638 unsigned PtrOff = 0;
7641 PtrOff = LVT.getSizeInBits() * Elt / 8;
7642 EVT PtrType = NewPtr.getValueType();
7643 if (TLI.isBigEndian())
7644 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
7645 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
7646 DAG.getConstant(PtrOff, PtrType));
7649 // The replacement we need to do here is a little tricky: we need to
7650 // replace an extractelement of a load with a load.
7651 // Use ReplaceAllUsesOfValuesWith to do the replacement.
7652 // Note that this replacement assumes that the extractvalue is the only
7653 // use of the load; that's okay because we don't want to perform this
7654 // transformation in other cases anyway.
7657 if (NVT.bitsGT(LVT)) {
7658 // If the result type of vextract is wider than the load, then issue an
7659 // extending load instead.
7660 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
7661 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
7662 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
7663 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
7664 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
7665 Chain = Load.getValue(1);
7667 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
7668 LN0->getPointerInfo().getWithOffset(PtrOff),
7669 LN0->isVolatile(), LN0->isNonTemporal(),
7670 LN0->isInvariant(), Align);
7671 Chain = Load.getValue(1);
7672 if (NVT.bitsLT(LVT))
7673 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
7675 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
7677 WorkListRemover DeadNodes(*this);
7678 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
7679 SDValue To[] = { Load, Chain };
7680 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7681 // Since we're explcitly calling ReplaceAllUses, add the new node to the
7682 // worklist explicitly as well.
7683 AddToWorkList(Load.getNode());
7684 AddUsersToWorkList(Load.getNode()); // Add users too
7685 // Make sure to revisit this node to clean it up; it will usually be dead.
7687 return SDValue(N, 0);
7693 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
7694 unsigned NumInScalars = N->getNumOperands();
7695 DebugLoc dl = N->getDebugLoc();
7696 EVT VT = N->getValueType(0);
7698 // A vector built entirely of undefs is undef.
7699 if (ISD::allOperandsUndef(N))
7700 return DAG.getUNDEF(VT);
7702 // Check to see if this is a BUILD_VECTOR of a bunch of values
7703 // which come from any_extend or zero_extend nodes. If so, we can create
7704 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
7705 // optimizations. We do not handle sign-extend because we can't fill the sign
7707 EVT SourceType = MVT::Other;
7708 bool AllAnyExt = true;
7710 for (unsigned i = 0; i != NumInScalars; ++i) {
7711 SDValue In = N->getOperand(i);
7712 // Ignore undef inputs.
7713 if (In.getOpcode() == ISD::UNDEF) continue;
7715 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
7716 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
7718 // Abort if the element is not an extension.
7719 if (!ZeroExt && !AnyExt) {
7720 SourceType = MVT::Other;
7724 // The input is a ZeroExt or AnyExt. Check the original type.
7725 EVT InTy = In.getOperand(0).getValueType();
7727 // Check that all of the widened source types are the same.
7728 if (SourceType == MVT::Other)
7731 else if (InTy != SourceType) {
7732 // Multiple income types. Abort.
7733 SourceType = MVT::Other;
7737 // Check if all of the extends are ANY_EXTENDs.
7738 AllAnyExt &= AnyExt;
7741 // In order to have valid types, all of the inputs must be extended from the
7742 // same source type and all of the inputs must be any or zero extend.
7743 // Scalar sizes must be a power of two.
7744 EVT OutScalarTy = N->getValueType(0).getScalarType();
7745 bool ValidTypes = SourceType != MVT::Other &&
7746 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7747 isPowerOf2_32(SourceType.getSizeInBits());
7749 // We perform this optimization post type-legalization because
7750 // the type-legalizer often scalarizes integer-promoted vectors.
7751 // Performing this optimization before may create bit-casts which
7752 // will be type-legalized to complex code sequences.
7753 // We perform this optimization only before the operation legalizer because we
7754 // may introduce illegal operations.
7755 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
7756 // turn into a single shuffle instruction.
7757 if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) &&
7759 bool isLE = TLI.isLittleEndian();
7760 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7761 assert(ElemRatio > 1 && "Invalid element size ratio");
7762 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
7763 DAG.getConstant(0, SourceType);
7765 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7766 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7768 // Populate the new build_vector
7769 for (unsigned i=0; i < N->getNumOperands(); ++i) {
7770 SDValue Cast = N->getOperand(i);
7771 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7772 Cast.getOpcode() == ISD::ZERO_EXTEND ||
7773 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7775 if (Cast.getOpcode() == ISD::UNDEF)
7776 In = DAG.getUNDEF(SourceType);
7778 In = Cast->getOperand(0);
7779 unsigned Index = isLE ? (i * ElemRatio) :
7780 (i * ElemRatio + (ElemRatio - 1));
7782 assert(Index < Ops.size() && "Invalid index");
7786 // The type of the new BUILD_VECTOR node.
7787 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7788 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7789 "Invalid vector size");
7790 // Check if the new vector type is legal.
7791 if (!isTypeLegal(VecVT)) return SDValue();
7793 // Make the new BUILD_VECTOR.
7794 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7795 VecVT, &Ops[0], Ops.size());
7797 // The new BUILD_VECTOR node has the potential to be further optimized.
7798 AddToWorkList(BV.getNode());
7799 // Bitcast to the desired type.
7800 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7803 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7804 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7805 // at most two distinct vectors, turn this into a shuffle node.
7807 // May only combine to shuffle after legalize if shuffle is legal.
7808 if (LegalOperations &&
7809 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
7812 SDValue VecIn1, VecIn2;
7813 for (unsigned i = 0; i != NumInScalars; ++i) {
7814 // Ignore undef inputs.
7815 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7817 // If this input is something other than a EXTRACT_VECTOR_ELT with a
7818 // constant index, bail out.
7819 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7820 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7821 VecIn1 = VecIn2 = SDValue(0, 0);
7825 // We allow up to two distinct input vectors.
7826 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7827 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7830 if (VecIn1.getNode() == 0) {
7831 VecIn1 = ExtractedFromVec;
7832 } else if (VecIn2.getNode() == 0) {
7833 VecIn2 = ExtractedFromVec;
7836 VecIn1 = VecIn2 = SDValue(0, 0);
7841 // If everything is good, we can make a shuffle operation.
7842 if (VecIn1.getNode()) {
7843 SmallVector<int, 8> Mask;
7844 for (unsigned i = 0; i != NumInScalars; ++i) {
7845 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7850 // If extracting from the first vector, just use the index directly.
7851 SDValue Extract = N->getOperand(i);
7852 SDValue ExtVal = Extract.getOperand(1);
7853 if (Extract.getOperand(0) == VecIn1) {
7854 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7855 if (ExtIndex > VT.getVectorNumElements())
7858 Mask.push_back(ExtIndex);
7862 // Otherwise, use InIdx + VecSize
7863 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7864 Mask.push_back(Idx+NumInScalars);
7867 // We can't generate a shuffle node with mismatched input and output types.
7868 // Attempt to transform a single input vector to the correct type.
7869 if ((VT != VecIn1.getValueType())) {
7870 // We don't support shuffeling between TWO values of different types.
7871 if (VecIn2.getNode() != 0)
7874 // We only support widening of vectors which are half the size of the
7875 // output registers. For example XMM->YMM widening on X86 with AVX.
7876 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
7879 // Widen the input vector by adding undef values.
7880 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7881 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
7884 // If VecIn2 is unused then change it to undef.
7885 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7887 // Check that we were able to transform all incoming values to the same type.
7888 if (VecIn2.getValueType() != VecIn1.getValueType() ||
7889 VecIn1.getValueType() != VT)
7892 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
7893 if (!isTypeLegal(VT))
7896 // Return the new VECTOR_SHUFFLE node.
7900 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7906 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7907 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7908 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
7909 // inputs come from at most two distinct vectors, turn this into a shuffle
7912 // If we only have one input vector, we don't need to do any concatenation.
7913 if (N->getNumOperands() == 1)
7914 return N->getOperand(0);
7916 // Check if all of the operands are undefs.
7917 if (ISD::allOperandsUndef(N))
7918 return DAG.getUNDEF(N->getValueType(0));
7923 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7924 EVT NVT = N->getValueType(0);
7925 SDValue V = N->getOperand(0);
7927 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7928 // Handle only simple case where vector being inserted and vector
7929 // being extracted are of same type, and are half size of larger vectors.
7930 EVT BigVT = V->getOperand(0).getValueType();
7931 EVT SmallVT = V->getOperand(1).getValueType();
7932 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7935 // Only handle cases where both indexes are constants with the same type.
7936 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7937 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
7939 if (InsIdx && ExtIdx &&
7940 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
7941 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
7943 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7945 // indices are equal => V1
7946 // otherwise => (extract_subvec V1, ExtIdx)
7947 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
7948 return V->getOperand(1);
7949 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7950 V->getOperand(0), N->getOperand(1));
7957 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7958 EVT VT = N->getValueType(0);
7959 unsigned NumElts = VT.getVectorNumElements();
7961 SDValue N0 = N->getOperand(0);
7962 SDValue N1 = N->getOperand(1);
7964 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
7966 // Canonicalize shuffle undef, undef -> undef
7967 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
7968 return DAG.getUNDEF(VT);
7970 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7972 // Canonicalize shuffle v, v -> v, undef
7974 SmallVector<int, 8> NewMask;
7975 for (unsigned i = 0; i != NumElts; ++i) {
7976 int Idx = SVN->getMaskElt(i);
7977 if (Idx >= (int)NumElts) Idx -= NumElts;
7978 NewMask.push_back(Idx);
7980 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
7984 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
7985 if (N0.getOpcode() == ISD::UNDEF) {
7986 SmallVector<int, 8> NewMask;
7987 for (unsigned i = 0; i != NumElts; ++i) {
7988 int Idx = SVN->getMaskElt(i);
7990 if (Idx < (int)NumElts)
7995 NewMask.push_back(Idx);
7997 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
8001 // Remove references to rhs if it is undef
8002 if (N1.getOpcode() == ISD::UNDEF) {
8003 bool Changed = false;
8004 SmallVector<int, 8> NewMask;
8005 for (unsigned i = 0; i != NumElts; ++i) {
8006 int Idx = SVN->getMaskElt(i);
8007 if (Idx >= (int)NumElts) {
8011 NewMask.push_back(Idx);
8014 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
8017 // If it is a splat, check if the argument vector is another splat or a
8018 // build_vector with all scalar elements the same.
8019 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
8020 SDNode *V = N0.getNode();
8022 // If this is a bit convert that changes the element type of the vector but
8023 // not the number of vector elements, look through it. Be careful not to
8024 // look though conversions that change things like v4f32 to v2f64.
8025 if (V->getOpcode() == ISD::BITCAST) {
8026 SDValue ConvInput = V->getOperand(0);
8027 if (ConvInput.getValueType().isVector() &&
8028 ConvInput.getValueType().getVectorNumElements() == NumElts)
8029 V = ConvInput.getNode();
8032 if (V->getOpcode() == ISD::BUILD_VECTOR) {
8033 assert(V->getNumOperands() == NumElts &&
8034 "BUILD_VECTOR has wrong number of operands");
8036 bool AllSame = true;
8037 for (unsigned i = 0; i != NumElts; ++i) {
8038 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
8039 Base = V->getOperand(i);
8043 // Splat of <u, u, u, u>, return <u, u, u, u>
8044 if (!Base.getNode())
8046 for (unsigned i = 0; i != NumElts; ++i) {
8047 if (V->getOperand(i) != Base) {
8052 // Splat of <x, x, x, x>, return <x, x, x, x>
8058 // If this shuffle node is simply a swizzle of another shuffle node,
8059 // and it reverses the swizzle of the previous shuffle then we can
8060 // optimize shuffle(shuffle(x, undef), undef) -> x.
8061 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
8062 N1.getOpcode() == ISD::UNDEF) {
8064 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
8066 // Shuffle nodes can only reverse shuffles with a single non-undef value.
8067 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
8070 // The incoming shuffle must be of the same type as the result of the
8072 assert(OtherSV->getOperand(0).getValueType() == VT &&
8073 "Shuffle types don't match");
8075 for (unsigned i = 0; i != NumElts; ++i) {
8076 int Idx = SVN->getMaskElt(i);
8077 assert(Idx < (int)NumElts && "Index references undef operand");
8078 // Next, this index comes from the first value, which is the incoming
8079 // shuffle. Adopt the incoming index.
8081 Idx = OtherSV->getMaskElt(Idx);
8083 // The combined shuffle must map each index to itself.
8084 if (Idx >= 0 && (unsigned)Idx != i)
8088 return OtherSV->getOperand(0);
8094 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
8095 if (!TLI.getShouldFoldAtomicFences())
8098 SDValue atomic = N->getOperand(0);
8099 switch (atomic.getOpcode()) {
8100 case ISD::ATOMIC_CMP_SWAP:
8101 case ISD::ATOMIC_SWAP:
8102 case ISD::ATOMIC_LOAD_ADD:
8103 case ISD::ATOMIC_LOAD_SUB:
8104 case ISD::ATOMIC_LOAD_AND:
8105 case ISD::ATOMIC_LOAD_OR:
8106 case ISD::ATOMIC_LOAD_XOR:
8107 case ISD::ATOMIC_LOAD_NAND:
8108 case ISD::ATOMIC_LOAD_MIN:
8109 case ISD::ATOMIC_LOAD_MAX:
8110 case ISD::ATOMIC_LOAD_UMIN:
8111 case ISD::ATOMIC_LOAD_UMAX:
8117 SDValue fence = atomic.getOperand(0);
8118 if (fence.getOpcode() != ISD::MEMBARRIER)
8121 switch (atomic.getOpcode()) {
8122 case ISD::ATOMIC_CMP_SWAP:
8123 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8124 fence.getOperand(0),
8125 atomic.getOperand(1), atomic.getOperand(2),
8126 atomic.getOperand(3)), atomic.getResNo());
8127 case ISD::ATOMIC_SWAP:
8128 case ISD::ATOMIC_LOAD_ADD:
8129 case ISD::ATOMIC_LOAD_SUB:
8130 case ISD::ATOMIC_LOAD_AND:
8131 case ISD::ATOMIC_LOAD_OR:
8132 case ISD::ATOMIC_LOAD_XOR:
8133 case ISD::ATOMIC_LOAD_NAND:
8134 case ISD::ATOMIC_LOAD_MIN:
8135 case ISD::ATOMIC_LOAD_MAX:
8136 case ISD::ATOMIC_LOAD_UMIN:
8137 case ISD::ATOMIC_LOAD_UMAX:
8138 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8139 fence.getOperand(0),
8140 atomic.getOperand(1), atomic.getOperand(2)),
8147 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
8148 /// an AND to a vector_shuffle with the destination vector and a zero vector.
8149 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
8150 /// vector_shuffle V, Zero, <0, 4, 2, 4>
8151 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
8152 EVT VT = N->getValueType(0);
8153 DebugLoc dl = N->getDebugLoc();
8154 SDValue LHS = N->getOperand(0);
8155 SDValue RHS = N->getOperand(1);
8156 if (N->getOpcode() == ISD::AND) {
8157 if (RHS.getOpcode() == ISD::BITCAST)
8158 RHS = RHS.getOperand(0);
8159 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
8160 SmallVector<int, 8> Indices;
8161 unsigned NumElts = RHS.getNumOperands();
8162 for (unsigned i = 0; i != NumElts; ++i) {
8163 SDValue Elt = RHS.getOperand(i);
8164 if (!isa<ConstantSDNode>(Elt))
8167 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
8168 Indices.push_back(i);
8169 else if (cast<ConstantSDNode>(Elt)->isNullValue())
8170 Indices.push_back(NumElts);
8175 // Let's see if the target supports this vector_shuffle.
8176 EVT RVT = RHS.getValueType();
8177 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
8180 // Return the new VECTOR_SHUFFLE node.
8181 EVT EltVT = RVT.getVectorElementType();
8182 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
8183 DAG.getConstant(0, EltVT));
8184 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8185 RVT, &ZeroOps[0], ZeroOps.size());
8186 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
8187 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
8188 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
8195 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
8196 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
8197 // After legalize, the target may be depending on adds and other
8198 // binary ops to provide legal ways to construct constants or other
8199 // things. Simplifying them may result in a loss of legality.
8200 if (LegalOperations) return SDValue();
8202 assert(N->getValueType(0).isVector() &&
8203 "SimplifyVBinOp only works on vectors!");
8205 SDValue LHS = N->getOperand(0);
8206 SDValue RHS = N->getOperand(1);
8207 SDValue Shuffle = XformToShuffleWithZero(N);
8208 if (Shuffle.getNode()) return Shuffle;
8210 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
8212 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
8213 RHS.getOpcode() == ISD::BUILD_VECTOR) {
8214 SmallVector<SDValue, 8> Ops;
8215 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
8216 SDValue LHSOp = LHS.getOperand(i);
8217 SDValue RHSOp = RHS.getOperand(i);
8218 // If these two elements can't be folded, bail out.
8219 if ((LHSOp.getOpcode() != ISD::UNDEF &&
8220 LHSOp.getOpcode() != ISD::Constant &&
8221 LHSOp.getOpcode() != ISD::ConstantFP) ||
8222 (RHSOp.getOpcode() != ISD::UNDEF &&
8223 RHSOp.getOpcode() != ISD::Constant &&
8224 RHSOp.getOpcode() != ISD::ConstantFP))
8227 // Can't fold divide by zero.
8228 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
8229 N->getOpcode() == ISD::FDIV) {
8230 if ((RHSOp.getOpcode() == ISD::Constant &&
8231 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
8232 (RHSOp.getOpcode() == ISD::ConstantFP &&
8233 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
8237 EVT VT = LHSOp.getValueType();
8238 EVT RVT = RHSOp.getValueType();
8240 // Integer BUILD_VECTOR operands may have types larger than the element
8241 // size (e.g., when the element type is not legal). Prior to type
8242 // legalization, the types may not match between the two BUILD_VECTORS.
8243 // Truncate one of the operands to make them match.
8244 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
8245 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
8247 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
8251 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
8253 if (FoldOp.getOpcode() != ISD::UNDEF &&
8254 FoldOp.getOpcode() != ISD::Constant &&
8255 FoldOp.getOpcode() != ISD::ConstantFP)
8257 Ops.push_back(FoldOp);
8258 AddToWorkList(FoldOp.getNode());
8261 if (Ops.size() == LHS.getNumOperands())
8262 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8263 LHS.getValueType(), &Ops[0], Ops.size());
8269 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
8270 SDValue N1, SDValue N2){
8271 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
8273 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
8274 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8276 // If we got a simplified select_cc node back from SimplifySelectCC, then
8277 // break it down into a new SETCC node, and a new SELECT node, and then return
8278 // the SELECT node, since we were called with a SELECT node.
8279 if (SCC.getNode()) {
8280 // Check to see if we got a select_cc back (to turn into setcc/select).
8281 // Otherwise, just return whatever node we got back, like fabs.
8282 if (SCC.getOpcode() == ISD::SELECT_CC) {
8283 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
8285 SCC.getOperand(0), SCC.getOperand(1),
8287 AddToWorkList(SETCC.getNode());
8288 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
8289 SCC.getOperand(2), SCC.getOperand(3), SETCC);
8297 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
8298 /// are the two values being selected between, see if we can simplify the
8299 /// select. Callers of this should assume that TheSelect is deleted if this
8300 /// returns true. As such, they should return the appropriate thing (e.g. the
8301 /// node) back to the top-level of the DAG combiner loop to avoid it being
8303 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
8306 // Cannot simplify select with vector condition
8307 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
8309 // If this is a select from two identical things, try to pull the operation
8310 // through the select.
8311 if (LHS.getOpcode() != RHS.getOpcode() ||
8312 !LHS.hasOneUse() || !RHS.hasOneUse())
8315 // If this is a load and the token chain is identical, replace the select
8316 // of two loads with a load through a select of the address to load from.
8317 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
8318 // constants have been dropped into the constant pool.
8319 if (LHS.getOpcode() == ISD::LOAD) {
8320 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
8321 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
8323 // Token chains must be identical.
8324 if (LHS.getOperand(0) != RHS.getOperand(0) ||
8325 // Do not let this transformation reduce the number of volatile loads.
8326 LLD->isVolatile() || RLD->isVolatile() ||
8327 // If this is an EXTLOAD, the VT's must match.
8328 LLD->getMemoryVT() != RLD->getMemoryVT() ||
8329 // If this is an EXTLOAD, the kind of extension must match.
8330 (LLD->getExtensionType() != RLD->getExtensionType() &&
8331 // The only exception is if one of the extensions is anyext.
8332 LLD->getExtensionType() != ISD::EXTLOAD &&
8333 RLD->getExtensionType() != ISD::EXTLOAD) ||
8334 // FIXME: this discards src value information. This is
8335 // over-conservative. It would be beneficial to be able to remember
8336 // both potential memory locations. Since we are discarding
8337 // src value info, don't do the transformation if the memory
8338 // locations are not in the default address space.
8339 LLD->getPointerInfo().getAddrSpace() != 0 ||
8340 RLD->getPointerInfo().getAddrSpace() != 0)
8343 // Check that the select condition doesn't reach either load. If so,
8344 // folding this will induce a cycle into the DAG. If not, this is safe to
8345 // xform, so create a select of the addresses.
8347 if (TheSelect->getOpcode() == ISD::SELECT) {
8348 SDNode *CondNode = TheSelect->getOperand(0).getNode();
8349 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
8350 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
8352 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
8353 LLD->getBasePtr().getValueType(),
8354 TheSelect->getOperand(0), LLD->getBasePtr(),
8356 } else { // Otherwise SELECT_CC
8357 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
8358 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
8360 if ((LLD->hasAnyUseOfValue(1) &&
8361 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
8362 (RLD->hasAnyUseOfValue(1) &&
8363 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
8366 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
8367 LLD->getBasePtr().getValueType(),
8368 TheSelect->getOperand(0),
8369 TheSelect->getOperand(1),
8370 LLD->getBasePtr(), RLD->getBasePtr(),
8371 TheSelect->getOperand(4));
8375 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
8376 Load = DAG.getLoad(TheSelect->getValueType(0),
8377 TheSelect->getDebugLoc(),
8378 // FIXME: Discards pointer info.
8379 LLD->getChain(), Addr, MachinePointerInfo(),
8380 LLD->isVolatile(), LLD->isNonTemporal(),
8381 LLD->isInvariant(), LLD->getAlignment());
8383 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
8384 RLD->getExtensionType() : LLD->getExtensionType(),
8385 TheSelect->getDebugLoc(),
8386 TheSelect->getValueType(0),
8387 // FIXME: Discards pointer info.
8388 LLD->getChain(), Addr, MachinePointerInfo(),
8389 LLD->getMemoryVT(), LLD->isVolatile(),
8390 LLD->isNonTemporal(), LLD->getAlignment());
8393 // Users of the select now use the result of the load.
8394 CombineTo(TheSelect, Load);
8396 // Users of the old loads now use the new load's chain. We know the
8397 // old-load value is dead now.
8398 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
8399 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
8406 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
8407 /// where 'cond' is the comparison specified by CC.
8408 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
8409 SDValue N2, SDValue N3,
8410 ISD::CondCode CC, bool NotExtCompare) {
8411 // (x ? y : y) -> y.
8412 if (N2 == N3) return N2;
8414 EVT VT = N2.getValueType();
8415 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
8416 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
8417 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
8419 // Determine if the condition we're dealing with is constant
8420 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
8421 N0, N1, CC, DL, false);
8422 if (SCC.getNode()) AddToWorkList(SCC.getNode());
8423 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
8425 // fold select_cc true, x, y -> x
8426 if (SCCC && !SCCC->isNullValue())
8428 // fold select_cc false, x, y -> y
8429 if (SCCC && SCCC->isNullValue())
8432 // Check to see if we can simplify the select into an fabs node
8433 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
8434 // Allow either -0.0 or 0.0
8435 if (CFP->getValueAPF().isZero()) {
8436 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
8437 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
8438 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
8439 N2 == N3.getOperand(0))
8440 return DAG.getNode(ISD::FABS, DL, VT, N0);
8442 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
8443 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
8444 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
8445 N2.getOperand(0) == N3)
8446 return DAG.getNode(ISD::FABS, DL, VT, N3);
8450 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
8451 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
8452 // in it. This is a win when the constant is not otherwise available because
8453 // it replaces two constant pool loads with one. We only do this if the FP
8454 // type is known to be legal, because if it isn't, then we are before legalize
8455 // types an we want the other legalization to happen first (e.g. to avoid
8456 // messing with soft float) and if the ConstantFP is not legal, because if
8457 // it is legal, we may not need to store the FP constant in a constant pool.
8458 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
8459 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
8460 if (TLI.isTypeLegal(N2.getValueType()) &&
8461 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
8462 TargetLowering::Legal) &&
8463 // If both constants have multiple uses, then we won't need to do an
8464 // extra load, they are likely around in registers for other users.
8465 (TV->hasOneUse() || FV->hasOneUse())) {
8466 Constant *Elts[] = {
8467 const_cast<ConstantFP*>(FV->getConstantFPValue()),
8468 const_cast<ConstantFP*>(TV->getConstantFPValue())
8470 Type *FPTy = Elts[0]->getType();
8471 const TargetData &TD = *TLI.getTargetData();
8473 // Create a ConstantArray of the two constants.
8474 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
8475 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
8476 TD.getPrefTypeAlignment(FPTy));
8477 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8479 // Get the offsets to the 0 and 1 element of the array so that we can
8480 // select between them.
8481 SDValue Zero = DAG.getIntPtrConstant(0);
8482 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
8483 SDValue One = DAG.getIntPtrConstant(EltSize);
8485 SDValue Cond = DAG.getSetCC(DL,
8486 TLI.getSetCCResultType(N0.getValueType()),
8488 AddToWorkList(Cond.getNode());
8489 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
8491 AddToWorkList(CstOffset.getNode());
8492 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
8494 AddToWorkList(CPIdx.getNode());
8495 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
8496 MachinePointerInfo::getConstantPool(), false,
8497 false, false, Alignment);
8502 // Check to see if we can perform the "gzip trick", transforming
8503 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
8504 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
8505 (N1C->isNullValue() || // (a < 0) ? b : 0
8506 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
8507 EVT XType = N0.getValueType();
8508 EVT AType = N2.getValueType();
8509 if (XType.bitsGE(AType)) {
8510 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
8511 // single-bit constant.
8512 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
8513 unsigned ShCtV = N2C->getAPIntValue().logBase2();
8514 ShCtV = XType.getSizeInBits()-ShCtV-1;
8515 SDValue ShCt = DAG.getConstant(ShCtV,
8516 getShiftAmountTy(N0.getValueType()));
8517 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
8519 AddToWorkList(Shift.getNode());
8521 if (XType.bitsGT(AType)) {
8522 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8523 AddToWorkList(Shift.getNode());
8526 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8529 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
8531 DAG.getConstant(XType.getSizeInBits()-1,
8532 getShiftAmountTy(N0.getValueType())));
8533 AddToWorkList(Shift.getNode());
8535 if (XType.bitsGT(AType)) {
8536 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8537 AddToWorkList(Shift.getNode());
8540 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8544 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
8545 // where y is has a single bit set.
8546 // A plaintext description would be, we can turn the SELECT_CC into an AND
8547 // when the condition can be materialized as an all-ones register. Any
8548 // single bit-test can be materialized as an all-ones register with
8549 // shift-left and shift-right-arith.
8550 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
8551 N0->getValueType(0) == VT &&
8552 N1C && N1C->isNullValue() &&
8553 N2C && N2C->isNullValue()) {
8554 SDValue AndLHS = N0->getOperand(0);
8555 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8556 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
8557 // Shift the tested bit over the sign bit.
8558 APInt AndMask = ConstAndRHS->getAPIntValue();
8560 DAG.getConstant(AndMask.countLeadingZeros(),
8561 getShiftAmountTy(AndLHS.getValueType()));
8562 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
8564 // Now arithmetic right shift it all the way over, so the result is either
8565 // all-ones, or zero.
8567 DAG.getConstant(AndMask.getBitWidth()-1,
8568 getShiftAmountTy(Shl.getValueType()));
8569 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
8571 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
8575 // fold select C, 16, 0 -> shl C, 4
8576 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
8577 TLI.getBooleanContents(N0.getValueType().isVector()) ==
8578 TargetLowering::ZeroOrOneBooleanContent) {
8580 // If the caller doesn't want us to simplify this into a zext of a compare,
8582 if (NotExtCompare && N2C->getAPIntValue() == 1)
8585 // Get a SetCC of the condition
8586 // FIXME: Should probably make sure that setcc is legal if we ever have a
8587 // target where it isn't.
8589 // cast from setcc result type to select result type
8591 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
8593 if (N2.getValueType().bitsLT(SCC.getValueType()))
8594 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
8596 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8597 N2.getValueType(), SCC);
8599 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
8600 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8601 N2.getValueType(), SCC);
8604 AddToWorkList(SCC.getNode());
8605 AddToWorkList(Temp.getNode());
8607 if (N2C->getAPIntValue() == 1)
8610 // shl setcc result by log2 n2c
8611 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
8612 DAG.getConstant(N2C->getAPIntValue().logBase2(),
8613 getShiftAmountTy(Temp.getValueType())));
8616 // Check to see if this is the equivalent of setcc
8617 // FIXME: Turn all of these into setcc if setcc if setcc is legal
8618 // otherwise, go ahead with the folds.
8619 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
8620 EVT XType = N0.getValueType();
8621 if (!LegalOperations ||
8622 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
8623 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
8624 if (Res.getValueType() != VT)
8625 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
8629 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
8630 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
8631 (!LegalOperations ||
8632 TLI.isOperationLegal(ISD::CTLZ, XType))) {
8633 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
8634 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
8635 DAG.getConstant(Log2_32(XType.getSizeInBits()),
8636 getShiftAmountTy(Ctlz.getValueType())));
8638 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
8639 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
8640 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
8641 XType, DAG.getConstant(0, XType), N0);
8642 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
8643 return DAG.getNode(ISD::SRL, DL, XType,
8644 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
8645 DAG.getConstant(XType.getSizeInBits()-1,
8646 getShiftAmountTy(XType)));
8648 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
8649 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
8650 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
8651 DAG.getConstant(XType.getSizeInBits()-1,
8652 getShiftAmountTy(N0.getValueType())));
8653 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
8657 // Check to see if this is an integer abs.
8658 // select_cc setg[te] X, 0, X, -X ->
8659 // select_cc setgt X, -1, X, -X ->
8660 // select_cc setl[te] X, 0, -X, X ->
8661 // select_cc setlt X, 1, -X, X ->
8662 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8664 ConstantSDNode *SubC = NULL;
8665 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
8666 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
8667 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
8668 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
8669 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
8670 (N1C->isOne() && CC == ISD::SETLT)) &&
8671 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
8672 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
8674 EVT XType = N0.getValueType();
8675 if (SubC && SubC->isNullValue() && XType.isInteger()) {
8676 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
8678 DAG.getConstant(XType.getSizeInBits()-1,
8679 getShiftAmountTy(N0.getValueType())));
8680 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
8682 AddToWorkList(Shift.getNode());
8683 AddToWorkList(Add.getNode());
8684 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
8691 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
8692 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
8693 SDValue N1, ISD::CondCode Cond,
8694 DebugLoc DL, bool foldBooleans) {
8695 TargetLowering::DAGCombinerInfo
8696 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
8697 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
8700 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
8701 /// return a DAG expression to select that will generate the same value by
8702 /// multiplying by a magic number. See:
8703 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8704 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
8705 std::vector<SDNode*> Built;
8706 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
8708 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8714 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
8715 /// return a DAG expression to select that will generate the same value by
8716 /// multiplying by a magic number. See:
8717 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8718 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
8719 std::vector<SDNode*> Built;
8720 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
8722 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8728 /// FindBaseOffset - Return true if base is a frame index, which is known not
8729 // to alias with anything but itself. Provides base object and offset as
8731 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
8732 const GlobalValue *&GV, void *&CV) {
8733 // Assume it is a primitive operation.
8734 Base = Ptr; Offset = 0; GV = 0; CV = 0;
8736 // If it's an adding a simple constant then integrate the offset.
8737 if (Base.getOpcode() == ISD::ADD) {
8738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
8739 Base = Base.getOperand(0);
8740 Offset += C->getZExtValue();
8744 // Return the underlying GlobalValue, and update the Offset. Return false
8745 // for GlobalAddressSDNode since the same GlobalAddress may be represented
8746 // by multiple nodes with different offsets.
8747 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
8748 GV = G->getGlobal();
8749 Offset += G->getOffset();
8753 // Return the underlying Constant value, and update the Offset. Return false
8754 // for ConstantSDNodes since the same constant pool entry may be represented
8755 // by multiple nodes with different offsets.
8756 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
8757 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
8758 : (void *)C->getConstVal();
8759 Offset += C->getOffset();
8762 // If it's any of the following then it can't alias with anything but itself.
8763 return isa<FrameIndexSDNode>(Base);
8766 /// isAlias - Return true if there is any possibility that the two addresses
8768 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
8769 const Value *SrcValue1, int SrcValueOffset1,
8770 unsigned SrcValueAlign1,
8771 const MDNode *TBAAInfo1,
8772 SDValue Ptr2, int64_t Size2,
8773 const Value *SrcValue2, int SrcValueOffset2,
8774 unsigned SrcValueAlign2,
8775 const MDNode *TBAAInfo2) const {
8776 // If they are the same then they must be aliases.
8777 if (Ptr1 == Ptr2) return true;
8779 // Gather base node and offset information.
8780 SDValue Base1, Base2;
8781 int64_t Offset1, Offset2;
8782 const GlobalValue *GV1, *GV2;
8784 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
8785 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
8787 // If they have a same base address then check to see if they overlap.
8788 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
8789 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8791 // It is possible for different frame indices to alias each other, mostly
8792 // when tail call optimization reuses return address slots for arguments.
8793 // To catch this case, look up the actual index of frame indices to compute
8794 // the real alias relationship.
8795 if (isFrameIndex1 && isFrameIndex2) {
8796 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8797 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
8798 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
8799 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8802 // Otherwise, if we know what the bases are, and they aren't identical, then
8803 // we know they cannot alias.
8804 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
8807 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
8808 // compared to the size and offset of the access, we may be able to prove they
8809 // do not alias. This check is conservative for now to catch cases created by
8810 // splitting vector types.
8811 if ((SrcValueAlign1 == SrcValueAlign2) &&
8812 (SrcValueOffset1 != SrcValueOffset2) &&
8813 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
8814 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
8815 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
8817 // There is no overlap between these relatively aligned accesses of similar
8818 // size, return no alias.
8819 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
8823 if (CombinerGlobalAA) {
8824 // Use alias analysis information.
8825 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
8826 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
8827 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
8828 AliasAnalysis::AliasResult AAResult =
8829 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
8830 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
8831 if (AAResult == AliasAnalysis::NoAlias)
8835 // Otherwise we have to assume they alias.
8839 /// FindAliasInfo - Extracts the relevant alias information from the memory
8840 /// node. Returns true if the operand was a load.
8841 bool DAGCombiner::FindAliasInfo(SDNode *N,
8842 SDValue &Ptr, int64_t &Size,
8843 const Value *&SrcValue,
8844 int &SrcValueOffset,
8845 unsigned &SrcValueAlign,
8846 const MDNode *&TBAAInfo) const {
8847 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
8849 Ptr = LS->getBasePtr();
8850 Size = LS->getMemoryVT().getSizeInBits() >> 3;
8851 SrcValue = LS->getSrcValue();
8852 SrcValueOffset = LS->getSrcValueOffset();
8853 SrcValueAlign = LS->getOriginalAlignment();
8854 TBAAInfo = LS->getTBAAInfo();
8855 return isa<LoadSDNode>(LS);
8858 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8859 /// looking for aliasing nodes and adding them to the Aliases vector.
8860 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8861 SmallVector<SDValue, 8> &Aliases) {
8862 SmallVector<SDValue, 8> Chains; // List of chains to visit.
8863 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
8865 // Get alias information for node.
8868 const Value *SrcValue;
8870 unsigned SrcValueAlign;
8871 const MDNode *SrcTBAAInfo;
8872 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8873 SrcValueAlign, SrcTBAAInfo);
8876 Chains.push_back(OriginalChain);
8879 // Look at each chain and determine if it is an alias. If so, add it to the
8880 // aliases list. If not, then continue up the chain looking for the next
8882 while (!Chains.empty()) {
8883 SDValue Chain = Chains.back();
8886 // For TokenFactor nodes, look at each operand and only continue up the
8887 // chain until we find two aliases. If we've seen two aliases, assume we'll
8888 // find more and revert to original chain since the xform is unlikely to be
8891 // FIXME: The depth check could be made to return the last non-aliasing
8892 // chain we found before we hit a tokenfactor rather than the original
8894 if (Depth > 6 || Aliases.size() == 2) {
8896 Aliases.push_back(OriginalChain);
8900 // Don't bother if we've been before.
8901 if (!Visited.insert(Chain.getNode()))
8904 switch (Chain.getOpcode()) {
8905 case ISD::EntryToken:
8906 // Entry token is ideal chain operand, but handled in FindBetterChain.
8911 // Get alias information for Chain.
8914 const Value *OpSrcValue;
8915 int OpSrcValueOffset;
8916 unsigned OpSrcValueAlign;
8917 const MDNode *OpSrcTBAAInfo;
8918 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8919 OpSrcValue, OpSrcValueOffset,
8923 // If chain is alias then stop here.
8924 if (!(IsLoad && IsOpLoad) &&
8925 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8927 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8928 OpSrcValueAlign, OpSrcTBAAInfo)) {
8929 Aliases.push_back(Chain);
8931 // Look further up the chain.
8932 Chains.push_back(Chain.getOperand(0));
8938 case ISD::TokenFactor:
8939 // We have to check each of the operands of the token factor for "small"
8940 // token factors, so we queue them up. Adding the operands to the queue
8941 // (stack) in reverse order maintains the original order and increases the
8942 // likelihood that getNode will find a matching token factor (CSE.)
8943 if (Chain.getNumOperands() > 16) {
8944 Aliases.push_back(Chain);
8947 for (unsigned n = Chain.getNumOperands(); n;)
8948 Chains.push_back(Chain.getOperand(--n));
8953 // For all other instructions we will just have to take what we can get.
8954 Aliases.push_back(Chain);
8960 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8961 /// for a better chain (aliasing node.)
8962 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8963 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
8965 // Accumulate all the aliases to this node.
8966 GatherAllAliases(N, OldChain, Aliases);
8968 // If no operands then chain to entry token.
8969 if (Aliases.size() == 0)
8970 return DAG.getEntryNode();
8972 // If a single operand then chain to it. We don't need to revisit it.
8973 if (Aliases.size() == 1)
8976 // Construct a custom tailored token factor.
8977 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8978 &Aliases[0], Aliases.size());
8981 // SelectionDAG::Combine - This is the entry point for the file.
8983 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8984 CodeGenOpt::Level OptLevel) {
8985 /// run - This is the main entry point to this class.
8987 DAGCombiner(*this, AA, OptLevel).Run(Level);