1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
41 STATISTIC(NodesCombined , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
68 // This has the semantics that when adding to the worklist,
69 // the item added must be next to be processed. It should
70 // also only appear once. The naive approach to this takes
73 // To reduce the insert/remove time to logarithmic, we use
74 // a set and a vector to maintain our worklist.
76 // The set contains the items on the worklist, but does not
77 // maintain the order they should be visited.
79 // The vector maintains the order nodes should be visited, but may
80 // contain duplicate or removed nodes. When choosing a node to
81 // visit, we pop off the order stack until we find an item that is
82 // also in the contents set. All operations are O(log N).
83 SmallPtrSet<SDNode*, 64> WorkListContents;
84 SmallVector<SDNode*, 64> WorkListOrder;
86 // AA - Used for DAG load/store alias analysis.
89 /// AddUsersToWorkList - When an instruction is simplified, add all users of
90 /// the instruction to the work lists because they might get more simplified
93 void AddUsersToWorkList(SDNode *N) {
94 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
99 /// visit - call the node-specific routine that knows how to fold each
100 /// particular type of node.
101 SDValue visit(SDNode *N);
104 /// AddToWorkList - Add to the work list making sure its instance is at the
105 /// back (next to be processed.)
106 void AddToWorkList(SDNode *N) {
107 WorkListContents.insert(N);
108 WorkListOrder.push_back(N);
111 /// removeFromWorkList - remove all instances of N from the worklist.
113 void removeFromWorkList(SDNode *N) {
114 WorkListContents.erase(N);
117 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
120 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121 return CombineTo(N, &Res, 1, AddTo);
124 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126 SDValue To[] = { Res0, Res1 };
127 return CombineTo(N, To, 2, AddTo);
130 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
134 /// SimplifyDemandedBits - Check the specified integer node value to see if
135 /// it can be simplified or if things it uses can be simplified by bit
136 /// propagation. If so, return true.
137 bool SimplifyDemandedBits(SDValue Op) {
138 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139 APInt Demanded = APInt::getAllOnesValue(BitWidth);
140 return SimplifyDemandedBits(Op, Demanded);
143 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145 bool CombineToPreIndexedLoadStore(SDNode *N);
146 bool CombineToPostIndexedLoadStore(SDNode *N);
148 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152 SDValue PromoteIntBinOp(SDValue Op);
153 SDValue PromoteIntShiftOp(SDValue Op);
154 SDValue PromoteExtend(SDValue Op);
155 bool PromoteLoad(SDValue Op);
157 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
158 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
159 ISD::NodeType ExtType);
161 /// combine - call the node-specific routine that knows how to fold each
162 /// particular type of node. If that doesn't do anything, try the
163 /// target-specific DAG combines.
164 SDValue combine(SDNode *N);
166 // Visitation implementation - Implement dag node combining for different
167 // node types. The semantics are as follows:
169 // SDValue.getNode() == 0 - No change was made
170 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
171 // otherwise - N should be replaced by the returned Operand.
173 SDValue visitTokenFactor(SDNode *N);
174 SDValue visitMERGE_VALUES(SDNode *N);
175 SDValue visitADD(SDNode *N);
176 SDValue visitSUB(SDNode *N);
177 SDValue visitADDC(SDNode *N);
178 SDValue visitSUBC(SDNode *N);
179 SDValue visitADDE(SDNode *N);
180 SDValue visitSUBE(SDNode *N);
181 SDValue visitMUL(SDNode *N);
182 SDValue visitSDIV(SDNode *N);
183 SDValue visitUDIV(SDNode *N);
184 SDValue visitSREM(SDNode *N);
185 SDValue visitUREM(SDNode *N);
186 SDValue visitMULHU(SDNode *N);
187 SDValue visitMULHS(SDNode *N);
188 SDValue visitSMUL_LOHI(SDNode *N);
189 SDValue visitUMUL_LOHI(SDNode *N);
190 SDValue visitSMULO(SDNode *N);
191 SDValue visitUMULO(SDNode *N);
192 SDValue visitSDIVREM(SDNode *N);
193 SDValue visitUDIVREM(SDNode *N);
194 SDValue visitAND(SDNode *N);
195 SDValue visitOR(SDNode *N);
196 SDValue visitXOR(SDNode *N);
197 SDValue SimplifyVBinOp(SDNode *N);
198 SDValue SimplifyVUnaryOp(SDNode *N);
199 SDValue visitSHL(SDNode *N);
200 SDValue visitSRA(SDNode *N);
201 SDValue visitSRL(SDNode *N);
202 SDValue visitCTLZ(SDNode *N);
203 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204 SDValue visitCTTZ(SDNode *N);
205 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206 SDValue visitCTPOP(SDNode *N);
207 SDValue visitSELECT(SDNode *N);
208 SDValue visitVSELECT(SDNode *N);
209 SDValue visitSELECT_CC(SDNode *N);
210 SDValue visitSETCC(SDNode *N);
211 SDValue visitSIGN_EXTEND(SDNode *N);
212 SDValue visitZERO_EXTEND(SDNode *N);
213 SDValue visitANY_EXTEND(SDNode *N);
214 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
215 SDValue visitTRUNCATE(SDNode *N);
216 SDValue visitBITCAST(SDNode *N);
217 SDValue visitBUILD_PAIR(SDNode *N);
218 SDValue visitFADD(SDNode *N);
219 SDValue visitFSUB(SDNode *N);
220 SDValue visitFMUL(SDNode *N);
221 SDValue visitFMA(SDNode *N);
222 SDValue visitFDIV(SDNode *N);
223 SDValue visitFREM(SDNode *N);
224 SDValue visitFCOPYSIGN(SDNode *N);
225 SDValue visitSINT_TO_FP(SDNode *N);
226 SDValue visitUINT_TO_FP(SDNode *N);
227 SDValue visitFP_TO_SINT(SDNode *N);
228 SDValue visitFP_TO_UINT(SDNode *N);
229 SDValue visitFP_ROUND(SDNode *N);
230 SDValue visitFP_ROUND_INREG(SDNode *N);
231 SDValue visitFP_EXTEND(SDNode *N);
232 SDValue visitFNEG(SDNode *N);
233 SDValue visitFABS(SDNode *N);
234 SDValue visitFCEIL(SDNode *N);
235 SDValue visitFTRUNC(SDNode *N);
236 SDValue visitFFLOOR(SDNode *N);
237 SDValue visitBRCOND(SDNode *N);
238 SDValue visitBR_CC(SDNode *N);
239 SDValue visitLOAD(SDNode *N);
240 SDValue visitSTORE(SDNode *N);
241 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
242 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
243 SDValue visitBUILD_VECTOR(SDNode *N);
244 SDValue visitCONCAT_VECTORS(SDNode *N);
245 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
246 SDValue visitVECTOR_SHUFFLE(SDNode *N);
248 SDValue XformToShuffleWithZero(SDNode *N);
249 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
251 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
254 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
255 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
256 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
257 SDValue N3, ISD::CondCode CC,
258 bool NotExtCompare = false);
259 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
260 DebugLoc DL, bool foldBooleans = true);
261 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
264 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
265 SDValue BuildSDIV(SDNode *N);
266 SDValue BuildUDIV(SDNode *N);
267 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268 bool DemandHighBits = true);
269 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
271 SDValue ReduceLoadWidth(SDNode *N);
272 SDValue ReduceLoadOpStoreWidth(SDNode *N);
273 SDValue TransformFPLoadStorePair(SDNode *N);
274 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280 /// looking for aliasing nodes and adding them to the Aliases vector.
281 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282 SmallVector<SDValue, 8> &Aliases);
284 /// isAlias - Return true if there is any possibility that the two addresses
286 bool isAlias(SDValue Ptr1, int64_t Size1,
287 const Value *SrcValue1, int SrcValueOffset1,
288 unsigned SrcValueAlign1,
289 const MDNode *TBAAInfo1,
290 SDValue Ptr2, int64_t Size2,
291 const Value *SrcValue2, int SrcValueOffset2,
292 unsigned SrcValueAlign2,
293 const MDNode *TBAAInfo2) const;
295 /// isAlias - Return true if there is any possibility that the two addresses
297 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299 /// FindAliasInfo - Extracts the relevant alias information from the memory
300 /// node. Returns true if the operand was a load.
301 bool FindAliasInfo(SDNode *N,
302 SDValue &Ptr, int64_t &Size,
303 const Value *&SrcValue, int &SrcValueOffset,
304 unsigned &SrcValueAlignment,
305 const MDNode *&TBAAInfo) const;
307 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308 /// looking for a better chain (aliasing node.)
309 SDValue FindBetterChain(SDNode *N, SDValue Chain);
311 /// Merge consecutive store operations into a wide store.
312 /// This optimization uses wide integers or vectors when possible.
313 /// \return True if some memory operations were changed.
314 bool MergeConsecutiveStores(StoreSDNode *N);
317 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321 /// Run - runs the dag combiner on all nodes in the work list
322 void Run(CombineLevel AtLevel);
324 SelectionDAG &getDAG() const { return DAG; }
326 /// getShiftAmountTy - Returns a type large enough to hold any valid
327 /// shift amount - before type legalization these can be huge.
328 EVT getShiftAmountTy(EVT LHSTy) {
329 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
332 /// isTypeLegal - This method returns true if we are running before type
333 /// legalization or if the specified VT is legal.
334 bool isTypeLegal(const EVT &VT) {
335 if (!LegalTypes) return true;
336 return TLI.isTypeLegal(VT);
343 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
344 /// nodes from the worklist.
345 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
348 explicit WorkListRemover(DAGCombiner &dc)
349 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
351 virtual void NodeDeleted(SDNode *N, SDNode *E) {
352 DC.removeFromWorkList(N);
357 //===----------------------------------------------------------------------===//
358 // TargetLowering::DAGCombinerInfo implementation
359 //===----------------------------------------------------------------------===//
361 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
362 ((DAGCombiner*)DC)->AddToWorkList(N);
365 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
366 ((DAGCombiner*)DC)->removeFromWorkList(N);
369 SDValue TargetLowering::DAGCombinerInfo::
370 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
371 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
374 SDValue TargetLowering::DAGCombinerInfo::
375 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
376 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
380 SDValue TargetLowering::DAGCombinerInfo::
381 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
382 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
385 void TargetLowering::DAGCombinerInfo::
386 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
387 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
390 //===----------------------------------------------------------------------===//
392 //===----------------------------------------------------------------------===//
394 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
395 /// specified expression for the same cost as the expression itself, or 2 if we
396 /// can compute the negated form more cheaply than the expression itself.
397 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
398 const TargetLowering &TLI,
399 const TargetOptions *Options,
400 unsigned Depth = 0) {
401 // fneg is removable even if it has multiple uses.
402 if (Op.getOpcode() == ISD::FNEG) return 2;
404 // Don't allow anything with multiple uses.
405 if (!Op.hasOneUse()) return 0;
407 // Don't recurse exponentially.
408 if (Depth > 6) return 0;
410 switch (Op.getOpcode()) {
411 default: return false;
412 case ISD::ConstantFP:
413 // Don't invert constant FP values after legalize. The negated constant
414 // isn't necessarily legal.
415 return LegalOperations ? 0 : 1;
417 // FIXME: determine better conditions for this xform.
418 if (!Options->UnsafeFPMath) return 0;
420 // After operation legalization, it might not be legal to create new FSUBs.
421 if (LegalOperations &&
422 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
425 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
426 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
429 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
430 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
433 // We can't turn -(A-B) into B-A when we honor signed zeros.
434 if (!Options->UnsafeFPMath) return 0;
436 // fold (fneg (fsub A, B)) -> (fsub B, A)
441 if (Options->HonorSignDependentRoundingFPMath()) return 0;
443 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
444 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
448 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
454 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
459 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
460 /// returns the newly negated expression.
461 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
462 bool LegalOperations, unsigned Depth = 0) {
463 // fneg is removable even if it has multiple uses.
464 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
466 // Don't allow anything with multiple uses.
467 assert(Op.hasOneUse() && "Unknown reuse!");
469 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
470 switch (Op.getOpcode()) {
471 default: llvm_unreachable("Unknown code");
472 case ISD::ConstantFP: {
473 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
475 return DAG.getConstantFP(V, Op.getValueType());
478 // FIXME: determine better conditions for this xform.
479 assert(DAG.getTarget().Options.UnsafeFPMath);
481 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
482 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
483 DAG.getTargetLoweringInfo(),
484 &DAG.getTarget().Options, Depth+1))
485 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
486 GetNegatedExpression(Op.getOperand(0), DAG,
487 LegalOperations, Depth+1),
489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
491 GetNegatedExpression(Op.getOperand(1), DAG,
492 LegalOperations, Depth+1),
495 // We can't turn -(A-B) into B-A when we honor signed zeros.
496 assert(DAG.getTarget().Options.UnsafeFPMath);
498 // fold (fneg (fsub 0, B)) -> B
499 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
500 if (N0CFP->getValueAPF().isZero())
501 return Op.getOperand(1);
503 // fold (fneg (fsub A, B)) -> (fsub B, A)
504 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
505 Op.getOperand(1), Op.getOperand(0));
509 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
511 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
512 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513 DAG.getTargetLoweringInfo(),
514 &DAG.getTarget().Options, Depth+1))
515 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
516 GetNegatedExpression(Op.getOperand(0), DAG,
517 LegalOperations, Depth+1),
520 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
521 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
523 GetNegatedExpression(Op.getOperand(1), DAG,
524 LegalOperations, Depth+1));
528 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
529 GetNegatedExpression(Op.getOperand(0), DAG,
530 LegalOperations, Depth+1));
532 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
533 GetNegatedExpression(Op.getOperand(0), DAG,
534 LegalOperations, Depth+1),
540 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
541 // that selects between the values 1 and 0, making it equivalent to a setcc.
542 // Also, set the incoming LHS, RHS, and CC references to the appropriate
543 // nodes based on the type of node we are checking. This simplifies life a
544 // bit for the callers.
545 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
547 if (N.getOpcode() == ISD::SETCC) {
548 LHS = N.getOperand(0);
549 RHS = N.getOperand(1);
550 CC = N.getOperand(2);
553 if (N.getOpcode() == ISD::SELECT_CC &&
554 N.getOperand(2).getOpcode() == ISD::Constant &&
555 N.getOperand(3).getOpcode() == ISD::Constant &&
556 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
557 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
558 LHS = N.getOperand(0);
559 RHS = N.getOperand(1);
560 CC = N.getOperand(4);
566 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
567 // one use. If this is true, it allows the users to invert the operation for
568 // free when it is profitable to do so.
569 static bool isOneUseSetCC(SDValue N) {
571 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
576 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
577 SDValue N0, SDValue N1) {
578 EVT VT = N0.getValueType();
579 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
580 if (isa<ConstantSDNode>(N1)) {
581 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
583 DAG.FoldConstantArithmetic(Opc, VT,
584 cast<ConstantSDNode>(N0.getOperand(1)),
585 cast<ConstantSDNode>(N1));
586 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
588 if (N0.hasOneUse()) {
589 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
590 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
591 N0.getOperand(0), N1);
592 AddToWorkList(OpNode.getNode());
593 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
597 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
598 if (isa<ConstantSDNode>(N0)) {
599 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
601 DAG.FoldConstantArithmetic(Opc, VT,
602 cast<ConstantSDNode>(N1.getOperand(1)),
603 cast<ConstantSDNode>(N0));
604 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
606 if (N1.hasOneUse()) {
607 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
608 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
609 N1.getOperand(0), N0);
610 AddToWorkList(OpNode.getNode());
611 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
618 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
620 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
622 DEBUG(dbgs() << "\nReplacing.1 ";
624 dbgs() << "\nWith: ";
625 To[0].getNode()->dump(&DAG);
626 dbgs() << " and " << NumTo-1 << " other values\n";
627 for (unsigned i = 0, e = NumTo; i != e; ++i)
628 assert((!To[i].getNode() ||
629 N->getValueType(i) == To[i].getValueType()) &&
630 "Cannot combine value to value of different type!"));
631 WorkListRemover DeadNodes(*this);
632 DAG.ReplaceAllUsesWith(N, To);
634 // Push the new nodes and any users onto the worklist
635 for (unsigned i = 0, e = NumTo; i != e; ++i) {
636 if (To[i].getNode()) {
637 AddToWorkList(To[i].getNode());
638 AddUsersToWorkList(To[i].getNode());
643 // Finally, if the node is now dead, remove it from the graph. The node
644 // may not be dead if the replacement process recursively simplified to
645 // something else needing this node.
646 if (N->use_empty()) {
647 // Nodes can be reintroduced into the worklist. Make sure we do not
648 // process a node that has been replaced.
649 removeFromWorkList(N);
651 // Finally, since the node is now dead, remove it from the graph.
654 return SDValue(N, 0);
658 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
659 // Replace all uses. If any nodes become isomorphic to other nodes and
660 // are deleted, make sure to remove them from our worklist.
661 WorkListRemover DeadNodes(*this);
662 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
664 // Push the new node and any (possibly new) users onto the worklist.
665 AddToWorkList(TLO.New.getNode());
666 AddUsersToWorkList(TLO.New.getNode());
668 // Finally, if the node is now dead, remove it from the graph. The node
669 // may not be dead if the replacement process recursively simplified to
670 // something else needing this node.
671 if (TLO.Old.getNode()->use_empty()) {
672 removeFromWorkList(TLO.Old.getNode());
674 // If the operands of this node are only used by the node, they will now
675 // be dead. Make sure to visit them first to delete dead nodes early.
676 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
677 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
678 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
680 DAG.DeleteNode(TLO.Old.getNode());
684 /// SimplifyDemandedBits - Check the specified integer node value to see if
685 /// it can be simplified or if things it uses can be simplified by bit
686 /// propagation. If so, return true.
687 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
688 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
689 APInt KnownZero, KnownOne;
690 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
694 AddToWorkList(Op.getNode());
696 // Replace the old value with the new one.
698 DEBUG(dbgs() << "\nReplacing.2 ";
699 TLO.Old.getNode()->dump(&DAG);
700 dbgs() << "\nWith: ";
701 TLO.New.getNode()->dump(&DAG);
704 CommitTargetLoweringOpt(TLO);
708 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
709 DebugLoc dl = Load->getDebugLoc();
710 EVT VT = Load->getValueType(0);
711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
713 DEBUG(dbgs() << "\nReplacing.9 ";
715 dbgs() << "\nWith: ";
716 Trunc.getNode()->dump(&DAG);
718 WorkListRemover DeadNodes(*this);
719 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
720 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
721 removeFromWorkList(Load);
722 DAG.DeleteNode(Load);
723 AddToWorkList(Trunc.getNode());
726 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
728 DebugLoc dl = Op.getDebugLoc();
729 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
730 EVT MemVT = LD->getMemoryVT();
731 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
732 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
734 : LD->getExtensionType();
736 return DAG.getExtLoad(ExtType, dl, PVT,
737 LD->getChain(), LD->getBasePtr(),
738 LD->getPointerInfo(),
739 MemVT, LD->isVolatile(),
740 LD->isNonTemporal(), LD->getAlignment());
743 unsigned Opc = Op.getOpcode();
746 case ISD::AssertSext:
747 return DAG.getNode(ISD::AssertSext, dl, PVT,
748 SExtPromoteOperand(Op.getOperand(0), PVT),
750 case ISD::AssertZext:
751 return DAG.getNode(ISD::AssertZext, dl, PVT,
752 ZExtPromoteOperand(Op.getOperand(0), PVT),
754 case ISD::Constant: {
756 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
757 return DAG.getNode(ExtOpc, dl, PVT, Op);
761 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
763 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
766 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
767 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
769 EVT OldVT = Op.getValueType();
770 DebugLoc dl = Op.getDebugLoc();
771 bool Replace = false;
772 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
773 if (NewOp.getNode() == 0)
775 AddToWorkList(NewOp.getNode());
778 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
779 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
780 DAG.getValueType(OldVT));
783 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
784 EVT OldVT = Op.getValueType();
785 DebugLoc dl = Op.getDebugLoc();
786 bool Replace = false;
787 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
788 if (NewOp.getNode() == 0)
790 AddToWorkList(NewOp.getNode());
793 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
794 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
797 /// PromoteIntBinOp - Promote the specified integer binary operation if the
798 /// target indicates it is beneficial. e.g. On x86, it's usually better to
799 /// promote i16 operations to i32 since i16 instructions are longer.
800 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
801 if (!LegalOperations)
804 EVT VT = Op.getValueType();
805 if (VT.isVector() || !VT.isInteger())
808 // If operation type is 'undesirable', e.g. i16 on x86, consider
810 unsigned Opc = Op.getOpcode();
811 if (TLI.isTypeDesirableForOp(Opc, VT))
815 // Consult target whether it is a good idea to promote this operation and
816 // what's the right type to promote it to.
817 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
818 assert(PVT != VT && "Don't know what type to promote to!");
820 bool Replace0 = false;
821 SDValue N0 = Op.getOperand(0);
822 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
823 if (NN0.getNode() == 0)
826 bool Replace1 = false;
827 SDValue N1 = Op.getOperand(1);
832 NN1 = PromoteOperand(N1, PVT, Replace1);
833 if (NN1.getNode() == 0)
837 AddToWorkList(NN0.getNode());
839 AddToWorkList(NN1.getNode());
842 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
844 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
846 DEBUG(dbgs() << "\nPromoting ";
847 Op.getNode()->dump(&DAG));
848 DebugLoc dl = Op.getDebugLoc();
849 return DAG.getNode(ISD::TRUNCATE, dl, VT,
850 DAG.getNode(Opc, dl, PVT, NN0, NN1));
855 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
856 /// target indicates it is beneficial. e.g. On x86, it's usually better to
857 /// promote i16 operations to i32 since i16 instructions are longer.
858 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
859 if (!LegalOperations)
862 EVT VT = Op.getValueType();
863 if (VT.isVector() || !VT.isInteger())
866 // If operation type is 'undesirable', e.g. i16 on x86, consider
868 unsigned Opc = Op.getOpcode();
869 if (TLI.isTypeDesirableForOp(Opc, VT))
873 // Consult target whether it is a good idea to promote this operation and
874 // what's the right type to promote it to.
875 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
876 assert(PVT != VT && "Don't know what type to promote to!");
878 bool Replace = false;
879 SDValue N0 = Op.getOperand(0);
881 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
882 else if (Opc == ISD::SRL)
883 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
885 N0 = PromoteOperand(N0, PVT, Replace);
886 if (N0.getNode() == 0)
889 AddToWorkList(N0.getNode());
891 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
893 DEBUG(dbgs() << "\nPromoting ";
894 Op.getNode()->dump(&DAG));
895 DebugLoc dl = Op.getDebugLoc();
896 return DAG.getNode(ISD::TRUNCATE, dl, VT,
897 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
902 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
903 if (!LegalOperations)
906 EVT VT = Op.getValueType();
907 if (VT.isVector() || !VT.isInteger())
910 // If operation type is 'undesirable', e.g. i16 on x86, consider
912 unsigned Opc = Op.getOpcode();
913 if (TLI.isTypeDesirableForOp(Opc, VT))
917 // Consult target whether it is a good idea to promote this operation and
918 // what's the right type to promote it to.
919 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
920 assert(PVT != VT && "Don't know what type to promote to!");
921 // fold (aext (aext x)) -> (aext x)
922 // fold (aext (zext x)) -> (zext x)
923 // fold (aext (sext x)) -> (sext x)
924 DEBUG(dbgs() << "\nPromoting ";
925 Op.getNode()->dump(&DAG));
926 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
931 bool DAGCombiner::PromoteLoad(SDValue Op) {
932 if (!LegalOperations)
935 EVT VT = Op.getValueType();
936 if (VT.isVector() || !VT.isInteger())
939 // If operation type is 'undesirable', e.g. i16 on x86, consider
941 unsigned Opc = Op.getOpcode();
942 if (TLI.isTypeDesirableForOp(Opc, VT))
946 // Consult target whether it is a good idea to promote this operation and
947 // what's the right type to promote it to.
948 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
949 assert(PVT != VT && "Don't know what type to promote to!");
951 DebugLoc dl = Op.getDebugLoc();
952 SDNode *N = Op.getNode();
953 LoadSDNode *LD = cast<LoadSDNode>(N);
954 EVT MemVT = LD->getMemoryVT();
955 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
956 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
958 : LD->getExtensionType();
959 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
960 LD->getChain(), LD->getBasePtr(),
961 LD->getPointerInfo(),
962 MemVT, LD->isVolatile(),
963 LD->isNonTemporal(), LD->getAlignment());
964 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
966 DEBUG(dbgs() << "\nPromoting ";
969 Result.getNode()->dump(&DAG);
971 WorkListRemover DeadNodes(*this);
972 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
973 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
974 removeFromWorkList(N);
976 AddToWorkList(Result.getNode());
983 //===----------------------------------------------------------------------===//
984 // Main DAG Combiner implementation
985 //===----------------------------------------------------------------------===//
987 void DAGCombiner::Run(CombineLevel AtLevel) {
988 // set the instance variables, so that the various visit routines may use it.
990 LegalOperations = Level >= AfterLegalizeVectorOps;
991 LegalTypes = Level >= AfterLegalizeTypes;
993 // Add all the dag nodes to the worklist.
994 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
995 E = DAG.allnodes_end(); I != E; ++I)
998 // Create a dummy node (which is not added to allnodes), that adds a reference
999 // to the root node, preventing it from being deleted, and tracking any
1000 // changes of the root.
1001 HandleSDNode Dummy(DAG.getRoot());
1003 // The root of the dag may dangle to deleted nodes until the dag combiner is
1004 // done. Set it to null to avoid confusion.
1005 DAG.setRoot(SDValue());
1007 // while the worklist isn't empty, find a node and
1008 // try and combine it.
1009 while (!WorkListContents.empty()) {
1011 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1012 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1013 // worklist *should* contain, and check the node we want to visit is should
1014 // actually be visited.
1016 N = WorkListOrder.pop_back_val();
1017 } while (!WorkListContents.erase(N));
1019 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1020 // N is deleted from the DAG, since they too may now be dead or may have a
1021 // reduced number of uses, allowing other xforms.
1022 if (N->use_empty() && N != &Dummy) {
1023 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1024 AddToWorkList(N->getOperand(i).getNode());
1030 SDValue RV = combine(N);
1032 if (RV.getNode() == 0)
1037 // If we get back the same node we passed in, rather than a new node or
1038 // zero, we know that the node must have defined multiple values and
1039 // CombineTo was used. Since CombineTo takes care of the worklist
1040 // mechanics for us, we have no work to do in this case.
1041 if (RV.getNode() == N)
1044 assert(N->getOpcode() != ISD::DELETED_NODE &&
1045 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1046 "Node was deleted but visit returned new node!");
1048 DEBUG(dbgs() << "\nReplacing.3 ";
1050 dbgs() << "\nWith: ";
1051 RV.getNode()->dump(&DAG);
1054 // Transfer debug value.
1055 DAG.TransferDbgValues(SDValue(N, 0), RV);
1056 WorkListRemover DeadNodes(*this);
1057 if (N->getNumValues() == RV.getNode()->getNumValues())
1058 DAG.ReplaceAllUsesWith(N, RV.getNode());
1060 assert(N->getValueType(0) == RV.getValueType() &&
1061 N->getNumValues() == 1 && "Type mismatch");
1063 DAG.ReplaceAllUsesWith(N, &OpV);
1066 // Push the new node and any users onto the worklist
1067 AddToWorkList(RV.getNode());
1068 AddUsersToWorkList(RV.getNode());
1070 // Add any uses of the old node to the worklist in case this node is the
1071 // last one that uses them. They may become dead after this node is
1073 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1074 AddToWorkList(N->getOperand(i).getNode());
1076 // Finally, if the node is now dead, remove it from the graph. The node
1077 // may not be dead if the replacement process recursively simplified to
1078 // something else needing this node.
1079 if (N->use_empty()) {
1080 // Nodes can be reintroduced into the worklist. Make sure we do not
1081 // process a node that has been replaced.
1082 removeFromWorkList(N);
1084 // Finally, since the node is now dead, remove it from the graph.
1089 // If the root changed (e.g. it was a dead load, update the root).
1090 DAG.setRoot(Dummy.getValue());
1091 DAG.RemoveDeadNodes();
1094 SDValue DAGCombiner::visit(SDNode *N) {
1095 switch (N->getOpcode()) {
1097 case ISD::TokenFactor: return visitTokenFactor(N);
1098 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1099 case ISD::ADD: return visitADD(N);
1100 case ISD::SUB: return visitSUB(N);
1101 case ISD::ADDC: return visitADDC(N);
1102 case ISD::SUBC: return visitSUBC(N);
1103 case ISD::ADDE: return visitADDE(N);
1104 case ISD::SUBE: return visitSUBE(N);
1105 case ISD::MUL: return visitMUL(N);
1106 case ISD::SDIV: return visitSDIV(N);
1107 case ISD::UDIV: return visitUDIV(N);
1108 case ISD::SREM: return visitSREM(N);
1109 case ISD::UREM: return visitUREM(N);
1110 case ISD::MULHU: return visitMULHU(N);
1111 case ISD::MULHS: return visitMULHS(N);
1112 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1113 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1114 case ISD::SMULO: return visitSMULO(N);
1115 case ISD::UMULO: return visitUMULO(N);
1116 case ISD::SDIVREM: return visitSDIVREM(N);
1117 case ISD::UDIVREM: return visitUDIVREM(N);
1118 case ISD::AND: return visitAND(N);
1119 case ISD::OR: return visitOR(N);
1120 case ISD::XOR: return visitXOR(N);
1121 case ISD::SHL: return visitSHL(N);
1122 case ISD::SRA: return visitSRA(N);
1123 case ISD::SRL: return visitSRL(N);
1124 case ISD::CTLZ: return visitCTLZ(N);
1125 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1126 case ISD::CTTZ: return visitCTTZ(N);
1127 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1128 case ISD::CTPOP: return visitCTPOP(N);
1129 case ISD::SELECT: return visitSELECT(N);
1130 case ISD::VSELECT: return visitVSELECT(N);
1131 case ISD::SELECT_CC: return visitSELECT_CC(N);
1132 case ISD::SETCC: return visitSETCC(N);
1133 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1134 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1135 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1136 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1137 case ISD::TRUNCATE: return visitTRUNCATE(N);
1138 case ISD::BITCAST: return visitBITCAST(N);
1139 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1140 case ISD::FADD: return visitFADD(N);
1141 case ISD::FSUB: return visitFSUB(N);
1142 case ISD::FMUL: return visitFMUL(N);
1143 case ISD::FMA: return visitFMA(N);
1144 case ISD::FDIV: return visitFDIV(N);
1145 case ISD::FREM: return visitFREM(N);
1146 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1147 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1148 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1149 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1150 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1151 case ISD::FP_ROUND: return visitFP_ROUND(N);
1152 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1153 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1154 case ISD::FNEG: return visitFNEG(N);
1155 case ISD::FABS: return visitFABS(N);
1156 case ISD::FFLOOR: return visitFFLOOR(N);
1157 case ISD::FCEIL: return visitFCEIL(N);
1158 case ISD::FTRUNC: return visitFTRUNC(N);
1159 case ISD::BRCOND: return visitBRCOND(N);
1160 case ISD::BR_CC: return visitBR_CC(N);
1161 case ISD::LOAD: return visitLOAD(N);
1162 case ISD::STORE: return visitSTORE(N);
1163 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1164 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1165 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1166 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1167 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1168 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1173 SDValue DAGCombiner::combine(SDNode *N) {
1174 SDValue RV = visit(N);
1176 // If nothing happened, try a target-specific DAG combine.
1177 if (RV.getNode() == 0) {
1178 assert(N->getOpcode() != ISD::DELETED_NODE &&
1179 "Node was deleted but visit returned NULL!");
1181 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1182 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1184 // Expose the DAG combiner to the target combiner impls.
1185 TargetLowering::DAGCombinerInfo
1186 DagCombineInfo(DAG, Level, false, this);
1188 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1192 // If nothing happened still, try promoting the operation.
1193 if (RV.getNode() == 0) {
1194 switch (N->getOpcode()) {
1202 RV = PromoteIntBinOp(SDValue(N, 0));
1207 RV = PromoteIntShiftOp(SDValue(N, 0));
1209 case ISD::SIGN_EXTEND:
1210 case ISD::ZERO_EXTEND:
1211 case ISD::ANY_EXTEND:
1212 RV = PromoteExtend(SDValue(N, 0));
1215 if (PromoteLoad(SDValue(N, 0)))
1221 // If N is a commutative binary node, try commuting it to enable more
1223 if (RV.getNode() == 0 &&
1224 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1225 N->getNumValues() == 1) {
1226 SDValue N0 = N->getOperand(0);
1227 SDValue N1 = N->getOperand(1);
1229 // Constant operands are canonicalized to RHS.
1230 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1231 SDValue Ops[] = { N1, N0 };
1232 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1235 return SDValue(CSENode, 0);
1242 /// getInputChainForNode - Given a node, return its input chain if it has one,
1243 /// otherwise return a null sd operand.
1244 static SDValue getInputChainForNode(SDNode *N) {
1245 if (unsigned NumOps = N->getNumOperands()) {
1246 if (N->getOperand(0).getValueType() == MVT::Other)
1247 return N->getOperand(0);
1248 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1249 return N->getOperand(NumOps-1);
1250 for (unsigned i = 1; i < NumOps-1; ++i)
1251 if (N->getOperand(i).getValueType() == MVT::Other)
1252 return N->getOperand(i);
1257 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1258 // If N has two operands, where one has an input chain equal to the other,
1259 // the 'other' chain is redundant.
1260 if (N->getNumOperands() == 2) {
1261 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1262 return N->getOperand(0);
1263 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1264 return N->getOperand(1);
1267 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1268 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1269 SmallPtrSet<SDNode*, 16> SeenOps;
1270 bool Changed = false; // If we should replace this token factor.
1272 // Start out with this token factor.
1275 // Iterate through token factors. The TFs grows when new token factors are
1277 for (unsigned i = 0; i < TFs.size(); ++i) {
1278 SDNode *TF = TFs[i];
1280 // Check each of the operands.
1281 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1282 SDValue Op = TF->getOperand(i);
1284 switch (Op.getOpcode()) {
1285 case ISD::EntryToken:
1286 // Entry tokens don't need to be added to the list. They are
1291 case ISD::TokenFactor:
1292 if (Op.hasOneUse() &&
1293 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1294 // Queue up for processing.
1295 TFs.push_back(Op.getNode());
1296 // Clean up in case the token factor is removed.
1297 AddToWorkList(Op.getNode());
1304 // Only add if it isn't already in the list.
1305 if (SeenOps.insert(Op.getNode()))
1316 // If we've change things around then replace token factor.
1319 // The entry token is the only possible outcome.
1320 Result = DAG.getEntryNode();
1322 // New and improved token factor.
1323 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1324 MVT::Other, &Ops[0], Ops.size());
1327 // Don't add users to work list.
1328 return CombineTo(N, Result, false);
1334 /// MERGE_VALUES can always be eliminated.
1335 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1336 WorkListRemover DeadNodes(*this);
1337 // Replacing results may cause a different MERGE_VALUES to suddenly
1338 // be CSE'd with N, and carry its uses with it. Iterate until no
1339 // uses remain, to ensure that the node can be safely deleted.
1340 // First add the users of this node to the work list so that they
1341 // can be tried again once they have new operands.
1342 AddUsersToWorkList(N);
1344 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1345 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1346 } while (!N->use_empty());
1347 removeFromWorkList(N);
1349 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1353 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1354 SelectionDAG &DAG) {
1355 EVT VT = N0.getValueType();
1356 SDValue N00 = N0.getOperand(0);
1357 SDValue N01 = N0.getOperand(1);
1358 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1360 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1361 isa<ConstantSDNode>(N00.getOperand(1))) {
1362 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1363 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1364 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1365 N00.getOperand(0), N01),
1366 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1367 N00.getOperand(1), N01));
1368 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1374 SDValue DAGCombiner::visitADD(SDNode *N) {
1375 SDValue N0 = N->getOperand(0);
1376 SDValue N1 = N->getOperand(1);
1377 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1378 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1379 EVT VT = N0.getValueType();
1382 if (VT.isVector()) {
1383 SDValue FoldedVOp = SimplifyVBinOp(N);
1384 if (FoldedVOp.getNode()) return FoldedVOp;
1386 // fold (add x, 0) -> x, vector edition
1387 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1389 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1393 // fold (add x, undef) -> undef
1394 if (N0.getOpcode() == ISD::UNDEF)
1396 if (N1.getOpcode() == ISD::UNDEF)
1398 // fold (add c1, c2) -> c1+c2
1400 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1401 // canonicalize constant to RHS
1403 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1404 // fold (add x, 0) -> x
1405 if (N1C && N1C->isNullValue())
1407 // fold (add Sym, c) -> Sym+c
1408 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1409 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1410 GA->getOpcode() == ISD::GlobalAddress)
1411 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1413 (uint64_t)N1C->getSExtValue());
1414 // fold ((c1-A)+c2) -> (c1+c2)-A
1415 if (N1C && N0.getOpcode() == ISD::SUB)
1416 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1417 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1418 DAG.getConstant(N1C->getAPIntValue()+
1419 N0C->getAPIntValue(), VT),
1422 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1423 if (RADD.getNode() != 0)
1425 // fold ((0-A) + B) -> B-A
1426 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1427 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1428 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1429 // fold (A + (0-B)) -> A-B
1430 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1431 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1432 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1433 // fold (A+(B-A)) -> B
1434 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1435 return N1.getOperand(0);
1436 // fold ((B-A)+A) -> B
1437 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1438 return N0.getOperand(0);
1439 // fold (A+(B-(A+C))) to (B-C)
1440 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1441 N0 == N1.getOperand(1).getOperand(0))
1442 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1443 N1.getOperand(1).getOperand(1));
1444 // fold (A+(B-(C+A))) to (B-C)
1445 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1446 N0 == N1.getOperand(1).getOperand(1))
1447 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1448 N1.getOperand(1).getOperand(0));
1449 // fold (A+((B-A)+or-C)) to (B+or-C)
1450 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1451 N1.getOperand(0).getOpcode() == ISD::SUB &&
1452 N0 == N1.getOperand(0).getOperand(1))
1453 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1454 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1456 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1457 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1458 SDValue N00 = N0.getOperand(0);
1459 SDValue N01 = N0.getOperand(1);
1460 SDValue N10 = N1.getOperand(0);
1461 SDValue N11 = N1.getOperand(1);
1463 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1464 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1465 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1466 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1469 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1470 return SDValue(N, 0);
1472 // fold (a+b) -> (a|b) iff a and b share no bits.
1473 if (VT.isInteger() && !VT.isVector()) {
1474 APInt LHSZero, LHSOne;
1475 APInt RHSZero, RHSOne;
1476 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1478 if (LHSZero.getBoolValue()) {
1479 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1481 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1482 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1483 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1484 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1488 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1489 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1490 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1491 if (Result.getNode()) return Result;
1493 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1494 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1495 if (Result.getNode()) return Result;
1498 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1499 if (N1.getOpcode() == ISD::SHL &&
1500 N1.getOperand(0).getOpcode() == ISD::SUB)
1501 if (ConstantSDNode *C =
1502 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1503 if (C->getAPIntValue() == 0)
1504 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1505 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1506 N1.getOperand(0).getOperand(1),
1508 if (N0.getOpcode() == ISD::SHL &&
1509 N0.getOperand(0).getOpcode() == ISD::SUB)
1510 if (ConstantSDNode *C =
1511 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1512 if (C->getAPIntValue() == 0)
1513 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1514 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1515 N0.getOperand(0).getOperand(1),
1518 if (N1.getOpcode() == ISD::AND) {
1519 SDValue AndOp0 = N1.getOperand(0);
1520 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1521 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1522 unsigned DestBits = VT.getScalarType().getSizeInBits();
1524 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1525 // and similar xforms where the inner op is either ~0 or 0.
1526 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1527 DebugLoc DL = N->getDebugLoc();
1528 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1532 // add (sext i1), X -> sub X, (zext i1)
1533 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1534 N0.getOperand(0).getValueType() == MVT::i1 &&
1535 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1536 DebugLoc DL = N->getDebugLoc();
1537 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1538 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1544 SDValue DAGCombiner::visitADDC(SDNode *N) {
1545 SDValue N0 = N->getOperand(0);
1546 SDValue N1 = N->getOperand(1);
1547 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549 EVT VT = N0.getValueType();
1551 // If the flag result is dead, turn this into an ADD.
1552 if (!N->hasAnyUseOfValue(1))
1553 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1554 DAG.getNode(ISD::CARRY_FALSE,
1555 N->getDebugLoc(), MVT::Glue));
1557 // canonicalize constant to RHS.
1559 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1561 // fold (addc x, 0) -> x + no carry out
1562 if (N1C && N1C->isNullValue())
1563 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1564 N->getDebugLoc(), MVT::Glue));
1566 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1567 APInt LHSZero, LHSOne;
1568 APInt RHSZero, RHSOne;
1569 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1571 if (LHSZero.getBoolValue()) {
1572 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1574 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1575 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1576 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1577 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1578 DAG.getNode(ISD::CARRY_FALSE,
1579 N->getDebugLoc(), MVT::Glue));
1585 SDValue DAGCombiner::visitADDE(SDNode *N) {
1586 SDValue N0 = N->getOperand(0);
1587 SDValue N1 = N->getOperand(1);
1588 SDValue CarryIn = N->getOperand(2);
1589 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1592 // canonicalize constant to RHS
1594 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1597 // fold (adde x, y, false) -> (addc x, y)
1598 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1599 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1604 // Since it may not be valid to emit a fold to zero for vector initializers
1605 // check if we can before folding.
1606 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1607 SelectionDAG &DAG, bool LegalOperations) {
1608 if (!VT.isVector()) {
1609 return DAG.getConstant(0, VT);
1611 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1612 // Produce a vector of zeros.
1613 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1614 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1615 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1616 &Ops[0], Ops.size());
1621 SDValue DAGCombiner::visitSUB(SDNode *N) {
1622 SDValue N0 = N->getOperand(0);
1623 SDValue N1 = N->getOperand(1);
1624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1626 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1627 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1628 EVT VT = N0.getValueType();
1631 if (VT.isVector()) {
1632 SDValue FoldedVOp = SimplifyVBinOp(N);
1633 if (FoldedVOp.getNode()) return FoldedVOp;
1635 // fold (sub x, 0) -> x, vector edition
1636 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1640 // fold (sub x, x) -> 0
1641 // FIXME: Refactor this and xor and other similar operations together.
1643 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1644 // fold (sub c1, c2) -> c1-c2
1646 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1647 // fold (sub x, c) -> (add x, -c)
1649 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1650 DAG.getConstant(-N1C->getAPIntValue(), VT));
1651 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1652 if (N0C && N0C->isAllOnesValue())
1653 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1654 // fold A-(A-B) -> B
1655 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1656 return N1.getOperand(1);
1657 // fold (A+B)-A -> B
1658 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1659 return N0.getOperand(1);
1660 // fold (A+B)-B -> A
1661 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1662 return N0.getOperand(0);
1663 // fold C2-(A+C1) -> (C2-C1)-A
1664 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1665 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1667 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1670 // fold ((A+(B+or-C))-B) -> A+or-C
1671 if (N0.getOpcode() == ISD::ADD &&
1672 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1673 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1674 N0.getOperand(1).getOperand(0) == N1)
1675 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1676 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1677 // fold ((A+(C+B))-B) -> A+C
1678 if (N0.getOpcode() == ISD::ADD &&
1679 N0.getOperand(1).getOpcode() == ISD::ADD &&
1680 N0.getOperand(1).getOperand(1) == N1)
1681 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1682 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1683 // fold ((A-(B-C))-C) -> A-B
1684 if (N0.getOpcode() == ISD::SUB &&
1685 N0.getOperand(1).getOpcode() == ISD::SUB &&
1686 N0.getOperand(1).getOperand(1) == N1)
1687 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1688 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1690 // If either operand of a sub is undef, the result is undef
1691 if (N0.getOpcode() == ISD::UNDEF)
1693 if (N1.getOpcode() == ISD::UNDEF)
1696 // If the relocation model supports it, consider symbol offsets.
1697 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1698 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1699 // fold (sub Sym, c) -> Sym-c
1700 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1701 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1703 (uint64_t)N1C->getSExtValue());
1704 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1705 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1706 if (GA->getGlobal() == GB->getGlobal())
1707 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1714 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1715 SDValue N0 = N->getOperand(0);
1716 SDValue N1 = N->getOperand(1);
1717 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719 EVT VT = N0.getValueType();
1721 // If the flag result is dead, turn this into an SUB.
1722 if (!N->hasAnyUseOfValue(1))
1723 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1724 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1727 // fold (subc x, x) -> 0 + no borrow
1729 return CombineTo(N, DAG.getConstant(0, VT),
1730 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1733 // fold (subc x, 0) -> x + no borrow
1734 if (N1C && N1C->isNullValue())
1735 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1738 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1739 if (N0C && N0C->isAllOnesValue())
1740 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1741 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1747 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1748 SDValue N0 = N->getOperand(0);
1749 SDValue N1 = N->getOperand(1);
1750 SDValue CarryIn = N->getOperand(2);
1752 // fold (sube x, y, false) -> (subc x, y)
1753 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1754 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1759 SDValue DAGCombiner::visitMUL(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1764 EVT VT = N0.getValueType();
1767 if (VT.isVector()) {
1768 SDValue FoldedVOp = SimplifyVBinOp(N);
1769 if (FoldedVOp.getNode()) return FoldedVOp;
1772 // fold (mul x, undef) -> 0
1773 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1774 return DAG.getConstant(0, VT);
1775 // fold (mul c1, c2) -> c1*c2
1777 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1778 // canonicalize constant to RHS
1780 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1781 // fold (mul x, 0) -> 0
1782 if (N1C && N1C->isNullValue())
1784 // fold (mul x, -1) -> 0-x
1785 if (N1C && N1C->isAllOnesValue())
1786 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1787 DAG.getConstant(0, VT), N0);
1788 // fold (mul x, (1 << c)) -> x << c
1789 if (N1C && N1C->getAPIntValue().isPowerOf2())
1790 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1791 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1792 getShiftAmountTy(N0.getValueType())));
1793 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1794 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1795 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1796 // FIXME: If the input is something that is easily negated (e.g. a
1797 // single-use add), we should put the negate there.
1798 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1799 DAG.getConstant(0, VT),
1800 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1801 DAG.getConstant(Log2Val,
1802 getShiftAmountTy(N0.getValueType()))));
1804 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1805 if (N1C && N0.getOpcode() == ISD::SHL &&
1806 isa<ConstantSDNode>(N0.getOperand(1))) {
1807 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1808 N1, N0.getOperand(1));
1809 AddToWorkList(C3.getNode());
1810 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1811 N0.getOperand(0), C3);
1814 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1817 SDValue Sh(0,0), Y(0,0);
1818 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1819 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1820 N0.getNode()->hasOneUse()) {
1822 } else if (N1.getOpcode() == ISD::SHL &&
1823 isa<ConstantSDNode>(N1.getOperand(1)) &&
1824 N1.getNode()->hasOneUse()) {
1829 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1830 Sh.getOperand(0), Y);
1831 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1832 Mul, Sh.getOperand(1));
1836 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1837 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1838 isa<ConstantSDNode>(N0.getOperand(1)))
1839 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1840 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1841 N0.getOperand(0), N1),
1842 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1843 N0.getOperand(1), N1));
1846 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1847 if (RMUL.getNode() != 0)
1853 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1854 SDValue N0 = N->getOperand(0);
1855 SDValue N1 = N->getOperand(1);
1856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1858 EVT VT = N->getValueType(0);
1861 if (VT.isVector()) {
1862 SDValue FoldedVOp = SimplifyVBinOp(N);
1863 if (FoldedVOp.getNode()) return FoldedVOp;
1866 // fold (sdiv c1, c2) -> c1/c2
1867 if (N0C && N1C && !N1C->isNullValue())
1868 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1869 // fold (sdiv X, 1) -> X
1870 if (N1C && N1C->getAPIntValue() == 1LL)
1872 // fold (sdiv X, -1) -> 0-X
1873 if (N1C && N1C->isAllOnesValue())
1874 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1875 DAG.getConstant(0, VT), N0);
1876 // If we know the sign bits of both operands are zero, strength reduce to a
1877 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1878 if (!VT.isVector()) {
1879 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1880 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1883 // fold (sdiv X, pow2) -> simple ops after legalize
1884 if (N1C && !N1C->isNullValue() &&
1885 (N1C->getAPIntValue().isPowerOf2() ||
1886 (-N1C->getAPIntValue()).isPowerOf2())) {
1887 // If dividing by powers of two is cheap, then don't perform the following
1889 if (TLI.isPow2DivCheap())
1892 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1894 // Splat the sign bit into the register
1895 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1896 DAG.getConstant(VT.getSizeInBits()-1,
1897 getShiftAmountTy(N0.getValueType())));
1898 AddToWorkList(SGN.getNode());
1900 // Add (N0 < 0) ? abs2 - 1 : 0;
1901 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1902 DAG.getConstant(VT.getSizeInBits() - lg2,
1903 getShiftAmountTy(SGN.getValueType())));
1904 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1905 AddToWorkList(SRL.getNode());
1906 AddToWorkList(ADD.getNode()); // Divide by pow2
1907 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1908 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1910 // If we're dividing by a positive value, we're done. Otherwise, we must
1911 // negate the result.
1912 if (N1C->getAPIntValue().isNonNegative())
1915 AddToWorkList(SRA.getNode());
1916 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1917 DAG.getConstant(0, VT), SRA);
1920 // if integer divide is expensive and we satisfy the requirements, emit an
1921 // alternate sequence.
1922 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1923 SDValue Op = BuildSDIV(N);
1924 if (Op.getNode()) return Op;
1928 if (N0.getOpcode() == ISD::UNDEF)
1929 return DAG.getConstant(0, VT);
1930 // X / undef -> undef
1931 if (N1.getOpcode() == ISD::UNDEF)
1937 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942 EVT VT = N->getValueType(0);
1945 if (VT.isVector()) {
1946 SDValue FoldedVOp = SimplifyVBinOp(N);
1947 if (FoldedVOp.getNode()) return FoldedVOp;
1950 // fold (udiv c1, c2) -> c1/c2
1951 if (N0C && N1C && !N1C->isNullValue())
1952 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1953 // fold (udiv x, (1 << c)) -> x >>u c
1954 if (N1C && N1C->getAPIntValue().isPowerOf2())
1955 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1956 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1957 getShiftAmountTy(N0.getValueType())));
1958 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1959 if (N1.getOpcode() == ISD::SHL) {
1960 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1961 if (SHC->getAPIntValue().isPowerOf2()) {
1962 EVT ADDVT = N1.getOperand(1).getValueType();
1963 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1965 DAG.getConstant(SHC->getAPIntValue()
1968 AddToWorkList(Add.getNode());
1969 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1973 // fold (udiv x, c) -> alternate
1974 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1975 SDValue Op = BuildUDIV(N);
1976 if (Op.getNode()) return Op;
1980 if (N0.getOpcode() == ISD::UNDEF)
1981 return DAG.getConstant(0, VT);
1982 // X / undef -> undef
1983 if (N1.getOpcode() == ISD::UNDEF)
1989 SDValue DAGCombiner::visitSREM(SDNode *N) {
1990 SDValue N0 = N->getOperand(0);
1991 SDValue N1 = N->getOperand(1);
1992 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1993 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1994 EVT VT = N->getValueType(0);
1996 // fold (srem c1, c2) -> c1%c2
1997 if (N0C && N1C && !N1C->isNullValue())
1998 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1999 // If we know the sign bits of both operands are zero, strength reduce to a
2000 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2001 if (!VT.isVector()) {
2002 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2003 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
2006 // If X/C can be simplified by the division-by-constant logic, lower
2007 // X%C to the equivalent of X-X/C*C.
2008 if (N1C && !N1C->isNullValue()) {
2009 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
2010 AddToWorkList(Div.getNode());
2011 SDValue OptimizedDiv = combine(Div.getNode());
2012 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2013 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2015 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2016 AddToWorkList(Mul.getNode());
2022 if (N0.getOpcode() == ISD::UNDEF)
2023 return DAG.getConstant(0, VT);
2024 // X % undef -> undef
2025 if (N1.getOpcode() == ISD::UNDEF)
2031 SDValue DAGCombiner::visitUREM(SDNode *N) {
2032 SDValue N0 = N->getOperand(0);
2033 SDValue N1 = N->getOperand(1);
2034 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2036 EVT VT = N->getValueType(0);
2038 // fold (urem c1, c2) -> c1%c2
2039 if (N0C && N1C && !N1C->isNullValue())
2040 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2041 // fold (urem x, pow2) -> (and x, pow2-1)
2042 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2043 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2044 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2045 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2046 if (N1.getOpcode() == ISD::SHL) {
2047 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2048 if (SHC->getAPIntValue().isPowerOf2()) {
2050 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2051 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2053 AddToWorkList(Add.getNode());
2054 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2059 // If X/C can be simplified by the division-by-constant logic, lower
2060 // X%C to the equivalent of X-X/C*C.
2061 if (N1C && !N1C->isNullValue()) {
2062 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2063 AddToWorkList(Div.getNode());
2064 SDValue OptimizedDiv = combine(Div.getNode());
2065 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2066 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2068 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2069 AddToWorkList(Mul.getNode());
2075 if (N0.getOpcode() == ISD::UNDEF)
2076 return DAG.getConstant(0, VT);
2077 // X % undef -> undef
2078 if (N1.getOpcode() == ISD::UNDEF)
2084 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2085 SDValue N0 = N->getOperand(0);
2086 SDValue N1 = N->getOperand(1);
2087 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2088 EVT VT = N->getValueType(0);
2089 DebugLoc DL = N->getDebugLoc();
2091 // fold (mulhs x, 0) -> 0
2092 if (N1C && N1C->isNullValue())
2094 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2095 if (N1C && N1C->getAPIntValue() == 1)
2096 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2097 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2098 getShiftAmountTy(N0.getValueType())));
2099 // fold (mulhs x, undef) -> 0
2100 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2101 return DAG.getConstant(0, VT);
2103 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2105 if (VT.isSimple() && !VT.isVector()) {
2106 MVT Simple = VT.getSimpleVT();
2107 unsigned SimpleSize = Simple.getSizeInBits();
2108 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2109 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2110 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2111 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2112 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2113 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2114 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2115 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2122 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2123 SDValue N0 = N->getOperand(0);
2124 SDValue N1 = N->getOperand(1);
2125 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2126 EVT VT = N->getValueType(0);
2127 DebugLoc DL = N->getDebugLoc();
2129 // fold (mulhu x, 0) -> 0
2130 if (N1C && N1C->isNullValue())
2132 // fold (mulhu x, 1) -> 0
2133 if (N1C && N1C->getAPIntValue() == 1)
2134 return DAG.getConstant(0, N0.getValueType());
2135 // fold (mulhu x, undef) -> 0
2136 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2137 return DAG.getConstant(0, VT);
2139 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2141 if (VT.isSimple() && !VT.isVector()) {
2142 MVT Simple = VT.getSimpleVT();
2143 unsigned SimpleSize = Simple.getSizeInBits();
2144 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2145 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2146 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2147 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2148 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2149 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2150 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2151 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2158 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2159 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2160 /// that are being performed. Return true if a simplification was made.
2162 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2164 // If the high half is not needed, just compute the low half.
2165 bool HiExists = N->hasAnyUseOfValue(1);
2167 (!LegalOperations ||
2168 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2169 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2170 N->op_begin(), N->getNumOperands());
2171 return CombineTo(N, Res, Res);
2174 // If the low half is not needed, just compute the high half.
2175 bool LoExists = N->hasAnyUseOfValue(0);
2177 (!LegalOperations ||
2178 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2179 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2180 N->op_begin(), N->getNumOperands());
2181 return CombineTo(N, Res, Res);
2184 // If both halves are used, return as it is.
2185 if (LoExists && HiExists)
2188 // If the two computed results can be simplified separately, separate them.
2190 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2191 N->op_begin(), N->getNumOperands());
2192 AddToWorkList(Lo.getNode());
2193 SDValue LoOpt = combine(Lo.getNode());
2194 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2195 (!LegalOperations ||
2196 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2197 return CombineTo(N, LoOpt, LoOpt);
2201 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2202 N->op_begin(), N->getNumOperands());
2203 AddToWorkList(Hi.getNode());
2204 SDValue HiOpt = combine(Hi.getNode());
2205 if (HiOpt.getNode() && HiOpt != Hi &&
2206 (!LegalOperations ||
2207 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2208 return CombineTo(N, HiOpt, HiOpt);
2214 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2215 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2216 if (Res.getNode()) return Res;
2218 EVT VT = N->getValueType(0);
2219 DebugLoc DL = N->getDebugLoc();
2221 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2223 if (VT.isSimple() && !VT.isVector()) {
2224 MVT Simple = VT.getSimpleVT();
2225 unsigned SimpleSize = Simple.getSizeInBits();
2226 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2227 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2228 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2229 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2230 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2231 // Compute the high part as N1.
2232 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2233 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2234 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2235 // Compute the low part as N0.
2236 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2237 return CombineTo(N, Lo, Hi);
2244 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2245 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2246 if (Res.getNode()) return Res;
2248 EVT VT = N->getValueType(0);
2249 DebugLoc DL = N->getDebugLoc();
2251 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2253 if (VT.isSimple() && !VT.isVector()) {
2254 MVT Simple = VT.getSimpleVT();
2255 unsigned SimpleSize = Simple.getSizeInBits();
2256 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2257 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2258 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2259 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2260 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2261 // Compute the high part as N1.
2262 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2263 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2264 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2265 // Compute the low part as N0.
2266 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2267 return CombineTo(N, Lo, Hi);
2274 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2275 // (smulo x, 2) -> (saddo x, x)
2276 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2277 if (C2->getAPIntValue() == 2)
2278 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2279 N->getOperand(0), N->getOperand(0));
2284 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2285 // (umulo x, 2) -> (uaddo x, x)
2286 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2287 if (C2->getAPIntValue() == 2)
2288 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2289 N->getOperand(0), N->getOperand(0));
2294 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2295 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2296 if (Res.getNode()) return Res;
2301 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2302 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2303 if (Res.getNode()) return Res;
2308 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2309 /// two operands of the same opcode, try to simplify it.
2310 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2311 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2312 EVT VT = N0.getValueType();
2313 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2315 // Bail early if none of these transforms apply.
2316 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2318 // For each of OP in AND/OR/XOR:
2319 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2320 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2321 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2322 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2324 // do not sink logical op inside of a vector extend, since it may combine
2326 EVT Op0VT = N0.getOperand(0).getValueType();
2327 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2328 N0.getOpcode() == ISD::SIGN_EXTEND ||
2329 // Avoid infinite looping with PromoteIntBinOp.
2330 (N0.getOpcode() == ISD::ANY_EXTEND &&
2331 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2332 (N0.getOpcode() == ISD::TRUNCATE &&
2333 (!TLI.isZExtFree(VT, Op0VT) ||
2334 !TLI.isTruncateFree(Op0VT, VT)) &&
2335 TLI.isTypeLegal(Op0VT))) &&
2337 Op0VT == N1.getOperand(0).getValueType() &&
2338 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2339 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2340 N0.getOperand(0).getValueType(),
2341 N0.getOperand(0), N1.getOperand(0));
2342 AddToWorkList(ORNode.getNode());
2343 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2346 // For each of OP in SHL/SRL/SRA/AND...
2347 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2348 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2349 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2350 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2351 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2352 N0.getOperand(1) == N1.getOperand(1)) {
2353 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2354 N0.getOperand(0).getValueType(),
2355 N0.getOperand(0), N1.getOperand(0));
2356 AddToWorkList(ORNode.getNode());
2357 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2358 ORNode, N0.getOperand(1));
2361 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2362 // Only perform this optimization after type legalization and before
2363 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2364 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2365 // we don't want to undo this promotion.
2366 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2368 if ((N0.getOpcode() == ISD::BITCAST ||
2369 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2370 Level == AfterLegalizeTypes) {
2371 SDValue In0 = N0.getOperand(0);
2372 SDValue In1 = N1.getOperand(0);
2373 EVT In0Ty = In0.getValueType();
2374 EVT In1Ty = In1.getValueType();
2375 DebugLoc DL = N->getDebugLoc();
2376 // If both incoming values are integers, and the original types are the
2378 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2379 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2380 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2381 AddToWorkList(Op.getNode());
2386 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2387 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2388 // If both shuffles use the same mask, and both shuffle within a single
2389 // vector, then it is worthwhile to move the swizzle after the operation.
2390 // The type-legalizer generates this pattern when loading illegal
2391 // vector types from memory. In many cases this allows additional shuffle
2393 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2394 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2395 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2396 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2397 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2399 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2400 "Inputs to shuffles are not the same type");
2402 unsigned NumElts = VT.getVectorNumElements();
2404 // Check that both shuffles use the same mask. The masks are known to be of
2405 // the same length because the result vector type is the same.
2406 bool SameMask = true;
2407 for (unsigned i = 0; i != NumElts; ++i) {
2408 int Idx0 = SVN0->getMaskElt(i);
2409 int Idx1 = SVN1->getMaskElt(i);
2417 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2418 N0.getOperand(0), N1.getOperand(0));
2419 AddToWorkList(Op.getNode());
2420 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2421 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2428 SDValue DAGCombiner::visitAND(SDNode *N) {
2429 SDValue N0 = N->getOperand(0);
2430 SDValue N1 = N->getOperand(1);
2431 SDValue LL, LR, RL, RR, CC0, CC1;
2432 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2433 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2434 EVT VT = N1.getValueType();
2435 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2438 if (VT.isVector()) {
2439 SDValue FoldedVOp = SimplifyVBinOp(N);
2440 if (FoldedVOp.getNode()) return FoldedVOp;
2442 // fold (and x, 0) -> 0, vector edition
2443 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2445 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2448 // fold (and x, -1) -> x, vector edition
2449 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2451 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2455 // fold (and x, undef) -> 0
2456 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2457 return DAG.getConstant(0, VT);
2458 // fold (and c1, c2) -> c1&c2
2460 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2461 // canonicalize constant to RHS
2463 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2464 // fold (and x, -1) -> x
2465 if (N1C && N1C->isAllOnesValue())
2467 // if (and x, c) is known to be zero, return 0
2468 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2469 APInt::getAllOnesValue(BitWidth)))
2470 return DAG.getConstant(0, VT);
2472 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2473 if (RAND.getNode() != 0)
2475 // fold (and (or x, C), D) -> D if (C & D) == D
2476 if (N1C && N0.getOpcode() == ISD::OR)
2477 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2478 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2480 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2481 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2482 SDValue N0Op0 = N0.getOperand(0);
2483 APInt Mask = ~N1C->getAPIntValue();
2484 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2485 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2486 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2487 N0.getValueType(), N0Op0);
2489 // Replace uses of the AND with uses of the Zero extend node.
2492 // We actually want to replace all uses of the any_extend with the
2493 // zero_extend, to avoid duplicating things. This will later cause this
2494 // AND to be folded.
2495 CombineTo(N0.getNode(), Zext);
2496 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2499 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2500 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2501 // already be zero by virtue of the width of the base type of the load.
2503 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2505 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2506 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2507 N0.getOpcode() == ISD::LOAD) {
2508 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2509 N0 : N0.getOperand(0) );
2511 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2512 // This can be a pure constant or a vector splat, in which case we treat the
2513 // vector as a scalar and use the splat value.
2514 APInt Constant = APInt::getNullValue(1);
2515 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2516 Constant = C->getAPIntValue();
2517 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2518 APInt SplatValue, SplatUndef;
2519 unsigned SplatBitSize;
2521 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2522 SplatBitSize, HasAnyUndefs);
2524 // Undef bits can contribute to a possible optimisation if set, so
2526 SplatValue |= SplatUndef;
2528 // The splat value may be something like "0x00FFFFFF", which means 0 for
2529 // the first vector value and FF for the rest, repeating. We need a mask
2530 // that will apply equally to all members of the vector, so AND all the
2531 // lanes of the constant together.
2532 EVT VT = Vector->getValueType(0);
2533 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2535 // If the splat value has been compressed to a bitlength lower
2536 // than the size of the vector lane, we need to re-expand it to
2538 if (BitWidth > SplatBitSize)
2539 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2540 SplatBitSize < BitWidth;
2541 SplatBitSize = SplatBitSize * 2)
2542 SplatValue |= SplatValue.shl(SplatBitSize);
2544 Constant = APInt::getAllOnesValue(BitWidth);
2545 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2546 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2550 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2551 // actually legal and isn't going to get expanded, else this is a false
2553 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2554 Load->getMemoryVT());
2556 // Resize the constant to the same size as the original memory access before
2557 // extension. If it is still the AllOnesValue then this AND is completely
2560 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2563 switch (Load->getExtensionType()) {
2564 default: B = false; break;
2565 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2567 case ISD::NON_EXTLOAD: B = true; break;
2570 if (B && Constant.isAllOnesValue()) {
2571 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2572 // preserve semantics once we get rid of the AND.
2573 SDValue NewLoad(Load, 0);
2574 if (Load->getExtensionType() == ISD::EXTLOAD) {
2575 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2576 Load->getValueType(0), Load->getDebugLoc(),
2577 Load->getChain(), Load->getBasePtr(),
2578 Load->getOffset(), Load->getMemoryVT(),
2579 Load->getMemOperand());
2580 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2581 if (Load->getNumValues() == 3) {
2582 // PRE/POST_INC loads have 3 values.
2583 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2584 NewLoad.getValue(2) };
2585 CombineTo(Load, To, 3, true);
2587 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2591 // Fold the AND away, taking care not to fold to the old load node if we
2593 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2595 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2598 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2599 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2600 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2601 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2603 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2604 LL.getValueType().isInteger()) {
2605 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2606 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2607 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2608 LR.getValueType(), LL, RL);
2609 AddToWorkList(ORNode.getNode());
2610 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2612 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2613 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2614 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2615 LR.getValueType(), LL, RL);
2616 AddToWorkList(ANDNode.getNode());
2617 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2619 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2620 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2621 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2622 LR.getValueType(), LL, RL);
2623 AddToWorkList(ORNode.getNode());
2624 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2627 // canonicalize equivalent to ll == rl
2628 if (LL == RR && LR == RL) {
2629 Op1 = ISD::getSetCCSwappedOperands(Op1);
2632 if (LL == RL && LR == RR) {
2633 bool isInteger = LL.getValueType().isInteger();
2634 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2635 if (Result != ISD::SETCC_INVALID &&
2636 (!LegalOperations ||
2637 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2638 TLI.isOperationLegal(ISD::SETCC,
2639 TLI.getSetCCResultType(N0.getSimpleValueType())))))
2640 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2645 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2646 if (N0.getOpcode() == N1.getOpcode()) {
2647 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2648 if (Tmp.getNode()) return Tmp;
2651 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2652 // fold (and (sra)) -> (and (srl)) when possible.
2653 if (!VT.isVector() &&
2654 SimplifyDemandedBits(SDValue(N, 0)))
2655 return SDValue(N, 0);
2657 // fold (zext_inreg (extload x)) -> (zextload x)
2658 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2659 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2660 EVT MemVT = LN0->getMemoryVT();
2661 // If we zero all the possible extended bits, then we can turn this into
2662 // a zextload if we are running before legalize or the operation is legal.
2663 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2664 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2665 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2666 ((!LegalOperations && !LN0->isVolatile()) ||
2667 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2668 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2669 LN0->getChain(), LN0->getBasePtr(),
2670 LN0->getPointerInfo(), MemVT,
2671 LN0->isVolatile(), LN0->isNonTemporal(),
2672 LN0->getAlignment());
2674 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2675 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2678 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2679 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2681 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2682 EVT MemVT = LN0->getMemoryVT();
2683 // If we zero all the possible extended bits, then we can turn this into
2684 // a zextload if we are running before legalize or the operation is legal.
2685 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2686 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2687 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2688 ((!LegalOperations && !LN0->isVolatile()) ||
2689 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2690 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2692 LN0->getBasePtr(), LN0->getPointerInfo(),
2694 LN0->isVolatile(), LN0->isNonTemporal(),
2695 LN0->getAlignment());
2697 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2698 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2702 // fold (and (load x), 255) -> (zextload x, i8)
2703 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2704 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2705 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2706 (N0.getOpcode() == ISD::ANY_EXTEND &&
2707 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2708 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2709 LoadSDNode *LN0 = HasAnyExt
2710 ? cast<LoadSDNode>(N0.getOperand(0))
2711 : cast<LoadSDNode>(N0);
2712 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2713 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2714 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2715 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2716 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2717 EVT LoadedVT = LN0->getMemoryVT();
2719 if (ExtVT == LoadedVT &&
2720 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2721 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2724 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2725 LN0->getChain(), LN0->getBasePtr(),
2726 LN0->getPointerInfo(),
2727 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2728 LN0->getAlignment());
2730 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2734 // Do not change the width of a volatile load.
2735 // Do not generate loads of non-round integer types since these can
2736 // be expensive (and would be wrong if the type is not byte sized).
2737 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2738 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2739 EVT PtrType = LN0->getOperand(1).getValueType();
2741 unsigned Alignment = LN0->getAlignment();
2742 SDValue NewPtr = LN0->getBasePtr();
2744 // For big endian targets, we need to add an offset to the pointer
2745 // to load the correct bytes. For little endian systems, we merely
2746 // need to read fewer bytes from the same pointer.
2747 if (TLI.isBigEndian()) {
2748 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2749 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2750 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2751 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2752 NewPtr, DAG.getConstant(PtrOff, PtrType));
2753 Alignment = MinAlign(Alignment, PtrOff);
2756 AddToWorkList(NewPtr.getNode());
2758 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2760 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2761 LN0->getChain(), NewPtr,
2762 LN0->getPointerInfo(),
2763 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2766 CombineTo(LN0, Load, Load.getValue(1));
2767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2773 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2774 VT.getSizeInBits() <= 64) {
2775 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2776 APInt ADDC = ADDI->getAPIntValue();
2777 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2778 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2779 // immediate for an add, but it is legal if its top c2 bits are set,
2780 // transform the ADD so the immediate doesn't need to be materialized
2782 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2783 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2784 SRLI->getZExtValue());
2785 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2787 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2789 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2790 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2791 CombineTo(N0.getNode(), NewAdd);
2792 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2803 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2805 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2806 bool DemandHighBits) {
2807 if (!LegalOperations)
2810 EVT VT = N->getValueType(0);
2811 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2813 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2816 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2817 bool LookPassAnd0 = false;
2818 bool LookPassAnd1 = false;
2819 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2821 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2823 if (N0.getOpcode() == ISD::AND) {
2824 if (!N0.getNode()->hasOneUse())
2826 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2827 if (!N01C || N01C->getZExtValue() != 0xFF00)
2829 N0 = N0.getOperand(0);
2830 LookPassAnd0 = true;
2833 if (N1.getOpcode() == ISD::AND) {
2834 if (!N1.getNode()->hasOneUse())
2836 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2837 if (!N11C || N11C->getZExtValue() != 0xFF)
2839 N1 = N1.getOperand(0);
2840 LookPassAnd1 = true;
2843 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2845 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2847 if (!N0.getNode()->hasOneUse() ||
2848 !N1.getNode()->hasOneUse())
2851 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2852 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2855 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2858 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2859 SDValue N00 = N0->getOperand(0);
2860 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2861 if (!N00.getNode()->hasOneUse())
2863 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2864 if (!N001C || N001C->getZExtValue() != 0xFF)
2866 N00 = N00.getOperand(0);
2867 LookPassAnd0 = true;
2870 SDValue N10 = N1->getOperand(0);
2871 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2872 if (!N10.getNode()->hasOneUse())
2874 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2875 if (!N101C || N101C->getZExtValue() != 0xFF00)
2877 N10 = N10.getOperand(0);
2878 LookPassAnd1 = true;
2884 // Make sure everything beyond the low halfword is zero since the SRL 16
2885 // will clear the top bits.
2886 unsigned OpSizeInBits = VT.getSizeInBits();
2887 if (DemandHighBits && OpSizeInBits > 16 &&
2888 (!LookPassAnd0 || !LookPassAnd1) &&
2889 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2892 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2893 if (OpSizeInBits > 16)
2894 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2895 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2899 /// isBSwapHWordElement - Return true if the specified node is an element
2900 /// that makes up a 32-bit packed halfword byteswap. i.e.
2901 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2902 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2903 if (!N.getNode()->hasOneUse())
2906 unsigned Opc = N.getOpcode();
2907 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2910 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2915 switch (N1C->getZExtValue()) {
2918 case 0xFF: Num = 0; break;
2919 case 0xFF00: Num = 1; break;
2920 case 0xFF0000: Num = 2; break;
2921 case 0xFF000000: Num = 3; break;
2924 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2925 SDValue N0 = N.getOperand(0);
2926 if (Opc == ISD::AND) {
2927 if (Num == 0 || Num == 2) {
2929 // (x >> 8) & 0xff0000
2930 if (N0.getOpcode() != ISD::SRL)
2932 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2933 if (!C || C->getZExtValue() != 8)
2936 // (x << 8) & 0xff00
2937 // (x << 8) & 0xff000000
2938 if (N0.getOpcode() != ISD::SHL)
2940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2941 if (!C || C->getZExtValue() != 8)
2944 } else if (Opc == ISD::SHL) {
2946 // (x & 0xff0000) << 8
2947 if (Num != 0 && Num != 2)
2949 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2950 if (!C || C->getZExtValue() != 8)
2952 } else { // Opc == ISD::SRL
2953 // (x & 0xff00) >> 8
2954 // (x & 0xff000000) >> 8
2955 if (Num != 1 && Num != 3)
2957 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2958 if (!C || C->getZExtValue() != 8)
2965 Parts[Num] = N0.getOperand(0).getNode();
2969 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2970 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2971 /// => (rotl (bswap x), 16)
2972 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2973 if (!LegalOperations)
2976 EVT VT = N->getValueType(0);
2979 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2982 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2984 // (or (or (and), (and)), (or (and), (and)))
2985 // (or (or (or (and), (and)), (and)), (and))
2986 if (N0.getOpcode() != ISD::OR)
2988 SDValue N00 = N0.getOperand(0);
2989 SDValue N01 = N0.getOperand(1);
2991 if (N1.getOpcode() == ISD::OR &&
2992 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
2993 // (or (or (and), (and)), (or (and), (and)))
2994 SDValue N000 = N00.getOperand(0);
2995 if (!isBSwapHWordElement(N000, Parts))
2998 SDValue N001 = N00.getOperand(1);
2999 if (!isBSwapHWordElement(N001, Parts))
3001 SDValue N010 = N01.getOperand(0);
3002 if (!isBSwapHWordElement(N010, Parts))
3004 SDValue N011 = N01.getOperand(1);
3005 if (!isBSwapHWordElement(N011, Parts))
3008 // (or (or (or (and), (and)), (and)), (and))
3009 if (!isBSwapHWordElement(N1, Parts))
3011 if (!isBSwapHWordElement(N01, Parts))
3013 if (N00.getOpcode() != ISD::OR)
3015 SDValue N000 = N00.getOperand(0);
3016 if (!isBSwapHWordElement(N000, Parts))
3018 SDValue N001 = N00.getOperand(1);
3019 if (!isBSwapHWordElement(N001, Parts))
3023 // Make sure the parts are all coming from the same node.
3024 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3027 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
3028 SDValue(Parts[0],0));
3030 // Result of the bswap should be rotated by 16. If it's not legal, than
3031 // do (x << 16) | (x >> 16).
3032 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3033 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3034 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3035 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3036 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3037 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3038 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3039 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3042 SDValue DAGCombiner::visitOR(SDNode *N) {
3043 SDValue N0 = N->getOperand(0);
3044 SDValue N1 = N->getOperand(1);
3045 SDValue LL, LR, RL, RR, CC0, CC1;
3046 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3048 EVT VT = N1.getValueType();
3051 if (VT.isVector()) {
3052 SDValue FoldedVOp = SimplifyVBinOp(N);
3053 if (FoldedVOp.getNode()) return FoldedVOp;
3055 // fold (or x, 0) -> x, vector edition
3056 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3058 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3061 // fold (or x, -1) -> -1, vector edition
3062 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3064 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3068 // fold (or x, undef) -> -1
3069 if (!LegalOperations &&
3070 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3071 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3072 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3074 // fold (or c1, c2) -> c1|c2
3076 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3077 // canonicalize constant to RHS
3079 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3080 // fold (or x, 0) -> x
3081 if (N1C && N1C->isNullValue())
3083 // fold (or x, -1) -> -1
3084 if (N1C && N1C->isAllOnesValue())
3086 // fold (or x, c) -> c iff (x & ~c) == 0
3087 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3090 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3091 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3092 if (BSwap.getNode() != 0)
3094 BSwap = MatchBSwapHWordLow(N, N0, N1);
3095 if (BSwap.getNode() != 0)
3099 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3100 if (ROR.getNode() != 0)
3102 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3103 // iff (c1 & c2) == 0.
3104 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3105 isa<ConstantSDNode>(N0.getOperand(1))) {
3106 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3107 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3108 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3109 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3110 N0.getOperand(0), N1),
3111 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3113 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3114 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3115 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3116 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3118 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3119 LL.getValueType().isInteger()) {
3120 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3121 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3122 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3123 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3124 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3125 LR.getValueType(), LL, RL);
3126 AddToWorkList(ORNode.getNode());
3127 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3129 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3130 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3131 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3132 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3133 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3134 LR.getValueType(), LL, RL);
3135 AddToWorkList(ANDNode.getNode());
3136 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3139 // canonicalize equivalent to ll == rl
3140 if (LL == RR && LR == RL) {
3141 Op1 = ISD::getSetCCSwappedOperands(Op1);
3144 if (LL == RL && LR == RR) {
3145 bool isInteger = LL.getValueType().isInteger();
3146 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3147 if (Result != ISD::SETCC_INVALID &&
3148 (!LegalOperations ||
3149 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3150 TLI.isOperationLegal(ISD::SETCC,
3151 TLI.getSetCCResultType(N0.getValueType())))))
3152 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3157 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3158 if (N0.getOpcode() == N1.getOpcode()) {
3159 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3160 if (Tmp.getNode()) return Tmp;
3163 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3164 if (N0.getOpcode() == ISD::AND &&
3165 N1.getOpcode() == ISD::AND &&
3166 N0.getOperand(1).getOpcode() == ISD::Constant &&
3167 N1.getOperand(1).getOpcode() == ISD::Constant &&
3168 // Don't increase # computations.
3169 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3170 // We can only do this xform if we know that bits from X that are set in C2
3171 // but not in C1 are already zero. Likewise for Y.
3172 const APInt &LHSMask =
3173 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3174 const APInt &RHSMask =
3175 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3177 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3178 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3179 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3180 N0.getOperand(0), N1.getOperand(0));
3181 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3182 DAG.getConstant(LHSMask | RHSMask, VT));
3186 // See if this is some rotate idiom.
3187 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3188 return SDValue(Rot, 0);
3190 // Simplify the operands using demanded-bits information.
3191 if (!VT.isVector() &&
3192 SimplifyDemandedBits(SDValue(N, 0)))
3193 return SDValue(N, 0);
3198 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3199 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3200 if (Op.getOpcode() == ISD::AND) {
3201 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3202 Mask = Op.getOperand(1);
3203 Op = Op.getOperand(0);
3209 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3217 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3218 // idioms for rotate, and if the target supports rotation instructions, generate
3220 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3221 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3222 EVT VT = LHS.getValueType();
3223 if (!TLI.isTypeLegal(VT)) return 0;
3225 // The target must have at least one rotate flavor.
3226 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3227 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3228 if (!HasROTL && !HasROTR) return 0;
3230 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3231 SDValue LHSShift; // The shift.
3232 SDValue LHSMask; // AND value if any.
3233 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3234 return 0; // Not part of a rotate.
3236 SDValue RHSShift; // The shift.
3237 SDValue RHSMask; // AND value if any.
3238 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3239 return 0; // Not part of a rotate.
3241 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3242 return 0; // Not shifting the same value.
3244 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3245 return 0; // Shifts must disagree.
3247 // Canonicalize shl to left side in a shl/srl pair.
3248 if (RHSShift.getOpcode() == ISD::SHL) {
3249 std::swap(LHS, RHS);
3250 std::swap(LHSShift, RHSShift);
3251 std::swap(LHSMask , RHSMask );
3254 unsigned OpSizeInBits = VT.getSizeInBits();
3255 SDValue LHSShiftArg = LHSShift.getOperand(0);
3256 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3257 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3259 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3260 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3261 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3262 RHSShiftAmt.getOpcode() == ISD::Constant) {
3263 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3264 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3265 if ((LShVal + RShVal) != OpSizeInBits)
3268 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3269 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3271 // If there is an AND of either shifted operand, apply it to the result.
3272 if (LHSMask.getNode() || RHSMask.getNode()) {
3273 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3275 if (LHSMask.getNode()) {
3276 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3277 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3279 if (RHSMask.getNode()) {
3280 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3281 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3284 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3287 return Rot.getNode();
3290 // If there is a mask here, and we have a variable shift, we can't be sure
3291 // that we're masking out the right stuff.
3292 if (LHSMask.getNode() || RHSMask.getNode())
3295 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3296 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3297 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3298 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3299 if (ConstantSDNode *SUBC =
3300 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3301 if (SUBC->getAPIntValue() == OpSizeInBits) {
3302 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3303 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3308 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3309 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3310 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3311 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3312 if (ConstantSDNode *SUBC =
3313 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3314 if (SUBC->getAPIntValue() == OpSizeInBits) {
3315 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3316 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3321 // Look for sign/zext/any-extended or truncate cases:
3322 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3323 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3324 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3325 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3326 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3327 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3328 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3329 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3330 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3331 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3332 if (RExtOp0.getOpcode() == ISD::SUB &&
3333 RExtOp0.getOperand(1) == LExtOp0) {
3334 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3336 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3337 // (rotr x, (sub 32, y))
3338 if (ConstantSDNode *SUBC =
3339 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3340 if (SUBC->getAPIntValue() == OpSizeInBits) {
3341 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3343 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3346 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3347 RExtOp0 == LExtOp0.getOperand(1)) {
3348 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3350 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3351 // (rotl x, (sub 32, y))
3352 if (ConstantSDNode *SUBC =
3353 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3354 if (SUBC->getAPIntValue() == OpSizeInBits) {
3355 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3357 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3366 SDValue DAGCombiner::visitXOR(SDNode *N) {
3367 SDValue N0 = N->getOperand(0);
3368 SDValue N1 = N->getOperand(1);
3369 SDValue LHS, RHS, CC;
3370 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3371 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3372 EVT VT = N0.getValueType();
3375 if (VT.isVector()) {
3376 SDValue FoldedVOp = SimplifyVBinOp(N);
3377 if (FoldedVOp.getNode()) return FoldedVOp;
3379 // fold (xor x, 0) -> x, vector edition
3380 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3382 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3386 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3387 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3388 return DAG.getConstant(0, VT);
3389 // fold (xor x, undef) -> undef
3390 if (N0.getOpcode() == ISD::UNDEF)
3392 if (N1.getOpcode() == ISD::UNDEF)
3394 // fold (xor c1, c2) -> c1^c2
3396 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3397 // canonicalize constant to RHS
3399 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3400 // fold (xor x, 0) -> x
3401 if (N1C && N1C->isNullValue())
3404 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3405 if (RXOR.getNode() != 0)
3408 // fold !(x cc y) -> (x !cc y)
3409 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3410 bool isInt = LHS.getValueType().isInteger();
3411 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3414 if (!LegalOperations ||
3415 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3416 switch (N0.getOpcode()) {
3418 llvm_unreachable("Unhandled SetCC Equivalent!");
3420 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3421 case ISD::SELECT_CC:
3422 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3423 N0.getOperand(3), NotCC);
3428 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3429 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3430 N0.getNode()->hasOneUse() &&
3431 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3432 SDValue V = N0.getOperand(0);
3433 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3434 DAG.getConstant(1, V.getValueType()));
3435 AddToWorkList(V.getNode());
3436 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3439 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3440 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3441 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3442 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3443 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3444 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3445 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3446 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3447 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3448 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3451 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3452 if (N1C && N1C->isAllOnesValue() &&
3453 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3454 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3455 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3456 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3457 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3458 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3459 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3460 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3463 // fold (xor (and x, y), y) -> (and (not x), y)
3464 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3465 N0->getOperand(1) == N1) {
3466 SDValue X = N0->getOperand(0);
3467 SDValue NotX = DAG.getNOT(X.getDebugLoc(), X, VT);
3468 AddToWorkList(NotX.getNode());
3469 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NotX, N1);
3471 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3472 if (N1C && N0.getOpcode() == ISD::XOR) {
3473 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3474 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3476 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3477 DAG.getConstant(N1C->getAPIntValue() ^
3478 N00C->getAPIntValue(), VT));
3480 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3481 DAG.getConstant(N1C->getAPIntValue() ^
3482 N01C->getAPIntValue(), VT));
3484 // fold (xor x, x) -> 0
3486 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3488 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3489 if (N0.getOpcode() == N1.getOpcode()) {
3490 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3491 if (Tmp.getNode()) return Tmp;
3494 // Simplify the expression using non-local knowledge.
3495 if (!VT.isVector() &&
3496 SimplifyDemandedBits(SDValue(N, 0)))
3497 return SDValue(N, 0);
3502 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3503 /// the shift amount is a constant.
3504 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3505 SDNode *LHS = N->getOperand(0).getNode();
3506 if (!LHS->hasOneUse()) return SDValue();
3508 // We want to pull some binops through shifts, so that we have (and (shift))
3509 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3510 // thing happens with address calculations, so it's important to canonicalize
3512 bool HighBitSet = false; // Can we transform this if the high bit is set?
3514 switch (LHS->getOpcode()) {
3515 default: return SDValue();
3518 HighBitSet = false; // We can only transform sra if the high bit is clear.
3521 HighBitSet = true; // We can only transform sra if the high bit is set.
3524 if (N->getOpcode() != ISD::SHL)
3525 return SDValue(); // only shl(add) not sr[al](add).
3526 HighBitSet = false; // We can only transform sra if the high bit is clear.
3530 // We require the RHS of the binop to be a constant as well.
3531 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3532 if (!BinOpCst) return SDValue();
3534 // FIXME: disable this unless the input to the binop is a shift by a constant.
3535 // If it is not a shift, it pessimizes some common cases like:
3537 // void foo(int *X, int i) { X[i & 1235] = 1; }
3538 // int bar(int *X, int i) { return X[i & 255]; }
3539 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3540 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3541 BinOpLHSVal->getOpcode() != ISD::SRA &&
3542 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3543 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3546 EVT VT = N->getValueType(0);
3548 // If this is a signed shift right, and the high bit is modified by the
3549 // logical operation, do not perform the transformation. The highBitSet
3550 // boolean indicates the value of the high bit of the constant which would
3551 // cause it to be modified for this operation.
3552 if (N->getOpcode() == ISD::SRA) {
3553 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3554 if (BinOpRHSSignSet != HighBitSet)
3558 // Fold the constants, shifting the binop RHS by the shift amount.
3559 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3561 LHS->getOperand(1), N->getOperand(1));
3563 // Create the new shift.
3564 SDValue NewShift = DAG.getNode(N->getOpcode(),
3565 LHS->getOperand(0).getDebugLoc(),
3566 VT, LHS->getOperand(0), N->getOperand(1));
3568 // Create the new binop.
3569 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3572 SDValue DAGCombiner::visitSHL(SDNode *N) {
3573 SDValue N0 = N->getOperand(0);
3574 SDValue N1 = N->getOperand(1);
3575 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3576 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3577 EVT VT = N0.getValueType();
3578 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3580 // fold (shl c1, c2) -> c1<<c2
3582 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3583 // fold (shl 0, x) -> 0
3584 if (N0C && N0C->isNullValue())
3586 // fold (shl x, c >= size(x)) -> undef
3587 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3588 return DAG.getUNDEF(VT);
3589 // fold (shl x, 0) -> x
3590 if (N1C && N1C->isNullValue())
3592 // fold (shl undef, x) -> 0
3593 if (N0.getOpcode() == ISD::UNDEF)
3594 return DAG.getConstant(0, VT);
3595 // if (shl x, c) is known to be zero, return 0
3596 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3597 APInt::getAllOnesValue(OpSizeInBits)))
3598 return DAG.getConstant(0, VT);
3599 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3600 if (N1.getOpcode() == ISD::TRUNCATE &&
3601 N1.getOperand(0).getOpcode() == ISD::AND &&
3602 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3603 SDValue N101 = N1.getOperand(0).getOperand(1);
3604 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3605 EVT TruncVT = N1.getValueType();
3606 SDValue N100 = N1.getOperand(0).getOperand(0);
3607 APInt TruncC = N101C->getAPIntValue();
3608 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3609 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3610 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3611 DAG.getNode(ISD::TRUNCATE,
3614 DAG.getConstant(TruncC, TruncVT)));
3618 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3619 return SDValue(N, 0);
3621 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3622 if (N1C && N0.getOpcode() == ISD::SHL &&
3623 N0.getOperand(1).getOpcode() == ISD::Constant) {
3624 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3625 uint64_t c2 = N1C->getZExtValue();
3626 if (c1 + c2 >= OpSizeInBits)
3627 return DAG.getConstant(0, VT);
3628 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3629 DAG.getConstant(c1 + c2, N1.getValueType()));
3632 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3633 // For this to be valid, the second form must not preserve any of the bits
3634 // that are shifted out by the inner shift in the first form. This means
3635 // the outer shift size must be >= the number of bits added by the ext.
3636 // As a corollary, we don't care what kind of ext it is.
3637 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3638 N0.getOpcode() == ISD::ANY_EXTEND ||
3639 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3640 N0.getOperand(0).getOpcode() == ISD::SHL &&
3641 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3643 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3644 uint64_t c2 = N1C->getZExtValue();
3645 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3646 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3647 if (c2 >= OpSizeInBits - InnerShiftSize) {
3648 if (c1 + c2 >= OpSizeInBits)
3649 return DAG.getConstant(0, VT);
3650 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3651 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3652 N0.getOperand(0)->getOperand(0)),
3653 DAG.getConstant(c1 + c2, N1.getValueType()));
3657 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3658 // (and (srl x, (sub c1, c2), MASK)
3659 // Only fold this if the inner shift has no other uses -- if it does, folding
3660 // this will increase the total number of instructions.
3661 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3662 N0.getOperand(1).getOpcode() == ISD::Constant) {
3663 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3664 if (c1 < VT.getSizeInBits()) {
3665 uint64_t c2 = N1C->getZExtValue();
3666 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3667 VT.getSizeInBits() - c1);
3670 Mask = Mask.shl(c2-c1);
3671 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3672 DAG.getConstant(c2-c1, N1.getValueType()));
3674 Mask = Mask.lshr(c1-c2);
3675 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3676 DAG.getConstant(c1-c2, N1.getValueType()));
3678 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3679 DAG.getConstant(Mask, VT));
3682 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3683 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3684 SDValue HiBitsMask =
3685 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3686 VT.getSizeInBits() -
3687 N1C->getZExtValue()),
3689 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3694 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3695 if (NewSHL.getNode())
3702 SDValue DAGCombiner::visitSRA(SDNode *N) {
3703 SDValue N0 = N->getOperand(0);
3704 SDValue N1 = N->getOperand(1);
3705 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3706 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3707 EVT VT = N0.getValueType();
3708 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3710 // fold (sra c1, c2) -> (sra c1, c2)
3712 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3713 // fold (sra 0, x) -> 0
3714 if (N0C && N0C->isNullValue())
3716 // fold (sra -1, x) -> -1
3717 if (N0C && N0C->isAllOnesValue())
3719 // fold (sra x, (setge c, size(x))) -> undef
3720 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3721 return DAG.getUNDEF(VT);
3722 // fold (sra x, 0) -> x
3723 if (N1C && N1C->isNullValue())
3725 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3727 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3728 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3729 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3731 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3732 ExtVT, VT.getVectorNumElements());
3733 if ((!LegalOperations ||
3734 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3735 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3736 N0.getOperand(0), DAG.getValueType(ExtVT));
3739 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3740 if (N1C && N0.getOpcode() == ISD::SRA) {
3741 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3742 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3743 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3744 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3745 DAG.getConstant(Sum, N1C->getValueType(0)));
3749 // fold (sra (shl X, m), (sub result_size, n))
3750 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3751 // result_size - n != m.
3752 // If truncate is free for the target sext(shl) is likely to result in better
3754 if (N0.getOpcode() == ISD::SHL) {
3755 // Get the two constanst of the shifts, CN0 = m, CN = n.
3756 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3758 // Determine what the truncate's result bitsize and type would be.
3760 EVT::getIntegerVT(*DAG.getContext(),
3761 OpSizeInBits - N1C->getZExtValue());
3762 // Determine the residual right-shift amount.
3763 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3765 // If the shift is not a no-op (in which case this should be just a sign
3766 // extend already), the truncated to type is legal, sign_extend is legal
3767 // on that type, and the truncate to that type is both legal and free,
3768 // perform the transform.
3769 if ((ShiftAmt > 0) &&
3770 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3771 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3772 TLI.isTruncateFree(VT, TruncVT)) {
3774 SDValue Amt = DAG.getConstant(ShiftAmt,
3775 getShiftAmountTy(N0.getOperand(0).getValueType()));
3776 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3777 N0.getOperand(0), Amt);
3778 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3780 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3781 N->getValueType(0), Trunc);
3786 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3787 if (N1.getOpcode() == ISD::TRUNCATE &&
3788 N1.getOperand(0).getOpcode() == ISD::AND &&
3789 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3790 SDValue N101 = N1.getOperand(0).getOperand(1);
3791 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3792 EVT TruncVT = N1.getValueType();
3793 SDValue N100 = N1.getOperand(0).getOperand(0);
3794 APInt TruncC = N101C->getAPIntValue();
3795 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3796 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3797 DAG.getNode(ISD::AND, N->getDebugLoc(),
3799 DAG.getNode(ISD::TRUNCATE,
3802 DAG.getConstant(TruncC, TruncVT)));
3806 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3807 // if c1 is equal to the number of bits the trunc removes
3808 if (N0.getOpcode() == ISD::TRUNCATE &&
3809 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3810 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3811 N0.getOperand(0).hasOneUse() &&
3812 N0.getOperand(0).getOperand(1).hasOneUse() &&
3813 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3814 EVT LargeVT = N0.getOperand(0).getValueType();
3815 ConstantSDNode *LargeShiftAmt =
3816 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3818 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3819 LargeShiftAmt->getZExtValue()) {
3821 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3822 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3823 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3824 N0.getOperand(0).getOperand(0), Amt);
3825 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3829 // Simplify, based on bits shifted out of the LHS.
3830 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3831 return SDValue(N, 0);
3834 // If the sign bit is known to be zero, switch this to a SRL.
3835 if (DAG.SignBitIsZero(N0))
3836 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3839 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3840 if (NewSRA.getNode())
3847 SDValue DAGCombiner::visitSRL(SDNode *N) {
3848 SDValue N0 = N->getOperand(0);
3849 SDValue N1 = N->getOperand(1);
3850 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3851 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3852 EVT VT = N0.getValueType();
3853 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3855 // fold (srl c1, c2) -> c1 >>u c2
3857 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3858 // fold (srl 0, x) -> 0
3859 if (N0C && N0C->isNullValue())
3861 // fold (srl x, c >= size(x)) -> undef
3862 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3863 return DAG.getUNDEF(VT);
3864 // fold (srl x, 0) -> x
3865 if (N1C && N1C->isNullValue())
3867 // if (srl x, c) is known to be zero, return 0
3868 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3869 APInt::getAllOnesValue(OpSizeInBits)))
3870 return DAG.getConstant(0, VT);
3872 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3873 if (N1C && N0.getOpcode() == ISD::SRL &&
3874 N0.getOperand(1).getOpcode() == ISD::Constant) {
3875 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3876 uint64_t c2 = N1C->getZExtValue();
3877 if (c1 + c2 >= OpSizeInBits)
3878 return DAG.getConstant(0, VT);
3879 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3880 DAG.getConstant(c1 + c2, N1.getValueType()));
3883 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3884 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3885 N0.getOperand(0).getOpcode() == ISD::SRL &&
3886 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3888 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3889 uint64_t c2 = N1C->getZExtValue();
3890 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3891 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3892 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3893 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3894 if (c1 + OpSizeInBits == InnerShiftSize) {
3895 if (c1 + c2 >= InnerShiftSize)
3896 return DAG.getConstant(0, VT);
3897 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3898 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3899 N0.getOperand(0)->getOperand(0),
3900 DAG.getConstant(c1 + c2, ShiftCountVT)));
3904 // fold (srl (shl x, c), c) -> (and x, cst2)
3905 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3906 N0.getValueSizeInBits() <= 64) {
3907 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3908 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3909 DAG.getConstant(~0ULL >> ShAmt, VT));
3913 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3914 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3915 // Shifting in all undef bits?
3916 EVT SmallVT = N0.getOperand(0).getValueType();
3917 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3918 return DAG.getUNDEF(VT);
3920 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3921 uint64_t ShiftAmt = N1C->getZExtValue();
3922 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3924 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3925 AddToWorkList(SmallShift.getNode());
3926 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3930 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3931 // bit, which is unmodified by sra.
3932 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3933 if (N0.getOpcode() == ISD::SRA)
3934 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3937 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3938 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3939 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3940 APInt KnownZero, KnownOne;
3941 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3943 // If any of the input bits are KnownOne, then the input couldn't be all
3944 // zeros, thus the result of the srl will always be zero.
3945 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3947 // If all of the bits input the to ctlz node are known to be zero, then
3948 // the result of the ctlz is "32" and the result of the shift is one.
3949 APInt UnknownBits = ~KnownZero;
3950 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3952 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3953 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3954 // Okay, we know that only that the single bit specified by UnknownBits
3955 // could be set on input to the CTLZ node. If this bit is set, the SRL
3956 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3957 // to an SRL/XOR pair, which is likely to simplify more.
3958 unsigned ShAmt = UnknownBits.countTrailingZeros();
3959 SDValue Op = N0.getOperand(0);
3962 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3963 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3964 AddToWorkList(Op.getNode());
3967 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3968 Op, DAG.getConstant(1, VT));
3972 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3973 if (N1.getOpcode() == ISD::TRUNCATE &&
3974 N1.getOperand(0).getOpcode() == ISD::AND &&
3975 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3976 SDValue N101 = N1.getOperand(0).getOperand(1);
3977 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3978 EVT TruncVT = N1.getValueType();
3979 SDValue N100 = N1.getOperand(0).getOperand(0);
3980 APInt TruncC = N101C->getAPIntValue();
3981 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3982 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3983 DAG.getNode(ISD::AND, N->getDebugLoc(),
3985 DAG.getNode(ISD::TRUNCATE,
3988 DAG.getConstant(TruncC, TruncVT)));
3992 // fold operands of srl based on knowledge that the low bits are not
3994 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3995 return SDValue(N, 0);
3998 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3999 if (NewSRL.getNode())
4003 // Attempt to convert a srl of a load into a narrower zero-extending load.
4004 SDValue NarrowLoad = ReduceLoadWidth(N);
4005 if (NarrowLoad.getNode())
4008 // Here is a common situation. We want to optimize:
4011 // %b = and i32 %a, 2
4012 // %c = srl i32 %b, 1
4013 // brcond i32 %c ...
4019 // %c = setcc eq %b, 0
4022 // However when after the source operand of SRL is optimized into AND, the SRL
4023 // itself may not be optimized further. Look for it and add the BRCOND into
4025 if (N->hasOneUse()) {
4026 SDNode *Use = *N->use_begin();
4027 if (Use->getOpcode() == ISD::BRCOND)
4029 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4030 // Also look pass the truncate.
4031 Use = *Use->use_begin();
4032 if (Use->getOpcode() == ISD::BRCOND)
4040 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4041 SDValue N0 = N->getOperand(0);
4042 EVT VT = N->getValueType(0);
4044 // fold (ctlz c1) -> c2
4045 if (isa<ConstantSDNode>(N0))
4046 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
4050 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4051 SDValue N0 = N->getOperand(0);
4052 EVT VT = N->getValueType(0);
4054 // fold (ctlz_zero_undef c1) -> c2
4055 if (isa<ConstantSDNode>(N0))
4056 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4060 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4061 SDValue N0 = N->getOperand(0);
4062 EVT VT = N->getValueType(0);
4064 // fold (cttz c1) -> c2
4065 if (isa<ConstantSDNode>(N0))
4066 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4070 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4071 SDValue N0 = N->getOperand(0);
4072 EVT VT = N->getValueType(0);
4074 // fold (cttz_zero_undef c1) -> c2
4075 if (isa<ConstantSDNode>(N0))
4076 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4080 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4081 SDValue N0 = N->getOperand(0);
4082 EVT VT = N->getValueType(0);
4084 // fold (ctpop c1) -> c2
4085 if (isa<ConstantSDNode>(N0))
4086 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4090 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4091 SDValue N0 = N->getOperand(0);
4092 SDValue N1 = N->getOperand(1);
4093 SDValue N2 = N->getOperand(2);
4094 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4095 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4096 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4097 EVT VT = N->getValueType(0);
4098 EVT VT0 = N0.getValueType();
4100 // fold (select C, X, X) -> X
4103 // fold (select true, X, Y) -> X
4104 if (N0C && !N0C->isNullValue())
4106 // fold (select false, X, Y) -> Y
4107 if (N0C && N0C->isNullValue())
4109 // fold (select C, 1, X) -> (or C, X)
4110 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4111 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4112 // fold (select C, 0, 1) -> (xor C, 1)
4113 if (VT.isInteger() &&
4116 TLI.getBooleanContents(false) ==
4117 TargetLowering::ZeroOrOneBooleanContent)) &&
4118 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4121 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4122 N0, DAG.getConstant(1, VT0));
4123 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4124 N0, DAG.getConstant(1, VT0));
4125 AddToWorkList(XORNode.getNode());
4127 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4128 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4130 // fold (select C, 0, X) -> (and (not C), X)
4131 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4132 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4133 AddToWorkList(NOTNode.getNode());
4134 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4136 // fold (select C, X, 1) -> (or (not C), X)
4137 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4138 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4139 AddToWorkList(NOTNode.getNode());
4140 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4142 // fold (select C, X, 0) -> (and C, X)
4143 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4144 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4145 // fold (select X, X, Y) -> (or X, Y)
4146 // fold (select X, 1, Y) -> (or X, Y)
4147 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4148 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4149 // fold (select X, Y, X) -> (and X, Y)
4150 // fold (select X, Y, 0) -> (and X, Y)
4151 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4152 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4154 // If we can fold this based on the true/false value, do so.
4155 if (SimplifySelectOps(N, N1, N2))
4156 return SDValue(N, 0); // Don't revisit N.
4158 // fold selects based on a setcc into other things, such as min/max/abs
4159 if (N0.getOpcode() == ISD::SETCC) {
4161 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4162 // having to say they don't support SELECT_CC on every type the DAG knows
4163 // about, since there is no way to mark an opcode illegal at all value types
4164 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4165 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4166 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4167 N0.getOperand(0), N0.getOperand(1),
4168 N1, N2, N0.getOperand(2));
4169 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4175 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4176 SDValue N0 = N->getOperand(0);
4177 SDValue N1 = N->getOperand(1);
4178 SDValue N2 = N->getOperand(2);
4179 DebugLoc DL = N->getDebugLoc();
4181 // Canonicalize integer abs.
4182 // vselect (setg[te] X, 0), X, -X ->
4183 // vselect (setgt X, -1), X, -X ->
4184 // vselect (setl[te] X, 0), -X, X ->
4185 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4186 if (N0.getOpcode() == ISD::SETCC) {
4187 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4188 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4190 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4192 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4193 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4194 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4195 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4196 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4197 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4198 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4201 EVT VT = LHS.getValueType();
4202 SDValue Shift = DAG.getNode(
4203 ISD::SRA, DL, VT, LHS,
4204 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4205 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4206 AddToWorkList(Shift.getNode());
4207 AddToWorkList(Add.getNode());
4208 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4215 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4216 SDValue N0 = N->getOperand(0);
4217 SDValue N1 = N->getOperand(1);
4218 SDValue N2 = N->getOperand(2);
4219 SDValue N3 = N->getOperand(3);
4220 SDValue N4 = N->getOperand(4);
4221 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4223 // fold select_cc lhs, rhs, x, x, cc -> x
4227 // Determine if the condition we're dealing with is constant
4228 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4229 N0, N1, CC, N->getDebugLoc(), false);
4230 if (SCC.getNode()) AddToWorkList(SCC.getNode());
4232 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4233 if (!SCCC->isNullValue())
4234 return N2; // cond always true -> true val
4236 return N3; // cond always false -> false val
4239 // Fold to a simpler select_cc
4240 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4241 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4242 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4245 // If we can fold this based on the true/false value, do so.
4246 if (SimplifySelectOps(N, N2, N3))
4247 return SDValue(N, 0); // Don't revisit N.
4249 // fold select_cc into other things, such as min/max/abs
4250 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4253 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4254 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4255 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4259 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4260 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4261 // transformation. Returns true if extension are possible and the above
4262 // mentioned transformation is profitable.
4263 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4265 SmallVector<SDNode*, 4> &ExtendNodes,
4266 const TargetLowering &TLI) {
4267 bool HasCopyToRegUses = false;
4268 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4269 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4270 UE = N0.getNode()->use_end();
4275 if (UI.getUse().getResNo() != N0.getResNo())
4277 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4278 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4279 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4280 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4281 // Sign bits will be lost after a zext.
4284 for (unsigned i = 0; i != 2; ++i) {
4285 SDValue UseOp = User->getOperand(i);
4288 if (!isa<ConstantSDNode>(UseOp))
4293 ExtendNodes.push_back(User);
4296 // If truncates aren't free and there are users we can't
4297 // extend, it isn't worthwhile.
4300 // Remember if this value is live-out.
4301 if (User->getOpcode() == ISD::CopyToReg)
4302 HasCopyToRegUses = true;
4305 if (HasCopyToRegUses) {
4306 bool BothLiveOut = false;
4307 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4309 SDUse &Use = UI.getUse();
4310 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4316 // Both unextended and extended values are live out. There had better be
4317 // a good reason for the transformation.
4318 return ExtendNodes.size();
4323 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4324 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4325 ISD::NodeType ExtType) {
4326 // Extend SetCC uses if necessary.
4327 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4328 SDNode *SetCC = SetCCs[i];
4329 SmallVector<SDValue, 4> Ops;
4331 for (unsigned j = 0; j != 2; ++j) {
4332 SDValue SOp = SetCC->getOperand(j);
4334 Ops.push_back(ExtLoad);
4336 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4339 Ops.push_back(SetCC->getOperand(2));
4340 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4341 &Ops[0], Ops.size()));
4345 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4346 SDValue N0 = N->getOperand(0);
4347 EVT VT = N->getValueType(0);
4349 // fold (sext c1) -> c1
4350 if (isa<ConstantSDNode>(N0))
4351 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4353 // fold (sext (sext x)) -> (sext x)
4354 // fold (sext (aext x)) -> (sext x)
4355 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4356 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4359 if (N0.getOpcode() == ISD::TRUNCATE) {
4360 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4361 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4362 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4363 if (NarrowLoad.getNode()) {
4364 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4365 if (NarrowLoad.getNode() != N0.getNode()) {
4366 CombineTo(N0.getNode(), NarrowLoad);
4367 // CombineTo deleted the truncate, if needed, but not what's under it.
4370 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4373 // See if the value being truncated is already sign extended. If so, just
4374 // eliminate the trunc/sext pair.
4375 SDValue Op = N0.getOperand(0);
4376 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4377 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4378 unsigned DestBits = VT.getScalarType().getSizeInBits();
4379 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4381 if (OpBits == DestBits) {
4382 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4383 // bits, it is already ready.
4384 if (NumSignBits > DestBits-MidBits)
4386 } else if (OpBits < DestBits) {
4387 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4388 // bits, just sext from i32.
4389 if (NumSignBits > OpBits-MidBits)
4390 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4392 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4393 // bits, just truncate to i32.
4394 if (NumSignBits > OpBits-MidBits)
4395 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4398 // fold (sext (truncate x)) -> (sextinreg x).
4399 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4400 N0.getValueType())) {
4401 if (OpBits < DestBits)
4402 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4403 else if (OpBits > DestBits)
4404 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4405 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4406 DAG.getValueType(N0.getValueType()));
4410 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4411 // None of the supported targets knows how to perform load and sign extend
4412 // on vectors in one instruction. We only perform this transformation on
4414 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4415 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4416 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4417 bool DoXform = true;
4418 SmallVector<SDNode*, 4> SetCCs;
4419 if (!N0.hasOneUse())
4420 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4422 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4423 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4425 LN0->getBasePtr(), LN0->getPointerInfo(),
4427 LN0->isVolatile(), LN0->isNonTemporal(),
4428 LN0->getAlignment());
4429 CombineTo(N, ExtLoad);
4430 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4431 N0.getValueType(), ExtLoad);
4432 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4433 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4439 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4440 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4441 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4442 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4443 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4444 EVT MemVT = LN0->getMemoryVT();
4445 if ((!LegalOperations && !LN0->isVolatile()) ||
4446 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4447 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4449 LN0->getBasePtr(), LN0->getPointerInfo(),
4451 LN0->isVolatile(), LN0->isNonTemporal(),
4452 LN0->getAlignment());
4453 CombineTo(N, ExtLoad);
4454 CombineTo(N0.getNode(),
4455 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4456 N0.getValueType(), ExtLoad),
4457 ExtLoad.getValue(1));
4458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4462 // fold (sext (and/or/xor (load x), cst)) ->
4463 // (and/or/xor (sextload x), (sext cst))
4464 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4465 N0.getOpcode() == ISD::XOR) &&
4466 isa<LoadSDNode>(N0.getOperand(0)) &&
4467 N0.getOperand(1).getOpcode() == ISD::Constant &&
4468 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4469 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4470 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4471 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4472 bool DoXform = true;
4473 SmallVector<SDNode*, 4> SetCCs;
4474 if (!N0.hasOneUse())
4475 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4478 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4479 LN0->getChain(), LN0->getBasePtr(),
4480 LN0->getPointerInfo(),
4483 LN0->isNonTemporal(),
4484 LN0->getAlignment());
4485 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4486 Mask = Mask.sext(VT.getSizeInBits());
4487 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4488 ExtLoad, DAG.getConstant(Mask, VT));
4489 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4490 N0.getOperand(0).getDebugLoc(),
4491 N0.getOperand(0).getValueType(), ExtLoad);
4493 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4494 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4496 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4501 if (N0.getOpcode() == ISD::SETCC) {
4502 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4503 // Only do this before legalize for now.
4504 if (VT.isVector() && !LegalOperations &&
4505 TLI.getBooleanContents(true) ==
4506 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4507 EVT N0VT = N0.getOperand(0).getValueType();
4508 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4509 // of the same size as the compared operands. Only optimize sext(setcc())
4510 // if this is the case.
4511 EVT SVT = TLI.getSetCCResultType(N0VT);
4513 // We know that the # elements of the results is the same as the
4514 // # elements of the compare (and the # elements of the compare result
4515 // for that matter). Check to see that they are the same size. If so,
4516 // we know that the element size of the sext'd result matches the
4517 // element size of the compare operands.
4518 if (VT.getSizeInBits() == SVT.getSizeInBits())
4519 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4521 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4522 // If the desired elements are smaller or larger than the source
4523 // elements we can use a matching integer vector type and then
4524 // truncate/sign extend
4525 EVT MatchingElementType =
4526 EVT::getIntegerVT(*DAG.getContext(),
4527 N0VT.getScalarType().getSizeInBits());
4528 EVT MatchingVectorType =
4529 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4530 N0VT.getVectorNumElements());
4532 if (SVT == MatchingVectorType) {
4533 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4534 N0.getOperand(0), N0.getOperand(1),
4535 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4536 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4540 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4541 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4543 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4545 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4546 NegOne, DAG.getConstant(0, VT),
4547 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4548 if (SCC.getNode()) return SCC;
4549 if (!VT.isVector() && (!LegalOperations ||
4550 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))))
4551 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4552 DAG.getSetCC(N->getDebugLoc(),
4553 TLI.getSetCCResultType(VT),
4554 N0.getOperand(0), N0.getOperand(1),
4555 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4556 NegOne, DAG.getConstant(0, VT));
4559 // fold (sext x) -> (zext x) if the sign bit is known zero.
4560 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4561 DAG.SignBitIsZero(N0))
4562 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4567 // isTruncateOf - If N is a truncate of some other value, return true, record
4568 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4569 // This function computes KnownZero to avoid a duplicated call to
4570 // ComputeMaskedBits in the caller.
4571 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4574 if (N->getOpcode() == ISD::TRUNCATE) {
4575 Op = N->getOperand(0);
4576 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4580 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4581 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4584 SDValue Op0 = N->getOperand(0);
4585 SDValue Op1 = N->getOperand(1);
4586 assert(Op0.getValueType() == Op1.getValueType());
4588 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4589 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4590 if (COp0 && COp0->isNullValue())
4592 else if (COp1 && COp1->isNullValue())
4597 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4599 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4605 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4606 SDValue N0 = N->getOperand(0);
4607 EVT VT = N->getValueType(0);
4609 // fold (zext c1) -> c1
4610 if (isa<ConstantSDNode>(N0))
4611 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4612 // fold (zext (zext x)) -> (zext x)
4613 // fold (zext (aext x)) -> (zext x)
4614 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4615 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4618 // fold (zext (truncate x)) -> (zext x) or
4619 // (zext (truncate x)) -> (truncate x)
4620 // This is valid when the truncated bits of x are already zero.
4621 // FIXME: We should extend this to work for vectors too.
4624 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4625 APInt TruncatedBits =
4626 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4627 APInt(Op.getValueSizeInBits(), 0) :
4628 APInt::getBitsSet(Op.getValueSizeInBits(),
4629 N0.getValueSizeInBits(),
4630 std::min(Op.getValueSizeInBits(),
4631 VT.getSizeInBits()));
4632 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4633 if (VT.bitsGT(Op.getValueType()))
4634 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4635 if (VT.bitsLT(Op.getValueType()))
4636 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4642 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4643 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4644 if (N0.getOpcode() == ISD::TRUNCATE) {
4645 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4646 if (NarrowLoad.getNode()) {
4647 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4648 if (NarrowLoad.getNode() != N0.getNode()) {
4649 CombineTo(N0.getNode(), NarrowLoad);
4650 // CombineTo deleted the truncate, if needed, but not what's under it.
4653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4657 // fold (zext (truncate x)) -> (and x, mask)
4658 if (N0.getOpcode() == ISD::TRUNCATE &&
4659 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4661 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4662 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4663 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4664 if (NarrowLoad.getNode()) {
4665 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4666 if (NarrowLoad.getNode() != N0.getNode()) {
4667 CombineTo(N0.getNode(), NarrowLoad);
4668 // CombineTo deleted the truncate, if needed, but not what's under it.
4671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4674 SDValue Op = N0.getOperand(0);
4675 if (Op.getValueType().bitsLT(VT)) {
4676 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4677 AddToWorkList(Op.getNode());
4678 } else if (Op.getValueType().bitsGT(VT)) {
4679 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4680 AddToWorkList(Op.getNode());
4682 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4683 N0.getValueType().getScalarType());
4686 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4687 // if either of the casts is not free.
4688 if (N0.getOpcode() == ISD::AND &&
4689 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4690 N0.getOperand(1).getOpcode() == ISD::Constant &&
4691 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4692 N0.getValueType()) ||
4693 !TLI.isZExtFree(N0.getValueType(), VT))) {
4694 SDValue X = N0.getOperand(0).getOperand(0);
4695 if (X.getValueType().bitsLT(VT)) {
4696 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4697 } else if (X.getValueType().bitsGT(VT)) {
4698 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4700 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4701 Mask = Mask.zext(VT.getSizeInBits());
4702 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4703 X, DAG.getConstant(Mask, VT));
4706 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4707 // None of the supported targets knows how to perform load and vector_zext
4708 // on vectors in one instruction. We only perform this transformation on
4710 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4711 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4712 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4713 bool DoXform = true;
4714 SmallVector<SDNode*, 4> SetCCs;
4715 if (!N0.hasOneUse())
4716 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4718 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4719 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4721 LN0->getBasePtr(), LN0->getPointerInfo(),
4723 LN0->isVolatile(), LN0->isNonTemporal(),
4724 LN0->getAlignment());
4725 CombineTo(N, ExtLoad);
4726 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4727 N0.getValueType(), ExtLoad);
4728 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4730 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4732 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4736 // fold (zext (and/or/xor (load x), cst)) ->
4737 // (and/or/xor (zextload x), (zext cst))
4738 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4739 N0.getOpcode() == ISD::XOR) &&
4740 isa<LoadSDNode>(N0.getOperand(0)) &&
4741 N0.getOperand(1).getOpcode() == ISD::Constant &&
4742 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4743 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4744 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4745 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4746 bool DoXform = true;
4747 SmallVector<SDNode*, 4> SetCCs;
4748 if (!N0.hasOneUse())
4749 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4752 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4753 LN0->getChain(), LN0->getBasePtr(),
4754 LN0->getPointerInfo(),
4757 LN0->isNonTemporal(),
4758 LN0->getAlignment());
4759 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4760 Mask = Mask.zext(VT.getSizeInBits());
4761 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4762 ExtLoad, DAG.getConstant(Mask, VT));
4763 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4764 N0.getOperand(0).getDebugLoc(),
4765 N0.getOperand(0).getValueType(), ExtLoad);
4767 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4768 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4775 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4776 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4777 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4778 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4779 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4780 EVT MemVT = LN0->getMemoryVT();
4781 if ((!LegalOperations && !LN0->isVolatile()) ||
4782 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4783 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4785 LN0->getBasePtr(), LN0->getPointerInfo(),
4787 LN0->isVolatile(), LN0->isNonTemporal(),
4788 LN0->getAlignment());
4789 CombineTo(N, ExtLoad);
4790 CombineTo(N0.getNode(),
4791 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4793 ExtLoad.getValue(1));
4794 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4798 if (N0.getOpcode() == ISD::SETCC) {
4799 if (!LegalOperations && VT.isVector()) {
4800 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4801 // Only do this before legalize for now.
4802 EVT N0VT = N0.getOperand(0).getValueType();
4803 EVT EltVT = VT.getVectorElementType();
4804 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4805 DAG.getConstant(1, EltVT));
4806 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4807 // We know that the # elements of the results is the same as the
4808 // # elements of the compare (and the # elements of the compare result
4809 // for that matter). Check to see that they are the same size. If so,
4810 // we know that the element size of the sext'd result matches the
4811 // element size of the compare operands.
4812 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4813 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4815 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4816 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4817 &OneOps[0], OneOps.size()));
4819 // If the desired elements are smaller or larger than the source
4820 // elements we can use a matching integer vector type and then
4821 // truncate/sign extend
4822 EVT MatchingElementType =
4823 EVT::getIntegerVT(*DAG.getContext(),
4824 N0VT.getScalarType().getSizeInBits());
4825 EVT MatchingVectorType =
4826 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4827 N0VT.getVectorNumElements());
4829 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4831 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4832 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4833 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4834 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4835 &OneOps[0], OneOps.size()));
4838 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4840 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4841 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4842 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4843 if (SCC.getNode()) return SCC;
4846 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4847 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4848 isa<ConstantSDNode>(N0.getOperand(1)) &&
4849 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4851 SDValue ShAmt = N0.getOperand(1);
4852 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4853 if (N0.getOpcode() == ISD::SHL) {
4854 SDValue InnerZExt = N0.getOperand(0);
4855 // If the original shl may be shifting out bits, do not perform this
4857 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4858 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4859 if (ShAmtVal > KnownZeroBits)
4863 DebugLoc DL = N->getDebugLoc();
4865 // Ensure that the shift amount is wide enough for the shifted value.
4866 if (VT.getSizeInBits() >= 256)
4867 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4869 return DAG.getNode(N0.getOpcode(), DL, VT,
4870 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4877 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4881 // fold (aext c1) -> c1
4882 if (isa<ConstantSDNode>(N0))
4883 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4884 // fold (aext (aext x)) -> (aext x)
4885 // fold (aext (zext x)) -> (zext x)
4886 // fold (aext (sext x)) -> (sext x)
4887 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4888 N0.getOpcode() == ISD::ZERO_EXTEND ||
4889 N0.getOpcode() == ISD::SIGN_EXTEND)
4890 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4892 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4893 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4894 if (N0.getOpcode() == ISD::TRUNCATE) {
4895 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4896 if (NarrowLoad.getNode()) {
4897 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4898 if (NarrowLoad.getNode() != N0.getNode()) {
4899 CombineTo(N0.getNode(), NarrowLoad);
4900 // CombineTo deleted the truncate, if needed, but not what's under it.
4903 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4907 // fold (aext (truncate x))
4908 if (N0.getOpcode() == ISD::TRUNCATE) {
4909 SDValue TruncOp = N0.getOperand(0);
4910 if (TruncOp.getValueType() == VT)
4911 return TruncOp; // x iff x size == zext size.
4912 if (TruncOp.getValueType().bitsGT(VT))
4913 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4914 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4917 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4918 // if the trunc is not free.
4919 if (N0.getOpcode() == ISD::AND &&
4920 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4921 N0.getOperand(1).getOpcode() == ISD::Constant &&
4922 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4923 N0.getValueType())) {
4924 SDValue X = N0.getOperand(0).getOperand(0);
4925 if (X.getValueType().bitsLT(VT)) {
4926 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4927 } else if (X.getValueType().bitsGT(VT)) {
4928 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4930 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4931 Mask = Mask.zext(VT.getSizeInBits());
4932 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4933 X, DAG.getConstant(Mask, VT));
4936 // fold (aext (load x)) -> (aext (truncate (extload x)))
4937 // None of the supported targets knows how to perform load and any_ext
4938 // on vectors in one instruction. We only perform this transformation on
4940 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4941 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4942 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4943 bool DoXform = true;
4944 SmallVector<SDNode*, 4> SetCCs;
4945 if (!N0.hasOneUse())
4946 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4948 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4949 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4951 LN0->getBasePtr(), LN0->getPointerInfo(),
4953 LN0->isVolatile(), LN0->isNonTemporal(),
4954 LN0->getAlignment());
4955 CombineTo(N, ExtLoad);
4956 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4957 N0.getValueType(), ExtLoad);
4958 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4959 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4961 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4965 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4966 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4967 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4968 if (N0.getOpcode() == ISD::LOAD &&
4969 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4971 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4972 EVT MemVT = LN0->getMemoryVT();
4973 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4974 VT, LN0->getChain(), LN0->getBasePtr(),
4975 LN0->getPointerInfo(), MemVT,
4976 LN0->isVolatile(), LN0->isNonTemporal(),
4977 LN0->getAlignment());
4978 CombineTo(N, ExtLoad);
4979 CombineTo(N0.getNode(),
4980 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4981 N0.getValueType(), ExtLoad),
4982 ExtLoad.getValue(1));
4983 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4986 if (N0.getOpcode() == ISD::SETCC) {
4987 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4988 // Only do this before legalize for now.
4989 if (VT.isVector() && !LegalOperations) {
4990 EVT N0VT = N0.getOperand(0).getValueType();
4991 // We know that the # elements of the results is the same as the
4992 // # elements of the compare (and the # elements of the compare result
4993 // for that matter). Check to see that they are the same size. If so,
4994 // we know that the element size of the sext'd result matches the
4995 // element size of the compare operands.
4996 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4997 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4999 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5000 // If the desired elements are smaller or larger than the source
5001 // elements we can use a matching integer vector type and then
5002 // truncate/sign extend
5004 EVT MatchingElementType =
5005 EVT::getIntegerVT(*DAG.getContext(),
5006 N0VT.getScalarType().getSizeInBits());
5007 EVT MatchingVectorType =
5008 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5009 N0VT.getVectorNumElements());
5011 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
5013 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5014 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
5018 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5020 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
5021 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5022 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5030 /// GetDemandedBits - See if the specified operand can be simplified with the
5031 /// knowledge that only the bits specified by Mask are used. If so, return the
5032 /// simpler operand, otherwise return a null SDValue.
5033 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5034 switch (V.getOpcode()) {
5036 case ISD::Constant: {
5037 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5038 assert(CV != 0 && "Const value should be ConstSDNode.");
5039 const APInt &CVal = CV->getAPIntValue();
5040 APInt NewVal = CVal & Mask;
5041 if (NewVal != CVal) {
5042 return DAG.getConstant(NewVal, V.getValueType());
5048 // If the LHS or RHS don't contribute bits to the or, drop them.
5049 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5050 return V.getOperand(1);
5051 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5052 return V.getOperand(0);
5055 // Only look at single-use SRLs.
5056 if (!V.getNode()->hasOneUse())
5058 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5059 // See if we can recursively simplify the LHS.
5060 unsigned Amt = RHSC->getZExtValue();
5062 // Watch out for shift count overflow though.
5063 if (Amt >= Mask.getBitWidth()) break;
5064 APInt NewMask = Mask << Amt;
5065 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5066 if (SimplifyLHS.getNode())
5067 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
5068 SimplifyLHS, V.getOperand(1));
5074 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5075 /// bits and then truncated to a narrower type and where N is a multiple
5076 /// of number of bits of the narrower type, transform it to a narrower load
5077 /// from address + N / num of bits of new type. If the result is to be
5078 /// extended, also fold the extension to form a extending load.
5079 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5080 unsigned Opc = N->getOpcode();
5082 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5083 SDValue N0 = N->getOperand(0);
5084 EVT VT = N->getValueType(0);
5087 // This transformation isn't valid for vector loads.
5091 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5093 if (Opc == ISD::SIGN_EXTEND_INREG) {
5094 ExtType = ISD::SEXTLOAD;
5095 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5096 } else if (Opc == ISD::SRL) {
5097 // Another special-case: SRL is basically zero-extending a narrower value.
5098 ExtType = ISD::ZEXTLOAD;
5100 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5101 if (!N01) return SDValue();
5102 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5103 VT.getSizeInBits() - N01->getZExtValue());
5105 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5108 unsigned EVTBits = ExtVT.getSizeInBits();
5110 // Do not generate loads of non-round integer types since these can
5111 // be expensive (and would be wrong if the type is not byte sized).
5112 if (!ExtVT.isRound())
5116 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5117 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5118 ShAmt = N01->getZExtValue();
5119 // Is the shift amount a multiple of size of VT?
5120 if ((ShAmt & (EVTBits-1)) == 0) {
5121 N0 = N0.getOperand(0);
5122 // Is the load width a multiple of size of VT?
5123 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5127 // At this point, we must have a load or else we can't do the transform.
5128 if (!isa<LoadSDNode>(N0)) return SDValue();
5130 // Because a SRL must be assumed to *need* to zero-extend the high bits
5131 // (as opposed to anyext the high bits), we can't combine the zextload
5132 // lowering of SRL and an sextload.
5133 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5136 // If the shift amount is larger than the input type then we're not
5137 // accessing any of the loaded bytes. If the load was a zextload/extload
5138 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5139 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5144 // If the load is shifted left (and the result isn't shifted back right),
5145 // we can fold the truncate through the shift.
5146 unsigned ShLeftAmt = 0;
5147 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5148 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5149 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5150 ShLeftAmt = N01->getZExtValue();
5151 N0 = N0.getOperand(0);
5155 // If we haven't found a load, we can't narrow it. Don't transform one with
5156 // multiple uses, this would require adding a new load.
5157 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5160 // Don't change the width of a volatile load.
5161 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5162 if (LN0->isVolatile())
5165 // Verify that we are actually reducing a load width here.
5166 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5169 // For the transform to be legal, the load must produce only two values
5170 // (the value loaded and the chain). Don't transform a pre-increment
5171 // load, for example, which produces an extra value. Otherwise the
5172 // transformation is not equivalent, and the downstream logic to replace
5173 // uses gets things wrong.
5174 if (LN0->getNumValues() > 2)
5177 EVT PtrType = N0.getOperand(1).getValueType();
5179 if (PtrType == MVT::Untyped || PtrType.isExtended())
5180 // It's not possible to generate a constant of extended or untyped type.
5183 // For big endian targets, we need to adjust the offset to the pointer to
5184 // load the correct bytes.
5185 if (TLI.isBigEndian()) {
5186 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5187 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5188 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5191 uint64_t PtrOff = ShAmt / 8;
5192 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5193 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5194 PtrType, LN0->getBasePtr(),
5195 DAG.getConstant(PtrOff, PtrType));
5196 AddToWorkList(NewPtr.getNode());
5199 if (ExtType == ISD::NON_EXTLOAD)
5200 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5201 LN0->getPointerInfo().getWithOffset(PtrOff),
5202 LN0->isVolatile(), LN0->isNonTemporal(),
5203 LN0->isInvariant(), NewAlign);
5205 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5206 LN0->getPointerInfo().getWithOffset(PtrOff),
5207 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5210 // Replace the old load's chain with the new load's chain.
5211 WorkListRemover DeadNodes(*this);
5212 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5214 // Shift the result left, if we've swallowed a left shift.
5215 SDValue Result = Load;
5216 if (ShLeftAmt != 0) {
5217 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5218 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5220 // If the shift amount is as large as the result size (but, presumably,
5221 // no larger than the source) then the useful bits of the result are
5222 // zero; we can't simply return the shortened shift, because the result
5223 // of that operation is undefined.
5224 if (ShLeftAmt >= VT.getSizeInBits())
5225 Result = DAG.getConstant(0, VT);
5227 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5228 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5231 // Return the new loaded value.
5235 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5236 SDValue N0 = N->getOperand(0);
5237 SDValue N1 = N->getOperand(1);
5238 EVT VT = N->getValueType(0);
5239 EVT EVT = cast<VTSDNode>(N1)->getVT();
5240 unsigned VTBits = VT.getScalarType().getSizeInBits();
5241 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5243 // fold (sext_in_reg c1) -> c1
5244 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5245 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5247 // If the input is already sign extended, just drop the extension.
5248 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5251 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5252 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5253 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5254 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5255 N0.getOperand(0), N1);
5258 // fold (sext_in_reg (sext x)) -> (sext x)
5259 // fold (sext_in_reg (aext x)) -> (sext x)
5260 // if x is small enough.
5261 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5262 SDValue N00 = N0.getOperand(0);
5263 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5264 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5265 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5268 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5269 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5270 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5272 // fold operands of sext_in_reg based on knowledge that the top bits are not
5274 if (SimplifyDemandedBits(SDValue(N, 0)))
5275 return SDValue(N, 0);
5277 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5278 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5279 SDValue NarrowLoad = ReduceLoadWidth(N);
5280 if (NarrowLoad.getNode())
5283 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5284 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5285 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5286 if (N0.getOpcode() == ISD::SRL) {
5287 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5288 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5289 // We can turn this into an SRA iff the input to the SRL is already sign
5291 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5292 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5293 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5294 N0.getOperand(0), N0.getOperand(1));
5298 // fold (sext_inreg (extload x)) -> (sextload x)
5299 if (ISD::isEXTLoad(N0.getNode()) &&
5300 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5301 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5302 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5303 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5304 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5305 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5307 LN0->getBasePtr(), LN0->getPointerInfo(),
5309 LN0->isVolatile(), LN0->isNonTemporal(),
5310 LN0->getAlignment());
5311 CombineTo(N, ExtLoad);
5312 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5313 AddToWorkList(ExtLoad.getNode());
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5316 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5317 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5319 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5320 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5321 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5322 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5323 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5325 LN0->getBasePtr(), LN0->getPointerInfo(),
5327 LN0->isVolatile(), LN0->isNonTemporal(),
5328 LN0->getAlignment());
5329 CombineTo(N, ExtLoad);
5330 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5331 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5334 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5335 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5336 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5337 N0.getOperand(1), false);
5338 if (BSwap.getNode() != 0)
5339 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5346 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5347 SDValue N0 = N->getOperand(0);
5348 EVT VT = N->getValueType(0);
5349 bool isLE = TLI.isLittleEndian();
5352 if (N0.getValueType() == N->getValueType(0))
5354 // fold (truncate c1) -> c1
5355 if (isa<ConstantSDNode>(N0))
5356 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5357 // fold (truncate (truncate x)) -> (truncate x)
5358 if (N0.getOpcode() == ISD::TRUNCATE)
5359 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5360 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5361 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5362 N0.getOpcode() == ISD::SIGN_EXTEND ||
5363 N0.getOpcode() == ISD::ANY_EXTEND) {
5364 if (N0.getOperand(0).getValueType().bitsLT(VT))
5365 // if the source is smaller than the dest, we still need an extend
5366 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5368 if (N0.getOperand(0).getValueType().bitsGT(VT))
5369 // if the source is larger than the dest, than we just need the truncate
5370 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5371 // if the source and dest are the same type, we can drop both the extend
5372 // and the truncate.
5373 return N0.getOperand(0);
5376 // Fold extract-and-trunc into a narrow extract. For example:
5377 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5378 // i32 y = TRUNCATE(i64 x)
5380 // v16i8 b = BITCAST (v2i64 val)
5381 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5383 // Note: We only run this optimization after type legalization (which often
5384 // creates this pattern) and before operation legalization after which
5385 // we need to be more careful about the vector instructions that we generate.
5386 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5387 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5389 EVT VecTy = N0.getOperand(0).getValueType();
5390 EVT ExTy = N0.getValueType();
5391 EVT TrTy = N->getValueType(0);
5393 unsigned NumElem = VecTy.getVectorNumElements();
5394 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5396 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5397 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5399 SDValue EltNo = N0->getOperand(1);
5400 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5401 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5402 EVT IndexTy = N0->getOperand(1).getValueType();
5403 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5405 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5406 NVT, N0.getOperand(0));
5408 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5409 N->getDebugLoc(), TrTy, V,
5410 DAG.getConstant(Index, IndexTy));
5414 // Fold a series of buildvector, bitcast, and truncate if possible.
5416 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5417 // (2xi32 (buildvector x, y)).
5418 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5419 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5420 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5421 N0.getOperand(0).hasOneUse()) {
5423 SDValue BuildVect = N0.getOperand(0);
5424 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5425 EVT TruncVecEltTy = VT.getVectorElementType();
5427 // Check that the element types match.
5428 if (BuildVectEltTy == TruncVecEltTy) {
5429 // Now we only need to compute the offset of the truncated elements.
5430 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5431 unsigned TruncVecNumElts = VT.getVectorNumElements();
5432 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5434 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5435 "Invalid number of elements");
5437 SmallVector<SDValue, 8> Opnds;
5438 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5439 Opnds.push_back(BuildVect.getOperand(i));
5441 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, &Opnds[0],
5446 // See if we can simplify the input to this truncate through knowledge that
5447 // only the low bits are being used.
5448 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5449 // Currently we only perform this optimization on scalars because vectors
5450 // may have different active low bits.
5451 if (!VT.isVector()) {
5453 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5454 VT.getSizeInBits()));
5455 if (Shorter.getNode())
5456 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5458 // fold (truncate (load x)) -> (smaller load x)
5459 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5460 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5461 SDValue Reduced = ReduceLoadWidth(N);
5462 if (Reduced.getNode())
5465 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5466 // where ... are all 'undef'.
5467 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5468 SmallVector<EVT, 8> VTs;
5471 unsigned NumDefs = 0;
5473 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5474 SDValue X = N0.getOperand(i);
5475 if (X.getOpcode() != ISD::UNDEF) {
5480 // Stop if more than one members are non-undef.
5483 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5484 VT.getVectorElementType(),
5485 X.getValueType().getVectorNumElements()));
5489 return DAG.getUNDEF(VT);
5492 assert(V.getNode() && "The single defined operand is empty!");
5493 SmallVector<SDValue, 8> Opnds;
5494 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5496 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5499 SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
5500 AddToWorkList(NV.getNode());
5501 Opnds.push_back(NV);
5503 return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5504 &Opnds[0], Opnds.size());
5508 // Simplify the operands using demanded-bits information.
5509 if (!VT.isVector() &&
5510 SimplifyDemandedBits(SDValue(N, 0)))
5511 return SDValue(N, 0);
5516 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5517 SDValue Elt = N->getOperand(i);
5518 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5519 return Elt.getNode();
5520 return Elt.getOperand(Elt.getResNo()).getNode();
5523 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5524 /// if load locations are consecutive.
5525 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5526 assert(N->getOpcode() == ISD::BUILD_PAIR);
5528 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5529 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5530 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5531 LD1->getPointerInfo().getAddrSpace() !=
5532 LD2->getPointerInfo().getAddrSpace())
5534 EVT LD1VT = LD1->getValueType(0);
5536 if (ISD::isNON_EXTLoad(LD2) &&
5538 // If both are volatile this would reduce the number of volatile loads.
5539 // If one is volatile it might be ok, but play conservative and bail out.
5540 !LD1->isVolatile() &&
5541 !LD2->isVolatile() &&
5542 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5543 unsigned Align = LD1->getAlignment();
5544 unsigned NewAlign = TLI.getDataLayout()->
5545 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5547 if (NewAlign <= Align &&
5548 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5549 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5550 LD1->getBasePtr(), LD1->getPointerInfo(),
5551 false, false, false, Align);
5557 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5558 SDValue N0 = N->getOperand(0);
5559 EVT VT = N->getValueType(0);
5561 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5562 // Only do this before legalize, since afterward the target may be depending
5563 // on the bitconvert.
5564 // First check to see if this is all constant.
5566 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5568 bool isSimple = true;
5569 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5570 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5571 N0.getOperand(i).getOpcode() != ISD::Constant &&
5572 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5577 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5578 assert(!DestEltVT.isVector() &&
5579 "Element type of vector ValueType must not be vector!");
5581 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5584 // If the input is a constant, let getNode fold it.
5585 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5586 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5587 if (Res.getNode() != N) {
5588 if (!LegalOperations ||
5589 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5592 // Folding it resulted in an illegal node, and it's too late to
5593 // do that. Clean up the old node and forego the transformation.
5594 // Ideally this won't happen very often, because instcombine
5595 // and the earlier dagcombine runs (where illegal nodes are
5596 // permitted) should have folded most of them already.
5597 DAG.DeleteNode(Res.getNode());
5601 // (conv (conv x, t1), t2) -> (conv x, t2)
5602 if (N0.getOpcode() == ISD::BITCAST)
5603 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5606 // fold (conv (load x)) -> (load (conv*)x)
5607 // If the resultant load doesn't need a higher alignment than the original!
5608 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5609 // Do not change the width of a volatile load.
5610 !cast<LoadSDNode>(N0)->isVolatile() &&
5611 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5612 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5613 unsigned Align = TLI.getDataLayout()->
5614 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5615 unsigned OrigAlign = LN0->getAlignment();
5617 if (Align <= OrigAlign) {
5618 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5619 LN0->getBasePtr(), LN0->getPointerInfo(),
5620 LN0->isVolatile(), LN0->isNonTemporal(),
5621 LN0->isInvariant(), OrigAlign);
5623 CombineTo(N0.getNode(),
5624 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5625 N0.getValueType(), Load),
5631 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5632 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5633 // This often reduces constant pool loads.
5634 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5635 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5636 N0.getNode()->hasOneUse() && VT.isInteger() &&
5637 !VT.isVector() && !N0.getValueType().isVector()) {
5638 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5640 AddToWorkList(NewConv.getNode());
5642 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5643 if (N0.getOpcode() == ISD::FNEG)
5644 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5645 NewConv, DAG.getConstant(SignBit, VT));
5646 assert(N0.getOpcode() == ISD::FABS);
5647 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5648 NewConv, DAG.getConstant(~SignBit, VT));
5651 // fold (bitconvert (fcopysign cst, x)) ->
5652 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5653 // Note that we don't handle (copysign x, cst) because this can always be
5654 // folded to an fneg or fabs.
5655 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5656 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5657 VT.isInteger() && !VT.isVector()) {
5658 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5659 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5660 if (isTypeLegal(IntXVT)) {
5661 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5662 IntXVT, N0.getOperand(1));
5663 AddToWorkList(X.getNode());
5665 // If X has a different width than the result/lhs, sext it or truncate it.
5666 unsigned VTWidth = VT.getSizeInBits();
5667 if (OrigXWidth < VTWidth) {
5668 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5669 AddToWorkList(X.getNode());
5670 } else if (OrigXWidth > VTWidth) {
5671 // To get the sign bit in the right place, we have to shift it right
5672 // before truncating.
5673 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5674 X.getValueType(), X,
5675 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5676 AddToWorkList(X.getNode());
5677 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5678 AddToWorkList(X.getNode());
5681 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5682 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5683 X, DAG.getConstant(SignBit, VT));
5684 AddToWorkList(X.getNode());
5686 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5687 VT, N0.getOperand(0));
5688 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5689 Cst, DAG.getConstant(~SignBit, VT));
5690 AddToWorkList(Cst.getNode());
5692 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5696 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5697 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5698 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5699 if (CombineLD.getNode())
5706 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5707 EVT VT = N->getValueType(0);
5708 return CombineConsecutiveLoads(N, VT);
5711 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5712 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5713 /// destination element value type.
5714 SDValue DAGCombiner::
5715 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5716 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5718 // If this is already the right type, we're done.
5719 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5721 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5722 unsigned DstBitSize = DstEltVT.getSizeInBits();
5724 // If this is a conversion of N elements of one type to N elements of another
5725 // type, convert each element. This handles FP<->INT cases.
5726 if (SrcBitSize == DstBitSize) {
5727 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5728 BV->getValueType(0).getVectorNumElements());
5730 // Due to the FP element handling below calling this routine recursively,
5731 // we can end up with a scalar-to-vector node here.
5732 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5733 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5734 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5735 DstEltVT, BV->getOperand(0)));
5737 SmallVector<SDValue, 8> Ops;
5738 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5739 SDValue Op = BV->getOperand(i);
5740 // If the vector element type is not legal, the BUILD_VECTOR operands
5741 // are promoted and implicitly truncated. Make that explicit here.
5742 if (Op.getValueType() != SrcEltVT)
5743 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5744 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5746 AddToWorkList(Ops.back().getNode());
5748 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5749 &Ops[0], Ops.size());
5752 // Otherwise, we're growing or shrinking the elements. To avoid having to
5753 // handle annoying details of growing/shrinking FP values, we convert them to
5755 if (SrcEltVT.isFloatingPoint()) {
5756 // Convert the input float vector to a int vector where the elements are the
5758 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5759 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5760 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5764 // Now we know the input is an integer vector. If the output is a FP type,
5765 // convert to integer first, then to FP of the right size.
5766 if (DstEltVT.isFloatingPoint()) {
5767 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5768 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5769 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5771 // Next, convert to FP elements of the same size.
5772 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5775 // Okay, we know the src/dst types are both integers of differing types.
5776 // Handling growing first.
5777 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5778 if (SrcBitSize < DstBitSize) {
5779 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5781 SmallVector<SDValue, 8> Ops;
5782 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5783 i += NumInputsPerOutput) {
5784 bool isLE = TLI.isLittleEndian();
5785 APInt NewBits = APInt(DstBitSize, 0);
5786 bool EltIsUndef = true;
5787 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5788 // Shift the previously computed bits over.
5789 NewBits <<= SrcBitSize;
5790 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5791 if (Op.getOpcode() == ISD::UNDEF) continue;
5794 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5795 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5799 Ops.push_back(DAG.getUNDEF(DstEltVT));
5801 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5804 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5805 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5806 &Ops[0], Ops.size());
5809 // Finally, this must be the case where we are shrinking elements: each input
5810 // turns into multiple outputs.
5811 bool isS2V = ISD::isScalarToVector(BV);
5812 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5813 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5814 NumOutputsPerInput*BV->getNumOperands());
5815 SmallVector<SDValue, 8> Ops;
5817 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5818 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5819 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5820 Ops.push_back(DAG.getUNDEF(DstEltVT));
5824 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5825 getAPIntValue().zextOrTrunc(SrcBitSize);
5827 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5828 APInt ThisVal = OpVal.trunc(DstBitSize);
5829 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5830 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5831 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5832 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5834 OpVal = OpVal.lshr(DstBitSize);
5837 // For big endian targets, swap the order of the pieces of each element.
5838 if (TLI.isBigEndian())
5839 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5842 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5843 &Ops[0], Ops.size());
5846 SDValue DAGCombiner::visitFADD(SDNode *N) {
5847 SDValue N0 = N->getOperand(0);
5848 SDValue N1 = N->getOperand(1);
5849 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5850 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5851 EVT VT = N->getValueType(0);
5854 if (VT.isVector()) {
5855 SDValue FoldedVOp = SimplifyVBinOp(N);
5856 if (FoldedVOp.getNode()) return FoldedVOp;
5859 // fold (fadd c1, c2) -> c1 + c2
5861 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5862 // canonicalize constant to RHS
5863 if (N0CFP && !N1CFP)
5864 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5865 // fold (fadd A, 0) -> A
5866 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5867 N1CFP->getValueAPF().isZero())
5869 // fold (fadd A, (fneg B)) -> (fsub A, B)
5870 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5871 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5872 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5873 GetNegatedExpression(N1, DAG, LegalOperations));
5874 // fold (fadd (fneg A), B) -> (fsub B, A)
5875 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5876 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5877 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5878 GetNegatedExpression(N0, DAG, LegalOperations));
5880 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5881 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5882 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5883 isa<ConstantFPSDNode>(N0.getOperand(1)))
5884 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5885 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5886 N0.getOperand(1), N1));
5888 // No FP constant should be created after legalization as Instruction
5889 // Selection pass has hard time in dealing with FP constant.
5891 // We don't need test this condition for transformation like following, as
5892 // the DAG being transformed implies it is legal to take FP constant as
5895 // (fadd (fmul c, x), x) -> (fmul c+1, x)
5897 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5899 // If allow, fold (fadd (fneg x), x) -> 0.0
5900 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5901 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5902 return DAG.getConstantFP(0.0, VT);
5905 // If allow, fold (fadd x, (fneg x)) -> 0.0
5906 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5907 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5908 return DAG.getConstantFP(0.0, VT);
5911 // In unsafe math mode, we can fold chains of FADD's of the same value
5912 // into multiplications. This transform is not safe in general because
5913 // we are reducing the number of rounding steps.
5914 if (DAG.getTarget().Options.UnsafeFPMath &&
5915 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5917 if (N0.getOpcode() == ISD::FMUL) {
5918 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5919 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5921 // (fadd (fmul c, x), x) -> (fmul c+1, x)
5922 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5923 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5925 DAG.getConstantFP(1.0, VT));
5926 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5930 // (fadd (fmul x, c), x) -> (fmul c+1, x)
5931 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5932 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5934 DAG.getConstantFP(1.0, VT));
5935 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5939 // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5940 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5941 N1.getOperand(0) == N1.getOperand(1) &&
5942 N0.getOperand(1) == N1.getOperand(0)) {
5943 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5945 DAG.getConstantFP(2.0, VT));
5946 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5947 N0.getOperand(1), NewCFP);
5950 // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5951 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5952 N1.getOperand(0) == N1.getOperand(1) &&
5953 N0.getOperand(0) == N1.getOperand(0)) {
5954 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5956 DAG.getConstantFP(2.0, VT));
5957 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5958 N0.getOperand(0), NewCFP);
5962 if (N1.getOpcode() == ISD::FMUL) {
5963 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5964 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5966 // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5967 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5968 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5970 DAG.getConstantFP(1.0, VT));
5971 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5975 // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5976 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5977 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5979 DAG.getConstantFP(1.0, VT));
5980 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5985 // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5986 if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5987 N1.getOperand(0) == N1.getOperand(1) &&
5988 N0.getOperand(1) == N1.getOperand(0)) {
5989 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5991 DAG.getConstantFP(2.0, VT));
5992 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5993 N0.getOperand(1), NewCFP);
5996 // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5997 if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5998 N1.getOperand(0) == N1.getOperand(1) &&
5999 N0.getOperand(0) == N1.getOperand(0)) {
6000 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
6002 DAG.getConstantFP(2.0, VT));
6003 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6004 N0.getOperand(0), NewCFP);
6008 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6009 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6010 // (fadd (fadd x, x), x) -> (fmul 3.0, x)
6011 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6012 (N0.getOperand(0) == N1)) {
6013 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6014 N1, DAG.getConstantFP(3.0, VT));
6018 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6019 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6020 // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
6021 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6022 N1.getOperand(0) == N0) {
6023 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6024 N0, DAG.getConstantFP(3.0, VT));
6028 // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
6029 if (AllowNewFpConst &&
6030 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6031 N0.getOperand(0) == N0.getOperand(1) &&
6032 N1.getOperand(0) == N1.getOperand(1) &&
6033 N0.getOperand(0) == N1.getOperand(0)) {
6034 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6036 DAG.getConstantFP(4.0, VT));
6040 // FADD -> FMA combines:
6041 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6042 DAG.getTarget().Options.UnsafeFPMath) &&
6043 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6044 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6046 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6047 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6048 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
6049 N0.getOperand(0), N0.getOperand(1), N1);
6052 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6053 // Note: Commutes FADD operands.
6054 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6055 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
6056 N1.getOperand(0), N1.getOperand(1), N0);
6063 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6064 SDValue N0 = N->getOperand(0);
6065 SDValue N1 = N->getOperand(1);
6066 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6067 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6068 EVT VT = N->getValueType(0);
6069 DebugLoc dl = N->getDebugLoc();
6072 if (VT.isVector()) {
6073 SDValue FoldedVOp = SimplifyVBinOp(N);
6074 if (FoldedVOp.getNode()) return FoldedVOp;
6077 // fold (fsub c1, c2) -> c1-c2
6079 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
6080 // fold (fsub A, 0) -> A
6081 if (DAG.getTarget().Options.UnsafeFPMath &&
6082 N1CFP && N1CFP->getValueAPF().isZero())
6084 // fold (fsub 0, B) -> -B
6085 if (DAG.getTarget().Options.UnsafeFPMath &&
6086 N0CFP && N0CFP->getValueAPF().isZero()) {
6087 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6088 return GetNegatedExpression(N1, DAG, LegalOperations);
6089 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6090 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6092 // fold (fsub A, (fneg B)) -> (fadd A, B)
6093 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6094 return DAG.getNode(ISD::FADD, dl, VT, N0,
6095 GetNegatedExpression(N1, DAG, LegalOperations));
6097 // If 'unsafe math' is enabled, fold
6098 // (fsub x, x) -> 0.0 &
6099 // (fsub x, (fadd x, y)) -> (fneg y) &
6100 // (fsub x, (fadd y, x)) -> (fneg y)
6101 if (DAG.getTarget().Options.UnsafeFPMath) {
6103 return DAG.getConstantFP(0.0f, VT);
6105 if (N1.getOpcode() == ISD::FADD) {
6106 SDValue N10 = N1->getOperand(0);
6107 SDValue N11 = N1->getOperand(1);
6109 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6110 &DAG.getTarget().Options))
6111 return GetNegatedExpression(N11, DAG, LegalOperations);
6112 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6113 &DAG.getTarget().Options))
6114 return GetNegatedExpression(N10, DAG, LegalOperations);
6118 // FSUB -> FMA combines:
6119 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6120 DAG.getTarget().Options.UnsafeFPMath) &&
6121 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6122 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6124 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6125 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6126 return DAG.getNode(ISD::FMA, dl, VT,
6127 N0.getOperand(0), N0.getOperand(1),
6128 DAG.getNode(ISD::FNEG, dl, VT, N1));
6131 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6132 // Note: Commutes FSUB operands.
6133 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6134 return DAG.getNode(ISD::FMA, dl, VT,
6135 DAG.getNode(ISD::FNEG, dl, VT,
6137 N1.getOperand(1), N0);
6140 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6141 if (N0.getOpcode() == ISD::FNEG &&
6142 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6143 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6144 SDValue N00 = N0.getOperand(0).getOperand(0);
6145 SDValue N01 = N0.getOperand(0).getOperand(1);
6146 return DAG.getNode(ISD::FMA, dl, VT,
6147 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6148 DAG.getNode(ISD::FNEG, dl, VT, N1));
6155 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6156 SDValue N0 = N->getOperand(0);
6157 SDValue N1 = N->getOperand(1);
6158 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6159 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6160 EVT VT = N->getValueType(0);
6161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6164 if (VT.isVector()) {
6165 SDValue FoldedVOp = SimplifyVBinOp(N);
6166 if (FoldedVOp.getNode()) return FoldedVOp;
6169 // fold (fmul c1, c2) -> c1*c2
6171 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
6172 // canonicalize constant to RHS
6173 if (N0CFP && !N1CFP)
6174 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
6175 // fold (fmul A, 0) -> 0
6176 if (DAG.getTarget().Options.UnsafeFPMath &&
6177 N1CFP && N1CFP->getValueAPF().isZero())
6179 // fold (fmul A, 0) -> 0, vector edition.
6180 if (DAG.getTarget().Options.UnsafeFPMath &&
6181 ISD::isBuildVectorAllZeros(N1.getNode()))
6183 // fold (fmul A, 1.0) -> A
6184 if (N1CFP && N1CFP->isExactlyValue(1.0))
6186 // fold (fmul X, 2.0) -> (fadd X, X)
6187 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6188 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
6189 // fold (fmul X, -1.0) -> (fneg X)
6190 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6191 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6192 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
6194 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6195 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6196 &DAG.getTarget().Options)) {
6197 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6198 &DAG.getTarget().Options)) {
6199 // Both can be negated for free, check to see if at least one is cheaper
6201 if (LHSNeg == 2 || RHSNeg == 2)
6202 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6203 GetNegatedExpression(N0, DAG, LegalOperations),
6204 GetNegatedExpression(N1, DAG, LegalOperations));
6208 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6209 if (DAG.getTarget().Options.UnsafeFPMath &&
6210 N1CFP && N0.getOpcode() == ISD::FMUL &&
6211 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6212 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
6213 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6214 N0.getOperand(1), N1));
6219 SDValue DAGCombiner::visitFMA(SDNode *N) {
6220 SDValue N0 = N->getOperand(0);
6221 SDValue N1 = N->getOperand(1);
6222 SDValue N2 = N->getOperand(2);
6223 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6224 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6225 EVT VT = N->getValueType(0);
6226 DebugLoc dl = N->getDebugLoc();
6228 if (DAG.getTarget().Options.UnsafeFPMath) {
6229 if (N0CFP && N0CFP->isZero())
6231 if (N1CFP && N1CFP->isZero())
6234 if (N0CFP && N0CFP->isExactlyValue(1.0))
6235 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6236 if (N1CFP && N1CFP->isExactlyValue(1.0))
6237 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6239 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6240 if (N0CFP && !N1CFP)
6241 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6243 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6244 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6245 N2.getOpcode() == ISD::FMUL &&
6246 N0 == N2.getOperand(0) &&
6247 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6248 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6249 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6253 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6254 if (DAG.getTarget().Options.UnsafeFPMath &&
6255 N0.getOpcode() == ISD::FMUL && N1CFP &&
6256 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6257 return DAG.getNode(ISD::FMA, dl, VT,
6259 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6263 // (fma x, 1, y) -> (fadd x, y)
6264 // (fma x, -1, y) -> (fadd (fneg x), y)
6266 if (N1CFP->isExactlyValue(1.0))
6267 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6269 if (N1CFP->isExactlyValue(-1.0) &&
6270 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6271 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6272 AddToWorkList(RHSNeg.getNode());
6273 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6277 // (fma x, c, x) -> (fmul x, (c+1))
6278 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6279 return DAG.getNode(ISD::FMUL, dl, VT,
6281 DAG.getNode(ISD::FADD, dl, VT,
6282 N1, DAG.getConstantFP(1.0, VT)));
6285 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6286 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6287 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6288 return DAG.getNode(ISD::FMUL, dl, VT,
6290 DAG.getNode(ISD::FADD, dl, VT,
6291 N1, DAG.getConstantFP(-1.0, VT)));
6298 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6299 SDValue N0 = N->getOperand(0);
6300 SDValue N1 = N->getOperand(1);
6301 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6302 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6303 EVT VT = N->getValueType(0);
6304 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6307 if (VT.isVector()) {
6308 SDValue FoldedVOp = SimplifyVBinOp(N);
6309 if (FoldedVOp.getNode()) return FoldedVOp;
6312 // fold (fdiv c1, c2) -> c1/c2
6314 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6316 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6317 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6318 // Compute the reciprocal 1.0 / c2.
6319 APFloat N1APF = N1CFP->getValueAPF();
6320 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6321 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6322 // Only do the transform if the reciprocal is a legal fp immediate that
6323 // isn't too nasty (eg NaN, denormal, ...).
6324 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6325 (!LegalOperations ||
6326 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6327 // backend)... we should handle this gracefully after Legalize.
6328 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6329 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6330 TLI.isFPImmLegal(Recip, VT)))
6331 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6332 DAG.getConstantFP(Recip, VT));
6335 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6336 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6337 &DAG.getTarget().Options)) {
6338 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6339 &DAG.getTarget().Options)) {
6340 // Both can be negated for free, check to see if at least one is cheaper
6342 if (LHSNeg == 2 || RHSNeg == 2)
6343 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6344 GetNegatedExpression(N0, DAG, LegalOperations),
6345 GetNegatedExpression(N1, DAG, LegalOperations));
6352 SDValue DAGCombiner::visitFREM(SDNode *N) {
6353 SDValue N0 = N->getOperand(0);
6354 SDValue N1 = N->getOperand(1);
6355 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6356 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6357 EVT VT = N->getValueType(0);
6359 // fold (frem c1, c2) -> fmod(c1,c2)
6361 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6366 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6367 SDValue N0 = N->getOperand(0);
6368 SDValue N1 = N->getOperand(1);
6369 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6370 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6371 EVT VT = N->getValueType(0);
6373 if (N0CFP && N1CFP) // Constant fold
6374 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6377 const APFloat& V = N1CFP->getValueAPF();
6378 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6379 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6380 if (!V.isNegative()) {
6381 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6382 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6384 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6385 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6386 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6390 // copysign(fabs(x), y) -> copysign(x, y)
6391 // copysign(fneg(x), y) -> copysign(x, y)
6392 // copysign(copysign(x,z), y) -> copysign(x, y)
6393 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6394 N0.getOpcode() == ISD::FCOPYSIGN)
6395 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6396 N0.getOperand(0), N1);
6398 // copysign(x, abs(y)) -> abs(x)
6399 if (N1.getOpcode() == ISD::FABS)
6400 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6402 // copysign(x, copysign(y,z)) -> copysign(x, z)
6403 if (N1.getOpcode() == ISD::FCOPYSIGN)
6404 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6405 N0, N1.getOperand(1));
6407 // copysign(x, fp_extend(y)) -> copysign(x, y)
6408 // copysign(x, fp_round(y)) -> copysign(x, y)
6409 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6410 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6411 N0, N1.getOperand(0));
6416 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6417 SDValue N0 = N->getOperand(0);
6418 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6419 EVT VT = N->getValueType(0);
6420 EVT OpVT = N0.getValueType();
6422 // fold (sint_to_fp c1) -> c1fp
6424 // ...but only if the target supports immediate floating-point values
6425 (!LegalOperations ||
6426 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6427 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6429 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6430 // but UINT_TO_FP is legal on this target, try to convert.
6431 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6432 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6433 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6434 if (DAG.SignBitIsZero(N0))
6435 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6438 // The next optimizations are desireable only if SELECT_CC can be lowered.
6439 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6440 // having to say they don't support SELECT_CC on every type the DAG knows
6441 // about, since there is no way to mark an opcode illegal at all value types
6442 // (See also visitSELECT)
6443 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6444 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6445 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6447 (!LegalOperations ||
6448 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6450 { N0.getOperand(0), N0.getOperand(1),
6451 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6453 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6456 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6457 // (select_cc x, y, 1.0, 0.0,, cc)
6458 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6459 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6460 (!LegalOperations ||
6461 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6463 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6464 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6465 N0.getOperand(0).getOperand(2) };
6466 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6473 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6474 SDValue N0 = N->getOperand(0);
6475 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6476 EVT VT = N->getValueType(0);
6477 EVT OpVT = N0.getValueType();
6479 // fold (uint_to_fp c1) -> c1fp
6481 // ...but only if the target supports immediate floating-point values
6482 (!LegalOperations ||
6483 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6484 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6486 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6487 // but SINT_TO_FP is legal on this target, try to convert.
6488 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6489 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6490 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6491 if (DAG.SignBitIsZero(N0))
6492 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6495 // The next optimizations are desireable only if SELECT_CC can be lowered.
6496 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6497 // having to say they don't support SELECT_CC on every type the DAG knows
6498 // about, since there is no way to mark an opcode illegal at all value types
6499 // (See also visitSELECT)
6500 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6501 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6503 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6504 (!LegalOperations ||
6505 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6507 { N0.getOperand(0), N0.getOperand(1),
6508 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6510 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6517 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6518 SDValue N0 = N->getOperand(0);
6519 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6520 EVT VT = N->getValueType(0);
6522 // fold (fp_to_sint c1fp) -> c1
6524 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6529 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6530 SDValue N0 = N->getOperand(0);
6531 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6532 EVT VT = N->getValueType(0);
6534 // fold (fp_to_uint c1fp) -> c1
6536 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6541 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6542 SDValue N0 = N->getOperand(0);
6543 SDValue N1 = N->getOperand(1);
6544 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6545 EVT VT = N->getValueType(0);
6547 // fold (fp_round c1fp) -> c1fp
6549 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6551 // fold (fp_round (fp_extend x)) -> x
6552 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6553 return N0.getOperand(0);
6555 // fold (fp_round (fp_round x)) -> (fp_round x)
6556 if (N0.getOpcode() == ISD::FP_ROUND) {
6557 // This is a value preserving truncation if both round's are.
6558 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6559 N0.getNode()->getConstantOperandVal(1) == 1;
6560 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6561 DAG.getIntPtrConstant(IsTrunc));
6564 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6565 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6566 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6567 N0.getOperand(0), N1);
6568 AddToWorkList(Tmp.getNode());
6569 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6570 Tmp, N0.getOperand(1));
6576 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6577 SDValue N0 = N->getOperand(0);
6578 EVT VT = N->getValueType(0);
6579 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6580 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6582 // fold (fp_round_inreg c1fp) -> c1fp
6583 if (N0CFP && isTypeLegal(EVT)) {
6584 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6585 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6591 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6592 SDValue N0 = N->getOperand(0);
6593 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6594 EVT VT = N->getValueType(0);
6596 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6597 if (N->hasOneUse() &&
6598 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6601 // fold (fp_extend c1fp) -> c1fp
6603 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6605 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6607 if (N0.getOpcode() == ISD::FP_ROUND
6608 && N0.getNode()->getConstantOperandVal(1) == 1) {
6609 SDValue In = N0.getOperand(0);
6610 if (In.getValueType() == VT) return In;
6611 if (VT.bitsLT(In.getValueType()))
6612 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6613 In, N0.getOperand(1));
6614 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6617 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6618 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6619 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6620 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6621 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6622 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6624 LN0->getBasePtr(), LN0->getPointerInfo(),
6626 LN0->isVolatile(), LN0->isNonTemporal(),
6627 LN0->getAlignment());
6628 CombineTo(N, ExtLoad);
6629 CombineTo(N0.getNode(),
6630 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6631 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6632 ExtLoad.getValue(1));
6633 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6639 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6640 SDValue N0 = N->getOperand(0);
6641 EVT VT = N->getValueType(0);
6643 if (VT.isVector()) {
6644 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6645 if (FoldedVOp.getNode()) return FoldedVOp;
6648 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6649 &DAG.getTarget().Options))
6650 return GetNegatedExpression(N0, DAG, LegalOperations);
6652 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6653 // constant pool values.
6654 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6656 N0.getNode()->hasOneUse() &&
6657 N0.getOperand(0).getValueType().isInteger()) {
6658 SDValue Int = N0.getOperand(0);
6659 EVT IntVT = Int.getValueType();
6660 if (IntVT.isInteger() && !IntVT.isVector()) {
6661 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6662 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6663 AddToWorkList(Int.getNode());
6664 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6669 // (fneg (fmul c, x)) -> (fmul -c, x)
6670 if (N0.getOpcode() == ISD::FMUL) {
6671 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6673 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6675 DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6683 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6684 SDValue N0 = N->getOperand(0);
6685 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6686 EVT VT = N->getValueType(0);
6688 // fold (fceil c1) -> fceil(c1)
6690 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6695 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6696 SDValue N0 = N->getOperand(0);
6697 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6698 EVT VT = N->getValueType(0);
6700 // fold (ftrunc c1) -> ftrunc(c1)
6702 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6707 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6708 SDValue N0 = N->getOperand(0);
6709 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6710 EVT VT = N->getValueType(0);
6712 // fold (ffloor c1) -> ffloor(c1)
6714 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6719 SDValue DAGCombiner::visitFABS(SDNode *N) {
6720 SDValue N0 = N->getOperand(0);
6721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6722 EVT VT = N->getValueType(0);
6724 if (VT.isVector()) {
6725 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6726 if (FoldedVOp.getNode()) return FoldedVOp;
6729 // fold (fabs c1) -> fabs(c1)
6731 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6732 // fold (fabs (fabs x)) -> (fabs x)
6733 if (N0.getOpcode() == ISD::FABS)
6734 return N->getOperand(0);
6735 // fold (fabs (fneg x)) -> (fabs x)
6736 // fold (fabs (fcopysign x, y)) -> (fabs x)
6737 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6738 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6740 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6741 // constant pool values.
6742 if (!TLI.isFAbsFree(VT) &&
6743 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6744 N0.getOperand(0).getValueType().isInteger() &&
6745 !N0.getOperand(0).getValueType().isVector()) {
6746 SDValue Int = N0.getOperand(0);
6747 EVT IntVT = Int.getValueType();
6748 if (IntVT.isInteger() && !IntVT.isVector()) {
6749 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6750 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6751 AddToWorkList(Int.getNode());
6752 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6753 N->getValueType(0), Int);
6760 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6761 SDValue Chain = N->getOperand(0);
6762 SDValue N1 = N->getOperand(1);
6763 SDValue N2 = N->getOperand(2);
6765 // If N is a constant we could fold this into a fallthrough or unconditional
6766 // branch. However that doesn't happen very often in normal code, because
6767 // Instcombine/SimplifyCFG should have handled the available opportunities.
6768 // If we did this folding here, it would be necessary to update the
6769 // MachineBasicBlock CFG, which is awkward.
6771 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6773 if (N1.getOpcode() == ISD::SETCC &&
6774 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6775 N1.getOperand(0).getValueType())) {
6776 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6777 Chain, N1.getOperand(2),
6778 N1.getOperand(0), N1.getOperand(1), N2);
6781 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6782 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6783 (N1.getOperand(0).hasOneUse() &&
6784 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6786 if (N1.getOpcode() == ISD::TRUNCATE) {
6787 // Look pass the truncate.
6788 Trunc = N1.getNode();
6789 N1 = N1.getOperand(0);
6792 // Match this pattern so that we can generate simpler code:
6795 // %b = and i32 %a, 2
6796 // %c = srl i32 %b, 1
6797 // brcond i32 %c ...
6802 // %b = and i32 %a, 2
6803 // %c = setcc eq %b, 0
6806 // This applies only when the AND constant value has one bit set and the
6807 // SRL constant is equal to the log2 of the AND constant. The back-end is
6808 // smart enough to convert the result into a TEST/JMP sequence.
6809 SDValue Op0 = N1.getOperand(0);
6810 SDValue Op1 = N1.getOperand(1);
6812 if (Op0.getOpcode() == ISD::AND &&
6813 Op1.getOpcode() == ISD::Constant) {
6814 SDValue AndOp1 = Op0.getOperand(1);
6816 if (AndOp1.getOpcode() == ISD::Constant) {
6817 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6819 if (AndConst.isPowerOf2() &&
6820 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6822 DAG.getSetCC(N->getDebugLoc(),
6823 TLI.getSetCCResultType(Op0.getValueType()),
6824 Op0, DAG.getConstant(0, Op0.getValueType()),
6827 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6828 MVT::Other, Chain, SetCC, N2);
6829 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6830 // will convert it back to (X & C1) >> C2.
6831 CombineTo(N, NewBRCond, false);
6832 // Truncate is dead.
6834 removeFromWorkList(Trunc);
6835 DAG.DeleteNode(Trunc);
6837 // Replace the uses of SRL with SETCC
6838 WorkListRemover DeadNodes(*this);
6839 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6840 removeFromWorkList(N1.getNode());
6841 DAG.DeleteNode(N1.getNode());
6842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6848 // Restore N1 if the above transformation doesn't match.
6849 N1 = N->getOperand(1);
6852 // Transform br(xor(x, y)) -> br(x != y)
6853 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6854 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6855 SDNode *TheXor = N1.getNode();
6856 SDValue Op0 = TheXor->getOperand(0);
6857 SDValue Op1 = TheXor->getOperand(1);
6858 if (Op0.getOpcode() == Op1.getOpcode()) {
6859 // Avoid missing important xor optimizations.
6860 SDValue Tmp = visitXOR(TheXor);
6861 if (Tmp.getNode()) {
6862 if (Tmp.getNode() != TheXor) {
6863 DEBUG(dbgs() << "\nReplacing.8 ";
6865 dbgs() << "\nWith: ";
6866 Tmp.getNode()->dump(&DAG);
6868 WorkListRemover DeadNodes(*this);
6869 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6870 removeFromWorkList(TheXor);
6871 DAG.DeleteNode(TheXor);
6872 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6873 MVT::Other, Chain, Tmp, N2);
6876 // visitXOR has changed XOR's operands or replaced the XOR completely,
6878 return SDValue(N, 0);
6882 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6884 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6885 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6886 Op0.getOpcode() == ISD::XOR) {
6887 TheXor = Op0.getNode();
6891 EVT SetCCVT = N1.getValueType();
6893 SetCCVT = TLI.getSetCCResultType(SetCCVT);
6894 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6897 Equal ? ISD::SETEQ : ISD::SETNE);
6898 // Replace the uses of XOR with SETCC
6899 WorkListRemover DeadNodes(*this);
6900 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6901 removeFromWorkList(N1.getNode());
6902 DAG.DeleteNode(N1.getNode());
6903 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6904 MVT::Other, Chain, SetCC, N2);
6911 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6913 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6914 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6915 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6917 // If N is a constant we could fold this into a fallthrough or unconditional
6918 // branch. However that doesn't happen very often in normal code, because
6919 // Instcombine/SimplifyCFG should have handled the available opportunities.
6920 // If we did this folding here, it would be necessary to update the
6921 // MachineBasicBlock CFG, which is awkward.
6923 // Use SimplifySetCC to simplify SETCC's.
6924 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6925 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6927 if (Simp.getNode()) AddToWorkList(Simp.getNode());
6929 // fold to a simpler setcc
6930 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6931 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6932 N->getOperand(0), Simp.getOperand(2),
6933 Simp.getOperand(0), Simp.getOperand(1),
6939 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6940 /// uses N as its base pointer and that N may be folded in the load / store
6941 /// addressing mode.
6942 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6944 const TargetLowering &TLI) {
6946 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
6947 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6949 VT = Use->getValueType(0);
6950 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
6951 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6953 VT = ST->getValue().getValueType();
6957 TargetLowering::AddrMode AM;
6958 if (N->getOpcode() == ISD::ADD) {
6959 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6962 AM.BaseOffs = Offset->getSExtValue();
6966 } else if (N->getOpcode() == ISD::SUB) {
6967 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6970 AM.BaseOffs = -Offset->getSExtValue();
6977 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6980 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6981 /// pre-indexed load / store when the base pointer is an add or subtract
6982 /// and it has other uses besides the load / store. After the
6983 /// transformation, the new indexed load / store has effectively folded
6984 /// the add / subtract in and all of its other uses are redirected to the
6985 /// new load / store.
6986 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6987 if (Level < AfterLegalizeDAG)
6993 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6994 if (LD->isIndexed())
6996 VT = LD->getMemoryVT();
6997 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6998 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7000 Ptr = LD->getBasePtr();
7001 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7002 if (ST->isIndexed())
7004 VT = ST->getMemoryVT();
7005 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7006 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7008 Ptr = ST->getBasePtr();
7014 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7015 // out. There is no reason to make this a preinc/predec.
7016 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7017 Ptr.getNode()->hasOneUse())
7020 // Ask the target to do addressing mode selection.
7023 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7024 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7027 // Backends without true r+i pre-indexed forms may need to pass a
7028 // constant base with a variable offset so that constant coercion
7029 // will work with the patterns in canonical form.
7030 bool Swapped = false;
7031 if (isa<ConstantSDNode>(BasePtr)) {
7032 std::swap(BasePtr, Offset);
7036 // Don't create a indexed load / store with zero offset.
7037 if (isa<ConstantSDNode>(Offset) &&
7038 cast<ConstantSDNode>(Offset)->isNullValue())
7041 // Try turning it into a pre-indexed load / store except when:
7042 // 1) The new base ptr is a frame index.
7043 // 2) If N is a store and the new base ptr is either the same as or is a
7044 // predecessor of the value being stored.
7045 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7046 // that would create a cycle.
7047 // 4) All uses are load / store ops that use it as old base ptr.
7049 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7050 // (plus the implicit offset) to a register to preinc anyway.
7051 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7056 SDValue Val = cast<StoreSDNode>(N)->getValue();
7057 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7061 // If the offset is a constant, there may be other adds of constants that
7062 // can be folded with this one. We should do this to avoid having to keep
7063 // a copy of the original base pointer.
7064 SmallVector<SDNode *, 16> OtherUses;
7065 if (isa<ConstantSDNode>(Offset))
7066 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7067 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7069 if (Use == Ptr.getNode())
7072 if (Use->isPredecessorOf(N))
7075 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7080 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7081 if (Op1.getNode() == BasePtr.getNode())
7082 std::swap(Op0, Op1);
7083 assert(Op0.getNode() == BasePtr.getNode() &&
7084 "Use of ADD/SUB but not an operand");
7086 if (!isa<ConstantSDNode>(Op1)) {
7091 // FIXME: In some cases, we can be smarter about this.
7092 if (Op1.getValueType() != Offset.getValueType()) {
7097 OtherUses.push_back(Use);
7101 std::swap(BasePtr, Offset);
7103 // Now check for #3 and #4.
7104 bool RealUse = false;
7106 // Caches for hasPredecessorHelper
7107 SmallPtrSet<const SDNode *, 32> Visited;
7108 SmallVector<const SDNode *, 16> Worklist;
7110 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7111 E = Ptr.getNode()->use_end(); I != E; ++I) {
7115 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7118 // If Ptr may be folded in addressing mode of other use, then it's
7119 // not profitable to do this transformation.
7120 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7129 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7130 BasePtr, Offset, AM);
7132 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7133 BasePtr, Offset, AM);
7136 DEBUG(dbgs() << "\nReplacing.4 ";
7138 dbgs() << "\nWith: ";
7139 Result.getNode()->dump(&DAG);
7141 WorkListRemover DeadNodes(*this);
7143 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7144 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7149 // Finally, since the node is now dead, remove it from the graph.
7153 std::swap(BasePtr, Offset);
7155 // Replace other uses of BasePtr that can be updated to use Ptr
7156 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7157 unsigned OffsetIdx = 1;
7158 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7160 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7161 BasePtr.getNode() && "Expected BasePtr operand");
7163 // We need to replace ptr0 in the following expression:
7164 // x0 * offset0 + y0 * ptr0 = t0
7166 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7168 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7169 // indexed load/store and the expresion that needs to be re-written.
7171 // Therefore, we have:
7172 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7174 ConstantSDNode *CN =
7175 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7177 APInt Offset0 = CN->getAPIntValue();
7178 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7180 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7181 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7182 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7183 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7185 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7187 APInt CNV = Offset0;
7188 if (X0 < 0) CNV = -CNV;
7189 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7190 else CNV = CNV - Offset1;
7192 // We can now generate the new expression.
7193 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7194 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7196 SDValue NewUse = DAG.getNode(Opcode,
7197 OtherUses[i]->getDebugLoc(),
7198 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7199 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7200 removeFromWorkList(OtherUses[i]);
7201 DAG.DeleteNode(OtherUses[i]);
7204 // Replace the uses of Ptr with uses of the updated base value.
7205 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7206 removeFromWorkList(Ptr.getNode());
7207 DAG.DeleteNode(Ptr.getNode());
7212 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7213 /// add / sub of the base pointer node into a post-indexed load / store.
7214 /// The transformation folded the add / subtract into the new indexed
7215 /// load / store effectively and all of its uses are redirected to the
7216 /// new load / store.
7217 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7218 if (Level < AfterLegalizeDAG)
7224 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7225 if (LD->isIndexed())
7227 VT = LD->getMemoryVT();
7228 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7229 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7231 Ptr = LD->getBasePtr();
7232 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7233 if (ST->isIndexed())
7235 VT = ST->getMemoryVT();
7236 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7237 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7239 Ptr = ST->getBasePtr();
7245 if (Ptr.getNode()->hasOneUse())
7248 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7249 E = Ptr.getNode()->use_end(); I != E; ++I) {
7252 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7257 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7258 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7259 // Don't create a indexed load / store with zero offset.
7260 if (isa<ConstantSDNode>(Offset) &&
7261 cast<ConstantSDNode>(Offset)->isNullValue())
7264 // Try turning it into a post-indexed load / store except when
7265 // 1) All uses are load / store ops that use it as base ptr (and
7266 // it may be folded as addressing mmode).
7267 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7268 // nor a successor of N. Otherwise, if Op is folded that would
7271 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7275 bool TryNext = false;
7276 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7277 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7279 if (Use == Ptr.getNode())
7282 // If all the uses are load / store addresses, then don't do the
7284 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7285 bool RealUse = false;
7286 for (SDNode::use_iterator III = Use->use_begin(),
7287 EEE = Use->use_end(); III != EEE; ++III) {
7288 SDNode *UseUse = *III;
7289 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7304 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7305 SDValue Result = isLoad
7306 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7307 BasePtr, Offset, AM)
7308 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7309 BasePtr, Offset, AM);
7312 DEBUG(dbgs() << "\nReplacing.5 ";
7314 dbgs() << "\nWith: ";
7315 Result.getNode()->dump(&DAG);
7317 WorkListRemover DeadNodes(*this);
7319 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7320 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7322 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7325 // Finally, since the node is now dead, remove it from the graph.
7328 // Replace the uses of Use with uses of the updated base value.
7329 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7330 Result.getValue(isLoad ? 1 : 0));
7331 removeFromWorkList(Op);
7341 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7342 LoadSDNode *LD = cast<LoadSDNode>(N);
7343 SDValue Chain = LD->getChain();
7344 SDValue Ptr = LD->getBasePtr();
7346 // If load is not volatile and there are no uses of the loaded value (and
7347 // the updated indexed value in case of indexed loads), change uses of the
7348 // chain value into uses of the chain input (i.e. delete the dead load).
7349 if (!LD->isVolatile()) {
7350 if (N->getValueType(1) == MVT::Other) {
7352 if (!N->hasAnyUseOfValue(0)) {
7353 // It's not safe to use the two value CombineTo variant here. e.g.
7354 // v1, chain2 = load chain1, loc
7355 // v2, chain3 = load chain2, loc
7357 // Now we replace use of chain2 with chain1. This makes the second load
7358 // isomorphic to the one we are deleting, and thus makes this load live.
7359 DEBUG(dbgs() << "\nReplacing.6 ";
7361 dbgs() << "\nWith chain: ";
7362 Chain.getNode()->dump(&DAG);
7364 WorkListRemover DeadNodes(*this);
7365 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7367 if (N->use_empty()) {
7368 removeFromWorkList(N);
7372 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7376 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7377 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7378 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7379 DEBUG(dbgs() << "\nReplacing.7 ";
7381 dbgs() << "\nWith: ";
7382 Undef.getNode()->dump(&DAG);
7383 dbgs() << " and 2 other values\n");
7384 WorkListRemover DeadNodes(*this);
7385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7387 DAG.getUNDEF(N->getValueType(1)));
7388 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7389 removeFromWorkList(N);
7391 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7396 // If this load is directly stored, replace the load value with the stored
7398 // TODO: Handle store large -> read small portion.
7399 // TODO: Handle TRUNCSTORE/LOADEXT
7400 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7401 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7402 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7403 if (PrevST->getBasePtr() == Ptr &&
7404 PrevST->getValue().getValueType() == N->getValueType(0))
7405 return CombineTo(N, Chain.getOperand(1), Chain);
7409 // Try to infer better alignment information than the load already has.
7410 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7411 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7412 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7414 DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7415 LD->getValueType(0),
7416 Chain, Ptr, LD->getPointerInfo(),
7418 LD->isVolatile(), LD->isNonTemporal(), Align);
7419 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7425 // Walk up chain skipping non-aliasing memory nodes.
7426 SDValue BetterChain = FindBetterChain(N, Chain);
7428 // If there is a better chain.
7429 if (Chain != BetterChain) {
7432 // Replace the chain to void dependency.
7433 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7434 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7435 BetterChain, Ptr, LD->getPointerInfo(),
7436 LD->isVolatile(), LD->isNonTemporal(),
7437 LD->isInvariant(), LD->getAlignment());
7439 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7440 LD->getValueType(0),
7441 BetterChain, Ptr, LD->getPointerInfo(),
7444 LD->isNonTemporal(),
7445 LD->getAlignment());
7448 // Create token factor to keep old chain connected.
7449 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7450 MVT::Other, Chain, ReplLoad.getValue(1));
7452 // Make sure the new and old chains are cleaned up.
7453 AddToWorkList(Token.getNode());
7455 // Replace uses with load result and token factor. Don't add users
7457 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7461 // Try transforming N to an indexed load.
7462 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7463 return SDValue(N, 0);
7468 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7469 /// load is having specific bytes cleared out. If so, return the byte size
7470 /// being masked out and the shift amount.
7471 static std::pair<unsigned, unsigned>
7472 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7473 std::pair<unsigned, unsigned> Result(0, 0);
7475 // Check for the structure we're looking for.
7476 if (V->getOpcode() != ISD::AND ||
7477 !isa<ConstantSDNode>(V->getOperand(1)) ||
7478 !ISD::isNormalLoad(V->getOperand(0).getNode()))
7481 // Check the chain and pointer.
7482 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7483 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
7485 // The store should be chained directly to the load or be an operand of a
7487 if (LD == Chain.getNode())
7489 else if (Chain->getOpcode() != ISD::TokenFactor)
7490 return Result; // Fail.
7493 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7494 if (Chain->getOperand(i).getNode() == LD) {
7498 if (!isOk) return Result;
7501 // This only handles simple types.
7502 if (V.getValueType() != MVT::i16 &&
7503 V.getValueType() != MVT::i32 &&
7504 V.getValueType() != MVT::i64)
7507 // Check the constant mask. Invert it so that the bits being masked out are
7508 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
7509 // follow the sign bit for uniformity.
7510 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7511 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7512 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
7513 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7514 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
7515 if (NotMaskLZ == 64) return Result; // All zero mask.
7517 // See if we have a continuous run of bits. If so, we have 0*1+0*
7518 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7521 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7522 if (V.getValueType() != MVT::i64 && NotMaskLZ)
7523 NotMaskLZ -= 64-V.getValueSizeInBits();
7525 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7526 switch (MaskedBytes) {
7530 default: return Result; // All one mask, or 5-byte mask.
7533 // Verify that the first bit starts at a multiple of mask so that the access
7534 // is aligned the same as the access width.
7535 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7537 Result.first = MaskedBytes;
7538 Result.second = NotMaskTZ/8;
7543 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7544 /// provides a value as specified by MaskInfo. If so, replace the specified
7545 /// store with a narrower store of truncated IVal.
7547 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7548 SDValue IVal, StoreSDNode *St,
7550 unsigned NumBytes = MaskInfo.first;
7551 unsigned ByteShift = MaskInfo.second;
7552 SelectionDAG &DAG = DC->getDAG();
7554 // Check to see if IVal is all zeros in the part being masked in by the 'or'
7555 // that uses this. If not, this is not a replacement.
7556 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7557 ByteShift*8, (ByteShift+NumBytes)*8);
7558 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7560 // Check that it is legal on the target to do this. It is legal if the new
7561 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7563 MVT VT = MVT::getIntegerVT(NumBytes*8);
7564 if (!DC->isTypeLegal(VT))
7567 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
7568 // shifted by ByteShift and truncated down to NumBytes.
7570 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7571 DAG.getConstant(ByteShift*8,
7572 DC->getShiftAmountTy(IVal.getValueType())));
7574 // Figure out the offset for the store and the alignment of the access.
7576 unsigned NewAlign = St->getAlignment();
7578 if (DAG.getTargetLoweringInfo().isLittleEndian())
7579 StOffset = ByteShift;
7581 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7583 SDValue Ptr = St->getBasePtr();
7585 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7586 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7587 NewAlign = MinAlign(NewAlign, StOffset);
7590 // Truncate down to the new size.
7591 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7594 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7595 St->getPointerInfo().getWithOffset(StOffset),
7596 false, false, NewAlign).getNode();
7600 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7601 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7602 /// of the loaded bits, try narrowing the load and store if it would end up
7603 /// being a win for performance or code size.
7604 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7605 StoreSDNode *ST = cast<StoreSDNode>(N);
7606 if (ST->isVolatile())
7609 SDValue Chain = ST->getChain();
7610 SDValue Value = ST->getValue();
7611 SDValue Ptr = ST->getBasePtr();
7612 EVT VT = Value.getValueType();
7614 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7617 unsigned Opc = Value.getOpcode();
7619 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7620 // is a byte mask indicating a consecutive number of bytes, check to see if
7621 // Y is known to provide just those bytes. If so, we try to replace the
7622 // load + replace + store sequence with a single (narrower) store, which makes
7624 if (Opc == ISD::OR) {
7625 std::pair<unsigned, unsigned> MaskedLoad;
7626 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7627 if (MaskedLoad.first)
7628 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7629 Value.getOperand(1), ST,this))
7630 return SDValue(NewST, 0);
7632 // Or is commutative, so try swapping X and Y.
7633 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7634 if (MaskedLoad.first)
7635 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7636 Value.getOperand(0), ST,this))
7637 return SDValue(NewST, 0);
7640 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7641 Value.getOperand(1).getOpcode() != ISD::Constant)
7644 SDValue N0 = Value.getOperand(0);
7645 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7646 Chain == SDValue(N0.getNode(), 1)) {
7647 LoadSDNode *LD = cast<LoadSDNode>(N0);
7648 if (LD->getBasePtr() != Ptr ||
7649 LD->getPointerInfo().getAddrSpace() !=
7650 ST->getPointerInfo().getAddrSpace())
7653 // Find the type to narrow it the load / op / store to.
7654 SDValue N1 = Value.getOperand(1);
7655 unsigned BitWidth = N1.getValueSizeInBits();
7656 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7657 if (Opc == ISD::AND)
7658 Imm ^= APInt::getAllOnesValue(BitWidth);
7659 if (Imm == 0 || Imm.isAllOnesValue())
7661 unsigned ShAmt = Imm.countTrailingZeros();
7662 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7663 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7664 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7665 while (NewBW < BitWidth &&
7666 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7667 TLI.isNarrowingProfitable(VT, NewVT))) {
7668 NewBW = NextPowerOf2(NewBW);
7669 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7671 if (NewBW >= BitWidth)
7674 // If the lsb changed does not start at the type bitwidth boundary,
7675 // start at the previous one.
7677 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7678 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7679 std::min(BitWidth, ShAmt + NewBW));
7680 if ((Imm & Mask) == Imm) {
7681 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7682 if (Opc == ISD::AND)
7683 NewImm ^= APInt::getAllOnesValue(NewBW);
7684 uint64_t PtrOff = ShAmt / 8;
7685 // For big endian targets, we need to adjust the offset to the pointer to
7686 // load the correct bytes.
7687 if (TLI.isBigEndian())
7688 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7690 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7691 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7692 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7695 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7696 Ptr.getValueType(), Ptr,
7697 DAG.getConstant(PtrOff, Ptr.getValueType()));
7698 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7699 LD->getChain(), NewPtr,
7700 LD->getPointerInfo().getWithOffset(PtrOff),
7701 LD->isVolatile(), LD->isNonTemporal(),
7702 LD->isInvariant(), NewAlign);
7703 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7704 DAG.getConstant(NewImm, NewVT));
7705 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7707 ST->getPointerInfo().getWithOffset(PtrOff),
7708 false, false, NewAlign);
7710 AddToWorkList(NewPtr.getNode());
7711 AddToWorkList(NewLD.getNode());
7712 AddToWorkList(NewVal.getNode());
7713 WorkListRemover DeadNodes(*this);
7714 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7723 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7724 /// if the load value isn't used by any other operations, then consider
7725 /// transforming the pair to integer load / store operations if the target
7726 /// deems the transformation profitable.
7727 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7728 StoreSDNode *ST = cast<StoreSDNode>(N);
7729 SDValue Chain = ST->getChain();
7730 SDValue Value = ST->getValue();
7731 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7732 Value.hasOneUse() &&
7733 Chain == SDValue(Value.getNode(), 1)) {
7734 LoadSDNode *LD = cast<LoadSDNode>(Value);
7735 EVT VT = LD->getMemoryVT();
7736 if (!VT.isFloatingPoint() ||
7737 VT != ST->getMemoryVT() ||
7738 LD->isNonTemporal() ||
7739 ST->isNonTemporal() ||
7740 LD->getPointerInfo().getAddrSpace() != 0 ||
7741 ST->getPointerInfo().getAddrSpace() != 0)
7744 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7745 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7746 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7747 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7748 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7751 unsigned LDAlign = LD->getAlignment();
7752 unsigned STAlign = ST->getAlignment();
7753 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7754 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7755 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7758 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7759 LD->getChain(), LD->getBasePtr(),
7760 LD->getPointerInfo(),
7761 false, false, false, LDAlign);
7763 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7764 NewLD, ST->getBasePtr(),
7765 ST->getPointerInfo(),
7766 false, false, STAlign);
7768 AddToWorkList(NewLD.getNode());
7769 AddToWorkList(NewST.getNode());
7770 WorkListRemover DeadNodes(*this);
7771 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7779 /// Helper struct to parse and store a memory address as base + index + offset.
7780 /// We ignore sign extensions when it is safe to do so.
7781 /// The following two expressions are not equivalent. To differentiate we need
7782 /// to store whether there was a sign extension involved in the index
7784 /// (load (i64 add (i64 copyfromreg %c)
7785 /// (i64 signextend (add (i8 load %index)
7789 /// (load (i64 add (i64 copyfromreg %c)
7790 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
7792 struct BaseIndexOffset {
7796 bool IsIndexSignExt;
7798 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7800 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7801 bool IsIndexSignExt) :
7802 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7804 bool equalBaseIndex(const BaseIndexOffset &Other) {
7805 return Other.Base == Base && Other.Index == Index &&
7806 Other.IsIndexSignExt == IsIndexSignExt;
7809 /// Parses tree in Ptr for base, index, offset addresses.
7810 static BaseIndexOffset match(SDValue Ptr) {
7811 bool IsIndexSignExt = false;
7813 // Just Base or possibly anything else.
7814 if (Ptr->getOpcode() != ISD::ADD)
7815 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7818 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7819 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7820 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7824 // Look at Base + Index + Offset cases.
7825 SDValue Base = Ptr->getOperand(0);
7826 SDValue IndexOffset = Ptr->getOperand(1);
7828 // Skip signextends.
7829 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7830 IndexOffset = IndexOffset->getOperand(0);
7831 IsIndexSignExt = true;
7834 // Either the case of Base + Index (no offset) or something else.
7835 if (IndexOffset->getOpcode() != ISD::ADD)
7836 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7838 // Now we have the case of Base + Index + offset.
7839 SDValue Index = IndexOffset->getOperand(0);
7840 SDValue Offset = IndexOffset->getOperand(1);
7842 if (!isa<ConstantSDNode>(Offset))
7843 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7845 // Ignore signextends.
7846 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7847 Index = Index->getOperand(0);
7848 IsIndexSignExt = true;
7849 } else IsIndexSignExt = false;
7851 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7852 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7856 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7857 /// is located in a sequence of memory operations connected by a chain.
7859 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7860 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7861 // Ptr to the mem node.
7862 LSBaseSDNode *MemNode;
7863 // Offset from the base ptr.
7864 int64_t OffsetFromBase;
7865 // What is the sequence number of this mem node.
7866 // Lowest mem operand in the DAG starts at zero.
7867 unsigned SequenceNum;
7870 /// Sorts store nodes in a link according to their offset from a shared
7872 struct ConsecutiveMemoryChainSorter {
7873 bool operator()(MemOpLink LHS, MemOpLink RHS) {
7874 return LHS.OffsetFromBase < RHS.OffsetFromBase;
7878 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7879 EVT MemVT = St->getMemoryVT();
7880 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7881 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7882 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7884 // Don't merge vectors into wider inputs.
7885 if (MemVT.isVector() || !MemVT.isSimple())
7888 // Perform an early exit check. Do not bother looking at stored values that
7889 // are not constants or loads.
7890 SDValue StoredVal = St->getValue();
7891 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7892 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7896 // Only look at ends of store sequences.
7897 SDValue Chain = SDValue(St, 1);
7898 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7901 // This holds the base pointer, index, and the offset in bytes from the base
7903 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7905 // We must have a base and an offset.
7906 if (!BasePtr.Base.getNode())
7909 // Do not handle stores to undef base pointers.
7910 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7913 // Save the LoadSDNodes that we find in the chain.
7914 // We need to make sure that these nodes do not interfere with
7915 // any of the store nodes.
7916 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7918 // Save the StoreSDNodes that we find in the chain.
7919 SmallVector<MemOpLink, 8> StoreNodes;
7921 // Walk up the chain and look for nodes with offsets from the same
7922 // base pointer. Stop when reaching an instruction with a different kind
7923 // or instruction which has a different base pointer.
7925 StoreSDNode *Index = St;
7927 // If the chain has more than one use, then we can't reorder the mem ops.
7928 if (Index != St && !SDValue(Index, 1)->hasOneUse())
7931 // Find the base pointer and offset for this memory node.
7932 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7934 // Check that the base pointer is the same as the original one.
7935 if (!Ptr.equalBaseIndex(BasePtr))
7938 // Check that the alignment is the same.
7939 if (Index->getAlignment() != St->getAlignment())
7942 // The memory operands must not be volatile.
7943 if (Index->isVolatile() || Index->isIndexed())
7947 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7948 if (St->isTruncatingStore())
7951 // The stored memory type must be the same.
7952 if (Index->getMemoryVT() != MemVT)
7955 // We do not allow unaligned stores because we want to prevent overriding
7957 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7960 // We found a potential memory operand to merge.
7961 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
7963 // Find the next memory operand in the chain. If the next operand in the
7964 // chain is a store then move up and continue the scan with the next
7965 // memory operand. If the next operand is a load save it and use alias
7966 // information to check if it interferes with anything.
7967 SDNode *NextInChain = Index->getChain().getNode();
7969 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7970 // We found a store node. Use it for the next iteration.
7973 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
7974 // Save the load node for later. Continue the scan.
7975 AliasLoadNodes.push_back(Ldn);
7976 NextInChain = Ldn->getChain().getNode();
7985 // Check if there is anything to merge.
7986 if (StoreNodes.size() < 2)
7989 // Sort the memory operands according to their distance from the base pointer.
7990 std::sort(StoreNodes.begin(), StoreNodes.end(),
7991 ConsecutiveMemoryChainSorter());
7993 // Scan the memory operations on the chain and find the first non-consecutive
7994 // store memory address.
7995 unsigned LastConsecutiveStore = 0;
7996 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
7997 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
7999 // Check that the addresses are consecutive starting from the second
8000 // element in the list of stores.
8002 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8003 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8008 // Check if this store interferes with any of the loads that we found.
8009 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8010 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8014 // We found a load that alias with this store. Stop the sequence.
8018 // Mark this node as useful.
8019 LastConsecutiveStore = i;
8022 // The node with the lowest store address.
8023 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8025 // Store the constants into memory as one consecutive store.
8027 unsigned LastLegalType = 0;
8028 unsigned LastLegalVectorType = 0;
8029 bool NonZero = false;
8030 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8031 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8032 SDValue StoredVal = St->getValue();
8034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8035 NonZero |= !C->isNullValue();
8036 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8037 NonZero |= !C->getConstantFPValue()->isNullValue();
8043 // Find a legal type for the constant store.
8044 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8045 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8046 if (TLI.isTypeLegal(StoreTy))
8047 LastLegalType = i+1;
8048 // Or check whether a truncstore is legal.
8049 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8050 TargetLowering::TypePromoteInteger) {
8051 EVT LegalizedStoredValueTy =
8052 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8053 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8054 LastLegalType = i+1;
8057 // Find a legal type for the vector store.
8058 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8059 if (TLI.isTypeLegal(Ty))
8060 LastLegalVectorType = i + 1;
8063 // We only use vectors if the constant is known to be zero and the
8064 // function is not marked with the noimplicitfloat attribute.
8065 if (NonZero || NoVectors)
8066 LastLegalVectorType = 0;
8068 // Check if we found a legal integer type to store.
8069 if (LastLegalType == 0 && LastLegalVectorType == 0)
8072 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8073 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8075 // Make sure we have something to merge.
8079 unsigned EarliestNodeUsed = 0;
8080 for (unsigned i=0; i < NumElem; ++i) {
8081 // Find a chain for the new wide-store operand. Notice that some
8082 // of the store nodes that we found may not be selected for inclusion
8083 // in the wide store. The chain we use needs to be the chain of the
8084 // earliest store node which is *used* and replaced by the wide store.
8085 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8086 EarliestNodeUsed = i;
8089 // The earliest Node in the DAG.
8090 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8091 DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
8095 // Find a legal type for the vector store.
8096 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8097 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8098 StoredVal = DAG.getConstant(0, Ty);
8100 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8101 APInt StoreInt(StoreBW, 0);
8103 // Construct a single integer constant which is made of the smaller
8105 bool IsLE = TLI.isLittleEndian();
8106 for (unsigned i = 0; i < NumElem ; ++i) {
8107 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8108 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8109 SDValue Val = St->getValue();
8110 StoreInt<<=ElementSizeBytes*8;
8111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8112 StoreInt|=C->getAPIntValue().zext(StoreBW);
8113 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8114 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8116 assert(false && "Invalid constant element type");
8120 // Create the new Load and Store operations.
8121 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8122 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8125 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8126 FirstInChain->getBasePtr(),
8127 FirstInChain->getPointerInfo(),
8129 FirstInChain->getAlignment());
8131 // Replace the first store with the new store
8132 CombineTo(EarliestOp, NewStore);
8133 // Erase all other stores.
8134 for (unsigned i = 0; i < NumElem ; ++i) {
8135 if (StoreNodes[i].MemNode == EarliestOp)
8137 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8138 // ReplaceAllUsesWith will replace all uses that existed when it was
8139 // called, but graph optimizations may cause new ones to appear. For
8140 // example, the case in pr14333 looks like
8142 // St's chain -> St -> another store -> X
8144 // And the only difference from St to the other store is the chain.
8145 // When we change it's chain to be St's chain they become identical,
8146 // get CSEed and the net result is that X is now a use of St.
8147 // Since we know that St is redundant, just iterate.
8148 while (!St->use_empty())
8149 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8150 removeFromWorkList(St);
8157 // Below we handle the case of multiple consecutive stores that
8158 // come from multiple consecutive loads. We merge them into a single
8159 // wide load and a single wide store.
8161 // Look for load nodes which are used by the stored values.
8162 SmallVector<MemOpLink, 8> LoadNodes;
8164 // Find acceptable loads. Loads need to have the same chain (token factor),
8165 // must not be zext, volatile, indexed, and they must be consecutive.
8166 BaseIndexOffset LdBasePtr;
8167 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8168 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8169 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8172 // Loads must only have one use.
8173 if (!Ld->hasNUsesOfValue(1, 0))
8176 // Check that the alignment is the same as the stores.
8177 if (Ld->getAlignment() != St->getAlignment())
8180 // The memory operands must not be volatile.
8181 if (Ld->isVolatile() || Ld->isIndexed())
8184 // We do not accept ext loads.
8185 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8188 // The stored memory type must be the same.
8189 if (Ld->getMemoryVT() != MemVT)
8192 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8193 // If this is not the first ptr that we check.
8194 if (LdBasePtr.Base.getNode()) {
8195 // The base ptr must be the same.
8196 if (!LdPtr.equalBaseIndex(LdBasePtr))
8199 // Check that all other base pointers are the same as this one.
8203 // We found a potential memory operand to merge.
8204 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8207 if (LoadNodes.size() < 2)
8210 // Scan the memory operations on the chain and find the first non-consecutive
8211 // load memory address. These variables hold the index in the store node
8213 unsigned LastConsecutiveLoad = 0;
8214 // This variable refers to the size and not index in the array.
8215 unsigned LastLegalVectorType = 0;
8216 unsigned LastLegalIntegerType = 0;
8217 StartAddress = LoadNodes[0].OffsetFromBase;
8218 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8219 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8220 // All loads much share the same chain.
8221 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8224 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8225 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8227 LastConsecutiveLoad = i;
8229 // Find a legal type for the vector store.
8230 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8231 if (TLI.isTypeLegal(StoreTy))
8232 LastLegalVectorType = i + 1;
8234 // Find a legal type for the integer store.
8235 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8236 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8237 if (TLI.isTypeLegal(StoreTy))
8238 LastLegalIntegerType = i + 1;
8239 // Or check whether a truncstore and extload is legal.
8240 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8241 TargetLowering::TypePromoteInteger) {
8242 EVT LegalizedStoredValueTy =
8243 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8244 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8245 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8246 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8247 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8248 LastLegalIntegerType = i+1;
8252 // Only use vector types if the vector type is larger than the integer type.
8253 // If they are the same, use integers.
8254 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8255 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8257 // We add +1 here because the LastXXX variables refer to location while
8258 // the NumElem refers to array/index size.
8259 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8260 NumElem = std::min(LastLegalType, NumElem);
8265 // The earliest Node in the DAG.
8266 unsigned EarliestNodeUsed = 0;
8267 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8268 for (unsigned i=1; i<NumElem; ++i) {
8269 // Find a chain for the new wide-store operand. Notice that some
8270 // of the store nodes that we found may not be selected for inclusion
8271 // in the wide store. The chain we use needs to be the chain of the
8272 // earliest store node which is *used* and replaced by the wide store.
8273 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8274 EarliestNodeUsed = i;
8277 // Find if it is better to use vectors or integers to load and store
8281 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8283 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8284 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8287 DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
8288 DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
8290 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8291 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8292 FirstLoad->getChain(),
8293 FirstLoad->getBasePtr(),
8294 FirstLoad->getPointerInfo(),
8295 false, false, false,
8296 FirstLoad->getAlignment());
8298 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8299 FirstInChain->getBasePtr(),
8300 FirstInChain->getPointerInfo(), false, false,
8301 FirstInChain->getAlignment());
8303 // Replace one of the loads with the new load.
8304 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8305 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8306 SDValue(NewLoad.getNode(), 1));
8308 // Remove the rest of the load chains.
8309 for (unsigned i = 1; i < NumElem ; ++i) {
8310 // Replace all chain users of the old load nodes with the chain of the new
8312 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8313 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8316 // Replace the first store with the new store.
8317 CombineTo(EarliestOp, NewStore);
8318 // Erase all other stores.
8319 for (unsigned i = 0; i < NumElem ; ++i) {
8320 // Remove all Store nodes.
8321 if (StoreNodes[i].MemNode == EarliestOp)
8323 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8324 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8325 removeFromWorkList(St);
8332 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8333 StoreSDNode *ST = cast<StoreSDNode>(N);
8334 SDValue Chain = ST->getChain();
8335 SDValue Value = ST->getValue();
8336 SDValue Ptr = ST->getBasePtr();
8338 // If this is a store of a bit convert, store the input value if the
8339 // resultant store does not need a higher alignment than the original.
8340 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8341 ST->isUnindexed()) {
8342 unsigned OrigAlign = ST->getAlignment();
8343 EVT SVT = Value.getOperand(0).getValueType();
8344 unsigned Align = TLI.getDataLayout()->
8345 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8346 if (Align <= OrigAlign &&
8347 ((!LegalOperations && !ST->isVolatile()) ||
8348 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8349 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8350 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8351 ST->isNonTemporal(), OrigAlign);
8354 // Turn 'store undef, Ptr' -> nothing.
8355 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8358 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8359 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8360 // NOTE: If the original store is volatile, this transform must not increase
8361 // the number of stores. For example, on x86-32 an f64 can be stored in one
8362 // processor operation but an i64 (which is not legal) requires two. So the
8363 // transform should not be done in this case.
8364 if (Value.getOpcode() != ISD::TargetConstantFP) {
8366 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8367 default: llvm_unreachable("Unknown FP type");
8368 case MVT::f16: // We don't do this for these yet.
8374 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8375 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8376 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8377 bitcastToAPInt().getZExtValue(), MVT::i32);
8378 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8379 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8380 ST->isNonTemporal(), ST->getAlignment());
8384 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8385 !ST->isVolatile()) ||
8386 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8387 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8388 getZExtValue(), MVT::i64);
8389 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8390 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8391 ST->isNonTemporal(), ST->getAlignment());
8394 if (!ST->isVolatile() &&
8395 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8396 // Many FP stores are not made apparent until after legalize, e.g. for
8397 // argument passing. Since this is so common, custom legalize the
8398 // 64-bit integer store into two 32-bit stores.
8399 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8400 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8401 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8402 if (TLI.isBigEndian()) std::swap(Lo, Hi);
8404 unsigned Alignment = ST->getAlignment();
8405 bool isVolatile = ST->isVolatile();
8406 bool isNonTemporal = ST->isNonTemporal();
8408 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
8409 Ptr, ST->getPointerInfo(),
8410 isVolatile, isNonTemporal,
8411 ST->getAlignment());
8412 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
8413 DAG.getConstant(4, Ptr.getValueType()));
8414 Alignment = MinAlign(Alignment, 4U);
8415 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
8416 Ptr, ST->getPointerInfo().getWithOffset(4),
8417 isVolatile, isNonTemporal,
8419 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8428 // Try to infer better alignment information than the store already has.
8429 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8430 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8431 if (Align > ST->getAlignment())
8432 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
8433 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8434 ST->isVolatile(), ST->isNonTemporal(), Align);
8438 // Try transforming a pair floating point load / store ops to integer
8439 // load / store ops.
8440 SDValue NewST = TransformFPLoadStorePair(N);
8441 if (NewST.getNode())
8445 // Walk up chain skipping non-aliasing memory nodes.
8446 SDValue BetterChain = FindBetterChain(N, Chain);
8448 // If there is a better chain.
8449 if (Chain != BetterChain) {
8452 // Replace the chain to avoid dependency.
8453 if (ST->isTruncatingStore()) {
8454 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8455 ST->getPointerInfo(),
8456 ST->getMemoryVT(), ST->isVolatile(),
8457 ST->isNonTemporal(), ST->getAlignment());
8459 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8460 ST->getPointerInfo(),
8461 ST->isVolatile(), ST->isNonTemporal(),
8462 ST->getAlignment());
8465 // Create token to keep both nodes around.
8466 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
8467 MVT::Other, Chain, ReplStore);
8469 // Make sure the new and old chains are cleaned up.
8470 AddToWorkList(Token.getNode());
8472 // Don't add users to work list.
8473 return CombineTo(N, Token, false);
8477 // Try transforming N to an indexed store.
8478 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8479 return SDValue(N, 0);
8481 // FIXME: is there such a thing as a truncating indexed store?
8482 if (ST->isTruncatingStore() && ST->isUnindexed() &&
8483 Value.getValueType().isInteger()) {
8484 // See if we can simplify the input to this truncstore with knowledge that
8485 // only the low bits are being used. For example:
8486 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
8488 GetDemandedBits(Value,
8489 APInt::getLowBitsSet(
8490 Value.getValueType().getScalarType().getSizeInBits(),
8491 ST->getMemoryVT().getScalarType().getSizeInBits()));
8492 AddToWorkList(Value.getNode());
8493 if (Shorter.getNode())
8494 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
8495 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8496 ST->isVolatile(), ST->isNonTemporal(),
8497 ST->getAlignment());
8499 // Otherwise, see if we can simplify the operation with
8500 // SimplifyDemandedBits, which only works if the value has a single use.
8501 if (SimplifyDemandedBits(Value,
8502 APInt::getLowBitsSet(
8503 Value.getValueType().getScalarType().getSizeInBits(),
8504 ST->getMemoryVT().getScalarType().getSizeInBits())))
8505 return SDValue(N, 0);
8508 // If this is a load followed by a store to the same location, then the store
8510 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8511 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8512 ST->isUnindexed() && !ST->isVolatile() &&
8513 // There can't be any side effects between the load and store, such as
8515 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8516 // The store is dead, remove it.
8521 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8522 // truncating store. We can do this even if this is already a truncstore.
8523 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8524 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8525 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8526 ST->getMemoryVT())) {
8527 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8528 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8529 ST->isVolatile(), ST->isNonTemporal(),
8530 ST->getAlignment());
8533 // Only perform this optimization before the types are legal, because we
8534 // don't want to perform this optimization on every DAGCombine invocation.
8536 bool EverChanged = false;
8539 // There can be multiple store sequences on the same chain.
8540 // Keep trying to merge store sequences until we are unable to do so
8541 // or until we merge the last store on the chain.
8542 bool Changed = MergeConsecutiveStores(ST);
8543 EverChanged |= Changed;
8544 if (!Changed) break;
8545 } while (ST->getOpcode() != ISD::DELETED_NODE);
8548 return SDValue(N, 0);
8551 return ReduceLoadOpStoreWidth(N);
8554 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8555 SDValue InVec = N->getOperand(0);
8556 SDValue InVal = N->getOperand(1);
8557 SDValue EltNo = N->getOperand(2);
8558 DebugLoc dl = N->getDebugLoc();
8560 // If the inserted element is an UNDEF, just use the input vector.
8561 if (InVal.getOpcode() == ISD::UNDEF)
8564 EVT VT = InVec.getValueType();
8566 // If we can't generate a legal BUILD_VECTOR, exit
8567 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8570 // Check that we know which element is being inserted
8571 if (!isa<ConstantSDNode>(EltNo))
8573 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8575 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8576 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
8578 SmallVector<SDValue, 8> Ops;
8579 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8580 Ops.append(InVec.getNode()->op_begin(),
8581 InVec.getNode()->op_end());
8582 } else if (InVec.getOpcode() == ISD::UNDEF) {
8583 unsigned NElts = VT.getVectorNumElements();
8584 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8589 // Insert the element
8590 if (Elt < Ops.size()) {
8591 // All the operands of BUILD_VECTOR must have the same type;
8592 // we enforce that here.
8593 EVT OpVT = Ops[0].getValueType();
8594 if (InVal.getValueType() != OpVT)
8595 InVal = OpVT.bitsGT(InVal.getValueType()) ?
8596 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8597 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8601 // Return the new vector
8602 return DAG.getNode(ISD::BUILD_VECTOR, dl,
8603 VT, &Ops[0], Ops.size());
8606 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8607 // (vextract (scalar_to_vector val, 0) -> val
8608 SDValue InVec = N->getOperand(0);
8609 EVT VT = InVec.getValueType();
8610 EVT NVT = N->getValueType(0);
8612 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8613 // Check if the result type doesn't match the inserted element type. A
8614 // SCALAR_TO_VECTOR may truncate the inserted element and the
8615 // EXTRACT_VECTOR_ELT may widen the extracted vector.
8616 SDValue InOp = InVec.getOperand(0);
8617 if (InOp.getValueType() != NVT) {
8618 assert(InOp.getValueType().isInteger() && NVT.isInteger());
8619 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
8624 SDValue EltNo = N->getOperand(1);
8625 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8627 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8628 // We only perform this optimization before the op legalization phase because
8629 // we may introduce new vector instructions which are not backed by TD
8630 // patterns. For example on AVX, extracting elements from a wide vector
8631 // without using extract_subvector.
8632 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8633 && ConstEltNo && !LegalOperations) {
8634 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8635 int NumElem = VT.getVectorNumElements();
8636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8637 // Find the new index to extract from.
8638 int OrigElt = SVOp->getMaskElt(Elt);
8640 // Extracting an undef index is undef.
8642 return DAG.getUNDEF(NVT);
8644 // Select the right vector half to extract from.
8645 if (OrigElt < NumElem) {
8646 InVec = InVec->getOperand(0);
8648 InVec = InVec->getOperand(1);
8652 EVT IndexTy = N->getOperand(1).getValueType();
8653 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
8654 InVec, DAG.getConstant(OrigElt, IndexTy));
8657 // Perform only after legalization to ensure build_vector / vector_shuffle
8658 // optimizations have already been done.
8659 if (!LegalOperations) return SDValue();
8661 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8662 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8663 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8666 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8667 bool NewLoad = false;
8668 bool BCNumEltsChanged = false;
8669 EVT ExtVT = VT.getVectorElementType();
8672 // If the result of load has to be truncated, then it's not necessarily
8674 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8677 if (InVec.getOpcode() == ISD::BITCAST) {
8678 // Don't duplicate a load with other uses.
8679 if (!InVec.hasOneUse())
8682 EVT BCVT = InVec.getOperand(0).getValueType();
8683 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8685 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8686 BCNumEltsChanged = true;
8687 InVec = InVec.getOperand(0);
8688 ExtVT = BCVT.getVectorElementType();
8692 LoadSDNode *LN0 = NULL;
8693 const ShuffleVectorSDNode *SVN = NULL;
8694 if (ISD::isNormalLoad(InVec.getNode())) {
8695 LN0 = cast<LoadSDNode>(InVec);
8696 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8697 InVec.getOperand(0).getValueType() == ExtVT &&
8698 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8699 // Don't duplicate a load with other uses.
8700 if (!InVec.hasOneUse())
8703 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8704 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8705 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8707 // (load $addr+1*size)
8709 // Don't duplicate a load with other uses.
8710 if (!InVec.hasOneUse())
8713 // If the bit convert changed the number of elements, it is unsafe
8714 // to examine the mask.
8715 if (BCNumEltsChanged)
8718 // Select the input vector, guarding against out of range extract vector.
8719 unsigned NumElems = VT.getVectorNumElements();
8720 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8721 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8723 if (InVec.getOpcode() == ISD::BITCAST) {
8724 // Don't duplicate a load with other uses.
8725 if (!InVec.hasOneUse())
8728 InVec = InVec.getOperand(0);
8730 if (ISD::isNormalLoad(InVec.getNode())) {
8731 LN0 = cast<LoadSDNode>(InVec);
8732 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8736 // Make sure we found a non-volatile load and the extractelement is
8738 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8741 // If Idx was -1 above, Elt is going to be -1, so just return undef.
8743 return DAG.getUNDEF(LVT);
8745 unsigned Align = LN0->getAlignment();
8747 // Check the resultant load doesn't need a higher alignment than the
8751 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8753 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8759 SDValue NewPtr = LN0->getBasePtr();
8760 unsigned PtrOff = 0;
8763 PtrOff = LVT.getSizeInBits() * Elt / 8;
8764 EVT PtrType = NewPtr.getValueType();
8765 if (TLI.isBigEndian())
8766 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8767 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8768 DAG.getConstant(PtrOff, PtrType));
8771 // The replacement we need to do here is a little tricky: we need to
8772 // replace an extractelement of a load with a load.
8773 // Use ReplaceAllUsesOfValuesWith to do the replacement.
8774 // Note that this replacement assumes that the extractvalue is the only
8775 // use of the load; that's okay because we don't want to perform this
8776 // transformation in other cases anyway.
8779 if (NVT.bitsGT(LVT)) {
8780 // If the result type of vextract is wider than the load, then issue an
8781 // extending load instead.
8782 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8783 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8784 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8785 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8786 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8787 Chain = Load.getValue(1);
8789 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8790 LN0->getPointerInfo().getWithOffset(PtrOff),
8791 LN0->isVolatile(), LN0->isNonTemporal(),
8792 LN0->isInvariant(), Align);
8793 Chain = Load.getValue(1);
8794 if (NVT.bitsLT(LVT))
8795 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8797 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8799 WorkListRemover DeadNodes(*this);
8800 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8801 SDValue To[] = { Load, Chain };
8802 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8803 // Since we're explcitly calling ReplaceAllUses, add the new node to the
8804 // worklist explicitly as well.
8805 AddToWorkList(Load.getNode());
8806 AddUsersToWorkList(Load.getNode()); // Add users too
8807 // Make sure to revisit this node to clean it up; it will usually be dead.
8809 return SDValue(N, 0);
8815 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8816 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8817 // We perform this optimization post type-legalization because
8818 // the type-legalizer often scalarizes integer-promoted vectors.
8819 // Performing this optimization before may create bit-casts which
8820 // will be type-legalized to complex code sequences.
8821 // We perform this optimization only before the operation legalizer because we
8822 // may introduce illegal operations.
8823 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8826 unsigned NumInScalars = N->getNumOperands();
8827 DebugLoc dl = N->getDebugLoc();
8828 EVT VT = N->getValueType(0);
8830 // Check to see if this is a BUILD_VECTOR of a bunch of values
8831 // which come from any_extend or zero_extend nodes. If so, we can create
8832 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8833 // optimizations. We do not handle sign-extend because we can't fill the sign
8835 EVT SourceType = MVT::Other;
8836 bool AllAnyExt = true;
8838 for (unsigned i = 0; i != NumInScalars; ++i) {
8839 SDValue In = N->getOperand(i);
8840 // Ignore undef inputs.
8841 if (In.getOpcode() == ISD::UNDEF) continue;
8843 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
8844 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8846 // Abort if the element is not an extension.
8847 if (!ZeroExt && !AnyExt) {
8848 SourceType = MVT::Other;
8852 // The input is a ZeroExt or AnyExt. Check the original type.
8853 EVT InTy = In.getOperand(0).getValueType();
8855 // Check that all of the widened source types are the same.
8856 if (SourceType == MVT::Other)
8859 else if (InTy != SourceType) {
8860 // Multiple income types. Abort.
8861 SourceType = MVT::Other;
8865 // Check if all of the extends are ANY_EXTENDs.
8866 AllAnyExt &= AnyExt;
8869 // In order to have valid types, all of the inputs must be extended from the
8870 // same source type and all of the inputs must be any or zero extend.
8871 // Scalar sizes must be a power of two.
8872 EVT OutScalarTy = VT.getScalarType();
8873 bool ValidTypes = SourceType != MVT::Other &&
8874 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8875 isPowerOf2_32(SourceType.getSizeInBits());
8877 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8878 // turn into a single shuffle instruction.
8882 bool isLE = TLI.isLittleEndian();
8883 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8884 assert(ElemRatio > 1 && "Invalid element size ratio");
8885 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8886 DAG.getConstant(0, SourceType);
8888 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8889 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8891 // Populate the new build_vector
8892 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8893 SDValue Cast = N->getOperand(i);
8894 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8895 Cast.getOpcode() == ISD::ZERO_EXTEND ||
8896 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8898 if (Cast.getOpcode() == ISD::UNDEF)
8899 In = DAG.getUNDEF(SourceType);
8901 In = Cast->getOperand(0);
8902 unsigned Index = isLE ? (i * ElemRatio) :
8903 (i * ElemRatio + (ElemRatio - 1));
8905 assert(Index < Ops.size() && "Invalid index");
8909 // The type of the new BUILD_VECTOR node.
8910 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8911 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8912 "Invalid vector size");
8913 // Check if the new vector type is legal.
8914 if (!isTypeLegal(VecVT)) return SDValue();
8916 // Make the new BUILD_VECTOR.
8917 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8919 // The new BUILD_VECTOR node has the potential to be further optimized.
8920 AddToWorkList(BV.getNode());
8921 // Bitcast to the desired type.
8922 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8925 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8926 EVT VT = N->getValueType(0);
8928 unsigned NumInScalars = N->getNumOperands();
8929 DebugLoc dl = N->getDebugLoc();
8931 EVT SrcVT = MVT::Other;
8932 unsigned Opcode = ISD::DELETED_NODE;
8933 unsigned NumDefs = 0;
8935 for (unsigned i = 0; i != NumInScalars; ++i) {
8936 SDValue In = N->getOperand(i);
8937 unsigned Opc = In.getOpcode();
8939 if (Opc == ISD::UNDEF)
8942 // If all scalar values are floats and converted from integers.
8943 if (Opcode == ISD::DELETED_NODE &&
8944 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8951 EVT InVT = In.getOperand(0).getValueType();
8953 // If all scalar values are typed differently, bail out. It's chosen to
8954 // simplify BUILD_VECTOR of integer types.
8955 if (SrcVT == MVT::Other)
8962 // If the vector has just one element defined, it's not worth to fold it into
8963 // a vectorized one.
8967 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8968 && "Should only handle conversion from integer to float.");
8969 assert(SrcVT != MVT::Other && "Cannot determine source type!");
8971 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8973 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
8976 SmallVector<SDValue, 8> Opnds;
8977 for (unsigned i = 0; i != NumInScalars; ++i) {
8978 SDValue In = N->getOperand(i);
8980 if (In.getOpcode() == ISD::UNDEF)
8981 Opnds.push_back(DAG.getUNDEF(SrcVT));
8983 Opnds.push_back(In.getOperand(0));
8985 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8986 &Opnds[0], Opnds.size());
8987 AddToWorkList(BV.getNode());
8989 return DAG.getNode(Opcode, dl, VT, BV);
8992 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8993 unsigned NumInScalars = N->getNumOperands();
8994 DebugLoc dl = N->getDebugLoc();
8995 EVT VT = N->getValueType(0);
8997 // A vector built entirely of undefs is undef.
8998 if (ISD::allOperandsUndef(N))
8999 return DAG.getUNDEF(VT);
9001 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9005 V = reduceBuildVecConvertToConvertBuildVec(N);
9009 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9010 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9011 // at most two distinct vectors, turn this into a shuffle node.
9013 // May only combine to shuffle after legalize if shuffle is legal.
9014 if (LegalOperations &&
9015 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9018 SDValue VecIn1, VecIn2;
9019 for (unsigned i = 0; i != NumInScalars; ++i) {
9020 // Ignore undef inputs.
9021 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9023 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9024 // constant index, bail out.
9025 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9026 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9027 VecIn1 = VecIn2 = SDValue(0, 0);
9031 // We allow up to two distinct input vectors.
9032 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9033 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9036 if (VecIn1.getNode() == 0) {
9037 VecIn1 = ExtractedFromVec;
9038 } else if (VecIn2.getNode() == 0) {
9039 VecIn2 = ExtractedFromVec;
9042 VecIn1 = VecIn2 = SDValue(0, 0);
9047 // If everything is good, we can make a shuffle operation.
9048 if (VecIn1.getNode()) {
9049 SmallVector<int, 8> Mask;
9050 for (unsigned i = 0; i != NumInScalars; ++i) {
9051 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9056 // If extracting from the first vector, just use the index directly.
9057 SDValue Extract = N->getOperand(i);
9058 SDValue ExtVal = Extract.getOperand(1);
9059 if (Extract.getOperand(0) == VecIn1) {
9060 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9061 if (ExtIndex > VT.getVectorNumElements())
9064 Mask.push_back(ExtIndex);
9068 // Otherwise, use InIdx + VecSize
9069 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9070 Mask.push_back(Idx+NumInScalars);
9073 // We can't generate a shuffle node with mismatched input and output types.
9074 // Attempt to transform a single input vector to the correct type.
9075 if ((VT != VecIn1.getValueType())) {
9076 // We don't support shuffeling between TWO values of different types.
9077 if (VecIn2.getNode() != 0)
9080 // We only support widening of vectors which are half the size of the
9081 // output registers. For example XMM->YMM widening on X86 with AVX.
9082 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9085 // If the input vector type has a different base type to the output
9086 // vector type, bail out.
9087 if (VecIn1.getValueType().getVectorElementType() !=
9088 VT.getVectorElementType())
9091 // Widen the input vector by adding undef values.
9092 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9093 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9096 // If VecIn2 is unused then change it to undef.
9097 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9099 // Check that we were able to transform all incoming values to the same
9101 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9102 VecIn1.getValueType() != VT)
9105 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9106 if (!isTypeLegal(VT))
9109 // Return the new VECTOR_SHUFFLE node.
9113 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9119 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9120 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9121 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9122 // inputs come from at most two distinct vectors, turn this into a shuffle
9125 // If we only have one input vector, we don't need to do any concatenation.
9126 if (N->getNumOperands() == 1)
9127 return N->getOperand(0);
9129 // Check if all of the operands are undefs.
9130 if (ISD::allOperandsUndef(N))
9131 return DAG.getUNDEF(N->getValueType(0));
9133 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9134 // nodes often generate nop CONCAT_VECTOR nodes.
9135 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9136 // place the incoming vectors at the exact same location.
9137 SDValue SingleSource = SDValue();
9138 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9140 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9141 SDValue Op = N->getOperand(i);
9143 if (Op.getOpcode() == ISD::UNDEF)
9146 // Check if this is the identity extract:
9147 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9150 // Find the single incoming vector for the extract_subvector.
9151 if (SingleSource.getNode()) {
9152 if (Op.getOperand(0) != SingleSource)
9155 SingleSource = Op.getOperand(0);
9157 // Check the source type is the same as the type of the result.
9158 // If not, this concat may extend the vector, so we can not
9159 // optimize it away.
9160 if (SingleSource.getValueType() != N->getValueType(0))
9164 unsigned IdentityIndex = i * PartNumElem;
9165 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9166 // The extract index must be constant.
9170 // Check that we are reading from the identity index.
9171 if (CS->getZExtValue() != IdentityIndex)
9175 if (SingleSource.getNode())
9176 return SingleSource;
9181 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9182 EVT NVT = N->getValueType(0);
9183 SDValue V = N->getOperand(0);
9185 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9187 // (extract_subvec (concat V1, V2, ...), i)
9190 // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9191 if (V->getOperand(0).getValueType() != NVT)
9193 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9194 unsigned NumElems = NVT.getVectorNumElements();
9195 assert((Idx % NumElems) == 0 &&
9196 "IDX in concat is not a multiple of the result vector length.");
9197 return V->getOperand(Idx / NumElems);
9201 if (V->getOpcode() == ISD::BITCAST)
9202 V = V.getOperand(0);
9204 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9205 DebugLoc dl = N->getDebugLoc();
9206 // Handle only simple case where vector being inserted and vector
9207 // being extracted are of same type, and are half size of larger vectors.
9208 EVT BigVT = V->getOperand(0).getValueType();
9209 EVT SmallVT = V->getOperand(1).getValueType();
9210 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9213 // Only handle cases where both indexes are constants with the same type.
9214 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9215 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9217 if (InsIdx && ExtIdx &&
9218 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9219 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9221 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9223 // indices are equal or bit offsets are equal => V1
9224 // otherwise => (extract_subvec V1, ExtIdx)
9225 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9226 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9227 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9228 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9229 DAG.getNode(ISD::BITCAST, dl,
9230 N->getOperand(0).getValueType(),
9231 V->getOperand(0)), N->getOperand(1));
9238 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9239 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9240 EVT VT = N->getValueType(0);
9241 unsigned NumElts = VT.getVectorNumElements();
9243 SDValue N0 = N->getOperand(0);
9244 SDValue N1 = N->getOperand(1);
9245 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9247 SmallVector<SDValue, 4> Ops;
9248 EVT ConcatVT = N0.getOperand(0).getValueType();
9249 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9250 unsigned NumConcats = NumElts / NumElemsPerConcat;
9252 // Look at every vector that's inserted. We're looking for exact
9253 // subvector-sized copies from a concatenated vector
9254 for (unsigned I = 0; I != NumConcats; ++I) {
9255 // Make sure we're dealing with a copy.
9256 unsigned Begin = I * NumElemsPerConcat;
9257 bool AllUndef = true, NoUndef = true;
9258 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9259 if (SVN->getMaskElt(J) >= 0)
9266 unsigned Begin = I * NumElemsPerConcat;
9267 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9270 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9271 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9274 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9275 if (FirstElt < N0.getNumOperands())
9276 Ops.push_back(N0.getOperand(FirstElt));
9278 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9280 } else if (AllUndef) {
9281 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9282 } else { // Mixed with general masks and undefs, can't do optimization.
9287 return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, Ops.data(),
9291 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9292 EVT VT = N->getValueType(0);
9293 unsigned NumElts = VT.getVectorNumElements();
9295 SDValue N0 = N->getOperand(0);
9296 SDValue N1 = N->getOperand(1);
9298 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9300 // Canonicalize shuffle undef, undef -> undef
9301 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9302 return DAG.getUNDEF(VT);
9304 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9306 // Canonicalize shuffle v, v -> v, undef
9308 SmallVector<int, 8> NewMask;
9309 for (unsigned i = 0; i != NumElts; ++i) {
9310 int Idx = SVN->getMaskElt(i);
9311 if (Idx >= (int)NumElts) Idx -= NumElts;
9312 NewMask.push_back(Idx);
9314 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
9318 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
9319 if (N0.getOpcode() == ISD::UNDEF) {
9320 SmallVector<int, 8> NewMask;
9321 for (unsigned i = 0; i != NumElts; ++i) {
9322 int Idx = SVN->getMaskElt(i);
9324 if (Idx < (int)NumElts)
9329 NewMask.push_back(Idx);
9331 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
9335 // Remove references to rhs if it is undef
9336 if (N1.getOpcode() == ISD::UNDEF) {
9337 bool Changed = false;
9338 SmallVector<int, 8> NewMask;
9339 for (unsigned i = 0; i != NumElts; ++i) {
9340 int Idx = SVN->getMaskElt(i);
9341 if (Idx >= (int)NumElts) {
9345 NewMask.push_back(Idx);
9348 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
9351 // If it is a splat, check if the argument vector is another splat or a
9352 // build_vector with all scalar elements the same.
9353 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9354 SDNode *V = N0.getNode();
9356 // If this is a bit convert that changes the element type of the vector but
9357 // not the number of vector elements, look through it. Be careful not to
9358 // look though conversions that change things like v4f32 to v2f64.
9359 if (V->getOpcode() == ISD::BITCAST) {
9360 SDValue ConvInput = V->getOperand(0);
9361 if (ConvInput.getValueType().isVector() &&
9362 ConvInput.getValueType().getVectorNumElements() == NumElts)
9363 V = ConvInput.getNode();
9366 if (V->getOpcode() == ISD::BUILD_VECTOR) {
9367 assert(V->getNumOperands() == NumElts &&
9368 "BUILD_VECTOR has wrong number of operands");
9370 bool AllSame = true;
9371 for (unsigned i = 0; i != NumElts; ++i) {
9372 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9373 Base = V->getOperand(i);
9377 // Splat of <u, u, u, u>, return <u, u, u, u>
9378 if (!Base.getNode())
9380 for (unsigned i = 0; i != NumElts; ++i) {
9381 if (V->getOperand(i) != Base) {
9386 // Splat of <x, x, x, x>, return <x, x, x, x>
9392 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9393 Level < AfterLegalizeVectorOps &&
9394 (N1.getOpcode() == ISD::UNDEF ||
9395 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9396 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9397 SDValue V = partitionShuffleOfConcats(N, DAG);
9403 // If this shuffle node is simply a swizzle of another shuffle node,
9404 // and it reverses the swizzle of the previous shuffle then we can
9405 // optimize shuffle(shuffle(x, undef), undef) -> x.
9406 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9407 N1.getOpcode() == ISD::UNDEF) {
9409 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9411 // Shuffle nodes can only reverse shuffles with a single non-undef value.
9412 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9415 // The incoming shuffle must be of the same type as the result of the
9417 assert(OtherSV->getOperand(0).getValueType() == VT &&
9418 "Shuffle types don't match");
9420 for (unsigned i = 0; i != NumElts; ++i) {
9421 int Idx = SVN->getMaskElt(i);
9422 assert(Idx < (int)NumElts && "Index references undef operand");
9423 // Next, this index comes from the first value, which is the incoming
9424 // shuffle. Adopt the incoming index.
9426 Idx = OtherSV->getMaskElt(Idx);
9428 // The combined shuffle must map each index to itself.
9429 if (Idx >= 0 && (unsigned)Idx != i)
9433 return OtherSV->getOperand(0);
9439 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9440 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9441 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9442 /// vector_shuffle V, Zero, <0, 4, 2, 4>
9443 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9444 EVT VT = N->getValueType(0);
9445 DebugLoc dl = N->getDebugLoc();
9446 SDValue LHS = N->getOperand(0);
9447 SDValue RHS = N->getOperand(1);
9448 if (N->getOpcode() == ISD::AND) {
9449 if (RHS.getOpcode() == ISD::BITCAST)
9450 RHS = RHS.getOperand(0);
9451 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9452 SmallVector<int, 8> Indices;
9453 unsigned NumElts = RHS.getNumOperands();
9454 for (unsigned i = 0; i != NumElts; ++i) {
9455 SDValue Elt = RHS.getOperand(i);
9456 if (!isa<ConstantSDNode>(Elt))
9459 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9460 Indices.push_back(i);
9461 else if (cast<ConstantSDNode>(Elt)->isNullValue())
9462 Indices.push_back(NumElts);
9467 // Let's see if the target supports this vector_shuffle.
9468 EVT RVT = RHS.getValueType();
9469 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9472 // Return the new VECTOR_SHUFFLE node.
9473 EVT EltVT = RVT.getVectorElementType();
9474 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9475 DAG.getConstant(0, EltVT));
9476 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9477 RVT, &ZeroOps[0], ZeroOps.size());
9478 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9479 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9480 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9487 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9488 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9489 assert(N->getValueType(0).isVector() &&
9490 "SimplifyVBinOp only works on vectors!");
9492 SDValue LHS = N->getOperand(0);
9493 SDValue RHS = N->getOperand(1);
9494 SDValue Shuffle = XformToShuffleWithZero(N);
9495 if (Shuffle.getNode()) return Shuffle;
9497 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9499 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9500 RHS.getOpcode() == ISD::BUILD_VECTOR) {
9501 SmallVector<SDValue, 8> Ops;
9502 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9503 SDValue LHSOp = LHS.getOperand(i);
9504 SDValue RHSOp = RHS.getOperand(i);
9505 // If these two elements can't be folded, bail out.
9506 if ((LHSOp.getOpcode() != ISD::UNDEF &&
9507 LHSOp.getOpcode() != ISD::Constant &&
9508 LHSOp.getOpcode() != ISD::ConstantFP) ||
9509 (RHSOp.getOpcode() != ISD::UNDEF &&
9510 RHSOp.getOpcode() != ISD::Constant &&
9511 RHSOp.getOpcode() != ISD::ConstantFP))
9514 // Can't fold divide by zero.
9515 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9516 N->getOpcode() == ISD::FDIV) {
9517 if ((RHSOp.getOpcode() == ISD::Constant &&
9518 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9519 (RHSOp.getOpcode() == ISD::ConstantFP &&
9520 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9524 EVT VT = LHSOp.getValueType();
9525 EVT RVT = RHSOp.getValueType();
9527 // Integer BUILD_VECTOR operands may have types larger than the element
9528 // size (e.g., when the element type is not legal). Prior to type
9529 // legalization, the types may not match between the two BUILD_VECTORS.
9530 // Truncate one of the operands to make them match.
9531 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9532 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
9534 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
9538 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
9540 if (FoldOp.getOpcode() != ISD::UNDEF &&
9541 FoldOp.getOpcode() != ISD::Constant &&
9542 FoldOp.getOpcode() != ISD::ConstantFP)
9544 Ops.push_back(FoldOp);
9545 AddToWorkList(FoldOp.getNode());
9548 if (Ops.size() == LHS.getNumOperands())
9549 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9550 LHS.getValueType(), &Ops[0], Ops.size());
9556 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9557 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9558 assert(N->getValueType(0).isVector() &&
9559 "SimplifyVUnaryOp only works on vectors!");
9561 SDValue N0 = N->getOperand(0);
9563 if (N0.getOpcode() != ISD::BUILD_VECTOR)
9566 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9567 SmallVector<SDValue, 8> Ops;
9568 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9569 SDValue Op = N0.getOperand(i);
9570 if (Op.getOpcode() != ISD::UNDEF &&
9571 Op.getOpcode() != ISD::ConstantFP)
9573 EVT EltVT = Op.getValueType();
9574 SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
9575 if (FoldOp.getOpcode() != ISD::UNDEF &&
9576 FoldOp.getOpcode() != ISD::ConstantFP)
9578 Ops.push_back(FoldOp);
9579 AddToWorkList(FoldOp.getNode());
9582 if (Ops.size() != N0.getNumOperands())
9585 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9586 N0.getValueType(), &Ops[0], Ops.size());
9589 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
9590 SDValue N1, SDValue N2){
9591 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9593 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9594 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9596 // If we got a simplified select_cc node back from SimplifySelectCC, then
9597 // break it down into a new SETCC node, and a new SELECT node, and then return
9598 // the SELECT node, since we were called with a SELECT node.
9599 if (SCC.getNode()) {
9600 // Check to see if we got a select_cc back (to turn into setcc/select).
9601 // Otherwise, just return whatever node we got back, like fabs.
9602 if (SCC.getOpcode() == ISD::SELECT_CC) {
9603 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
9605 SCC.getOperand(0), SCC.getOperand(1),
9607 AddToWorkList(SETCC.getNode());
9608 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
9609 SCC.getOperand(2), SCC.getOperand(3), SETCC);
9617 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9618 /// are the two values being selected between, see if we can simplify the
9619 /// select. Callers of this should assume that TheSelect is deleted if this
9620 /// returns true. As such, they should return the appropriate thing (e.g. the
9621 /// node) back to the top-level of the DAG combiner loop to avoid it being
9623 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9626 // Cannot simplify select with vector condition
9627 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9629 // If this is a select from two identical things, try to pull the operation
9630 // through the select.
9631 if (LHS.getOpcode() != RHS.getOpcode() ||
9632 !LHS.hasOneUse() || !RHS.hasOneUse())
9635 // If this is a load and the token chain is identical, replace the select
9636 // of two loads with a load through a select of the address to load from.
9637 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9638 // constants have been dropped into the constant pool.
9639 if (LHS.getOpcode() == ISD::LOAD) {
9640 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9641 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9643 // Token chains must be identical.
9644 if (LHS.getOperand(0) != RHS.getOperand(0) ||
9645 // Do not let this transformation reduce the number of volatile loads.
9646 LLD->isVolatile() || RLD->isVolatile() ||
9647 // If this is an EXTLOAD, the VT's must match.
9648 LLD->getMemoryVT() != RLD->getMemoryVT() ||
9649 // If this is an EXTLOAD, the kind of extension must match.
9650 (LLD->getExtensionType() != RLD->getExtensionType() &&
9651 // The only exception is if one of the extensions is anyext.
9652 LLD->getExtensionType() != ISD::EXTLOAD &&
9653 RLD->getExtensionType() != ISD::EXTLOAD) ||
9654 // FIXME: this discards src value information. This is
9655 // over-conservative. It would be beneficial to be able to remember
9656 // both potential memory locations. Since we are discarding
9657 // src value info, don't do the transformation if the memory
9658 // locations are not in the default address space.
9659 LLD->getPointerInfo().getAddrSpace() != 0 ||
9660 RLD->getPointerInfo().getAddrSpace() != 0 ||
9661 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9662 LLD->getBasePtr().getValueType()))
9665 // Check that the select condition doesn't reach either load. If so,
9666 // folding this will induce a cycle into the DAG. If not, this is safe to
9667 // xform, so create a select of the addresses.
9669 if (TheSelect->getOpcode() == ISD::SELECT) {
9670 SDNode *CondNode = TheSelect->getOperand(0).getNode();
9671 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9672 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9674 // The loads must not depend on one another.
9675 if (LLD->isPredecessorOf(RLD) ||
9676 RLD->isPredecessorOf(LLD))
9678 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
9679 LLD->getBasePtr().getValueType(),
9680 TheSelect->getOperand(0), LLD->getBasePtr(),
9682 } else { // Otherwise SELECT_CC
9683 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9684 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9686 if ((LLD->hasAnyUseOfValue(1) &&
9687 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9688 (RLD->hasAnyUseOfValue(1) &&
9689 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9692 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
9693 LLD->getBasePtr().getValueType(),
9694 TheSelect->getOperand(0),
9695 TheSelect->getOperand(1),
9696 LLD->getBasePtr(), RLD->getBasePtr(),
9697 TheSelect->getOperand(4));
9701 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9702 Load = DAG.getLoad(TheSelect->getValueType(0),
9703 TheSelect->getDebugLoc(),
9704 // FIXME: Discards pointer info.
9705 LLD->getChain(), Addr, MachinePointerInfo(),
9706 LLD->isVolatile(), LLD->isNonTemporal(),
9707 LLD->isInvariant(), LLD->getAlignment());
9709 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9710 RLD->getExtensionType() : LLD->getExtensionType(),
9711 TheSelect->getDebugLoc(),
9712 TheSelect->getValueType(0),
9713 // FIXME: Discards pointer info.
9714 LLD->getChain(), Addr, MachinePointerInfo(),
9715 LLD->getMemoryVT(), LLD->isVolatile(),
9716 LLD->isNonTemporal(), LLD->getAlignment());
9719 // Users of the select now use the result of the load.
9720 CombineTo(TheSelect, Load);
9722 // Users of the old loads now use the new load's chain. We know the
9723 // old-load value is dead now.
9724 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9725 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9732 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9733 /// where 'cond' is the comparison specified by CC.
9734 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
9735 SDValue N2, SDValue N3,
9736 ISD::CondCode CC, bool NotExtCompare) {
9737 // (x ? y : y) -> y.
9738 if (N2 == N3) return N2;
9740 EVT VT = N2.getValueType();
9741 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9742 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9743 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9745 // Determine if the condition we're dealing with is constant
9746 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
9747 N0, N1, CC, DL, false);
9748 if (SCC.getNode()) AddToWorkList(SCC.getNode());
9749 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9751 // fold select_cc true, x, y -> x
9752 if (SCCC && !SCCC->isNullValue())
9754 // fold select_cc false, x, y -> y
9755 if (SCCC && SCCC->isNullValue())
9758 // Check to see if we can simplify the select into an fabs node
9759 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9760 // Allow either -0.0 or 0.0
9761 if (CFP->getValueAPF().isZero()) {
9762 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9763 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9764 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9765 N2 == N3.getOperand(0))
9766 return DAG.getNode(ISD::FABS, DL, VT, N0);
9768 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9769 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9770 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9771 N2.getOperand(0) == N3)
9772 return DAG.getNode(ISD::FABS, DL, VT, N3);
9776 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9777 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9778 // in it. This is a win when the constant is not otherwise available because
9779 // it replaces two constant pool loads with one. We only do this if the FP
9780 // type is known to be legal, because if it isn't, then we are before legalize
9781 // types an we want the other legalization to happen first (e.g. to avoid
9782 // messing with soft float) and if the ConstantFP is not legal, because if
9783 // it is legal, we may not need to store the FP constant in a constant pool.
9784 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9785 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9786 if (TLI.isTypeLegal(N2.getValueType()) &&
9787 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9788 TargetLowering::Legal) &&
9789 // If both constants have multiple uses, then we won't need to do an
9790 // extra load, they are likely around in registers for other users.
9791 (TV->hasOneUse() || FV->hasOneUse())) {
9792 Constant *Elts[] = {
9793 const_cast<ConstantFP*>(FV->getConstantFPValue()),
9794 const_cast<ConstantFP*>(TV->getConstantFPValue())
9796 Type *FPTy = Elts[0]->getType();
9797 const DataLayout &TD = *TLI.getDataLayout();
9799 // Create a ConstantArray of the two constants.
9800 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9801 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9802 TD.getPrefTypeAlignment(FPTy));
9803 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9805 // Get the offsets to the 0 and 1 element of the array so that we can
9806 // select between them.
9807 SDValue Zero = DAG.getIntPtrConstant(0);
9808 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9809 SDValue One = DAG.getIntPtrConstant(EltSize);
9811 SDValue Cond = DAG.getSetCC(DL,
9812 TLI.getSetCCResultType(N0.getValueType()),
9814 AddToWorkList(Cond.getNode());
9815 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
9817 AddToWorkList(CstOffset.getNode());
9818 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9820 AddToWorkList(CPIdx.getNode());
9821 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9822 MachinePointerInfo::getConstantPool(), false,
9823 false, false, Alignment);
9828 // Check to see if we can perform the "gzip trick", transforming
9829 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9830 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9831 (N1C->isNullValue() || // (a < 0) ? b : 0
9832 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
9833 EVT XType = N0.getValueType();
9834 EVT AType = N2.getValueType();
9835 if (XType.bitsGE(AType)) {
9836 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9837 // single-bit constant.
9838 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9839 unsigned ShCtV = N2C->getAPIntValue().logBase2();
9840 ShCtV = XType.getSizeInBits()-ShCtV-1;
9841 SDValue ShCt = DAG.getConstant(ShCtV,
9842 getShiftAmountTy(N0.getValueType()));
9843 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9845 AddToWorkList(Shift.getNode());
9847 if (XType.bitsGT(AType)) {
9848 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9849 AddToWorkList(Shift.getNode());
9852 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9855 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9857 DAG.getConstant(XType.getSizeInBits()-1,
9858 getShiftAmountTy(N0.getValueType())));
9859 AddToWorkList(Shift.getNode());
9861 if (XType.bitsGT(AType)) {
9862 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9863 AddToWorkList(Shift.getNode());
9866 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9870 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9871 // where y is has a single bit set.
9872 // A plaintext description would be, we can turn the SELECT_CC into an AND
9873 // when the condition can be materialized as an all-ones register. Any
9874 // single bit-test can be materialized as an all-ones register with
9875 // shift-left and shift-right-arith.
9876 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9877 N0->getValueType(0) == VT &&
9878 N1C && N1C->isNullValue() &&
9879 N2C && N2C->isNullValue()) {
9880 SDValue AndLHS = N0->getOperand(0);
9881 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9882 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9883 // Shift the tested bit over the sign bit.
9884 APInt AndMask = ConstAndRHS->getAPIntValue();
9886 DAG.getConstant(AndMask.countLeadingZeros(),
9887 getShiftAmountTy(AndLHS.getValueType()));
9888 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9890 // Now arithmetic right shift it all the way over, so the result is either
9891 // all-ones, or zero.
9893 DAG.getConstant(AndMask.getBitWidth()-1,
9894 getShiftAmountTy(Shl.getValueType()));
9895 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9897 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9901 // fold select C, 16, 0 -> shl C, 4
9902 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9903 TLI.getBooleanContents(N0.getValueType().isVector()) ==
9904 TargetLowering::ZeroOrOneBooleanContent) {
9906 // If the caller doesn't want us to simplify this into a zext of a compare,
9908 if (NotExtCompare && N2C->getAPIntValue() == 1)
9911 // Get a SetCC of the condition
9912 // NOTE: Don't create a SETCC if it's not legal on this target.
9913 if (!LegalOperations ||
9914 TLI.isOperationLegal(ISD::SETCC,
9915 LegalTypes ? TLI.getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9917 // cast from setcc result type to select result type
9919 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9921 if (N2.getValueType().bitsLT(SCC.getValueType()))
9922 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(),
9925 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9926 N2.getValueType(), SCC);
9928 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9929 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9930 N2.getValueType(), SCC);
9933 AddToWorkList(SCC.getNode());
9934 AddToWorkList(Temp.getNode());
9936 if (N2C->getAPIntValue() == 1)
9939 // shl setcc result by log2 n2c
9940 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9941 DAG.getConstant(N2C->getAPIntValue().logBase2(),
9942 getShiftAmountTy(Temp.getValueType())));
9946 // Check to see if this is the equivalent of setcc
9947 // FIXME: Turn all of these into setcc if setcc if setcc is legal
9948 // otherwise, go ahead with the folds.
9949 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9950 EVT XType = N0.getValueType();
9951 if (!LegalOperations ||
9952 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9953 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9954 if (Res.getValueType() != VT)
9955 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9959 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9960 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9961 (!LegalOperations ||
9962 TLI.isOperationLegal(ISD::CTLZ, XType))) {
9963 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9964 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9965 DAG.getConstant(Log2_32(XType.getSizeInBits()),
9966 getShiftAmountTy(Ctlz.getValueType())));
9968 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9969 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9970 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9971 XType, DAG.getConstant(0, XType), N0);
9972 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9973 return DAG.getNode(ISD::SRL, DL, XType,
9974 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9975 DAG.getConstant(XType.getSizeInBits()-1,
9976 getShiftAmountTy(XType)));
9978 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9979 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9980 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9981 DAG.getConstant(XType.getSizeInBits()-1,
9982 getShiftAmountTy(N0.getValueType())));
9983 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9987 // Check to see if this is an integer abs.
9988 // select_cc setg[te] X, 0, X, -X ->
9989 // select_cc setgt X, -1, X, -X ->
9990 // select_cc setl[te] X, 0, -X, X ->
9991 // select_cc setlt X, 1, -X, X ->
9992 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9994 ConstantSDNode *SubC = NULL;
9995 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9996 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9997 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9998 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9999 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10000 (N1C->isOne() && CC == ISD::SETLT)) &&
10001 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10002 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10004 EVT XType = N0.getValueType();
10005 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10006 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
10008 DAG.getConstant(XType.getSizeInBits()-1,
10009 getShiftAmountTy(N0.getValueType())));
10010 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
10012 AddToWorkList(Shift.getNode());
10013 AddToWorkList(Add.getNode());
10014 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10021 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10022 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10023 SDValue N1, ISD::CondCode Cond,
10024 DebugLoc DL, bool foldBooleans) {
10025 TargetLowering::DAGCombinerInfo
10026 DagCombineInfo(DAG, Level, false, this);
10027 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10030 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10031 /// return a DAG expression to select that will generate the same value by
10032 /// multiplying by a magic number. See:
10033 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10034 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10035 std::vector<SDNode*> Built;
10036 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10038 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10040 AddToWorkList(*ii);
10044 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10045 /// return a DAG expression to select that will generate the same value by
10046 /// multiplying by a magic number. See:
10047 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10048 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10049 std::vector<SDNode*> Built;
10050 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10052 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10054 AddToWorkList(*ii);
10058 /// FindBaseOffset - Return true if base is a frame index, which is known not
10059 // to alias with anything but itself. Provides base object and offset as
10061 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10062 const GlobalValue *&GV, const void *&CV) {
10063 // Assume it is a primitive operation.
10064 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10066 // If it's an adding a simple constant then integrate the offset.
10067 if (Base.getOpcode() == ISD::ADD) {
10068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10069 Base = Base.getOperand(0);
10070 Offset += C->getZExtValue();
10074 // Return the underlying GlobalValue, and update the Offset. Return false
10075 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10076 // by multiple nodes with different offsets.
10077 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10078 GV = G->getGlobal();
10079 Offset += G->getOffset();
10083 // Return the underlying Constant value, and update the Offset. Return false
10084 // for ConstantSDNodes since the same constant pool entry may be represented
10085 // by multiple nodes with different offsets.
10086 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10087 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10088 : (const void *)C->getConstVal();
10089 Offset += C->getOffset();
10092 // If it's any of the following then it can't alias with anything but itself.
10093 return isa<FrameIndexSDNode>(Base);
10096 /// isAlias - Return true if there is any possibility that the two addresses
10098 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10099 const Value *SrcValue1, int SrcValueOffset1,
10100 unsigned SrcValueAlign1,
10101 const MDNode *TBAAInfo1,
10102 SDValue Ptr2, int64_t Size2,
10103 const Value *SrcValue2, int SrcValueOffset2,
10104 unsigned SrcValueAlign2,
10105 const MDNode *TBAAInfo2) const {
10106 // If they are the same then they must be aliases.
10107 if (Ptr1 == Ptr2) return true;
10109 // Gather base node and offset information.
10110 SDValue Base1, Base2;
10111 int64_t Offset1, Offset2;
10112 const GlobalValue *GV1, *GV2;
10113 const void *CV1, *CV2;
10114 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10115 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10117 // If they have a same base address then check to see if they overlap.
10118 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10119 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10121 // It is possible for different frame indices to alias each other, mostly
10122 // when tail call optimization reuses return address slots for arguments.
10123 // To catch this case, look up the actual index of frame indices to compute
10124 // the real alias relationship.
10125 if (isFrameIndex1 && isFrameIndex2) {
10126 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10127 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10128 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10129 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10132 // Otherwise, if we know what the bases are, and they aren't identical, then
10133 // we know they cannot alias.
10134 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10137 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10138 // compared to the size and offset of the access, we may be able to prove they
10139 // do not alias. This check is conservative for now to catch cases created by
10140 // splitting vector types.
10141 if ((SrcValueAlign1 == SrcValueAlign2) &&
10142 (SrcValueOffset1 != SrcValueOffset2) &&
10143 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10144 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10145 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10147 // There is no overlap between these relatively aligned accesses of similar
10148 // size, return no alias.
10149 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10153 if (CombinerGlobalAA) {
10154 // Use alias analysis information.
10155 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10156 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10157 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10158 AliasAnalysis::AliasResult AAResult =
10159 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10160 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10161 if (AAResult == AliasAnalysis::NoAlias)
10165 // Otherwise we have to assume they alias.
10169 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10170 SDValue Ptr0, Ptr1;
10171 int64_t Size0, Size1;
10172 const Value *SrcValue0, *SrcValue1;
10173 int SrcValueOffset0, SrcValueOffset1;
10174 unsigned SrcValueAlign0, SrcValueAlign1;
10175 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10176 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10177 SrcValueAlign0, SrcTBAAInfo0);
10178 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10179 SrcValueAlign1, SrcTBAAInfo1);
10180 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10181 SrcValueAlign0, SrcTBAAInfo0,
10182 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10183 SrcValueAlign1, SrcTBAAInfo1);
10186 /// FindAliasInfo - Extracts the relevant alias information from the memory
10187 /// node. Returns true if the operand was a load.
10188 bool DAGCombiner::FindAliasInfo(SDNode *N,
10189 SDValue &Ptr, int64_t &Size,
10190 const Value *&SrcValue,
10191 int &SrcValueOffset,
10192 unsigned &SrcValueAlign,
10193 const MDNode *&TBAAInfo) const {
10194 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10196 Ptr = LS->getBasePtr();
10197 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10198 SrcValue = LS->getSrcValue();
10199 SrcValueOffset = LS->getSrcValueOffset();
10200 SrcValueAlign = LS->getOriginalAlignment();
10201 TBAAInfo = LS->getTBAAInfo();
10202 return isa<LoadSDNode>(LS);
10205 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10206 /// looking for aliasing nodes and adding them to the Aliases vector.
10207 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10208 SmallVector<SDValue, 8> &Aliases) {
10209 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10210 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10212 // Get alias information for node.
10215 const Value *SrcValue;
10216 int SrcValueOffset;
10217 unsigned SrcValueAlign;
10218 const MDNode *SrcTBAAInfo;
10219 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10220 SrcValueAlign, SrcTBAAInfo);
10223 Chains.push_back(OriginalChain);
10224 unsigned Depth = 0;
10226 // Look at each chain and determine if it is an alias. If so, add it to the
10227 // aliases list. If not, then continue up the chain looking for the next
10229 while (!Chains.empty()) {
10230 SDValue Chain = Chains.back();
10233 // For TokenFactor nodes, look at each operand and only continue up the
10234 // chain until we find two aliases. If we've seen two aliases, assume we'll
10235 // find more and revert to original chain since the xform is unlikely to be
10238 // FIXME: The depth check could be made to return the last non-aliasing
10239 // chain we found before we hit a tokenfactor rather than the original
10241 if (Depth > 6 || Aliases.size() == 2) {
10243 Aliases.push_back(OriginalChain);
10247 // Don't bother if we've been before.
10248 if (!Visited.insert(Chain.getNode()))
10251 switch (Chain.getOpcode()) {
10252 case ISD::EntryToken:
10253 // Entry token is ideal chain operand, but handled in FindBetterChain.
10258 // Get alias information for Chain.
10261 const Value *OpSrcValue;
10262 int OpSrcValueOffset;
10263 unsigned OpSrcValueAlign;
10264 const MDNode *OpSrcTBAAInfo;
10265 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10266 OpSrcValue, OpSrcValueOffset,
10270 // If chain is alias then stop here.
10271 if (!(IsLoad && IsOpLoad) &&
10272 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10274 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10275 OpSrcValueAlign, OpSrcTBAAInfo)) {
10276 Aliases.push_back(Chain);
10278 // Look further up the chain.
10279 Chains.push_back(Chain.getOperand(0));
10285 case ISD::TokenFactor:
10286 // We have to check each of the operands of the token factor for "small"
10287 // token factors, so we queue them up. Adding the operands to the queue
10288 // (stack) in reverse order maintains the original order and increases the
10289 // likelihood that getNode will find a matching token factor (CSE.)
10290 if (Chain.getNumOperands() > 16) {
10291 Aliases.push_back(Chain);
10294 for (unsigned n = Chain.getNumOperands(); n;)
10295 Chains.push_back(Chain.getOperand(--n));
10300 // For all other instructions we will just have to take what we can get.
10301 Aliases.push_back(Chain);
10307 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10308 /// for a better chain (aliasing node.)
10309 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10310 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
10312 // Accumulate all the aliases to this node.
10313 GatherAllAliases(N, OldChain, Aliases);
10315 // If no operands then chain to entry token.
10316 if (Aliases.size() == 0)
10317 return DAG.getEntryNode();
10319 // If a single operand then chain to it. We don't need to revisit it.
10320 if (Aliases.size() == 1)
10323 // Construct a custom tailored token factor.
10324 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
10325 &Aliases[0], Aliases.size());
10328 // SelectionDAG::Combine - This is the entry point for the file.
10330 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10331 CodeGenOpt::Level OptLevel) {
10332 /// run - This is the main entry point to this class.
10334 DAGCombiner(*this, AA, OptLevel).Run(Level);