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 visitBRCOND(SDNode *N);
232 SDValue visitBR_CC(SDNode *N);
233 SDValue visitLOAD(SDNode *N);
234 SDValue visitSTORE(SDNode *N);
235 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
236 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
237 SDValue visitBUILD_VECTOR(SDNode *N);
238 SDValue visitCONCAT_VECTORS(SDNode *N);
239 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
240 SDValue visitVECTOR_SHUFFLE(SDNode *N);
241 SDValue visitMEMBARRIER(SDNode *N);
243 SDValue XformToShuffleWithZero(SDNode *N);
244 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
246 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
248 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
249 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
250 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
251 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
252 SDValue N3, ISD::CondCode CC,
253 bool NotExtCompare = false);
254 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
255 DebugLoc DL, bool foldBooleans = true);
256 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
258 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
259 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
260 SDValue BuildSDIV(SDNode *N);
261 SDValue BuildUDIV(SDNode *N);
262 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
263 bool DemandHighBits = true);
264 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
265 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
266 SDValue ReduceLoadWidth(SDNode *N);
267 SDValue ReduceLoadOpStoreWidth(SDNode *N);
268 SDValue TransformFPLoadStorePair(SDNode *N);
270 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
272 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
273 /// looking for aliasing nodes and adding them to the Aliases vector.
274 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
275 SmallVector<SDValue, 8> &Aliases);
277 /// isAlias - Return true if there is any possibility that the two addresses
279 bool isAlias(SDValue Ptr1, int64_t Size1,
280 const Value *SrcValue1, int SrcValueOffset1,
281 unsigned SrcValueAlign1,
282 const MDNode *TBAAInfo1,
283 SDValue Ptr2, int64_t Size2,
284 const Value *SrcValue2, int SrcValueOffset2,
285 unsigned SrcValueAlign2,
286 const MDNode *TBAAInfo2) const;
288 /// FindAliasInfo - Extracts the relevant alias information from the memory
289 /// node. Returns true if the operand was a load.
290 bool FindAliasInfo(SDNode *N,
291 SDValue &Ptr, int64_t &Size,
292 const Value *&SrcValue, int &SrcValueOffset,
293 unsigned &SrcValueAlignment,
294 const MDNode *&TBAAInfo) const;
296 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
297 /// looking for a better chain (aliasing node.)
298 SDValue FindBetterChain(SDNode *N, SDValue Chain);
301 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
302 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
303 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
305 /// Run - runs the dag combiner on all nodes in the work list
306 void Run(CombineLevel AtLevel);
308 SelectionDAG &getDAG() const { return DAG; }
310 /// getShiftAmountTy - Returns a type large enough to hold any valid
311 /// shift amount - before type legalization these can be huge.
312 EVT getShiftAmountTy(EVT LHSTy) {
313 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
316 /// isTypeLegal - This method returns true if we are running before type
317 /// legalization or if the specified VT is legal.
318 bool isTypeLegal(const EVT &VT) {
319 if (!LegalTypes) return true;
320 return TLI.isTypeLegal(VT);
327 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
328 /// nodes from the worklist.
329 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
332 explicit WorkListRemover(DAGCombiner &dc)
333 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
335 virtual void NodeDeleted(SDNode *N, SDNode *E) {
336 DC.removeFromWorkList(N);
341 //===----------------------------------------------------------------------===//
342 // TargetLowering::DAGCombinerInfo implementation
343 //===----------------------------------------------------------------------===//
345 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
346 ((DAGCombiner*)DC)->AddToWorkList(N);
349 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
350 ((DAGCombiner*)DC)->removeFromWorkList(N);
353 SDValue TargetLowering::DAGCombinerInfo::
354 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
355 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
358 SDValue TargetLowering::DAGCombinerInfo::
359 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
360 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
364 SDValue TargetLowering::DAGCombinerInfo::
365 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
366 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
369 void TargetLowering::DAGCombinerInfo::
370 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
371 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
374 //===----------------------------------------------------------------------===//
376 //===----------------------------------------------------------------------===//
378 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
379 /// specified expression for the same cost as the expression itself, or 2 if we
380 /// can compute the negated form more cheaply than the expression itself.
381 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
382 const TargetLowering &TLI,
383 const TargetOptions *Options,
384 unsigned Depth = 0) {
385 // No compile time optimizations on this type.
386 if (Op.getValueType() == MVT::ppcf128)
389 // fneg is removable even if it has multiple uses.
390 if (Op.getOpcode() == ISD::FNEG) return 2;
392 // Don't allow anything with multiple uses.
393 if (!Op.hasOneUse()) return 0;
395 // Don't recurse exponentially.
396 if (Depth > 6) return 0;
398 switch (Op.getOpcode()) {
399 default: return false;
400 case ISD::ConstantFP:
401 // Don't invert constant FP values after legalize. The negated constant
402 // isn't necessarily legal.
403 return LegalOperations ? 0 : 1;
405 // FIXME: determine better conditions for this xform.
406 if (!Options->UnsafeFPMath) return 0;
408 // After operation legalization, it might not be legal to create new FSUBs.
409 if (LegalOperations &&
410 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
413 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
414 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
417 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
418 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
421 // We can't turn -(A-B) into B-A when we honor signed zeros.
422 if (!Options->UnsafeFPMath) return 0;
424 // fold (fneg (fsub A, B)) -> (fsub B, A)
429 if (Options->HonorSignDependentRoundingFPMath()) return 0;
431 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
432 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
436 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
442 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
447 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
448 /// returns the newly negated expression.
449 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
450 bool LegalOperations, unsigned Depth = 0) {
451 // fneg is removable even if it has multiple uses.
452 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
454 // Don't allow anything with multiple uses.
455 assert(Op.hasOneUse() && "Unknown reuse!");
457 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
458 switch (Op.getOpcode()) {
459 default: llvm_unreachable("Unknown code");
460 case ISD::ConstantFP: {
461 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
463 return DAG.getConstantFP(V, Op.getValueType());
466 // FIXME: determine better conditions for this xform.
467 assert(DAG.getTarget().Options.UnsafeFPMath);
469 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
470 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
471 DAG.getTargetLoweringInfo(),
472 &DAG.getTarget().Options, Depth+1))
473 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
474 GetNegatedExpression(Op.getOperand(0), DAG,
475 LegalOperations, Depth+1),
477 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
478 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
479 GetNegatedExpression(Op.getOperand(1), DAG,
480 LegalOperations, Depth+1),
483 // We can't turn -(A-B) into B-A when we honor signed zeros.
484 assert(DAG.getTarget().Options.UnsafeFPMath);
486 // fold (fneg (fsub 0, B)) -> B
487 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
488 if (N0CFP->getValueAPF().isZero())
489 return Op.getOperand(1);
491 // fold (fneg (fsub A, B)) -> (fsub B, A)
492 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
493 Op.getOperand(1), Op.getOperand(0));
497 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
499 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
500 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
501 DAG.getTargetLoweringInfo(),
502 &DAG.getTarget().Options, Depth+1))
503 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
504 GetNegatedExpression(Op.getOperand(0), DAG,
505 LegalOperations, Depth+1),
508 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
509 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
511 GetNegatedExpression(Op.getOperand(1), DAG,
512 LegalOperations, Depth+1));
516 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
517 GetNegatedExpression(Op.getOperand(0), DAG,
518 LegalOperations, Depth+1));
520 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
521 GetNegatedExpression(Op.getOperand(0), DAG,
522 LegalOperations, Depth+1),
528 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
529 // that selects between the values 1 and 0, making it equivalent to a setcc.
530 // Also, set the incoming LHS, RHS, and CC references to the appropriate
531 // nodes based on the type of node we are checking. This simplifies life a
532 // bit for the callers.
533 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
535 if (N.getOpcode() == ISD::SETCC) {
536 LHS = N.getOperand(0);
537 RHS = N.getOperand(1);
538 CC = N.getOperand(2);
541 if (N.getOpcode() == ISD::SELECT_CC &&
542 N.getOperand(2).getOpcode() == ISD::Constant &&
543 N.getOperand(3).getOpcode() == ISD::Constant &&
544 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
545 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
546 LHS = N.getOperand(0);
547 RHS = N.getOperand(1);
548 CC = N.getOperand(4);
554 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
555 // one use. If this is true, it allows the users to invert the operation for
556 // free when it is profitable to do so.
557 static bool isOneUseSetCC(SDValue N) {
559 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
564 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
565 SDValue N0, SDValue N1) {
566 EVT VT = N0.getValueType();
567 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
568 if (isa<ConstantSDNode>(N1)) {
569 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
571 DAG.FoldConstantArithmetic(Opc, VT,
572 cast<ConstantSDNode>(N0.getOperand(1)),
573 cast<ConstantSDNode>(N1));
574 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
576 if (N0.hasOneUse()) {
577 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
578 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
579 N0.getOperand(0), N1);
580 AddToWorkList(OpNode.getNode());
581 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
585 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
586 if (isa<ConstantSDNode>(N0)) {
587 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
589 DAG.FoldConstantArithmetic(Opc, VT,
590 cast<ConstantSDNode>(N1.getOperand(1)),
591 cast<ConstantSDNode>(N0));
592 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
594 if (N1.hasOneUse()) {
595 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
596 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
597 N1.getOperand(0), N0);
598 AddToWorkList(OpNode.getNode());
599 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
606 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
608 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
610 DEBUG(dbgs() << "\nReplacing.1 ";
612 dbgs() << "\nWith: ";
613 To[0].getNode()->dump(&DAG);
614 dbgs() << " and " << NumTo-1 << " other values\n";
615 for (unsigned i = 0, e = NumTo; i != e; ++i)
616 assert((!To[i].getNode() ||
617 N->getValueType(i) == To[i].getValueType()) &&
618 "Cannot combine value to value of different type!"));
619 WorkListRemover DeadNodes(*this);
620 DAG.ReplaceAllUsesWith(N, To);
622 // Push the new nodes and any users onto the worklist
623 for (unsigned i = 0, e = NumTo; i != e; ++i) {
624 if (To[i].getNode()) {
625 AddToWorkList(To[i].getNode());
626 AddUsersToWorkList(To[i].getNode());
631 // Finally, if the node is now dead, remove it from the graph. The node
632 // may not be dead if the replacement process recursively simplified to
633 // something else needing this node.
634 if (N->use_empty()) {
635 // Nodes can be reintroduced into the worklist. Make sure we do not
636 // process a node that has been replaced.
637 removeFromWorkList(N);
639 // Finally, since the node is now dead, remove it from the graph.
642 return SDValue(N, 0);
646 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
647 // Replace all uses. If any nodes become isomorphic to other nodes and
648 // are deleted, make sure to remove them from our worklist.
649 WorkListRemover DeadNodes(*this);
650 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
652 // Push the new node and any (possibly new) users onto the worklist.
653 AddToWorkList(TLO.New.getNode());
654 AddUsersToWorkList(TLO.New.getNode());
656 // Finally, if the node is now dead, remove it from the graph. The node
657 // may not be dead if the replacement process recursively simplified to
658 // something else needing this node.
659 if (TLO.Old.getNode()->use_empty()) {
660 removeFromWorkList(TLO.Old.getNode());
662 // If the operands of this node are only used by the node, they will now
663 // be dead. Make sure to visit them first to delete dead nodes early.
664 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
665 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
666 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
668 DAG.DeleteNode(TLO.Old.getNode());
672 /// SimplifyDemandedBits - Check the specified integer node value to see if
673 /// it can be simplified or if things it uses can be simplified by bit
674 /// propagation. If so, return true.
675 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
676 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
677 APInt KnownZero, KnownOne;
678 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
682 AddToWorkList(Op.getNode());
684 // Replace the old value with the new one.
686 DEBUG(dbgs() << "\nReplacing.2 ";
687 TLO.Old.getNode()->dump(&DAG);
688 dbgs() << "\nWith: ";
689 TLO.New.getNode()->dump(&DAG);
692 CommitTargetLoweringOpt(TLO);
696 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
697 DebugLoc dl = Load->getDebugLoc();
698 EVT VT = Load->getValueType(0);
699 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
701 DEBUG(dbgs() << "\nReplacing.9 ";
703 dbgs() << "\nWith: ";
704 Trunc.getNode()->dump(&DAG);
706 WorkListRemover DeadNodes(*this);
707 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
708 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
709 removeFromWorkList(Load);
710 DAG.DeleteNode(Load);
711 AddToWorkList(Trunc.getNode());
714 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
716 DebugLoc dl = Op.getDebugLoc();
717 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
718 EVT MemVT = LD->getMemoryVT();
719 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
720 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
722 : LD->getExtensionType();
724 return DAG.getExtLoad(ExtType, dl, PVT,
725 LD->getChain(), LD->getBasePtr(),
726 LD->getPointerInfo(),
727 MemVT, LD->isVolatile(),
728 LD->isNonTemporal(), LD->getAlignment());
731 unsigned Opc = Op.getOpcode();
734 case ISD::AssertSext:
735 return DAG.getNode(ISD::AssertSext, dl, PVT,
736 SExtPromoteOperand(Op.getOperand(0), PVT),
738 case ISD::AssertZext:
739 return DAG.getNode(ISD::AssertZext, dl, PVT,
740 ZExtPromoteOperand(Op.getOperand(0), PVT),
742 case ISD::Constant: {
744 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
745 return DAG.getNode(ExtOpc, dl, PVT, Op);
749 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
751 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
754 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
755 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
757 EVT OldVT = Op.getValueType();
758 DebugLoc dl = Op.getDebugLoc();
759 bool Replace = false;
760 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
761 if (NewOp.getNode() == 0)
763 AddToWorkList(NewOp.getNode());
766 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
767 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
768 DAG.getValueType(OldVT));
771 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
772 EVT OldVT = Op.getValueType();
773 DebugLoc dl = Op.getDebugLoc();
774 bool Replace = false;
775 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
776 if (NewOp.getNode() == 0)
778 AddToWorkList(NewOp.getNode());
781 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
782 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
785 /// PromoteIntBinOp - Promote the specified integer binary operation if the
786 /// target indicates it is beneficial. e.g. On x86, it's usually better to
787 /// promote i16 operations to i32 since i16 instructions are longer.
788 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
789 if (!LegalOperations)
792 EVT VT = Op.getValueType();
793 if (VT.isVector() || !VT.isInteger())
796 // If operation type is 'undesirable', e.g. i16 on x86, consider
798 unsigned Opc = Op.getOpcode();
799 if (TLI.isTypeDesirableForOp(Opc, VT))
803 // Consult target whether it is a good idea to promote this operation and
804 // what's the right type to promote it to.
805 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
806 assert(PVT != VT && "Don't know what type to promote to!");
808 bool Replace0 = false;
809 SDValue N0 = Op.getOperand(0);
810 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
811 if (NN0.getNode() == 0)
814 bool Replace1 = false;
815 SDValue N1 = Op.getOperand(1);
820 NN1 = PromoteOperand(N1, PVT, Replace1);
821 if (NN1.getNode() == 0)
825 AddToWorkList(NN0.getNode());
827 AddToWorkList(NN1.getNode());
830 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
832 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
834 DEBUG(dbgs() << "\nPromoting ";
835 Op.getNode()->dump(&DAG));
836 DebugLoc dl = Op.getDebugLoc();
837 return DAG.getNode(ISD::TRUNCATE, dl, VT,
838 DAG.getNode(Opc, dl, PVT, NN0, NN1));
843 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
844 /// target indicates it is beneficial. e.g. On x86, it's usually better to
845 /// promote i16 operations to i32 since i16 instructions are longer.
846 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
847 if (!LegalOperations)
850 EVT VT = Op.getValueType();
851 if (VT.isVector() || !VT.isInteger())
854 // If operation type is 'undesirable', e.g. i16 on x86, consider
856 unsigned Opc = Op.getOpcode();
857 if (TLI.isTypeDesirableForOp(Opc, VT))
861 // Consult target whether it is a good idea to promote this operation and
862 // what's the right type to promote it to.
863 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
864 assert(PVT != VT && "Don't know what type to promote to!");
866 bool Replace = false;
867 SDValue N0 = Op.getOperand(0);
869 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
870 else if (Opc == ISD::SRL)
871 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
873 N0 = PromoteOperand(N0, PVT, Replace);
874 if (N0.getNode() == 0)
877 AddToWorkList(N0.getNode());
879 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
881 DEBUG(dbgs() << "\nPromoting ";
882 Op.getNode()->dump(&DAG));
883 DebugLoc dl = Op.getDebugLoc();
884 return DAG.getNode(ISD::TRUNCATE, dl, VT,
885 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
890 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
891 if (!LegalOperations)
894 EVT VT = Op.getValueType();
895 if (VT.isVector() || !VT.isInteger())
898 // If operation type is 'undesirable', e.g. i16 on x86, consider
900 unsigned Opc = Op.getOpcode();
901 if (TLI.isTypeDesirableForOp(Opc, VT))
905 // Consult target whether it is a good idea to promote this operation and
906 // what's the right type to promote it to.
907 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908 assert(PVT != VT && "Don't know what type to promote to!");
909 // fold (aext (aext x)) -> (aext x)
910 // fold (aext (zext x)) -> (zext x)
911 // fold (aext (sext x)) -> (sext x)
912 DEBUG(dbgs() << "\nPromoting ";
913 Op.getNode()->dump(&DAG));
914 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
919 bool DAGCombiner::PromoteLoad(SDValue Op) {
920 if (!LegalOperations)
923 EVT VT = Op.getValueType();
924 if (VT.isVector() || !VT.isInteger())
927 // If operation type is 'undesirable', e.g. i16 on x86, consider
929 unsigned Opc = Op.getOpcode();
930 if (TLI.isTypeDesirableForOp(Opc, VT))
934 // Consult target whether it is a good idea to promote this operation and
935 // what's the right type to promote it to.
936 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
937 assert(PVT != VT && "Don't know what type to promote to!");
939 DebugLoc dl = Op.getDebugLoc();
940 SDNode *N = Op.getNode();
941 LoadSDNode *LD = cast<LoadSDNode>(N);
942 EVT MemVT = LD->getMemoryVT();
943 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
944 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
946 : LD->getExtensionType();
947 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
948 LD->getChain(), LD->getBasePtr(),
949 LD->getPointerInfo(),
950 MemVT, LD->isVolatile(),
951 LD->isNonTemporal(), LD->getAlignment());
952 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
954 DEBUG(dbgs() << "\nPromoting ";
957 Result.getNode()->dump(&DAG);
959 WorkListRemover DeadNodes(*this);
960 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
961 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
962 removeFromWorkList(N);
964 AddToWorkList(Result.getNode());
971 //===----------------------------------------------------------------------===//
972 // Main DAG Combiner implementation
973 //===----------------------------------------------------------------------===//
975 void DAGCombiner::Run(CombineLevel AtLevel) {
976 // set the instance variables, so that the various visit routines may use it.
978 LegalOperations = Level >= AfterLegalizeVectorOps;
979 LegalTypes = Level >= AfterLegalizeTypes;
981 // Add all the dag nodes to the worklist.
982 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
983 E = DAG.allnodes_end(); I != E; ++I)
986 // Create a dummy node (which is not added to allnodes), that adds a reference
987 // to the root node, preventing it from being deleted, and tracking any
988 // changes of the root.
989 HandleSDNode Dummy(DAG.getRoot());
991 // The root of the dag may dangle to deleted nodes until the dag combiner is
992 // done. Set it to null to avoid confusion.
993 DAG.setRoot(SDValue());
995 // while the worklist isn't empty, find a node and
996 // try and combine it.
997 while (!WorkListContents.empty()) {
999 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1000 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1001 // worklist *should* contain, and check the node we want to visit is should
1002 // actually be visited.
1004 N = WorkListOrder.pop_back_val();
1005 } while (!WorkListContents.erase(N));
1007 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1008 // N is deleted from the DAG, since they too may now be dead or may have a
1009 // reduced number of uses, allowing other xforms.
1010 if (N->use_empty() && N != &Dummy) {
1011 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1012 AddToWorkList(N->getOperand(i).getNode());
1018 SDValue RV = combine(N);
1020 if (RV.getNode() == 0)
1025 // If we get back the same node we passed in, rather than a new node or
1026 // zero, we know that the node must have defined multiple values and
1027 // CombineTo was used. Since CombineTo takes care of the worklist
1028 // mechanics for us, we have no work to do in this case.
1029 if (RV.getNode() == N)
1032 assert(N->getOpcode() != ISD::DELETED_NODE &&
1033 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1034 "Node was deleted but visit returned new node!");
1036 DEBUG(dbgs() << "\nReplacing.3 ";
1038 dbgs() << "\nWith: ";
1039 RV.getNode()->dump(&DAG);
1042 // Transfer debug value.
1043 DAG.TransferDbgValues(SDValue(N, 0), RV);
1044 WorkListRemover DeadNodes(*this);
1045 if (N->getNumValues() == RV.getNode()->getNumValues())
1046 DAG.ReplaceAllUsesWith(N, RV.getNode());
1048 assert(N->getValueType(0) == RV.getValueType() &&
1049 N->getNumValues() == 1 && "Type mismatch");
1051 DAG.ReplaceAllUsesWith(N, &OpV);
1054 // Push the new node and any users onto the worklist
1055 AddToWorkList(RV.getNode());
1056 AddUsersToWorkList(RV.getNode());
1058 // Add any uses of the old node to the worklist in case this node is the
1059 // last one that uses them. They may become dead after this node is
1061 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1062 AddToWorkList(N->getOperand(i).getNode());
1064 // Finally, if the node is now dead, remove it from the graph. The node
1065 // may not be dead if the replacement process recursively simplified to
1066 // something else needing this node.
1067 if (N->use_empty()) {
1068 // Nodes can be reintroduced into the worklist. Make sure we do not
1069 // process a node that has been replaced.
1070 removeFromWorkList(N);
1072 // Finally, since the node is now dead, remove it from the graph.
1077 // If the root changed (e.g. it was a dead load, update the root).
1078 DAG.setRoot(Dummy.getValue());
1079 DAG.RemoveDeadNodes();
1082 SDValue DAGCombiner::visit(SDNode *N) {
1083 switch (N->getOpcode()) {
1085 case ISD::TokenFactor: return visitTokenFactor(N);
1086 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1087 case ISD::ADD: return visitADD(N);
1088 case ISD::SUB: return visitSUB(N);
1089 case ISD::ADDC: return visitADDC(N);
1090 case ISD::SUBC: return visitSUBC(N);
1091 case ISD::ADDE: return visitADDE(N);
1092 case ISD::SUBE: return visitSUBE(N);
1093 case ISD::MUL: return visitMUL(N);
1094 case ISD::SDIV: return visitSDIV(N);
1095 case ISD::UDIV: return visitUDIV(N);
1096 case ISD::SREM: return visitSREM(N);
1097 case ISD::UREM: return visitUREM(N);
1098 case ISD::MULHU: return visitMULHU(N);
1099 case ISD::MULHS: return visitMULHS(N);
1100 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1101 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1102 case ISD::SMULO: return visitSMULO(N);
1103 case ISD::UMULO: return visitUMULO(N);
1104 case ISD::SDIVREM: return visitSDIVREM(N);
1105 case ISD::UDIVREM: return visitUDIVREM(N);
1106 case ISD::AND: return visitAND(N);
1107 case ISD::OR: return visitOR(N);
1108 case ISD::XOR: return visitXOR(N);
1109 case ISD::SHL: return visitSHL(N);
1110 case ISD::SRA: return visitSRA(N);
1111 case ISD::SRL: return visitSRL(N);
1112 case ISD::CTLZ: return visitCTLZ(N);
1113 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1114 case ISD::CTTZ: return visitCTTZ(N);
1115 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1116 case ISD::CTPOP: return visitCTPOP(N);
1117 case ISD::SELECT: return visitSELECT(N);
1118 case ISD::SELECT_CC: return visitSELECT_CC(N);
1119 case ISD::SETCC: return visitSETCC(N);
1120 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1121 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1122 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1123 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1124 case ISD::TRUNCATE: return visitTRUNCATE(N);
1125 case ISD::BITCAST: return visitBITCAST(N);
1126 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1127 case ISD::FADD: return visitFADD(N);
1128 case ISD::FSUB: return visitFSUB(N);
1129 case ISD::FMUL: return visitFMUL(N);
1130 case ISD::FMA: return visitFMA(N);
1131 case ISD::FDIV: return visitFDIV(N);
1132 case ISD::FREM: return visitFREM(N);
1133 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1134 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1135 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1136 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1137 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1138 case ISD::FP_ROUND: return visitFP_ROUND(N);
1139 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1140 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1141 case ISD::FNEG: return visitFNEG(N);
1142 case ISD::FABS: return visitFABS(N);
1143 case ISD::BRCOND: return visitBRCOND(N);
1144 case ISD::BR_CC: return visitBR_CC(N);
1145 case ISD::LOAD: return visitLOAD(N);
1146 case ISD::STORE: return visitSTORE(N);
1147 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1148 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1149 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1150 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1151 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1152 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1153 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1158 SDValue DAGCombiner::combine(SDNode *N) {
1159 SDValue RV = visit(N);
1161 // If nothing happened, try a target-specific DAG combine.
1162 if (RV.getNode() == 0) {
1163 assert(N->getOpcode() != ISD::DELETED_NODE &&
1164 "Node was deleted but visit returned NULL!");
1166 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1167 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1169 // Expose the DAG combiner to the target combiner impls.
1170 TargetLowering::DAGCombinerInfo
1171 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1173 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1177 // If nothing happened still, try promoting the operation.
1178 if (RV.getNode() == 0) {
1179 switch (N->getOpcode()) {
1187 RV = PromoteIntBinOp(SDValue(N, 0));
1192 RV = PromoteIntShiftOp(SDValue(N, 0));
1194 case ISD::SIGN_EXTEND:
1195 case ISD::ZERO_EXTEND:
1196 case ISD::ANY_EXTEND:
1197 RV = PromoteExtend(SDValue(N, 0));
1200 if (PromoteLoad(SDValue(N, 0)))
1206 // If N is a commutative binary node, try commuting it to enable more
1208 if (RV.getNode() == 0 &&
1209 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1210 N->getNumValues() == 1) {
1211 SDValue N0 = N->getOperand(0);
1212 SDValue N1 = N->getOperand(1);
1214 // Constant operands are canonicalized to RHS.
1215 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1216 SDValue Ops[] = { N1, N0 };
1217 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1220 return SDValue(CSENode, 0);
1227 /// getInputChainForNode - Given a node, return its input chain if it has one,
1228 /// otherwise return a null sd operand.
1229 static SDValue getInputChainForNode(SDNode *N) {
1230 if (unsigned NumOps = N->getNumOperands()) {
1231 if (N->getOperand(0).getValueType() == MVT::Other)
1232 return N->getOperand(0);
1233 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1234 return N->getOperand(NumOps-1);
1235 for (unsigned i = 1; i < NumOps-1; ++i)
1236 if (N->getOperand(i).getValueType() == MVT::Other)
1237 return N->getOperand(i);
1242 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1243 // If N has two operands, where one has an input chain equal to the other,
1244 // the 'other' chain is redundant.
1245 if (N->getNumOperands() == 2) {
1246 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1247 return N->getOperand(0);
1248 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1249 return N->getOperand(1);
1252 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1253 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1254 SmallPtrSet<SDNode*, 16> SeenOps;
1255 bool Changed = false; // If we should replace this token factor.
1257 // Start out with this token factor.
1260 // Iterate through token factors. The TFs grows when new token factors are
1262 for (unsigned i = 0; i < TFs.size(); ++i) {
1263 SDNode *TF = TFs[i];
1265 // Check each of the operands.
1266 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1267 SDValue Op = TF->getOperand(i);
1269 switch (Op.getOpcode()) {
1270 case ISD::EntryToken:
1271 // Entry tokens don't need to be added to the list. They are
1276 case ISD::TokenFactor:
1277 if (Op.hasOneUse() &&
1278 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1279 // Queue up for processing.
1280 TFs.push_back(Op.getNode());
1281 // Clean up in case the token factor is removed.
1282 AddToWorkList(Op.getNode());
1289 // Only add if it isn't already in the list.
1290 if (SeenOps.insert(Op.getNode()))
1301 // If we've change things around then replace token factor.
1304 // The entry token is the only possible outcome.
1305 Result = DAG.getEntryNode();
1307 // New and improved token factor.
1308 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1309 MVT::Other, &Ops[0], Ops.size());
1312 // Don't add users to work list.
1313 return CombineTo(N, Result, false);
1319 /// MERGE_VALUES can always be eliminated.
1320 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1321 WorkListRemover DeadNodes(*this);
1322 // Replacing results may cause a different MERGE_VALUES to suddenly
1323 // be CSE'd with N, and carry its uses with it. Iterate until no
1324 // uses remain, to ensure that the node can be safely deleted.
1325 // First add the users of this node to the work list so that they
1326 // can be tried again once they have new operands.
1327 AddUsersToWorkList(N);
1329 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1330 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1331 } while (!N->use_empty());
1332 removeFromWorkList(N);
1334 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1338 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1339 SelectionDAG &DAG) {
1340 EVT VT = N0.getValueType();
1341 SDValue N00 = N0.getOperand(0);
1342 SDValue N01 = N0.getOperand(1);
1343 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1345 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1346 isa<ConstantSDNode>(N00.getOperand(1))) {
1347 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1348 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1349 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1350 N00.getOperand(0), N01),
1351 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1352 N00.getOperand(1), N01));
1353 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1359 SDValue DAGCombiner::visitADD(SDNode *N) {
1360 SDValue N0 = N->getOperand(0);
1361 SDValue N1 = N->getOperand(1);
1362 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1363 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1364 EVT VT = N0.getValueType();
1367 if (VT.isVector()) {
1368 SDValue FoldedVOp = SimplifyVBinOp(N);
1369 if (FoldedVOp.getNode()) return FoldedVOp;
1372 // fold (add x, undef) -> undef
1373 if (N0.getOpcode() == ISD::UNDEF)
1375 if (N1.getOpcode() == ISD::UNDEF)
1377 // fold (add c1, c2) -> c1+c2
1379 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1380 // canonicalize constant to RHS
1382 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1383 // fold (add x, 0) -> x
1384 if (N1C && N1C->isNullValue())
1386 // fold (add Sym, c) -> Sym+c
1387 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1388 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1389 GA->getOpcode() == ISD::GlobalAddress)
1390 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1392 (uint64_t)N1C->getSExtValue());
1393 // fold ((c1-A)+c2) -> (c1+c2)-A
1394 if (N1C && N0.getOpcode() == ISD::SUB)
1395 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1396 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1397 DAG.getConstant(N1C->getAPIntValue()+
1398 N0C->getAPIntValue(), VT),
1401 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1402 if (RADD.getNode() != 0)
1404 // fold ((0-A) + B) -> B-A
1405 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1406 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1407 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1408 // fold (A + (0-B)) -> A-B
1409 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1410 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1411 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1412 // fold (A+(B-A)) -> B
1413 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1414 return N1.getOperand(0);
1415 // fold ((B-A)+A) -> B
1416 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1417 return N0.getOperand(0);
1418 // fold (A+(B-(A+C))) to (B-C)
1419 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1420 N0 == N1.getOperand(1).getOperand(0))
1421 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1422 N1.getOperand(1).getOperand(1));
1423 // fold (A+(B-(C+A))) to (B-C)
1424 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1425 N0 == N1.getOperand(1).getOperand(1))
1426 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1427 N1.getOperand(1).getOperand(0));
1428 // fold (A+((B-A)+or-C)) to (B+or-C)
1429 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1430 N1.getOperand(0).getOpcode() == ISD::SUB &&
1431 N0 == N1.getOperand(0).getOperand(1))
1432 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1433 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1435 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1436 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1437 SDValue N00 = N0.getOperand(0);
1438 SDValue N01 = N0.getOperand(1);
1439 SDValue N10 = N1.getOperand(0);
1440 SDValue N11 = N1.getOperand(1);
1442 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1443 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1444 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1445 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1448 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1449 return SDValue(N, 0);
1451 // fold (a+b) -> (a|b) iff a and b share no bits.
1452 if (VT.isInteger() && !VT.isVector()) {
1453 APInt LHSZero, LHSOne;
1454 APInt RHSZero, RHSOne;
1455 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1457 if (LHSZero.getBoolValue()) {
1458 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1460 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1461 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1462 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1463 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1467 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1468 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1469 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1470 if (Result.getNode()) return Result;
1472 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1473 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1474 if (Result.getNode()) return Result;
1477 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1478 if (N1.getOpcode() == ISD::SHL &&
1479 N1.getOperand(0).getOpcode() == ISD::SUB)
1480 if (ConstantSDNode *C =
1481 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1482 if (C->getAPIntValue() == 0)
1483 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1484 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1485 N1.getOperand(0).getOperand(1),
1487 if (N0.getOpcode() == ISD::SHL &&
1488 N0.getOperand(0).getOpcode() == ISD::SUB)
1489 if (ConstantSDNode *C =
1490 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1491 if (C->getAPIntValue() == 0)
1492 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1493 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1494 N0.getOperand(0).getOperand(1),
1497 if (N1.getOpcode() == ISD::AND) {
1498 SDValue AndOp0 = N1.getOperand(0);
1499 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1500 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1501 unsigned DestBits = VT.getScalarType().getSizeInBits();
1503 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1504 // and similar xforms where the inner op is either ~0 or 0.
1505 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1506 DebugLoc DL = N->getDebugLoc();
1507 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1511 // add (sext i1), X -> sub X, (zext i1)
1512 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1513 N0.getOperand(0).getValueType() == MVT::i1 &&
1514 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1515 DebugLoc DL = N->getDebugLoc();
1516 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1517 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1523 SDValue DAGCombiner::visitADDC(SDNode *N) {
1524 SDValue N0 = N->getOperand(0);
1525 SDValue N1 = N->getOperand(1);
1526 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1527 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1528 EVT VT = N0.getValueType();
1530 // If the flag result is dead, turn this into an ADD.
1531 if (!N->hasAnyUseOfValue(1))
1532 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1533 DAG.getNode(ISD::CARRY_FALSE,
1534 N->getDebugLoc(), MVT::Glue));
1536 // canonicalize constant to RHS.
1538 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1540 // fold (addc x, 0) -> x + no carry out
1541 if (N1C && N1C->isNullValue())
1542 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1543 N->getDebugLoc(), MVT::Glue));
1545 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1546 APInt LHSZero, LHSOne;
1547 APInt RHSZero, RHSOne;
1548 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1550 if (LHSZero.getBoolValue()) {
1551 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1553 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1554 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1555 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1556 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1557 DAG.getNode(ISD::CARRY_FALSE,
1558 N->getDebugLoc(), MVT::Glue));
1564 SDValue DAGCombiner::visitADDE(SDNode *N) {
1565 SDValue N0 = N->getOperand(0);
1566 SDValue N1 = N->getOperand(1);
1567 SDValue CarryIn = N->getOperand(2);
1568 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1569 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1571 // canonicalize constant to RHS
1573 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1576 // fold (adde x, y, false) -> (addc x, y)
1577 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1578 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1583 // Since it may not be valid to emit a fold to zero for vector initializers
1584 // check if we can before folding.
1585 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1586 SelectionDAG &DAG, bool LegalOperations) {
1587 if (!VT.isVector()) {
1588 return DAG.getConstant(0, VT);
1590 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1591 // Produce a vector of zeros.
1592 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1593 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1594 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1595 &Ops[0], Ops.size());
1600 SDValue DAGCombiner::visitSUB(SDNode *N) {
1601 SDValue N0 = N->getOperand(0);
1602 SDValue N1 = N->getOperand(1);
1603 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1604 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1605 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1606 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1607 EVT VT = N0.getValueType();
1610 if (VT.isVector()) {
1611 SDValue FoldedVOp = SimplifyVBinOp(N);
1612 if (FoldedVOp.getNode()) return FoldedVOp;
1615 // fold (sub x, x) -> 0
1616 // FIXME: Refactor this and xor and other similar operations together.
1618 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1619 // fold (sub c1, c2) -> c1-c2
1621 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1622 // fold (sub x, c) -> (add x, -c)
1624 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1625 DAG.getConstant(-N1C->getAPIntValue(), VT));
1626 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1627 if (N0C && N0C->isAllOnesValue())
1628 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1629 // fold A-(A-B) -> B
1630 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1631 return N1.getOperand(1);
1632 // fold (A+B)-A -> B
1633 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1634 return N0.getOperand(1);
1635 // fold (A+B)-B -> A
1636 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1637 return N0.getOperand(0);
1638 // fold C2-(A+C1) -> (C2-C1)-A
1639 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1640 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1641 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1644 // fold ((A+(B+or-C))-B) -> A+or-C
1645 if (N0.getOpcode() == ISD::ADD &&
1646 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1647 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1648 N0.getOperand(1).getOperand(0) == N1)
1649 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1650 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1651 // fold ((A+(C+B))-B) -> A+C
1652 if (N0.getOpcode() == ISD::ADD &&
1653 N0.getOperand(1).getOpcode() == ISD::ADD &&
1654 N0.getOperand(1).getOperand(1) == N1)
1655 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1656 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1657 // fold ((A-(B-C))-C) -> A-B
1658 if (N0.getOpcode() == ISD::SUB &&
1659 N0.getOperand(1).getOpcode() == ISD::SUB &&
1660 N0.getOperand(1).getOperand(1) == N1)
1661 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1662 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1664 // If either operand of a sub is undef, the result is undef
1665 if (N0.getOpcode() == ISD::UNDEF)
1667 if (N1.getOpcode() == ISD::UNDEF)
1670 // If the relocation model supports it, consider symbol offsets.
1671 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1672 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1673 // fold (sub Sym, c) -> Sym-c
1674 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1675 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1677 (uint64_t)N1C->getSExtValue());
1678 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1679 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1680 if (GA->getGlobal() == GB->getGlobal())
1681 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1688 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1689 SDValue N0 = N->getOperand(0);
1690 SDValue N1 = N->getOperand(1);
1691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1693 EVT VT = N0.getValueType();
1695 // If the flag result is dead, turn this into an SUB.
1696 if (!N->hasAnyUseOfValue(1))
1697 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1698 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1701 // fold (subc x, x) -> 0 + no borrow
1703 return CombineTo(N, DAG.getConstant(0, VT),
1704 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1707 // fold (subc x, 0) -> x + no borrow
1708 if (N1C && N1C->isNullValue())
1709 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1712 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1713 if (N0C && N0C->isAllOnesValue())
1714 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1715 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1721 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1722 SDValue N0 = N->getOperand(0);
1723 SDValue N1 = N->getOperand(1);
1724 SDValue CarryIn = N->getOperand(2);
1726 // fold (sube x, y, false) -> (subc x, y)
1727 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1728 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1733 SDValue DAGCombiner::visitMUL(SDNode *N) {
1734 SDValue N0 = N->getOperand(0);
1735 SDValue N1 = N->getOperand(1);
1736 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1737 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1738 EVT VT = N0.getValueType();
1741 if (VT.isVector()) {
1742 SDValue FoldedVOp = SimplifyVBinOp(N);
1743 if (FoldedVOp.getNode()) return FoldedVOp;
1746 // fold (mul x, undef) -> 0
1747 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1748 return DAG.getConstant(0, VT);
1749 // fold (mul c1, c2) -> c1*c2
1751 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1752 // canonicalize constant to RHS
1754 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1755 // fold (mul x, 0) -> 0
1756 if (N1C && N1C->isNullValue())
1758 // fold (mul x, -1) -> 0-x
1759 if (N1C && N1C->isAllOnesValue())
1760 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1761 DAG.getConstant(0, VT), N0);
1762 // fold (mul x, (1 << c)) -> x << c
1763 if (N1C && N1C->getAPIntValue().isPowerOf2())
1764 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1765 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1766 getShiftAmountTy(N0.getValueType())));
1767 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1768 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1769 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1770 // FIXME: If the input is something that is easily negated (e.g. a
1771 // single-use add), we should put the negate there.
1772 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1773 DAG.getConstant(0, VT),
1774 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1775 DAG.getConstant(Log2Val,
1776 getShiftAmountTy(N0.getValueType()))));
1778 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1779 if (N1C && N0.getOpcode() == ISD::SHL &&
1780 isa<ConstantSDNode>(N0.getOperand(1))) {
1781 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1782 N1, N0.getOperand(1));
1783 AddToWorkList(C3.getNode());
1784 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1785 N0.getOperand(0), C3);
1788 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1791 SDValue Sh(0,0), Y(0,0);
1792 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1793 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1794 N0.getNode()->hasOneUse()) {
1796 } else if (N1.getOpcode() == ISD::SHL &&
1797 isa<ConstantSDNode>(N1.getOperand(1)) &&
1798 N1.getNode()->hasOneUse()) {
1803 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1804 Sh.getOperand(0), Y);
1805 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1806 Mul, Sh.getOperand(1));
1810 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1811 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1812 isa<ConstantSDNode>(N0.getOperand(1)))
1813 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1814 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1815 N0.getOperand(0), N1),
1816 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1817 N0.getOperand(1), N1));
1820 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1821 if (RMUL.getNode() != 0)
1827 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1828 SDValue N0 = N->getOperand(0);
1829 SDValue N1 = N->getOperand(1);
1830 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1831 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1832 EVT VT = N->getValueType(0);
1835 if (VT.isVector()) {
1836 SDValue FoldedVOp = SimplifyVBinOp(N);
1837 if (FoldedVOp.getNode()) return FoldedVOp;
1840 // fold (sdiv c1, c2) -> c1/c2
1841 if (N0C && N1C && !N1C->isNullValue())
1842 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1843 // fold (sdiv X, 1) -> X
1844 if (N1C && N1C->getAPIntValue() == 1LL)
1846 // fold (sdiv X, -1) -> 0-X
1847 if (N1C && N1C->isAllOnesValue())
1848 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1849 DAG.getConstant(0, VT), N0);
1850 // If we know the sign bits of both operands are zero, strength reduce to a
1851 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1852 if (!VT.isVector()) {
1853 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1854 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1857 // fold (sdiv X, pow2) -> simple ops after legalize
1858 if (N1C && !N1C->isNullValue() &&
1859 (N1C->getAPIntValue().isPowerOf2() ||
1860 (-N1C->getAPIntValue()).isPowerOf2())) {
1861 // If dividing by powers of two is cheap, then don't perform the following
1863 if (TLI.isPow2DivCheap())
1866 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1868 // Splat the sign bit into the register
1869 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1870 DAG.getConstant(VT.getSizeInBits()-1,
1871 getShiftAmountTy(N0.getValueType())));
1872 AddToWorkList(SGN.getNode());
1874 // Add (N0 < 0) ? abs2 - 1 : 0;
1875 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1876 DAG.getConstant(VT.getSizeInBits() - lg2,
1877 getShiftAmountTy(SGN.getValueType())));
1878 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1879 AddToWorkList(SRL.getNode());
1880 AddToWorkList(ADD.getNode()); // Divide by pow2
1881 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1882 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1884 // If we're dividing by a positive value, we're done. Otherwise, we must
1885 // negate the result.
1886 if (N1C->getAPIntValue().isNonNegative())
1889 AddToWorkList(SRA.getNode());
1890 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1891 DAG.getConstant(0, VT), SRA);
1894 // if integer divide is expensive and we satisfy the requirements, emit an
1895 // alternate sequence.
1896 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1897 SDValue Op = BuildSDIV(N);
1898 if (Op.getNode()) return Op;
1902 if (N0.getOpcode() == ISD::UNDEF)
1903 return DAG.getConstant(0, VT);
1904 // X / undef -> undef
1905 if (N1.getOpcode() == ISD::UNDEF)
1911 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1912 SDValue N0 = N->getOperand(0);
1913 SDValue N1 = N->getOperand(1);
1914 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1916 EVT VT = N->getValueType(0);
1919 if (VT.isVector()) {
1920 SDValue FoldedVOp = SimplifyVBinOp(N);
1921 if (FoldedVOp.getNode()) return FoldedVOp;
1924 // fold (udiv c1, c2) -> c1/c2
1925 if (N0C && N1C && !N1C->isNullValue())
1926 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1927 // fold (udiv x, (1 << c)) -> x >>u c
1928 if (N1C && N1C->getAPIntValue().isPowerOf2())
1929 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1930 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1931 getShiftAmountTy(N0.getValueType())));
1932 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1933 if (N1.getOpcode() == ISD::SHL) {
1934 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1935 if (SHC->getAPIntValue().isPowerOf2()) {
1936 EVT ADDVT = N1.getOperand(1).getValueType();
1937 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1939 DAG.getConstant(SHC->getAPIntValue()
1942 AddToWorkList(Add.getNode());
1943 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1947 // fold (udiv x, c) -> alternate
1948 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1949 SDValue Op = BuildUDIV(N);
1950 if (Op.getNode()) return Op;
1954 if (N0.getOpcode() == ISD::UNDEF)
1955 return DAG.getConstant(0, VT);
1956 // X / undef -> undef
1957 if (N1.getOpcode() == ISD::UNDEF)
1963 SDValue DAGCombiner::visitSREM(SDNode *N) {
1964 SDValue N0 = N->getOperand(0);
1965 SDValue N1 = N->getOperand(1);
1966 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1967 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1968 EVT VT = N->getValueType(0);
1970 // fold (srem c1, c2) -> c1%c2
1971 if (N0C && N1C && !N1C->isNullValue())
1972 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1973 // If we know the sign bits of both operands are zero, strength reduce to a
1974 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1975 if (!VT.isVector()) {
1976 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1977 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1980 // If X/C can be simplified by the division-by-constant logic, lower
1981 // X%C to the equivalent of X-X/C*C.
1982 if (N1C && !N1C->isNullValue()) {
1983 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1984 AddToWorkList(Div.getNode());
1985 SDValue OptimizedDiv = combine(Div.getNode());
1986 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1987 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1989 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1990 AddToWorkList(Mul.getNode());
1996 if (N0.getOpcode() == ISD::UNDEF)
1997 return DAG.getConstant(0, VT);
1998 // X % undef -> undef
1999 if (N1.getOpcode() == ISD::UNDEF)
2005 SDValue DAGCombiner::visitUREM(SDNode *N) {
2006 SDValue N0 = N->getOperand(0);
2007 SDValue N1 = N->getOperand(1);
2008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2010 EVT VT = N->getValueType(0);
2012 // fold (urem c1, c2) -> c1%c2
2013 if (N0C && N1C && !N1C->isNullValue())
2014 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2015 // fold (urem x, pow2) -> (and x, pow2-1)
2016 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2017 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2018 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2019 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2020 if (N1.getOpcode() == ISD::SHL) {
2021 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2022 if (SHC->getAPIntValue().isPowerOf2()) {
2024 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2025 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2027 AddToWorkList(Add.getNode());
2028 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2033 // If X/C can be simplified by the division-by-constant logic, lower
2034 // X%C to the equivalent of X-X/C*C.
2035 if (N1C && !N1C->isNullValue()) {
2036 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2037 AddToWorkList(Div.getNode());
2038 SDValue OptimizedDiv = combine(Div.getNode());
2039 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2040 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2042 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2043 AddToWorkList(Mul.getNode());
2049 if (N0.getOpcode() == ISD::UNDEF)
2050 return DAG.getConstant(0, VT);
2051 // X % undef -> undef
2052 if (N1.getOpcode() == ISD::UNDEF)
2058 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2059 SDValue N0 = N->getOperand(0);
2060 SDValue N1 = N->getOperand(1);
2061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062 EVT VT = N->getValueType(0);
2063 DebugLoc DL = N->getDebugLoc();
2065 // fold (mulhs x, 0) -> 0
2066 if (N1C && N1C->isNullValue())
2068 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2069 if (N1C && N1C->getAPIntValue() == 1)
2070 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2071 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2072 getShiftAmountTy(N0.getValueType())));
2073 // fold (mulhs x, undef) -> 0
2074 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2075 return DAG.getConstant(0, VT);
2077 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2079 if (VT.isSimple() && !VT.isVector()) {
2080 MVT Simple = VT.getSimpleVT();
2081 unsigned SimpleSize = Simple.getSizeInBits();
2082 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2083 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2084 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2085 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2086 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2087 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2088 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2089 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2096 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2097 SDValue N0 = N->getOperand(0);
2098 SDValue N1 = N->getOperand(1);
2099 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2100 EVT VT = N->getValueType(0);
2101 DebugLoc DL = N->getDebugLoc();
2103 // fold (mulhu x, 0) -> 0
2104 if (N1C && N1C->isNullValue())
2106 // fold (mulhu x, 1) -> 0
2107 if (N1C && N1C->getAPIntValue() == 1)
2108 return DAG.getConstant(0, N0.getValueType());
2109 // fold (mulhu x, undef) -> 0
2110 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2111 return DAG.getConstant(0, VT);
2113 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2115 if (VT.isSimple() && !VT.isVector()) {
2116 MVT Simple = VT.getSimpleVT();
2117 unsigned SimpleSize = Simple.getSizeInBits();
2118 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2119 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2120 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2121 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2122 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2123 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2124 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2125 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2132 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2133 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2134 /// that are being performed. Return true if a simplification was made.
2136 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2138 // If the high half is not needed, just compute the low half.
2139 bool HiExists = N->hasAnyUseOfValue(1);
2141 (!LegalOperations ||
2142 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2143 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2144 N->op_begin(), N->getNumOperands());
2145 return CombineTo(N, Res, Res);
2148 // If the low half is not needed, just compute the high half.
2149 bool LoExists = N->hasAnyUseOfValue(0);
2151 (!LegalOperations ||
2152 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2153 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2154 N->op_begin(), N->getNumOperands());
2155 return CombineTo(N, Res, Res);
2158 // If both halves are used, return as it is.
2159 if (LoExists && HiExists)
2162 // If the two computed results can be simplified separately, separate them.
2164 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2165 N->op_begin(), N->getNumOperands());
2166 AddToWorkList(Lo.getNode());
2167 SDValue LoOpt = combine(Lo.getNode());
2168 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2169 (!LegalOperations ||
2170 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2171 return CombineTo(N, LoOpt, LoOpt);
2175 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2176 N->op_begin(), N->getNumOperands());
2177 AddToWorkList(Hi.getNode());
2178 SDValue HiOpt = combine(Hi.getNode());
2179 if (HiOpt.getNode() && HiOpt != Hi &&
2180 (!LegalOperations ||
2181 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2182 return CombineTo(N, HiOpt, HiOpt);
2188 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2189 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2190 if (Res.getNode()) return Res;
2192 EVT VT = N->getValueType(0);
2193 DebugLoc DL = N->getDebugLoc();
2195 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2197 if (VT.isSimple() && !VT.isVector()) {
2198 MVT Simple = VT.getSimpleVT();
2199 unsigned SimpleSize = Simple.getSizeInBits();
2200 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2203 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2204 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2205 // Compute the high part as N1.
2206 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2207 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2208 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2209 // Compute the low part as N0.
2210 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2211 return CombineTo(N, Lo, Hi);
2218 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2219 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2220 if (Res.getNode()) return Res;
2222 EVT VT = N->getValueType(0);
2223 DebugLoc DL = N->getDebugLoc();
2225 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2227 if (VT.isSimple() && !VT.isVector()) {
2228 MVT Simple = VT.getSimpleVT();
2229 unsigned SimpleSize = Simple.getSizeInBits();
2230 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2231 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2232 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2233 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2234 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2235 // Compute the high part as N1.
2236 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2237 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2238 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2239 // Compute the low part as N0.
2240 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2241 return CombineTo(N, Lo, Hi);
2248 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2249 // (smulo x, 2) -> (saddo x, x)
2250 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2251 if (C2->getAPIntValue() == 2)
2252 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2253 N->getOperand(0), N->getOperand(0));
2258 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2259 // (umulo x, 2) -> (uaddo x, x)
2260 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2261 if (C2->getAPIntValue() == 2)
2262 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2263 N->getOperand(0), N->getOperand(0));
2268 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2269 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2270 if (Res.getNode()) return Res;
2275 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2276 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2277 if (Res.getNode()) return Res;
2282 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2283 /// two operands of the same opcode, try to simplify it.
2284 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2285 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2286 EVT VT = N0.getValueType();
2287 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2289 // Bail early if none of these transforms apply.
2290 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2292 // For each of OP in AND/OR/XOR:
2293 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2294 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2295 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2296 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2298 // do not sink logical op inside of a vector extend, since it may combine
2300 EVT Op0VT = N0.getOperand(0).getValueType();
2301 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2302 N0.getOpcode() == ISD::SIGN_EXTEND ||
2303 // Avoid infinite looping with PromoteIntBinOp.
2304 (N0.getOpcode() == ISD::ANY_EXTEND &&
2305 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2306 (N0.getOpcode() == ISD::TRUNCATE &&
2307 (!TLI.isZExtFree(VT, Op0VT) ||
2308 !TLI.isTruncateFree(Op0VT, VT)) &&
2309 TLI.isTypeLegal(Op0VT))) &&
2311 Op0VT == N1.getOperand(0).getValueType() &&
2312 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2313 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2314 N0.getOperand(0).getValueType(),
2315 N0.getOperand(0), N1.getOperand(0));
2316 AddToWorkList(ORNode.getNode());
2317 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2320 // For each of OP in SHL/SRL/SRA/AND...
2321 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2322 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2323 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2324 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2325 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2326 N0.getOperand(1) == N1.getOperand(1)) {
2327 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2328 N0.getOperand(0).getValueType(),
2329 N0.getOperand(0), N1.getOperand(0));
2330 AddToWorkList(ORNode.getNode());
2331 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2332 ORNode, N0.getOperand(1));
2335 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2336 // Only perform this optimization after type legalization and before
2337 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2338 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2339 // we don't want to undo this promotion.
2340 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2342 if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR)
2343 && Level == AfterLegalizeTypes) {
2344 SDValue In0 = N0.getOperand(0);
2345 SDValue In1 = N1.getOperand(0);
2346 EVT In0Ty = In0.getValueType();
2347 EVT In1Ty = In1.getValueType();
2348 // If both incoming values are integers, and the original types are the same.
2349 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2350 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1);
2351 SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op);
2352 AddToWorkList(Op.getNode());
2357 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2358 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2359 // If both shuffles use the same mask, and both shuffle within a single
2360 // vector, then it is worthwhile to move the swizzle after the operation.
2361 // The type-legalizer generates this pattern when loading illegal
2362 // vector types from memory. In many cases this allows additional shuffle
2364 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2365 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2366 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2367 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2368 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2370 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2371 "Inputs to shuffles are not the same type");
2373 unsigned NumElts = VT.getVectorNumElements();
2375 // Check that both shuffles use the same mask. The masks are known to be of
2376 // the same length because the result vector type is the same.
2377 bool SameMask = true;
2378 for (unsigned i = 0; i != NumElts; ++i) {
2379 int Idx0 = SVN0->getMaskElt(i);
2380 int Idx1 = SVN1->getMaskElt(i);
2388 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2389 N0.getOperand(0), N1.getOperand(0));
2390 AddToWorkList(Op.getNode());
2391 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2392 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2399 SDValue DAGCombiner::visitAND(SDNode *N) {
2400 SDValue N0 = N->getOperand(0);
2401 SDValue N1 = N->getOperand(1);
2402 SDValue LL, LR, RL, RR, CC0, CC1;
2403 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2404 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2405 EVT VT = N1.getValueType();
2406 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2409 if (VT.isVector()) {
2410 SDValue FoldedVOp = SimplifyVBinOp(N);
2411 if (FoldedVOp.getNode()) return FoldedVOp;
2414 // fold (and x, undef) -> 0
2415 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2416 return DAG.getConstant(0, VT);
2417 // fold (and c1, c2) -> c1&c2
2419 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2420 // canonicalize constant to RHS
2422 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2423 // fold (and x, -1) -> x
2424 if (N1C && N1C->isAllOnesValue())
2426 // if (and x, c) is known to be zero, return 0
2427 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2428 APInt::getAllOnesValue(BitWidth)))
2429 return DAG.getConstant(0, VT);
2431 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2432 if (RAND.getNode() != 0)
2434 // fold (and (or x, C), D) -> D if (C & D) == D
2435 if (N1C && N0.getOpcode() == ISD::OR)
2436 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2437 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2439 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2440 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2441 SDValue N0Op0 = N0.getOperand(0);
2442 APInt Mask = ~N1C->getAPIntValue();
2443 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2444 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2445 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2446 N0.getValueType(), N0Op0);
2448 // Replace uses of the AND with uses of the Zero extend node.
2451 // We actually want to replace all uses of the any_extend with the
2452 // zero_extend, to avoid duplicating things. This will later cause this
2453 // AND to be folded.
2454 CombineTo(N0.getNode(), Zext);
2455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2458 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2459 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2460 // already be zero by virtue of the width of the base type of the load.
2462 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2464 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2465 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2466 N0.getOpcode() == ISD::LOAD) {
2467 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2468 N0 : N0.getOperand(0) );
2470 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2471 // This can be a pure constant or a vector splat, in which case we treat the
2472 // vector as a scalar and use the splat value.
2473 APInt Constant = APInt::getNullValue(1);
2474 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2475 Constant = C->getAPIntValue();
2476 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2477 APInt SplatValue, SplatUndef;
2478 unsigned SplatBitSize;
2480 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2481 SplatBitSize, HasAnyUndefs);
2483 // Undef bits can contribute to a possible optimisation if set, so
2485 SplatValue |= SplatUndef;
2487 // The splat value may be something like "0x00FFFFFF", which means 0 for
2488 // the first vector value and FF for the rest, repeating. We need a mask
2489 // that will apply equally to all members of the vector, so AND all the
2490 // lanes of the constant together.
2491 EVT VT = Vector->getValueType(0);
2492 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2493 Constant = APInt::getAllOnesValue(BitWidth);
2494 for (unsigned i = 0, n = VT.getVectorNumElements(); i < n; ++i)
2495 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2499 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2500 // actually legal and isn't going to get expanded, else this is a false
2502 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2503 Load->getMemoryVT());
2505 // Resize the constant to the same size as the original memory access before
2506 // extension. If it is still the AllOnesValue then this AND is completely
2509 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2512 switch (Load->getExtensionType()) {
2513 default: B = false; break;
2514 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2516 case ISD::NON_EXTLOAD: B = true; break;
2519 if (B && Constant.isAllOnesValue()) {
2520 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2521 // preserve semantics once we get rid of the AND.
2522 SDValue NewLoad(Load, 0);
2523 if (Load->getExtensionType() == ISD::EXTLOAD) {
2524 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2525 Load->getValueType(0), Load->getDebugLoc(),
2526 Load->getChain(), Load->getBasePtr(),
2527 Load->getOffset(), Load->getMemoryVT(),
2528 Load->getMemOperand());
2529 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2530 if (Load->getNumValues() == 3) {
2531 // PRE/POST_INC loads have 3 values.
2532 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2533 NewLoad.getValue(2) };
2534 CombineTo(Load, To, 3, true);
2536 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2540 // Fold the AND away, taking care not to fold to the old load node if we
2542 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2544 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2547 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2548 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2549 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2550 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2552 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2553 LL.getValueType().isInteger()) {
2554 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2555 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2556 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2557 LR.getValueType(), LL, RL);
2558 AddToWorkList(ORNode.getNode());
2559 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2561 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2562 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2563 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2564 LR.getValueType(), LL, RL);
2565 AddToWorkList(ANDNode.getNode());
2566 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2568 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2569 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2570 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2571 LR.getValueType(), LL, RL);
2572 AddToWorkList(ORNode.getNode());
2573 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2576 // canonicalize equivalent to ll == rl
2577 if (LL == RR && LR == RL) {
2578 Op1 = ISD::getSetCCSwappedOperands(Op1);
2581 if (LL == RL && LR == RR) {
2582 bool isInteger = LL.getValueType().isInteger();
2583 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2584 if (Result != ISD::SETCC_INVALID &&
2585 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2586 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2591 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2592 if (N0.getOpcode() == N1.getOpcode()) {
2593 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2594 if (Tmp.getNode()) return Tmp;
2597 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2598 // fold (and (sra)) -> (and (srl)) when possible.
2599 if (!VT.isVector() &&
2600 SimplifyDemandedBits(SDValue(N, 0)))
2601 return SDValue(N, 0);
2603 // fold (zext_inreg (extload x)) -> (zextload x)
2604 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2605 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2606 EVT MemVT = LN0->getMemoryVT();
2607 // If we zero all the possible extended bits, then we can turn this into
2608 // a zextload if we are running before legalize or the operation is legal.
2609 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2610 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2611 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2612 ((!LegalOperations && !LN0->isVolatile()) ||
2613 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2614 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2615 LN0->getChain(), LN0->getBasePtr(),
2616 LN0->getPointerInfo(), MemVT,
2617 LN0->isVolatile(), LN0->isNonTemporal(),
2618 LN0->getAlignment());
2620 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2621 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2624 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2625 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2627 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2628 EVT MemVT = LN0->getMemoryVT();
2629 // If we zero all the possible extended bits, then we can turn this into
2630 // a zextload if we are running before legalize or the operation is legal.
2631 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2632 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2633 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2634 ((!LegalOperations && !LN0->isVolatile()) ||
2635 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2636 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2638 LN0->getBasePtr(), LN0->getPointerInfo(),
2640 LN0->isVolatile(), LN0->isNonTemporal(),
2641 LN0->getAlignment());
2643 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2644 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2648 // fold (and (load x), 255) -> (zextload x, i8)
2649 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2650 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2651 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2652 (N0.getOpcode() == ISD::ANY_EXTEND &&
2653 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2654 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2655 LoadSDNode *LN0 = HasAnyExt
2656 ? cast<LoadSDNode>(N0.getOperand(0))
2657 : cast<LoadSDNode>(N0);
2658 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2659 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2660 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2661 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2662 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2663 EVT LoadedVT = LN0->getMemoryVT();
2665 if (ExtVT == LoadedVT &&
2666 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2667 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2670 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2671 LN0->getChain(), LN0->getBasePtr(),
2672 LN0->getPointerInfo(),
2673 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2674 LN0->getAlignment());
2676 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2677 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2680 // Do not change the width of a volatile load.
2681 // Do not generate loads of non-round integer types since these can
2682 // be expensive (and would be wrong if the type is not byte sized).
2683 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2684 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2685 EVT PtrType = LN0->getOperand(1).getValueType();
2687 unsigned Alignment = LN0->getAlignment();
2688 SDValue NewPtr = LN0->getBasePtr();
2690 // For big endian targets, we need to add an offset to the pointer
2691 // to load the correct bytes. For little endian systems, we merely
2692 // need to read fewer bytes from the same pointer.
2693 if (TLI.isBigEndian()) {
2694 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2695 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2696 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2697 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2698 NewPtr, DAG.getConstant(PtrOff, PtrType));
2699 Alignment = MinAlign(Alignment, PtrOff);
2702 AddToWorkList(NewPtr.getNode());
2704 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2706 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2707 LN0->getChain(), NewPtr,
2708 LN0->getPointerInfo(),
2709 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2712 CombineTo(LN0, Load, Load.getValue(1));
2713 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2722 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2724 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2725 bool DemandHighBits) {
2726 if (!LegalOperations)
2729 EVT VT = N->getValueType(0);
2730 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2732 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2735 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2736 bool LookPassAnd0 = false;
2737 bool LookPassAnd1 = false;
2738 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2740 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2742 if (N0.getOpcode() == ISD::AND) {
2743 if (!N0.getNode()->hasOneUse())
2745 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2746 if (!N01C || N01C->getZExtValue() != 0xFF00)
2748 N0 = N0.getOperand(0);
2749 LookPassAnd0 = true;
2752 if (N1.getOpcode() == ISD::AND) {
2753 if (!N1.getNode()->hasOneUse())
2755 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2756 if (!N11C || N11C->getZExtValue() != 0xFF)
2758 N1 = N1.getOperand(0);
2759 LookPassAnd1 = true;
2762 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2764 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2766 if (!N0.getNode()->hasOneUse() ||
2767 !N1.getNode()->hasOneUse())
2770 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2771 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2774 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2777 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2778 SDValue N00 = N0->getOperand(0);
2779 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2780 if (!N00.getNode()->hasOneUse())
2782 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2783 if (!N001C || N001C->getZExtValue() != 0xFF)
2785 N00 = N00.getOperand(0);
2786 LookPassAnd0 = true;
2789 SDValue N10 = N1->getOperand(0);
2790 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2791 if (!N10.getNode()->hasOneUse())
2793 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2794 if (!N101C || N101C->getZExtValue() != 0xFF00)
2796 N10 = N10.getOperand(0);
2797 LookPassAnd1 = true;
2803 // Make sure everything beyond the low halfword is zero since the SRL 16
2804 // will clear the top bits.
2805 unsigned OpSizeInBits = VT.getSizeInBits();
2806 if (DemandHighBits && OpSizeInBits > 16 &&
2807 (!LookPassAnd0 || !LookPassAnd1) &&
2808 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2811 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2812 if (OpSizeInBits > 16)
2813 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2814 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2818 /// isBSwapHWordElement - Return true if the specified node is an element
2819 /// that makes up a 32-bit packed halfword byteswap. i.e.
2820 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2821 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2822 if (!N.getNode()->hasOneUse())
2825 unsigned Opc = N.getOpcode();
2826 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2829 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2834 switch (N1C->getZExtValue()) {
2837 case 0xFF: Num = 0; break;
2838 case 0xFF00: Num = 1; break;
2839 case 0xFF0000: Num = 2; break;
2840 case 0xFF000000: Num = 3; break;
2843 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2844 SDValue N0 = N.getOperand(0);
2845 if (Opc == ISD::AND) {
2846 if (Num == 0 || Num == 2) {
2848 // (x >> 8) & 0xff0000
2849 if (N0.getOpcode() != ISD::SRL)
2851 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2852 if (!C || C->getZExtValue() != 8)
2855 // (x << 8) & 0xff00
2856 // (x << 8) & 0xff000000
2857 if (N0.getOpcode() != ISD::SHL)
2859 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2860 if (!C || C->getZExtValue() != 8)
2863 } else if (Opc == ISD::SHL) {
2865 // (x & 0xff0000) << 8
2866 if (Num != 0 && Num != 2)
2868 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2869 if (!C || C->getZExtValue() != 8)
2871 } else { // Opc == ISD::SRL
2872 // (x & 0xff00) >> 8
2873 // (x & 0xff000000) >> 8
2874 if (Num != 1 && Num != 3)
2876 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2877 if (!C || C->getZExtValue() != 8)
2884 Parts[Num] = N0.getOperand(0).getNode();
2888 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2889 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2890 /// => (rotl (bswap x), 16)
2891 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2892 if (!LegalOperations)
2895 EVT VT = N->getValueType(0);
2898 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2901 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2903 // (or (or (and), (and)), (or (and), (and)))
2904 // (or (or (or (and), (and)), (and)), (and))
2905 if (N0.getOpcode() != ISD::OR)
2907 SDValue N00 = N0.getOperand(0);
2908 SDValue N01 = N0.getOperand(1);
2910 if (N1.getOpcode() == ISD::OR) {
2911 // (or (or (and), (and)), (or (and), (and)))
2912 SDValue N000 = N00.getOperand(0);
2913 if (!isBSwapHWordElement(N000, Parts))
2916 SDValue N001 = N00.getOperand(1);
2917 if (!isBSwapHWordElement(N001, Parts))
2919 SDValue N010 = N01.getOperand(0);
2920 if (!isBSwapHWordElement(N010, Parts))
2922 SDValue N011 = N01.getOperand(1);
2923 if (!isBSwapHWordElement(N011, Parts))
2926 // (or (or (or (and), (and)), (and)), (and))
2927 if (!isBSwapHWordElement(N1, Parts))
2929 if (!isBSwapHWordElement(N01, Parts))
2931 if (N00.getOpcode() != ISD::OR)
2933 SDValue N000 = N00.getOperand(0);
2934 if (!isBSwapHWordElement(N000, Parts))
2936 SDValue N001 = N00.getOperand(1);
2937 if (!isBSwapHWordElement(N001, Parts))
2941 // Make sure the parts are all coming from the same node.
2942 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2945 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2946 SDValue(Parts[0],0));
2948 // Result of the bswap should be rotated by 16. If it's not legal, than
2949 // do (x << 16) | (x >> 16).
2950 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2951 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2952 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2953 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2954 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2955 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2956 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2957 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2960 SDValue DAGCombiner::visitOR(SDNode *N) {
2961 SDValue N0 = N->getOperand(0);
2962 SDValue N1 = N->getOperand(1);
2963 SDValue LL, LR, RL, RR, CC0, CC1;
2964 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2965 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2966 EVT VT = N1.getValueType();
2969 if (VT.isVector()) {
2970 SDValue FoldedVOp = SimplifyVBinOp(N);
2971 if (FoldedVOp.getNode()) return FoldedVOp;
2974 // fold (or x, undef) -> -1
2975 if (!LegalOperations &&
2976 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2977 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2978 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2980 // fold (or c1, c2) -> c1|c2
2982 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2983 // canonicalize constant to RHS
2985 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2986 // fold (or x, 0) -> x
2987 if (N1C && N1C->isNullValue())
2989 // fold (or x, -1) -> -1
2990 if (N1C && N1C->isAllOnesValue())
2992 // fold (or x, c) -> c iff (x & ~c) == 0
2993 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2996 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
2997 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
2998 if (BSwap.getNode() != 0)
3000 BSwap = MatchBSwapHWordLow(N, N0, N1);
3001 if (BSwap.getNode() != 0)
3005 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3006 if (ROR.getNode() != 0)
3008 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3009 // iff (c1 & c2) == 0.
3010 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3011 isa<ConstantSDNode>(N0.getOperand(1))) {
3012 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3013 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3014 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3015 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3016 N0.getOperand(0), N1),
3017 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3019 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3020 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3021 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3022 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3024 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3025 LL.getValueType().isInteger()) {
3026 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3027 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3028 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3029 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3030 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3031 LR.getValueType(), LL, RL);
3032 AddToWorkList(ORNode.getNode());
3033 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3035 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3036 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3037 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3038 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3039 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3040 LR.getValueType(), LL, RL);
3041 AddToWorkList(ANDNode.getNode());
3042 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3045 // canonicalize equivalent to ll == rl
3046 if (LL == RR && LR == RL) {
3047 Op1 = ISD::getSetCCSwappedOperands(Op1);
3050 if (LL == RL && LR == RR) {
3051 bool isInteger = LL.getValueType().isInteger();
3052 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3053 if (Result != ISD::SETCC_INVALID &&
3054 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3055 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3060 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3061 if (N0.getOpcode() == N1.getOpcode()) {
3062 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3063 if (Tmp.getNode()) return Tmp;
3066 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3067 if (N0.getOpcode() == ISD::AND &&
3068 N1.getOpcode() == ISD::AND &&
3069 N0.getOperand(1).getOpcode() == ISD::Constant &&
3070 N1.getOperand(1).getOpcode() == ISD::Constant &&
3071 // Don't increase # computations.
3072 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3073 // We can only do this xform if we know that bits from X that are set in C2
3074 // but not in C1 are already zero. Likewise for Y.
3075 const APInt &LHSMask =
3076 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3077 const APInt &RHSMask =
3078 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3080 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3081 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3082 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3083 N0.getOperand(0), N1.getOperand(0));
3084 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3085 DAG.getConstant(LHSMask | RHSMask, VT));
3089 // See if this is some rotate idiom.
3090 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3091 return SDValue(Rot, 0);
3093 // Simplify the operands using demanded-bits information.
3094 if (!VT.isVector() &&
3095 SimplifyDemandedBits(SDValue(N, 0)))
3096 return SDValue(N, 0);
3101 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3102 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3103 if (Op.getOpcode() == ISD::AND) {
3104 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3105 Mask = Op.getOperand(1);
3106 Op = Op.getOperand(0);
3112 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3120 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3121 // idioms for rotate, and if the target supports rotation instructions, generate
3123 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3124 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3125 EVT VT = LHS.getValueType();
3126 if (!TLI.isTypeLegal(VT)) return 0;
3128 // The target must have at least one rotate flavor.
3129 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3130 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3131 if (!HasROTL && !HasROTR) return 0;
3133 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3134 SDValue LHSShift; // The shift.
3135 SDValue LHSMask; // AND value if any.
3136 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3137 return 0; // Not part of a rotate.
3139 SDValue RHSShift; // The shift.
3140 SDValue RHSMask; // AND value if any.
3141 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3142 return 0; // Not part of a rotate.
3144 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3145 return 0; // Not shifting the same value.
3147 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3148 return 0; // Shifts must disagree.
3150 // Canonicalize shl to left side in a shl/srl pair.
3151 if (RHSShift.getOpcode() == ISD::SHL) {
3152 std::swap(LHS, RHS);
3153 std::swap(LHSShift, RHSShift);
3154 std::swap(LHSMask , RHSMask );
3157 unsigned OpSizeInBits = VT.getSizeInBits();
3158 SDValue LHSShiftArg = LHSShift.getOperand(0);
3159 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3160 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3162 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3163 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3164 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3165 RHSShiftAmt.getOpcode() == ISD::Constant) {
3166 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3167 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3168 if ((LShVal + RShVal) != OpSizeInBits)
3173 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
3175 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
3177 // If there is an AND of either shifted operand, apply it to the result.
3178 if (LHSMask.getNode() || RHSMask.getNode()) {
3179 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3181 if (LHSMask.getNode()) {
3182 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3183 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3185 if (RHSMask.getNode()) {
3186 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3187 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3190 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3193 return Rot.getNode();
3196 // If there is a mask here, and we have a variable shift, we can't be sure
3197 // that we're masking out the right stuff.
3198 if (LHSMask.getNode() || RHSMask.getNode())
3201 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3202 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3203 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3204 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3205 if (ConstantSDNode *SUBC =
3206 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3207 if (SUBC->getAPIntValue() == OpSizeInBits) {
3209 return DAG.getNode(ISD::ROTL, DL, VT,
3210 LHSShiftArg, LHSShiftAmt).getNode();
3212 return DAG.getNode(ISD::ROTR, DL, VT,
3213 LHSShiftArg, RHSShiftAmt).getNode();
3218 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3219 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3220 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3221 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3222 if (ConstantSDNode *SUBC =
3223 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3224 if (SUBC->getAPIntValue() == OpSizeInBits) {
3226 return DAG.getNode(ISD::ROTR, DL, VT,
3227 LHSShiftArg, RHSShiftAmt).getNode();
3229 return DAG.getNode(ISD::ROTL, DL, VT,
3230 LHSShiftArg, LHSShiftAmt).getNode();
3235 // Look for sign/zext/any-extended or truncate cases:
3236 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3237 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3238 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3239 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3240 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3241 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3242 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3243 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3244 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3245 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3246 if (RExtOp0.getOpcode() == ISD::SUB &&
3247 RExtOp0.getOperand(1) == LExtOp0) {
3248 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3250 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3251 // (rotr x, (sub 32, y))
3252 if (ConstantSDNode *SUBC =
3253 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3254 if (SUBC->getAPIntValue() == OpSizeInBits) {
3255 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3257 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3260 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3261 RExtOp0 == LExtOp0.getOperand(1)) {
3262 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3264 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3265 // (rotl x, (sub 32, y))
3266 if (ConstantSDNode *SUBC =
3267 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3268 if (SUBC->getAPIntValue() == OpSizeInBits) {
3269 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3271 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3280 SDValue DAGCombiner::visitXOR(SDNode *N) {
3281 SDValue N0 = N->getOperand(0);
3282 SDValue N1 = N->getOperand(1);
3283 SDValue LHS, RHS, CC;
3284 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3285 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3286 EVT VT = N0.getValueType();
3289 if (VT.isVector()) {
3290 SDValue FoldedVOp = SimplifyVBinOp(N);
3291 if (FoldedVOp.getNode()) return FoldedVOp;
3294 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3295 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3296 return DAG.getConstant(0, VT);
3297 // fold (xor x, undef) -> undef
3298 if (N0.getOpcode() == ISD::UNDEF)
3300 if (N1.getOpcode() == ISD::UNDEF)
3302 // fold (xor c1, c2) -> c1^c2
3304 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3305 // canonicalize constant to RHS
3307 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3308 // fold (xor x, 0) -> x
3309 if (N1C && N1C->isNullValue())
3312 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3313 if (RXOR.getNode() != 0)
3316 // fold !(x cc y) -> (x !cc y)
3317 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3318 bool isInt = LHS.getValueType().isInteger();
3319 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3322 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3323 switch (N0.getOpcode()) {
3325 llvm_unreachable("Unhandled SetCC Equivalent!");
3327 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3328 case ISD::SELECT_CC:
3329 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3330 N0.getOperand(3), NotCC);
3335 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3336 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3337 N0.getNode()->hasOneUse() &&
3338 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3339 SDValue V = N0.getOperand(0);
3340 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3341 DAG.getConstant(1, V.getValueType()));
3342 AddToWorkList(V.getNode());
3343 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3346 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3347 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3348 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3349 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3350 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3351 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3352 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3353 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3354 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3355 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3358 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3359 if (N1C && N1C->isAllOnesValue() &&
3360 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3361 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3362 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3363 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3364 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3365 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3366 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3367 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3370 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3371 if (N1C && N0.getOpcode() == ISD::XOR) {
3372 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3373 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3375 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3376 DAG.getConstant(N1C->getAPIntValue() ^
3377 N00C->getAPIntValue(), VT));
3379 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3380 DAG.getConstant(N1C->getAPIntValue() ^
3381 N01C->getAPIntValue(), VT));
3383 // fold (xor x, x) -> 0
3385 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3387 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3388 if (N0.getOpcode() == N1.getOpcode()) {
3389 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3390 if (Tmp.getNode()) return Tmp;
3393 // Simplify the expression using non-local knowledge.
3394 if (!VT.isVector() &&
3395 SimplifyDemandedBits(SDValue(N, 0)))
3396 return SDValue(N, 0);
3401 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3402 /// the shift amount is a constant.
3403 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3404 SDNode *LHS = N->getOperand(0).getNode();
3405 if (!LHS->hasOneUse()) return SDValue();
3407 // We want to pull some binops through shifts, so that we have (and (shift))
3408 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3409 // thing happens with address calculations, so it's important to canonicalize
3411 bool HighBitSet = false; // Can we transform this if the high bit is set?
3413 switch (LHS->getOpcode()) {
3414 default: return SDValue();
3417 HighBitSet = false; // We can only transform sra if the high bit is clear.
3420 HighBitSet = true; // We can only transform sra if the high bit is set.
3423 if (N->getOpcode() != ISD::SHL)
3424 return SDValue(); // only shl(add) not sr[al](add).
3425 HighBitSet = false; // We can only transform sra if the high bit is clear.
3429 // We require the RHS of the binop to be a constant as well.
3430 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3431 if (!BinOpCst) return SDValue();
3433 // FIXME: disable this unless the input to the binop is a shift by a constant.
3434 // If it is not a shift, it pessimizes some common cases like:
3436 // void foo(int *X, int i) { X[i & 1235] = 1; }
3437 // int bar(int *X, int i) { return X[i & 255]; }
3438 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3439 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3440 BinOpLHSVal->getOpcode() != ISD::SRA &&
3441 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3442 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3445 EVT VT = N->getValueType(0);
3447 // If this is a signed shift right, and the high bit is modified by the
3448 // logical operation, do not perform the transformation. The highBitSet
3449 // boolean indicates the value of the high bit of the constant which would
3450 // cause it to be modified for this operation.
3451 if (N->getOpcode() == ISD::SRA) {
3452 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3453 if (BinOpRHSSignSet != HighBitSet)
3457 // Fold the constants, shifting the binop RHS by the shift amount.
3458 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3460 LHS->getOperand(1), N->getOperand(1));
3462 // Create the new shift.
3463 SDValue NewShift = DAG.getNode(N->getOpcode(),
3464 LHS->getOperand(0).getDebugLoc(),
3465 VT, LHS->getOperand(0), N->getOperand(1));
3467 // Create the new binop.
3468 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3471 SDValue DAGCombiner::visitSHL(SDNode *N) {
3472 SDValue N0 = N->getOperand(0);
3473 SDValue N1 = N->getOperand(1);
3474 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3475 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3476 EVT VT = N0.getValueType();
3477 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3479 // fold (shl c1, c2) -> c1<<c2
3481 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3482 // fold (shl 0, x) -> 0
3483 if (N0C && N0C->isNullValue())
3485 // fold (shl x, c >= size(x)) -> undef
3486 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3487 return DAG.getUNDEF(VT);
3488 // fold (shl x, 0) -> x
3489 if (N1C && N1C->isNullValue())
3491 // fold (shl undef, x) -> 0
3492 if (N0.getOpcode() == ISD::UNDEF)
3493 return DAG.getConstant(0, VT);
3494 // if (shl x, c) is known to be zero, return 0
3495 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3496 APInt::getAllOnesValue(OpSizeInBits)))
3497 return DAG.getConstant(0, VT);
3498 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3499 if (N1.getOpcode() == ISD::TRUNCATE &&
3500 N1.getOperand(0).getOpcode() == ISD::AND &&
3501 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3502 SDValue N101 = N1.getOperand(0).getOperand(1);
3503 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3504 EVT TruncVT = N1.getValueType();
3505 SDValue N100 = N1.getOperand(0).getOperand(0);
3506 APInt TruncC = N101C->getAPIntValue();
3507 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3508 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3509 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3510 DAG.getNode(ISD::TRUNCATE,
3513 DAG.getConstant(TruncC, TruncVT)));
3517 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3518 return SDValue(N, 0);
3520 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3521 if (N1C && N0.getOpcode() == ISD::SHL &&
3522 N0.getOperand(1).getOpcode() == ISD::Constant) {
3523 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3524 uint64_t c2 = N1C->getZExtValue();
3525 if (c1 + c2 >= OpSizeInBits)
3526 return DAG.getConstant(0, VT);
3527 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3528 DAG.getConstant(c1 + c2, N1.getValueType()));
3531 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3532 // For this to be valid, the second form must not preserve any of the bits
3533 // that are shifted out by the inner shift in the first form. This means
3534 // the outer shift size must be >= the number of bits added by the ext.
3535 // As a corollary, we don't care what kind of ext it is.
3536 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3537 N0.getOpcode() == ISD::ANY_EXTEND ||
3538 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3539 N0.getOperand(0).getOpcode() == ISD::SHL &&
3540 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3542 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3543 uint64_t c2 = N1C->getZExtValue();
3544 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3545 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3546 if (c2 >= OpSizeInBits - InnerShiftSize) {
3547 if (c1 + c2 >= OpSizeInBits)
3548 return DAG.getConstant(0, VT);
3549 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3550 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3551 N0.getOperand(0)->getOperand(0)),
3552 DAG.getConstant(c1 + c2, N1.getValueType()));
3556 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3557 // (and (srl x, (sub c1, c2), MASK)
3558 // Only fold this if the inner shift has no other uses -- if it does, folding
3559 // this will increase the total number of instructions.
3560 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3561 N0.getOperand(1).getOpcode() == ISD::Constant) {
3562 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3563 if (c1 < VT.getSizeInBits()) {
3564 uint64_t c2 = N1C->getZExtValue();
3565 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3566 VT.getSizeInBits() - c1);
3569 Mask = Mask.shl(c2-c1);
3570 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3571 DAG.getConstant(c2-c1, N1.getValueType()));
3573 Mask = Mask.lshr(c1-c2);
3574 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3575 DAG.getConstant(c1-c2, N1.getValueType()));
3577 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3578 DAG.getConstant(Mask, VT));
3581 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3582 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3583 SDValue HiBitsMask =
3584 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3585 VT.getSizeInBits() -
3586 N1C->getZExtValue()),
3588 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3593 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3594 if (NewSHL.getNode())
3601 SDValue DAGCombiner::visitSRA(SDNode *N) {
3602 SDValue N0 = N->getOperand(0);
3603 SDValue N1 = N->getOperand(1);
3604 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3605 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3606 EVT VT = N0.getValueType();
3607 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3609 // fold (sra c1, c2) -> (sra c1, c2)
3611 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3612 // fold (sra 0, x) -> 0
3613 if (N0C && N0C->isNullValue())
3615 // fold (sra -1, x) -> -1
3616 if (N0C && N0C->isAllOnesValue())
3618 // fold (sra x, (setge c, size(x))) -> undef
3619 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3620 return DAG.getUNDEF(VT);
3621 // fold (sra x, 0) -> x
3622 if (N1C && N1C->isNullValue())
3624 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3626 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3627 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3628 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3630 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3631 ExtVT, VT.getVectorNumElements());
3632 if ((!LegalOperations ||
3633 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3634 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3635 N0.getOperand(0), DAG.getValueType(ExtVT));
3638 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3639 if (N1C && N0.getOpcode() == ISD::SRA) {
3640 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3641 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3642 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3643 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3644 DAG.getConstant(Sum, N1C->getValueType(0)));
3648 // fold (sra (shl X, m), (sub result_size, n))
3649 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3650 // result_size - n != m.
3651 // If truncate is free for the target sext(shl) is likely to result in better
3653 if (N0.getOpcode() == ISD::SHL) {
3654 // Get the two constanst of the shifts, CN0 = m, CN = n.
3655 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3657 // Determine what the truncate's result bitsize and type would be.
3659 EVT::getIntegerVT(*DAG.getContext(),
3660 OpSizeInBits - N1C->getZExtValue());
3661 // Determine the residual right-shift amount.
3662 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3664 // If the shift is not a no-op (in which case this should be just a sign
3665 // extend already), the truncated to type is legal, sign_extend is legal
3666 // on that type, and the truncate to that type is both legal and free,
3667 // perform the transform.
3668 if ((ShiftAmt > 0) &&
3669 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3670 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3671 TLI.isTruncateFree(VT, TruncVT)) {
3673 SDValue Amt = DAG.getConstant(ShiftAmt,
3674 getShiftAmountTy(N0.getOperand(0).getValueType()));
3675 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3676 N0.getOperand(0), Amt);
3677 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3679 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3680 N->getValueType(0), Trunc);
3685 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3686 if (N1.getOpcode() == ISD::TRUNCATE &&
3687 N1.getOperand(0).getOpcode() == ISD::AND &&
3688 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3689 SDValue N101 = N1.getOperand(0).getOperand(1);
3690 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3691 EVT TruncVT = N1.getValueType();
3692 SDValue N100 = N1.getOperand(0).getOperand(0);
3693 APInt TruncC = N101C->getAPIntValue();
3694 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3695 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3696 DAG.getNode(ISD::AND, N->getDebugLoc(),
3698 DAG.getNode(ISD::TRUNCATE,
3701 DAG.getConstant(TruncC, TruncVT)));
3705 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3706 // if c1 is equal to the number of bits the trunc removes
3707 if (N0.getOpcode() == ISD::TRUNCATE &&
3708 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3709 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3710 N0.getOperand(0).hasOneUse() &&
3711 N0.getOperand(0).getOperand(1).hasOneUse() &&
3712 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3713 EVT LargeVT = N0.getOperand(0).getValueType();
3714 ConstantSDNode *LargeShiftAmt =
3715 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3717 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3718 LargeShiftAmt->getZExtValue()) {
3720 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3721 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3722 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3723 N0.getOperand(0).getOperand(0), Amt);
3724 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3728 // Simplify, based on bits shifted out of the LHS.
3729 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3730 return SDValue(N, 0);
3733 // If the sign bit is known to be zero, switch this to a SRL.
3734 if (DAG.SignBitIsZero(N0))
3735 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3738 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3739 if (NewSRA.getNode())
3746 SDValue DAGCombiner::visitSRL(SDNode *N) {
3747 SDValue N0 = N->getOperand(0);
3748 SDValue N1 = N->getOperand(1);
3749 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3750 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3751 EVT VT = N0.getValueType();
3752 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3754 // fold (srl c1, c2) -> c1 >>u c2
3756 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3757 // fold (srl 0, x) -> 0
3758 if (N0C && N0C->isNullValue())
3760 // fold (srl x, c >= size(x)) -> undef
3761 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3762 return DAG.getUNDEF(VT);
3763 // fold (srl x, 0) -> x
3764 if (N1C && N1C->isNullValue())
3766 // if (srl x, c) is known to be zero, return 0
3767 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3768 APInt::getAllOnesValue(OpSizeInBits)))
3769 return DAG.getConstant(0, VT);
3771 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3772 if (N1C && N0.getOpcode() == ISD::SRL &&
3773 N0.getOperand(1).getOpcode() == ISD::Constant) {
3774 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3775 uint64_t c2 = N1C->getZExtValue();
3776 if (c1 + c2 >= OpSizeInBits)
3777 return DAG.getConstant(0, VT);
3778 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3779 DAG.getConstant(c1 + c2, N1.getValueType()));
3782 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3783 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3784 N0.getOperand(0).getOpcode() == ISD::SRL &&
3785 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3787 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3788 uint64_t c2 = N1C->getZExtValue();
3789 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3790 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3791 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3792 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3793 if (c1 + OpSizeInBits == InnerShiftSize) {
3794 if (c1 + c2 >= InnerShiftSize)
3795 return DAG.getConstant(0, VT);
3796 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3797 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3798 N0.getOperand(0)->getOperand(0),
3799 DAG.getConstant(c1 + c2, ShiftCountVT)));
3803 // fold (srl (shl x, c), c) -> (and x, cst2)
3804 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3805 N0.getValueSizeInBits() <= 64) {
3806 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3807 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3808 DAG.getConstant(~0ULL >> ShAmt, VT));
3812 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3813 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3814 // Shifting in all undef bits?
3815 EVT SmallVT = N0.getOperand(0).getValueType();
3816 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3817 return DAG.getUNDEF(VT);
3819 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3820 uint64_t ShiftAmt = N1C->getZExtValue();
3821 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3823 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3824 AddToWorkList(SmallShift.getNode());
3825 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3829 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3830 // bit, which is unmodified by sra.
3831 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3832 if (N0.getOpcode() == ISD::SRA)
3833 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3836 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3837 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3838 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3839 APInt KnownZero, KnownOne;
3840 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3842 // If any of the input bits are KnownOne, then the input couldn't be all
3843 // zeros, thus the result of the srl will always be zero.
3844 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3846 // If all of the bits input the to ctlz node are known to be zero, then
3847 // the result of the ctlz is "32" and the result of the shift is one.
3848 APInt UnknownBits = ~KnownZero;
3849 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3851 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3852 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3853 // Okay, we know that only that the single bit specified by UnknownBits
3854 // could be set on input to the CTLZ node. If this bit is set, the SRL
3855 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3856 // to an SRL/XOR pair, which is likely to simplify more.
3857 unsigned ShAmt = UnknownBits.countTrailingZeros();
3858 SDValue Op = N0.getOperand(0);
3861 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3862 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3863 AddToWorkList(Op.getNode());
3866 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3867 Op, DAG.getConstant(1, VT));
3871 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3872 if (N1.getOpcode() == ISD::TRUNCATE &&
3873 N1.getOperand(0).getOpcode() == ISD::AND &&
3874 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3875 SDValue N101 = N1.getOperand(0).getOperand(1);
3876 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3877 EVT TruncVT = N1.getValueType();
3878 SDValue N100 = N1.getOperand(0).getOperand(0);
3879 APInt TruncC = N101C->getAPIntValue();
3880 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3881 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3882 DAG.getNode(ISD::AND, N->getDebugLoc(),
3884 DAG.getNode(ISD::TRUNCATE,
3887 DAG.getConstant(TruncC, TruncVT)));
3891 // fold operands of srl based on knowledge that the low bits are not
3893 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3894 return SDValue(N, 0);
3897 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3898 if (NewSRL.getNode())
3902 // Attempt to convert a srl of a load into a narrower zero-extending load.
3903 SDValue NarrowLoad = ReduceLoadWidth(N);
3904 if (NarrowLoad.getNode())
3907 // Here is a common situation. We want to optimize:
3910 // %b = and i32 %a, 2
3911 // %c = srl i32 %b, 1
3912 // brcond i32 %c ...
3918 // %c = setcc eq %b, 0
3921 // However when after the source operand of SRL is optimized into AND, the SRL
3922 // itself may not be optimized further. Look for it and add the BRCOND into
3924 if (N->hasOneUse()) {
3925 SDNode *Use = *N->use_begin();
3926 if (Use->getOpcode() == ISD::BRCOND)
3928 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3929 // Also look pass the truncate.
3930 Use = *Use->use_begin();
3931 if (Use->getOpcode() == ISD::BRCOND)
3939 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3940 SDValue N0 = N->getOperand(0);
3941 EVT VT = N->getValueType(0);
3943 // fold (ctlz c1) -> c2
3944 if (isa<ConstantSDNode>(N0))
3945 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3949 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3950 SDValue N0 = N->getOperand(0);
3951 EVT VT = N->getValueType(0);
3953 // fold (ctlz_zero_undef c1) -> c2
3954 if (isa<ConstantSDNode>(N0))
3955 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3959 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3960 SDValue N0 = N->getOperand(0);
3961 EVT VT = N->getValueType(0);
3963 // fold (cttz c1) -> c2
3964 if (isa<ConstantSDNode>(N0))
3965 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3969 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
3970 SDValue N0 = N->getOperand(0);
3971 EVT VT = N->getValueType(0);
3973 // fold (cttz_zero_undef c1) -> c2
3974 if (isa<ConstantSDNode>(N0))
3975 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3979 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3980 SDValue N0 = N->getOperand(0);
3981 EVT VT = N->getValueType(0);
3983 // fold (ctpop c1) -> c2
3984 if (isa<ConstantSDNode>(N0))
3985 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3989 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3990 SDValue N0 = N->getOperand(0);
3991 SDValue N1 = N->getOperand(1);
3992 SDValue N2 = N->getOperand(2);
3993 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3994 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3995 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3996 EVT VT = N->getValueType(0);
3997 EVT VT0 = N0.getValueType();
3999 // fold (select C, X, X) -> X
4002 // fold (select true, X, Y) -> X
4003 if (N0C && !N0C->isNullValue())
4005 // fold (select false, X, Y) -> Y
4006 if (N0C && N0C->isNullValue())
4008 // fold (select C, 1, X) -> (or C, X)
4009 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4010 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4011 // fold (select C, 0, 1) -> (xor C, 1)
4012 if (VT.isInteger() &&
4015 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
4016 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4019 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4020 N0, DAG.getConstant(1, VT0));
4021 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4022 N0, DAG.getConstant(1, VT0));
4023 AddToWorkList(XORNode.getNode());
4025 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4026 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4028 // fold (select C, 0, X) -> (and (not C), X)
4029 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4030 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4031 AddToWorkList(NOTNode.getNode());
4032 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4034 // fold (select C, X, 1) -> (or (not C), X)
4035 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4036 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4037 AddToWorkList(NOTNode.getNode());
4038 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4040 // fold (select C, X, 0) -> (and C, X)
4041 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4042 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4043 // fold (select X, X, Y) -> (or X, Y)
4044 // fold (select X, 1, Y) -> (or X, Y)
4045 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4046 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4047 // fold (select X, Y, X) -> (and X, Y)
4048 // fold (select X, Y, 0) -> (and X, Y)
4049 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4050 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4052 // If we can fold this based on the true/false value, do so.
4053 if (SimplifySelectOps(N, N1, N2))
4054 return SDValue(N, 0); // Don't revisit N.
4056 // fold selects based on a setcc into other things, such as min/max/abs
4057 if (N0.getOpcode() == ISD::SETCC) {
4059 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4060 // having to say they don't support SELECT_CC on every type the DAG knows
4061 // about, since there is no way to mark an opcode illegal at all value types
4062 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4063 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4064 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4065 N0.getOperand(0), N0.getOperand(1),
4066 N1, N2, N0.getOperand(2));
4067 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4073 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4074 SDValue N0 = N->getOperand(0);
4075 SDValue N1 = N->getOperand(1);
4076 SDValue N2 = N->getOperand(2);
4077 SDValue N3 = N->getOperand(3);
4078 SDValue N4 = N->getOperand(4);
4079 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4081 // fold select_cc lhs, rhs, x, x, cc -> x
4085 // Determine if the condition we're dealing with is constant
4086 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4087 N0, N1, CC, N->getDebugLoc(), false);
4088 if (SCC.getNode()) AddToWorkList(SCC.getNode());
4090 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4091 if (!SCCC->isNullValue())
4092 return N2; // cond always true -> true val
4094 return N3; // cond always false -> false val
4097 // Fold to a simpler select_cc
4098 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4099 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4100 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4103 // If we can fold this based on the true/false value, do so.
4104 if (SimplifySelectOps(N, N2, N3))
4105 return SDValue(N, 0); // Don't revisit N.
4107 // fold select_cc into other things, such as min/max/abs
4108 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4111 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4112 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4113 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4117 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4118 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4119 // transformation. Returns true if extension are possible and the above
4120 // mentioned transformation is profitable.
4121 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4123 SmallVector<SDNode*, 4> &ExtendNodes,
4124 const TargetLowering &TLI) {
4125 bool HasCopyToRegUses = false;
4126 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4127 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4128 UE = N0.getNode()->use_end();
4133 if (UI.getUse().getResNo() != N0.getResNo())
4135 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4136 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4137 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4138 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4139 // Sign bits will be lost after a zext.
4142 for (unsigned i = 0; i != 2; ++i) {
4143 SDValue UseOp = User->getOperand(i);
4146 if (!isa<ConstantSDNode>(UseOp))
4151 ExtendNodes.push_back(User);
4154 // If truncates aren't free and there are users we can't
4155 // extend, it isn't worthwhile.
4158 // Remember if this value is live-out.
4159 if (User->getOpcode() == ISD::CopyToReg)
4160 HasCopyToRegUses = true;
4163 if (HasCopyToRegUses) {
4164 bool BothLiveOut = false;
4165 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4167 SDUse &Use = UI.getUse();
4168 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4174 // Both unextended and extended values are live out. There had better be
4175 // a good reason for the transformation.
4176 return ExtendNodes.size();
4181 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4182 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4183 ISD::NodeType ExtType) {
4184 // Extend SetCC uses if necessary.
4185 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4186 SDNode *SetCC = SetCCs[i];
4187 SmallVector<SDValue, 4> Ops;
4189 for (unsigned j = 0; j != 2; ++j) {
4190 SDValue SOp = SetCC->getOperand(j);
4192 Ops.push_back(ExtLoad);
4194 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4197 Ops.push_back(SetCC->getOperand(2));
4198 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4199 &Ops[0], Ops.size()));
4203 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4204 SDValue N0 = N->getOperand(0);
4205 EVT VT = N->getValueType(0);
4207 // fold (sext c1) -> c1
4208 if (isa<ConstantSDNode>(N0))
4209 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4211 // fold (sext (sext x)) -> (sext x)
4212 // fold (sext (aext x)) -> (sext x)
4213 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4214 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4217 if (N0.getOpcode() == ISD::TRUNCATE) {
4218 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4219 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4220 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4221 if (NarrowLoad.getNode()) {
4222 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4223 if (NarrowLoad.getNode() != N0.getNode()) {
4224 CombineTo(N0.getNode(), NarrowLoad);
4225 // CombineTo deleted the truncate, if needed, but not what's under it.
4228 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4231 // See if the value being truncated is already sign extended. If so, just
4232 // eliminate the trunc/sext pair.
4233 SDValue Op = N0.getOperand(0);
4234 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4235 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4236 unsigned DestBits = VT.getScalarType().getSizeInBits();
4237 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4239 if (OpBits == DestBits) {
4240 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4241 // bits, it is already ready.
4242 if (NumSignBits > DestBits-MidBits)
4244 } else if (OpBits < DestBits) {
4245 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4246 // bits, just sext from i32.
4247 if (NumSignBits > OpBits-MidBits)
4248 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4250 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4251 // bits, just truncate to i32.
4252 if (NumSignBits > OpBits-MidBits)
4253 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4256 // fold (sext (truncate x)) -> (sextinreg x).
4257 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4258 N0.getValueType())) {
4259 if (OpBits < DestBits)
4260 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4261 else if (OpBits > DestBits)
4262 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4263 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4264 DAG.getValueType(N0.getValueType()));
4268 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4269 // None of the supported targets knows how to perform load and sign extend
4270 // on vectors in one instruction. We only perform this transformation on
4272 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4273 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4274 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4275 bool DoXform = true;
4276 SmallVector<SDNode*, 4> SetCCs;
4277 if (!N0.hasOneUse())
4278 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4280 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4281 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4283 LN0->getBasePtr(), LN0->getPointerInfo(),
4285 LN0->isVolatile(), LN0->isNonTemporal(),
4286 LN0->getAlignment());
4287 CombineTo(N, ExtLoad);
4288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4289 N0.getValueType(), ExtLoad);
4290 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4291 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4293 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4297 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4298 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4299 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4300 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4301 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4302 EVT MemVT = LN0->getMemoryVT();
4303 if ((!LegalOperations && !LN0->isVolatile()) ||
4304 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4305 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4307 LN0->getBasePtr(), LN0->getPointerInfo(),
4309 LN0->isVolatile(), LN0->isNonTemporal(),
4310 LN0->getAlignment());
4311 CombineTo(N, ExtLoad);
4312 CombineTo(N0.getNode(),
4313 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4314 N0.getValueType(), ExtLoad),
4315 ExtLoad.getValue(1));
4316 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4320 // fold (sext (and/or/xor (load x), cst)) ->
4321 // (and/or/xor (sextload x), (sext cst))
4322 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4323 N0.getOpcode() == ISD::XOR) &&
4324 isa<LoadSDNode>(N0.getOperand(0)) &&
4325 N0.getOperand(1).getOpcode() == ISD::Constant &&
4326 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4327 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4328 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4329 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4330 bool DoXform = true;
4331 SmallVector<SDNode*, 4> SetCCs;
4332 if (!N0.hasOneUse())
4333 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4336 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4337 LN0->getChain(), LN0->getBasePtr(),
4338 LN0->getPointerInfo(),
4341 LN0->isNonTemporal(),
4342 LN0->getAlignment());
4343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4344 Mask = Mask.sext(VT.getSizeInBits());
4345 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4346 ExtLoad, DAG.getConstant(Mask, VT));
4347 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4348 N0.getOperand(0).getDebugLoc(),
4349 N0.getOperand(0).getValueType(), ExtLoad);
4351 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4352 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4354 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4359 if (N0.getOpcode() == ISD::SETCC) {
4360 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4361 // Only do this before legalize for now.
4362 if (VT.isVector() && !LegalOperations) {
4363 EVT N0VT = N0.getOperand(0).getValueType();
4364 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4365 // of the same size as the compared operands. Only optimize sext(setcc())
4366 // if this is the case.
4367 EVT SVT = TLI.getSetCCResultType(N0VT);
4369 // We know that the # elements of the results is the same as the
4370 // # elements of the compare (and the # elements of the compare result
4371 // for that matter). Check to see that they are the same size. If so,
4372 // we know that the element size of the sext'd result matches the
4373 // element size of the compare operands.
4374 if (VT.getSizeInBits() == SVT.getSizeInBits())
4375 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4377 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4378 // If the desired elements are smaller or larger than the source
4379 // elements we can use a matching integer vector type and then
4380 // truncate/sign extend
4382 EVT MatchingElementType =
4383 EVT::getIntegerVT(*DAG.getContext(),
4384 N0VT.getScalarType().getSizeInBits());
4385 EVT MatchingVectorType =
4386 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4387 N0VT.getVectorNumElements());
4389 if (SVT == MatchingVectorType) {
4390 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4391 N0.getOperand(0), N0.getOperand(1),
4392 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4393 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4398 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4399 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4401 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4403 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4404 NegOne, DAG.getConstant(0, VT),
4405 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4406 if (SCC.getNode()) return SCC;
4407 if (!LegalOperations ||
4408 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4409 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4410 DAG.getSetCC(N->getDebugLoc(),
4411 TLI.getSetCCResultType(VT),
4412 N0.getOperand(0), N0.getOperand(1),
4413 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4414 NegOne, DAG.getConstant(0, VT));
4417 // fold (sext x) -> (zext x) if the sign bit is known zero.
4418 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4419 DAG.SignBitIsZero(N0))
4420 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4425 // isTruncateOf - If N is a truncate of some other value, return true, record
4426 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4427 // This function computes KnownZero to avoid a duplicated call to
4428 // ComputeMaskedBits in the caller.
4429 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4432 if (N->getOpcode() == ISD::TRUNCATE) {
4433 Op = N->getOperand(0);
4434 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4438 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4439 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4442 SDValue Op0 = N->getOperand(0);
4443 SDValue Op1 = N->getOperand(1);
4444 assert(Op0.getValueType() == Op1.getValueType());
4446 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4447 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4448 if (COp0 && COp0->isNullValue())
4450 else if (COp1 && COp1->isNullValue())
4455 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4457 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4463 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4464 SDValue N0 = N->getOperand(0);
4465 EVT VT = N->getValueType(0);
4467 // fold (zext c1) -> c1
4468 if (isa<ConstantSDNode>(N0))
4469 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4470 // fold (zext (zext x)) -> (zext x)
4471 // fold (zext (aext x)) -> (zext x)
4472 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4473 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4476 // fold (zext (truncate x)) -> (zext x) or
4477 // (zext (truncate x)) -> (truncate x)
4478 // This is valid when the truncated bits of x are already zero.
4479 // FIXME: We should extend this to work for vectors too.
4482 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4483 APInt TruncatedBits =
4484 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4485 APInt(Op.getValueSizeInBits(), 0) :
4486 APInt::getBitsSet(Op.getValueSizeInBits(),
4487 N0.getValueSizeInBits(),
4488 std::min(Op.getValueSizeInBits(),
4489 VT.getSizeInBits()));
4490 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4491 if (VT.bitsGT(Op.getValueType()))
4492 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4493 if (VT.bitsLT(Op.getValueType()))
4494 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4500 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4501 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4502 if (N0.getOpcode() == ISD::TRUNCATE) {
4503 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4504 if (NarrowLoad.getNode()) {
4505 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4506 if (NarrowLoad.getNode() != N0.getNode()) {
4507 CombineTo(N0.getNode(), NarrowLoad);
4508 // CombineTo deleted the truncate, if needed, but not what's under it.
4511 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4515 // fold (zext (truncate x)) -> (and x, mask)
4516 if (N0.getOpcode() == ISD::TRUNCATE &&
4517 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4519 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4520 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4521 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4522 if (NarrowLoad.getNode()) {
4523 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4524 if (NarrowLoad.getNode() != N0.getNode()) {
4525 CombineTo(N0.getNode(), NarrowLoad);
4526 // CombineTo deleted the truncate, if needed, but not what's under it.
4529 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4532 SDValue Op = N0.getOperand(0);
4533 if (Op.getValueType().bitsLT(VT)) {
4534 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4535 AddToWorkList(Op.getNode());
4536 } else if (Op.getValueType().bitsGT(VT)) {
4537 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4538 AddToWorkList(Op.getNode());
4540 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4541 N0.getValueType().getScalarType());
4544 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4545 // if either of the casts is not free.
4546 if (N0.getOpcode() == ISD::AND &&
4547 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4548 N0.getOperand(1).getOpcode() == ISD::Constant &&
4549 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4550 N0.getValueType()) ||
4551 !TLI.isZExtFree(N0.getValueType(), VT))) {
4552 SDValue X = N0.getOperand(0).getOperand(0);
4553 if (X.getValueType().bitsLT(VT)) {
4554 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4555 } else if (X.getValueType().bitsGT(VT)) {
4556 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4558 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4559 Mask = Mask.zext(VT.getSizeInBits());
4560 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4561 X, DAG.getConstant(Mask, VT));
4564 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4565 // None of the supported targets knows how to perform load and vector_zext
4566 // on vectors in one instruction. We only perform this transformation on
4568 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4569 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4570 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4571 bool DoXform = true;
4572 SmallVector<SDNode*, 4> SetCCs;
4573 if (!N0.hasOneUse())
4574 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4576 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4577 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4579 LN0->getBasePtr(), LN0->getPointerInfo(),
4581 LN0->isVolatile(), LN0->isNonTemporal(),
4582 LN0->getAlignment());
4583 CombineTo(N, ExtLoad);
4584 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4585 N0.getValueType(), ExtLoad);
4586 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4588 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4590 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4594 // fold (zext (and/or/xor (load x), cst)) ->
4595 // (and/or/xor (zextload x), (zext cst))
4596 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4597 N0.getOpcode() == ISD::XOR) &&
4598 isa<LoadSDNode>(N0.getOperand(0)) &&
4599 N0.getOperand(1).getOpcode() == ISD::Constant &&
4600 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4601 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4602 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4603 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4604 bool DoXform = true;
4605 SmallVector<SDNode*, 4> SetCCs;
4606 if (!N0.hasOneUse())
4607 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4610 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4611 LN0->getChain(), LN0->getBasePtr(),
4612 LN0->getPointerInfo(),
4615 LN0->isNonTemporal(),
4616 LN0->getAlignment());
4617 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4618 Mask = Mask.zext(VT.getSizeInBits());
4619 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4620 ExtLoad, DAG.getConstant(Mask, VT));
4621 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4622 N0.getOperand(0).getDebugLoc(),
4623 N0.getOperand(0).getValueType(), ExtLoad);
4625 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4626 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4628 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4633 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4634 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4635 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4636 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4637 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4638 EVT MemVT = LN0->getMemoryVT();
4639 if ((!LegalOperations && !LN0->isVolatile()) ||
4640 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4641 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4643 LN0->getBasePtr(), LN0->getPointerInfo(),
4645 LN0->isVolatile(), LN0->isNonTemporal(),
4646 LN0->getAlignment());
4647 CombineTo(N, ExtLoad);
4648 CombineTo(N0.getNode(),
4649 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4651 ExtLoad.getValue(1));
4652 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4656 if (N0.getOpcode() == ISD::SETCC) {
4657 if (!LegalOperations && VT.isVector()) {
4658 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4659 // Only do this before legalize for now.
4660 EVT N0VT = N0.getOperand(0).getValueType();
4661 EVT EltVT = VT.getVectorElementType();
4662 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4663 DAG.getConstant(1, EltVT));
4664 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4665 // We know that the # elements of the results is the same as the
4666 // # elements of the compare (and the # elements of the compare result
4667 // for that matter). Check to see that they are the same size. If so,
4668 // we know that the element size of the sext'd result matches the
4669 // element size of the compare operands.
4670 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4671 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4673 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4674 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4675 &OneOps[0], OneOps.size()));
4677 // If the desired elements are smaller or larger than the source
4678 // elements we can use a matching integer vector type and then
4679 // truncate/sign extend
4680 EVT MatchingElementType =
4681 EVT::getIntegerVT(*DAG.getContext(),
4682 N0VT.getScalarType().getSizeInBits());
4683 EVT MatchingVectorType =
4684 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4685 N0VT.getVectorNumElements());
4687 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4689 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4690 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4691 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4692 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4693 &OneOps[0], OneOps.size()));
4696 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4698 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4699 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4700 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4701 if (SCC.getNode()) return SCC;
4704 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4705 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4706 isa<ConstantSDNode>(N0.getOperand(1)) &&
4707 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4709 SDValue ShAmt = N0.getOperand(1);
4710 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4711 if (N0.getOpcode() == ISD::SHL) {
4712 SDValue InnerZExt = N0.getOperand(0);
4713 // If the original shl may be shifting out bits, do not perform this
4715 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4716 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4717 if (ShAmtVal > KnownZeroBits)
4721 DebugLoc DL = N->getDebugLoc();
4723 // Ensure that the shift amount is wide enough for the shifted value.
4724 if (VT.getSizeInBits() >= 256)
4725 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4727 return DAG.getNode(N0.getOpcode(), DL, VT,
4728 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4735 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4736 SDValue N0 = N->getOperand(0);
4737 EVT VT = N->getValueType(0);
4739 // fold (aext c1) -> c1
4740 if (isa<ConstantSDNode>(N0))
4741 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4742 // fold (aext (aext x)) -> (aext x)
4743 // fold (aext (zext x)) -> (zext x)
4744 // fold (aext (sext x)) -> (sext x)
4745 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4746 N0.getOpcode() == ISD::ZERO_EXTEND ||
4747 N0.getOpcode() == ISD::SIGN_EXTEND)
4748 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4750 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4751 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4752 if (N0.getOpcode() == ISD::TRUNCATE) {
4753 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4754 if (NarrowLoad.getNode()) {
4755 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4756 if (NarrowLoad.getNode() != N0.getNode()) {
4757 CombineTo(N0.getNode(), NarrowLoad);
4758 // CombineTo deleted the truncate, if needed, but not what's under it.
4761 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4765 // fold (aext (truncate x))
4766 if (N0.getOpcode() == ISD::TRUNCATE) {
4767 SDValue TruncOp = N0.getOperand(0);
4768 if (TruncOp.getValueType() == VT)
4769 return TruncOp; // x iff x size == zext size.
4770 if (TruncOp.getValueType().bitsGT(VT))
4771 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4772 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4775 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4776 // if the trunc is not free.
4777 if (N0.getOpcode() == ISD::AND &&
4778 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4779 N0.getOperand(1).getOpcode() == ISD::Constant &&
4780 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4781 N0.getValueType())) {
4782 SDValue X = N0.getOperand(0).getOperand(0);
4783 if (X.getValueType().bitsLT(VT)) {
4784 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4785 } else if (X.getValueType().bitsGT(VT)) {
4786 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4788 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4789 Mask = Mask.zext(VT.getSizeInBits());
4790 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4791 X, DAG.getConstant(Mask, VT));
4794 // fold (aext (load x)) -> (aext (truncate (extload x)))
4795 // None of the supported targets knows how to perform load and any_ext
4796 // on vectors in one instruction. We only perform this transformation on
4798 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4799 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4800 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4801 bool DoXform = true;
4802 SmallVector<SDNode*, 4> SetCCs;
4803 if (!N0.hasOneUse())
4804 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4806 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4807 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4809 LN0->getBasePtr(), LN0->getPointerInfo(),
4811 LN0->isVolatile(), LN0->isNonTemporal(),
4812 LN0->getAlignment());
4813 CombineTo(N, ExtLoad);
4814 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4815 N0.getValueType(), ExtLoad);
4816 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4817 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4823 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4824 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4825 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4826 if (N0.getOpcode() == ISD::LOAD &&
4827 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4830 EVT MemVT = LN0->getMemoryVT();
4831 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4832 VT, LN0->getChain(), LN0->getBasePtr(),
4833 LN0->getPointerInfo(), MemVT,
4834 LN0->isVolatile(), LN0->isNonTemporal(),
4835 LN0->getAlignment());
4836 CombineTo(N, ExtLoad);
4837 CombineTo(N0.getNode(),
4838 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4839 N0.getValueType(), ExtLoad),
4840 ExtLoad.getValue(1));
4841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4844 if (N0.getOpcode() == ISD::SETCC) {
4845 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4846 // Only do this before legalize for now.
4847 if (VT.isVector() && !LegalOperations) {
4848 EVT N0VT = N0.getOperand(0).getValueType();
4849 // We know that the # elements of the results is the same as the
4850 // # elements of the compare (and the # elements of the compare result
4851 // for that matter). Check to see that they are the same size. If so,
4852 // we know that the element size of the sext'd result matches the
4853 // element size of the compare operands.
4854 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4855 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4857 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4858 // If the desired elements are smaller or larger than the source
4859 // elements we can use a matching integer vector type and then
4860 // truncate/sign extend
4862 EVT MatchingElementType =
4863 EVT::getIntegerVT(*DAG.getContext(),
4864 N0VT.getScalarType().getSizeInBits());
4865 EVT MatchingVectorType =
4866 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4867 N0VT.getVectorNumElements());
4869 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4871 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4872 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4876 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4878 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4879 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4880 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4888 /// GetDemandedBits - See if the specified operand can be simplified with the
4889 /// knowledge that only the bits specified by Mask are used. If so, return the
4890 /// simpler operand, otherwise return a null SDValue.
4891 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4892 switch (V.getOpcode()) {
4894 case ISD::Constant: {
4895 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4896 assert(CV != 0 && "Const value should be ConstSDNode.");
4897 const APInt &CVal = CV->getAPIntValue();
4898 APInt NewVal = CVal & Mask;
4899 if (NewVal != CVal) {
4900 return DAG.getConstant(NewVal, V.getValueType());
4906 // If the LHS or RHS don't contribute bits to the or, drop them.
4907 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4908 return V.getOperand(1);
4909 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4910 return V.getOperand(0);
4913 // Only look at single-use SRLs.
4914 if (!V.getNode()->hasOneUse())
4916 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4917 // See if we can recursively simplify the LHS.
4918 unsigned Amt = RHSC->getZExtValue();
4920 // Watch out for shift count overflow though.
4921 if (Amt >= Mask.getBitWidth()) break;
4922 APInt NewMask = Mask << Amt;
4923 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4924 if (SimplifyLHS.getNode())
4925 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4926 SimplifyLHS, V.getOperand(1));
4932 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4933 /// bits and then truncated to a narrower type and where N is a multiple
4934 /// of number of bits of the narrower type, transform it to a narrower load
4935 /// from address + N / num of bits of new type. If the result is to be
4936 /// extended, also fold the extension to form a extending load.
4937 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4938 unsigned Opc = N->getOpcode();
4940 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4941 SDValue N0 = N->getOperand(0);
4942 EVT VT = N->getValueType(0);
4945 // This transformation isn't valid for vector loads.
4949 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4951 if (Opc == ISD::SIGN_EXTEND_INREG) {
4952 ExtType = ISD::SEXTLOAD;
4953 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4954 } else if (Opc == ISD::SRL) {
4955 // Another special-case: SRL is basically zero-extending a narrower value.
4956 ExtType = ISD::ZEXTLOAD;
4958 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4959 if (!N01) return SDValue();
4960 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4961 VT.getSizeInBits() - N01->getZExtValue());
4963 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4966 unsigned EVTBits = ExtVT.getSizeInBits();
4968 // Do not generate loads of non-round integer types since these can
4969 // be expensive (and would be wrong if the type is not byte sized).
4970 if (!ExtVT.isRound())
4974 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4975 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4976 ShAmt = N01->getZExtValue();
4977 // Is the shift amount a multiple of size of VT?
4978 if ((ShAmt & (EVTBits-1)) == 0) {
4979 N0 = N0.getOperand(0);
4980 // Is the load width a multiple of size of VT?
4981 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4985 // At this point, we must have a load or else we can't do the transform.
4986 if (!isa<LoadSDNode>(N0)) return SDValue();
4988 // If the shift amount is larger than the input type then we're not
4989 // accessing any of the loaded bytes. If the load was a zextload/extload
4990 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4991 // If the load was a sextload then the result is a splat of the sign bit
4992 // of the extended byte. This is not worth optimizing for.
4993 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4998 // If the load is shifted left (and the result isn't shifted back right),
4999 // we can fold the truncate through the shift.
5000 unsigned ShLeftAmt = 0;
5001 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5002 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5003 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5004 ShLeftAmt = N01->getZExtValue();
5005 N0 = N0.getOperand(0);
5009 // If we haven't found a load, we can't narrow it. Don't transform one with
5010 // multiple uses, this would require adding a new load.
5011 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
5012 // Don't change the width of a volatile load.
5013 cast<LoadSDNode>(N0)->isVolatile())
5016 // Verify that we are actually reducing a load width here.
5017 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5020 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5021 EVT PtrType = N0.getOperand(1).getValueType();
5023 if (PtrType == MVT::Untyped || PtrType.isExtended())
5024 // It's not possible to generate a constant of extended or untyped type.
5027 // For big endian targets, we need to adjust the offset to the pointer to
5028 // load the correct bytes.
5029 if (TLI.isBigEndian()) {
5030 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5031 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5032 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5035 uint64_t PtrOff = ShAmt / 8;
5036 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5037 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5038 PtrType, LN0->getBasePtr(),
5039 DAG.getConstant(PtrOff, PtrType));
5040 AddToWorkList(NewPtr.getNode());
5043 if (ExtType == ISD::NON_EXTLOAD)
5044 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5045 LN0->getPointerInfo().getWithOffset(PtrOff),
5046 LN0->isVolatile(), LN0->isNonTemporal(),
5047 LN0->isInvariant(), NewAlign);
5049 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5050 LN0->getPointerInfo().getWithOffset(PtrOff),
5051 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5054 // Replace the old load's chain with the new load's chain.
5055 WorkListRemover DeadNodes(*this);
5056 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5058 // Shift the result left, if we've swallowed a left shift.
5059 SDValue Result = Load;
5060 if (ShLeftAmt != 0) {
5061 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5062 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5064 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5065 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5068 // Return the new loaded value.
5072 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5073 SDValue N0 = N->getOperand(0);
5074 SDValue N1 = N->getOperand(1);
5075 EVT VT = N->getValueType(0);
5076 EVT EVT = cast<VTSDNode>(N1)->getVT();
5077 unsigned VTBits = VT.getScalarType().getSizeInBits();
5078 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5080 // fold (sext_in_reg c1) -> c1
5081 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5082 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5084 // If the input is already sign extended, just drop the extension.
5085 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5088 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5089 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5090 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5091 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5092 N0.getOperand(0), N1);
5095 // fold (sext_in_reg (sext x)) -> (sext x)
5096 // fold (sext_in_reg (aext x)) -> (sext x)
5097 // if x is small enough.
5098 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5099 SDValue N00 = N0.getOperand(0);
5100 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5101 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5102 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5105 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5106 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5107 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5109 // fold operands of sext_in_reg based on knowledge that the top bits are not
5111 if (SimplifyDemandedBits(SDValue(N, 0)))
5112 return SDValue(N, 0);
5114 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5115 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5116 SDValue NarrowLoad = ReduceLoadWidth(N);
5117 if (NarrowLoad.getNode())
5120 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5121 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5122 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5123 if (N0.getOpcode() == ISD::SRL) {
5124 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5125 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5126 // We can turn this into an SRA iff the input to the SRL is already sign
5128 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5129 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5130 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5131 N0.getOperand(0), N0.getOperand(1));
5135 // fold (sext_inreg (extload x)) -> (sextload x)
5136 if (ISD::isEXTLoad(N0.getNode()) &&
5137 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5138 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5139 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5140 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5141 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5142 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5144 LN0->getBasePtr(), LN0->getPointerInfo(),
5146 LN0->isVolatile(), LN0->isNonTemporal(),
5147 LN0->getAlignment());
5148 CombineTo(N, ExtLoad);
5149 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5152 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5153 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5155 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5156 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5157 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5158 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5159 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5161 LN0->getBasePtr(), LN0->getPointerInfo(),
5163 LN0->isVolatile(), LN0->isNonTemporal(),
5164 LN0->getAlignment());
5165 CombineTo(N, ExtLoad);
5166 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5170 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5171 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5172 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5173 N0.getOperand(1), false);
5174 if (BSwap.getNode() != 0)
5175 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5182 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5183 SDValue N0 = N->getOperand(0);
5184 EVT VT = N->getValueType(0);
5185 bool isLE = TLI.isLittleEndian();
5188 if (N0.getValueType() == N->getValueType(0))
5190 // fold (truncate c1) -> c1
5191 if (isa<ConstantSDNode>(N0))
5192 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5193 // fold (truncate (truncate x)) -> (truncate x)
5194 if (N0.getOpcode() == ISD::TRUNCATE)
5195 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5196 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5197 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5198 N0.getOpcode() == ISD::SIGN_EXTEND ||
5199 N0.getOpcode() == ISD::ANY_EXTEND) {
5200 if (N0.getOperand(0).getValueType().bitsLT(VT))
5201 // if the source is smaller than the dest, we still need an extend
5202 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5204 else if (N0.getOperand(0).getValueType().bitsGT(VT))
5205 // if the source is larger than the dest, than we just need the truncate
5206 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5208 // if the source and dest are the same type, we can drop both the extend
5209 // and the truncate.
5210 return N0.getOperand(0);
5213 // Fold extract-and-trunc into a narrow extract. For example:
5214 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5215 // i32 y = TRUNCATE(i64 x)
5217 // v16i8 b = BITCAST (v2i64 val)
5218 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5220 // Note: We only run this optimization after type legalization (which often
5221 // creates this pattern) and before operation legalization after which
5222 // we need to be more careful about the vector instructions that we generate.
5223 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5224 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5226 EVT VecTy = N0.getOperand(0).getValueType();
5227 EVT ExTy = N0.getValueType();
5228 EVT TrTy = N->getValueType(0);
5230 unsigned NumElem = VecTy.getVectorNumElements();
5231 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5233 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5234 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5236 SDValue EltNo = N0->getOperand(1);
5237 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5238 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5239 EVT IndexTy = N0->getOperand(1).getValueType();
5240 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5242 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5243 NVT, N0.getOperand(0));
5245 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5246 N->getDebugLoc(), TrTy, V,
5247 DAG.getConstant(Index, IndexTy));
5251 // See if we can simplify the input to this truncate through knowledge that
5252 // only the low bits are being used.
5253 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5254 // Currently we only perform this optimization on scalars because vectors
5255 // may have different active low bits.
5256 if (!VT.isVector()) {
5258 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5259 VT.getSizeInBits()));
5260 if (Shorter.getNode())
5261 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5263 // fold (truncate (load x)) -> (smaller load x)
5264 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5265 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5266 SDValue Reduced = ReduceLoadWidth(N);
5267 if (Reduced.getNode())
5271 // Simplify the operands using demanded-bits information.
5272 if (!VT.isVector() &&
5273 SimplifyDemandedBits(SDValue(N, 0)))
5274 return SDValue(N, 0);
5279 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5280 SDValue Elt = N->getOperand(i);
5281 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5282 return Elt.getNode();
5283 return Elt.getOperand(Elt.getResNo()).getNode();
5286 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5287 /// if load locations are consecutive.
5288 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5289 assert(N->getOpcode() == ISD::BUILD_PAIR);
5291 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5292 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5293 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5294 LD1->getPointerInfo().getAddrSpace() !=
5295 LD2->getPointerInfo().getAddrSpace())
5297 EVT LD1VT = LD1->getValueType(0);
5299 if (ISD::isNON_EXTLoad(LD2) &&
5301 // If both are volatile this would reduce the number of volatile loads.
5302 // If one is volatile it might be ok, but play conservative and bail out.
5303 !LD1->isVolatile() &&
5304 !LD2->isVolatile() &&
5305 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5306 unsigned Align = LD1->getAlignment();
5307 unsigned NewAlign = TLI.getTargetData()->
5308 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5310 if (NewAlign <= Align &&
5311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5312 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5313 LD1->getBasePtr(), LD1->getPointerInfo(),
5314 false, false, false, Align);
5320 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5321 SDValue N0 = N->getOperand(0);
5322 EVT VT = N->getValueType(0);
5324 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5325 // Only do this before legalize, since afterward the target may be depending
5326 // on the bitconvert.
5327 // First check to see if this is all constant.
5329 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5331 bool isSimple = true;
5332 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5333 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5334 N0.getOperand(i).getOpcode() != ISD::Constant &&
5335 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5340 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5341 assert(!DestEltVT.isVector() &&
5342 "Element type of vector ValueType must not be vector!");
5344 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5347 // If the input is a constant, let getNode fold it.
5348 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5349 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5350 if (Res.getNode() != N) {
5351 if (!LegalOperations ||
5352 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5355 // Folding it resulted in an illegal node, and it's too late to
5356 // do that. Clean up the old node and forego the transformation.
5357 // Ideally this won't happen very often, because instcombine
5358 // and the earlier dagcombine runs (where illegal nodes are
5359 // permitted) should have folded most of them already.
5360 DAG.DeleteNode(Res.getNode());
5364 // (conv (conv x, t1), t2) -> (conv x, t2)
5365 if (N0.getOpcode() == ISD::BITCAST)
5366 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5369 // fold (conv (load x)) -> (load (conv*)x)
5370 // If the resultant load doesn't need a higher alignment than the original!
5371 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5372 // Do not change the width of a volatile load.
5373 !cast<LoadSDNode>(N0)->isVolatile() &&
5374 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5375 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5376 unsigned Align = TLI.getTargetData()->
5377 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5378 unsigned OrigAlign = LN0->getAlignment();
5380 if (Align <= OrigAlign) {
5381 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5382 LN0->getBasePtr(), LN0->getPointerInfo(),
5383 LN0->isVolatile(), LN0->isNonTemporal(),
5384 LN0->isInvariant(), OrigAlign);
5386 CombineTo(N0.getNode(),
5387 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5388 N0.getValueType(), Load),
5394 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5395 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5396 // This often reduces constant pool loads.
5397 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5398 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5399 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5400 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5402 AddToWorkList(NewConv.getNode());
5404 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5405 if (N0.getOpcode() == ISD::FNEG)
5406 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5407 NewConv, DAG.getConstant(SignBit, VT));
5408 assert(N0.getOpcode() == ISD::FABS);
5409 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5410 NewConv, DAG.getConstant(~SignBit, VT));
5413 // fold (bitconvert (fcopysign cst, x)) ->
5414 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5415 // Note that we don't handle (copysign x, cst) because this can always be
5416 // folded to an fneg or fabs.
5417 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5418 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5419 VT.isInteger() && !VT.isVector()) {
5420 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5421 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5422 if (isTypeLegal(IntXVT)) {
5423 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5424 IntXVT, N0.getOperand(1));
5425 AddToWorkList(X.getNode());
5427 // If X has a different width than the result/lhs, sext it or truncate it.
5428 unsigned VTWidth = VT.getSizeInBits();
5429 if (OrigXWidth < VTWidth) {
5430 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5431 AddToWorkList(X.getNode());
5432 } else if (OrigXWidth > VTWidth) {
5433 // To get the sign bit in the right place, we have to shift it right
5434 // before truncating.
5435 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5436 X.getValueType(), X,
5437 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5438 AddToWorkList(X.getNode());
5439 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5440 AddToWorkList(X.getNode());
5443 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5444 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5445 X, DAG.getConstant(SignBit, VT));
5446 AddToWorkList(X.getNode());
5448 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5449 VT, N0.getOperand(0));
5450 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5451 Cst, DAG.getConstant(~SignBit, VT));
5452 AddToWorkList(Cst.getNode());
5454 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5458 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5459 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5460 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5461 if (CombineLD.getNode())
5468 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5469 EVT VT = N->getValueType(0);
5470 return CombineConsecutiveLoads(N, VT);
5473 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5474 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5475 /// destination element value type.
5476 SDValue DAGCombiner::
5477 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5478 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5480 // If this is already the right type, we're done.
5481 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5483 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5484 unsigned DstBitSize = DstEltVT.getSizeInBits();
5486 // If this is a conversion of N elements of one type to N elements of another
5487 // type, convert each element. This handles FP<->INT cases.
5488 if (SrcBitSize == DstBitSize) {
5489 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5490 BV->getValueType(0).getVectorNumElements());
5492 // Due to the FP element handling below calling this routine recursively,
5493 // we can end up with a scalar-to-vector node here.
5494 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5495 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5496 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5497 DstEltVT, BV->getOperand(0)));
5499 SmallVector<SDValue, 8> Ops;
5500 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5501 SDValue Op = BV->getOperand(i);
5502 // If the vector element type is not legal, the BUILD_VECTOR operands
5503 // are promoted and implicitly truncated. Make that explicit here.
5504 if (Op.getValueType() != SrcEltVT)
5505 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5506 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5508 AddToWorkList(Ops.back().getNode());
5510 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5511 &Ops[0], Ops.size());
5514 // Otherwise, we're growing or shrinking the elements. To avoid having to
5515 // handle annoying details of growing/shrinking FP values, we convert them to
5517 if (SrcEltVT.isFloatingPoint()) {
5518 // Convert the input float vector to a int vector where the elements are the
5520 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5521 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5522 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5526 // Now we know the input is an integer vector. If the output is a FP type,
5527 // convert to integer first, then to FP of the right size.
5528 if (DstEltVT.isFloatingPoint()) {
5529 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5530 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5531 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5533 // Next, convert to FP elements of the same size.
5534 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5537 // Okay, we know the src/dst types are both integers of differing types.
5538 // Handling growing first.
5539 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5540 if (SrcBitSize < DstBitSize) {
5541 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5543 SmallVector<SDValue, 8> Ops;
5544 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5545 i += NumInputsPerOutput) {
5546 bool isLE = TLI.isLittleEndian();
5547 APInt NewBits = APInt(DstBitSize, 0);
5548 bool EltIsUndef = true;
5549 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5550 // Shift the previously computed bits over.
5551 NewBits <<= SrcBitSize;
5552 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5553 if (Op.getOpcode() == ISD::UNDEF) continue;
5556 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5557 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5561 Ops.push_back(DAG.getUNDEF(DstEltVT));
5563 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5566 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5567 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5568 &Ops[0], Ops.size());
5571 // Finally, this must be the case where we are shrinking elements: each input
5572 // turns into multiple outputs.
5573 bool isS2V = ISD::isScalarToVector(BV);
5574 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5575 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5576 NumOutputsPerInput*BV->getNumOperands());
5577 SmallVector<SDValue, 8> Ops;
5579 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5580 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5581 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5582 Ops.push_back(DAG.getUNDEF(DstEltVT));
5586 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5587 getAPIntValue().zextOrTrunc(SrcBitSize);
5589 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5590 APInt ThisVal = OpVal.trunc(DstBitSize);
5591 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5592 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5593 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5594 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5596 OpVal = OpVal.lshr(DstBitSize);
5599 // For big endian targets, swap the order of the pieces of each element.
5600 if (TLI.isBigEndian())
5601 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5604 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5605 &Ops[0], Ops.size());
5608 SDValue DAGCombiner::visitFADD(SDNode *N) {
5609 SDValue N0 = N->getOperand(0);
5610 SDValue N1 = N->getOperand(1);
5611 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5612 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5613 EVT VT = N->getValueType(0);
5616 if (VT.isVector()) {
5617 SDValue FoldedVOp = SimplifyVBinOp(N);
5618 if (FoldedVOp.getNode()) return FoldedVOp;
5621 // fold (fadd c1, c2) -> c1 + c2
5622 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5623 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5624 // canonicalize constant to RHS
5625 if (N0CFP && !N1CFP)
5626 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5627 // fold (fadd A, 0) -> A
5628 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5629 N1CFP->getValueAPF().isZero())
5631 // fold (fadd A, (fneg B)) -> (fsub A, B)
5632 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5633 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5634 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5635 GetNegatedExpression(N1, DAG, LegalOperations));
5636 // fold (fadd (fneg A), B) -> (fsub B, A)
5637 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5638 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5639 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5640 GetNegatedExpression(N0, DAG, LegalOperations));
5642 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5643 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5644 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5645 isa<ConstantFPSDNode>(N0.getOperand(1)))
5646 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5647 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5648 N0.getOperand(1), N1));
5650 // FADD -> FMA combines:
5651 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5652 DAG.getTarget().Options.UnsafeFPMath) &&
5653 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5654 TLI.isOperationLegal(ISD::FMA, VT)) {
5656 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5657 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5658 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5659 N0.getOperand(0), N0.getOperand(1), N1);
5662 // fold (fadd x, (fmul y, z)) -> (fma x, y, z)
5663 // Note: Commutes FADD operands.
5664 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5665 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5666 N1.getOperand(0), N1.getOperand(1), N0);
5673 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5674 SDValue N0 = N->getOperand(0);
5675 SDValue N1 = N->getOperand(1);
5676 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5677 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5678 EVT VT = N->getValueType(0);
5681 if (VT.isVector()) {
5682 SDValue FoldedVOp = SimplifyVBinOp(N);
5683 if (FoldedVOp.getNode()) return FoldedVOp;
5686 // fold (fsub c1, c2) -> c1-c2
5687 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5688 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5689 // fold (fsub A, 0) -> A
5690 if (DAG.getTarget().Options.UnsafeFPMath &&
5691 N1CFP && N1CFP->getValueAPF().isZero())
5693 // fold (fsub 0, B) -> -B
5694 if (DAG.getTarget().Options.UnsafeFPMath &&
5695 N0CFP && N0CFP->getValueAPF().isZero()) {
5696 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5697 return GetNegatedExpression(N1, DAG, LegalOperations);
5698 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5699 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
5701 // fold (fsub A, (fneg B)) -> (fadd A, B)
5702 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5703 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
5704 GetNegatedExpression(N1, DAG, LegalOperations));
5706 // If 'unsafe math' is enabled, fold
5707 // (fsub x, x) -> 0.0 &
5708 // (fsub x, (fadd x, y)) -> (fneg y) &
5709 // (fsub x, (fadd y, x)) -> (fneg y)
5710 if (DAG.getTarget().Options.UnsafeFPMath) {
5712 return DAG.getConstantFP(0.0f, VT);
5714 if (N1.getOpcode() == ISD::FADD) {
5715 SDValue N10 = N1->getOperand(0);
5716 SDValue N11 = N1->getOperand(1);
5718 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5719 &DAG.getTarget().Options))
5720 return GetNegatedExpression(N11, DAG, LegalOperations);
5721 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5722 &DAG.getTarget().Options))
5723 return GetNegatedExpression(N10, DAG, LegalOperations);
5727 // FSUB -> FMA combines:
5728 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5729 DAG.getTarget().Options.UnsafeFPMath) &&
5730 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5731 TLI.isOperationLegal(ISD::FMA, VT)) {
5733 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
5734 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5735 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5736 N0.getOperand(0), N0.getOperand(1),
5737 DAG.getNode(ISD::FNEG, N1->getDebugLoc(), VT, N1));
5740 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
5741 // Note: Commutes FSUB operands.
5742 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5743 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5744 DAG.getNode(ISD::FNEG, N1->getDebugLoc(), VT,
5746 N1.getOperand(1), N0);
5753 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5754 SDValue N0 = N->getOperand(0);
5755 SDValue N1 = N->getOperand(1);
5756 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5757 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5758 EVT VT = N->getValueType(0);
5759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5762 if (VT.isVector()) {
5763 SDValue FoldedVOp = SimplifyVBinOp(N);
5764 if (FoldedVOp.getNode()) return FoldedVOp;
5767 // fold (fmul c1, c2) -> c1*c2
5768 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5769 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5770 // canonicalize constant to RHS
5771 if (N0CFP && !N1CFP)
5772 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5773 // fold (fmul A, 0) -> 0
5774 if (DAG.getTarget().Options.UnsafeFPMath &&
5775 N1CFP && N1CFP->getValueAPF().isZero())
5777 // fold (fmul A, 0) -> 0, vector edition.
5778 if (DAG.getTarget().Options.UnsafeFPMath &&
5779 ISD::isBuildVectorAllZeros(N1.getNode()))
5781 // fold (fmul A, 1.0) -> A
5782 if (N1CFP && N1CFP->isExactlyValue(1.0))
5784 // fold (fmul X, 2.0) -> (fadd X, X)
5785 if (N1CFP && N1CFP->isExactlyValue(+2.0))
5786 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5787 // fold (fmul X, -1.0) -> (fneg X)
5788 if (N1CFP && N1CFP->isExactlyValue(-1.0))
5789 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5790 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5792 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5793 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5794 &DAG.getTarget().Options)) {
5795 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5796 &DAG.getTarget().Options)) {
5797 // Both can be negated for free, check to see if at least one is cheaper
5799 if (LHSNeg == 2 || RHSNeg == 2)
5800 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5801 GetNegatedExpression(N0, DAG, LegalOperations),
5802 GetNegatedExpression(N1, DAG, LegalOperations));
5806 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5807 if (DAG.getTarget().Options.UnsafeFPMath &&
5808 N1CFP && N0.getOpcode() == ISD::FMUL &&
5809 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5810 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5811 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5812 N0.getOperand(1), N1));
5817 SDValue DAGCombiner::visitFMA(SDNode *N) {
5818 SDValue N0 = N->getOperand(0);
5819 SDValue N1 = N->getOperand(1);
5820 SDValue N2 = N->getOperand(2);
5821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5822 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5823 EVT VT = N->getValueType(0);
5825 if (N0CFP && N0CFP->isExactlyValue(1.0))
5826 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
5827 if (N1CFP && N1CFP->isExactlyValue(1.0))
5828 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
5830 // Canonicalize (fma c, x, y) -> (fma x, c, y)
5831 if (N0CFP && !N1CFP)
5832 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
5837 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5838 SDValue N0 = N->getOperand(0);
5839 SDValue N1 = N->getOperand(1);
5840 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5841 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5842 EVT VT = N->getValueType(0);
5843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5846 if (VT.isVector()) {
5847 SDValue FoldedVOp = SimplifyVBinOp(N);
5848 if (FoldedVOp.getNode()) return FoldedVOp;
5851 // fold (fdiv c1, c2) -> c1/c2
5852 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5853 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5855 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
5856 if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
5857 // Compute the reciprocal 1.0 / c2.
5858 APFloat N1APF = N1CFP->getValueAPF();
5859 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
5860 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
5861 // Only do the transform if the reciprocal is a legal fp immediate that
5862 // isn't too nasty (eg NaN, denormal, ...).
5863 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
5864 (!LegalOperations ||
5865 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
5866 // backend)... we should handle this gracefully after Legalize.
5867 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
5868 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
5869 TLI.isFPImmLegal(Recip, VT)))
5870 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
5871 DAG.getConstantFP(Recip, VT));
5874 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5875 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5876 &DAG.getTarget().Options)) {
5877 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5878 &DAG.getTarget().Options)) {
5879 // Both can be negated for free, check to see if at least one is cheaper
5881 if (LHSNeg == 2 || RHSNeg == 2)
5882 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5883 GetNegatedExpression(N0, DAG, LegalOperations),
5884 GetNegatedExpression(N1, DAG, LegalOperations));
5891 SDValue DAGCombiner::visitFREM(SDNode *N) {
5892 SDValue N0 = N->getOperand(0);
5893 SDValue N1 = N->getOperand(1);
5894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5895 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5896 EVT VT = N->getValueType(0);
5898 // fold (frem c1, c2) -> fmod(c1,c2)
5899 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5900 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5905 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5906 SDValue N0 = N->getOperand(0);
5907 SDValue N1 = N->getOperand(1);
5908 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5909 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5910 EVT VT = N->getValueType(0);
5912 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5913 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5916 const APFloat& V = N1CFP->getValueAPF();
5917 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5918 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5919 if (!V.isNegative()) {
5920 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5921 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5923 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5924 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5925 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5929 // copysign(fabs(x), y) -> copysign(x, y)
5930 // copysign(fneg(x), y) -> copysign(x, y)
5931 // copysign(copysign(x,z), y) -> copysign(x, y)
5932 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5933 N0.getOpcode() == ISD::FCOPYSIGN)
5934 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5935 N0.getOperand(0), N1);
5937 // copysign(x, abs(y)) -> abs(x)
5938 if (N1.getOpcode() == ISD::FABS)
5939 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5941 // copysign(x, copysign(y,z)) -> copysign(x, z)
5942 if (N1.getOpcode() == ISD::FCOPYSIGN)
5943 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5944 N0, N1.getOperand(1));
5946 // copysign(x, fp_extend(y)) -> copysign(x, y)
5947 // copysign(x, fp_round(y)) -> copysign(x, y)
5948 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5949 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5950 N0, N1.getOperand(0));
5955 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5956 SDValue N0 = N->getOperand(0);
5957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5958 EVT VT = N->getValueType(0);
5959 EVT OpVT = N0.getValueType();
5961 // fold (sint_to_fp c1) -> c1fp
5962 if (N0C && OpVT != MVT::ppcf128 &&
5963 // ...but only if the target supports immediate floating-point values
5964 (!LegalOperations ||
5965 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5966 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5968 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5969 // but UINT_TO_FP is legal on this target, try to convert.
5970 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5971 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5972 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5973 if (DAG.SignBitIsZero(N0))
5974 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5977 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
5978 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
5979 (!LegalOperations ||
5980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
5982 { N0.getOperand(0), N0.getOperand(1),
5983 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
5985 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
5988 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
5989 // (select_cc x, y, 1.0, 0.0,, cc)
5990 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
5991 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
5992 (!LegalOperations ||
5993 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
5995 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
5996 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
5997 N0.getOperand(0).getOperand(2) };
5998 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6004 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6005 SDValue N0 = N->getOperand(0);
6006 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6007 EVT VT = N->getValueType(0);
6008 EVT OpVT = N0.getValueType();
6010 // fold (uint_to_fp c1) -> c1fp
6011 if (N0C && OpVT != MVT::ppcf128 &&
6012 // ...but only if the target supports immediate floating-point values
6013 (!LegalOperations ||
6014 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6015 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6017 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6018 // but SINT_TO_FP is legal on this target, try to convert.
6019 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6020 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6021 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6022 if (DAG.SignBitIsZero(N0))
6023 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6026 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6027 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6028 (!LegalOperations ||
6029 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6031 { N0.getOperand(0), N0.getOperand(1),
6032 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6034 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6041 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6042 SDValue N0 = N->getOperand(0);
6043 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6044 EVT VT = N->getValueType(0);
6046 // fold (fp_to_sint c1fp) -> c1
6048 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6053 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6054 SDValue N0 = N->getOperand(0);
6055 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6056 EVT VT = N->getValueType(0);
6058 // fold (fp_to_uint c1fp) -> c1
6059 if (N0CFP && VT != MVT::ppcf128)
6060 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6065 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6066 SDValue N0 = N->getOperand(0);
6067 SDValue N1 = N->getOperand(1);
6068 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6069 EVT VT = N->getValueType(0);
6071 // fold (fp_round c1fp) -> c1fp
6072 if (N0CFP && N0.getValueType() != MVT::ppcf128)
6073 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6075 // fold (fp_round (fp_extend x)) -> x
6076 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6077 return N0.getOperand(0);
6079 // fold (fp_round (fp_round x)) -> (fp_round x)
6080 if (N0.getOpcode() == ISD::FP_ROUND) {
6081 // This is a value preserving truncation if both round's are.
6082 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6083 N0.getNode()->getConstantOperandVal(1) == 1;
6084 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6085 DAG.getIntPtrConstant(IsTrunc));
6088 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6089 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6090 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6091 N0.getOperand(0), N1);
6092 AddToWorkList(Tmp.getNode());
6093 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6094 Tmp, N0.getOperand(1));
6100 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6101 SDValue N0 = N->getOperand(0);
6102 EVT VT = N->getValueType(0);
6103 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6106 // fold (fp_round_inreg c1fp) -> c1fp
6107 if (N0CFP && isTypeLegal(EVT)) {
6108 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6109 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6115 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6116 SDValue N0 = N->getOperand(0);
6117 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6118 EVT VT = N->getValueType(0);
6120 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6121 if (N->hasOneUse() &&
6122 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6125 // fold (fp_extend c1fp) -> c1fp
6126 if (N0CFP && VT != MVT::ppcf128)
6127 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6129 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6131 if (N0.getOpcode() == ISD::FP_ROUND
6132 && N0.getNode()->getConstantOperandVal(1) == 1) {
6133 SDValue In = N0.getOperand(0);
6134 if (In.getValueType() == VT) return In;
6135 if (VT.bitsLT(In.getValueType()))
6136 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6137 In, N0.getOperand(1));
6138 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6141 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6142 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6143 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6144 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6146 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6148 LN0->getBasePtr(), LN0->getPointerInfo(),
6150 LN0->isVolatile(), LN0->isNonTemporal(),
6151 LN0->getAlignment());
6152 CombineTo(N, ExtLoad);
6153 CombineTo(N0.getNode(),
6154 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6155 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6156 ExtLoad.getValue(1));
6157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6163 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6164 SDValue N0 = N->getOperand(0);
6165 EVT VT = N->getValueType(0);
6167 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6168 &DAG.getTarget().Options))
6169 return GetNegatedExpression(N0, DAG, LegalOperations);
6171 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6172 // constant pool values.
6173 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6175 N0.getNode()->hasOneUse() &&
6176 N0.getOperand(0).getValueType().isInteger()) {
6177 SDValue Int = N0.getOperand(0);
6178 EVT IntVT = Int.getValueType();
6179 if (IntVT.isInteger() && !IntVT.isVector()) {
6180 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6181 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6182 AddToWorkList(Int.getNode());
6183 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6191 SDValue DAGCombiner::visitFABS(SDNode *N) {
6192 SDValue N0 = N->getOperand(0);
6193 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6194 EVT VT = N->getValueType(0);
6196 // fold (fabs c1) -> fabs(c1)
6197 if (N0CFP && VT != MVT::ppcf128)
6198 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6199 // fold (fabs (fabs x)) -> (fabs x)
6200 if (N0.getOpcode() == ISD::FABS)
6201 return N->getOperand(0);
6202 // fold (fabs (fneg x)) -> (fabs x)
6203 // fold (fabs (fcopysign x, y)) -> (fabs x)
6204 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6205 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6207 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6208 // constant pool values.
6209 if (!TLI.isFAbsFree(VT) &&
6210 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6211 N0.getOperand(0).getValueType().isInteger() &&
6212 !N0.getOperand(0).getValueType().isVector()) {
6213 SDValue Int = N0.getOperand(0);
6214 EVT IntVT = Int.getValueType();
6215 if (IntVT.isInteger() && !IntVT.isVector()) {
6216 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6217 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6218 AddToWorkList(Int.getNode());
6219 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6220 N->getValueType(0), Int);
6227 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6228 SDValue Chain = N->getOperand(0);
6229 SDValue N1 = N->getOperand(1);
6230 SDValue N2 = N->getOperand(2);
6232 // If N is a constant we could fold this into a fallthrough or unconditional
6233 // branch. However that doesn't happen very often in normal code, because
6234 // Instcombine/SimplifyCFG should have handled the available opportunities.
6235 // If we did this folding here, it would be necessary to update the
6236 // MachineBasicBlock CFG, which is awkward.
6238 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6240 if (N1.getOpcode() == ISD::SETCC &&
6241 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6242 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6243 Chain, N1.getOperand(2),
6244 N1.getOperand(0), N1.getOperand(1), N2);
6247 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6248 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6249 (N1.getOperand(0).hasOneUse() &&
6250 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6252 if (N1.getOpcode() == ISD::TRUNCATE) {
6253 // Look pass the truncate.
6254 Trunc = N1.getNode();
6255 N1 = N1.getOperand(0);
6258 // Match this pattern so that we can generate simpler code:
6261 // %b = and i32 %a, 2
6262 // %c = srl i32 %b, 1
6263 // brcond i32 %c ...
6268 // %b = and i32 %a, 2
6269 // %c = setcc eq %b, 0
6272 // This applies only when the AND constant value has one bit set and the
6273 // SRL constant is equal to the log2 of the AND constant. The back-end is
6274 // smart enough to convert the result into a TEST/JMP sequence.
6275 SDValue Op0 = N1.getOperand(0);
6276 SDValue Op1 = N1.getOperand(1);
6278 if (Op0.getOpcode() == ISD::AND &&
6279 Op1.getOpcode() == ISD::Constant) {
6280 SDValue AndOp1 = Op0.getOperand(1);
6282 if (AndOp1.getOpcode() == ISD::Constant) {
6283 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6285 if (AndConst.isPowerOf2() &&
6286 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6288 DAG.getSetCC(N->getDebugLoc(),
6289 TLI.getSetCCResultType(Op0.getValueType()),
6290 Op0, DAG.getConstant(0, Op0.getValueType()),
6293 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6294 MVT::Other, Chain, SetCC, N2);
6295 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6296 // will convert it back to (X & C1) >> C2.
6297 CombineTo(N, NewBRCond, false);
6298 // Truncate is dead.
6300 removeFromWorkList(Trunc);
6301 DAG.DeleteNode(Trunc);
6303 // Replace the uses of SRL with SETCC
6304 WorkListRemover DeadNodes(*this);
6305 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6306 removeFromWorkList(N1.getNode());
6307 DAG.DeleteNode(N1.getNode());
6308 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6314 // Restore N1 if the above transformation doesn't match.
6315 N1 = N->getOperand(1);
6318 // Transform br(xor(x, y)) -> br(x != y)
6319 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6320 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6321 SDNode *TheXor = N1.getNode();
6322 SDValue Op0 = TheXor->getOperand(0);
6323 SDValue Op1 = TheXor->getOperand(1);
6324 if (Op0.getOpcode() == Op1.getOpcode()) {
6325 // Avoid missing important xor optimizations.
6326 SDValue Tmp = visitXOR(TheXor);
6327 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6328 DEBUG(dbgs() << "\nReplacing.8 ";
6330 dbgs() << "\nWith: ";
6331 Tmp.getNode()->dump(&DAG);
6333 WorkListRemover DeadNodes(*this);
6334 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6335 removeFromWorkList(TheXor);
6336 DAG.DeleteNode(TheXor);
6337 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6338 MVT::Other, Chain, Tmp, N2);
6342 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6344 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6345 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6346 Op0.getOpcode() == ISD::XOR) {
6347 TheXor = Op0.getNode();
6351 EVT SetCCVT = N1.getValueType();
6353 SetCCVT = TLI.getSetCCResultType(SetCCVT);
6354 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6357 Equal ? ISD::SETEQ : ISD::SETNE);
6358 // Replace the uses of XOR with SETCC
6359 WorkListRemover DeadNodes(*this);
6360 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6361 removeFromWorkList(N1.getNode());
6362 DAG.DeleteNode(N1.getNode());
6363 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6364 MVT::Other, Chain, SetCC, N2);
6371 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6373 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6374 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6375 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6377 // If N is a constant we could fold this into a fallthrough or unconditional
6378 // branch. However that doesn't happen very often in normal code, because
6379 // Instcombine/SimplifyCFG should have handled the available opportunities.
6380 // If we did this folding here, it would be necessary to update the
6381 // MachineBasicBlock CFG, which is awkward.
6383 // Use SimplifySetCC to simplify SETCC's.
6384 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6385 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6387 if (Simp.getNode()) AddToWorkList(Simp.getNode());
6389 // fold to a simpler setcc
6390 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6391 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6392 N->getOperand(0), Simp.getOperand(2),
6393 Simp.getOperand(0), Simp.getOperand(1),
6399 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6400 /// uses N as its base pointer and that N may be folded in the load / store
6401 /// addressing mode.
6402 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6404 const TargetLowering &TLI) {
6406 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
6407 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6409 VT = Use->getValueType(0);
6410 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
6411 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6413 VT = ST->getValue().getValueType();
6417 TargetLowering::AddrMode AM;
6418 if (N->getOpcode() == ISD::ADD) {
6419 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6422 AM.BaseOffs = Offset->getSExtValue();
6426 } else if (N->getOpcode() == ISD::SUB) {
6427 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6430 AM.BaseOffs = -Offset->getSExtValue();
6437 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6440 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6441 /// pre-indexed load / store when the base pointer is an add or subtract
6442 /// and it has other uses besides the load / store. After the
6443 /// transformation, the new indexed load / store has effectively folded
6444 /// the add / subtract in and all of its other uses are redirected to the
6445 /// new load / store.
6446 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6447 if (Level < AfterLegalizeDAG)
6453 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6454 if (LD->isIndexed())
6456 VT = LD->getMemoryVT();
6457 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6458 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6460 Ptr = LD->getBasePtr();
6461 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6462 if (ST->isIndexed())
6464 VT = ST->getMemoryVT();
6465 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6466 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6468 Ptr = ST->getBasePtr();
6474 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6475 // out. There is no reason to make this a preinc/predec.
6476 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6477 Ptr.getNode()->hasOneUse())
6480 // Ask the target to do addressing mode selection.
6483 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6484 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6486 // Don't create a indexed load / store with zero offset.
6487 if (isa<ConstantSDNode>(Offset) &&
6488 cast<ConstantSDNode>(Offset)->isNullValue())
6491 // Try turning it into a pre-indexed load / store except when:
6492 // 1) The new base ptr is a frame index.
6493 // 2) If N is a store and the new base ptr is either the same as or is a
6494 // predecessor of the value being stored.
6495 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6496 // that would create a cycle.
6497 // 4) All uses are load / store ops that use it as old base ptr.
6499 // Check #1. Preinc'ing a frame index would require copying the stack pointer
6500 // (plus the implicit offset) to a register to preinc anyway.
6501 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6506 SDValue Val = cast<StoreSDNode>(N)->getValue();
6507 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6511 // Now check for #3 and #4.
6512 bool RealUse = false;
6514 // Caches for hasPredecessorHelper
6515 SmallPtrSet<const SDNode *, 32> Visited;
6516 SmallVector<const SDNode *, 16> Worklist;
6518 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6519 E = Ptr.getNode()->use_end(); I != E; ++I) {
6523 if (N->hasPredecessorHelper(Use, Visited, Worklist))
6526 // If Ptr may be folded in addressing mode of other use, then it's
6527 // not profitable to do this transformation.
6528 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6537 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6538 BasePtr, Offset, AM);
6540 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6541 BasePtr, Offset, AM);
6544 DEBUG(dbgs() << "\nReplacing.4 ";
6546 dbgs() << "\nWith: ";
6547 Result.getNode()->dump(&DAG);
6549 WorkListRemover DeadNodes(*this);
6551 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6552 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6557 // Finally, since the node is now dead, remove it from the graph.
6560 // Replace the uses of Ptr with uses of the updated base value.
6561 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6562 removeFromWorkList(Ptr.getNode());
6563 DAG.DeleteNode(Ptr.getNode());
6568 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6569 /// add / sub of the base pointer node into a post-indexed load / store.
6570 /// The transformation folded the add / subtract into the new indexed
6571 /// load / store effectively and all of its uses are redirected to the
6572 /// new load / store.
6573 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6574 if (Level < AfterLegalizeDAG)
6580 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6581 if (LD->isIndexed())
6583 VT = LD->getMemoryVT();
6584 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6585 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6587 Ptr = LD->getBasePtr();
6588 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6589 if (ST->isIndexed())
6591 VT = ST->getMemoryVT();
6592 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6593 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6595 Ptr = ST->getBasePtr();
6601 if (Ptr.getNode()->hasOneUse())
6604 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6605 E = Ptr.getNode()->use_end(); I != E; ++I) {
6608 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6613 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6614 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6615 // Don't create a indexed load / store with zero offset.
6616 if (isa<ConstantSDNode>(Offset) &&
6617 cast<ConstantSDNode>(Offset)->isNullValue())
6620 // Try turning it into a post-indexed load / store except when
6621 // 1) All uses are load / store ops that use it as base ptr (and
6622 // it may be folded as addressing mmode).
6623 // 2) Op must be independent of N, i.e. Op is neither a predecessor
6624 // nor a successor of N. Otherwise, if Op is folded that would
6627 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6631 bool TryNext = false;
6632 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6633 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6635 if (Use == Ptr.getNode())
6638 // If all the uses are load / store addresses, then don't do the
6640 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6641 bool RealUse = false;
6642 for (SDNode::use_iterator III = Use->use_begin(),
6643 EEE = Use->use_end(); III != EEE; ++III) {
6644 SDNode *UseUse = *III;
6645 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
6660 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6661 SDValue Result = isLoad
6662 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6663 BasePtr, Offset, AM)
6664 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6665 BasePtr, Offset, AM);
6668 DEBUG(dbgs() << "\nReplacing.5 ";
6670 dbgs() << "\nWith: ";
6671 Result.getNode()->dump(&DAG);
6673 WorkListRemover DeadNodes(*this);
6675 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6676 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6678 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6681 // Finally, since the node is now dead, remove it from the graph.
6684 // Replace the uses of Use with uses of the updated base value.
6685 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6686 Result.getValue(isLoad ? 1 : 0));
6687 removeFromWorkList(Op);
6697 SDValue DAGCombiner::visitLOAD(SDNode *N) {
6698 LoadSDNode *LD = cast<LoadSDNode>(N);
6699 SDValue Chain = LD->getChain();
6700 SDValue Ptr = LD->getBasePtr();
6702 // If load is not volatile and there are no uses of the loaded value (and
6703 // the updated indexed value in case of indexed loads), change uses of the
6704 // chain value into uses of the chain input (i.e. delete the dead load).
6705 if (!LD->isVolatile()) {
6706 if (N->getValueType(1) == MVT::Other) {
6708 if (!N->hasAnyUseOfValue(0)) {
6709 // It's not safe to use the two value CombineTo variant here. e.g.
6710 // v1, chain2 = load chain1, loc
6711 // v2, chain3 = load chain2, loc
6713 // Now we replace use of chain2 with chain1. This makes the second load
6714 // isomorphic to the one we are deleting, and thus makes this load live.
6715 DEBUG(dbgs() << "\nReplacing.6 ";
6717 dbgs() << "\nWith chain: ";
6718 Chain.getNode()->dump(&DAG);
6720 WorkListRemover DeadNodes(*this);
6721 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
6723 if (N->use_empty()) {
6724 removeFromWorkList(N);
6728 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6732 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6733 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
6734 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6735 DEBUG(dbgs() << "\nReplacing.7 ";
6737 dbgs() << "\nWith: ";
6738 Undef.getNode()->dump(&DAG);
6739 dbgs() << " and 2 other values\n");
6740 WorkListRemover DeadNodes(*this);
6741 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
6742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6743 DAG.getUNDEF(N->getValueType(1)));
6744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
6745 removeFromWorkList(N);
6747 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6752 // If this load is directly stored, replace the load value with the stored
6754 // TODO: Handle store large -> read small portion.
6755 // TODO: Handle TRUNCSTORE/LOADEXT
6756 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6757 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6758 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6759 if (PrevST->getBasePtr() == Ptr &&
6760 PrevST->getValue().getValueType() == N->getValueType(0))
6761 return CombineTo(N, Chain.getOperand(1), Chain);
6765 // Try to infer better alignment information than the load already has.
6766 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6767 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6768 if (Align > LD->getAlignment())
6769 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6770 LD->getValueType(0),
6771 Chain, Ptr, LD->getPointerInfo(),
6773 LD->isVolatile(), LD->isNonTemporal(), Align);
6778 // Walk up chain skipping non-aliasing memory nodes.
6779 SDValue BetterChain = FindBetterChain(N, Chain);
6781 // If there is a better chain.
6782 if (Chain != BetterChain) {
6785 // Replace the chain to void dependency.
6786 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6787 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6788 BetterChain, Ptr, LD->getPointerInfo(),
6789 LD->isVolatile(), LD->isNonTemporal(),
6790 LD->isInvariant(), LD->getAlignment());
6792 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6793 LD->getValueType(0),
6794 BetterChain, Ptr, LD->getPointerInfo(),
6797 LD->isNonTemporal(),
6798 LD->getAlignment());
6801 // Create token factor to keep old chain connected.
6802 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6803 MVT::Other, Chain, ReplLoad.getValue(1));
6805 // Make sure the new and old chains are cleaned up.
6806 AddToWorkList(Token.getNode());
6808 // Replace uses with load result and token factor. Don't add users
6810 return CombineTo(N, ReplLoad.getValue(0), Token, false);
6814 // Try transforming N to an indexed load.
6815 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6816 return SDValue(N, 0);
6821 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6822 /// load is having specific bytes cleared out. If so, return the byte size
6823 /// being masked out and the shift amount.
6824 static std::pair<unsigned, unsigned>
6825 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6826 std::pair<unsigned, unsigned> Result(0, 0);
6828 // Check for the structure we're looking for.
6829 if (V->getOpcode() != ISD::AND ||
6830 !isa<ConstantSDNode>(V->getOperand(1)) ||
6831 !ISD::isNormalLoad(V->getOperand(0).getNode()))
6834 // Check the chain and pointer.
6835 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6836 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
6838 // The store should be chained directly to the load or be an operand of a
6840 if (LD == Chain.getNode())
6842 else if (Chain->getOpcode() != ISD::TokenFactor)
6843 return Result; // Fail.
6846 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6847 if (Chain->getOperand(i).getNode() == LD) {
6851 if (!isOk) return Result;
6854 // This only handles simple types.
6855 if (V.getValueType() != MVT::i16 &&
6856 V.getValueType() != MVT::i32 &&
6857 V.getValueType() != MVT::i64)
6860 // Check the constant mask. Invert it so that the bits being masked out are
6861 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
6862 // follow the sign bit for uniformity.
6863 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6864 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6865 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
6866 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6867 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
6868 if (NotMaskLZ == 64) return Result; // All zero mask.
6870 // See if we have a continuous run of bits. If so, we have 0*1+0*
6871 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6874 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6875 if (V.getValueType() != MVT::i64 && NotMaskLZ)
6876 NotMaskLZ -= 64-V.getValueSizeInBits();
6878 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6879 switch (MaskedBytes) {
6883 default: return Result; // All one mask, or 5-byte mask.
6886 // Verify that the first bit starts at a multiple of mask so that the access
6887 // is aligned the same as the access width.
6888 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6890 Result.first = MaskedBytes;
6891 Result.second = NotMaskTZ/8;
6896 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6897 /// provides a value as specified by MaskInfo. If so, replace the specified
6898 /// store with a narrower store of truncated IVal.
6900 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6901 SDValue IVal, StoreSDNode *St,
6903 unsigned NumBytes = MaskInfo.first;
6904 unsigned ByteShift = MaskInfo.second;
6905 SelectionDAG &DAG = DC->getDAG();
6907 // Check to see if IVal is all zeros in the part being masked in by the 'or'
6908 // that uses this. If not, this is not a replacement.
6909 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6910 ByteShift*8, (ByteShift+NumBytes)*8);
6911 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6913 // Check that it is legal on the target to do this. It is legal if the new
6914 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6916 MVT VT = MVT::getIntegerVT(NumBytes*8);
6917 if (!DC->isTypeLegal(VT))
6920 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
6921 // shifted by ByteShift and truncated down to NumBytes.
6923 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6924 DAG.getConstant(ByteShift*8,
6925 DC->getShiftAmountTy(IVal.getValueType())));
6927 // Figure out the offset for the store and the alignment of the access.
6929 unsigned NewAlign = St->getAlignment();
6931 if (DAG.getTargetLoweringInfo().isLittleEndian())
6932 StOffset = ByteShift;
6934 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6936 SDValue Ptr = St->getBasePtr();
6938 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6939 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6940 NewAlign = MinAlign(NewAlign, StOffset);
6943 // Truncate down to the new size.
6944 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6947 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6948 St->getPointerInfo().getWithOffset(StOffset),
6949 false, false, NewAlign).getNode();
6953 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6954 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6955 /// of the loaded bits, try narrowing the load and store if it would end up
6956 /// being a win for performance or code size.
6957 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6958 StoreSDNode *ST = cast<StoreSDNode>(N);
6959 if (ST->isVolatile())
6962 SDValue Chain = ST->getChain();
6963 SDValue Value = ST->getValue();
6964 SDValue Ptr = ST->getBasePtr();
6965 EVT VT = Value.getValueType();
6967 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6970 unsigned Opc = Value.getOpcode();
6972 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6973 // is a byte mask indicating a consecutive number of bytes, check to see if
6974 // Y is known to provide just those bytes. If so, we try to replace the
6975 // load + replace + store sequence with a single (narrower) store, which makes
6977 if (Opc == ISD::OR) {
6978 std::pair<unsigned, unsigned> MaskedLoad;
6979 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6980 if (MaskedLoad.first)
6981 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6982 Value.getOperand(1), ST,this))
6983 return SDValue(NewST, 0);
6985 // Or is commutative, so try swapping X and Y.
6986 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6987 if (MaskedLoad.first)
6988 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6989 Value.getOperand(0), ST,this))
6990 return SDValue(NewST, 0);
6993 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6994 Value.getOperand(1).getOpcode() != ISD::Constant)
6997 SDValue N0 = Value.getOperand(0);
6998 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6999 Chain == SDValue(N0.getNode(), 1)) {
7000 LoadSDNode *LD = cast<LoadSDNode>(N0);
7001 if (LD->getBasePtr() != Ptr ||
7002 LD->getPointerInfo().getAddrSpace() !=
7003 ST->getPointerInfo().getAddrSpace())
7006 // Find the type to narrow it the load / op / store to.
7007 SDValue N1 = Value.getOperand(1);
7008 unsigned BitWidth = N1.getValueSizeInBits();
7009 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7010 if (Opc == ISD::AND)
7011 Imm ^= APInt::getAllOnesValue(BitWidth);
7012 if (Imm == 0 || Imm.isAllOnesValue())
7014 unsigned ShAmt = Imm.countTrailingZeros();
7015 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7016 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7017 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7018 while (NewBW < BitWidth &&
7019 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7020 TLI.isNarrowingProfitable(VT, NewVT))) {
7021 NewBW = NextPowerOf2(NewBW);
7022 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7024 if (NewBW >= BitWidth)
7027 // If the lsb changed does not start at the type bitwidth boundary,
7028 // start at the previous one.
7030 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7031 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
7032 if ((Imm & Mask) == Imm) {
7033 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7034 if (Opc == ISD::AND)
7035 NewImm ^= APInt::getAllOnesValue(NewBW);
7036 uint64_t PtrOff = ShAmt / 8;
7037 // For big endian targets, we need to adjust the offset to the pointer to
7038 // load the correct bytes.
7039 if (TLI.isBigEndian())
7040 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7042 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7043 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7044 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
7047 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7048 Ptr.getValueType(), Ptr,
7049 DAG.getConstant(PtrOff, Ptr.getValueType()));
7050 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7051 LD->getChain(), NewPtr,
7052 LD->getPointerInfo().getWithOffset(PtrOff),
7053 LD->isVolatile(), LD->isNonTemporal(),
7054 LD->isInvariant(), NewAlign);
7055 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7056 DAG.getConstant(NewImm, NewVT));
7057 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7059 ST->getPointerInfo().getWithOffset(PtrOff),
7060 false, false, NewAlign);
7062 AddToWorkList(NewPtr.getNode());
7063 AddToWorkList(NewLD.getNode());
7064 AddToWorkList(NewVal.getNode());
7065 WorkListRemover DeadNodes(*this);
7066 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7075 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7076 /// if the load value isn't used by any other operations, then consider
7077 /// transforming the pair to integer load / store operations if the target
7078 /// deems the transformation profitable.
7079 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7080 StoreSDNode *ST = cast<StoreSDNode>(N);
7081 SDValue Chain = ST->getChain();
7082 SDValue Value = ST->getValue();
7083 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7084 Value.hasOneUse() &&
7085 Chain == SDValue(Value.getNode(), 1)) {
7086 LoadSDNode *LD = cast<LoadSDNode>(Value);
7087 EVT VT = LD->getMemoryVT();
7088 if (!VT.isFloatingPoint() ||
7089 VT != ST->getMemoryVT() ||
7090 LD->isNonTemporal() ||
7091 ST->isNonTemporal() ||
7092 LD->getPointerInfo().getAddrSpace() != 0 ||
7093 ST->getPointerInfo().getAddrSpace() != 0)
7096 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7097 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7098 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7099 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7100 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7103 unsigned LDAlign = LD->getAlignment();
7104 unsigned STAlign = ST->getAlignment();
7105 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7106 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
7107 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7110 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7111 LD->getChain(), LD->getBasePtr(),
7112 LD->getPointerInfo(),
7113 false, false, false, LDAlign);
7115 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7116 NewLD, ST->getBasePtr(),
7117 ST->getPointerInfo(),
7118 false, false, STAlign);
7120 AddToWorkList(NewLD.getNode());
7121 AddToWorkList(NewST.getNode());
7122 WorkListRemover DeadNodes(*this);
7123 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7131 SDValue DAGCombiner::visitSTORE(SDNode *N) {
7132 StoreSDNode *ST = cast<StoreSDNode>(N);
7133 SDValue Chain = ST->getChain();
7134 SDValue Value = ST->getValue();
7135 SDValue Ptr = ST->getBasePtr();
7137 // If this is a store of a bit convert, store the input value if the
7138 // resultant store does not need a higher alignment than the original.
7139 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7140 ST->isUnindexed()) {
7141 unsigned OrigAlign = ST->getAlignment();
7142 EVT SVT = Value.getOperand(0).getValueType();
7143 unsigned Align = TLI.getTargetData()->
7144 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7145 if (Align <= OrigAlign &&
7146 ((!LegalOperations && !ST->isVolatile()) ||
7147 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7148 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7149 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7150 ST->isNonTemporal(), OrigAlign);
7153 // Turn 'store undef, Ptr' -> nothing.
7154 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7157 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7158 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7159 // NOTE: If the original store is volatile, this transform must not increase
7160 // the number of stores. For example, on x86-32 an f64 can be stored in one
7161 // processor operation but an i64 (which is not legal) requires two. So the
7162 // transform should not be done in this case.
7163 if (Value.getOpcode() != ISD::TargetConstantFP) {
7165 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7166 default: llvm_unreachable("Unknown FP type");
7167 case MVT::f16: // We don't do this for these yet.
7173 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7174 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7175 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7176 bitcastToAPInt().getZExtValue(), MVT::i32);
7177 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7178 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7179 ST->isNonTemporal(), ST->getAlignment());
7183 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7184 !ST->isVolatile()) ||
7185 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7186 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7187 getZExtValue(), MVT::i64);
7188 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7189 Ptr, ST->getPointerInfo(), ST->isVolatile(),
7190 ST->isNonTemporal(), ST->getAlignment());
7193 if (!ST->isVolatile() &&
7194 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7195 // Many FP stores are not made apparent until after legalize, e.g. for
7196 // argument passing. Since this is so common, custom legalize the
7197 // 64-bit integer store into two 32-bit stores.
7198 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7199 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7200 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7201 if (TLI.isBigEndian()) std::swap(Lo, Hi);
7203 unsigned Alignment = ST->getAlignment();
7204 bool isVolatile = ST->isVolatile();
7205 bool isNonTemporal = ST->isNonTemporal();
7207 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7208 Ptr, ST->getPointerInfo(),
7209 isVolatile, isNonTemporal,
7210 ST->getAlignment());
7211 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7212 DAG.getConstant(4, Ptr.getValueType()));
7213 Alignment = MinAlign(Alignment, 4U);
7214 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7215 Ptr, ST->getPointerInfo().getWithOffset(4),
7216 isVolatile, isNonTemporal,
7218 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7227 // Try to infer better alignment information than the store already has.
7228 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7229 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7230 if (Align > ST->getAlignment())
7231 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7232 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7233 ST->isVolatile(), ST->isNonTemporal(), Align);
7237 // Try transforming a pair floating point load / store ops to integer
7238 // load / store ops.
7239 SDValue NewST = TransformFPLoadStorePair(N);
7240 if (NewST.getNode())
7244 // Walk up chain skipping non-aliasing memory nodes.
7245 SDValue BetterChain = FindBetterChain(N, Chain);
7247 // If there is a better chain.
7248 if (Chain != BetterChain) {
7251 // Replace the chain to avoid dependency.
7252 if (ST->isTruncatingStore()) {
7253 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7254 ST->getPointerInfo(),
7255 ST->getMemoryVT(), ST->isVolatile(),
7256 ST->isNonTemporal(), ST->getAlignment());
7258 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7259 ST->getPointerInfo(),
7260 ST->isVolatile(), ST->isNonTemporal(),
7261 ST->getAlignment());
7264 // Create token to keep both nodes around.
7265 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7266 MVT::Other, Chain, ReplStore);
7268 // Make sure the new and old chains are cleaned up.
7269 AddToWorkList(Token.getNode());
7271 // Don't add users to work list.
7272 return CombineTo(N, Token, false);
7276 // Try transforming N to an indexed store.
7277 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7278 return SDValue(N, 0);
7280 // FIXME: is there such a thing as a truncating indexed store?
7281 if (ST->isTruncatingStore() && ST->isUnindexed() &&
7282 Value.getValueType().isInteger()) {
7283 // See if we can simplify the input to this truncstore with knowledge that
7284 // only the low bits are being used. For example:
7285 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
7287 GetDemandedBits(Value,
7288 APInt::getLowBitsSet(
7289 Value.getValueType().getScalarType().getSizeInBits(),
7290 ST->getMemoryVT().getScalarType().getSizeInBits()));
7291 AddToWorkList(Value.getNode());
7292 if (Shorter.getNode())
7293 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
7294 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7295 ST->isVolatile(), ST->isNonTemporal(),
7296 ST->getAlignment());
7298 // Otherwise, see if we can simplify the operation with
7299 // SimplifyDemandedBits, which only works if the value has a single use.
7300 if (SimplifyDemandedBits(Value,
7301 APInt::getLowBitsSet(
7302 Value.getValueType().getScalarType().getSizeInBits(),
7303 ST->getMemoryVT().getScalarType().getSizeInBits())))
7304 return SDValue(N, 0);
7307 // If this is a load followed by a store to the same location, then the store
7309 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
7310 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
7311 ST->isUnindexed() && !ST->isVolatile() &&
7312 // There can't be any side effects between the load and store, such as
7314 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
7315 // The store is dead, remove it.
7320 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
7321 // truncating store. We can do this even if this is already a truncstore.
7322 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
7323 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
7324 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
7325 ST->getMemoryVT())) {
7326 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7327 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7328 ST->isVolatile(), ST->isNonTemporal(),
7329 ST->getAlignment());
7332 return ReduceLoadOpStoreWidth(N);
7335 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
7336 SDValue InVec = N->getOperand(0);
7337 SDValue InVal = N->getOperand(1);
7338 SDValue EltNo = N->getOperand(2);
7339 DebugLoc dl = N->getDebugLoc();
7341 // If the inserted element is an UNDEF, just use the input vector.
7342 if (InVal.getOpcode() == ISD::UNDEF)
7345 EVT VT = InVec.getValueType();
7347 // If we can't generate a legal BUILD_VECTOR, exit
7348 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
7351 // Check that we know which element is being inserted
7352 if (!isa<ConstantSDNode>(EltNo))
7354 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7356 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
7357 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
7359 SmallVector<SDValue, 8> Ops;
7360 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
7361 Ops.append(InVec.getNode()->op_begin(),
7362 InVec.getNode()->op_end());
7363 } else if (InVec.getOpcode() == ISD::UNDEF) {
7364 unsigned NElts = VT.getVectorNumElements();
7365 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
7370 // Insert the element
7371 if (Elt < Ops.size()) {
7372 // All the operands of BUILD_VECTOR must have the same type;
7373 // we enforce that here.
7374 EVT OpVT = Ops[0].getValueType();
7375 if (InVal.getValueType() != OpVT)
7376 InVal = OpVT.bitsGT(InVal.getValueType()) ?
7377 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
7378 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
7382 // Return the new vector
7383 return DAG.getNode(ISD::BUILD_VECTOR, dl,
7384 VT, &Ops[0], Ops.size());
7387 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
7388 // (vextract (scalar_to_vector val, 0) -> val
7389 SDValue InVec = N->getOperand(0);
7390 EVT VT = InVec.getValueType();
7391 EVT NVT = N->getValueType(0);
7393 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7394 // Check if the result type doesn't match the inserted element type. A
7395 // SCALAR_TO_VECTOR may truncate the inserted element and the
7396 // EXTRACT_VECTOR_ELT may widen the extracted vector.
7397 SDValue InOp = InVec.getOperand(0);
7398 if (InOp.getValueType() != NVT) {
7399 assert(InOp.getValueType().isInteger() && NVT.isInteger());
7400 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
7405 SDValue EltNo = N->getOperand(1);
7406 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
7408 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
7409 // We only perform this optimization before the op legalization phase because
7410 // we may introduce new vector instructions which are not backed by TD patterns.
7411 // For example on AVX, extracting elements from a wide vector without using
7412 // extract_subvector.
7413 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
7414 && ConstEltNo && !LegalOperations) {
7415 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7416 int NumElem = VT.getVectorNumElements();
7417 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
7418 // Find the new index to extract from.
7419 int OrigElt = SVOp->getMaskElt(Elt);
7421 // Extracting an undef index is undef.
7423 return DAG.getUNDEF(NVT);
7425 // Select the right vector half to extract from.
7426 if (OrigElt < NumElem) {
7427 InVec = InVec->getOperand(0);
7429 InVec = InVec->getOperand(1);
7433 EVT IndexTy = N->getOperand(1).getValueType();
7434 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
7435 InVec, DAG.getConstant(OrigElt, IndexTy));
7438 // Perform only after legalization to ensure build_vector / vector_shuffle
7439 // optimizations have already been done.
7440 if (!LegalOperations) return SDValue();
7442 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
7443 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
7444 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
7447 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7448 bool NewLoad = false;
7449 bool BCNumEltsChanged = false;
7450 EVT ExtVT = VT.getVectorElementType();
7453 // If the result of load has to be truncated, then it's not necessarily
7455 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
7458 if (InVec.getOpcode() == ISD::BITCAST) {
7459 // Don't duplicate a load with other uses.
7460 if (!InVec.hasOneUse())
7463 EVT BCVT = InVec.getOperand(0).getValueType();
7464 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
7466 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
7467 BCNumEltsChanged = true;
7468 InVec = InVec.getOperand(0);
7469 ExtVT = BCVT.getVectorElementType();
7473 LoadSDNode *LN0 = NULL;
7474 const ShuffleVectorSDNode *SVN = NULL;
7475 if (ISD::isNormalLoad(InVec.getNode())) {
7476 LN0 = cast<LoadSDNode>(InVec);
7477 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7478 InVec.getOperand(0).getValueType() == ExtVT &&
7479 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
7480 // Don't duplicate a load with other uses.
7481 if (!InVec.hasOneUse())
7484 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
7485 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
7486 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
7488 // (load $addr+1*size)
7490 // Don't duplicate a load with other uses.
7491 if (!InVec.hasOneUse())
7494 // If the bit convert changed the number of elements, it is unsafe
7495 // to examine the mask.
7496 if (BCNumEltsChanged)
7499 // Select the input vector, guarding against out of range extract vector.
7500 unsigned NumElems = VT.getVectorNumElements();
7501 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
7502 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
7504 if (InVec.getOpcode() == ISD::BITCAST) {
7505 // Don't duplicate a load with other uses.
7506 if (!InVec.hasOneUse())
7509 InVec = InVec.getOperand(0);
7511 if (ISD::isNormalLoad(InVec.getNode())) {
7512 LN0 = cast<LoadSDNode>(InVec);
7513 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
7517 // Make sure we found a non-volatile load and the extractelement is
7519 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
7522 // If Idx was -1 above, Elt is going to be -1, so just return undef.
7524 return DAG.getUNDEF(LVT);
7526 unsigned Align = LN0->getAlignment();
7528 // Check the resultant load doesn't need a higher alignment than the
7532 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
7534 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
7540 SDValue NewPtr = LN0->getBasePtr();
7541 unsigned PtrOff = 0;
7544 PtrOff = LVT.getSizeInBits() * Elt / 8;
7545 EVT PtrType = NewPtr.getValueType();
7546 if (TLI.isBigEndian())
7547 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
7548 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
7549 DAG.getConstant(PtrOff, PtrType));
7552 // The replacement we need to do here is a little tricky: we need to
7553 // replace an extractelement of a load with a load.
7554 // Use ReplaceAllUsesOfValuesWith to do the replacement.
7555 // Note that this replacement assumes that the extractvalue is the only
7556 // use of the load; that's okay because we don't want to perform this
7557 // transformation in other cases anyway.
7560 if (NVT.bitsGT(LVT)) {
7561 // If the result type of vextract is wider than the load, then issue an
7562 // extending load instead.
7563 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
7564 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
7565 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
7566 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
7567 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
7568 Chain = Load.getValue(1);
7570 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
7571 LN0->getPointerInfo().getWithOffset(PtrOff),
7572 LN0->isVolatile(), LN0->isNonTemporal(),
7573 LN0->isInvariant(), Align);
7574 Chain = Load.getValue(1);
7575 if (NVT.bitsLT(LVT))
7576 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
7578 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
7580 WorkListRemover DeadNodes(*this);
7581 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
7582 SDValue To[] = { Load, Chain };
7583 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7584 // Since we're explcitly calling ReplaceAllUses, add the new node to the
7585 // worklist explicitly as well.
7586 AddToWorkList(Load.getNode());
7587 AddUsersToWorkList(Load.getNode()); // Add users too
7588 // Make sure to revisit this node to clean it up; it will usually be dead.
7590 return SDValue(N, 0);
7596 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
7597 unsigned NumInScalars = N->getNumOperands();
7598 DebugLoc dl = N->getDebugLoc();
7599 EVT VT = N->getValueType(0);
7600 // Check to see if this is a BUILD_VECTOR of a bunch of values
7601 // which come from any_extend or zero_extend nodes. If so, we can create
7602 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
7603 // optimizations. We do not handle sign-extend because we can't fill the sign
7605 EVT SourceType = MVT::Other;
7606 bool AllAnyExt = true;
7607 bool AllUndef = true;
7608 for (unsigned i = 0; i != NumInScalars; ++i) {
7609 SDValue In = N->getOperand(i);
7610 // Ignore undef inputs.
7611 if (In.getOpcode() == ISD::UNDEF) continue;
7614 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
7615 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
7617 // Abort if the element is not an extension.
7618 if (!ZeroExt && !AnyExt) {
7619 SourceType = MVT::Other;
7623 // The input is a ZeroExt or AnyExt. Check the original type.
7624 EVT InTy = In.getOperand(0).getValueType();
7626 // Check that all of the widened source types are the same.
7627 if (SourceType == MVT::Other)
7630 else if (InTy != SourceType) {
7631 // Multiple income types. Abort.
7632 SourceType = MVT::Other;
7636 // Check if all of the extends are ANY_EXTENDs.
7637 AllAnyExt &= AnyExt;
7641 return DAG.getUNDEF(VT);
7643 // In order to have valid types, all of the inputs must be extended from the
7644 // same source type and all of the inputs must be any or zero extend.
7645 // Scalar sizes must be a power of two.
7646 EVT OutScalarTy = N->getValueType(0).getScalarType();
7647 bool ValidTypes = SourceType != MVT::Other &&
7648 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7649 isPowerOf2_32(SourceType.getSizeInBits());
7651 // We perform this optimization post type-legalization because
7652 // the type-legalizer often scalarizes integer-promoted vectors.
7653 // Performing this optimization before may create bit-casts which
7654 // will be type-legalized to complex code sequences.
7655 // We perform this optimization only before the operation legalizer because we
7656 // may introduce illegal operations.
7657 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
7658 // turn into a single shuffle instruction.
7659 if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) &&
7661 bool isLE = TLI.isLittleEndian();
7662 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7663 assert(ElemRatio > 1 && "Invalid element size ratio");
7664 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
7665 DAG.getConstant(0, SourceType);
7667 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7668 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7670 // Populate the new build_vector
7671 for (unsigned i=0; i < N->getNumOperands(); ++i) {
7672 SDValue Cast = N->getOperand(i);
7673 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7674 Cast.getOpcode() == ISD::ZERO_EXTEND ||
7675 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7677 if (Cast.getOpcode() == ISD::UNDEF)
7678 In = DAG.getUNDEF(SourceType);
7680 In = Cast->getOperand(0);
7681 unsigned Index = isLE ? (i * ElemRatio) :
7682 (i * ElemRatio + (ElemRatio - 1));
7684 assert(Index < Ops.size() && "Invalid index");
7688 // The type of the new BUILD_VECTOR node.
7689 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7690 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7691 "Invalid vector size");
7692 // Check if the new vector type is legal.
7693 if (!isTypeLegal(VecVT)) return SDValue();
7695 // Make the new BUILD_VECTOR.
7696 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7697 VecVT, &Ops[0], Ops.size());
7699 // The new BUILD_VECTOR node has the potential to be further optimized.
7700 AddToWorkList(BV.getNode());
7701 // Bitcast to the desired type.
7702 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7705 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7706 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7707 // at most two distinct vectors, turn this into a shuffle node.
7709 // May only combine to shuffle after legalize if shuffle is legal.
7710 if (LegalOperations &&
7711 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
7714 SDValue VecIn1, VecIn2;
7715 for (unsigned i = 0; i != NumInScalars; ++i) {
7716 // Ignore undef inputs.
7717 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7719 // If this input is something other than a EXTRACT_VECTOR_ELT with a
7720 // constant index, bail out.
7721 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7722 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7723 VecIn1 = VecIn2 = SDValue(0, 0);
7727 // We allow up to two distinct input vectors.
7728 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7729 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7732 if (VecIn1.getNode() == 0) {
7733 VecIn1 = ExtractedFromVec;
7734 } else if (VecIn2.getNode() == 0) {
7735 VecIn2 = ExtractedFromVec;
7738 VecIn1 = VecIn2 = SDValue(0, 0);
7743 // If everything is good, we can make a shuffle operation.
7744 if (VecIn1.getNode()) {
7745 SmallVector<int, 8> Mask;
7746 for (unsigned i = 0; i != NumInScalars; ++i) {
7747 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7752 // If extracting from the first vector, just use the index directly.
7753 SDValue Extract = N->getOperand(i);
7754 SDValue ExtVal = Extract.getOperand(1);
7755 if (Extract.getOperand(0) == VecIn1) {
7756 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7757 if (ExtIndex > VT.getVectorNumElements())
7760 Mask.push_back(ExtIndex);
7764 // Otherwise, use InIdx + VecSize
7765 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7766 Mask.push_back(Idx+NumInScalars);
7769 // We can't generate a shuffle node with mismatched input and output types.
7770 // Attempt to transform a single input vector to the correct type.
7771 if ((VT != VecIn1.getValueType())) {
7772 // We don't support shuffeling between TWO values of different types.
7773 if (VecIn2.getNode() != 0)
7776 // We only support widening of vectors which are half the size of the
7777 // output registers. For example XMM->YMM widening on X86 with AVX.
7778 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
7781 // Widen the input vector by adding undef values.
7782 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7783 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
7786 // If VecIn2 is unused then change it to undef.
7787 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7789 // Check that we were able to transform all incoming values to the same type.
7790 if (VecIn2.getValueType() != VecIn1.getValueType() ||
7791 VecIn1.getValueType() != VT)
7794 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
7795 if (!isTypeLegal(VT))
7798 // Return the new VECTOR_SHUFFLE node.
7802 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7808 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7809 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7810 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
7811 // inputs come from at most two distinct vectors, turn this into a shuffle
7814 // If we only have one input vector, we don't need to do any concatenation.
7815 if (N->getNumOperands() == 1)
7816 return N->getOperand(0);
7821 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7822 EVT NVT = N->getValueType(0);
7823 SDValue V = N->getOperand(0);
7825 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7826 // Handle only simple case where vector being inserted and vector
7827 // being extracted are of same type, and are half size of larger vectors.
7828 EVT BigVT = V->getOperand(0).getValueType();
7829 EVT SmallVT = V->getOperand(1).getValueType();
7830 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7833 // Only handle cases where both indexes are constants with the same type.
7834 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7835 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
7837 if (InsIdx && ExtIdx &&
7838 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
7839 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
7841 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7843 // indices are equal => V1
7844 // otherwise => (extract_subvec V1, ExtIdx)
7845 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
7846 return V->getOperand(1);
7847 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7848 V->getOperand(0), N->getOperand(1));
7855 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7856 EVT VT = N->getValueType(0);
7857 unsigned NumElts = VT.getVectorNumElements();
7859 SDValue N0 = N->getOperand(0);
7860 SDValue N1 = N->getOperand(1);
7862 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
7864 // Canonicalize shuffle undef, undef -> undef
7865 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
7866 return DAG.getUNDEF(VT);
7868 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7870 // Canonicalize shuffle v, v -> v, undef
7872 SmallVector<int, 8> NewMask;
7873 for (unsigned i = 0; i != NumElts; ++i) {
7874 int Idx = SVN->getMaskElt(i);
7875 if (Idx >= (int)NumElts) Idx -= NumElts;
7876 NewMask.push_back(Idx);
7878 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
7882 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
7883 if (N0.getOpcode() == ISD::UNDEF) {
7884 SmallVector<int, 8> NewMask;
7885 for (unsigned i = 0; i != NumElts; ++i) {
7886 int Idx = SVN->getMaskElt(i);
7888 if (Idx < (int)NumElts)
7893 NewMask.push_back(Idx);
7895 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
7899 // Remove references to rhs if it is undef
7900 if (N1.getOpcode() == ISD::UNDEF) {
7901 bool Changed = false;
7902 SmallVector<int, 8> NewMask;
7903 for (unsigned i = 0; i != NumElts; ++i) {
7904 int Idx = SVN->getMaskElt(i);
7905 if (Idx >= (int)NumElts) {
7909 NewMask.push_back(Idx);
7912 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
7915 // If it is a splat, check if the argument vector is another splat or a
7916 // build_vector with all scalar elements the same.
7917 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7918 SDNode *V = N0.getNode();
7920 // If this is a bit convert that changes the element type of the vector but
7921 // not the number of vector elements, look through it. Be careful not to
7922 // look though conversions that change things like v4f32 to v2f64.
7923 if (V->getOpcode() == ISD::BITCAST) {
7924 SDValue ConvInput = V->getOperand(0);
7925 if (ConvInput.getValueType().isVector() &&
7926 ConvInput.getValueType().getVectorNumElements() == NumElts)
7927 V = ConvInput.getNode();
7930 if (V->getOpcode() == ISD::BUILD_VECTOR) {
7931 assert(V->getNumOperands() == NumElts &&
7932 "BUILD_VECTOR has wrong number of operands");
7934 bool AllSame = true;
7935 for (unsigned i = 0; i != NumElts; ++i) {
7936 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7937 Base = V->getOperand(i);
7941 // Splat of <u, u, u, u>, return <u, u, u, u>
7942 if (!Base.getNode())
7944 for (unsigned i = 0; i != NumElts; ++i) {
7945 if (V->getOperand(i) != Base) {
7950 // Splat of <x, x, x, x>, return <x, x, x, x>
7956 // If this shuffle node is simply a swizzle of another shuffle node,
7957 // and it reverses the swizzle of the previous shuffle then we can
7958 // optimize shuffle(shuffle(x, undef), undef) -> x.
7959 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
7960 N1.getOpcode() == ISD::UNDEF) {
7962 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
7964 // Shuffle nodes can only reverse shuffles with a single non-undef value.
7965 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
7968 // The incoming shuffle must be of the same type as the result of the
7970 assert(OtherSV->getOperand(0).getValueType() == VT &&
7971 "Shuffle types don't match");
7973 for (unsigned i = 0; i != NumElts; ++i) {
7974 int Idx = SVN->getMaskElt(i);
7975 assert(Idx < (int)NumElts && "Index references undef operand");
7976 // Next, this index comes from the first value, which is the incoming
7977 // shuffle. Adopt the incoming index.
7979 Idx = OtherSV->getMaskElt(Idx);
7981 // The combined shuffle must map each index to itself.
7982 if (Idx >= 0 && (unsigned)Idx != i)
7986 return OtherSV->getOperand(0);
7992 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
7993 if (!TLI.getShouldFoldAtomicFences())
7996 SDValue atomic = N->getOperand(0);
7997 switch (atomic.getOpcode()) {
7998 case ISD::ATOMIC_CMP_SWAP:
7999 case ISD::ATOMIC_SWAP:
8000 case ISD::ATOMIC_LOAD_ADD:
8001 case ISD::ATOMIC_LOAD_SUB:
8002 case ISD::ATOMIC_LOAD_AND:
8003 case ISD::ATOMIC_LOAD_OR:
8004 case ISD::ATOMIC_LOAD_XOR:
8005 case ISD::ATOMIC_LOAD_NAND:
8006 case ISD::ATOMIC_LOAD_MIN:
8007 case ISD::ATOMIC_LOAD_MAX:
8008 case ISD::ATOMIC_LOAD_UMIN:
8009 case ISD::ATOMIC_LOAD_UMAX:
8015 SDValue fence = atomic.getOperand(0);
8016 if (fence.getOpcode() != ISD::MEMBARRIER)
8019 switch (atomic.getOpcode()) {
8020 case ISD::ATOMIC_CMP_SWAP:
8021 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8022 fence.getOperand(0),
8023 atomic.getOperand(1), atomic.getOperand(2),
8024 atomic.getOperand(3)), atomic.getResNo());
8025 case ISD::ATOMIC_SWAP:
8026 case ISD::ATOMIC_LOAD_ADD:
8027 case ISD::ATOMIC_LOAD_SUB:
8028 case ISD::ATOMIC_LOAD_AND:
8029 case ISD::ATOMIC_LOAD_OR:
8030 case ISD::ATOMIC_LOAD_XOR:
8031 case ISD::ATOMIC_LOAD_NAND:
8032 case ISD::ATOMIC_LOAD_MIN:
8033 case ISD::ATOMIC_LOAD_MAX:
8034 case ISD::ATOMIC_LOAD_UMIN:
8035 case ISD::ATOMIC_LOAD_UMAX:
8036 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8037 fence.getOperand(0),
8038 atomic.getOperand(1), atomic.getOperand(2)),
8045 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
8046 /// an AND to a vector_shuffle with the destination vector and a zero vector.
8047 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
8048 /// vector_shuffle V, Zero, <0, 4, 2, 4>
8049 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
8050 EVT VT = N->getValueType(0);
8051 DebugLoc dl = N->getDebugLoc();
8052 SDValue LHS = N->getOperand(0);
8053 SDValue RHS = N->getOperand(1);
8054 if (N->getOpcode() == ISD::AND) {
8055 if (RHS.getOpcode() == ISD::BITCAST)
8056 RHS = RHS.getOperand(0);
8057 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
8058 SmallVector<int, 8> Indices;
8059 unsigned NumElts = RHS.getNumOperands();
8060 for (unsigned i = 0; i != NumElts; ++i) {
8061 SDValue Elt = RHS.getOperand(i);
8062 if (!isa<ConstantSDNode>(Elt))
8065 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
8066 Indices.push_back(i);
8067 else if (cast<ConstantSDNode>(Elt)->isNullValue())
8068 Indices.push_back(NumElts);
8073 // Let's see if the target supports this vector_shuffle.
8074 EVT RVT = RHS.getValueType();
8075 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
8078 // Return the new VECTOR_SHUFFLE node.
8079 EVT EltVT = RVT.getVectorElementType();
8080 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
8081 DAG.getConstant(0, EltVT));
8082 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8083 RVT, &ZeroOps[0], ZeroOps.size());
8084 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
8085 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
8086 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
8093 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
8094 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
8095 // After legalize, the target may be depending on adds and other
8096 // binary ops to provide legal ways to construct constants or other
8097 // things. Simplifying them may result in a loss of legality.
8098 if (LegalOperations) return SDValue();
8100 assert(N->getValueType(0).isVector() &&
8101 "SimplifyVBinOp only works on vectors!");
8103 SDValue LHS = N->getOperand(0);
8104 SDValue RHS = N->getOperand(1);
8105 SDValue Shuffle = XformToShuffleWithZero(N);
8106 if (Shuffle.getNode()) return Shuffle;
8108 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
8110 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
8111 RHS.getOpcode() == ISD::BUILD_VECTOR) {
8112 SmallVector<SDValue, 8> Ops;
8113 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
8114 SDValue LHSOp = LHS.getOperand(i);
8115 SDValue RHSOp = RHS.getOperand(i);
8116 // If these two elements can't be folded, bail out.
8117 if ((LHSOp.getOpcode() != ISD::UNDEF &&
8118 LHSOp.getOpcode() != ISD::Constant &&
8119 LHSOp.getOpcode() != ISD::ConstantFP) ||
8120 (RHSOp.getOpcode() != ISD::UNDEF &&
8121 RHSOp.getOpcode() != ISD::Constant &&
8122 RHSOp.getOpcode() != ISD::ConstantFP))
8125 // Can't fold divide by zero.
8126 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
8127 N->getOpcode() == ISD::FDIV) {
8128 if ((RHSOp.getOpcode() == ISD::Constant &&
8129 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
8130 (RHSOp.getOpcode() == ISD::ConstantFP &&
8131 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
8135 EVT VT = LHSOp.getValueType();
8136 EVT RVT = RHSOp.getValueType();
8138 // Integer BUILD_VECTOR operands may have types larger than the element
8139 // size (e.g., when the element type is not legal). Prior to type
8140 // legalization, the types may not match between the two BUILD_VECTORS.
8141 // Truncate one of the operands to make them match.
8142 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
8143 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
8145 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
8149 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
8151 if (FoldOp.getOpcode() != ISD::UNDEF &&
8152 FoldOp.getOpcode() != ISD::Constant &&
8153 FoldOp.getOpcode() != ISD::ConstantFP)
8155 Ops.push_back(FoldOp);
8156 AddToWorkList(FoldOp.getNode());
8159 if (Ops.size() == LHS.getNumOperands())
8160 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8161 LHS.getValueType(), &Ops[0], Ops.size());
8167 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
8168 SDValue N1, SDValue N2){
8169 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
8171 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
8172 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8174 // If we got a simplified select_cc node back from SimplifySelectCC, then
8175 // break it down into a new SETCC node, and a new SELECT node, and then return
8176 // the SELECT node, since we were called with a SELECT node.
8177 if (SCC.getNode()) {
8178 // Check to see if we got a select_cc back (to turn into setcc/select).
8179 // Otherwise, just return whatever node we got back, like fabs.
8180 if (SCC.getOpcode() == ISD::SELECT_CC) {
8181 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
8183 SCC.getOperand(0), SCC.getOperand(1),
8185 AddToWorkList(SETCC.getNode());
8186 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
8187 SCC.getOperand(2), SCC.getOperand(3), SETCC);
8195 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
8196 /// are the two values being selected between, see if we can simplify the
8197 /// select. Callers of this should assume that TheSelect is deleted if this
8198 /// returns true. As such, they should return the appropriate thing (e.g. the
8199 /// node) back to the top-level of the DAG combiner loop to avoid it being
8201 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
8204 // Cannot simplify select with vector condition
8205 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
8207 // If this is a select from two identical things, try to pull the operation
8208 // through the select.
8209 if (LHS.getOpcode() != RHS.getOpcode() ||
8210 !LHS.hasOneUse() || !RHS.hasOneUse())
8213 // If this is a load and the token chain is identical, replace the select
8214 // of two loads with a load through a select of the address to load from.
8215 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
8216 // constants have been dropped into the constant pool.
8217 if (LHS.getOpcode() == ISD::LOAD) {
8218 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
8219 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
8221 // Token chains must be identical.
8222 if (LHS.getOperand(0) != RHS.getOperand(0) ||
8223 // Do not let this transformation reduce the number of volatile loads.
8224 LLD->isVolatile() || RLD->isVolatile() ||
8225 // If this is an EXTLOAD, the VT's must match.
8226 LLD->getMemoryVT() != RLD->getMemoryVT() ||
8227 // If this is an EXTLOAD, the kind of extension must match.
8228 (LLD->getExtensionType() != RLD->getExtensionType() &&
8229 // The only exception is if one of the extensions is anyext.
8230 LLD->getExtensionType() != ISD::EXTLOAD &&
8231 RLD->getExtensionType() != ISD::EXTLOAD) ||
8232 // FIXME: this discards src value information. This is
8233 // over-conservative. It would be beneficial to be able to remember
8234 // both potential memory locations. Since we are discarding
8235 // src value info, don't do the transformation if the memory
8236 // locations are not in the default address space.
8237 LLD->getPointerInfo().getAddrSpace() != 0 ||
8238 RLD->getPointerInfo().getAddrSpace() != 0)
8241 // Check that the select condition doesn't reach either load. If so,
8242 // folding this will induce a cycle into the DAG. If not, this is safe to
8243 // xform, so create a select of the addresses.
8245 if (TheSelect->getOpcode() == ISD::SELECT) {
8246 SDNode *CondNode = TheSelect->getOperand(0).getNode();
8247 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
8248 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
8250 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
8251 LLD->getBasePtr().getValueType(),
8252 TheSelect->getOperand(0), LLD->getBasePtr(),
8254 } else { // Otherwise SELECT_CC
8255 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
8256 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
8258 if ((LLD->hasAnyUseOfValue(1) &&
8259 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
8260 (RLD->hasAnyUseOfValue(1) &&
8261 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
8264 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
8265 LLD->getBasePtr().getValueType(),
8266 TheSelect->getOperand(0),
8267 TheSelect->getOperand(1),
8268 LLD->getBasePtr(), RLD->getBasePtr(),
8269 TheSelect->getOperand(4));
8273 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
8274 Load = DAG.getLoad(TheSelect->getValueType(0),
8275 TheSelect->getDebugLoc(),
8276 // FIXME: Discards pointer info.
8277 LLD->getChain(), Addr, MachinePointerInfo(),
8278 LLD->isVolatile(), LLD->isNonTemporal(),
8279 LLD->isInvariant(), LLD->getAlignment());
8281 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
8282 RLD->getExtensionType() : LLD->getExtensionType(),
8283 TheSelect->getDebugLoc(),
8284 TheSelect->getValueType(0),
8285 // FIXME: Discards pointer info.
8286 LLD->getChain(), Addr, MachinePointerInfo(),
8287 LLD->getMemoryVT(), LLD->isVolatile(),
8288 LLD->isNonTemporal(), LLD->getAlignment());
8291 // Users of the select now use the result of the load.
8292 CombineTo(TheSelect, Load);
8294 // Users of the old loads now use the new load's chain. We know the
8295 // old-load value is dead now.
8296 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
8297 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
8304 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
8305 /// where 'cond' is the comparison specified by CC.
8306 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
8307 SDValue N2, SDValue N3,
8308 ISD::CondCode CC, bool NotExtCompare) {
8309 // (x ? y : y) -> y.
8310 if (N2 == N3) return N2;
8312 EVT VT = N2.getValueType();
8313 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
8314 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
8315 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
8317 // Determine if the condition we're dealing with is constant
8318 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
8319 N0, N1, CC, DL, false);
8320 if (SCC.getNode()) AddToWorkList(SCC.getNode());
8321 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
8323 // fold select_cc true, x, y -> x
8324 if (SCCC && !SCCC->isNullValue())
8326 // fold select_cc false, x, y -> y
8327 if (SCCC && SCCC->isNullValue())
8330 // Check to see if we can simplify the select into an fabs node
8331 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
8332 // Allow either -0.0 or 0.0
8333 if (CFP->getValueAPF().isZero()) {
8334 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
8335 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
8336 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
8337 N2 == N3.getOperand(0))
8338 return DAG.getNode(ISD::FABS, DL, VT, N0);
8340 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
8341 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
8342 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
8343 N2.getOperand(0) == N3)
8344 return DAG.getNode(ISD::FABS, DL, VT, N3);
8348 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
8349 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
8350 // in it. This is a win when the constant is not otherwise available because
8351 // it replaces two constant pool loads with one. We only do this if the FP
8352 // type is known to be legal, because if it isn't, then we are before legalize
8353 // types an we want the other legalization to happen first (e.g. to avoid
8354 // messing with soft float) and if the ConstantFP is not legal, because if
8355 // it is legal, we may not need to store the FP constant in a constant pool.
8356 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
8357 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
8358 if (TLI.isTypeLegal(N2.getValueType()) &&
8359 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
8360 TargetLowering::Legal) &&
8361 // If both constants have multiple uses, then we won't need to do an
8362 // extra load, they are likely around in registers for other users.
8363 (TV->hasOneUse() || FV->hasOneUse())) {
8364 Constant *Elts[] = {
8365 const_cast<ConstantFP*>(FV->getConstantFPValue()),
8366 const_cast<ConstantFP*>(TV->getConstantFPValue())
8368 Type *FPTy = Elts[0]->getType();
8369 const TargetData &TD = *TLI.getTargetData();
8371 // Create a ConstantArray of the two constants.
8372 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
8373 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
8374 TD.getPrefTypeAlignment(FPTy));
8375 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8377 // Get the offsets to the 0 and 1 element of the array so that we can
8378 // select between them.
8379 SDValue Zero = DAG.getIntPtrConstant(0);
8380 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
8381 SDValue One = DAG.getIntPtrConstant(EltSize);
8383 SDValue Cond = DAG.getSetCC(DL,
8384 TLI.getSetCCResultType(N0.getValueType()),
8386 AddToWorkList(Cond.getNode());
8387 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
8389 AddToWorkList(CstOffset.getNode());
8390 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
8392 AddToWorkList(CPIdx.getNode());
8393 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
8394 MachinePointerInfo::getConstantPool(), false,
8395 false, false, Alignment);
8400 // Check to see if we can perform the "gzip trick", transforming
8401 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
8402 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
8403 (N1C->isNullValue() || // (a < 0) ? b : 0
8404 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
8405 EVT XType = N0.getValueType();
8406 EVT AType = N2.getValueType();
8407 if (XType.bitsGE(AType)) {
8408 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
8409 // single-bit constant.
8410 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
8411 unsigned ShCtV = N2C->getAPIntValue().logBase2();
8412 ShCtV = XType.getSizeInBits()-ShCtV-1;
8413 SDValue ShCt = DAG.getConstant(ShCtV,
8414 getShiftAmountTy(N0.getValueType()));
8415 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
8417 AddToWorkList(Shift.getNode());
8419 if (XType.bitsGT(AType)) {
8420 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8421 AddToWorkList(Shift.getNode());
8424 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8427 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
8429 DAG.getConstant(XType.getSizeInBits()-1,
8430 getShiftAmountTy(N0.getValueType())));
8431 AddToWorkList(Shift.getNode());
8433 if (XType.bitsGT(AType)) {
8434 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8435 AddToWorkList(Shift.getNode());
8438 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8442 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
8443 // where y is has a single bit set.
8444 // A plaintext description would be, we can turn the SELECT_CC into an AND
8445 // when the condition can be materialized as an all-ones register. Any
8446 // single bit-test can be materialized as an all-ones register with
8447 // shift-left and shift-right-arith.
8448 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
8449 N0->getValueType(0) == VT &&
8450 N1C && N1C->isNullValue() &&
8451 N2C && N2C->isNullValue()) {
8452 SDValue AndLHS = N0->getOperand(0);
8453 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8454 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
8455 // Shift the tested bit over the sign bit.
8456 APInt AndMask = ConstAndRHS->getAPIntValue();
8458 DAG.getConstant(AndMask.countLeadingZeros(),
8459 getShiftAmountTy(AndLHS.getValueType()));
8460 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
8462 // Now arithmetic right shift it all the way over, so the result is either
8463 // all-ones, or zero.
8465 DAG.getConstant(AndMask.getBitWidth()-1,
8466 getShiftAmountTy(Shl.getValueType()));
8467 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
8469 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
8473 // fold select C, 16, 0 -> shl C, 4
8474 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
8475 TLI.getBooleanContents(N0.getValueType().isVector()) ==
8476 TargetLowering::ZeroOrOneBooleanContent) {
8478 // If the caller doesn't want us to simplify this into a zext of a compare,
8480 if (NotExtCompare && N2C->getAPIntValue() == 1)
8483 // Get a SetCC of the condition
8484 // FIXME: Should probably make sure that setcc is legal if we ever have a
8485 // target where it isn't.
8487 // cast from setcc result type to select result type
8489 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
8491 if (N2.getValueType().bitsLT(SCC.getValueType()))
8492 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
8494 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8495 N2.getValueType(), SCC);
8497 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
8498 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8499 N2.getValueType(), SCC);
8502 AddToWorkList(SCC.getNode());
8503 AddToWorkList(Temp.getNode());
8505 if (N2C->getAPIntValue() == 1)
8508 // shl setcc result by log2 n2c
8509 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
8510 DAG.getConstant(N2C->getAPIntValue().logBase2(),
8511 getShiftAmountTy(Temp.getValueType())));
8514 // Check to see if this is the equivalent of setcc
8515 // FIXME: Turn all of these into setcc if setcc if setcc is legal
8516 // otherwise, go ahead with the folds.
8517 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
8518 EVT XType = N0.getValueType();
8519 if (!LegalOperations ||
8520 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
8521 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
8522 if (Res.getValueType() != VT)
8523 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
8527 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
8528 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
8529 (!LegalOperations ||
8530 TLI.isOperationLegal(ISD::CTLZ, XType))) {
8531 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
8532 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
8533 DAG.getConstant(Log2_32(XType.getSizeInBits()),
8534 getShiftAmountTy(Ctlz.getValueType())));
8536 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
8537 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
8538 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
8539 XType, DAG.getConstant(0, XType), N0);
8540 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
8541 return DAG.getNode(ISD::SRL, DL, XType,
8542 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
8543 DAG.getConstant(XType.getSizeInBits()-1,
8544 getShiftAmountTy(XType)));
8546 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
8547 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
8548 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
8549 DAG.getConstant(XType.getSizeInBits()-1,
8550 getShiftAmountTy(N0.getValueType())));
8551 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
8555 // Check to see if this is an integer abs.
8556 // select_cc setg[te] X, 0, X, -X ->
8557 // select_cc setgt X, -1, X, -X ->
8558 // select_cc setl[te] X, 0, -X, X ->
8559 // select_cc setlt X, 1, -X, X ->
8560 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8562 ConstantSDNode *SubC = NULL;
8563 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
8564 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
8565 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
8566 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
8567 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
8568 (N1C->isOne() && CC == ISD::SETLT)) &&
8569 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
8570 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
8572 EVT XType = N0.getValueType();
8573 if (SubC && SubC->isNullValue() && XType.isInteger()) {
8574 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
8576 DAG.getConstant(XType.getSizeInBits()-1,
8577 getShiftAmountTy(N0.getValueType())));
8578 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
8580 AddToWorkList(Shift.getNode());
8581 AddToWorkList(Add.getNode());
8582 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
8589 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
8590 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
8591 SDValue N1, ISD::CondCode Cond,
8592 DebugLoc DL, bool foldBooleans) {
8593 TargetLowering::DAGCombinerInfo
8594 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
8595 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
8598 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
8599 /// return a DAG expression to select that will generate the same value by
8600 /// multiplying by a magic number. See:
8601 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8602 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
8603 std::vector<SDNode*> Built;
8604 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
8606 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8612 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
8613 /// return a DAG expression to select that will generate the same value by
8614 /// multiplying by a magic number. See:
8615 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8616 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
8617 std::vector<SDNode*> Built;
8618 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
8620 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8626 /// FindBaseOffset - Return true if base is a frame index, which is known not
8627 // to alias with anything but itself. Provides base object and offset as
8629 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
8630 const GlobalValue *&GV, void *&CV) {
8631 // Assume it is a primitive operation.
8632 Base = Ptr; Offset = 0; GV = 0; CV = 0;
8634 // If it's an adding a simple constant then integrate the offset.
8635 if (Base.getOpcode() == ISD::ADD) {
8636 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
8637 Base = Base.getOperand(0);
8638 Offset += C->getZExtValue();
8642 // Return the underlying GlobalValue, and update the Offset. Return false
8643 // for GlobalAddressSDNode since the same GlobalAddress may be represented
8644 // by multiple nodes with different offsets.
8645 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
8646 GV = G->getGlobal();
8647 Offset += G->getOffset();
8651 // Return the underlying Constant value, and update the Offset. Return false
8652 // for ConstantSDNodes since the same constant pool entry may be represented
8653 // by multiple nodes with different offsets.
8654 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
8655 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
8656 : (void *)C->getConstVal();
8657 Offset += C->getOffset();
8660 // If it's any of the following then it can't alias with anything but itself.
8661 return isa<FrameIndexSDNode>(Base);
8664 /// isAlias - Return true if there is any possibility that the two addresses
8666 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
8667 const Value *SrcValue1, int SrcValueOffset1,
8668 unsigned SrcValueAlign1,
8669 const MDNode *TBAAInfo1,
8670 SDValue Ptr2, int64_t Size2,
8671 const Value *SrcValue2, int SrcValueOffset2,
8672 unsigned SrcValueAlign2,
8673 const MDNode *TBAAInfo2) const {
8674 // If they are the same then they must be aliases.
8675 if (Ptr1 == Ptr2) return true;
8677 // Gather base node and offset information.
8678 SDValue Base1, Base2;
8679 int64_t Offset1, Offset2;
8680 const GlobalValue *GV1, *GV2;
8682 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
8683 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
8685 // If they have a same base address then check to see if they overlap.
8686 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
8687 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8689 // It is possible for different frame indices to alias each other, mostly
8690 // when tail call optimization reuses return address slots for arguments.
8691 // To catch this case, look up the actual index of frame indices to compute
8692 // the real alias relationship.
8693 if (isFrameIndex1 && isFrameIndex2) {
8694 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8695 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
8696 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
8697 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8700 // Otherwise, if we know what the bases are, and they aren't identical, then
8701 // we know they cannot alias.
8702 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
8705 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
8706 // compared to the size and offset of the access, we may be able to prove they
8707 // do not alias. This check is conservative for now to catch cases created by
8708 // splitting vector types.
8709 if ((SrcValueAlign1 == SrcValueAlign2) &&
8710 (SrcValueOffset1 != SrcValueOffset2) &&
8711 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
8712 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
8713 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
8715 // There is no overlap between these relatively aligned accesses of similar
8716 // size, return no alias.
8717 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
8721 if (CombinerGlobalAA) {
8722 // Use alias analysis information.
8723 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
8724 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
8725 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
8726 AliasAnalysis::AliasResult AAResult =
8727 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
8728 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
8729 if (AAResult == AliasAnalysis::NoAlias)
8733 // Otherwise we have to assume they alias.
8737 /// FindAliasInfo - Extracts the relevant alias information from the memory
8738 /// node. Returns true if the operand was a load.
8739 bool DAGCombiner::FindAliasInfo(SDNode *N,
8740 SDValue &Ptr, int64_t &Size,
8741 const Value *&SrcValue,
8742 int &SrcValueOffset,
8743 unsigned &SrcValueAlign,
8744 const MDNode *&TBAAInfo) const {
8745 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
8747 Ptr = LS->getBasePtr();
8748 Size = LS->getMemoryVT().getSizeInBits() >> 3;
8749 SrcValue = LS->getSrcValue();
8750 SrcValueOffset = LS->getSrcValueOffset();
8751 SrcValueAlign = LS->getOriginalAlignment();
8752 TBAAInfo = LS->getTBAAInfo();
8753 return isa<LoadSDNode>(LS);
8756 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8757 /// looking for aliasing nodes and adding them to the Aliases vector.
8758 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8759 SmallVector<SDValue, 8> &Aliases) {
8760 SmallVector<SDValue, 8> Chains; // List of chains to visit.
8761 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
8763 // Get alias information for node.
8766 const Value *SrcValue;
8768 unsigned SrcValueAlign;
8769 const MDNode *SrcTBAAInfo;
8770 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8771 SrcValueAlign, SrcTBAAInfo);
8774 Chains.push_back(OriginalChain);
8777 // Look at each chain and determine if it is an alias. If so, add it to the
8778 // aliases list. If not, then continue up the chain looking for the next
8780 while (!Chains.empty()) {
8781 SDValue Chain = Chains.back();
8784 // For TokenFactor nodes, look at each operand and only continue up the
8785 // chain until we find two aliases. If we've seen two aliases, assume we'll
8786 // find more and revert to original chain since the xform is unlikely to be
8789 // FIXME: The depth check could be made to return the last non-aliasing
8790 // chain we found before we hit a tokenfactor rather than the original
8792 if (Depth > 6 || Aliases.size() == 2) {
8794 Aliases.push_back(OriginalChain);
8798 // Don't bother if we've been before.
8799 if (!Visited.insert(Chain.getNode()))
8802 switch (Chain.getOpcode()) {
8803 case ISD::EntryToken:
8804 // Entry token is ideal chain operand, but handled in FindBetterChain.
8809 // Get alias information for Chain.
8812 const Value *OpSrcValue;
8813 int OpSrcValueOffset;
8814 unsigned OpSrcValueAlign;
8815 const MDNode *OpSrcTBAAInfo;
8816 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8817 OpSrcValue, OpSrcValueOffset,
8821 // If chain is alias then stop here.
8822 if (!(IsLoad && IsOpLoad) &&
8823 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8825 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8826 OpSrcValueAlign, OpSrcTBAAInfo)) {
8827 Aliases.push_back(Chain);
8829 // Look further up the chain.
8830 Chains.push_back(Chain.getOperand(0));
8836 case ISD::TokenFactor:
8837 // We have to check each of the operands of the token factor for "small"
8838 // token factors, so we queue them up. Adding the operands to the queue
8839 // (stack) in reverse order maintains the original order and increases the
8840 // likelihood that getNode will find a matching token factor (CSE.)
8841 if (Chain.getNumOperands() > 16) {
8842 Aliases.push_back(Chain);
8845 for (unsigned n = Chain.getNumOperands(); n;)
8846 Chains.push_back(Chain.getOperand(--n));
8851 // For all other instructions we will just have to take what we can get.
8852 Aliases.push_back(Chain);
8858 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8859 /// for a better chain (aliasing node.)
8860 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8861 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
8863 // Accumulate all the aliases to this node.
8864 GatherAllAliases(N, OldChain, Aliases);
8866 // If no operands then chain to entry token.
8867 if (Aliases.size() == 0)
8868 return DAG.getEntryNode();
8870 // If a single operand then chain to it. We don't need to revisit it.
8871 if (Aliases.size() == 1)
8874 // Construct a custom tailored token factor.
8875 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8876 &Aliases[0], Aliases.size());
8879 // SelectionDAG::Combine - This is the entry point for the file.
8881 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8882 CodeGenOpt::Level OptLevel) {
8883 /// run - This is the main entry point to this class.
8885 DAGCombiner(*this, AA, OptLevel).Run(Level);