1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NodesCombined , "Number of dag nodes combined");
41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
44 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 CombinerAA("combiner-alias-analysis", cl::Hidden,
49 cl::desc("Turn on alias analysis during testing"));
52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53 cl::desc("Include global information in alias analysis"));
55 //------------------------------ DAGCombiner ---------------------------------//
59 const TargetLowering &TLI;
61 CodeGenOpt::Level OptLevel;
65 // Worklist of all of the nodes that need to be simplified.
66 std::vector<SDNode*> WorkList;
68 // AA - Used for DAG load/store alias analysis.
71 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
75 void AddUsersToWorkList(SDNode *N) {
76 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
81 /// visit - call the node-specific routine that knows how to fold each
82 /// particular type of node.
83 SDValue visit(SDNode *N);
86 /// AddToWorkList - Add to the work list making sure it's instance is at the
87 /// the back (next to be processed.)
88 void AddToWorkList(SDNode *N) {
89 removeFromWorkList(N);
90 WorkList.push_back(N);
93 /// removeFromWorkList - remove all instances of N from the worklist.
95 void removeFromWorkList(SDNode *N) {
96 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
100 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
103 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
104 return CombineTo(N, &Res, 1, AddTo);
107 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
109 SDValue To[] = { Res0, Res1 };
110 return CombineTo(N, To, 2, AddTo);
113 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
117 /// SimplifyDemandedBits - Check the specified integer node value to see if
118 /// it can be simplified or if things it uses can be simplified by bit
119 /// propagation. If so, return true.
120 bool SimplifyDemandedBits(SDValue Op) {
121 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
122 APInt Demanded = APInt::getAllOnesValue(BitWidth);
123 return SimplifyDemandedBits(Op, Demanded);
126 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
131 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
132 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
133 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
134 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue PromoteIntBinOp(SDValue Op);
136 SDValue PromoteIntShiftOp(SDValue Op);
137 SDValue PromoteExtend(SDValue Op);
138 bool PromoteLoad(SDValue Op);
140 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
141 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
142 ISD::NodeType ExtType);
144 /// combine - call the node-specific routine that knows how to fold each
145 /// particular type of node. If that doesn't do anything, try the
146 /// target-specific DAG combines.
147 SDValue combine(SDNode *N);
149 // Visitation implementation - Implement dag node combining for different
150 // node types. The semantics are as follows:
152 // SDValue.getNode() == 0 - No change was made
153 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
154 // otherwise - N should be replaced by the returned Operand.
156 SDValue visitTokenFactor(SDNode *N);
157 SDValue visitMERGE_VALUES(SDNode *N);
158 SDValue visitADD(SDNode *N);
159 SDValue visitSUB(SDNode *N);
160 SDValue visitADDC(SDNode *N);
161 SDValue visitADDE(SDNode *N);
162 SDValue visitMUL(SDNode *N);
163 SDValue visitSDIV(SDNode *N);
164 SDValue visitUDIV(SDNode *N);
165 SDValue visitSREM(SDNode *N);
166 SDValue visitUREM(SDNode *N);
167 SDValue visitMULHU(SDNode *N);
168 SDValue visitMULHS(SDNode *N);
169 SDValue visitSMUL_LOHI(SDNode *N);
170 SDValue visitUMUL_LOHI(SDNode *N);
171 SDValue visitSMULO(SDNode *N);
172 SDValue visitUMULO(SDNode *N);
173 SDValue visitSDIVREM(SDNode *N);
174 SDValue visitUDIVREM(SDNode *N);
175 SDValue visitAND(SDNode *N);
176 SDValue visitOR(SDNode *N);
177 SDValue visitXOR(SDNode *N);
178 SDValue SimplifyVBinOp(SDNode *N);
179 SDValue visitSHL(SDNode *N);
180 SDValue visitSRA(SDNode *N);
181 SDValue visitSRL(SDNode *N);
182 SDValue visitCTLZ(SDNode *N);
183 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
184 SDValue visitCTTZ(SDNode *N);
185 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
186 SDValue visitCTPOP(SDNode *N);
187 SDValue visitSELECT(SDNode *N);
188 SDValue visitSELECT_CC(SDNode *N);
189 SDValue visitSETCC(SDNode *N);
190 SDValue visitSIGN_EXTEND(SDNode *N);
191 SDValue visitZERO_EXTEND(SDNode *N);
192 SDValue visitANY_EXTEND(SDNode *N);
193 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
194 SDValue visitTRUNCATE(SDNode *N);
195 SDValue visitBITCAST(SDNode *N);
196 SDValue visitBUILD_PAIR(SDNode *N);
197 SDValue visitFADD(SDNode *N);
198 SDValue visitFSUB(SDNode *N);
199 SDValue visitFMUL(SDNode *N);
200 SDValue visitFDIV(SDNode *N);
201 SDValue visitFREM(SDNode *N);
202 SDValue visitFCOPYSIGN(SDNode *N);
203 SDValue visitSINT_TO_FP(SDNode *N);
204 SDValue visitUINT_TO_FP(SDNode *N);
205 SDValue visitFP_TO_SINT(SDNode *N);
206 SDValue visitFP_TO_UINT(SDNode *N);
207 SDValue visitFP_ROUND(SDNode *N);
208 SDValue visitFP_ROUND_INREG(SDNode *N);
209 SDValue visitFP_EXTEND(SDNode *N);
210 SDValue visitFNEG(SDNode *N);
211 SDValue visitFABS(SDNode *N);
212 SDValue visitBRCOND(SDNode *N);
213 SDValue visitBR_CC(SDNode *N);
214 SDValue visitLOAD(SDNode *N);
215 SDValue visitSTORE(SDNode *N);
216 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
217 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
218 SDValue visitBUILD_VECTOR(SDNode *N);
219 SDValue visitCONCAT_VECTORS(SDNode *N);
220 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
221 SDValue visitVECTOR_SHUFFLE(SDNode *N);
222 SDValue visitMEMBARRIER(SDNode *N);
224 SDValue XformToShuffleWithZero(SDNode *N);
225 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
227 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
229 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
230 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
231 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
232 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
233 SDValue N3, ISD::CondCode CC,
234 bool NotExtCompare = false);
235 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
236 DebugLoc DL, bool foldBooleans = true);
237 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
239 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
240 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
241 SDValue BuildSDIV(SDNode *N);
242 SDValue BuildUDIV(SDNode *N);
243 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
244 bool DemandHighBits = true);
245 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
246 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
247 SDValue ReduceLoadWidth(SDNode *N);
248 SDValue ReduceLoadOpStoreWidth(SDNode *N);
249 SDValue TransformFPLoadStorePair(SDNode *N);
251 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
253 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
254 /// looking for aliasing nodes and adding them to the Aliases vector.
255 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
256 SmallVector<SDValue, 8> &Aliases);
258 /// isAlias - Return true if there is any possibility that the two addresses
260 bool isAlias(SDValue Ptr1, int64_t Size1,
261 const Value *SrcValue1, int SrcValueOffset1,
262 unsigned SrcValueAlign1,
263 const MDNode *TBAAInfo1,
264 SDValue Ptr2, int64_t Size2,
265 const Value *SrcValue2, int SrcValueOffset2,
266 unsigned SrcValueAlign2,
267 const MDNode *TBAAInfo2) const;
269 /// FindAliasInfo - Extracts the relevant alias information from the memory
270 /// node. Returns true if the operand was a load.
271 bool FindAliasInfo(SDNode *N,
272 SDValue &Ptr, int64_t &Size,
273 const Value *&SrcValue, int &SrcValueOffset,
274 unsigned &SrcValueAlignment,
275 const MDNode *&TBAAInfo) const;
277 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
278 /// looking for a better chain (aliasing node.)
279 SDValue FindBetterChain(SDNode *N, SDValue Chain);
282 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
283 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
284 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
286 /// Run - runs the dag combiner on all nodes in the work list
287 void Run(CombineLevel AtLevel);
289 SelectionDAG &getDAG() const { return DAG; }
291 /// getShiftAmountTy - Returns a type large enough to hold any valid
292 /// shift amount - before type legalization these can be huge.
293 EVT getShiftAmountTy(EVT LHSTy) {
294 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
297 /// isTypeLegal - This method returns true if we are running before type
298 /// legalization or if the specified VT is legal.
299 bool isTypeLegal(const EVT &VT) {
300 if (!LegalTypes) return true;
301 return TLI.isTypeLegal(VT);
308 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
309 /// nodes from the worklist.
310 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
313 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
315 virtual void NodeDeleted(SDNode *N, SDNode *E) {
316 DC.removeFromWorkList(N);
319 virtual void NodeUpdated(SDNode *N) {
325 //===----------------------------------------------------------------------===//
326 // TargetLowering::DAGCombinerInfo implementation
327 //===----------------------------------------------------------------------===//
329 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
330 ((DAGCombiner*)DC)->AddToWorkList(N);
333 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
334 ((DAGCombiner*)DC)->removeFromWorkList(N);
337 SDValue TargetLowering::DAGCombinerInfo::
338 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
339 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
342 SDValue TargetLowering::DAGCombinerInfo::
343 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
344 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
348 SDValue TargetLowering::DAGCombinerInfo::
349 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
350 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
353 void TargetLowering::DAGCombinerInfo::
354 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
355 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
358 //===----------------------------------------------------------------------===//
360 //===----------------------------------------------------------------------===//
362 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
363 /// specified expression for the same cost as the expression itself, or 2 if we
364 /// can compute the negated form more cheaply than the expression itself.
365 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
366 const TargetOptions *Options,
367 unsigned Depth = 0) {
368 // No compile time optimizations on this type.
369 if (Op.getValueType() == MVT::ppcf128)
372 // fneg is removable even if it has multiple uses.
373 if (Op.getOpcode() == ISD::FNEG) return 2;
375 // Don't allow anything with multiple uses.
376 if (!Op.hasOneUse()) return 0;
378 // Don't recurse exponentially.
379 if (Depth > 6) return 0;
381 switch (Op.getOpcode()) {
382 default: return false;
383 case ISD::ConstantFP:
384 // Don't invert constant FP values after legalize. The negated constant
385 // isn't necessarily legal.
386 return LegalOperations ? 0 : 1;
388 // FIXME: determine better conditions for this xform.
389 if (!Options->UnsafeFPMath) return 0;
391 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
392 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Options,
395 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
396 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Options,
399 // We can't turn -(A-B) into B-A when we honor signed zeros.
400 if (!Options->UnsafeFPMath) return 0;
402 // fold (fneg (fsub A, B)) -> (fsub B, A)
407 if (Options->HonorSignDependentRoundingFPMath()) return 0;
409 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
410 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Options,
414 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Options,
420 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Options,
425 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
426 /// returns the newly negated expression.
427 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
428 bool LegalOperations, unsigned Depth = 0) {
429 // fneg is removable even if it has multiple uses.
430 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
432 // Don't allow anything with multiple uses.
433 assert(Op.hasOneUse() && "Unknown reuse!");
435 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
436 switch (Op.getOpcode()) {
437 default: llvm_unreachable("Unknown code");
438 case ISD::ConstantFP: {
439 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
441 return DAG.getConstantFP(V, Op.getValueType());
444 // FIXME: determine better conditions for this xform.
445 assert(DAG.getTarget().Options.UnsafeFPMath);
447 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
448 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
449 &DAG.getTarget().Options, Depth+1))
450 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
451 GetNegatedExpression(Op.getOperand(0), DAG,
452 LegalOperations, Depth+1),
454 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
455 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(1), DAG,
457 LegalOperations, Depth+1),
460 // We can't turn -(A-B) into B-A when we honor signed zeros.
461 assert(DAG.getTarget().Options.UnsafeFPMath);
463 // fold (fneg (fsub 0, B)) -> B
464 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
465 if (N0CFP->getValueAPF().isZero())
466 return Op.getOperand(1);
468 // fold (fneg (fsub A, B)) -> (fsub B, A)
469 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
470 Op.getOperand(1), Op.getOperand(0));
474 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
476 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
477 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
478 &DAG.getTarget().Options, Depth+1))
479 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
480 GetNegatedExpression(Op.getOperand(0), DAG,
481 LegalOperations, Depth+1),
484 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
485 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
487 GetNegatedExpression(Op.getOperand(1), DAG,
488 LegalOperations, Depth+1));
492 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
493 GetNegatedExpression(Op.getOperand(0), DAG,
494 LegalOperations, Depth+1));
496 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
497 GetNegatedExpression(Op.getOperand(0), DAG,
498 LegalOperations, Depth+1),
504 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
505 // that selects between the values 1 and 0, making it equivalent to a setcc.
506 // Also, set the incoming LHS, RHS, and CC references to the appropriate
507 // nodes based on the type of node we are checking. This simplifies life a
508 // bit for the callers.
509 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
511 if (N.getOpcode() == ISD::SETCC) {
512 LHS = N.getOperand(0);
513 RHS = N.getOperand(1);
514 CC = N.getOperand(2);
517 if (N.getOpcode() == ISD::SELECT_CC &&
518 N.getOperand(2).getOpcode() == ISD::Constant &&
519 N.getOperand(3).getOpcode() == ISD::Constant &&
520 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
521 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
522 LHS = N.getOperand(0);
523 RHS = N.getOperand(1);
524 CC = N.getOperand(4);
530 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
531 // one use. If this is true, it allows the users to invert the operation for
532 // free when it is profitable to do so.
533 static bool isOneUseSetCC(SDValue N) {
535 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
540 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
541 SDValue N0, SDValue N1) {
542 EVT VT = N0.getValueType();
543 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
544 if (isa<ConstantSDNode>(N1)) {
545 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
547 DAG.FoldConstantArithmetic(Opc, VT,
548 cast<ConstantSDNode>(N0.getOperand(1)),
549 cast<ConstantSDNode>(N1));
550 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
552 if (N0.hasOneUse()) {
553 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
554 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
555 N0.getOperand(0), N1);
556 AddToWorkList(OpNode.getNode());
557 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
561 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
562 if (isa<ConstantSDNode>(N0)) {
563 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
565 DAG.FoldConstantArithmetic(Opc, VT,
566 cast<ConstantSDNode>(N1.getOperand(1)),
567 cast<ConstantSDNode>(N0));
568 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
570 if (N1.hasOneUse()) {
571 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
572 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
573 N1.getOperand(0), N0);
574 AddToWorkList(OpNode.getNode());
575 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
582 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
584 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
586 DEBUG(dbgs() << "\nReplacing.1 ";
588 dbgs() << "\nWith: ";
589 To[0].getNode()->dump(&DAG);
590 dbgs() << " and " << NumTo-1 << " other values\n";
591 for (unsigned i = 0, e = NumTo; i != e; ++i)
592 assert((!To[i].getNode() ||
593 N->getValueType(i) == To[i].getValueType()) &&
594 "Cannot combine value to value of different type!"));
595 WorkListRemover DeadNodes(*this);
596 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
599 // Push the new nodes and any users onto the worklist
600 for (unsigned i = 0, e = NumTo; i != e; ++i) {
601 if (To[i].getNode()) {
602 AddToWorkList(To[i].getNode());
603 AddUsersToWorkList(To[i].getNode());
608 // Finally, if the node is now dead, remove it from the graph. The node
609 // may not be dead if the replacement process recursively simplified to
610 // something else needing this node.
611 if (N->use_empty()) {
612 // Nodes can be reintroduced into the worklist. Make sure we do not
613 // process a node that has been replaced.
614 removeFromWorkList(N);
616 // Finally, since the node is now dead, remove it from the graph.
619 return SDValue(N, 0);
623 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
624 // Replace all uses. If any nodes become isomorphic to other nodes and
625 // are deleted, make sure to remove them from our worklist.
626 WorkListRemover DeadNodes(*this);
627 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
629 // Push the new node and any (possibly new) users onto the worklist.
630 AddToWorkList(TLO.New.getNode());
631 AddUsersToWorkList(TLO.New.getNode());
633 // Finally, if the node is now dead, remove it from the graph. The node
634 // may not be dead if the replacement process recursively simplified to
635 // something else needing this node.
636 if (TLO.Old.getNode()->use_empty()) {
637 removeFromWorkList(TLO.Old.getNode());
639 // If the operands of this node are only used by the node, they will now
640 // be dead. Make sure to visit them first to delete dead nodes early.
641 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
642 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
643 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
645 DAG.DeleteNode(TLO.Old.getNode());
649 /// SimplifyDemandedBits - Check the specified integer node value to see if
650 /// it can be simplified or if things it uses can be simplified by bit
651 /// propagation. If so, return true.
652 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
653 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
654 APInt KnownZero, KnownOne;
655 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
659 AddToWorkList(Op.getNode());
661 // Replace the old value with the new one.
663 DEBUG(dbgs() << "\nReplacing.2 ";
664 TLO.Old.getNode()->dump(&DAG);
665 dbgs() << "\nWith: ";
666 TLO.New.getNode()->dump(&DAG);
669 CommitTargetLoweringOpt(TLO);
673 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
674 DebugLoc dl = Load->getDebugLoc();
675 EVT VT = Load->getValueType(0);
676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
678 DEBUG(dbgs() << "\nReplacing.9 ";
680 dbgs() << "\nWith: ";
681 Trunc.getNode()->dump(&DAG);
683 WorkListRemover DeadNodes(*this);
684 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
685 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
687 removeFromWorkList(Load);
688 DAG.DeleteNode(Load);
689 AddToWorkList(Trunc.getNode());
692 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
694 DebugLoc dl = Op.getDebugLoc();
695 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
696 EVT MemVT = LD->getMemoryVT();
697 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
698 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
700 : LD->getExtensionType();
702 return DAG.getExtLoad(ExtType, dl, PVT,
703 LD->getChain(), LD->getBasePtr(),
704 LD->getPointerInfo(),
705 MemVT, LD->isVolatile(),
706 LD->isNonTemporal(), LD->getAlignment());
709 unsigned Opc = Op.getOpcode();
712 case ISD::AssertSext:
713 return DAG.getNode(ISD::AssertSext, dl, PVT,
714 SExtPromoteOperand(Op.getOperand(0), PVT),
716 case ISD::AssertZext:
717 return DAG.getNode(ISD::AssertZext, dl, PVT,
718 ZExtPromoteOperand(Op.getOperand(0), PVT),
720 case ISD::Constant: {
722 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
723 return DAG.getNode(ExtOpc, dl, PVT, Op);
727 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
729 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
732 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
733 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
735 EVT OldVT = Op.getValueType();
736 DebugLoc dl = Op.getDebugLoc();
737 bool Replace = false;
738 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
739 if (NewOp.getNode() == 0)
741 AddToWorkList(NewOp.getNode());
744 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
745 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
746 DAG.getValueType(OldVT));
749 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
750 EVT OldVT = Op.getValueType();
751 DebugLoc dl = Op.getDebugLoc();
752 bool Replace = false;
753 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
754 if (NewOp.getNode() == 0)
756 AddToWorkList(NewOp.getNode());
759 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
760 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
763 /// PromoteIntBinOp - Promote the specified integer binary operation if the
764 /// target indicates it is beneficial. e.g. On x86, it's usually better to
765 /// promote i16 operations to i32 since i16 instructions are longer.
766 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
767 if (!LegalOperations)
770 EVT VT = Op.getValueType();
771 if (VT.isVector() || !VT.isInteger())
774 // If operation type is 'undesirable', e.g. i16 on x86, consider
776 unsigned Opc = Op.getOpcode();
777 if (TLI.isTypeDesirableForOp(Opc, VT))
781 // Consult target whether it is a good idea to promote this operation and
782 // what's the right type to promote it to.
783 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
784 assert(PVT != VT && "Don't know what type to promote to!");
786 bool Replace0 = false;
787 SDValue N0 = Op.getOperand(0);
788 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
789 if (NN0.getNode() == 0)
792 bool Replace1 = false;
793 SDValue N1 = Op.getOperand(1);
798 NN1 = PromoteOperand(N1, PVT, Replace1);
799 if (NN1.getNode() == 0)
803 AddToWorkList(NN0.getNode());
805 AddToWorkList(NN1.getNode());
808 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
810 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
812 DEBUG(dbgs() << "\nPromoting ";
813 Op.getNode()->dump(&DAG));
814 DebugLoc dl = Op.getDebugLoc();
815 return DAG.getNode(ISD::TRUNCATE, dl, VT,
816 DAG.getNode(Opc, dl, PVT, NN0, NN1));
821 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
822 /// target indicates it is beneficial. e.g. On x86, it's usually better to
823 /// promote i16 operations to i32 since i16 instructions are longer.
824 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
825 if (!LegalOperations)
828 EVT VT = Op.getValueType();
829 if (VT.isVector() || !VT.isInteger())
832 // If operation type is 'undesirable', e.g. i16 on x86, consider
834 unsigned Opc = Op.getOpcode();
835 if (TLI.isTypeDesirableForOp(Opc, VT))
839 // Consult target whether it is a good idea to promote this operation and
840 // what's the right type to promote it to.
841 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
842 assert(PVT != VT && "Don't know what type to promote to!");
844 bool Replace = false;
845 SDValue N0 = Op.getOperand(0);
847 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
848 else if (Opc == ISD::SRL)
849 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
851 N0 = PromoteOperand(N0, PVT, Replace);
852 if (N0.getNode() == 0)
855 AddToWorkList(N0.getNode());
857 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
859 DEBUG(dbgs() << "\nPromoting ";
860 Op.getNode()->dump(&DAG));
861 DebugLoc dl = Op.getDebugLoc();
862 return DAG.getNode(ISD::TRUNCATE, dl, VT,
863 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
868 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
869 if (!LegalOperations)
872 EVT VT = Op.getValueType();
873 if (VT.isVector() || !VT.isInteger())
876 // If operation type is 'undesirable', e.g. i16 on x86, consider
878 unsigned Opc = Op.getOpcode();
879 if (TLI.isTypeDesirableForOp(Opc, VT))
883 // Consult target whether it is a good idea to promote this operation and
884 // what's the right type to promote it to.
885 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
886 assert(PVT != VT && "Don't know what type to promote to!");
887 // fold (aext (aext x)) -> (aext x)
888 // fold (aext (zext x)) -> (zext x)
889 // fold (aext (sext x)) -> (sext x)
890 DEBUG(dbgs() << "\nPromoting ";
891 Op.getNode()->dump(&DAG));
892 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
897 bool DAGCombiner::PromoteLoad(SDValue Op) {
898 if (!LegalOperations)
901 EVT VT = Op.getValueType();
902 if (VT.isVector() || !VT.isInteger())
905 // If operation type is 'undesirable', e.g. i16 on x86, consider
907 unsigned Opc = Op.getOpcode();
908 if (TLI.isTypeDesirableForOp(Opc, VT))
912 // Consult target whether it is a good idea to promote this operation and
913 // what's the right type to promote it to.
914 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
915 assert(PVT != VT && "Don't know what type to promote to!");
917 DebugLoc dl = Op.getDebugLoc();
918 SDNode *N = Op.getNode();
919 LoadSDNode *LD = cast<LoadSDNode>(N);
920 EVT MemVT = LD->getMemoryVT();
921 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
922 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
924 : LD->getExtensionType();
925 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
926 LD->getChain(), LD->getBasePtr(),
927 LD->getPointerInfo(),
928 MemVT, LD->isVolatile(),
929 LD->isNonTemporal(), LD->getAlignment());
930 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
932 DEBUG(dbgs() << "\nPromoting ";
935 Result.getNode()->dump(&DAG);
937 WorkListRemover DeadNodes(*this);
938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
939 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
940 removeFromWorkList(N);
942 AddToWorkList(Result.getNode());
949 //===----------------------------------------------------------------------===//
950 // Main DAG Combiner implementation
951 //===----------------------------------------------------------------------===//
953 void DAGCombiner::Run(CombineLevel AtLevel) {
954 // set the instance variables, so that the various visit routines may use it.
956 LegalOperations = Level >= AfterLegalizeVectorOps;
957 LegalTypes = Level >= AfterLegalizeTypes;
959 // Add all the dag nodes to the worklist.
960 WorkList.reserve(DAG.allnodes_size());
961 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
962 E = DAG.allnodes_end(); I != E; ++I)
963 WorkList.push_back(I);
965 // Create a dummy node (which is not added to allnodes), that adds a reference
966 // to the root node, preventing it from being deleted, and tracking any
967 // changes of the root.
968 HandleSDNode Dummy(DAG.getRoot());
970 // The root of the dag may dangle to deleted nodes until the dag combiner is
971 // done. Set it to null to avoid confusion.
972 DAG.setRoot(SDValue());
974 // while the worklist isn't empty, inspect the node on the end of it and
975 // try and combine it.
976 while (!WorkList.empty()) {
977 SDNode *N = WorkList.back();
980 // If N has no uses, it is dead. Make sure to revisit all N's operands once
981 // N is deleted from the DAG, since they too may now be dead or may have a
982 // reduced number of uses, allowing other xforms.
983 if (N->use_empty() && N != &Dummy) {
984 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
985 AddToWorkList(N->getOperand(i).getNode());
991 SDValue RV = combine(N);
993 if (RV.getNode() == 0)
998 // If we get back the same node we passed in, rather than a new node or
999 // zero, we know that the node must have defined multiple values and
1000 // CombineTo was used. Since CombineTo takes care of the worklist
1001 // mechanics for us, we have no work to do in this case.
1002 if (RV.getNode() == N)
1005 assert(N->getOpcode() != ISD::DELETED_NODE &&
1006 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1007 "Node was deleted but visit returned new node!");
1009 DEBUG(dbgs() << "\nReplacing.3 ";
1011 dbgs() << "\nWith: ";
1012 RV.getNode()->dump(&DAG);
1015 // Transfer debug value.
1016 DAG.TransferDbgValues(SDValue(N, 0), RV);
1017 WorkListRemover DeadNodes(*this);
1018 if (N->getNumValues() == RV.getNode()->getNumValues())
1019 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
1021 assert(N->getValueType(0) == RV.getValueType() &&
1022 N->getNumValues() == 1 && "Type mismatch");
1024 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
1027 // Push the new node and any users onto the worklist
1028 AddToWorkList(RV.getNode());
1029 AddUsersToWorkList(RV.getNode());
1031 // Add any uses of the old node to the worklist in case this node is the
1032 // last one that uses them. They may become dead after this node is
1034 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1035 AddToWorkList(N->getOperand(i).getNode());
1037 // Finally, if the node is now dead, remove it from the graph. The node
1038 // may not be dead if the replacement process recursively simplified to
1039 // something else needing this node.
1040 if (N->use_empty()) {
1041 // Nodes can be reintroduced into the worklist. Make sure we do not
1042 // process a node that has been replaced.
1043 removeFromWorkList(N);
1045 // Finally, since the node is now dead, remove it from the graph.
1050 // If the root changed (e.g. it was a dead load, update the root).
1051 DAG.setRoot(Dummy.getValue());
1054 SDValue DAGCombiner::visit(SDNode *N) {
1055 switch (N->getOpcode()) {
1057 case ISD::TokenFactor: return visitTokenFactor(N);
1058 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1059 case ISD::ADD: return visitADD(N);
1060 case ISD::SUB: return visitSUB(N);
1061 case ISD::ADDC: return visitADDC(N);
1062 case ISD::ADDE: return visitADDE(N);
1063 case ISD::MUL: return visitMUL(N);
1064 case ISD::SDIV: return visitSDIV(N);
1065 case ISD::UDIV: return visitUDIV(N);
1066 case ISD::SREM: return visitSREM(N);
1067 case ISD::UREM: return visitUREM(N);
1068 case ISD::MULHU: return visitMULHU(N);
1069 case ISD::MULHS: return visitMULHS(N);
1070 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1071 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1072 case ISD::SMULO: return visitSMULO(N);
1073 case ISD::UMULO: return visitUMULO(N);
1074 case ISD::SDIVREM: return visitSDIVREM(N);
1075 case ISD::UDIVREM: return visitUDIVREM(N);
1076 case ISD::AND: return visitAND(N);
1077 case ISD::OR: return visitOR(N);
1078 case ISD::XOR: return visitXOR(N);
1079 case ISD::SHL: return visitSHL(N);
1080 case ISD::SRA: return visitSRA(N);
1081 case ISD::SRL: return visitSRL(N);
1082 case ISD::CTLZ: return visitCTLZ(N);
1083 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1084 case ISD::CTTZ: return visitCTTZ(N);
1085 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1086 case ISD::CTPOP: return visitCTPOP(N);
1087 case ISD::SELECT: return visitSELECT(N);
1088 case ISD::SELECT_CC: return visitSELECT_CC(N);
1089 case ISD::SETCC: return visitSETCC(N);
1090 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1091 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1092 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1093 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1094 case ISD::TRUNCATE: return visitTRUNCATE(N);
1095 case ISD::BITCAST: return visitBITCAST(N);
1096 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1097 case ISD::FADD: return visitFADD(N);
1098 case ISD::FSUB: return visitFSUB(N);
1099 case ISD::FMUL: return visitFMUL(N);
1100 case ISD::FDIV: return visitFDIV(N);
1101 case ISD::FREM: return visitFREM(N);
1102 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1103 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1104 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1105 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1106 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1107 case ISD::FP_ROUND: return visitFP_ROUND(N);
1108 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1109 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1110 case ISD::FNEG: return visitFNEG(N);
1111 case ISD::FABS: return visitFABS(N);
1112 case ISD::BRCOND: return visitBRCOND(N);
1113 case ISD::BR_CC: return visitBR_CC(N);
1114 case ISD::LOAD: return visitLOAD(N);
1115 case ISD::STORE: return visitSTORE(N);
1116 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1117 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1118 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1119 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1120 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1121 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1122 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1127 SDValue DAGCombiner::combine(SDNode *N) {
1128 SDValue RV = visit(N);
1130 // If nothing happened, try a target-specific DAG combine.
1131 if (RV.getNode() == 0) {
1132 assert(N->getOpcode() != ISD::DELETED_NODE &&
1133 "Node was deleted but visit returned NULL!");
1135 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1136 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1138 // Expose the DAG combiner to the target combiner impls.
1139 TargetLowering::DAGCombinerInfo
1140 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1142 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1146 // If nothing happened still, try promoting the operation.
1147 if (RV.getNode() == 0) {
1148 switch (N->getOpcode()) {
1156 RV = PromoteIntBinOp(SDValue(N, 0));
1161 RV = PromoteIntShiftOp(SDValue(N, 0));
1163 case ISD::SIGN_EXTEND:
1164 case ISD::ZERO_EXTEND:
1165 case ISD::ANY_EXTEND:
1166 RV = PromoteExtend(SDValue(N, 0));
1169 if (PromoteLoad(SDValue(N, 0)))
1175 // If N is a commutative binary node, try commuting it to enable more
1177 if (RV.getNode() == 0 &&
1178 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1179 N->getNumValues() == 1) {
1180 SDValue N0 = N->getOperand(0);
1181 SDValue N1 = N->getOperand(1);
1183 // Constant operands are canonicalized to RHS.
1184 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1185 SDValue Ops[] = { N1, N0 };
1186 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1189 return SDValue(CSENode, 0);
1196 /// getInputChainForNode - Given a node, return its input chain if it has one,
1197 /// otherwise return a null sd operand.
1198 static SDValue getInputChainForNode(SDNode *N) {
1199 if (unsigned NumOps = N->getNumOperands()) {
1200 if (N->getOperand(0).getValueType() == MVT::Other)
1201 return N->getOperand(0);
1202 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1203 return N->getOperand(NumOps-1);
1204 for (unsigned i = 1; i < NumOps-1; ++i)
1205 if (N->getOperand(i).getValueType() == MVT::Other)
1206 return N->getOperand(i);
1211 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1212 // If N has two operands, where one has an input chain equal to the other,
1213 // the 'other' chain is redundant.
1214 if (N->getNumOperands() == 2) {
1215 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1216 return N->getOperand(0);
1217 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1218 return N->getOperand(1);
1221 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1222 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1223 SmallPtrSet<SDNode*, 16> SeenOps;
1224 bool Changed = false; // If we should replace this token factor.
1226 // Start out with this token factor.
1229 // Iterate through token factors. The TFs grows when new token factors are
1231 for (unsigned i = 0; i < TFs.size(); ++i) {
1232 SDNode *TF = TFs[i];
1234 // Check each of the operands.
1235 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1236 SDValue Op = TF->getOperand(i);
1238 switch (Op.getOpcode()) {
1239 case ISD::EntryToken:
1240 // Entry tokens don't need to be added to the list. They are
1245 case ISD::TokenFactor:
1246 if (Op.hasOneUse() &&
1247 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1248 // Queue up for processing.
1249 TFs.push_back(Op.getNode());
1250 // Clean up in case the token factor is removed.
1251 AddToWorkList(Op.getNode());
1258 // Only add if it isn't already in the list.
1259 if (SeenOps.insert(Op.getNode()))
1270 // If we've change things around then replace token factor.
1273 // The entry token is the only possible outcome.
1274 Result = DAG.getEntryNode();
1276 // New and improved token factor.
1277 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1278 MVT::Other, &Ops[0], Ops.size());
1281 // Don't add users to work list.
1282 return CombineTo(N, Result, false);
1288 /// MERGE_VALUES can always be eliminated.
1289 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1290 WorkListRemover DeadNodes(*this);
1291 // Replacing results may cause a different MERGE_VALUES to suddenly
1292 // be CSE'd with N, and carry its uses with it. Iterate until no
1293 // uses remain, to ensure that the node can be safely deleted.
1295 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1296 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1298 } while (!N->use_empty());
1299 removeFromWorkList(N);
1301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1305 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1306 SelectionDAG &DAG) {
1307 EVT VT = N0.getValueType();
1308 SDValue N00 = N0.getOperand(0);
1309 SDValue N01 = N0.getOperand(1);
1310 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1312 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1313 isa<ConstantSDNode>(N00.getOperand(1))) {
1314 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1315 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1316 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1317 N00.getOperand(0), N01),
1318 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1319 N00.getOperand(1), N01));
1320 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1326 SDValue DAGCombiner::visitADD(SDNode *N) {
1327 SDValue N0 = N->getOperand(0);
1328 SDValue N1 = N->getOperand(1);
1329 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1331 EVT VT = N0.getValueType();
1334 if (VT.isVector()) {
1335 SDValue FoldedVOp = SimplifyVBinOp(N);
1336 if (FoldedVOp.getNode()) return FoldedVOp;
1339 // fold (add x, undef) -> undef
1340 if (N0.getOpcode() == ISD::UNDEF)
1342 if (N1.getOpcode() == ISD::UNDEF)
1344 // fold (add c1, c2) -> c1+c2
1346 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1347 // canonicalize constant to RHS
1349 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1350 // fold (add x, 0) -> x
1351 if (N1C && N1C->isNullValue())
1353 // fold (add Sym, c) -> Sym+c
1354 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1355 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1356 GA->getOpcode() == ISD::GlobalAddress)
1357 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1359 (uint64_t)N1C->getSExtValue());
1360 // fold ((c1-A)+c2) -> (c1+c2)-A
1361 if (N1C && N0.getOpcode() == ISD::SUB)
1362 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1363 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1364 DAG.getConstant(N1C->getAPIntValue()+
1365 N0C->getAPIntValue(), VT),
1368 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1369 if (RADD.getNode() != 0)
1371 // fold ((0-A) + B) -> B-A
1372 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1373 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1374 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1375 // fold (A + (0-B)) -> A-B
1376 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1377 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1378 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1379 // fold (A+(B-A)) -> B
1380 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1381 return N1.getOperand(0);
1382 // fold ((B-A)+A) -> B
1383 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1384 return N0.getOperand(0);
1385 // fold (A+(B-(A+C))) to (B-C)
1386 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1387 N0 == N1.getOperand(1).getOperand(0))
1388 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1389 N1.getOperand(1).getOperand(1));
1390 // fold (A+(B-(C+A))) to (B-C)
1391 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1392 N0 == N1.getOperand(1).getOperand(1))
1393 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1394 N1.getOperand(1).getOperand(0));
1395 // fold (A+((B-A)+or-C)) to (B+or-C)
1396 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1397 N1.getOperand(0).getOpcode() == ISD::SUB &&
1398 N0 == N1.getOperand(0).getOperand(1))
1399 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1400 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1402 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1403 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1404 SDValue N00 = N0.getOperand(0);
1405 SDValue N01 = N0.getOperand(1);
1406 SDValue N10 = N1.getOperand(0);
1407 SDValue N11 = N1.getOperand(1);
1409 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1410 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1411 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1412 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1415 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1416 return SDValue(N, 0);
1418 // fold (a+b) -> (a|b) iff a and b share no bits.
1419 if (VT.isInteger() && !VT.isVector()) {
1420 APInt LHSZero, LHSOne;
1421 APInt RHSZero, RHSOne;
1422 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1423 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1425 if (LHSZero.getBoolValue()) {
1426 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1428 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1429 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1430 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1431 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1432 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1436 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1437 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1438 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1439 if (Result.getNode()) return Result;
1441 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1442 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1443 if (Result.getNode()) return Result;
1446 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1447 if (N1.getOpcode() == ISD::SHL &&
1448 N1.getOperand(0).getOpcode() == ISD::SUB)
1449 if (ConstantSDNode *C =
1450 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1451 if (C->getAPIntValue() == 0)
1452 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1453 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1454 N1.getOperand(0).getOperand(1),
1456 if (N0.getOpcode() == ISD::SHL &&
1457 N0.getOperand(0).getOpcode() == ISD::SUB)
1458 if (ConstantSDNode *C =
1459 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1460 if (C->getAPIntValue() == 0)
1461 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1462 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1463 N0.getOperand(0).getOperand(1),
1466 if (N1.getOpcode() == ISD::AND) {
1467 SDValue AndOp0 = N1.getOperand(0);
1468 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1469 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1470 unsigned DestBits = VT.getScalarType().getSizeInBits();
1472 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1473 // and similar xforms where the inner op is either ~0 or 0.
1474 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1475 DebugLoc DL = N->getDebugLoc();
1476 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1480 // add (sext i1), X -> sub X, (zext i1)
1481 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1482 N0.getOperand(0).getValueType() == MVT::i1 &&
1483 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1484 DebugLoc DL = N->getDebugLoc();
1485 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1486 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1492 SDValue DAGCombiner::visitADDC(SDNode *N) {
1493 SDValue N0 = N->getOperand(0);
1494 SDValue N1 = N->getOperand(1);
1495 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1497 EVT VT = N0.getValueType();
1499 // If the flag result is dead, turn this into an ADD.
1500 if (N->hasNUsesOfValue(0, 1))
1501 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1502 DAG.getNode(ISD::CARRY_FALSE,
1503 N->getDebugLoc(), MVT::Glue));
1505 // canonicalize constant to RHS.
1507 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1509 // fold (addc x, 0) -> x + no carry out
1510 if (N1C && N1C->isNullValue())
1511 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1512 N->getDebugLoc(), MVT::Glue));
1514 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1515 APInt LHSZero, LHSOne;
1516 APInt RHSZero, RHSOne;
1517 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1518 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1520 if (LHSZero.getBoolValue()) {
1521 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1523 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1524 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1525 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1526 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1527 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1528 DAG.getNode(ISD::CARRY_FALSE,
1529 N->getDebugLoc(), MVT::Glue));
1535 SDValue DAGCombiner::visitADDE(SDNode *N) {
1536 SDValue N0 = N->getOperand(0);
1537 SDValue N1 = N->getOperand(1);
1538 SDValue CarryIn = N->getOperand(2);
1539 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1540 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542 // canonicalize constant to RHS
1544 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1547 // fold (adde x, y, false) -> (addc x, y)
1548 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1549 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1554 // Since it may not be valid to emit a fold to zero for vector initializers
1555 // check if we can before folding.
1556 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1557 SelectionDAG &DAG, bool LegalOperations) {
1558 if (!VT.isVector()) {
1559 return DAG.getConstant(0, VT);
1561 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1562 // Produce a vector of zeros.
1563 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1564 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1565 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1566 &Ops[0], Ops.size());
1571 SDValue DAGCombiner::visitSUB(SDNode *N) {
1572 SDValue N0 = N->getOperand(0);
1573 SDValue N1 = N->getOperand(1);
1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1576 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1577 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1578 EVT VT = N0.getValueType();
1581 if (VT.isVector()) {
1582 SDValue FoldedVOp = SimplifyVBinOp(N);
1583 if (FoldedVOp.getNode()) return FoldedVOp;
1586 // fold (sub x, x) -> 0
1587 // FIXME: Refactor this and xor and other similar operations together.
1589 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1590 // fold (sub c1, c2) -> c1-c2
1592 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1593 // fold (sub x, c) -> (add x, -c)
1595 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1596 DAG.getConstant(-N1C->getAPIntValue(), VT));
1597 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1598 if (N0C && N0C->isAllOnesValue())
1599 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1600 // fold A-(A-B) -> B
1601 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1602 return N1.getOperand(1);
1603 // fold (A+B)-A -> B
1604 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1605 return N0.getOperand(1);
1606 // fold (A+B)-B -> A
1607 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1608 return N0.getOperand(0);
1609 // fold C2-(A+C1) -> (C2-C1)-A
1610 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1611 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1612 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1615 // fold ((A+(B+or-C))-B) -> A+or-C
1616 if (N0.getOpcode() == ISD::ADD &&
1617 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1618 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1619 N0.getOperand(1).getOperand(0) == N1)
1620 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1621 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1622 // fold ((A+(C+B))-B) -> A+C
1623 if (N0.getOpcode() == ISD::ADD &&
1624 N0.getOperand(1).getOpcode() == ISD::ADD &&
1625 N0.getOperand(1).getOperand(1) == N1)
1626 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1627 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1628 // fold ((A-(B-C))-C) -> A-B
1629 if (N0.getOpcode() == ISD::SUB &&
1630 N0.getOperand(1).getOpcode() == ISD::SUB &&
1631 N0.getOperand(1).getOperand(1) == N1)
1632 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1633 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1635 // If either operand of a sub is undef, the result is undef
1636 if (N0.getOpcode() == ISD::UNDEF)
1638 if (N1.getOpcode() == ISD::UNDEF)
1641 // If the relocation model supports it, consider symbol offsets.
1642 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1643 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1644 // fold (sub Sym, c) -> Sym-c
1645 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1646 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1648 (uint64_t)N1C->getSExtValue());
1649 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1650 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1651 if (GA->getGlobal() == GB->getGlobal())
1652 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1659 SDValue DAGCombiner::visitMUL(SDNode *N) {
1660 SDValue N0 = N->getOperand(0);
1661 SDValue N1 = N->getOperand(1);
1662 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1664 EVT VT = N0.getValueType();
1667 if (VT.isVector()) {
1668 SDValue FoldedVOp = SimplifyVBinOp(N);
1669 if (FoldedVOp.getNode()) return FoldedVOp;
1672 // fold (mul x, undef) -> 0
1673 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1674 return DAG.getConstant(0, VT);
1675 // fold (mul c1, c2) -> c1*c2
1677 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1678 // canonicalize constant to RHS
1680 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1681 // fold (mul x, 0) -> 0
1682 if (N1C && N1C->isNullValue())
1684 // fold (mul x, -1) -> 0-x
1685 if (N1C && N1C->isAllOnesValue())
1686 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1687 DAG.getConstant(0, VT), N0);
1688 // fold (mul x, (1 << c)) -> x << c
1689 if (N1C && N1C->getAPIntValue().isPowerOf2())
1690 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1691 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1692 getShiftAmountTy(N0.getValueType())));
1693 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1694 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1695 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1696 // FIXME: If the input is something that is easily negated (e.g. a
1697 // single-use add), we should put the negate there.
1698 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1699 DAG.getConstant(0, VT),
1700 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1701 DAG.getConstant(Log2Val,
1702 getShiftAmountTy(N0.getValueType()))));
1704 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1705 if (N1C && N0.getOpcode() == ISD::SHL &&
1706 isa<ConstantSDNode>(N0.getOperand(1))) {
1707 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1708 N1, N0.getOperand(1));
1709 AddToWorkList(C3.getNode());
1710 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1711 N0.getOperand(0), C3);
1714 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1717 SDValue Sh(0,0), Y(0,0);
1718 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1719 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1720 N0.getNode()->hasOneUse()) {
1722 } else if (N1.getOpcode() == ISD::SHL &&
1723 isa<ConstantSDNode>(N1.getOperand(1)) &&
1724 N1.getNode()->hasOneUse()) {
1729 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1730 Sh.getOperand(0), Y);
1731 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1732 Mul, Sh.getOperand(1));
1736 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1737 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1738 isa<ConstantSDNode>(N0.getOperand(1)))
1739 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1740 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1741 N0.getOperand(0), N1),
1742 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1743 N0.getOperand(1), N1));
1746 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1747 if (RMUL.getNode() != 0)
1753 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1754 SDValue N0 = N->getOperand(0);
1755 SDValue N1 = N->getOperand(1);
1756 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1757 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1758 EVT VT = N->getValueType(0);
1761 if (VT.isVector()) {
1762 SDValue FoldedVOp = SimplifyVBinOp(N);
1763 if (FoldedVOp.getNode()) return FoldedVOp;
1766 // fold (sdiv c1, c2) -> c1/c2
1767 if (N0C && N1C && !N1C->isNullValue())
1768 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1769 // fold (sdiv X, 1) -> X
1770 if (N1C && N1C->getAPIntValue() == 1LL)
1772 // fold (sdiv X, -1) -> 0-X
1773 if (N1C && N1C->isAllOnesValue())
1774 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1775 DAG.getConstant(0, VT), N0);
1776 // If we know the sign bits of both operands are zero, strength reduce to a
1777 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1778 if (!VT.isVector()) {
1779 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1780 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1783 // fold (sdiv X, pow2) -> simple ops after legalize
1784 if (N1C && !N1C->isNullValue() &&
1785 (N1C->getAPIntValue().isPowerOf2() ||
1786 (-N1C->getAPIntValue()).isPowerOf2())) {
1787 // If dividing by powers of two is cheap, then don't perform the following
1789 if (TLI.isPow2DivCheap())
1792 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1794 // Splat the sign bit into the register
1795 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1796 DAG.getConstant(VT.getSizeInBits()-1,
1797 getShiftAmountTy(N0.getValueType())));
1798 AddToWorkList(SGN.getNode());
1800 // Add (N0 < 0) ? abs2 - 1 : 0;
1801 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1802 DAG.getConstant(VT.getSizeInBits() - lg2,
1803 getShiftAmountTy(SGN.getValueType())));
1804 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1805 AddToWorkList(SRL.getNode());
1806 AddToWorkList(ADD.getNode()); // Divide by pow2
1807 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1808 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1810 // If we're dividing by a positive value, we're done. Otherwise, we must
1811 // negate the result.
1812 if (N1C->getAPIntValue().isNonNegative())
1815 AddToWorkList(SRA.getNode());
1816 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1817 DAG.getConstant(0, VT), SRA);
1820 // if integer divide is expensive and we satisfy the requirements, emit an
1821 // alternate sequence.
1822 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1823 SDValue Op = BuildSDIV(N);
1824 if (Op.getNode()) return Op;
1828 if (N0.getOpcode() == ISD::UNDEF)
1829 return DAG.getConstant(0, VT);
1830 // X / undef -> undef
1831 if (N1.getOpcode() == ISD::UNDEF)
1837 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1838 SDValue N0 = N->getOperand(0);
1839 SDValue N1 = N->getOperand(1);
1840 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1841 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1842 EVT VT = N->getValueType(0);
1845 if (VT.isVector()) {
1846 SDValue FoldedVOp = SimplifyVBinOp(N);
1847 if (FoldedVOp.getNode()) return FoldedVOp;
1850 // fold (udiv c1, c2) -> c1/c2
1851 if (N0C && N1C && !N1C->isNullValue())
1852 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1853 // fold (udiv x, (1 << c)) -> x >>u c
1854 if (N1C && N1C->getAPIntValue().isPowerOf2())
1855 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1856 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1857 getShiftAmountTy(N0.getValueType())));
1858 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1859 if (N1.getOpcode() == ISD::SHL) {
1860 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1861 if (SHC->getAPIntValue().isPowerOf2()) {
1862 EVT ADDVT = N1.getOperand(1).getValueType();
1863 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1865 DAG.getConstant(SHC->getAPIntValue()
1868 AddToWorkList(Add.getNode());
1869 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1873 // fold (udiv x, c) -> alternate
1874 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1875 SDValue Op = BuildUDIV(N);
1876 if (Op.getNode()) return Op;
1880 if (N0.getOpcode() == ISD::UNDEF)
1881 return DAG.getConstant(0, VT);
1882 // X / undef -> undef
1883 if (N1.getOpcode() == ISD::UNDEF)
1889 SDValue DAGCombiner::visitSREM(SDNode *N) {
1890 SDValue N0 = N->getOperand(0);
1891 SDValue N1 = N->getOperand(1);
1892 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1893 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1894 EVT VT = N->getValueType(0);
1896 // fold (srem c1, c2) -> c1%c2
1897 if (N0C && N1C && !N1C->isNullValue())
1898 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1899 // If we know the sign bits of both operands are zero, strength reduce to a
1900 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1901 if (!VT.isVector()) {
1902 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1903 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1906 // If X/C can be simplified by the division-by-constant logic, lower
1907 // X%C to the equivalent of X-X/C*C.
1908 if (N1C && !N1C->isNullValue()) {
1909 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1910 AddToWorkList(Div.getNode());
1911 SDValue OptimizedDiv = combine(Div.getNode());
1912 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1913 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1915 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1916 AddToWorkList(Mul.getNode());
1922 if (N0.getOpcode() == ISD::UNDEF)
1923 return DAG.getConstant(0, VT);
1924 // X % undef -> undef
1925 if (N1.getOpcode() == ISD::UNDEF)
1931 SDValue DAGCombiner::visitUREM(SDNode *N) {
1932 SDValue N0 = N->getOperand(0);
1933 SDValue N1 = N->getOperand(1);
1934 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1935 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1936 EVT VT = N->getValueType(0);
1938 // fold (urem c1, c2) -> c1%c2
1939 if (N0C && N1C && !N1C->isNullValue())
1940 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1941 // fold (urem x, pow2) -> (and x, pow2-1)
1942 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1943 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1944 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1945 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1946 if (N1.getOpcode() == ISD::SHL) {
1947 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1948 if (SHC->getAPIntValue().isPowerOf2()) {
1950 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1951 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1953 AddToWorkList(Add.getNode());
1954 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1959 // If X/C can be simplified by the division-by-constant logic, lower
1960 // X%C to the equivalent of X-X/C*C.
1961 if (N1C && !N1C->isNullValue()) {
1962 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1963 AddToWorkList(Div.getNode());
1964 SDValue OptimizedDiv = combine(Div.getNode());
1965 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1966 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1968 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1969 AddToWorkList(Mul.getNode());
1975 if (N0.getOpcode() == ISD::UNDEF)
1976 return DAG.getConstant(0, VT);
1977 // X % undef -> undef
1978 if (N1.getOpcode() == ISD::UNDEF)
1984 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1988 EVT VT = N->getValueType(0);
1989 DebugLoc DL = N->getDebugLoc();
1991 // fold (mulhs x, 0) -> 0
1992 if (N1C && N1C->isNullValue())
1994 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1995 if (N1C && N1C->getAPIntValue() == 1)
1996 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1997 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1998 getShiftAmountTy(N0.getValueType())));
1999 // fold (mulhs x, undef) -> 0
2000 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2001 return DAG.getConstant(0, VT);
2003 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2005 if (VT.isSimple() && !VT.isVector()) {
2006 MVT Simple = VT.getSimpleVT();
2007 unsigned SimpleSize = Simple.getSizeInBits();
2008 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2009 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2010 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2011 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2012 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2013 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2014 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2015 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2022 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2023 SDValue N0 = N->getOperand(0);
2024 SDValue N1 = N->getOperand(1);
2025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2026 EVT VT = N->getValueType(0);
2027 DebugLoc DL = N->getDebugLoc();
2029 // fold (mulhu x, 0) -> 0
2030 if (N1C && N1C->isNullValue())
2032 // fold (mulhu x, 1) -> 0
2033 if (N1C && N1C->getAPIntValue() == 1)
2034 return DAG.getConstant(0, N0.getValueType());
2035 // fold (mulhu x, undef) -> 0
2036 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2037 return DAG.getConstant(0, VT);
2039 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2041 if (VT.isSimple() && !VT.isVector()) {
2042 MVT Simple = VT.getSimpleVT();
2043 unsigned SimpleSize = Simple.getSizeInBits();
2044 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2045 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2046 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2047 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2048 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2049 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2050 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2051 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2058 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2059 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2060 /// that are being performed. Return true if a simplification was made.
2062 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2064 // If the high half is not needed, just compute the low half.
2065 bool HiExists = N->hasAnyUseOfValue(1);
2067 (!LegalOperations ||
2068 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2069 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2070 N->op_begin(), N->getNumOperands());
2071 return CombineTo(N, Res, Res);
2074 // If the low half is not needed, just compute the high half.
2075 bool LoExists = N->hasAnyUseOfValue(0);
2077 (!LegalOperations ||
2078 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2079 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2080 N->op_begin(), N->getNumOperands());
2081 return CombineTo(N, Res, Res);
2084 // If both halves are used, return as it is.
2085 if (LoExists && HiExists)
2088 // If the two computed results can be simplified separately, separate them.
2090 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2091 N->op_begin(), N->getNumOperands());
2092 AddToWorkList(Lo.getNode());
2093 SDValue LoOpt = combine(Lo.getNode());
2094 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2095 (!LegalOperations ||
2096 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2097 return CombineTo(N, LoOpt, LoOpt);
2101 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2102 N->op_begin(), N->getNumOperands());
2103 AddToWorkList(Hi.getNode());
2104 SDValue HiOpt = combine(Hi.getNode());
2105 if (HiOpt.getNode() && HiOpt != Hi &&
2106 (!LegalOperations ||
2107 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2108 return CombineTo(N, HiOpt, HiOpt);
2114 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2115 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2116 if (Res.getNode()) return Res;
2118 EVT VT = N->getValueType(0);
2119 DebugLoc DL = N->getDebugLoc();
2121 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2123 if (VT.isSimple() && !VT.isVector()) {
2124 MVT Simple = VT.getSimpleVT();
2125 unsigned SimpleSize = Simple.getSizeInBits();
2126 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2127 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2128 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2129 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2130 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2131 // Compute the high part as N1.
2132 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2133 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2134 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2135 // Compute the low part as N0.
2136 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2137 return CombineTo(N, Lo, Hi);
2144 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2145 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2146 if (Res.getNode()) return Res;
2148 EVT VT = N->getValueType(0);
2149 DebugLoc DL = N->getDebugLoc();
2151 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2153 if (VT.isSimple() && !VT.isVector()) {
2154 MVT Simple = VT.getSimpleVT();
2155 unsigned SimpleSize = Simple.getSizeInBits();
2156 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2157 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2158 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2159 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2160 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2161 // Compute the high part as N1.
2162 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2163 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2164 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2165 // Compute the low part as N0.
2166 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2167 return CombineTo(N, Lo, Hi);
2174 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2175 // (smulo x, 2) -> (saddo x, x)
2176 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2177 if (C2->getAPIntValue() == 2)
2178 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2179 N->getOperand(0), N->getOperand(0));
2184 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2185 // (umulo x, 2) -> (uaddo x, x)
2186 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2187 if (C2->getAPIntValue() == 2)
2188 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2189 N->getOperand(0), N->getOperand(0));
2194 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2195 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2196 if (Res.getNode()) return Res;
2201 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2202 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2203 if (Res.getNode()) return Res;
2208 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2209 /// two operands of the same opcode, try to simplify it.
2210 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2211 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2212 EVT VT = N0.getValueType();
2213 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2215 // Bail early if none of these transforms apply.
2216 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2218 // For each of OP in AND/OR/XOR:
2219 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2220 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2221 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2222 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2224 // do not sink logical op inside of a vector extend, since it may combine
2226 EVT Op0VT = N0.getOperand(0).getValueType();
2227 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2228 N0.getOpcode() == ISD::SIGN_EXTEND ||
2229 // Avoid infinite looping with PromoteIntBinOp.
2230 (N0.getOpcode() == ISD::ANY_EXTEND &&
2231 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2232 (N0.getOpcode() == ISD::TRUNCATE &&
2233 (!TLI.isZExtFree(VT, Op0VT) ||
2234 !TLI.isTruncateFree(Op0VT, VT)) &&
2235 TLI.isTypeLegal(Op0VT))) &&
2237 Op0VT == N1.getOperand(0).getValueType() &&
2238 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2239 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2240 N0.getOperand(0).getValueType(),
2241 N0.getOperand(0), N1.getOperand(0));
2242 AddToWorkList(ORNode.getNode());
2243 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2246 // For each of OP in SHL/SRL/SRA/AND...
2247 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2248 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2249 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2250 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2251 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2252 N0.getOperand(1) == N1.getOperand(1)) {
2253 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2254 N0.getOperand(0).getValueType(),
2255 N0.getOperand(0), N1.getOperand(0));
2256 AddToWorkList(ORNode.getNode());
2257 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2258 ORNode, N0.getOperand(1));
2264 SDValue DAGCombiner::visitAND(SDNode *N) {
2265 SDValue N0 = N->getOperand(0);
2266 SDValue N1 = N->getOperand(1);
2267 SDValue LL, LR, RL, RR, CC0, CC1;
2268 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2269 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2270 EVT VT = N1.getValueType();
2271 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2274 if (VT.isVector()) {
2275 SDValue FoldedVOp = SimplifyVBinOp(N);
2276 if (FoldedVOp.getNode()) return FoldedVOp;
2279 // fold (and x, undef) -> 0
2280 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2281 return DAG.getConstant(0, VT);
2282 // fold (and c1, c2) -> c1&c2
2284 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2285 // canonicalize constant to RHS
2287 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2288 // fold (and x, -1) -> x
2289 if (N1C && N1C->isAllOnesValue())
2291 // if (and x, c) is known to be zero, return 0
2292 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2293 APInt::getAllOnesValue(BitWidth)))
2294 return DAG.getConstant(0, VT);
2296 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2297 if (RAND.getNode() != 0)
2299 // fold (and (or x, C), D) -> D if (C & D) == D
2300 if (N1C && N0.getOpcode() == ISD::OR)
2301 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2302 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2304 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2305 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2306 SDValue N0Op0 = N0.getOperand(0);
2307 APInt Mask = ~N1C->getAPIntValue();
2308 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2309 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2310 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2311 N0.getValueType(), N0Op0);
2313 // Replace uses of the AND with uses of the Zero extend node.
2316 // We actually want to replace all uses of the any_extend with the
2317 // zero_extend, to avoid duplicating things. This will later cause this
2318 // AND to be folded.
2319 CombineTo(N0.getNode(), Zext);
2320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2323 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2324 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2325 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2326 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2328 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2329 LL.getValueType().isInteger()) {
2330 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2331 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2332 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2333 LR.getValueType(), LL, RL);
2334 AddToWorkList(ORNode.getNode());
2335 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2337 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2338 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2339 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2340 LR.getValueType(), LL, RL);
2341 AddToWorkList(ANDNode.getNode());
2342 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2344 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2345 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2346 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2347 LR.getValueType(), LL, RL);
2348 AddToWorkList(ORNode.getNode());
2349 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2352 // canonicalize equivalent to ll == rl
2353 if (LL == RR && LR == RL) {
2354 Op1 = ISD::getSetCCSwappedOperands(Op1);
2357 if (LL == RL && LR == RR) {
2358 bool isInteger = LL.getValueType().isInteger();
2359 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2360 if (Result != ISD::SETCC_INVALID &&
2361 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2362 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2367 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2368 if (N0.getOpcode() == N1.getOpcode()) {
2369 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2370 if (Tmp.getNode()) return Tmp;
2373 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2374 // fold (and (sra)) -> (and (srl)) when possible.
2375 if (!VT.isVector() &&
2376 SimplifyDemandedBits(SDValue(N, 0)))
2377 return SDValue(N, 0);
2379 // fold (zext_inreg (extload x)) -> (zextload x)
2380 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2381 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2382 EVT MemVT = LN0->getMemoryVT();
2383 // If we zero all the possible extended bits, then we can turn this into
2384 // a zextload if we are running before legalize or the operation is legal.
2385 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2386 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2387 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2388 ((!LegalOperations && !LN0->isVolatile()) ||
2389 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2390 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2391 LN0->getChain(), LN0->getBasePtr(),
2392 LN0->getPointerInfo(), MemVT,
2393 LN0->isVolatile(), LN0->isNonTemporal(),
2394 LN0->getAlignment());
2396 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2397 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2400 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2401 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2403 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2404 EVT MemVT = LN0->getMemoryVT();
2405 // If we zero all the possible extended bits, then we can turn this into
2406 // a zextload if we are running before legalize or the operation is legal.
2407 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2408 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2409 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2410 ((!LegalOperations && !LN0->isVolatile()) ||
2411 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2414 LN0->getBasePtr(), LN0->getPointerInfo(),
2416 LN0->isVolatile(), LN0->isNonTemporal(),
2417 LN0->getAlignment());
2419 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2420 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2424 // fold (and (load x), 255) -> (zextload x, i8)
2425 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2426 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2427 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2428 (N0.getOpcode() == ISD::ANY_EXTEND &&
2429 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2430 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2431 LoadSDNode *LN0 = HasAnyExt
2432 ? cast<LoadSDNode>(N0.getOperand(0))
2433 : cast<LoadSDNode>(N0);
2434 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2435 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2436 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2437 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2438 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2439 EVT LoadedVT = LN0->getMemoryVT();
2441 if (ExtVT == LoadedVT &&
2442 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2443 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2446 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2447 LN0->getChain(), LN0->getBasePtr(),
2448 LN0->getPointerInfo(),
2449 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2450 LN0->getAlignment());
2452 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2453 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2456 // Do not change the width of a volatile load.
2457 // Do not generate loads of non-round integer types since these can
2458 // be expensive (and would be wrong if the type is not byte sized).
2459 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2460 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2461 EVT PtrType = LN0->getOperand(1).getValueType();
2463 unsigned Alignment = LN0->getAlignment();
2464 SDValue NewPtr = LN0->getBasePtr();
2466 // For big endian targets, we need to add an offset to the pointer
2467 // to load the correct bytes. For little endian systems, we merely
2468 // need to read fewer bytes from the same pointer.
2469 if (TLI.isBigEndian()) {
2470 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2471 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2472 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2473 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2474 NewPtr, DAG.getConstant(PtrOff, PtrType));
2475 Alignment = MinAlign(Alignment, PtrOff);
2478 AddToWorkList(NewPtr.getNode());
2480 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2482 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2483 LN0->getChain(), NewPtr,
2484 LN0->getPointerInfo(),
2485 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2488 CombineTo(LN0, Load, Load.getValue(1));
2489 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2498 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2500 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2501 bool DemandHighBits) {
2502 if (!LegalOperations)
2505 EVT VT = N->getValueType(0);
2506 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2508 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2511 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2512 bool LookPassAnd0 = false;
2513 bool LookPassAnd1 = false;
2514 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2516 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2518 if (N0.getOpcode() == ISD::AND) {
2519 if (!N0.getNode()->hasOneUse())
2521 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2522 if (!N01C || N01C->getZExtValue() != 0xFF00)
2524 N0 = N0.getOperand(0);
2525 LookPassAnd0 = true;
2528 if (N1.getOpcode() == ISD::AND) {
2529 if (!N1.getNode()->hasOneUse())
2531 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2532 if (!N11C || N11C->getZExtValue() != 0xFF)
2534 N1 = N1.getOperand(0);
2535 LookPassAnd1 = true;
2538 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2540 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2542 if (!N0.getNode()->hasOneUse() ||
2543 !N1.getNode()->hasOneUse())
2546 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2547 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2550 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2553 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2554 SDValue N00 = N0->getOperand(0);
2555 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2556 if (!N00.getNode()->hasOneUse())
2558 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2559 if (!N001C || N001C->getZExtValue() != 0xFF)
2561 N00 = N00.getOperand(0);
2562 LookPassAnd0 = true;
2565 SDValue N10 = N1->getOperand(0);
2566 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2567 if (!N10.getNode()->hasOneUse())
2569 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2570 if (!N101C || N101C->getZExtValue() != 0xFF00)
2572 N10 = N10.getOperand(0);
2573 LookPassAnd1 = true;
2579 // Make sure everything beyond the low halfword is zero since the SRL 16
2580 // will clear the top bits.
2581 unsigned OpSizeInBits = VT.getSizeInBits();
2582 if (DemandHighBits && OpSizeInBits > 16 &&
2583 (!LookPassAnd0 || !LookPassAnd1) &&
2584 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2587 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2588 if (OpSizeInBits > 16)
2589 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2590 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2594 /// isBSwapHWordElement - Return true if the specified node is an element
2595 /// that makes up a 32-bit packed halfword byteswap. i.e.
2596 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2597 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2598 if (!N.getNode()->hasOneUse())
2601 unsigned Opc = N.getOpcode();
2602 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2605 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2610 switch (N1C->getZExtValue()) {
2613 case 0xFF: Num = 0; break;
2614 case 0xFF00: Num = 1; break;
2615 case 0xFF0000: Num = 2; break;
2616 case 0xFF000000: Num = 3; break;
2619 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2620 SDValue N0 = N.getOperand(0);
2621 if (Opc == ISD::AND) {
2622 if (Num == 0 || Num == 2) {
2624 // (x >> 8) & 0xff0000
2625 if (N0.getOpcode() != ISD::SRL)
2627 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2628 if (!C || C->getZExtValue() != 8)
2631 // (x << 8) & 0xff00
2632 // (x << 8) & 0xff000000
2633 if (N0.getOpcode() != ISD::SHL)
2635 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2636 if (!C || C->getZExtValue() != 8)
2639 } else if (Opc == ISD::SHL) {
2641 // (x & 0xff0000) << 8
2642 if (Num != 0 && Num != 2)
2644 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2645 if (!C || C->getZExtValue() != 8)
2647 } else { // Opc == ISD::SRL
2648 // (x & 0xff00) >> 8
2649 // (x & 0xff000000) >> 8
2650 if (Num != 1 && Num != 3)
2652 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2653 if (!C || C->getZExtValue() != 8)
2660 Parts[Num] = N0.getOperand(0).getNode();
2664 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2665 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2666 /// => (rotl (bswap x), 16)
2667 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2668 if (!LegalOperations)
2671 EVT VT = N->getValueType(0);
2674 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2677 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2679 // (or (or (and), (and)), (or (and), (and)))
2680 // (or (or (or (and), (and)), (and)), (and))
2681 if (N0.getOpcode() != ISD::OR)
2683 SDValue N00 = N0.getOperand(0);
2684 SDValue N01 = N0.getOperand(1);
2686 if (N1.getOpcode() == ISD::OR) {
2687 // (or (or (and), (and)), (or (and), (and)))
2688 SDValue N000 = N00.getOperand(0);
2689 if (!isBSwapHWordElement(N000, Parts))
2692 SDValue N001 = N00.getOperand(1);
2693 if (!isBSwapHWordElement(N001, Parts))
2695 SDValue N010 = N01.getOperand(0);
2696 if (!isBSwapHWordElement(N010, Parts))
2698 SDValue N011 = N01.getOperand(1);
2699 if (!isBSwapHWordElement(N011, Parts))
2702 // (or (or (or (and), (and)), (and)), (and))
2703 if (!isBSwapHWordElement(N1, Parts))
2705 if (!isBSwapHWordElement(N01, Parts))
2707 if (N00.getOpcode() != ISD::OR)
2709 SDValue N000 = N00.getOperand(0);
2710 if (!isBSwapHWordElement(N000, Parts))
2712 SDValue N001 = N00.getOperand(1);
2713 if (!isBSwapHWordElement(N001, Parts))
2717 // Make sure the parts are all coming from the same node.
2718 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2721 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2722 SDValue(Parts[0],0));
2724 // Result of the bswap should be rotated by 16. If it's not legal, than
2725 // do (x << 16) | (x >> 16).
2726 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2727 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2728 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2729 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2730 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2731 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2732 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2733 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2736 SDValue DAGCombiner::visitOR(SDNode *N) {
2737 SDValue N0 = N->getOperand(0);
2738 SDValue N1 = N->getOperand(1);
2739 SDValue LL, LR, RL, RR, CC0, CC1;
2740 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2741 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2742 EVT VT = N1.getValueType();
2745 if (VT.isVector()) {
2746 SDValue FoldedVOp = SimplifyVBinOp(N);
2747 if (FoldedVOp.getNode()) return FoldedVOp;
2750 // fold (or x, undef) -> -1
2751 if (!LegalOperations &&
2752 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2753 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2754 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2756 // fold (or c1, c2) -> c1|c2
2758 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2759 // canonicalize constant to RHS
2761 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2762 // fold (or x, 0) -> x
2763 if (N1C && N1C->isNullValue())
2765 // fold (or x, -1) -> -1
2766 if (N1C && N1C->isAllOnesValue())
2768 // fold (or x, c) -> c iff (x & ~c) == 0
2769 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2772 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
2773 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
2774 if (BSwap.getNode() != 0)
2776 BSwap = MatchBSwapHWordLow(N, N0, N1);
2777 if (BSwap.getNode() != 0)
2781 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2782 if (ROR.getNode() != 0)
2784 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2785 // iff (c1 & c2) == 0.
2786 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2787 isa<ConstantSDNode>(N0.getOperand(1))) {
2788 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2789 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2790 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2791 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2792 N0.getOperand(0), N1),
2793 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2795 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2796 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2797 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2798 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2800 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2801 LL.getValueType().isInteger()) {
2802 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2803 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2804 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2805 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2806 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2807 LR.getValueType(), LL, RL);
2808 AddToWorkList(ORNode.getNode());
2809 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2811 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2812 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2813 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2814 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2815 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2816 LR.getValueType(), LL, RL);
2817 AddToWorkList(ANDNode.getNode());
2818 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2821 // canonicalize equivalent to ll == rl
2822 if (LL == RR && LR == RL) {
2823 Op1 = ISD::getSetCCSwappedOperands(Op1);
2826 if (LL == RL && LR == RR) {
2827 bool isInteger = LL.getValueType().isInteger();
2828 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2829 if (Result != ISD::SETCC_INVALID &&
2830 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2831 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2836 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2837 if (N0.getOpcode() == N1.getOpcode()) {
2838 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2839 if (Tmp.getNode()) return Tmp;
2842 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2843 if (N0.getOpcode() == ISD::AND &&
2844 N1.getOpcode() == ISD::AND &&
2845 N0.getOperand(1).getOpcode() == ISD::Constant &&
2846 N1.getOperand(1).getOpcode() == ISD::Constant &&
2847 // Don't increase # computations.
2848 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2849 // We can only do this xform if we know that bits from X that are set in C2
2850 // but not in C1 are already zero. Likewise for Y.
2851 const APInt &LHSMask =
2852 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2853 const APInt &RHSMask =
2854 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2856 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2857 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2858 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2859 N0.getOperand(0), N1.getOperand(0));
2860 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2861 DAG.getConstant(LHSMask | RHSMask, VT));
2865 // See if this is some rotate idiom.
2866 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2867 return SDValue(Rot, 0);
2869 // Simplify the operands using demanded-bits information.
2870 if (!VT.isVector() &&
2871 SimplifyDemandedBits(SDValue(N, 0)))
2872 return SDValue(N, 0);
2877 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2878 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2879 if (Op.getOpcode() == ISD::AND) {
2880 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2881 Mask = Op.getOperand(1);
2882 Op = Op.getOperand(0);
2888 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2896 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2897 // idioms for rotate, and if the target supports rotation instructions, generate
2899 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2900 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2901 EVT VT = LHS.getValueType();
2902 if (!TLI.isTypeLegal(VT)) return 0;
2904 // The target must have at least one rotate flavor.
2905 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2906 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2907 if (!HasROTL && !HasROTR) return 0;
2909 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2910 SDValue LHSShift; // The shift.
2911 SDValue LHSMask; // AND value if any.
2912 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2913 return 0; // Not part of a rotate.
2915 SDValue RHSShift; // The shift.
2916 SDValue RHSMask; // AND value if any.
2917 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2918 return 0; // Not part of a rotate.
2920 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2921 return 0; // Not shifting the same value.
2923 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2924 return 0; // Shifts must disagree.
2926 // Canonicalize shl to left side in a shl/srl pair.
2927 if (RHSShift.getOpcode() == ISD::SHL) {
2928 std::swap(LHS, RHS);
2929 std::swap(LHSShift, RHSShift);
2930 std::swap(LHSMask , RHSMask );
2933 unsigned OpSizeInBits = VT.getSizeInBits();
2934 SDValue LHSShiftArg = LHSShift.getOperand(0);
2935 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2936 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2938 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2939 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2940 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2941 RHSShiftAmt.getOpcode() == ISD::Constant) {
2942 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2943 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2944 if ((LShVal + RShVal) != OpSizeInBits)
2949 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2951 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2953 // If there is an AND of either shifted operand, apply it to the result.
2954 if (LHSMask.getNode() || RHSMask.getNode()) {
2955 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2957 if (LHSMask.getNode()) {
2958 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2959 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2961 if (RHSMask.getNode()) {
2962 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2963 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2966 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2969 return Rot.getNode();
2972 // If there is a mask here, and we have a variable shift, we can't be sure
2973 // that we're masking out the right stuff.
2974 if (LHSMask.getNode() || RHSMask.getNode())
2977 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2978 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2979 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2980 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2981 if (ConstantSDNode *SUBC =
2982 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2983 if (SUBC->getAPIntValue() == OpSizeInBits) {
2985 return DAG.getNode(ISD::ROTL, DL, VT,
2986 LHSShiftArg, LHSShiftAmt).getNode();
2988 return DAG.getNode(ISD::ROTR, DL, VT,
2989 LHSShiftArg, RHSShiftAmt).getNode();
2994 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2995 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2996 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2997 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2998 if (ConstantSDNode *SUBC =
2999 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3000 if (SUBC->getAPIntValue() == OpSizeInBits) {
3002 return DAG.getNode(ISD::ROTR, DL, VT,
3003 LHSShiftArg, RHSShiftAmt).getNode();
3005 return DAG.getNode(ISD::ROTL, DL, VT,
3006 LHSShiftArg, LHSShiftAmt).getNode();
3011 // Look for sign/zext/any-extended or truncate cases:
3012 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3013 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3014 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3015 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3016 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3017 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3018 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3019 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3020 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3021 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3022 if (RExtOp0.getOpcode() == ISD::SUB &&
3023 RExtOp0.getOperand(1) == LExtOp0) {
3024 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3026 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3027 // (rotr x, (sub 32, y))
3028 if (ConstantSDNode *SUBC =
3029 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3030 if (SUBC->getAPIntValue() == OpSizeInBits) {
3031 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3033 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3036 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3037 RExtOp0 == LExtOp0.getOperand(1)) {
3038 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3040 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3041 // (rotl x, (sub 32, y))
3042 if (ConstantSDNode *SUBC =
3043 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3044 if (SUBC->getAPIntValue() == OpSizeInBits) {
3045 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3047 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3056 SDValue DAGCombiner::visitXOR(SDNode *N) {
3057 SDValue N0 = N->getOperand(0);
3058 SDValue N1 = N->getOperand(1);
3059 SDValue LHS, RHS, CC;
3060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3062 EVT VT = N0.getValueType();
3065 if (VT.isVector()) {
3066 SDValue FoldedVOp = SimplifyVBinOp(N);
3067 if (FoldedVOp.getNode()) return FoldedVOp;
3070 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3071 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3072 return DAG.getConstant(0, VT);
3073 // fold (xor x, undef) -> undef
3074 if (N0.getOpcode() == ISD::UNDEF)
3076 if (N1.getOpcode() == ISD::UNDEF)
3078 // fold (xor c1, c2) -> c1^c2
3080 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3081 // canonicalize constant to RHS
3083 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3084 // fold (xor x, 0) -> x
3085 if (N1C && N1C->isNullValue())
3088 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3089 if (RXOR.getNode() != 0)
3092 // fold !(x cc y) -> (x !cc y)
3093 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3094 bool isInt = LHS.getValueType().isInteger();
3095 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3098 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3099 switch (N0.getOpcode()) {
3101 llvm_unreachable("Unhandled SetCC Equivalent!");
3103 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3104 case ISD::SELECT_CC:
3105 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3106 N0.getOperand(3), NotCC);
3111 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3112 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3113 N0.getNode()->hasOneUse() &&
3114 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3115 SDValue V = N0.getOperand(0);
3116 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3117 DAG.getConstant(1, V.getValueType()));
3118 AddToWorkList(V.getNode());
3119 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3122 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3123 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3124 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3125 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3126 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3127 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3128 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3129 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3130 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3131 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3134 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3135 if (N1C && N1C->isAllOnesValue() &&
3136 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3137 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3138 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3139 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3140 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3141 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3142 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3143 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3146 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3147 if (N1C && N0.getOpcode() == ISD::XOR) {
3148 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3149 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3151 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3152 DAG.getConstant(N1C->getAPIntValue() ^
3153 N00C->getAPIntValue(), VT));
3155 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3156 DAG.getConstant(N1C->getAPIntValue() ^
3157 N01C->getAPIntValue(), VT));
3159 // fold (xor x, x) -> 0
3161 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3163 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3164 if (N0.getOpcode() == N1.getOpcode()) {
3165 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3166 if (Tmp.getNode()) return Tmp;
3169 // Simplify the expression using non-local knowledge.
3170 if (!VT.isVector() &&
3171 SimplifyDemandedBits(SDValue(N, 0)))
3172 return SDValue(N, 0);
3177 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3178 /// the shift amount is a constant.
3179 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3180 SDNode *LHS = N->getOperand(0).getNode();
3181 if (!LHS->hasOneUse()) return SDValue();
3183 // We want to pull some binops through shifts, so that we have (and (shift))
3184 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3185 // thing happens with address calculations, so it's important to canonicalize
3187 bool HighBitSet = false; // Can we transform this if the high bit is set?
3189 switch (LHS->getOpcode()) {
3190 default: return SDValue();
3193 HighBitSet = false; // We can only transform sra if the high bit is clear.
3196 HighBitSet = true; // We can only transform sra if the high bit is set.
3199 if (N->getOpcode() != ISD::SHL)
3200 return SDValue(); // only shl(add) not sr[al](add).
3201 HighBitSet = false; // We can only transform sra if the high bit is clear.
3205 // We require the RHS of the binop to be a constant as well.
3206 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3207 if (!BinOpCst) return SDValue();
3209 // FIXME: disable this unless the input to the binop is a shift by a constant.
3210 // If it is not a shift, it pessimizes some common cases like:
3212 // void foo(int *X, int i) { X[i & 1235] = 1; }
3213 // int bar(int *X, int i) { return X[i & 255]; }
3214 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3215 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3216 BinOpLHSVal->getOpcode() != ISD::SRA &&
3217 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3218 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3221 EVT VT = N->getValueType(0);
3223 // If this is a signed shift right, and the high bit is modified by the
3224 // logical operation, do not perform the transformation. The highBitSet
3225 // boolean indicates the value of the high bit of the constant which would
3226 // cause it to be modified for this operation.
3227 if (N->getOpcode() == ISD::SRA) {
3228 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3229 if (BinOpRHSSignSet != HighBitSet)
3233 // Fold the constants, shifting the binop RHS by the shift amount.
3234 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3236 LHS->getOperand(1), N->getOperand(1));
3238 // Create the new shift.
3239 SDValue NewShift = DAG.getNode(N->getOpcode(),
3240 LHS->getOperand(0).getDebugLoc(),
3241 VT, LHS->getOperand(0), N->getOperand(1));
3243 // Create the new binop.
3244 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3247 SDValue DAGCombiner::visitSHL(SDNode *N) {
3248 SDValue N0 = N->getOperand(0);
3249 SDValue N1 = N->getOperand(1);
3250 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3252 EVT VT = N0.getValueType();
3253 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3255 // fold (shl c1, c2) -> c1<<c2
3257 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3258 // fold (shl 0, x) -> 0
3259 if (N0C && N0C->isNullValue())
3261 // fold (shl x, c >= size(x)) -> undef
3262 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3263 return DAG.getUNDEF(VT);
3264 // fold (shl x, 0) -> x
3265 if (N1C && N1C->isNullValue())
3267 // fold (shl undef, x) -> 0
3268 if (N0.getOpcode() == ISD::UNDEF)
3269 return DAG.getConstant(0, VT);
3270 // if (shl x, c) is known to be zero, return 0
3271 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3272 APInt::getAllOnesValue(OpSizeInBits)))
3273 return DAG.getConstant(0, VT);
3274 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3275 if (N1.getOpcode() == ISD::TRUNCATE &&
3276 N1.getOperand(0).getOpcode() == ISD::AND &&
3277 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3278 SDValue N101 = N1.getOperand(0).getOperand(1);
3279 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3280 EVT TruncVT = N1.getValueType();
3281 SDValue N100 = N1.getOperand(0).getOperand(0);
3282 APInt TruncC = N101C->getAPIntValue();
3283 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3284 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3285 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3286 DAG.getNode(ISD::TRUNCATE,
3289 DAG.getConstant(TruncC, TruncVT)));
3293 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3294 return SDValue(N, 0);
3296 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3297 if (N1C && N0.getOpcode() == ISD::SHL &&
3298 N0.getOperand(1).getOpcode() == ISD::Constant) {
3299 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3300 uint64_t c2 = N1C->getZExtValue();
3301 if (c1 + c2 >= OpSizeInBits)
3302 return DAG.getConstant(0, VT);
3303 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3304 DAG.getConstant(c1 + c2, N1.getValueType()));
3307 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3308 // For this to be valid, the second form must not preserve any of the bits
3309 // that are shifted out by the inner shift in the first form. This means
3310 // the outer shift size must be >= the number of bits added by the ext.
3311 // As a corollary, we don't care what kind of ext it is.
3312 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3313 N0.getOpcode() == ISD::ANY_EXTEND ||
3314 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3315 N0.getOperand(0).getOpcode() == ISD::SHL &&
3316 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3318 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3319 uint64_t c2 = N1C->getZExtValue();
3320 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3321 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3322 if (c2 >= OpSizeInBits - InnerShiftSize) {
3323 if (c1 + c2 >= OpSizeInBits)
3324 return DAG.getConstant(0, VT);
3325 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3326 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3327 N0.getOperand(0)->getOperand(0)),
3328 DAG.getConstant(c1 + c2, N1.getValueType()));
3332 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3333 // (and (srl x, (sub c1, c2), MASK)
3334 if (N1C && N0.getOpcode() == ISD::SRL &&
3335 N0.getOperand(1).getOpcode() == ISD::Constant) {
3336 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3337 if (c1 < VT.getSizeInBits()) {
3338 uint64_t c2 = N1C->getZExtValue();
3339 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3340 VT.getSizeInBits() - c1);
3343 Mask = Mask.shl(c2-c1);
3344 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3345 DAG.getConstant(c2-c1, N1.getValueType()));
3347 Mask = Mask.lshr(c1-c2);
3348 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3349 DAG.getConstant(c1-c2, N1.getValueType()));
3351 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3352 DAG.getConstant(Mask, VT));
3355 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3356 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3357 SDValue HiBitsMask =
3358 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3359 VT.getSizeInBits() -
3360 N1C->getZExtValue()),
3362 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3367 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3368 if (NewSHL.getNode())
3375 SDValue DAGCombiner::visitSRA(SDNode *N) {
3376 SDValue N0 = N->getOperand(0);
3377 SDValue N1 = N->getOperand(1);
3378 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3379 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3380 EVT VT = N0.getValueType();
3381 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3383 // fold (sra c1, c2) -> (sra c1, c2)
3385 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3386 // fold (sra 0, x) -> 0
3387 if (N0C && N0C->isNullValue())
3389 // fold (sra -1, x) -> -1
3390 if (N0C && N0C->isAllOnesValue())
3392 // fold (sra x, (setge c, size(x))) -> undef
3393 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3394 return DAG.getUNDEF(VT);
3395 // fold (sra x, 0) -> x
3396 if (N1C && N1C->isNullValue())
3398 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3400 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3401 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3402 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3404 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3405 ExtVT, VT.getVectorNumElements());
3406 if ((!LegalOperations ||
3407 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3408 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3409 N0.getOperand(0), DAG.getValueType(ExtVT));
3412 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3413 if (N1C && N0.getOpcode() == ISD::SRA) {
3414 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3415 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3416 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3417 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3418 DAG.getConstant(Sum, N1C->getValueType(0)));
3422 // fold (sra (shl X, m), (sub result_size, n))
3423 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3424 // result_size - n != m.
3425 // If truncate is free for the target sext(shl) is likely to result in better
3427 if (N0.getOpcode() == ISD::SHL) {
3428 // Get the two constanst of the shifts, CN0 = m, CN = n.
3429 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3431 // Determine what the truncate's result bitsize and type would be.
3433 EVT::getIntegerVT(*DAG.getContext(),
3434 OpSizeInBits - N1C->getZExtValue());
3435 // Determine the residual right-shift amount.
3436 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3438 // If the shift is not a no-op (in which case this should be just a sign
3439 // extend already), the truncated to type is legal, sign_extend is legal
3440 // on that type, and the truncate to that type is both legal and free,
3441 // perform the transform.
3442 if ((ShiftAmt > 0) &&
3443 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3444 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3445 TLI.isTruncateFree(VT, TruncVT)) {
3447 SDValue Amt = DAG.getConstant(ShiftAmt,
3448 getShiftAmountTy(N0.getOperand(0).getValueType()));
3449 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3450 N0.getOperand(0), Amt);
3451 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3453 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3454 N->getValueType(0), Trunc);
3459 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3460 if (N1.getOpcode() == ISD::TRUNCATE &&
3461 N1.getOperand(0).getOpcode() == ISD::AND &&
3462 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3463 SDValue N101 = N1.getOperand(0).getOperand(1);
3464 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3465 EVT TruncVT = N1.getValueType();
3466 SDValue N100 = N1.getOperand(0).getOperand(0);
3467 APInt TruncC = N101C->getAPIntValue();
3468 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3469 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3470 DAG.getNode(ISD::AND, N->getDebugLoc(),
3472 DAG.getNode(ISD::TRUNCATE,
3475 DAG.getConstant(TruncC, TruncVT)));
3479 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3480 // if c1 is equal to the number of bits the trunc removes
3481 if (N0.getOpcode() == ISD::TRUNCATE &&
3482 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3483 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3484 N0.getOperand(0).hasOneUse() &&
3485 N0.getOperand(0).getOperand(1).hasOneUse() &&
3486 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3487 EVT LargeVT = N0.getOperand(0).getValueType();
3488 ConstantSDNode *LargeShiftAmt =
3489 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3491 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3492 LargeShiftAmt->getZExtValue()) {
3494 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3495 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3496 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3497 N0.getOperand(0).getOperand(0), Amt);
3498 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3502 // Simplify, based on bits shifted out of the LHS.
3503 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3504 return SDValue(N, 0);
3507 // If the sign bit is known to be zero, switch this to a SRL.
3508 if (DAG.SignBitIsZero(N0))
3509 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3512 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3513 if (NewSRA.getNode())
3520 SDValue DAGCombiner::visitSRL(SDNode *N) {
3521 SDValue N0 = N->getOperand(0);
3522 SDValue N1 = N->getOperand(1);
3523 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3524 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3525 EVT VT = N0.getValueType();
3526 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3528 // fold (srl c1, c2) -> c1 >>u c2
3530 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3531 // fold (srl 0, x) -> 0
3532 if (N0C && N0C->isNullValue())
3534 // fold (srl x, c >= size(x)) -> undef
3535 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3536 return DAG.getUNDEF(VT);
3537 // fold (srl x, 0) -> x
3538 if (N1C && N1C->isNullValue())
3540 // if (srl x, c) is known to be zero, return 0
3541 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3542 APInt::getAllOnesValue(OpSizeInBits)))
3543 return DAG.getConstant(0, VT);
3545 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3546 if (N1C && N0.getOpcode() == ISD::SRL &&
3547 N0.getOperand(1).getOpcode() == ISD::Constant) {
3548 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3549 uint64_t c2 = N1C->getZExtValue();
3550 if (c1 + c2 >= OpSizeInBits)
3551 return DAG.getConstant(0, VT);
3552 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3553 DAG.getConstant(c1 + c2, N1.getValueType()));
3556 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3557 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3558 N0.getOperand(0).getOpcode() == ISD::SRL &&
3559 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3561 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3562 uint64_t c2 = N1C->getZExtValue();
3563 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3564 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3565 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3566 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3567 if (c1 + OpSizeInBits == InnerShiftSize) {
3568 if (c1 + c2 >= InnerShiftSize)
3569 return DAG.getConstant(0, VT);
3570 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3571 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3572 N0.getOperand(0)->getOperand(0),
3573 DAG.getConstant(c1 + c2, ShiftCountVT)));
3577 // fold (srl (shl x, c), c) -> (and x, cst2)
3578 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3579 N0.getValueSizeInBits() <= 64) {
3580 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3581 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3582 DAG.getConstant(~0ULL >> ShAmt, VT));
3586 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3587 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3588 // Shifting in all undef bits?
3589 EVT SmallVT = N0.getOperand(0).getValueType();
3590 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3591 return DAG.getUNDEF(VT);
3593 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3594 uint64_t ShiftAmt = N1C->getZExtValue();
3595 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3597 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3598 AddToWorkList(SmallShift.getNode());
3599 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3603 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3604 // bit, which is unmodified by sra.
3605 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3606 if (N0.getOpcode() == ISD::SRA)
3607 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3610 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3611 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3612 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3613 APInt KnownZero, KnownOne;
3614 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3615 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3617 // If any of the input bits are KnownOne, then the input couldn't be all
3618 // zeros, thus the result of the srl will always be zero.
3619 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3621 // If all of the bits input the to ctlz node are known to be zero, then
3622 // the result of the ctlz is "32" and the result of the shift is one.
3623 APInt UnknownBits = ~KnownZero & Mask;
3624 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3626 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3627 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3628 // Okay, we know that only that the single bit specified by UnknownBits
3629 // could be set on input to the CTLZ node. If this bit is set, the SRL
3630 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3631 // to an SRL/XOR pair, which is likely to simplify more.
3632 unsigned ShAmt = UnknownBits.countTrailingZeros();
3633 SDValue Op = N0.getOperand(0);
3636 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3637 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3638 AddToWorkList(Op.getNode());
3641 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3642 Op, DAG.getConstant(1, VT));
3646 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3647 if (N1.getOpcode() == ISD::TRUNCATE &&
3648 N1.getOperand(0).getOpcode() == ISD::AND &&
3649 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3650 SDValue N101 = N1.getOperand(0).getOperand(1);
3651 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3652 EVT TruncVT = N1.getValueType();
3653 SDValue N100 = N1.getOperand(0).getOperand(0);
3654 APInt TruncC = N101C->getAPIntValue();
3655 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3656 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3657 DAG.getNode(ISD::AND, N->getDebugLoc(),
3659 DAG.getNode(ISD::TRUNCATE,
3662 DAG.getConstant(TruncC, TruncVT)));
3666 // fold operands of srl based on knowledge that the low bits are not
3668 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3669 return SDValue(N, 0);
3672 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3673 if (NewSRL.getNode())
3677 // Attempt to convert a srl of a load into a narrower zero-extending load.
3678 SDValue NarrowLoad = ReduceLoadWidth(N);
3679 if (NarrowLoad.getNode())
3682 // Here is a common situation. We want to optimize:
3685 // %b = and i32 %a, 2
3686 // %c = srl i32 %b, 1
3687 // brcond i32 %c ...
3693 // %c = setcc eq %b, 0
3696 // However when after the source operand of SRL is optimized into AND, the SRL
3697 // itself may not be optimized further. Look for it and add the BRCOND into
3699 if (N->hasOneUse()) {
3700 SDNode *Use = *N->use_begin();
3701 if (Use->getOpcode() == ISD::BRCOND)
3703 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3704 // Also look pass the truncate.
3705 Use = *Use->use_begin();
3706 if (Use->getOpcode() == ISD::BRCOND)
3714 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3715 SDValue N0 = N->getOperand(0);
3716 EVT VT = N->getValueType(0);
3718 // fold (ctlz c1) -> c2
3719 if (isa<ConstantSDNode>(N0))
3720 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3724 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3725 SDValue N0 = N->getOperand(0);
3726 EVT VT = N->getValueType(0);
3728 // fold (ctlz_zero_undef c1) -> c2
3729 if (isa<ConstantSDNode>(N0))
3730 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3734 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3735 SDValue N0 = N->getOperand(0);
3736 EVT VT = N->getValueType(0);
3738 // fold (cttz c1) -> c2
3739 if (isa<ConstantSDNode>(N0))
3740 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3744 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
3745 SDValue N0 = N->getOperand(0);
3746 EVT VT = N->getValueType(0);
3748 // fold (cttz_zero_undef c1) -> c2
3749 if (isa<ConstantSDNode>(N0))
3750 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3754 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3755 SDValue N0 = N->getOperand(0);
3756 EVT VT = N->getValueType(0);
3758 // fold (ctpop c1) -> c2
3759 if (isa<ConstantSDNode>(N0))
3760 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3764 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3765 SDValue N0 = N->getOperand(0);
3766 SDValue N1 = N->getOperand(1);
3767 SDValue N2 = N->getOperand(2);
3768 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3770 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3771 EVT VT = N->getValueType(0);
3772 EVT VT0 = N0.getValueType();
3774 // fold (select C, X, X) -> X
3777 // fold (select true, X, Y) -> X
3778 if (N0C && !N0C->isNullValue())
3780 // fold (select false, X, Y) -> Y
3781 if (N0C && N0C->isNullValue())
3783 // fold (select C, 1, X) -> (or C, X)
3784 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3785 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3786 // fold (select C, 0, 1) -> (xor C, 1)
3787 if (VT.isInteger() &&
3790 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
3791 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3794 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3795 N0, DAG.getConstant(1, VT0));
3796 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3797 N0, DAG.getConstant(1, VT0));
3798 AddToWorkList(XORNode.getNode());
3800 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3801 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3803 // fold (select C, 0, X) -> (and (not C), X)
3804 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3805 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3806 AddToWorkList(NOTNode.getNode());
3807 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3809 // fold (select C, X, 1) -> (or (not C), X)
3810 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3811 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3812 AddToWorkList(NOTNode.getNode());
3813 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3815 // fold (select C, X, 0) -> (and C, X)
3816 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3817 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3818 // fold (select X, X, Y) -> (or X, Y)
3819 // fold (select X, 1, Y) -> (or X, Y)
3820 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3821 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3822 // fold (select X, Y, X) -> (and X, Y)
3823 // fold (select X, Y, 0) -> (and X, Y)
3824 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3825 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3827 // If we can fold this based on the true/false value, do so.
3828 if (SimplifySelectOps(N, N1, N2))
3829 return SDValue(N, 0); // Don't revisit N.
3831 // fold selects based on a setcc into other things, such as min/max/abs
3832 if (N0.getOpcode() == ISD::SETCC) {
3834 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3835 // having to say they don't support SELECT_CC on every type the DAG knows
3836 // about, since there is no way to mark an opcode illegal at all value types
3837 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3838 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3839 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3840 N0.getOperand(0), N0.getOperand(1),
3841 N1, N2, N0.getOperand(2));
3842 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3848 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3849 SDValue N0 = N->getOperand(0);
3850 SDValue N1 = N->getOperand(1);
3851 SDValue N2 = N->getOperand(2);
3852 SDValue N3 = N->getOperand(3);
3853 SDValue N4 = N->getOperand(4);
3854 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3856 // fold select_cc lhs, rhs, x, x, cc -> x
3860 // Determine if the condition we're dealing with is constant
3861 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3862 N0, N1, CC, N->getDebugLoc(), false);
3863 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3865 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3866 if (!SCCC->isNullValue())
3867 return N2; // cond always true -> true val
3869 return N3; // cond always false -> false val
3872 // Fold to a simpler select_cc
3873 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3874 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3875 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3878 // If we can fold this based on the true/false value, do so.
3879 if (SimplifySelectOps(N, N2, N3))
3880 return SDValue(N, 0); // Don't revisit N.
3882 // fold select_cc into other things, such as min/max/abs
3883 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3886 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3887 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3888 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3892 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3893 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3894 // transformation. Returns true if extension are possible and the above
3895 // mentioned transformation is profitable.
3896 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3898 SmallVector<SDNode*, 4> &ExtendNodes,
3899 const TargetLowering &TLI) {
3900 bool HasCopyToRegUses = false;
3901 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3902 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3903 UE = N0.getNode()->use_end();
3908 if (UI.getUse().getResNo() != N0.getResNo())
3910 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3911 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3912 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3913 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3914 // Sign bits will be lost after a zext.
3917 for (unsigned i = 0; i != 2; ++i) {
3918 SDValue UseOp = User->getOperand(i);
3921 if (!isa<ConstantSDNode>(UseOp))
3926 ExtendNodes.push_back(User);
3929 // If truncates aren't free and there are users we can't
3930 // extend, it isn't worthwhile.
3933 // Remember if this value is live-out.
3934 if (User->getOpcode() == ISD::CopyToReg)
3935 HasCopyToRegUses = true;
3938 if (HasCopyToRegUses) {
3939 bool BothLiveOut = false;
3940 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3942 SDUse &Use = UI.getUse();
3943 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3949 // Both unextended and extended values are live out. There had better be
3950 // a good reason for the transformation.
3951 return ExtendNodes.size();
3956 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
3957 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
3958 ISD::NodeType ExtType) {
3959 // Extend SetCC uses if necessary.
3960 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3961 SDNode *SetCC = SetCCs[i];
3962 SmallVector<SDValue, 4> Ops;
3964 for (unsigned j = 0; j != 2; ++j) {
3965 SDValue SOp = SetCC->getOperand(j);
3967 Ops.push_back(ExtLoad);
3969 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
3972 Ops.push_back(SetCC->getOperand(2));
3973 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
3974 &Ops[0], Ops.size()));
3978 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3979 SDValue N0 = N->getOperand(0);
3980 EVT VT = N->getValueType(0);
3982 // fold (sext c1) -> c1
3983 if (isa<ConstantSDNode>(N0))
3984 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3986 // fold (sext (sext x)) -> (sext x)
3987 // fold (sext (aext x)) -> (sext x)
3988 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3989 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3992 if (N0.getOpcode() == ISD::TRUNCATE) {
3993 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3994 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3995 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3996 if (NarrowLoad.getNode()) {
3997 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3998 if (NarrowLoad.getNode() != N0.getNode()) {
3999 CombineTo(N0.getNode(), NarrowLoad);
4000 // CombineTo deleted the truncate, if needed, but not what's under it.
4003 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4006 // See if the value being truncated is already sign extended. If so, just
4007 // eliminate the trunc/sext pair.
4008 SDValue Op = N0.getOperand(0);
4009 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4010 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4011 unsigned DestBits = VT.getScalarType().getSizeInBits();
4012 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4014 if (OpBits == DestBits) {
4015 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4016 // bits, it is already ready.
4017 if (NumSignBits > DestBits-MidBits)
4019 } else if (OpBits < DestBits) {
4020 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4021 // bits, just sext from i32.
4022 if (NumSignBits > OpBits-MidBits)
4023 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4025 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4026 // bits, just truncate to i32.
4027 if (NumSignBits > OpBits-MidBits)
4028 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4031 // fold (sext (truncate x)) -> (sextinreg x).
4032 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4033 N0.getValueType())) {
4034 if (OpBits < DestBits)
4035 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4036 else if (OpBits > DestBits)
4037 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4038 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4039 DAG.getValueType(N0.getValueType()));
4043 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4044 // None of the supported targets knows how to perform load and sign extend
4045 // on vectors in one instruction. We only perform this transformation on
4047 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4048 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4049 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4050 bool DoXform = true;
4051 SmallVector<SDNode*, 4> SetCCs;
4052 if (!N0.hasOneUse())
4053 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4055 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4056 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4058 LN0->getBasePtr(), LN0->getPointerInfo(),
4060 LN0->isVolatile(), LN0->isNonTemporal(),
4061 LN0->getAlignment());
4062 CombineTo(N, ExtLoad);
4063 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4064 N0.getValueType(), ExtLoad);
4065 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4066 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4068 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4072 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4073 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4074 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4075 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4076 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4077 EVT MemVT = LN0->getMemoryVT();
4078 if ((!LegalOperations && !LN0->isVolatile()) ||
4079 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4080 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4082 LN0->getBasePtr(), LN0->getPointerInfo(),
4084 LN0->isVolatile(), LN0->isNonTemporal(),
4085 LN0->getAlignment());
4086 CombineTo(N, ExtLoad);
4087 CombineTo(N0.getNode(),
4088 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4089 N0.getValueType(), ExtLoad),
4090 ExtLoad.getValue(1));
4091 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4095 // fold (sext (and/or/xor (load x), cst)) ->
4096 // (and/or/xor (sextload x), (sext cst))
4097 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4098 N0.getOpcode() == ISD::XOR) &&
4099 isa<LoadSDNode>(N0.getOperand(0)) &&
4100 N0.getOperand(1).getOpcode() == ISD::Constant &&
4101 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4102 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4103 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4104 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4105 bool DoXform = true;
4106 SmallVector<SDNode*, 4> SetCCs;
4107 if (!N0.hasOneUse())
4108 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4111 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4112 LN0->getChain(), LN0->getBasePtr(),
4113 LN0->getPointerInfo(),
4116 LN0->isNonTemporal(),
4117 LN0->getAlignment());
4118 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4119 Mask = Mask.sext(VT.getSizeInBits());
4120 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4121 ExtLoad, DAG.getConstant(Mask, VT));
4122 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4123 N0.getOperand(0).getDebugLoc(),
4124 N0.getOperand(0).getValueType(), ExtLoad);
4126 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4127 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4129 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4134 if (N0.getOpcode() == ISD::SETCC) {
4135 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4136 // Only do this before legalize for now.
4137 if (VT.isVector() && !LegalOperations) {
4138 EVT N0VT = N0.getOperand(0).getValueType();
4139 // We know that the # elements of the results is the same as the
4140 // # elements of the compare (and the # elements of the compare result
4141 // for that matter). Check to see that they are the same size. If so,
4142 // we know that the element size of the sext'd result matches the
4143 // element size of the compare operands.
4144 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4145 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4147 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4148 // If the desired elements are smaller or larger than the source
4149 // elements we can use a matching integer vector type and then
4150 // truncate/sign extend
4152 EVT MatchingElementType =
4153 EVT::getIntegerVT(*DAG.getContext(),
4154 N0VT.getScalarType().getSizeInBits());
4155 EVT MatchingVectorType =
4156 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4157 N0VT.getVectorNumElements());
4159 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4161 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4162 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4166 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4167 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4169 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4171 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4172 NegOne, DAG.getConstant(0, VT),
4173 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4174 if (SCC.getNode()) return SCC;
4175 if (!LegalOperations ||
4176 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4177 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4178 DAG.getSetCC(N->getDebugLoc(),
4179 TLI.getSetCCResultType(VT),
4180 N0.getOperand(0), N0.getOperand(1),
4181 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4182 NegOne, DAG.getConstant(0, VT));
4185 // fold (sext x) -> (zext x) if the sign bit is known zero.
4186 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4187 DAG.SignBitIsZero(N0))
4188 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4193 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4194 SDValue N0 = N->getOperand(0);
4195 EVT VT = N->getValueType(0);
4197 // fold (zext c1) -> c1
4198 if (isa<ConstantSDNode>(N0))
4199 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4200 // fold (zext (zext x)) -> (zext x)
4201 // fold (zext (aext x)) -> (zext x)
4202 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4203 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4206 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4207 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4208 if (N0.getOpcode() == ISD::TRUNCATE) {
4209 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4210 if (NarrowLoad.getNode()) {
4211 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4212 if (NarrowLoad.getNode() != N0.getNode()) {
4213 CombineTo(N0.getNode(), NarrowLoad);
4214 // CombineTo deleted the truncate, if needed, but not what's under it.
4217 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4221 // fold (zext (truncate x)) -> (and x, mask)
4222 if (N0.getOpcode() == ISD::TRUNCATE &&
4223 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4225 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4226 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4227 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4228 if (NarrowLoad.getNode()) {
4229 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4230 if (NarrowLoad.getNode() != N0.getNode()) {
4231 CombineTo(N0.getNode(), NarrowLoad);
4232 // CombineTo deleted the truncate, if needed, but not what's under it.
4235 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4238 SDValue Op = N0.getOperand(0);
4239 if (Op.getValueType().bitsLT(VT)) {
4240 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4241 } else if (Op.getValueType().bitsGT(VT)) {
4242 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4244 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4245 N0.getValueType().getScalarType());
4248 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4249 // if either of the casts is not free.
4250 if (N0.getOpcode() == ISD::AND &&
4251 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4252 N0.getOperand(1).getOpcode() == ISD::Constant &&
4253 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4254 N0.getValueType()) ||
4255 !TLI.isZExtFree(N0.getValueType(), VT))) {
4256 SDValue X = N0.getOperand(0).getOperand(0);
4257 if (X.getValueType().bitsLT(VT)) {
4258 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4259 } else if (X.getValueType().bitsGT(VT)) {
4260 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4262 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4263 Mask = Mask.zext(VT.getSizeInBits());
4264 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4265 X, DAG.getConstant(Mask, VT));
4268 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4269 // None of the supported targets knows how to perform load and vector_zext
4270 // on vectors in one instruction. We only perform this transformation on
4272 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4273 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4274 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4275 bool DoXform = true;
4276 SmallVector<SDNode*, 4> SetCCs;
4277 if (!N0.hasOneUse())
4278 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4280 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4281 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4283 LN0->getBasePtr(), LN0->getPointerInfo(),
4285 LN0->isVolatile(), LN0->isNonTemporal(),
4286 LN0->getAlignment());
4287 CombineTo(N, ExtLoad);
4288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4289 N0.getValueType(), ExtLoad);
4290 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4292 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4294 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4298 // fold (zext (and/or/xor (load x), cst)) ->
4299 // (and/or/xor (zextload x), (zext cst))
4300 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4301 N0.getOpcode() == ISD::XOR) &&
4302 isa<LoadSDNode>(N0.getOperand(0)) &&
4303 N0.getOperand(1).getOpcode() == ISD::Constant &&
4304 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4305 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4306 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4307 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4308 bool DoXform = true;
4309 SmallVector<SDNode*, 4> SetCCs;
4310 if (!N0.hasOneUse())
4311 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4314 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4315 LN0->getChain(), LN0->getBasePtr(),
4316 LN0->getPointerInfo(),
4319 LN0->isNonTemporal(),
4320 LN0->getAlignment());
4321 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4322 Mask = Mask.zext(VT.getSizeInBits());
4323 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4324 ExtLoad, DAG.getConstant(Mask, VT));
4325 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4326 N0.getOperand(0).getDebugLoc(),
4327 N0.getOperand(0).getValueType(), ExtLoad);
4329 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4330 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4332 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4337 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4338 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4339 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4340 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4341 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4342 EVT MemVT = LN0->getMemoryVT();
4343 if ((!LegalOperations && !LN0->isVolatile()) ||
4344 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4345 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4347 LN0->getBasePtr(), LN0->getPointerInfo(),
4349 LN0->isVolatile(), LN0->isNonTemporal(),
4350 LN0->getAlignment());
4351 CombineTo(N, ExtLoad);
4352 CombineTo(N0.getNode(),
4353 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4355 ExtLoad.getValue(1));
4356 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4360 if (N0.getOpcode() == ISD::SETCC) {
4361 if (!LegalOperations && VT.isVector()) {
4362 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4363 // Only do this before legalize for now.
4364 EVT N0VT = N0.getOperand(0).getValueType();
4365 EVT EltVT = VT.getVectorElementType();
4366 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4367 DAG.getConstant(1, EltVT));
4368 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4369 // We know that the # elements of the results is the same as the
4370 // # elements of the compare (and the # elements of the compare result
4371 // for that matter). Check to see that they are the same size. If so,
4372 // we know that the element size of the sext'd result matches the
4373 // element size of the compare operands.
4374 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4375 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4377 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4378 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4379 &OneOps[0], OneOps.size()));
4381 // If the desired elements are smaller or larger than the source
4382 // elements we can use a matching integer vector type and then
4383 // truncate/sign extend
4384 EVT MatchingElementType =
4385 EVT::getIntegerVT(*DAG.getContext(),
4386 N0VT.getScalarType().getSizeInBits());
4387 EVT MatchingVectorType =
4388 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4389 N0VT.getVectorNumElements());
4391 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4393 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4394 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4395 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4396 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4397 &OneOps[0], OneOps.size()));
4400 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4402 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4403 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4404 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4405 if (SCC.getNode()) return SCC;
4408 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4409 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4410 isa<ConstantSDNode>(N0.getOperand(1)) &&
4411 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4413 SDValue ShAmt = N0.getOperand(1);
4414 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4415 if (N0.getOpcode() == ISD::SHL) {
4416 SDValue InnerZExt = N0.getOperand(0);
4417 // If the original shl may be shifting out bits, do not perform this
4419 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4420 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4421 if (ShAmtVal > KnownZeroBits)
4425 DebugLoc DL = N->getDebugLoc();
4427 // Ensure that the shift amount is wide enough for the shifted value.
4428 if (VT.getSizeInBits() >= 256)
4429 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4431 return DAG.getNode(N0.getOpcode(), DL, VT,
4432 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4439 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4440 SDValue N0 = N->getOperand(0);
4441 EVT VT = N->getValueType(0);
4443 // fold (aext c1) -> c1
4444 if (isa<ConstantSDNode>(N0))
4445 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4446 // fold (aext (aext x)) -> (aext x)
4447 // fold (aext (zext x)) -> (zext x)
4448 // fold (aext (sext x)) -> (sext x)
4449 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4450 N0.getOpcode() == ISD::ZERO_EXTEND ||
4451 N0.getOpcode() == ISD::SIGN_EXTEND)
4452 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4454 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4455 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4456 if (N0.getOpcode() == ISD::TRUNCATE) {
4457 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4458 if (NarrowLoad.getNode()) {
4459 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4460 if (NarrowLoad.getNode() != N0.getNode()) {
4461 CombineTo(N0.getNode(), NarrowLoad);
4462 // CombineTo deleted the truncate, if needed, but not what's under it.
4465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4469 // fold (aext (truncate x))
4470 if (N0.getOpcode() == ISD::TRUNCATE) {
4471 SDValue TruncOp = N0.getOperand(0);
4472 if (TruncOp.getValueType() == VT)
4473 return TruncOp; // x iff x size == zext size.
4474 if (TruncOp.getValueType().bitsGT(VT))
4475 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4476 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4479 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4480 // if the trunc is not free.
4481 if (N0.getOpcode() == ISD::AND &&
4482 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4483 N0.getOperand(1).getOpcode() == ISD::Constant &&
4484 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4485 N0.getValueType())) {
4486 SDValue X = N0.getOperand(0).getOperand(0);
4487 if (X.getValueType().bitsLT(VT)) {
4488 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4489 } else if (X.getValueType().bitsGT(VT)) {
4490 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4492 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4493 Mask = Mask.zext(VT.getSizeInBits());
4494 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4495 X, DAG.getConstant(Mask, VT));
4498 // fold (aext (load x)) -> (aext (truncate (extload x)))
4499 // None of the supported targets knows how to perform load and any_ext
4500 // on vectors in one instruction. We only perform this transformation on
4502 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4503 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4504 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4505 bool DoXform = true;
4506 SmallVector<SDNode*, 4> SetCCs;
4507 if (!N0.hasOneUse())
4508 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4510 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4511 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4513 LN0->getBasePtr(), LN0->getPointerInfo(),
4515 LN0->isVolatile(), LN0->isNonTemporal(),
4516 LN0->getAlignment());
4517 CombineTo(N, ExtLoad);
4518 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4519 N0.getValueType(), ExtLoad);
4520 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4521 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4523 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4527 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4528 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4529 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4530 if (N0.getOpcode() == ISD::LOAD &&
4531 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4533 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4534 EVT MemVT = LN0->getMemoryVT();
4535 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4536 VT, LN0->getChain(), LN0->getBasePtr(),
4537 LN0->getPointerInfo(), MemVT,
4538 LN0->isVolatile(), LN0->isNonTemporal(),
4539 LN0->getAlignment());
4540 CombineTo(N, ExtLoad);
4541 CombineTo(N0.getNode(),
4542 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4543 N0.getValueType(), ExtLoad),
4544 ExtLoad.getValue(1));
4545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4548 if (N0.getOpcode() == ISD::SETCC) {
4549 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4550 // Only do this before legalize for now.
4551 if (VT.isVector() && !LegalOperations) {
4552 EVT N0VT = N0.getOperand(0).getValueType();
4553 // We know that the # elements of the results is the same as the
4554 // # elements of the compare (and the # elements of the compare result
4555 // for that matter). Check to see that they are the same size. If so,
4556 // we know that the element size of the sext'd result matches the
4557 // element size of the compare operands.
4558 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4559 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4561 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4562 // If the desired elements are smaller or larger than the source
4563 // elements we can use a matching integer vector type and then
4564 // truncate/sign extend
4566 EVT MatchingElementType =
4567 EVT::getIntegerVT(*DAG.getContext(),
4568 N0VT.getScalarType().getSizeInBits());
4569 EVT MatchingVectorType =
4570 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4571 N0VT.getVectorNumElements());
4573 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4575 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4576 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4580 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4582 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4583 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4584 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4592 /// GetDemandedBits - See if the specified operand can be simplified with the
4593 /// knowledge that only the bits specified by Mask are used. If so, return the
4594 /// simpler operand, otherwise return a null SDValue.
4595 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4596 switch (V.getOpcode()) {
4598 case ISD::Constant: {
4599 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4600 assert(CV != 0 && "Const value should be ConstSDNode.");
4601 const APInt &CVal = CV->getAPIntValue();
4602 APInt NewVal = CVal & Mask;
4603 if (NewVal != CVal) {
4604 return DAG.getConstant(NewVal, V.getValueType());
4610 // If the LHS or RHS don't contribute bits to the or, drop them.
4611 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4612 return V.getOperand(1);
4613 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4614 return V.getOperand(0);
4617 // Only look at single-use SRLs.
4618 if (!V.getNode()->hasOneUse())
4620 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4621 // See if we can recursively simplify the LHS.
4622 unsigned Amt = RHSC->getZExtValue();
4624 // Watch out for shift count overflow though.
4625 if (Amt >= Mask.getBitWidth()) break;
4626 APInt NewMask = Mask << Amt;
4627 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4628 if (SimplifyLHS.getNode())
4629 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4630 SimplifyLHS, V.getOperand(1));
4636 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4637 /// bits and then truncated to a narrower type and where N is a multiple
4638 /// of number of bits of the narrower type, transform it to a narrower load
4639 /// from address + N / num of bits of new type. If the result is to be
4640 /// extended, also fold the extension to form a extending load.
4641 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4642 unsigned Opc = N->getOpcode();
4644 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4645 SDValue N0 = N->getOperand(0);
4646 EVT VT = N->getValueType(0);
4649 // This transformation isn't valid for vector loads.
4653 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4655 if (Opc == ISD::SIGN_EXTEND_INREG) {
4656 ExtType = ISD::SEXTLOAD;
4657 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4658 } else if (Opc == ISD::SRL) {
4659 // Another special-case: SRL is basically zero-extending a narrower value.
4660 ExtType = ISD::ZEXTLOAD;
4662 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4663 if (!N01) return SDValue();
4664 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4665 VT.getSizeInBits() - N01->getZExtValue());
4667 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4670 unsigned EVTBits = ExtVT.getSizeInBits();
4672 // Do not generate loads of non-round integer types since these can
4673 // be expensive (and would be wrong if the type is not byte sized).
4674 if (!ExtVT.isRound())
4678 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4679 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4680 ShAmt = N01->getZExtValue();
4681 // Is the shift amount a multiple of size of VT?
4682 if ((ShAmt & (EVTBits-1)) == 0) {
4683 N0 = N0.getOperand(0);
4684 // Is the load width a multiple of size of VT?
4685 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4689 // At this point, we must have a load or else we can't do the transform.
4690 if (!isa<LoadSDNode>(N0)) return SDValue();
4692 // If the shift amount is larger than the input type then we're not
4693 // accessing any of the loaded bytes. If the load was a zextload/extload
4694 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4695 // If the load was a sextload then the result is a splat of the sign bit
4696 // of the extended byte. This is not worth optimizing for.
4697 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4702 // If the load is shifted left (and the result isn't shifted back right),
4703 // we can fold the truncate through the shift.
4704 unsigned ShLeftAmt = 0;
4705 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4706 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4707 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4708 ShLeftAmt = N01->getZExtValue();
4709 N0 = N0.getOperand(0);
4713 // If we haven't found a load, we can't narrow it. Don't transform one with
4714 // multiple uses, this would require adding a new load.
4715 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4716 // Don't change the width of a volatile load.
4717 cast<LoadSDNode>(N0)->isVolatile())
4720 // Verify that we are actually reducing a load width here.
4721 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4724 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4725 EVT PtrType = N0.getOperand(1).getValueType();
4727 // For big endian targets, we need to adjust the offset to the pointer to
4728 // load the correct bytes.
4729 if (TLI.isBigEndian()) {
4730 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4731 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4732 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4735 uint64_t PtrOff = ShAmt / 8;
4736 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4737 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4738 PtrType, LN0->getBasePtr(),
4739 DAG.getConstant(PtrOff, PtrType));
4740 AddToWorkList(NewPtr.getNode());
4743 if (ExtType == ISD::NON_EXTLOAD)
4744 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4745 LN0->getPointerInfo().getWithOffset(PtrOff),
4746 LN0->isVolatile(), LN0->isNonTemporal(),
4747 LN0->isInvariant(), NewAlign);
4749 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
4750 LN0->getPointerInfo().getWithOffset(PtrOff),
4751 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4754 // Replace the old load's chain with the new load's chain.
4755 WorkListRemover DeadNodes(*this);
4756 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4759 // Shift the result left, if we've swallowed a left shift.
4760 SDValue Result = Load;
4761 if (ShLeftAmt != 0) {
4762 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
4763 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4765 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4766 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4769 // Return the new loaded value.
4773 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4774 SDValue N0 = N->getOperand(0);
4775 SDValue N1 = N->getOperand(1);
4776 EVT VT = N->getValueType(0);
4777 EVT EVT = cast<VTSDNode>(N1)->getVT();
4778 unsigned VTBits = VT.getScalarType().getSizeInBits();
4779 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4781 // fold (sext_in_reg c1) -> c1
4782 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4783 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4785 // If the input is already sign extended, just drop the extension.
4786 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4789 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4790 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4791 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4792 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4793 N0.getOperand(0), N1);
4796 // fold (sext_in_reg (sext x)) -> (sext x)
4797 // fold (sext_in_reg (aext x)) -> (sext x)
4798 // if x is small enough.
4799 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4800 SDValue N00 = N0.getOperand(0);
4801 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4802 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4803 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4806 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4807 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4808 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4810 // fold operands of sext_in_reg based on knowledge that the top bits are not
4812 if (SimplifyDemandedBits(SDValue(N, 0)))
4813 return SDValue(N, 0);
4815 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4816 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4817 SDValue NarrowLoad = ReduceLoadWidth(N);
4818 if (NarrowLoad.getNode())
4821 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4822 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4823 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4824 if (N0.getOpcode() == ISD::SRL) {
4825 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4826 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4827 // We can turn this into an SRA iff the input to the SRL is already sign
4829 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4830 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4831 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4832 N0.getOperand(0), N0.getOperand(1));
4836 // fold (sext_inreg (extload x)) -> (sextload x)
4837 if (ISD::isEXTLoad(N0.getNode()) &&
4838 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4839 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4840 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4841 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4842 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4843 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4845 LN0->getBasePtr(), LN0->getPointerInfo(),
4847 LN0->isVolatile(), LN0->isNonTemporal(),
4848 LN0->getAlignment());
4849 CombineTo(N, ExtLoad);
4850 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4853 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4854 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4856 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4857 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4858 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4859 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4860 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4862 LN0->getBasePtr(), LN0->getPointerInfo(),
4864 LN0->isVolatile(), LN0->isNonTemporal(),
4865 LN0->getAlignment());
4866 CombineTo(N, ExtLoad);
4867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4871 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
4872 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
4873 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4874 N0.getOperand(1), false);
4875 if (BSwap.getNode() != 0)
4876 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4883 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4884 SDValue N0 = N->getOperand(0);
4885 EVT VT = N->getValueType(0);
4888 if (N0.getValueType() == N->getValueType(0))
4890 // fold (truncate c1) -> c1
4891 if (isa<ConstantSDNode>(N0))
4892 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4893 // fold (truncate (truncate x)) -> (truncate x)
4894 if (N0.getOpcode() == ISD::TRUNCATE)
4895 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4896 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4897 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4898 N0.getOpcode() == ISD::SIGN_EXTEND ||
4899 N0.getOpcode() == ISD::ANY_EXTEND) {
4900 if (N0.getOperand(0).getValueType().bitsLT(VT))
4901 // if the source is smaller than the dest, we still need an extend
4902 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4904 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4905 // if the source is larger than the dest, than we just need the truncate
4906 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4908 // if the source and dest are the same type, we can drop both the extend
4909 // and the truncate.
4910 return N0.getOperand(0);
4913 // See if we can simplify the input to this truncate through knowledge that
4914 // only the low bits are being used.
4915 // For example "trunc (or (shl x, 8), y)" // -> trunc y
4916 // Currently we only perform this optimization on scalars because vectors
4917 // may have different active low bits.
4918 if (!VT.isVector()) {
4920 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4921 VT.getSizeInBits()));
4922 if (Shorter.getNode())
4923 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4925 // fold (truncate (load x)) -> (smaller load x)
4926 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4927 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4928 SDValue Reduced = ReduceLoadWidth(N);
4929 if (Reduced.getNode())
4933 // Simplify the operands using demanded-bits information.
4934 if (!VT.isVector() &&
4935 SimplifyDemandedBits(SDValue(N, 0)))
4936 return SDValue(N, 0);
4941 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4942 SDValue Elt = N->getOperand(i);
4943 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4944 return Elt.getNode();
4945 return Elt.getOperand(Elt.getResNo()).getNode();
4948 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4949 /// if load locations are consecutive.
4950 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4951 assert(N->getOpcode() == ISD::BUILD_PAIR);
4953 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4954 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4955 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4956 LD1->getPointerInfo().getAddrSpace() !=
4957 LD2->getPointerInfo().getAddrSpace())
4959 EVT LD1VT = LD1->getValueType(0);
4961 if (ISD::isNON_EXTLoad(LD2) &&
4963 // If both are volatile this would reduce the number of volatile loads.
4964 // If one is volatile it might be ok, but play conservative and bail out.
4965 !LD1->isVolatile() &&
4966 !LD2->isVolatile() &&
4967 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4968 unsigned Align = LD1->getAlignment();
4969 unsigned NewAlign = TLI.getTargetData()->
4970 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4972 if (NewAlign <= Align &&
4973 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4974 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4975 LD1->getBasePtr(), LD1->getPointerInfo(),
4976 false, false, false, Align);
4982 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4983 SDValue N0 = N->getOperand(0);
4984 EVT VT = N->getValueType(0);
4986 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4987 // Only do this before legalize, since afterward the target may be depending
4988 // on the bitconvert.
4989 // First check to see if this is all constant.
4991 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4993 bool isSimple = true;
4994 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4995 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4996 N0.getOperand(i).getOpcode() != ISD::Constant &&
4997 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5002 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5003 assert(!DestEltVT.isVector() &&
5004 "Element type of vector ValueType must not be vector!");
5006 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5009 // If the input is a constant, let getNode fold it.
5010 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5011 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5012 if (Res.getNode() != N) {
5013 if (!LegalOperations ||
5014 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5017 // Folding it resulted in an illegal node, and it's too late to
5018 // do that. Clean up the old node and forego the transformation.
5019 // Ideally this won't happen very often, because instcombine
5020 // and the earlier dagcombine runs (where illegal nodes are
5021 // permitted) should have folded most of them already.
5022 DAG.DeleteNode(Res.getNode());
5026 // (conv (conv x, t1), t2) -> (conv x, t2)
5027 if (N0.getOpcode() == ISD::BITCAST)
5028 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5031 // fold (conv (load x)) -> (load (conv*)x)
5032 // If the resultant load doesn't need a higher alignment than the original!
5033 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5034 // Do not change the width of a volatile load.
5035 !cast<LoadSDNode>(N0)->isVolatile() &&
5036 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5037 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5038 unsigned Align = TLI.getTargetData()->
5039 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5040 unsigned OrigAlign = LN0->getAlignment();
5042 if (Align <= OrigAlign) {
5043 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5044 LN0->getBasePtr(), LN0->getPointerInfo(),
5045 LN0->isVolatile(), LN0->isNonTemporal(),
5046 LN0->isInvariant(), OrigAlign);
5048 CombineTo(N0.getNode(),
5049 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5050 N0.getValueType(), Load),
5056 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5057 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5058 // This often reduces constant pool loads.
5059 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
5060 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5061 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5063 AddToWorkList(NewConv.getNode());
5065 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5066 if (N0.getOpcode() == ISD::FNEG)
5067 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5068 NewConv, DAG.getConstant(SignBit, VT));
5069 assert(N0.getOpcode() == ISD::FABS);
5070 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5071 NewConv, DAG.getConstant(~SignBit, VT));
5074 // fold (bitconvert (fcopysign cst, x)) ->
5075 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5076 // Note that we don't handle (copysign x, cst) because this can always be
5077 // folded to an fneg or fabs.
5078 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5079 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5080 VT.isInteger() && !VT.isVector()) {
5081 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5082 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5083 if (isTypeLegal(IntXVT)) {
5084 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5085 IntXVT, N0.getOperand(1));
5086 AddToWorkList(X.getNode());
5088 // If X has a different width than the result/lhs, sext it or truncate it.
5089 unsigned VTWidth = VT.getSizeInBits();
5090 if (OrigXWidth < VTWidth) {
5091 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5092 AddToWorkList(X.getNode());
5093 } else if (OrigXWidth > VTWidth) {
5094 // To get the sign bit in the right place, we have to shift it right
5095 // before truncating.
5096 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5097 X.getValueType(), X,
5098 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5099 AddToWorkList(X.getNode());
5100 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5101 AddToWorkList(X.getNode());
5104 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5105 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5106 X, DAG.getConstant(SignBit, VT));
5107 AddToWorkList(X.getNode());
5109 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5110 VT, N0.getOperand(0));
5111 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5112 Cst, DAG.getConstant(~SignBit, VT));
5113 AddToWorkList(Cst.getNode());
5115 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5119 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5120 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5121 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5122 if (CombineLD.getNode())
5129 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5130 EVT VT = N->getValueType(0);
5131 return CombineConsecutiveLoads(N, VT);
5134 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5135 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5136 /// destination element value type.
5137 SDValue DAGCombiner::
5138 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5139 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5141 // If this is already the right type, we're done.
5142 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5144 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5145 unsigned DstBitSize = DstEltVT.getSizeInBits();
5147 // If this is a conversion of N elements of one type to N elements of another
5148 // type, convert each element. This handles FP<->INT cases.
5149 if (SrcBitSize == DstBitSize) {
5150 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5151 BV->getValueType(0).getVectorNumElements());
5153 // Due to the FP element handling below calling this routine recursively,
5154 // we can end up with a scalar-to-vector node here.
5155 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5156 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5157 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5158 DstEltVT, BV->getOperand(0)));
5160 SmallVector<SDValue, 8> Ops;
5161 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5162 SDValue Op = BV->getOperand(i);
5163 // If the vector element type is not legal, the BUILD_VECTOR operands
5164 // are promoted and implicitly truncated. Make that explicit here.
5165 if (Op.getValueType() != SrcEltVT)
5166 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5167 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5169 AddToWorkList(Ops.back().getNode());
5171 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5172 &Ops[0], Ops.size());
5175 // Otherwise, we're growing or shrinking the elements. To avoid having to
5176 // handle annoying details of growing/shrinking FP values, we convert them to
5178 if (SrcEltVT.isFloatingPoint()) {
5179 // Convert the input float vector to a int vector where the elements are the
5181 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5183 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5187 // Now we know the input is an integer vector. If the output is a FP type,
5188 // convert to integer first, then to FP of the right size.
5189 if (DstEltVT.isFloatingPoint()) {
5190 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5191 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5192 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5194 // Next, convert to FP elements of the same size.
5195 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5198 // Okay, we know the src/dst types are both integers of differing types.
5199 // Handling growing first.
5200 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5201 if (SrcBitSize < DstBitSize) {
5202 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5204 SmallVector<SDValue, 8> Ops;
5205 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5206 i += NumInputsPerOutput) {
5207 bool isLE = TLI.isLittleEndian();
5208 APInt NewBits = APInt(DstBitSize, 0);
5209 bool EltIsUndef = true;
5210 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5211 // Shift the previously computed bits over.
5212 NewBits <<= SrcBitSize;
5213 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5214 if (Op.getOpcode() == ISD::UNDEF) continue;
5217 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5218 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5222 Ops.push_back(DAG.getUNDEF(DstEltVT));
5224 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5227 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5228 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5229 &Ops[0], Ops.size());
5232 // Finally, this must be the case where we are shrinking elements: each input
5233 // turns into multiple outputs.
5234 bool isS2V = ISD::isScalarToVector(BV);
5235 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5236 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5237 NumOutputsPerInput*BV->getNumOperands());
5238 SmallVector<SDValue, 8> Ops;
5240 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5241 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5242 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5243 Ops.push_back(DAG.getUNDEF(DstEltVT));
5247 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5248 getAPIntValue().zextOrTrunc(SrcBitSize);
5250 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5251 APInt ThisVal = OpVal.trunc(DstBitSize);
5252 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5253 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5254 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5255 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5257 OpVal = OpVal.lshr(DstBitSize);
5260 // For big endian targets, swap the order of the pieces of each element.
5261 if (TLI.isBigEndian())
5262 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5265 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5266 &Ops[0], Ops.size());
5269 SDValue DAGCombiner::visitFADD(SDNode *N) {
5270 SDValue N0 = N->getOperand(0);
5271 SDValue N1 = N->getOperand(1);
5272 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5273 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5274 EVT VT = N->getValueType(0);
5277 if (VT.isVector()) {
5278 SDValue FoldedVOp = SimplifyVBinOp(N);
5279 if (FoldedVOp.getNode()) return FoldedVOp;
5282 // fold (fadd c1, c2) -> (fadd c1, c2)
5283 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5284 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5285 // canonicalize constant to RHS
5286 if (N0CFP && !N1CFP)
5287 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5288 // fold (fadd A, 0) -> A
5289 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5290 N1CFP->getValueAPF().isZero())
5292 // fold (fadd A, (fneg B)) -> (fsub A, B)
5293 if (isNegatibleForFree(N1, LegalOperations, &DAG.getTarget().Options) == 2)
5294 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5295 GetNegatedExpression(N1, DAG, LegalOperations));
5296 // fold (fadd (fneg A), B) -> (fsub B, A)
5297 if (isNegatibleForFree(N0, LegalOperations, &DAG.getTarget().Options) == 2)
5298 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5299 GetNegatedExpression(N0, DAG, LegalOperations));
5301 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5302 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5303 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5304 isa<ConstantFPSDNode>(N0.getOperand(1)))
5305 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5306 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5307 N0.getOperand(1), N1));
5312 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5313 SDValue N0 = N->getOperand(0);
5314 SDValue N1 = N->getOperand(1);
5315 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5316 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5317 EVT VT = N->getValueType(0);
5320 if (VT.isVector()) {
5321 SDValue FoldedVOp = SimplifyVBinOp(N);
5322 if (FoldedVOp.getNode()) return FoldedVOp;
5325 // fold (fsub c1, c2) -> c1-c2
5326 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5327 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5328 // fold (fsub A, 0) -> A
5329 if (DAG.getTarget().Options.UnsafeFPMath &&
5330 N1CFP && N1CFP->getValueAPF().isZero())
5332 // fold (fsub 0, B) -> -B
5333 if (DAG.getTarget().Options.UnsafeFPMath &&
5334 N0CFP && N0CFP->getValueAPF().isZero()) {
5335 if (isNegatibleForFree(N1, LegalOperations, &DAG.getTarget().Options))
5336 return GetNegatedExpression(N1, DAG, LegalOperations);
5337 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5338 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
5340 // fold (fsub A, (fneg B)) -> (fadd A, B)
5341 if (isNegatibleForFree(N1, LegalOperations, &DAG.getTarget().Options))
5342 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
5343 GetNegatedExpression(N1, DAG, LegalOperations));
5348 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5349 SDValue N0 = N->getOperand(0);
5350 SDValue N1 = N->getOperand(1);
5351 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5352 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5353 EVT VT = N->getValueType(0);
5356 if (VT.isVector()) {
5357 SDValue FoldedVOp = SimplifyVBinOp(N);
5358 if (FoldedVOp.getNode()) return FoldedVOp;
5361 // fold (fmul c1, c2) -> c1*c2
5362 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5363 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5364 // canonicalize constant to RHS
5365 if (N0CFP && !N1CFP)
5366 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5367 // fold (fmul A, 0) -> 0
5368 if (DAG.getTarget().Options.UnsafeFPMath &&
5369 N1CFP && N1CFP->getValueAPF().isZero())
5371 // fold (fmul A, 0) -> 0, vector edition.
5372 if (DAG.getTarget().Options.UnsafeFPMath &&
5373 ISD::isBuildVectorAllZeros(N1.getNode()))
5375 // fold (fmul X, 2.0) -> (fadd X, X)
5376 if (N1CFP && N1CFP->isExactlyValue(+2.0))
5377 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5378 // fold (fmul X, -1.0) -> (fneg X)
5379 if (N1CFP && N1CFP->isExactlyValue(-1.0))
5380 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5381 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5383 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5384 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations,
5385 &DAG.getTarget().Options)) {
5386 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations,
5387 &DAG.getTarget().Options)) {
5388 // Both can be negated for free, check to see if at least one is cheaper
5390 if (LHSNeg == 2 || RHSNeg == 2)
5391 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5392 GetNegatedExpression(N0, DAG, LegalOperations),
5393 GetNegatedExpression(N1, DAG, LegalOperations));
5397 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5398 if (DAG.getTarget().Options.UnsafeFPMath &&
5399 N1CFP && N0.getOpcode() == ISD::FMUL &&
5400 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5401 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5402 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5403 N0.getOperand(1), N1));
5408 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5409 SDValue N0 = N->getOperand(0);
5410 SDValue N1 = N->getOperand(1);
5411 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5412 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5413 EVT VT = N->getValueType(0);
5416 if (VT.isVector()) {
5417 SDValue FoldedVOp = SimplifyVBinOp(N);
5418 if (FoldedVOp.getNode()) return FoldedVOp;
5421 // fold (fdiv c1, c2) -> c1/c2
5422 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5423 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5426 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5427 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations,
5428 &DAG.getTarget().Options)) {
5429 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations,
5430 &DAG.getTarget().Options)) {
5431 // Both can be negated for free, check to see if at least one is cheaper
5433 if (LHSNeg == 2 || RHSNeg == 2)
5434 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5435 GetNegatedExpression(N0, DAG, LegalOperations),
5436 GetNegatedExpression(N1, DAG, LegalOperations));
5443 SDValue DAGCombiner::visitFREM(SDNode *N) {
5444 SDValue N0 = N->getOperand(0);
5445 SDValue N1 = N->getOperand(1);
5446 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5447 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5448 EVT VT = N->getValueType(0);
5450 // fold (frem c1, c2) -> fmod(c1,c2)
5451 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5452 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5457 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5458 SDValue N0 = N->getOperand(0);
5459 SDValue N1 = N->getOperand(1);
5460 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5462 EVT VT = N->getValueType(0);
5464 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5465 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5468 const APFloat& V = N1CFP->getValueAPF();
5469 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5470 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5471 if (!V.isNegative()) {
5472 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5473 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5475 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5476 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5477 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5481 // copysign(fabs(x), y) -> copysign(x, y)
5482 // copysign(fneg(x), y) -> copysign(x, y)
5483 // copysign(copysign(x,z), y) -> copysign(x, y)
5484 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5485 N0.getOpcode() == ISD::FCOPYSIGN)
5486 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5487 N0.getOperand(0), N1);
5489 // copysign(x, abs(y)) -> abs(x)
5490 if (N1.getOpcode() == ISD::FABS)
5491 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5493 // copysign(x, copysign(y,z)) -> copysign(x, z)
5494 if (N1.getOpcode() == ISD::FCOPYSIGN)
5495 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5496 N0, N1.getOperand(1));
5498 // copysign(x, fp_extend(y)) -> copysign(x, y)
5499 // copysign(x, fp_round(y)) -> copysign(x, y)
5500 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5501 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5502 N0, N1.getOperand(0));
5507 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5508 SDValue N0 = N->getOperand(0);
5509 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5510 EVT VT = N->getValueType(0);
5511 EVT OpVT = N0.getValueType();
5513 // fold (sint_to_fp c1) -> c1fp
5514 if (N0C && OpVT != MVT::ppcf128 &&
5515 // ...but only if the target supports immediate floating-point values
5516 (!LegalOperations ||
5517 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5518 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5520 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5521 // but UINT_TO_FP is legal on this target, try to convert.
5522 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5523 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5524 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5525 if (DAG.SignBitIsZero(N0))
5526 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5532 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5533 SDValue N0 = N->getOperand(0);
5534 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5535 EVT VT = N->getValueType(0);
5536 EVT OpVT = N0.getValueType();
5538 // fold (uint_to_fp c1) -> c1fp
5539 if (N0C && OpVT != MVT::ppcf128 &&
5540 // ...but only if the target supports immediate floating-point values
5541 (!LegalOperations ||
5542 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5543 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5545 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5546 // but SINT_TO_FP is legal on this target, try to convert.
5547 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5548 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5549 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5550 if (DAG.SignBitIsZero(N0))
5551 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5557 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5558 SDValue N0 = N->getOperand(0);
5559 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5560 EVT VT = N->getValueType(0);
5562 // fold (fp_to_sint c1fp) -> c1
5564 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5569 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5570 SDValue N0 = N->getOperand(0);
5571 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5572 EVT VT = N->getValueType(0);
5574 // fold (fp_to_uint c1fp) -> c1
5575 if (N0CFP && VT != MVT::ppcf128)
5576 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5581 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5582 SDValue N0 = N->getOperand(0);
5583 SDValue N1 = N->getOperand(1);
5584 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5585 EVT VT = N->getValueType(0);
5587 // fold (fp_round c1fp) -> c1fp
5588 if (N0CFP && N0.getValueType() != MVT::ppcf128)
5589 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5591 // fold (fp_round (fp_extend x)) -> x
5592 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5593 return N0.getOperand(0);
5595 // fold (fp_round (fp_round x)) -> (fp_round x)
5596 if (N0.getOpcode() == ISD::FP_ROUND) {
5597 // This is a value preserving truncation if both round's are.
5598 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5599 N0.getNode()->getConstantOperandVal(1) == 1;
5600 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5601 DAG.getIntPtrConstant(IsTrunc));
5604 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5605 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5606 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5607 N0.getOperand(0), N1);
5608 AddToWorkList(Tmp.getNode());
5609 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5610 Tmp, N0.getOperand(1));
5616 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5617 SDValue N0 = N->getOperand(0);
5618 EVT VT = N->getValueType(0);
5619 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5620 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5622 // fold (fp_round_inreg c1fp) -> c1fp
5623 if (N0CFP && isTypeLegal(EVT)) {
5624 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5625 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5631 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5632 SDValue N0 = N->getOperand(0);
5633 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5634 EVT VT = N->getValueType(0);
5636 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5637 if (N->hasOneUse() &&
5638 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5641 // fold (fp_extend c1fp) -> c1fp
5642 if (N0CFP && VT != MVT::ppcf128)
5643 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5645 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5647 if (N0.getOpcode() == ISD::FP_ROUND
5648 && N0.getNode()->getConstantOperandVal(1) == 1) {
5649 SDValue In = N0.getOperand(0);
5650 if (In.getValueType() == VT) return In;
5651 if (VT.bitsLT(In.getValueType()))
5652 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5653 In, N0.getOperand(1));
5654 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5657 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5658 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5659 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5660 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5661 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5662 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
5664 LN0->getBasePtr(), LN0->getPointerInfo(),
5666 LN0->isVolatile(), LN0->isNonTemporal(),
5667 LN0->getAlignment());
5668 CombineTo(N, ExtLoad);
5669 CombineTo(N0.getNode(),
5670 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5671 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5672 ExtLoad.getValue(1));
5673 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5679 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5680 SDValue N0 = N->getOperand(0);
5681 EVT VT = N->getValueType(0);
5683 if (isNegatibleForFree(N0, LegalOperations, &DAG.getTarget().Options))
5684 return GetNegatedExpression(N0, DAG, LegalOperations);
5686 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5687 // constant pool values.
5688 if (N0.getOpcode() == ISD::BITCAST &&
5690 N0.getNode()->hasOneUse() &&
5691 N0.getOperand(0).getValueType().isInteger()) {
5692 SDValue Int = N0.getOperand(0);
5693 EVT IntVT = Int.getValueType();
5694 if (IntVT.isInteger() && !IntVT.isVector()) {
5695 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5696 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5697 AddToWorkList(Int.getNode());
5698 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5706 SDValue DAGCombiner::visitFABS(SDNode *N) {
5707 SDValue N0 = N->getOperand(0);
5708 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5709 EVT VT = N->getValueType(0);
5711 // fold (fabs c1) -> fabs(c1)
5712 if (N0CFP && VT != MVT::ppcf128)
5713 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5714 // fold (fabs (fabs x)) -> (fabs x)
5715 if (N0.getOpcode() == ISD::FABS)
5716 return N->getOperand(0);
5717 // fold (fabs (fneg x)) -> (fabs x)
5718 // fold (fabs (fcopysign x, y)) -> (fabs x)
5719 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5720 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5722 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5723 // constant pool values.
5724 if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5725 N0.getOperand(0).getValueType().isInteger() &&
5726 !N0.getOperand(0).getValueType().isVector()) {
5727 SDValue Int = N0.getOperand(0);
5728 EVT IntVT = Int.getValueType();
5729 if (IntVT.isInteger() && !IntVT.isVector()) {
5730 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5731 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5732 AddToWorkList(Int.getNode());
5733 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5734 N->getValueType(0), Int);
5741 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5742 SDValue Chain = N->getOperand(0);
5743 SDValue N1 = N->getOperand(1);
5744 SDValue N2 = N->getOperand(2);
5746 // If N is a constant we could fold this into a fallthrough or unconditional
5747 // branch. However that doesn't happen very often in normal code, because
5748 // Instcombine/SimplifyCFG should have handled the available opportunities.
5749 // If we did this folding here, it would be necessary to update the
5750 // MachineBasicBlock CFG, which is awkward.
5752 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5754 if (N1.getOpcode() == ISD::SETCC &&
5755 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5756 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5757 Chain, N1.getOperand(2),
5758 N1.getOperand(0), N1.getOperand(1), N2);
5761 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5762 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5763 (N1.getOperand(0).hasOneUse() &&
5764 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5766 if (N1.getOpcode() == ISD::TRUNCATE) {
5767 // Look pass the truncate.
5768 Trunc = N1.getNode();
5769 N1 = N1.getOperand(0);
5772 // Match this pattern so that we can generate simpler code:
5775 // %b = and i32 %a, 2
5776 // %c = srl i32 %b, 1
5777 // brcond i32 %c ...
5782 // %b = and i32 %a, 2
5783 // %c = setcc eq %b, 0
5786 // This applies only when the AND constant value has one bit set and the
5787 // SRL constant is equal to the log2 of the AND constant. The back-end is
5788 // smart enough to convert the result into a TEST/JMP sequence.
5789 SDValue Op0 = N1.getOperand(0);
5790 SDValue Op1 = N1.getOperand(1);
5792 if (Op0.getOpcode() == ISD::AND &&
5793 Op1.getOpcode() == ISD::Constant) {
5794 SDValue AndOp1 = Op0.getOperand(1);
5796 if (AndOp1.getOpcode() == ISD::Constant) {
5797 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5799 if (AndConst.isPowerOf2() &&
5800 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5802 DAG.getSetCC(N->getDebugLoc(),
5803 TLI.getSetCCResultType(Op0.getValueType()),
5804 Op0, DAG.getConstant(0, Op0.getValueType()),
5807 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5808 MVT::Other, Chain, SetCC, N2);
5809 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5810 // will convert it back to (X & C1) >> C2.
5811 CombineTo(N, NewBRCond, false);
5812 // Truncate is dead.
5814 removeFromWorkList(Trunc);
5815 DAG.DeleteNode(Trunc);
5817 // Replace the uses of SRL with SETCC
5818 WorkListRemover DeadNodes(*this);
5819 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5820 removeFromWorkList(N1.getNode());
5821 DAG.DeleteNode(N1.getNode());
5822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5828 // Restore N1 if the above transformation doesn't match.
5829 N1 = N->getOperand(1);
5832 // Transform br(xor(x, y)) -> br(x != y)
5833 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5834 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5835 SDNode *TheXor = N1.getNode();
5836 SDValue Op0 = TheXor->getOperand(0);
5837 SDValue Op1 = TheXor->getOperand(1);
5838 if (Op0.getOpcode() == Op1.getOpcode()) {
5839 // Avoid missing important xor optimizations.
5840 SDValue Tmp = visitXOR(TheXor);
5841 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5842 DEBUG(dbgs() << "\nReplacing.8 ";
5844 dbgs() << "\nWith: ";
5845 Tmp.getNode()->dump(&DAG);
5847 WorkListRemover DeadNodes(*this);
5848 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5849 removeFromWorkList(TheXor);
5850 DAG.DeleteNode(TheXor);
5851 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5852 MVT::Other, Chain, Tmp, N2);
5856 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5858 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5859 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5860 Op0.getOpcode() == ISD::XOR) {
5861 TheXor = Op0.getNode();
5865 EVT SetCCVT = N1.getValueType();
5867 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5868 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5871 Equal ? ISD::SETEQ : ISD::SETNE);
5872 // Replace the uses of XOR with SETCC
5873 WorkListRemover DeadNodes(*this);
5874 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5875 removeFromWorkList(N1.getNode());
5876 DAG.DeleteNode(N1.getNode());
5877 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5878 MVT::Other, Chain, SetCC, N2);
5885 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5887 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5888 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5889 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5891 // If N is a constant we could fold this into a fallthrough or unconditional
5892 // branch. However that doesn't happen very often in normal code, because
5893 // Instcombine/SimplifyCFG should have handled the available opportunities.
5894 // If we did this folding here, it would be necessary to update the
5895 // MachineBasicBlock CFG, which is awkward.
5897 // Use SimplifySetCC to simplify SETCC's.
5898 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5899 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5901 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5903 // fold to a simpler setcc
5904 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5905 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5906 N->getOperand(0), Simp.getOperand(2),
5907 Simp.getOperand(0), Simp.getOperand(1),
5913 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5914 /// pre-indexed load / store when the base pointer is an add or subtract
5915 /// and it has other uses besides the load / store. After the
5916 /// transformation, the new indexed load / store has effectively folded
5917 /// the add / subtract in and all of its other uses are redirected to the
5918 /// new load / store.
5919 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5920 if (Level < AfterLegalizeDAG)
5926 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5927 if (LD->isIndexed())
5929 VT = LD->getMemoryVT();
5930 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5931 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5933 Ptr = LD->getBasePtr();
5934 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5935 if (ST->isIndexed())
5937 VT = ST->getMemoryVT();
5938 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5939 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5941 Ptr = ST->getBasePtr();
5947 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5948 // out. There is no reason to make this a preinc/predec.
5949 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5950 Ptr.getNode()->hasOneUse())
5953 // Ask the target to do addressing mode selection.
5956 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5957 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5959 // Don't create a indexed load / store with zero offset.
5960 if (isa<ConstantSDNode>(Offset) &&
5961 cast<ConstantSDNode>(Offset)->isNullValue())
5964 // Try turning it into a pre-indexed load / store except when:
5965 // 1) The new base ptr is a frame index.
5966 // 2) If N is a store and the new base ptr is either the same as or is a
5967 // predecessor of the value being stored.
5968 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5969 // that would create a cycle.
5970 // 4) All uses are load / store ops that use it as old base ptr.
5972 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5973 // (plus the implicit offset) to a register to preinc anyway.
5974 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5979 SDValue Val = cast<StoreSDNode>(N)->getValue();
5980 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5984 // Now check for #3 and #4.
5985 bool RealUse = false;
5987 // Caches for hasPredecessorHelper
5988 SmallPtrSet<const SDNode *, 32> Visited;
5989 SmallVector<const SDNode *, 16> Worklist;
5991 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5992 E = Ptr.getNode()->use_end(); I != E; ++I) {
5996 if (N->hasPredecessorHelper(Use, Visited, Worklist))
5999 if (!((Use->getOpcode() == ISD::LOAD &&
6000 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
6001 (Use->getOpcode() == ISD::STORE &&
6002 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
6011 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6012 BasePtr, Offset, AM);
6014 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6015 BasePtr, Offset, AM);
6018 DEBUG(dbgs() << "\nReplacing.4 ";
6020 dbgs() << "\nWith: ";
6021 Result.getNode()->dump(&DAG);
6023 WorkListRemover DeadNodes(*this);
6025 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
6027 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
6030 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
6034 // Finally, since the node is now dead, remove it from the graph.
6037 // Replace the uses of Ptr with uses of the updated base value.
6038 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
6040 removeFromWorkList(Ptr.getNode());
6041 DAG.DeleteNode(Ptr.getNode());
6046 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6047 /// add / sub of the base pointer node into a post-indexed load / store.
6048 /// The transformation folded the add / subtract into the new indexed
6049 /// load / store effectively and all of its uses are redirected to the
6050 /// new load / store.
6051 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6052 if (Level < AfterLegalizeDAG)
6058 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6059 if (LD->isIndexed())
6061 VT = LD->getMemoryVT();
6062 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6063 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6065 Ptr = LD->getBasePtr();
6066 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6067 if (ST->isIndexed())
6069 VT = ST->getMemoryVT();
6070 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6071 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6073 Ptr = ST->getBasePtr();
6079 if (Ptr.getNode()->hasOneUse())
6082 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6083 E = Ptr.getNode()->use_end(); I != E; ++I) {
6086 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6091 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6092 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6093 // Don't create a indexed load / store with zero offset.
6094 if (isa<ConstantSDNode>(Offset) &&
6095 cast<ConstantSDNode>(Offset)->isNullValue())
6098 // Try turning it into a post-indexed load / store except when
6099 // 1) All uses are load / store ops that use it as base ptr.
6100 // 2) Op must be independent of N, i.e. Op is neither a predecessor
6101 // nor a successor of N. Otherwise, if Op is folded that would
6104 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6108 bool TryNext = false;
6109 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6110 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6112 if (Use == Ptr.getNode())
6115 // If all the uses are load / store addresses, then don't do the
6117 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6118 bool RealUse = false;
6119 for (SDNode::use_iterator III = Use->use_begin(),
6120 EEE = Use->use_end(); III != EEE; ++III) {
6121 SDNode *UseUse = *III;
6122 if (!((UseUse->getOpcode() == ISD::LOAD &&
6123 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
6124 (UseUse->getOpcode() == ISD::STORE &&
6125 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
6140 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6141 SDValue Result = isLoad
6142 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6143 BasePtr, Offset, AM)
6144 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6145 BasePtr, Offset, AM);
6148 DEBUG(dbgs() << "\nReplacing.5 ";
6150 dbgs() << "\nWith: ";
6151 Result.getNode()->dump(&DAG);
6153 WorkListRemover DeadNodes(*this);
6155 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
6157 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
6160 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
6164 // Finally, since the node is now dead, remove it from the graph.
6167 // Replace the uses of Use with uses of the updated base value.
6168 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6169 Result.getValue(isLoad ? 1 : 0),
6171 removeFromWorkList(Op);
6181 SDValue DAGCombiner::visitLOAD(SDNode *N) {
6182 LoadSDNode *LD = cast<LoadSDNode>(N);
6183 SDValue Chain = LD->getChain();
6184 SDValue Ptr = LD->getBasePtr();
6186 // If load is not volatile and there are no uses of the loaded value (and
6187 // the updated indexed value in case of indexed loads), change uses of the
6188 // chain value into uses of the chain input (i.e. delete the dead load).
6189 if (!LD->isVolatile()) {
6190 if (N->getValueType(1) == MVT::Other) {
6192 if (N->hasNUsesOfValue(0, 0)) {
6193 // It's not safe to use the two value CombineTo variant here. e.g.
6194 // v1, chain2 = load chain1, loc
6195 // v2, chain3 = load chain2, loc
6197 // Now we replace use of chain2 with chain1. This makes the second load
6198 // isomorphic to the one we are deleting, and thus makes this load live.
6199 DEBUG(dbgs() << "\nReplacing.6 ";
6201 dbgs() << "\nWith chain: ";
6202 Chain.getNode()->dump(&DAG);
6204 WorkListRemover DeadNodes(*this);
6205 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
6207 if (N->use_empty()) {
6208 removeFromWorkList(N);
6212 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6216 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6217 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
6218 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6219 DEBUG(dbgs() << "\nReplacing.7 ";
6221 dbgs() << "\nWith: ";
6222 Undef.getNode()->dump(&DAG);
6223 dbgs() << " and 2 other values\n");
6224 WorkListRemover DeadNodes(*this);
6225 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
6226 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6227 DAG.getUNDEF(N->getValueType(1)),
6229 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
6230 removeFromWorkList(N);
6232 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6237 // If this load is directly stored, replace the load value with the stored
6239 // TODO: Handle store large -> read small portion.
6240 // TODO: Handle TRUNCSTORE/LOADEXT
6241 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6242 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6243 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6244 if (PrevST->getBasePtr() == Ptr &&
6245 PrevST->getValue().getValueType() == N->getValueType(0))
6246 return CombineTo(N, Chain.getOperand(1), Chain);
6250 // Try to infer better alignment information than the load already has.
6251 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6252 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6253 if (Align > LD->getAlignment())
6254 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6255 LD->getValueType(0),
6256 Chain, Ptr, LD->getPointerInfo(),
6258 LD->isVolatile(), LD->isNonTemporal(), Align);
6263 // Walk up chain skipping non-aliasing memory nodes.
6264 SDValue BetterChain = FindBetterChain(N, Chain);
6266 // If there is a better chain.
6267 if (Chain != BetterChain) {
6270 // Replace the chain to void dependency.
6271 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6272 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6273 BetterChain, Ptr, LD->getPointerInfo(),
6274 LD->isVolatile(), LD->isNonTemporal(),
6275 LD->isInvariant(), LD->getAlignment());
6277 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6278 LD->getValueType(0),
6279 BetterChain, Ptr, LD->getPointerInfo(),
6282 LD->isNonTemporal(),
6283 LD->getAlignment());
6286 // Create token factor to keep old chain connected.
6287 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6288 MVT::Other, Chain, ReplLoad.getValue(1));
6290 // Make sure the new and old chains are cleaned up.
6291 AddToWorkList(Token.getNode());
6293 // Replace uses with load result and token factor. Don't add users
6295 return CombineTo(N, ReplLoad.getValue(0), Token, false);
6299 // Try transforming N to an indexed load.
6300 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6301 return SDValue(N, 0);
6306 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6307 /// load is having specific bytes cleared out. If so, return the byte size
6308 /// being masked out and the shift amount.
6309 static std::pair<unsigned, unsigned>
6310 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6311 std::pair<unsigned, unsigned> Result(0, 0);
6313 // Check for the structure we're looking for.
6314 if (V->getOpcode() != ISD::AND ||
6315 !isa<ConstantSDNode>(V->getOperand(1)) ||
6316 !ISD::isNormalLoad(V->getOperand(0).getNode()))
6319 // Check the chain and pointer.
6320 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6321 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
6323 // The store should be chained directly to the load or be an operand of a
6325 if (LD == Chain.getNode())
6327 else if (Chain->getOpcode() != ISD::TokenFactor)
6328 return Result; // Fail.
6331 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6332 if (Chain->getOperand(i).getNode() == LD) {
6336 if (!isOk) return Result;
6339 // This only handles simple types.
6340 if (V.getValueType() != MVT::i16 &&
6341 V.getValueType() != MVT::i32 &&
6342 V.getValueType() != MVT::i64)
6345 // Check the constant mask. Invert it so that the bits being masked out are
6346 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
6347 // follow the sign bit for uniformity.
6348 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6349 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6350 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
6351 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6352 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
6353 if (NotMaskLZ == 64) return Result; // All zero mask.
6355 // See if we have a continuous run of bits. If so, we have 0*1+0*
6356 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6359 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6360 if (V.getValueType() != MVT::i64 && NotMaskLZ)
6361 NotMaskLZ -= 64-V.getValueSizeInBits();
6363 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6364 switch (MaskedBytes) {
6368 default: return Result; // All one mask, or 5-byte mask.
6371 // Verify that the first bit starts at a multiple of mask so that the access
6372 // is aligned the same as the access width.
6373 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6375 Result.first = MaskedBytes;
6376 Result.second = NotMaskTZ/8;
6381 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6382 /// provides a value as specified by MaskInfo. If so, replace the specified
6383 /// store with a narrower store of truncated IVal.
6385 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6386 SDValue IVal, StoreSDNode *St,
6388 unsigned NumBytes = MaskInfo.first;
6389 unsigned ByteShift = MaskInfo.second;
6390 SelectionDAG &DAG = DC->getDAG();
6392 // Check to see if IVal is all zeros in the part being masked in by the 'or'
6393 // that uses this. If not, this is not a replacement.
6394 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6395 ByteShift*8, (ByteShift+NumBytes)*8);
6396 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6398 // Check that it is legal on the target to do this. It is legal if the new
6399 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6401 MVT VT = MVT::getIntegerVT(NumBytes*8);
6402 if (!DC->isTypeLegal(VT))
6405 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
6406 // shifted by ByteShift and truncated down to NumBytes.
6408 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6409 DAG.getConstant(ByteShift*8,
6410 DC->getShiftAmountTy(IVal.getValueType())));
6412 // Figure out the offset for the store and the alignment of the access.
6414 unsigned NewAlign = St->getAlignment();
6416 if (DAG.getTargetLoweringInfo().isLittleEndian())
6417 StOffset = ByteShift;
6419 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6421 SDValue Ptr = St->getBasePtr();
6423 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6424 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6425 NewAlign = MinAlign(NewAlign, StOffset);
6428 // Truncate down to the new size.
6429 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6432 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6433 St->getPointerInfo().getWithOffset(StOffset),
6434 false, false, NewAlign).getNode();
6438 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6439 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6440 /// of the loaded bits, try narrowing the load and store if it would end up
6441 /// being a win for performance or code size.
6442 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6443 StoreSDNode *ST = cast<StoreSDNode>(N);
6444 if (ST->isVolatile())
6447 SDValue Chain = ST->getChain();
6448 SDValue Value = ST->getValue();
6449 SDValue Ptr = ST->getBasePtr();
6450 EVT VT = Value.getValueType();
6452 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6455 unsigned Opc = Value.getOpcode();
6457 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6458 // is a byte mask indicating a consecutive number of bytes, check to see if
6459 // Y is known to provide just those bytes. If so, we try to replace the
6460 // load + replace + store sequence with a single (narrower) store, which makes
6462 if (Opc == ISD::OR) {
6463 std::pair<unsigned, unsigned> MaskedLoad;
6464 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6465 if (MaskedLoad.first)
6466 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6467 Value.getOperand(1), ST,this))
6468 return SDValue(NewST, 0);
6470 // Or is commutative, so try swapping X and Y.
6471 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6472 if (MaskedLoad.first)
6473 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6474 Value.getOperand(0), ST,this))
6475 return SDValue(NewST, 0);
6478 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6479 Value.getOperand(1).getOpcode() != ISD::Constant)
6482 SDValue N0 = Value.getOperand(0);
6483 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6484 Chain == SDValue(N0.getNode(), 1)) {
6485 LoadSDNode *LD = cast<LoadSDNode>(N0);
6486 if (LD->getBasePtr() != Ptr ||
6487 LD->getPointerInfo().getAddrSpace() !=
6488 ST->getPointerInfo().getAddrSpace())
6491 // Find the type to narrow it the load / op / store to.
6492 SDValue N1 = Value.getOperand(1);
6493 unsigned BitWidth = N1.getValueSizeInBits();
6494 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6495 if (Opc == ISD::AND)
6496 Imm ^= APInt::getAllOnesValue(BitWidth);
6497 if (Imm == 0 || Imm.isAllOnesValue())
6499 unsigned ShAmt = Imm.countTrailingZeros();
6500 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6501 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6502 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6503 while (NewBW < BitWidth &&
6504 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6505 TLI.isNarrowingProfitable(VT, NewVT))) {
6506 NewBW = NextPowerOf2(NewBW);
6507 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6509 if (NewBW >= BitWidth)
6512 // If the lsb changed does not start at the type bitwidth boundary,
6513 // start at the previous one.
6515 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6516 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6517 if ((Imm & Mask) == Imm) {
6518 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6519 if (Opc == ISD::AND)
6520 NewImm ^= APInt::getAllOnesValue(NewBW);
6521 uint64_t PtrOff = ShAmt / 8;
6522 // For big endian targets, we need to adjust the offset to the pointer to
6523 // load the correct bytes.
6524 if (TLI.isBigEndian())
6525 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6527 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6528 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6529 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6532 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6533 Ptr.getValueType(), Ptr,
6534 DAG.getConstant(PtrOff, Ptr.getValueType()));
6535 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6536 LD->getChain(), NewPtr,
6537 LD->getPointerInfo().getWithOffset(PtrOff),
6538 LD->isVolatile(), LD->isNonTemporal(),
6539 LD->isInvariant(), NewAlign);
6540 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6541 DAG.getConstant(NewImm, NewVT));
6542 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6544 ST->getPointerInfo().getWithOffset(PtrOff),
6545 false, false, NewAlign);
6547 AddToWorkList(NewPtr.getNode());
6548 AddToWorkList(NewLD.getNode());
6549 AddToWorkList(NewVal.getNode());
6550 WorkListRemover DeadNodes(*this);
6551 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6561 /// TransformFPLoadStorePair - For a given floating point load / store pair,
6562 /// if the load value isn't used by any other operations, then consider
6563 /// transforming the pair to integer load / store operations if the target
6564 /// deems the transformation profitable.
6565 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6566 StoreSDNode *ST = cast<StoreSDNode>(N);
6567 SDValue Chain = ST->getChain();
6568 SDValue Value = ST->getValue();
6569 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6570 Value.hasOneUse() &&
6571 Chain == SDValue(Value.getNode(), 1)) {
6572 LoadSDNode *LD = cast<LoadSDNode>(Value);
6573 EVT VT = LD->getMemoryVT();
6574 if (!VT.isFloatingPoint() ||
6575 VT != ST->getMemoryVT() ||
6576 LD->isNonTemporal() ||
6577 ST->isNonTemporal() ||
6578 LD->getPointerInfo().getAddrSpace() != 0 ||
6579 ST->getPointerInfo().getAddrSpace() != 0)
6582 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6583 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6584 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6585 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6586 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6589 unsigned LDAlign = LD->getAlignment();
6590 unsigned STAlign = ST->getAlignment();
6591 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6592 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6593 if (LDAlign < ABIAlign || STAlign < ABIAlign)
6596 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6597 LD->getChain(), LD->getBasePtr(),
6598 LD->getPointerInfo(),
6599 false, false, false, LDAlign);
6601 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6602 NewLD, ST->getBasePtr(),
6603 ST->getPointerInfo(),
6604 false, false, STAlign);
6606 AddToWorkList(NewLD.getNode());
6607 AddToWorkList(NewST.getNode());
6608 WorkListRemover DeadNodes(*this);
6609 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
6618 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6619 StoreSDNode *ST = cast<StoreSDNode>(N);
6620 SDValue Chain = ST->getChain();
6621 SDValue Value = ST->getValue();
6622 SDValue Ptr = ST->getBasePtr();
6624 // If this is a store of a bit convert, store the input value if the
6625 // resultant store does not need a higher alignment than the original.
6626 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6627 ST->isUnindexed()) {
6628 unsigned OrigAlign = ST->getAlignment();
6629 EVT SVT = Value.getOperand(0).getValueType();
6630 unsigned Align = TLI.getTargetData()->
6631 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6632 if (Align <= OrigAlign &&
6633 ((!LegalOperations && !ST->isVolatile()) ||
6634 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6635 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6636 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6637 ST->isNonTemporal(), OrigAlign);
6640 // Turn 'store undef, Ptr' -> nothing.
6641 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
6644 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6645 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6646 // NOTE: If the original store is volatile, this transform must not increase
6647 // the number of stores. For example, on x86-32 an f64 can be stored in one
6648 // processor operation but an i64 (which is not legal) requires two. So the
6649 // transform should not be done in this case.
6650 if (Value.getOpcode() != ISD::TargetConstantFP) {
6652 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6653 default: llvm_unreachable("Unknown FP type");
6654 case MVT::f80: // We don't do this for these yet.
6659 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6660 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6661 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6662 bitcastToAPInt().getZExtValue(), MVT::i32);
6663 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6664 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6665 ST->isNonTemporal(), ST->getAlignment());
6669 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6670 !ST->isVolatile()) ||
6671 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6672 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6673 getZExtValue(), MVT::i64);
6674 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6675 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6676 ST->isNonTemporal(), ST->getAlignment());
6679 if (!ST->isVolatile() &&
6680 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6681 // Many FP stores are not made apparent until after legalize, e.g. for
6682 // argument passing. Since this is so common, custom legalize the
6683 // 64-bit integer store into two 32-bit stores.
6684 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6685 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6686 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6687 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6689 unsigned Alignment = ST->getAlignment();
6690 bool isVolatile = ST->isVolatile();
6691 bool isNonTemporal = ST->isNonTemporal();
6693 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6694 Ptr, ST->getPointerInfo(),
6695 isVolatile, isNonTemporal,
6696 ST->getAlignment());
6697 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6698 DAG.getConstant(4, Ptr.getValueType()));
6699 Alignment = MinAlign(Alignment, 4U);
6700 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6701 Ptr, ST->getPointerInfo().getWithOffset(4),
6702 isVolatile, isNonTemporal,
6704 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6713 // Try to infer better alignment information than the store already has.
6714 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6715 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6716 if (Align > ST->getAlignment())
6717 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6718 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6719 ST->isVolatile(), ST->isNonTemporal(), Align);
6723 // Try transforming a pair floating point load / store ops to integer
6724 // load / store ops.
6725 SDValue NewST = TransformFPLoadStorePair(N);
6726 if (NewST.getNode())
6730 // Walk up chain skipping non-aliasing memory nodes.
6731 SDValue BetterChain = FindBetterChain(N, Chain);
6733 // If there is a better chain.
6734 if (Chain != BetterChain) {
6737 // Replace the chain to avoid dependency.
6738 if (ST->isTruncatingStore()) {
6739 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6740 ST->getPointerInfo(),
6741 ST->getMemoryVT(), ST->isVolatile(),
6742 ST->isNonTemporal(), ST->getAlignment());
6744 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6745 ST->getPointerInfo(),
6746 ST->isVolatile(), ST->isNonTemporal(),
6747 ST->getAlignment());
6750 // Create token to keep both nodes around.
6751 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6752 MVT::Other, Chain, ReplStore);
6754 // Make sure the new and old chains are cleaned up.
6755 AddToWorkList(Token.getNode());
6757 // Don't add users to work list.
6758 return CombineTo(N, Token, false);
6762 // Try transforming N to an indexed store.
6763 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6764 return SDValue(N, 0);
6766 // FIXME: is there such a thing as a truncating indexed store?
6767 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6768 Value.getValueType().isInteger()) {
6769 // See if we can simplify the input to this truncstore with knowledge that
6770 // only the low bits are being used. For example:
6771 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6773 GetDemandedBits(Value,
6774 APInt::getLowBitsSet(
6775 Value.getValueType().getScalarType().getSizeInBits(),
6776 ST->getMemoryVT().getScalarType().getSizeInBits()));
6777 AddToWorkList(Value.getNode());
6778 if (Shorter.getNode())
6779 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6780 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6781 ST->isVolatile(), ST->isNonTemporal(),
6782 ST->getAlignment());
6784 // Otherwise, see if we can simplify the operation with
6785 // SimplifyDemandedBits, which only works if the value has a single use.
6786 if (SimplifyDemandedBits(Value,
6787 APInt::getLowBitsSet(
6788 Value.getValueType().getScalarType().getSizeInBits(),
6789 ST->getMemoryVT().getScalarType().getSizeInBits())))
6790 return SDValue(N, 0);
6793 // If this is a load followed by a store to the same location, then the store
6795 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6796 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6797 ST->isUnindexed() && !ST->isVolatile() &&
6798 // There can't be any side effects between the load and store, such as
6800 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6801 // The store is dead, remove it.
6806 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6807 // truncating store. We can do this even if this is already a truncstore.
6808 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6809 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6810 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6811 ST->getMemoryVT())) {
6812 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6813 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6814 ST->isVolatile(), ST->isNonTemporal(),
6815 ST->getAlignment());
6818 return ReduceLoadOpStoreWidth(N);
6821 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6822 SDValue InVec = N->getOperand(0);
6823 SDValue InVal = N->getOperand(1);
6824 SDValue EltNo = N->getOperand(2);
6825 DebugLoc dl = N->getDebugLoc();
6827 // If the inserted element is an UNDEF, just use the input vector.
6828 if (InVal.getOpcode() == ISD::UNDEF)
6831 EVT VT = InVec.getValueType();
6833 // If we can't generate a legal BUILD_VECTOR, exit
6834 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
6837 // Check that we know which element is being inserted
6838 if (!isa<ConstantSDNode>(EltNo))
6840 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6842 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
6843 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
6845 SmallVector<SDValue, 8> Ops;
6846 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
6847 Ops.append(InVec.getNode()->op_begin(),
6848 InVec.getNode()->op_end());
6849 } else if (InVec.getOpcode() == ISD::UNDEF) {
6850 unsigned NElts = VT.getVectorNumElements();
6851 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
6856 // Insert the element
6857 if (Elt < Ops.size()) {
6858 // All the operands of BUILD_VECTOR must have the same type;
6859 // we enforce that here.
6860 EVT OpVT = Ops[0].getValueType();
6861 if (InVal.getValueType() != OpVT)
6862 InVal = OpVT.bitsGT(InVal.getValueType()) ?
6863 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
6864 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
6868 // Return the new vector
6869 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6870 VT, &Ops[0], Ops.size());
6873 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6874 // (vextract (scalar_to_vector val, 0) -> val
6875 SDValue InVec = N->getOperand(0);
6877 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6878 // Check if the result type doesn't match the inserted element type. A
6879 // SCALAR_TO_VECTOR may truncate the inserted element and the
6880 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6881 SDValue InOp = InVec.getOperand(0);
6882 EVT NVT = N->getValueType(0);
6883 if (InOp.getValueType() != NVT) {
6884 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6885 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6890 // Perform only after legalization to ensure build_vector / vector_shuffle
6891 // optimizations have already been done.
6892 if (!LegalOperations) return SDValue();
6894 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6895 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6896 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6897 SDValue EltNo = N->getOperand(1);
6899 if (isa<ConstantSDNode>(EltNo)) {
6900 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6901 bool NewLoad = false;
6902 bool BCNumEltsChanged = false;
6903 EVT VT = InVec.getValueType();
6904 EVT ExtVT = VT.getVectorElementType();
6907 if (InVec.getOpcode() == ISD::BITCAST) {
6908 EVT BCVT = InVec.getOperand(0).getValueType();
6909 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6911 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6912 BCNumEltsChanged = true;
6913 InVec = InVec.getOperand(0);
6914 ExtVT = BCVT.getVectorElementType();
6918 LoadSDNode *LN0 = NULL;
6919 const ShuffleVectorSDNode *SVN = NULL;
6920 if (ISD::isNormalLoad(InVec.getNode())) {
6921 LN0 = cast<LoadSDNode>(InVec);
6922 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6923 InVec.getOperand(0).getValueType() == ExtVT &&
6924 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6925 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6926 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6927 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6929 // (load $addr+1*size)
6931 // If the bit convert changed the number of elements, it is unsafe
6932 // to examine the mask.
6933 if (BCNumEltsChanged)
6936 // Select the input vector, guarding against out of range extract vector.
6937 unsigned NumElems = VT.getVectorNumElements();
6938 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6939 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6941 if (InVec.getOpcode() == ISD::BITCAST)
6942 InVec = InVec.getOperand(0);
6943 if (ISD::isNormalLoad(InVec.getNode())) {
6944 LN0 = cast<LoadSDNode>(InVec);
6945 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6949 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
6952 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6954 return DAG.getUNDEF(LVT);
6956 unsigned Align = LN0->getAlignment();
6958 // Check the resultant load doesn't need a higher alignment than the
6962 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6964 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6970 SDValue NewPtr = LN0->getBasePtr();
6971 unsigned PtrOff = 0;
6974 PtrOff = LVT.getSizeInBits() * Elt / 8;
6975 EVT PtrType = NewPtr.getValueType();
6976 if (TLI.isBigEndian())
6977 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6978 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6979 DAG.getConstant(PtrOff, PtrType));
6982 // The replacement we need to do here is a little tricky: we need to
6983 // replace an extractelement of a load with a load.
6984 // Use ReplaceAllUsesOfValuesWith to do the replacement.
6985 SDValue Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6986 LN0->getPointerInfo().getWithOffset(PtrOff),
6987 LN0->isVolatile(), LN0->isNonTemporal(),
6988 LN0->isInvariant(), Align);
6989 WorkListRemover DeadNodes(*this);
6990 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
6991 SDValue To[] = { Load.getValue(0), Load.getValue(1) };
6992 DAG.ReplaceAllUsesOfValuesWith(From, To, 2, &DeadNodes);
6993 // Since we're explcitly calling ReplaceAllUses, add the new node to the
6994 // worklist explicitly as well.
6995 AddToWorkList(Load.getNode());
6996 // Make sure to revisit this node to clean it up; it will usually be dead.
6998 return SDValue(N, 0);
7004 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
7005 unsigned NumInScalars = N->getNumOperands();
7006 DebugLoc dl = N->getDebugLoc();
7007 EVT VT = N->getValueType(0);
7008 // Check to see if this is a BUILD_VECTOR of a bunch of values
7009 // which come from any_extend or zero_extend nodes. If so, we can create
7010 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
7011 // optimizations. We do not handle sign-extend because we can't fill the sign
7013 EVT SourceType = MVT::Other;
7014 bool allAnyExt = true;
7015 for (unsigned i = 0; i < NumInScalars; ++i) {
7016 SDValue In = N->getOperand(i);
7017 // Ignore undef inputs.
7018 if (In.getOpcode() == ISD::UNDEF) continue;
7020 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
7021 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
7023 // Abort if the element is not an extension.
7024 if (!ZeroExt && !AnyExt) {
7025 SourceType = MVT::Other;
7029 // The input is a ZeroExt or AnyExt. Check the original type.
7030 EVT InTy = In.getOperand(0).getValueType();
7032 // Check that all of the widened source types are the same.
7033 if (SourceType == MVT::Other)
7036 else if (InTy != SourceType) {
7037 // Multiple income types. Abort.
7038 SourceType = MVT::Other;
7042 // Check if all of the extends are ANY_EXTENDs.
7043 allAnyExt &= AnyExt;
7047 // In order to have valid types, all of the inputs must be extended from the
7048 // same source type and all of the inputs must be any or zero extend.
7049 // Scalar sizes must be a power of two.
7050 EVT OutScalarTy = N->getValueType(0).getScalarType();
7051 bool validTypes = SourceType != MVT::Other &&
7052 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7053 isPowerOf2_32(SourceType.getSizeInBits());
7055 // We perform this optimization post type-legalization because
7056 // the type-legalizer often scalarizes integer-promoted vectors.
7057 // Performing this optimization before may create bit-casts which
7058 // will be type-legalized to complex code sequences.
7059 // We perform this optimization only before the operation legalizer because we
7060 // may introduce illegal operations.
7061 if (LegalTypes && !LegalOperations && validTypes) {
7062 bool isLE = TLI.isLittleEndian();
7063 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7064 assert(ElemRatio > 1 && "Invalid element size ratio");
7065 SDValue Filler = allAnyExt ? DAG.getUNDEF(SourceType):
7066 DAG.getConstant(0, SourceType);
7068 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7069 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7071 // Populate the new build_vector
7072 for (unsigned i=0; i < N->getNumOperands(); ++i) {
7073 SDValue Cast = N->getOperand(i);
7074 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7075 Cast.getOpcode() == ISD::ZERO_EXTEND ||
7076 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7078 if (Cast.getOpcode() == ISD::UNDEF)
7079 In = DAG.getUNDEF(SourceType);
7081 In = Cast->getOperand(0);
7082 unsigned Index = isLE ? (i * ElemRatio) :
7083 (i * ElemRatio + (ElemRatio - 1));
7085 assert(Index < Ops.size() && "Invalid index");
7089 // The type of the new BUILD_VECTOR node.
7090 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7091 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7092 "Invalid vector size");
7093 // Check if the new vector type is legal.
7094 if (!isTypeLegal(VecVT)) return SDValue();
7096 // Make the new BUILD_VECTOR.
7097 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7098 VecVT, &Ops[0], Ops.size());
7100 // Bitcast to the desired type.
7101 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7104 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7105 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7106 // at most two distinct vectors, turn this into a shuffle node.
7107 SDValue VecIn1, VecIn2;
7108 for (unsigned i = 0; i != NumInScalars; ++i) {
7109 // Ignore undef inputs.
7110 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7112 // If this input is something other than a EXTRACT_VECTOR_ELT with a
7113 // constant index, bail out.
7114 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7115 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7116 VecIn1 = VecIn2 = SDValue(0, 0);
7120 // If the input vector type disagrees with the result of the build_vector,
7121 // we can't make a shuffle.
7122 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7123 if (ExtractedFromVec.getValueType() != VT) {
7124 VecIn1 = VecIn2 = SDValue(0, 0);
7128 // Otherwise, remember this. We allow up to two distinct input vectors.
7129 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7132 if (VecIn1.getNode() == 0) {
7133 VecIn1 = ExtractedFromVec;
7134 } else if (VecIn2.getNode() == 0) {
7135 VecIn2 = ExtractedFromVec;
7138 VecIn1 = VecIn2 = SDValue(0, 0);
7143 // If everything is good, we can make a shuffle operation.
7144 if (VecIn1.getNode()) {
7145 SmallVector<int, 8> Mask;
7146 for (unsigned i = 0; i != NumInScalars; ++i) {
7147 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7152 // If extracting from the first vector, just use the index directly.
7153 SDValue Extract = N->getOperand(i);
7154 SDValue ExtVal = Extract.getOperand(1);
7155 if (Extract.getOperand(0) == VecIn1) {
7156 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7157 if (ExtIndex > VT.getVectorNumElements())
7160 Mask.push_back(ExtIndex);
7164 // Otherwise, use InIdx + VecSize
7165 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7166 Mask.push_back(Idx+NumInScalars);
7169 // Add count and size info.
7170 if (!isTypeLegal(VT))
7173 // Return the new VECTOR_SHUFFLE node.
7176 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7177 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7183 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7184 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7185 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
7186 // inputs come from at most two distinct vectors, turn this into a shuffle
7189 // If we only have one input vector, we don't need to do any concatenation.
7190 if (N->getNumOperands() == 1)
7191 return N->getOperand(0);
7196 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7197 EVT NVT = N->getValueType(0);
7198 SDValue V = N->getOperand(0);
7200 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7201 // Handle only simple case where vector being inserted and vector
7202 // being extracted are of same type, and are half size of larger vectors.
7203 EVT BigVT = V->getOperand(0).getValueType();
7204 EVT SmallVT = V->getOperand(1).getValueType();
7205 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7208 // Only handle cases where both indexes are constants with the same type.
7209 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7210 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
7212 if (InsIdx && ExtIdx &&
7213 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
7214 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
7216 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7218 // indices are equal => V1
7219 // otherwise => (extract_subvec V1, ExtIdx)
7220 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
7221 return V->getOperand(1);
7222 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7223 V->getOperand(0), N->getOperand(1));
7230 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7231 EVT VT = N->getValueType(0);
7232 unsigned NumElts = VT.getVectorNumElements();
7234 SDValue N0 = N->getOperand(0);
7236 assert(N0.getValueType().getVectorNumElements() == NumElts &&
7237 "Vector shuffle must be normalized in DAG");
7239 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
7241 // If it is a splat, check if the argument vector is another splat or a
7242 // build_vector with all scalar elements the same.
7243 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7244 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7245 SDNode *V = N0.getNode();
7247 // If this is a bit convert that changes the element type of the vector but
7248 // not the number of vector elements, look through it. Be careful not to
7249 // look though conversions that change things like v4f32 to v2f64.
7250 if (V->getOpcode() == ISD::BITCAST) {
7251 SDValue ConvInput = V->getOperand(0);
7252 if (ConvInput.getValueType().isVector() &&
7253 ConvInput.getValueType().getVectorNumElements() == NumElts)
7254 V = ConvInput.getNode();
7257 if (V->getOpcode() == ISD::BUILD_VECTOR) {
7258 assert(V->getNumOperands() == NumElts &&
7259 "BUILD_VECTOR has wrong number of operands");
7261 bool AllSame = true;
7262 for (unsigned i = 0; i != NumElts; ++i) {
7263 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7264 Base = V->getOperand(i);
7268 // Splat of <u, u, u, u>, return <u, u, u, u>
7269 if (!Base.getNode())
7271 for (unsigned i = 0; i != NumElts; ++i) {
7272 if (V->getOperand(i) != Base) {
7277 // Splat of <x, x, x, x>, return <x, x, x, x>
7285 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
7286 if (!TLI.getShouldFoldAtomicFences())
7289 SDValue atomic = N->getOperand(0);
7290 switch (atomic.getOpcode()) {
7291 case ISD::ATOMIC_CMP_SWAP:
7292 case ISD::ATOMIC_SWAP:
7293 case ISD::ATOMIC_LOAD_ADD:
7294 case ISD::ATOMIC_LOAD_SUB:
7295 case ISD::ATOMIC_LOAD_AND:
7296 case ISD::ATOMIC_LOAD_OR:
7297 case ISD::ATOMIC_LOAD_XOR:
7298 case ISD::ATOMIC_LOAD_NAND:
7299 case ISD::ATOMIC_LOAD_MIN:
7300 case ISD::ATOMIC_LOAD_MAX:
7301 case ISD::ATOMIC_LOAD_UMIN:
7302 case ISD::ATOMIC_LOAD_UMAX:
7308 SDValue fence = atomic.getOperand(0);
7309 if (fence.getOpcode() != ISD::MEMBARRIER)
7312 switch (atomic.getOpcode()) {
7313 case ISD::ATOMIC_CMP_SWAP:
7314 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7315 fence.getOperand(0),
7316 atomic.getOperand(1), atomic.getOperand(2),
7317 atomic.getOperand(3)), atomic.getResNo());
7318 case ISD::ATOMIC_SWAP:
7319 case ISD::ATOMIC_LOAD_ADD:
7320 case ISD::ATOMIC_LOAD_SUB:
7321 case ISD::ATOMIC_LOAD_AND:
7322 case ISD::ATOMIC_LOAD_OR:
7323 case ISD::ATOMIC_LOAD_XOR:
7324 case ISD::ATOMIC_LOAD_NAND:
7325 case ISD::ATOMIC_LOAD_MIN:
7326 case ISD::ATOMIC_LOAD_MAX:
7327 case ISD::ATOMIC_LOAD_UMIN:
7328 case ISD::ATOMIC_LOAD_UMAX:
7329 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7330 fence.getOperand(0),
7331 atomic.getOperand(1), atomic.getOperand(2)),
7338 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
7339 /// an AND to a vector_shuffle with the destination vector and a zero vector.
7340 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
7341 /// vector_shuffle V, Zero, <0, 4, 2, 4>
7342 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
7343 EVT VT = N->getValueType(0);
7344 DebugLoc dl = N->getDebugLoc();
7345 SDValue LHS = N->getOperand(0);
7346 SDValue RHS = N->getOperand(1);
7347 if (N->getOpcode() == ISD::AND) {
7348 if (RHS.getOpcode() == ISD::BITCAST)
7349 RHS = RHS.getOperand(0);
7350 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
7351 SmallVector<int, 8> Indices;
7352 unsigned NumElts = RHS.getNumOperands();
7353 for (unsigned i = 0; i != NumElts; ++i) {
7354 SDValue Elt = RHS.getOperand(i);
7355 if (!isa<ConstantSDNode>(Elt))
7357 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
7358 Indices.push_back(i);
7359 else if (cast<ConstantSDNode>(Elt)->isNullValue())
7360 Indices.push_back(NumElts);
7365 // Let's see if the target supports this vector_shuffle.
7366 EVT RVT = RHS.getValueType();
7367 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
7370 // Return the new VECTOR_SHUFFLE node.
7371 EVT EltVT = RVT.getVectorElementType();
7372 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
7373 DAG.getConstant(0, EltVT));
7374 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7375 RVT, &ZeroOps[0], ZeroOps.size());
7376 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
7377 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
7378 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
7385 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
7386 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
7387 // After legalize, the target may be depending on adds and other
7388 // binary ops to provide legal ways to construct constants or other
7389 // things. Simplifying them may result in a loss of legality.
7390 if (LegalOperations) return SDValue();
7392 assert(N->getValueType(0).isVector() &&
7393 "SimplifyVBinOp only works on vectors!");
7395 SDValue LHS = N->getOperand(0);
7396 SDValue RHS = N->getOperand(1);
7397 SDValue Shuffle = XformToShuffleWithZero(N);
7398 if (Shuffle.getNode()) return Shuffle;
7400 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
7402 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
7403 RHS.getOpcode() == ISD::BUILD_VECTOR) {
7404 SmallVector<SDValue, 8> Ops;
7405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
7406 SDValue LHSOp = LHS.getOperand(i);
7407 SDValue RHSOp = RHS.getOperand(i);
7408 // If these two elements can't be folded, bail out.
7409 if ((LHSOp.getOpcode() != ISD::UNDEF &&
7410 LHSOp.getOpcode() != ISD::Constant &&
7411 LHSOp.getOpcode() != ISD::ConstantFP) ||
7412 (RHSOp.getOpcode() != ISD::UNDEF &&
7413 RHSOp.getOpcode() != ISD::Constant &&
7414 RHSOp.getOpcode() != ISD::ConstantFP))
7417 // Can't fold divide by zero.
7418 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
7419 N->getOpcode() == ISD::FDIV) {
7420 if ((RHSOp.getOpcode() == ISD::Constant &&
7421 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
7422 (RHSOp.getOpcode() == ISD::ConstantFP &&
7423 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
7427 EVT VT = LHSOp.getValueType();
7428 EVT RVT = RHSOp.getValueType();
7430 // Integer BUILD_VECTOR operands may have types larger than the element
7431 // size (e.g., when the element type is not legal). Prior to type
7432 // legalization, the types may not match between the two BUILD_VECTORS.
7433 // Truncate one of the operands to make them match.
7434 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
7435 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
7437 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
7441 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
7443 if (FoldOp.getOpcode() != ISD::UNDEF &&
7444 FoldOp.getOpcode() != ISD::Constant &&
7445 FoldOp.getOpcode() != ISD::ConstantFP)
7447 Ops.push_back(FoldOp);
7448 AddToWorkList(FoldOp.getNode());
7451 if (Ops.size() == LHS.getNumOperands())
7452 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7453 LHS.getValueType(), &Ops[0], Ops.size());
7459 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
7460 SDValue N1, SDValue N2){
7461 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
7463 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
7464 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7466 // If we got a simplified select_cc node back from SimplifySelectCC, then
7467 // break it down into a new SETCC node, and a new SELECT node, and then return
7468 // the SELECT node, since we were called with a SELECT node.
7469 if (SCC.getNode()) {
7470 // Check to see if we got a select_cc back (to turn into setcc/select).
7471 // Otherwise, just return whatever node we got back, like fabs.
7472 if (SCC.getOpcode() == ISD::SELECT_CC) {
7473 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
7475 SCC.getOperand(0), SCC.getOperand(1),
7477 AddToWorkList(SETCC.getNode());
7478 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
7479 SCC.getOperand(2), SCC.getOperand(3), SETCC);
7487 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
7488 /// are the two values being selected between, see if we can simplify the
7489 /// select. Callers of this should assume that TheSelect is deleted if this
7490 /// returns true. As such, they should return the appropriate thing (e.g. the
7491 /// node) back to the top-level of the DAG combiner loop to avoid it being
7493 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
7496 // Cannot simplify select with vector condition
7497 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
7499 // If this is a select from two identical things, try to pull the operation
7500 // through the select.
7501 if (LHS.getOpcode() != RHS.getOpcode() ||
7502 !LHS.hasOneUse() || !RHS.hasOneUse())
7505 // If this is a load and the token chain is identical, replace the select
7506 // of two loads with a load through a select of the address to load from.
7507 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
7508 // constants have been dropped into the constant pool.
7509 if (LHS.getOpcode() == ISD::LOAD) {
7510 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
7511 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
7513 // Token chains must be identical.
7514 if (LHS.getOperand(0) != RHS.getOperand(0) ||
7515 // Do not let this transformation reduce the number of volatile loads.
7516 LLD->isVolatile() || RLD->isVolatile() ||
7517 // If this is an EXTLOAD, the VT's must match.
7518 LLD->getMemoryVT() != RLD->getMemoryVT() ||
7519 // If this is an EXTLOAD, the kind of extension must match.
7520 (LLD->getExtensionType() != RLD->getExtensionType() &&
7521 // The only exception is if one of the extensions is anyext.
7522 LLD->getExtensionType() != ISD::EXTLOAD &&
7523 RLD->getExtensionType() != ISD::EXTLOAD) ||
7524 // FIXME: this discards src value information. This is
7525 // over-conservative. It would be beneficial to be able to remember
7526 // both potential memory locations. Since we are discarding
7527 // src value info, don't do the transformation if the memory
7528 // locations are not in the default address space.
7529 LLD->getPointerInfo().getAddrSpace() != 0 ||
7530 RLD->getPointerInfo().getAddrSpace() != 0)
7533 // Check that the select condition doesn't reach either load. If so,
7534 // folding this will induce a cycle into the DAG. If not, this is safe to
7535 // xform, so create a select of the addresses.
7537 if (TheSelect->getOpcode() == ISD::SELECT) {
7538 SDNode *CondNode = TheSelect->getOperand(0).getNode();
7539 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
7540 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
7542 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
7543 LLD->getBasePtr().getValueType(),
7544 TheSelect->getOperand(0), LLD->getBasePtr(),
7546 } else { // Otherwise SELECT_CC
7547 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
7548 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
7550 if ((LLD->hasAnyUseOfValue(1) &&
7551 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
7552 (LLD->hasAnyUseOfValue(1) &&
7553 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
7556 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
7557 LLD->getBasePtr().getValueType(),
7558 TheSelect->getOperand(0),
7559 TheSelect->getOperand(1),
7560 LLD->getBasePtr(), RLD->getBasePtr(),
7561 TheSelect->getOperand(4));
7565 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
7566 Load = DAG.getLoad(TheSelect->getValueType(0),
7567 TheSelect->getDebugLoc(),
7568 // FIXME: Discards pointer info.
7569 LLD->getChain(), Addr, MachinePointerInfo(),
7570 LLD->isVolatile(), LLD->isNonTemporal(),
7571 LLD->isInvariant(), LLD->getAlignment());
7573 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
7574 RLD->getExtensionType() : LLD->getExtensionType(),
7575 TheSelect->getDebugLoc(),
7576 TheSelect->getValueType(0),
7577 // FIXME: Discards pointer info.
7578 LLD->getChain(), Addr, MachinePointerInfo(),
7579 LLD->getMemoryVT(), LLD->isVolatile(),
7580 LLD->isNonTemporal(), LLD->getAlignment());
7583 // Users of the select now use the result of the load.
7584 CombineTo(TheSelect, Load);
7586 // Users of the old loads now use the new load's chain. We know the
7587 // old-load value is dead now.
7588 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
7589 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
7596 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
7597 /// where 'cond' is the comparison specified by CC.
7598 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
7599 SDValue N2, SDValue N3,
7600 ISD::CondCode CC, bool NotExtCompare) {
7601 // (x ? y : y) -> y.
7602 if (N2 == N3) return N2;
7604 EVT VT = N2.getValueType();
7605 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
7606 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
7607 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
7609 // Determine if the condition we're dealing with is constant
7610 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
7611 N0, N1, CC, DL, false);
7612 if (SCC.getNode()) AddToWorkList(SCC.getNode());
7613 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
7615 // fold select_cc true, x, y -> x
7616 if (SCCC && !SCCC->isNullValue())
7618 // fold select_cc false, x, y -> y
7619 if (SCCC && SCCC->isNullValue())
7622 // Check to see if we can simplify the select into an fabs node
7623 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
7624 // Allow either -0.0 or 0.0
7625 if (CFP->getValueAPF().isZero()) {
7626 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
7627 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
7628 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
7629 N2 == N3.getOperand(0))
7630 return DAG.getNode(ISD::FABS, DL, VT, N0);
7632 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
7633 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
7634 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
7635 N2.getOperand(0) == N3)
7636 return DAG.getNode(ISD::FABS, DL, VT, N3);
7640 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
7641 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
7642 // in it. This is a win when the constant is not otherwise available because
7643 // it replaces two constant pool loads with one. We only do this if the FP
7644 // type is known to be legal, because if it isn't, then we are before legalize
7645 // types an we want the other legalization to happen first (e.g. to avoid
7646 // messing with soft float) and if the ConstantFP is not legal, because if
7647 // it is legal, we may not need to store the FP constant in a constant pool.
7648 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
7649 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
7650 if (TLI.isTypeLegal(N2.getValueType()) &&
7651 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
7652 TargetLowering::Legal) &&
7653 // If both constants have multiple uses, then we won't need to do an
7654 // extra load, they are likely around in registers for other users.
7655 (TV->hasOneUse() || FV->hasOneUse())) {
7656 Constant *Elts[] = {
7657 const_cast<ConstantFP*>(FV->getConstantFPValue()),
7658 const_cast<ConstantFP*>(TV->getConstantFPValue())
7660 Type *FPTy = Elts[0]->getType();
7661 const TargetData &TD = *TLI.getTargetData();
7663 // Create a ConstantArray of the two constants.
7664 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
7665 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
7666 TD.getPrefTypeAlignment(FPTy));
7667 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
7669 // Get the offsets to the 0 and 1 element of the array so that we can
7670 // select between them.
7671 SDValue Zero = DAG.getIntPtrConstant(0);
7672 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
7673 SDValue One = DAG.getIntPtrConstant(EltSize);
7675 SDValue Cond = DAG.getSetCC(DL,
7676 TLI.getSetCCResultType(N0.getValueType()),
7678 AddToWorkList(Cond.getNode());
7679 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
7681 AddToWorkList(CstOffset.getNode());
7682 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
7684 AddToWorkList(CPIdx.getNode());
7685 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
7686 MachinePointerInfo::getConstantPool(), false,
7687 false, false, Alignment);
7692 // Check to see if we can perform the "gzip trick", transforming
7693 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7694 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7695 (N1C->isNullValue() || // (a < 0) ? b : 0
7696 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
7697 EVT XType = N0.getValueType();
7698 EVT AType = N2.getValueType();
7699 if (XType.bitsGE(AType)) {
7700 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7701 // single-bit constant.
7702 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7703 unsigned ShCtV = N2C->getAPIntValue().logBase2();
7704 ShCtV = XType.getSizeInBits()-ShCtV-1;
7705 SDValue ShCt = DAG.getConstant(ShCtV,
7706 getShiftAmountTy(N0.getValueType()));
7707 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7709 AddToWorkList(Shift.getNode());
7711 if (XType.bitsGT(AType)) {
7712 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7713 AddToWorkList(Shift.getNode());
7716 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7719 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7721 DAG.getConstant(XType.getSizeInBits()-1,
7722 getShiftAmountTy(N0.getValueType())));
7723 AddToWorkList(Shift.getNode());
7725 if (XType.bitsGT(AType)) {
7726 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7727 AddToWorkList(Shift.getNode());
7730 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7734 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7735 // where y is has a single bit set.
7736 // A plaintext description would be, we can turn the SELECT_CC into an AND
7737 // when the condition can be materialized as an all-ones register. Any
7738 // single bit-test can be materialized as an all-ones register with
7739 // shift-left and shift-right-arith.
7740 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7741 N0->getValueType(0) == VT &&
7742 N1C && N1C->isNullValue() &&
7743 N2C && N2C->isNullValue()) {
7744 SDValue AndLHS = N0->getOperand(0);
7745 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7746 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7747 // Shift the tested bit over the sign bit.
7748 APInt AndMask = ConstAndRHS->getAPIntValue();
7750 DAG.getConstant(AndMask.countLeadingZeros(),
7751 getShiftAmountTy(AndLHS.getValueType()));
7752 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7754 // Now arithmetic right shift it all the way over, so the result is either
7755 // all-ones, or zero.
7757 DAG.getConstant(AndMask.getBitWidth()-1,
7758 getShiftAmountTy(Shl.getValueType()));
7759 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7761 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7765 // fold select C, 16, 0 -> shl C, 4
7766 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7767 TLI.getBooleanContents(N0.getValueType().isVector()) ==
7768 TargetLowering::ZeroOrOneBooleanContent) {
7770 // If the caller doesn't want us to simplify this into a zext of a compare,
7772 if (NotExtCompare && N2C->getAPIntValue() == 1)
7775 // Get a SetCC of the condition
7776 // FIXME: Should probably make sure that setcc is legal if we ever have a
7777 // target where it isn't.
7779 // cast from setcc result type to select result type
7781 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7783 if (N2.getValueType().bitsLT(SCC.getValueType()))
7784 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7786 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7787 N2.getValueType(), SCC);
7789 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7790 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7791 N2.getValueType(), SCC);
7794 AddToWorkList(SCC.getNode());
7795 AddToWorkList(Temp.getNode());
7797 if (N2C->getAPIntValue() == 1)
7800 // shl setcc result by log2 n2c
7801 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7802 DAG.getConstant(N2C->getAPIntValue().logBase2(),
7803 getShiftAmountTy(Temp.getValueType())));
7806 // Check to see if this is the equivalent of setcc
7807 // FIXME: Turn all of these into setcc if setcc if setcc is legal
7808 // otherwise, go ahead with the folds.
7809 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7810 EVT XType = N0.getValueType();
7811 if (!LegalOperations ||
7812 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7813 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7814 if (Res.getValueType() != VT)
7815 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7819 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7820 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7821 (!LegalOperations ||
7822 TLI.isOperationLegal(ISD::CTLZ, XType))) {
7823 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7824 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7825 DAG.getConstant(Log2_32(XType.getSizeInBits()),
7826 getShiftAmountTy(Ctlz.getValueType())));
7828 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7829 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7830 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7831 XType, DAG.getConstant(0, XType), N0);
7832 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7833 return DAG.getNode(ISD::SRL, DL, XType,
7834 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7835 DAG.getConstant(XType.getSizeInBits()-1,
7836 getShiftAmountTy(XType)));
7838 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7839 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7840 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7841 DAG.getConstant(XType.getSizeInBits()-1,
7842 getShiftAmountTy(N0.getValueType())));
7843 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7847 // Check to see if this is an integer abs.
7848 // select_cc setg[te] X, 0, X, -X ->
7849 // select_cc setgt X, -1, X, -X ->
7850 // select_cc setl[te] X, 0, -X, X ->
7851 // select_cc setlt X, 1, -X, X ->
7852 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7854 ConstantSDNode *SubC = NULL;
7855 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7856 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7857 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7858 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7859 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7860 (N1C->isOne() && CC == ISD::SETLT)) &&
7861 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7862 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7864 EVT XType = N0.getValueType();
7865 if (SubC && SubC->isNullValue() && XType.isInteger()) {
7866 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7868 DAG.getConstant(XType.getSizeInBits()-1,
7869 getShiftAmountTy(N0.getValueType())));
7870 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7872 AddToWorkList(Shift.getNode());
7873 AddToWorkList(Add.getNode());
7874 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7881 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7882 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7883 SDValue N1, ISD::CondCode Cond,
7884 DebugLoc DL, bool foldBooleans) {
7885 TargetLowering::DAGCombinerInfo
7886 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7887 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7890 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7891 /// return a DAG expression to select that will generate the same value by
7892 /// multiplying by a magic number. See:
7893 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7894 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7895 std::vector<SDNode*> Built;
7896 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
7898 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7904 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7905 /// return a DAG expression to select that will generate the same value by
7906 /// multiplying by a magic number. See:
7907 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7908 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7909 std::vector<SDNode*> Built;
7910 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
7912 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7918 /// FindBaseOffset - Return true if base is a frame index, which is known not
7919 // to alias with anything but itself. Provides base object and offset as
7921 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7922 const GlobalValue *&GV, void *&CV) {
7923 // Assume it is a primitive operation.
7924 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7926 // If it's an adding a simple constant then integrate the offset.
7927 if (Base.getOpcode() == ISD::ADD) {
7928 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7929 Base = Base.getOperand(0);
7930 Offset += C->getZExtValue();
7934 // Return the underlying GlobalValue, and update the Offset. Return false
7935 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7936 // by multiple nodes with different offsets.
7937 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7938 GV = G->getGlobal();
7939 Offset += G->getOffset();
7943 // Return the underlying Constant value, and update the Offset. Return false
7944 // for ConstantSDNodes since the same constant pool entry may be represented
7945 // by multiple nodes with different offsets.
7946 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7947 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7948 : (void *)C->getConstVal();
7949 Offset += C->getOffset();
7952 // If it's any of the following then it can't alias with anything but itself.
7953 return isa<FrameIndexSDNode>(Base);
7956 /// isAlias - Return true if there is any possibility that the two addresses
7958 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7959 const Value *SrcValue1, int SrcValueOffset1,
7960 unsigned SrcValueAlign1,
7961 const MDNode *TBAAInfo1,
7962 SDValue Ptr2, int64_t Size2,
7963 const Value *SrcValue2, int SrcValueOffset2,
7964 unsigned SrcValueAlign2,
7965 const MDNode *TBAAInfo2) const {
7966 // If they are the same then they must be aliases.
7967 if (Ptr1 == Ptr2) return true;
7969 // Gather base node and offset information.
7970 SDValue Base1, Base2;
7971 int64_t Offset1, Offset2;
7972 const GlobalValue *GV1, *GV2;
7974 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7975 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7977 // If they have a same base address then check to see if they overlap.
7978 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7979 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7981 // It is possible for different frame indices to alias each other, mostly
7982 // when tail call optimization reuses return address slots for arguments.
7983 // To catch this case, look up the actual index of frame indices to compute
7984 // the real alias relationship.
7985 if (isFrameIndex1 && isFrameIndex2) {
7986 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7987 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7988 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7989 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7992 // Otherwise, if we know what the bases are, and they aren't identical, then
7993 // we know they cannot alias.
7994 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7997 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7998 // compared to the size and offset of the access, we may be able to prove they
7999 // do not alias. This check is conservative for now to catch cases created by
8000 // splitting vector types.
8001 if ((SrcValueAlign1 == SrcValueAlign2) &&
8002 (SrcValueOffset1 != SrcValueOffset2) &&
8003 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
8004 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
8005 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
8007 // There is no overlap between these relatively aligned accesses of similar
8008 // size, return no alias.
8009 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
8013 if (CombinerGlobalAA) {
8014 // Use alias analysis information.
8015 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
8016 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
8017 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
8018 AliasAnalysis::AliasResult AAResult =
8019 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
8020 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
8021 if (AAResult == AliasAnalysis::NoAlias)
8025 // Otherwise we have to assume they alias.
8029 /// FindAliasInfo - Extracts the relevant alias information from the memory
8030 /// node. Returns true if the operand was a load.
8031 bool DAGCombiner::FindAliasInfo(SDNode *N,
8032 SDValue &Ptr, int64_t &Size,
8033 const Value *&SrcValue,
8034 int &SrcValueOffset,
8035 unsigned &SrcValueAlign,
8036 const MDNode *&TBAAInfo) const {
8037 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8038 Ptr = LD->getBasePtr();
8039 Size = LD->getMemoryVT().getSizeInBits() >> 3;
8040 SrcValue = LD->getSrcValue();
8041 SrcValueOffset = LD->getSrcValueOffset();
8042 SrcValueAlign = LD->getOriginalAlignment();
8043 TBAAInfo = LD->getTBAAInfo();
8046 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8047 Ptr = ST->getBasePtr();
8048 Size = ST->getMemoryVT().getSizeInBits() >> 3;
8049 SrcValue = ST->getSrcValue();
8050 SrcValueOffset = ST->getSrcValueOffset();
8051 SrcValueAlign = ST->getOriginalAlignment();
8052 TBAAInfo = ST->getTBAAInfo();
8055 llvm_unreachable("FindAliasInfo expected a memory operand");
8058 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8059 /// looking for aliasing nodes and adding them to the Aliases vector.
8060 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8061 SmallVector<SDValue, 8> &Aliases) {
8062 SmallVector<SDValue, 8> Chains; // List of chains to visit.
8063 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
8065 // Get alias information for node.
8068 const Value *SrcValue;
8070 unsigned SrcValueAlign;
8071 const MDNode *SrcTBAAInfo;
8072 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8073 SrcValueAlign, SrcTBAAInfo);
8076 Chains.push_back(OriginalChain);
8079 // Look at each chain and determine if it is an alias. If so, add it to the
8080 // aliases list. If not, then continue up the chain looking for the next
8082 while (!Chains.empty()) {
8083 SDValue Chain = Chains.back();
8086 // For TokenFactor nodes, look at each operand and only continue up the
8087 // chain until we find two aliases. If we've seen two aliases, assume we'll
8088 // find more and revert to original chain since the xform is unlikely to be
8091 // FIXME: The depth check could be made to return the last non-aliasing
8092 // chain we found before we hit a tokenfactor rather than the original
8094 if (Depth > 6 || Aliases.size() == 2) {
8096 Aliases.push_back(OriginalChain);
8100 // Don't bother if we've been before.
8101 if (!Visited.insert(Chain.getNode()))
8104 switch (Chain.getOpcode()) {
8105 case ISD::EntryToken:
8106 // Entry token is ideal chain operand, but handled in FindBetterChain.
8111 // Get alias information for Chain.
8114 const Value *OpSrcValue;
8115 int OpSrcValueOffset;
8116 unsigned OpSrcValueAlign;
8117 const MDNode *OpSrcTBAAInfo;
8118 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8119 OpSrcValue, OpSrcValueOffset,
8123 // If chain is alias then stop here.
8124 if (!(IsLoad && IsOpLoad) &&
8125 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8127 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8128 OpSrcValueAlign, OpSrcTBAAInfo)) {
8129 Aliases.push_back(Chain);
8131 // Look further up the chain.
8132 Chains.push_back(Chain.getOperand(0));
8138 case ISD::TokenFactor:
8139 // We have to check each of the operands of the token factor for "small"
8140 // token factors, so we queue them up. Adding the operands to the queue
8141 // (stack) in reverse order maintains the original order and increases the
8142 // likelihood that getNode will find a matching token factor (CSE.)
8143 if (Chain.getNumOperands() > 16) {
8144 Aliases.push_back(Chain);
8147 for (unsigned n = Chain.getNumOperands(); n;)
8148 Chains.push_back(Chain.getOperand(--n));
8153 // For all other instructions we will just have to take what we can get.
8154 Aliases.push_back(Chain);
8160 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8161 /// for a better chain (aliasing node.)
8162 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8163 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
8165 // Accumulate all the aliases to this node.
8166 GatherAllAliases(N, OldChain, Aliases);
8168 // If no operands then chain to entry token.
8169 if (Aliases.size() == 0)
8170 return DAG.getEntryNode();
8172 // If a single operand then chain to it. We don't need to revisit it.
8173 if (Aliases.size() == 1)
8176 // Construct a custom tailored token factor.
8177 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8178 &Aliases[0], Aliases.size());
8181 // SelectionDAG::Combine - This is the entry point for the file.
8183 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8184 CodeGenOpt::Level OptLevel) {
8185 /// run - This is the main entry point to this class.
8187 DAGCombiner(*this, AA, OptLevel).Run(Level);