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 visitCTTZ(SDNode *N);
184 SDValue visitCTPOP(SDNode *N);
185 SDValue visitSELECT(SDNode *N);
186 SDValue visitSELECT_CC(SDNode *N);
187 SDValue visitSETCC(SDNode *N);
188 SDValue visitSIGN_EXTEND(SDNode *N);
189 SDValue visitZERO_EXTEND(SDNode *N);
190 SDValue visitANY_EXTEND(SDNode *N);
191 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
192 SDValue visitTRUNCATE(SDNode *N);
193 SDValue visitBITCAST(SDNode *N);
194 SDValue visitBUILD_PAIR(SDNode *N);
195 SDValue visitFADD(SDNode *N);
196 SDValue visitFSUB(SDNode *N);
197 SDValue visitFMUL(SDNode *N);
198 SDValue visitFDIV(SDNode *N);
199 SDValue visitFREM(SDNode *N);
200 SDValue visitFCOPYSIGN(SDNode *N);
201 SDValue visitSINT_TO_FP(SDNode *N);
202 SDValue visitUINT_TO_FP(SDNode *N);
203 SDValue visitFP_TO_SINT(SDNode *N);
204 SDValue visitFP_TO_UINT(SDNode *N);
205 SDValue visitFP_ROUND(SDNode *N);
206 SDValue visitFP_ROUND_INREG(SDNode *N);
207 SDValue visitFP_EXTEND(SDNode *N);
208 SDValue visitFNEG(SDNode *N);
209 SDValue visitFABS(SDNode *N);
210 SDValue visitBRCOND(SDNode *N);
211 SDValue visitBR_CC(SDNode *N);
212 SDValue visitLOAD(SDNode *N);
213 SDValue visitSTORE(SDNode *N);
214 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
215 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
216 SDValue visitBUILD_VECTOR(SDNode *N);
217 SDValue visitCONCAT_VECTORS(SDNode *N);
218 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
219 SDValue visitVECTOR_SHUFFLE(SDNode *N);
220 SDValue visitMEMBARRIER(SDNode *N);
222 SDValue XformToShuffleWithZero(SDNode *N);
223 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
225 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
227 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
228 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
229 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
230 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
231 SDValue N3, ISD::CondCode CC,
232 bool NotExtCompare = false);
233 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
234 DebugLoc DL, bool foldBooleans = true);
235 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
237 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
238 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
239 SDValue BuildSDIV(SDNode *N);
240 SDValue BuildUDIV(SDNode *N);
241 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
242 bool DemandHighBits = true);
243 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
244 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
245 SDValue ReduceLoadWidth(SDNode *N);
246 SDValue ReduceLoadOpStoreWidth(SDNode *N);
247 SDValue TransformFPLoadStorePair(SDNode *N);
249 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
251 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
252 /// looking for aliasing nodes and adding them to the Aliases vector.
253 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
254 SmallVector<SDValue, 8> &Aliases);
256 /// isAlias - Return true if there is any possibility that the two addresses
258 bool isAlias(SDValue Ptr1, int64_t Size1,
259 const Value *SrcValue1, int SrcValueOffset1,
260 unsigned SrcValueAlign1,
261 const MDNode *TBAAInfo1,
262 SDValue Ptr2, int64_t Size2,
263 const Value *SrcValue2, int SrcValueOffset2,
264 unsigned SrcValueAlign2,
265 const MDNode *TBAAInfo2) const;
267 /// FindAliasInfo - Extracts the relevant alias information from the memory
268 /// node. Returns true if the operand was a load.
269 bool FindAliasInfo(SDNode *N,
270 SDValue &Ptr, int64_t &Size,
271 const Value *&SrcValue, int &SrcValueOffset,
272 unsigned &SrcValueAlignment,
273 const MDNode *&TBAAInfo) const;
275 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
276 /// looking for a better chain (aliasing node.)
277 SDValue FindBetterChain(SDNode *N, SDValue Chain);
280 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
281 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
282 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
284 /// Run - runs the dag combiner on all nodes in the work list
285 void Run(CombineLevel AtLevel);
287 SelectionDAG &getDAG() const { return DAG; }
289 /// getShiftAmountTy - Returns a type large enough to hold any valid
290 /// shift amount - before type legalization these can be huge.
291 EVT getShiftAmountTy(EVT LHSTy) {
292 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
295 /// isTypeLegal - This method returns true if we are running before type
296 /// legalization or if the specified VT is legal.
297 bool isTypeLegal(const EVT &VT) {
298 if (!LegalTypes) return true;
299 return TLI.isTypeLegal(VT);
306 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
307 /// nodes from the worklist.
308 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
311 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
313 virtual void NodeDeleted(SDNode *N, SDNode *E) {
314 DC.removeFromWorkList(N);
317 virtual void NodeUpdated(SDNode *N) {
323 //===----------------------------------------------------------------------===//
324 // TargetLowering::DAGCombinerInfo implementation
325 //===----------------------------------------------------------------------===//
327 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
328 ((DAGCombiner*)DC)->AddToWorkList(N);
331 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
332 ((DAGCombiner*)DC)->removeFromWorkList(N);
335 SDValue TargetLowering::DAGCombinerInfo::
336 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
337 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
340 SDValue TargetLowering::DAGCombinerInfo::
341 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
342 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
346 SDValue TargetLowering::DAGCombinerInfo::
347 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
348 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
351 void TargetLowering::DAGCombinerInfo::
352 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
353 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
356 //===----------------------------------------------------------------------===//
358 //===----------------------------------------------------------------------===//
360 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
361 /// specified expression for the same cost as the expression itself, or 2 if we
362 /// can compute the negated form more cheaply than the expression itself.
363 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
364 unsigned Depth = 0) {
365 // No compile time optimizations on this type.
366 if (Op.getValueType() == MVT::ppcf128)
369 // fneg is removable even if it has multiple uses.
370 if (Op.getOpcode() == ISD::FNEG) return 2;
372 // Don't allow anything with multiple uses.
373 if (!Op.hasOneUse()) return 0;
375 // Don't recurse exponentially.
376 if (Depth > 6) return 0;
378 switch (Op.getOpcode()) {
379 default: return false;
380 case ISD::ConstantFP:
381 // Don't invert constant FP values after legalize. The negated constant
382 // isn't necessarily legal.
383 return LegalOperations ? 0 : 1;
385 // FIXME: determine better conditions for this xform.
386 if (!UnsafeFPMath) return 0;
388 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
389 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
391 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
392 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
394 // We can't turn -(A-B) into B-A when we honor signed zeros.
395 if (!UnsafeFPMath) return 0;
397 // fold (fneg (fsub A, B)) -> (fsub B, A)
402 if (HonorSignDependentRoundingFPMath()) return 0;
404 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
405 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
408 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
413 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
417 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
418 /// returns the newly negated expression.
419 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
420 bool LegalOperations, unsigned Depth = 0) {
421 // fneg is removable even if it has multiple uses.
422 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
424 // Don't allow anything with multiple uses.
425 assert(Op.hasOneUse() && "Unknown reuse!");
427 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
428 switch (Op.getOpcode()) {
429 default: llvm_unreachable("Unknown code");
430 case ISD::ConstantFP: {
431 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
433 return DAG.getConstantFP(V, Op.getValueType());
436 // FIXME: determine better conditions for this xform.
437 assert(UnsafeFPMath);
439 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
440 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
441 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
442 GetNegatedExpression(Op.getOperand(0), DAG,
443 LegalOperations, Depth+1),
445 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
446 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
447 GetNegatedExpression(Op.getOperand(1), DAG,
448 LegalOperations, Depth+1),
451 // We can't turn -(A-B) into B-A when we honor signed zeros.
452 assert(UnsafeFPMath);
454 // fold (fneg (fsub 0, B)) -> B
455 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
456 if (N0CFP->getValueAPF().isZero())
457 return Op.getOperand(1);
459 // fold (fneg (fsub A, B)) -> (fsub B, A)
460 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
461 Op.getOperand(1), Op.getOperand(0));
465 assert(!HonorSignDependentRoundingFPMath());
467 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
468 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
469 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
470 GetNegatedExpression(Op.getOperand(0), DAG,
471 LegalOperations, Depth+1),
474 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
475 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
477 GetNegatedExpression(Op.getOperand(1), DAG,
478 LegalOperations, Depth+1));
482 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
483 GetNegatedExpression(Op.getOperand(0), DAG,
484 LegalOperations, Depth+1));
486 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
487 GetNegatedExpression(Op.getOperand(0), DAG,
488 LegalOperations, Depth+1),
494 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
495 // that selects between the values 1 and 0, making it equivalent to a setcc.
496 // Also, set the incoming LHS, RHS, and CC references to the appropriate
497 // nodes based on the type of node we are checking. This simplifies life a
498 // bit for the callers.
499 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
501 if (N.getOpcode() == ISD::SETCC) {
502 LHS = N.getOperand(0);
503 RHS = N.getOperand(1);
504 CC = N.getOperand(2);
507 if (N.getOpcode() == ISD::SELECT_CC &&
508 N.getOperand(2).getOpcode() == ISD::Constant &&
509 N.getOperand(3).getOpcode() == ISD::Constant &&
510 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
511 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
512 LHS = N.getOperand(0);
513 RHS = N.getOperand(1);
514 CC = N.getOperand(4);
520 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
521 // one use. If this is true, it allows the users to invert the operation for
522 // free when it is profitable to do so.
523 static bool isOneUseSetCC(SDValue N) {
525 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
530 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
531 SDValue N0, SDValue N1) {
532 EVT VT = N0.getValueType();
533 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
534 if (isa<ConstantSDNode>(N1)) {
535 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
537 DAG.FoldConstantArithmetic(Opc, VT,
538 cast<ConstantSDNode>(N0.getOperand(1)),
539 cast<ConstantSDNode>(N1));
540 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
542 if (N0.hasOneUse()) {
543 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
544 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
545 N0.getOperand(0), N1);
546 AddToWorkList(OpNode.getNode());
547 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
551 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
552 if (isa<ConstantSDNode>(N0)) {
553 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
555 DAG.FoldConstantArithmetic(Opc, VT,
556 cast<ConstantSDNode>(N1.getOperand(1)),
557 cast<ConstantSDNode>(N0));
558 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
560 if (N1.hasOneUse()) {
561 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
562 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
563 N1.getOperand(0), N0);
564 AddToWorkList(OpNode.getNode());
565 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
572 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
574 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
576 DEBUG(dbgs() << "\nReplacing.1 ";
578 dbgs() << "\nWith: ";
579 To[0].getNode()->dump(&DAG);
580 dbgs() << " and " << NumTo-1 << " other values\n";
581 for (unsigned i = 0, e = NumTo; i != e; ++i)
582 assert((!To[i].getNode() ||
583 N->getValueType(i) == To[i].getValueType()) &&
584 "Cannot combine value to value of different type!"));
585 WorkListRemover DeadNodes(*this);
586 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
589 // Push the new nodes and any users onto the worklist
590 for (unsigned i = 0, e = NumTo; i != e; ++i) {
591 if (To[i].getNode()) {
592 AddToWorkList(To[i].getNode());
593 AddUsersToWorkList(To[i].getNode());
598 // Finally, if the node is now dead, remove it from the graph. The node
599 // may not be dead if the replacement process recursively simplified to
600 // something else needing this node.
601 if (N->use_empty()) {
602 // Nodes can be reintroduced into the worklist. Make sure we do not
603 // process a node that has been replaced.
604 removeFromWorkList(N);
606 // Finally, since the node is now dead, remove it from the graph.
609 return SDValue(N, 0);
613 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
614 // Replace all uses. If any nodes become isomorphic to other nodes and
615 // are deleted, make sure to remove them from our worklist.
616 WorkListRemover DeadNodes(*this);
617 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
619 // Push the new node and any (possibly new) users onto the worklist.
620 AddToWorkList(TLO.New.getNode());
621 AddUsersToWorkList(TLO.New.getNode());
623 // Finally, if the node is now dead, remove it from the graph. The node
624 // may not be dead if the replacement process recursively simplified to
625 // something else needing this node.
626 if (TLO.Old.getNode()->use_empty()) {
627 removeFromWorkList(TLO.Old.getNode());
629 // If the operands of this node are only used by the node, they will now
630 // be dead. Make sure to visit them first to delete dead nodes early.
631 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
632 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
633 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
635 DAG.DeleteNode(TLO.Old.getNode());
639 /// SimplifyDemandedBits - Check the specified integer node value to see if
640 /// it can be simplified or if things it uses can be simplified by bit
641 /// propagation. If so, return true.
642 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
643 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
644 APInt KnownZero, KnownOne;
645 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
649 AddToWorkList(Op.getNode());
651 // Replace the old value with the new one.
653 DEBUG(dbgs() << "\nReplacing.2 ";
654 TLO.Old.getNode()->dump(&DAG);
655 dbgs() << "\nWith: ";
656 TLO.New.getNode()->dump(&DAG);
659 CommitTargetLoweringOpt(TLO);
663 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
664 DebugLoc dl = Load->getDebugLoc();
665 EVT VT = Load->getValueType(0);
666 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
668 DEBUG(dbgs() << "\nReplacing.9 ";
670 dbgs() << "\nWith: ";
671 Trunc.getNode()->dump(&DAG);
673 WorkListRemover DeadNodes(*this);
674 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
675 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
677 removeFromWorkList(Load);
678 DAG.DeleteNode(Load);
679 AddToWorkList(Trunc.getNode());
682 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
684 DebugLoc dl = Op.getDebugLoc();
685 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
686 EVT MemVT = LD->getMemoryVT();
687 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
688 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
690 : LD->getExtensionType();
692 return DAG.getExtLoad(ExtType, dl, PVT,
693 LD->getChain(), LD->getBasePtr(),
694 LD->getPointerInfo(),
695 MemVT, LD->isVolatile(),
696 LD->isNonTemporal(), LD->getAlignment());
699 unsigned Opc = Op.getOpcode();
702 case ISD::AssertSext:
703 return DAG.getNode(ISD::AssertSext, dl, PVT,
704 SExtPromoteOperand(Op.getOperand(0), PVT),
706 case ISD::AssertZext:
707 return DAG.getNode(ISD::AssertZext, dl, PVT,
708 ZExtPromoteOperand(Op.getOperand(0), PVT),
710 case ISD::Constant: {
712 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
713 return DAG.getNode(ExtOpc, dl, PVT, Op);
717 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
719 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
722 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
723 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
725 EVT OldVT = Op.getValueType();
726 DebugLoc dl = Op.getDebugLoc();
727 bool Replace = false;
728 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
729 if (NewOp.getNode() == 0)
731 AddToWorkList(NewOp.getNode());
734 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
735 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
736 DAG.getValueType(OldVT));
739 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
740 EVT OldVT = Op.getValueType();
741 DebugLoc dl = Op.getDebugLoc();
742 bool Replace = false;
743 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
744 if (NewOp.getNode() == 0)
746 AddToWorkList(NewOp.getNode());
749 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
750 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
753 /// PromoteIntBinOp - Promote the specified integer binary operation if the
754 /// target indicates it is beneficial. e.g. On x86, it's usually better to
755 /// promote i16 operations to i32 since i16 instructions are longer.
756 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
757 if (!LegalOperations)
760 EVT VT = Op.getValueType();
761 if (VT.isVector() || !VT.isInteger())
764 // If operation type is 'undesirable', e.g. i16 on x86, consider
766 unsigned Opc = Op.getOpcode();
767 if (TLI.isTypeDesirableForOp(Opc, VT))
771 // Consult target whether it is a good idea to promote this operation and
772 // what's the right type to promote it to.
773 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
774 assert(PVT != VT && "Don't know what type to promote to!");
776 bool Replace0 = false;
777 SDValue N0 = Op.getOperand(0);
778 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
779 if (NN0.getNode() == 0)
782 bool Replace1 = false;
783 SDValue N1 = Op.getOperand(1);
788 NN1 = PromoteOperand(N1, PVT, Replace1);
789 if (NN1.getNode() == 0)
793 AddToWorkList(NN0.getNode());
795 AddToWorkList(NN1.getNode());
798 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
800 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
802 DEBUG(dbgs() << "\nPromoting ";
803 Op.getNode()->dump(&DAG));
804 DebugLoc dl = Op.getDebugLoc();
805 return DAG.getNode(ISD::TRUNCATE, dl, VT,
806 DAG.getNode(Opc, dl, PVT, NN0, NN1));
811 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
812 /// target indicates it is beneficial. e.g. On x86, it's usually better to
813 /// promote i16 operations to i32 since i16 instructions are longer.
814 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
815 if (!LegalOperations)
818 EVT VT = Op.getValueType();
819 if (VT.isVector() || !VT.isInteger())
822 // If operation type is 'undesirable', e.g. i16 on x86, consider
824 unsigned Opc = Op.getOpcode();
825 if (TLI.isTypeDesirableForOp(Opc, VT))
829 // Consult target whether it is a good idea to promote this operation and
830 // what's the right type to promote it to.
831 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
832 assert(PVT != VT && "Don't know what type to promote to!");
834 bool Replace = false;
835 SDValue N0 = Op.getOperand(0);
837 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
838 else if (Opc == ISD::SRL)
839 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
841 N0 = PromoteOperand(N0, PVT, Replace);
842 if (N0.getNode() == 0)
845 AddToWorkList(N0.getNode());
847 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
849 DEBUG(dbgs() << "\nPromoting ";
850 Op.getNode()->dump(&DAG));
851 DebugLoc dl = Op.getDebugLoc();
852 return DAG.getNode(ISD::TRUNCATE, dl, VT,
853 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
858 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
859 if (!LegalOperations)
862 EVT VT = Op.getValueType();
863 if (VT.isVector() || !VT.isInteger())
866 // If operation type is 'undesirable', e.g. i16 on x86, consider
868 unsigned Opc = Op.getOpcode();
869 if (TLI.isTypeDesirableForOp(Opc, VT))
873 // Consult target whether it is a good idea to promote this operation and
874 // what's the right type to promote it to.
875 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
876 assert(PVT != VT && "Don't know what type to promote to!");
877 // fold (aext (aext x)) -> (aext x)
878 // fold (aext (zext x)) -> (zext x)
879 // fold (aext (sext x)) -> (sext x)
880 DEBUG(dbgs() << "\nPromoting ";
881 Op.getNode()->dump(&DAG));
882 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
887 bool DAGCombiner::PromoteLoad(SDValue Op) {
888 if (!LegalOperations)
891 EVT VT = Op.getValueType();
892 if (VT.isVector() || !VT.isInteger())
895 // If operation type is 'undesirable', e.g. i16 on x86, consider
897 unsigned Opc = Op.getOpcode();
898 if (TLI.isTypeDesirableForOp(Opc, VT))
902 // Consult target whether it is a good idea to promote this operation and
903 // what's the right type to promote it to.
904 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
905 assert(PVT != VT && "Don't know what type to promote to!");
907 DebugLoc dl = Op.getDebugLoc();
908 SDNode *N = Op.getNode();
909 LoadSDNode *LD = cast<LoadSDNode>(N);
910 EVT MemVT = LD->getMemoryVT();
911 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
912 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
914 : LD->getExtensionType();
915 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
916 LD->getChain(), LD->getBasePtr(),
917 LD->getPointerInfo(),
918 MemVT, LD->isVolatile(),
919 LD->isNonTemporal(), LD->getAlignment());
920 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
922 DEBUG(dbgs() << "\nPromoting ";
925 Result.getNode()->dump(&DAG);
927 WorkListRemover DeadNodes(*this);
928 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
929 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
930 removeFromWorkList(N);
932 AddToWorkList(Result.getNode());
939 //===----------------------------------------------------------------------===//
940 // Main DAG Combiner implementation
941 //===----------------------------------------------------------------------===//
943 void DAGCombiner::Run(CombineLevel AtLevel) {
944 // set the instance variables, so that the various visit routines may use it.
946 LegalOperations = Level >= AfterLegalizeVectorOps;
947 LegalTypes = Level >= AfterLegalizeTypes;
949 // Add all the dag nodes to the worklist.
950 WorkList.reserve(DAG.allnodes_size());
951 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
952 E = DAG.allnodes_end(); I != E; ++I)
953 WorkList.push_back(I);
955 // Create a dummy node (which is not added to allnodes), that adds a reference
956 // to the root node, preventing it from being deleted, and tracking any
957 // changes of the root.
958 HandleSDNode Dummy(DAG.getRoot());
960 // The root of the dag may dangle to deleted nodes until the dag combiner is
961 // done. Set it to null to avoid confusion.
962 DAG.setRoot(SDValue());
964 // while the worklist isn't empty, inspect the node on the end of it and
965 // try and combine it.
966 while (!WorkList.empty()) {
967 SDNode *N = WorkList.back();
970 // If N has no uses, it is dead. Make sure to revisit all N's operands once
971 // N is deleted from the DAG, since they too may now be dead or may have a
972 // reduced number of uses, allowing other xforms.
973 if (N->use_empty() && N != &Dummy) {
974 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
975 AddToWorkList(N->getOperand(i).getNode());
981 SDValue RV = combine(N);
983 if (RV.getNode() == 0)
988 // If we get back the same node we passed in, rather than a new node or
989 // zero, we know that the node must have defined multiple values and
990 // CombineTo was used. Since CombineTo takes care of the worklist
991 // mechanics for us, we have no work to do in this case.
992 if (RV.getNode() == N)
995 assert(N->getOpcode() != ISD::DELETED_NODE &&
996 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
997 "Node was deleted but visit returned new node!");
999 DEBUG(dbgs() << "\nReplacing.3 ";
1001 dbgs() << "\nWith: ";
1002 RV.getNode()->dump(&DAG);
1005 // Transfer debug value.
1006 DAG.TransferDbgValues(SDValue(N, 0), RV);
1007 WorkListRemover DeadNodes(*this);
1008 if (N->getNumValues() == RV.getNode()->getNumValues())
1009 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
1011 assert(N->getValueType(0) == RV.getValueType() &&
1012 N->getNumValues() == 1 && "Type mismatch");
1014 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
1017 // Push the new node and any users onto the worklist
1018 AddToWorkList(RV.getNode());
1019 AddUsersToWorkList(RV.getNode());
1021 // Add any uses of the old node to the worklist in case this node is the
1022 // last one that uses them. They may become dead after this node is
1024 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1025 AddToWorkList(N->getOperand(i).getNode());
1027 // Finally, if the node is now dead, remove it from the graph. The node
1028 // may not be dead if the replacement process recursively simplified to
1029 // something else needing this node.
1030 if (N->use_empty()) {
1031 // Nodes can be reintroduced into the worklist. Make sure we do not
1032 // process a node that has been replaced.
1033 removeFromWorkList(N);
1035 // Finally, since the node is now dead, remove it from the graph.
1040 // If the root changed (e.g. it was a dead load, update the root).
1041 DAG.setRoot(Dummy.getValue());
1044 SDValue DAGCombiner::visit(SDNode *N) {
1045 switch (N->getOpcode()) {
1047 case ISD::TokenFactor: return visitTokenFactor(N);
1048 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1049 case ISD::ADD: return visitADD(N);
1050 case ISD::SUB: return visitSUB(N);
1051 case ISD::ADDC: return visitADDC(N);
1052 case ISD::ADDE: return visitADDE(N);
1053 case ISD::MUL: return visitMUL(N);
1054 case ISD::SDIV: return visitSDIV(N);
1055 case ISD::UDIV: return visitUDIV(N);
1056 case ISD::SREM: return visitSREM(N);
1057 case ISD::UREM: return visitUREM(N);
1058 case ISD::MULHU: return visitMULHU(N);
1059 case ISD::MULHS: return visitMULHS(N);
1060 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1061 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1062 case ISD::SMULO: return visitSMULO(N);
1063 case ISD::UMULO: return visitUMULO(N);
1064 case ISD::SDIVREM: return visitSDIVREM(N);
1065 case ISD::UDIVREM: return visitUDIVREM(N);
1066 case ISD::AND: return visitAND(N);
1067 case ISD::OR: return visitOR(N);
1068 case ISD::XOR: return visitXOR(N);
1069 case ISD::SHL: return visitSHL(N);
1070 case ISD::SRA: return visitSRA(N);
1071 case ISD::SRL: return visitSRL(N);
1072 case ISD::CTLZ: return visitCTLZ(N);
1073 case ISD::CTTZ: return visitCTTZ(N);
1074 case ISD::CTPOP: return visitCTPOP(N);
1075 case ISD::SELECT: return visitSELECT(N);
1076 case ISD::SELECT_CC: return visitSELECT_CC(N);
1077 case ISD::SETCC: return visitSETCC(N);
1078 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1079 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1080 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1081 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1082 case ISD::TRUNCATE: return visitTRUNCATE(N);
1083 case ISD::BITCAST: return visitBITCAST(N);
1084 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1085 case ISD::FADD: return visitFADD(N);
1086 case ISD::FSUB: return visitFSUB(N);
1087 case ISD::FMUL: return visitFMUL(N);
1088 case ISD::FDIV: return visitFDIV(N);
1089 case ISD::FREM: return visitFREM(N);
1090 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1091 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1092 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1093 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1094 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1095 case ISD::FP_ROUND: return visitFP_ROUND(N);
1096 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1097 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1098 case ISD::FNEG: return visitFNEG(N);
1099 case ISD::FABS: return visitFABS(N);
1100 case ISD::BRCOND: return visitBRCOND(N);
1101 case ISD::BR_CC: return visitBR_CC(N);
1102 case ISD::LOAD: return visitLOAD(N);
1103 case ISD::STORE: return visitSTORE(N);
1104 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1105 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1106 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1107 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1108 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1109 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1110 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1115 SDValue DAGCombiner::combine(SDNode *N) {
1116 SDValue RV = visit(N);
1118 // If nothing happened, try a target-specific DAG combine.
1119 if (RV.getNode() == 0) {
1120 assert(N->getOpcode() != ISD::DELETED_NODE &&
1121 "Node was deleted but visit returned NULL!");
1123 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1124 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1126 // Expose the DAG combiner to the target combiner impls.
1127 TargetLowering::DAGCombinerInfo
1128 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1130 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1134 // If nothing happened still, try promoting the operation.
1135 if (RV.getNode() == 0) {
1136 switch (N->getOpcode()) {
1144 RV = PromoteIntBinOp(SDValue(N, 0));
1149 RV = PromoteIntShiftOp(SDValue(N, 0));
1151 case ISD::SIGN_EXTEND:
1152 case ISD::ZERO_EXTEND:
1153 case ISD::ANY_EXTEND:
1154 RV = PromoteExtend(SDValue(N, 0));
1157 if (PromoteLoad(SDValue(N, 0)))
1163 // If N is a commutative binary node, try commuting it to enable more
1165 if (RV.getNode() == 0 &&
1166 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1167 N->getNumValues() == 1) {
1168 SDValue N0 = N->getOperand(0);
1169 SDValue N1 = N->getOperand(1);
1171 // Constant operands are canonicalized to RHS.
1172 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1173 SDValue Ops[] = { N1, N0 };
1174 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1177 return SDValue(CSENode, 0);
1184 /// getInputChainForNode - Given a node, return its input chain if it has one,
1185 /// otherwise return a null sd operand.
1186 static SDValue getInputChainForNode(SDNode *N) {
1187 if (unsigned NumOps = N->getNumOperands()) {
1188 if (N->getOperand(0).getValueType() == MVT::Other)
1189 return N->getOperand(0);
1190 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1191 return N->getOperand(NumOps-1);
1192 for (unsigned i = 1; i < NumOps-1; ++i)
1193 if (N->getOperand(i).getValueType() == MVT::Other)
1194 return N->getOperand(i);
1199 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1200 // If N has two operands, where one has an input chain equal to the other,
1201 // the 'other' chain is redundant.
1202 if (N->getNumOperands() == 2) {
1203 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1204 return N->getOperand(0);
1205 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1206 return N->getOperand(1);
1209 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1210 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1211 SmallPtrSet<SDNode*, 16> SeenOps;
1212 bool Changed = false; // If we should replace this token factor.
1214 // Start out with this token factor.
1217 // Iterate through token factors. The TFs grows when new token factors are
1219 for (unsigned i = 0; i < TFs.size(); ++i) {
1220 SDNode *TF = TFs[i];
1222 // Check each of the operands.
1223 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1224 SDValue Op = TF->getOperand(i);
1226 switch (Op.getOpcode()) {
1227 case ISD::EntryToken:
1228 // Entry tokens don't need to be added to the list. They are
1233 case ISD::TokenFactor:
1234 if (Op.hasOneUse() &&
1235 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1236 // Queue up for processing.
1237 TFs.push_back(Op.getNode());
1238 // Clean up in case the token factor is removed.
1239 AddToWorkList(Op.getNode());
1246 // Only add if it isn't already in the list.
1247 if (SeenOps.insert(Op.getNode()))
1258 // If we've change things around then replace token factor.
1261 // The entry token is the only possible outcome.
1262 Result = DAG.getEntryNode();
1264 // New and improved token factor.
1265 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1266 MVT::Other, &Ops[0], Ops.size());
1269 // Don't add users to work list.
1270 return CombineTo(N, Result, false);
1276 /// MERGE_VALUES can always be eliminated.
1277 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1278 WorkListRemover DeadNodes(*this);
1279 // Replacing results may cause a different MERGE_VALUES to suddenly
1280 // be CSE'd with N, and carry its uses with it. Iterate until no
1281 // uses remain, to ensure that the node can be safely deleted.
1283 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1284 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1286 } while (!N->use_empty());
1287 removeFromWorkList(N);
1289 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1293 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1294 SelectionDAG &DAG) {
1295 EVT VT = N0.getValueType();
1296 SDValue N00 = N0.getOperand(0);
1297 SDValue N01 = N0.getOperand(1);
1298 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1300 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1301 isa<ConstantSDNode>(N00.getOperand(1))) {
1302 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1303 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1304 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1305 N00.getOperand(0), N01),
1306 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1307 N00.getOperand(1), N01));
1308 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1314 SDValue DAGCombiner::visitADD(SDNode *N) {
1315 SDValue N0 = N->getOperand(0);
1316 SDValue N1 = N->getOperand(1);
1317 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1318 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1319 EVT VT = N0.getValueType();
1322 if (VT.isVector()) {
1323 SDValue FoldedVOp = SimplifyVBinOp(N);
1324 if (FoldedVOp.getNode()) return FoldedVOp;
1327 // fold (add x, undef) -> undef
1328 if (N0.getOpcode() == ISD::UNDEF)
1330 if (N1.getOpcode() == ISD::UNDEF)
1332 // fold (add c1, c2) -> c1+c2
1334 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1335 // canonicalize constant to RHS
1337 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1338 // fold (add x, 0) -> x
1339 if (N1C && N1C->isNullValue())
1341 // fold (add Sym, c) -> Sym+c
1342 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1343 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1344 GA->getOpcode() == ISD::GlobalAddress)
1345 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1347 (uint64_t)N1C->getSExtValue());
1348 // fold ((c1-A)+c2) -> (c1+c2)-A
1349 if (N1C && N0.getOpcode() == ISD::SUB)
1350 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1351 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1352 DAG.getConstant(N1C->getAPIntValue()+
1353 N0C->getAPIntValue(), VT),
1356 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1357 if (RADD.getNode() != 0)
1359 // fold ((0-A) + B) -> B-A
1360 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1361 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1362 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1363 // fold (A + (0-B)) -> A-B
1364 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1365 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1366 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1367 // fold (A+(B-A)) -> B
1368 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1369 return N1.getOperand(0);
1370 // fold ((B-A)+A) -> B
1371 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1372 return N0.getOperand(0);
1373 // fold (A+(B-(A+C))) to (B-C)
1374 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1375 N0 == N1.getOperand(1).getOperand(0))
1376 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1377 N1.getOperand(1).getOperand(1));
1378 // fold (A+(B-(C+A))) to (B-C)
1379 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1380 N0 == N1.getOperand(1).getOperand(1))
1381 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1382 N1.getOperand(1).getOperand(0));
1383 // fold (A+((B-A)+or-C)) to (B+or-C)
1384 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1385 N1.getOperand(0).getOpcode() == ISD::SUB &&
1386 N0 == N1.getOperand(0).getOperand(1))
1387 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1388 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1390 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1391 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1392 SDValue N00 = N0.getOperand(0);
1393 SDValue N01 = N0.getOperand(1);
1394 SDValue N10 = N1.getOperand(0);
1395 SDValue N11 = N1.getOperand(1);
1397 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1398 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1399 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1400 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1403 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1404 return SDValue(N, 0);
1406 // fold (a+b) -> (a|b) iff a and b share no bits.
1407 if (VT.isInteger() && !VT.isVector()) {
1408 APInt LHSZero, LHSOne;
1409 APInt RHSZero, RHSOne;
1410 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1411 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1413 if (LHSZero.getBoolValue()) {
1414 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1416 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1417 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1418 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1419 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1420 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1424 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1425 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1426 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1427 if (Result.getNode()) return Result;
1429 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1430 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1431 if (Result.getNode()) return Result;
1434 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1435 if (N1.getOpcode() == ISD::SHL &&
1436 N1.getOperand(0).getOpcode() == ISD::SUB)
1437 if (ConstantSDNode *C =
1438 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1439 if (C->getAPIntValue() == 0)
1440 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1441 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1442 N1.getOperand(0).getOperand(1),
1444 if (N0.getOpcode() == ISD::SHL &&
1445 N0.getOperand(0).getOpcode() == ISD::SUB)
1446 if (ConstantSDNode *C =
1447 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1448 if (C->getAPIntValue() == 0)
1449 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1450 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1451 N0.getOperand(0).getOperand(1),
1454 if (N1.getOpcode() == ISD::AND) {
1455 SDValue AndOp0 = N1.getOperand(0);
1456 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1457 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1458 unsigned DestBits = VT.getScalarType().getSizeInBits();
1460 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1461 // and similar xforms where the inner op is either ~0 or 0.
1462 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1463 DebugLoc DL = N->getDebugLoc();
1464 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1468 // add (sext i1), X -> sub X, (zext i1)
1469 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1470 N0.getOperand(0).getValueType() == MVT::i1 &&
1471 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1472 DebugLoc DL = N->getDebugLoc();
1473 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1474 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1480 SDValue DAGCombiner::visitADDC(SDNode *N) {
1481 SDValue N0 = N->getOperand(0);
1482 SDValue N1 = N->getOperand(1);
1483 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1484 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1485 EVT VT = N0.getValueType();
1487 // If the flag result is dead, turn this into an ADD.
1488 if (N->hasNUsesOfValue(0, 1))
1489 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1490 DAG.getNode(ISD::CARRY_FALSE,
1491 N->getDebugLoc(), MVT::Glue));
1493 // canonicalize constant to RHS.
1495 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1497 // fold (addc x, 0) -> x + no carry out
1498 if (N1C && N1C->isNullValue())
1499 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1500 N->getDebugLoc(), MVT::Glue));
1502 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1503 APInt LHSZero, LHSOne;
1504 APInt RHSZero, RHSOne;
1505 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1506 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1508 if (LHSZero.getBoolValue()) {
1509 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1511 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1512 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1513 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1514 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1515 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1516 DAG.getNode(ISD::CARRY_FALSE,
1517 N->getDebugLoc(), MVT::Glue));
1523 SDValue DAGCombiner::visitADDE(SDNode *N) {
1524 SDValue N0 = N->getOperand(0);
1525 SDValue N1 = N->getOperand(1);
1526 SDValue CarryIn = N->getOperand(2);
1527 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1528 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1530 // canonicalize constant to RHS
1532 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1535 // fold (adde x, y, false) -> (addc x, y)
1536 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1537 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1542 // Since it may not be valid to emit a fold to zero for vector initializers
1543 // check if we can before folding.
1544 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1545 SelectionDAG &DAG, bool LegalOperations) {
1546 if (!VT.isVector()) {
1547 return DAG.getConstant(0, VT);
1549 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1550 // Produce a vector of zeros.
1551 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1552 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1553 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1554 &Ops[0], Ops.size());
1559 SDValue DAGCombiner::visitSUB(SDNode *N) {
1560 SDValue N0 = N->getOperand(0);
1561 SDValue N1 = N->getOperand(1);
1562 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1563 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1564 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1565 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1566 EVT VT = N0.getValueType();
1569 if (VT.isVector()) {
1570 SDValue FoldedVOp = SimplifyVBinOp(N);
1571 if (FoldedVOp.getNode()) return FoldedVOp;
1574 // fold (sub x, x) -> 0
1575 // FIXME: Refactor this and xor and other similar operations together.
1577 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1578 // fold (sub c1, c2) -> c1-c2
1580 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1581 // fold (sub x, c) -> (add x, -c)
1583 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1584 DAG.getConstant(-N1C->getAPIntValue(), VT));
1585 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1586 if (N0C && N0C->isAllOnesValue())
1587 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1588 // fold A-(A-B) -> B
1589 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1590 return N1.getOperand(1);
1591 // fold (A+B)-A -> B
1592 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1593 return N0.getOperand(1);
1594 // fold (A+B)-B -> A
1595 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1596 return N0.getOperand(0);
1597 // fold C2-(A+C1) -> (C2-C1)-A
1598 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1599 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1600 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1603 // fold ((A+(B+or-C))-B) -> A+or-C
1604 if (N0.getOpcode() == ISD::ADD &&
1605 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1606 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1607 N0.getOperand(1).getOperand(0) == N1)
1608 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1609 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1610 // fold ((A+(C+B))-B) -> A+C
1611 if (N0.getOpcode() == ISD::ADD &&
1612 N0.getOperand(1).getOpcode() == ISD::ADD &&
1613 N0.getOperand(1).getOperand(1) == N1)
1614 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1615 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1616 // fold ((A-(B-C))-C) -> A-B
1617 if (N0.getOpcode() == ISD::SUB &&
1618 N0.getOperand(1).getOpcode() == ISD::SUB &&
1619 N0.getOperand(1).getOperand(1) == N1)
1620 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1621 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1623 // If either operand of a sub is undef, the result is undef
1624 if (N0.getOpcode() == ISD::UNDEF)
1626 if (N1.getOpcode() == ISD::UNDEF)
1629 // If the relocation model supports it, consider symbol offsets.
1630 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1631 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1632 // fold (sub Sym, c) -> Sym-c
1633 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1634 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1636 (uint64_t)N1C->getSExtValue());
1637 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1638 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1639 if (GA->getGlobal() == GB->getGlobal())
1640 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1647 SDValue DAGCombiner::visitMUL(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1652 EVT VT = N0.getValueType();
1655 if (VT.isVector()) {
1656 SDValue FoldedVOp = SimplifyVBinOp(N);
1657 if (FoldedVOp.getNode()) return FoldedVOp;
1660 // fold (mul x, undef) -> 0
1661 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1662 return DAG.getConstant(0, VT);
1663 // fold (mul c1, c2) -> c1*c2
1665 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1666 // canonicalize constant to RHS
1668 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1669 // fold (mul x, 0) -> 0
1670 if (N1C && N1C->isNullValue())
1672 // fold (mul x, -1) -> 0-x
1673 if (N1C && N1C->isAllOnesValue())
1674 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1675 DAG.getConstant(0, VT), N0);
1676 // fold (mul x, (1 << c)) -> x << c
1677 if (N1C && N1C->getAPIntValue().isPowerOf2())
1678 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1679 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1680 getShiftAmountTy(N0.getValueType())));
1681 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1682 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1683 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1684 // FIXME: If the input is something that is easily negated (e.g. a
1685 // single-use add), we should put the negate there.
1686 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1687 DAG.getConstant(0, VT),
1688 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1689 DAG.getConstant(Log2Val,
1690 getShiftAmountTy(N0.getValueType()))));
1692 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1693 if (N1C && N0.getOpcode() == ISD::SHL &&
1694 isa<ConstantSDNode>(N0.getOperand(1))) {
1695 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1696 N1, N0.getOperand(1));
1697 AddToWorkList(C3.getNode());
1698 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1699 N0.getOperand(0), C3);
1702 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1705 SDValue Sh(0,0), Y(0,0);
1706 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1707 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1708 N0.getNode()->hasOneUse()) {
1710 } else if (N1.getOpcode() == ISD::SHL &&
1711 isa<ConstantSDNode>(N1.getOperand(1)) &&
1712 N1.getNode()->hasOneUse()) {
1717 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1718 Sh.getOperand(0), Y);
1719 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1720 Mul, Sh.getOperand(1));
1724 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1725 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1726 isa<ConstantSDNode>(N0.getOperand(1)))
1727 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1728 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1729 N0.getOperand(0), N1),
1730 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1731 N0.getOperand(1), N1));
1734 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1735 if (RMUL.getNode() != 0)
1741 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1742 SDValue N0 = N->getOperand(0);
1743 SDValue N1 = N->getOperand(1);
1744 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1745 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1746 EVT VT = N->getValueType(0);
1749 if (VT.isVector()) {
1750 SDValue FoldedVOp = SimplifyVBinOp(N);
1751 if (FoldedVOp.getNode()) return FoldedVOp;
1754 // fold (sdiv c1, c2) -> c1/c2
1755 if (N0C && N1C && !N1C->isNullValue())
1756 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1757 // fold (sdiv X, 1) -> X
1758 if (N1C && N1C->getAPIntValue() == 1LL)
1760 // fold (sdiv X, -1) -> 0-X
1761 if (N1C && N1C->isAllOnesValue())
1762 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1763 DAG.getConstant(0, VT), N0);
1764 // If we know the sign bits of both operands are zero, strength reduce to a
1765 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1766 if (!VT.isVector()) {
1767 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1768 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1771 // fold (sdiv X, pow2) -> simple ops after legalize
1772 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1773 (N1C->getAPIntValue().isPowerOf2() ||
1774 (-N1C->getAPIntValue()).isPowerOf2())) {
1775 // If dividing by powers of two is cheap, then don't perform the following
1777 if (TLI.isPow2DivCheap())
1780 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1782 // Splat the sign bit into the register
1783 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1784 DAG.getConstant(VT.getSizeInBits()-1,
1785 getShiftAmountTy(N0.getValueType())));
1786 AddToWorkList(SGN.getNode());
1788 // Add (N0 < 0) ? abs2 - 1 : 0;
1789 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1790 DAG.getConstant(VT.getSizeInBits() - lg2,
1791 getShiftAmountTy(SGN.getValueType())));
1792 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1793 AddToWorkList(SRL.getNode());
1794 AddToWorkList(ADD.getNode()); // Divide by pow2
1795 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1796 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1798 // If we're dividing by a positive value, we're done. Otherwise, we must
1799 // negate the result.
1800 if (N1C->getAPIntValue().isNonNegative())
1803 AddToWorkList(SRA.getNode());
1804 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1805 DAG.getConstant(0, VT), SRA);
1808 // if integer divide is expensive and we satisfy the requirements, emit an
1809 // alternate sequence.
1810 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1811 SDValue Op = BuildSDIV(N);
1812 if (Op.getNode()) return Op;
1816 if (N0.getOpcode() == ISD::UNDEF)
1817 return DAG.getConstant(0, VT);
1818 // X / undef -> undef
1819 if (N1.getOpcode() == ISD::UNDEF)
1825 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1826 SDValue N0 = N->getOperand(0);
1827 SDValue N1 = N->getOperand(1);
1828 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1829 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1830 EVT VT = N->getValueType(0);
1833 if (VT.isVector()) {
1834 SDValue FoldedVOp = SimplifyVBinOp(N);
1835 if (FoldedVOp.getNode()) return FoldedVOp;
1838 // fold (udiv c1, c2) -> c1/c2
1839 if (N0C && N1C && !N1C->isNullValue())
1840 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1841 // fold (udiv x, (1 << c)) -> x >>u c
1842 if (N1C && N1C->getAPIntValue().isPowerOf2())
1843 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1844 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1845 getShiftAmountTy(N0.getValueType())));
1846 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1847 if (N1.getOpcode() == ISD::SHL) {
1848 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1849 if (SHC->getAPIntValue().isPowerOf2()) {
1850 EVT ADDVT = N1.getOperand(1).getValueType();
1851 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1853 DAG.getConstant(SHC->getAPIntValue()
1856 AddToWorkList(Add.getNode());
1857 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1861 // fold (udiv x, c) -> alternate
1862 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1863 SDValue Op = BuildUDIV(N);
1864 if (Op.getNode()) return Op;
1868 if (N0.getOpcode() == ISD::UNDEF)
1869 return DAG.getConstant(0, VT);
1870 // X / undef -> undef
1871 if (N1.getOpcode() == ISD::UNDEF)
1877 SDValue DAGCombiner::visitSREM(SDNode *N) {
1878 SDValue N0 = N->getOperand(0);
1879 SDValue N1 = N->getOperand(1);
1880 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1881 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1882 EVT VT = N->getValueType(0);
1884 // fold (srem c1, c2) -> c1%c2
1885 if (N0C && N1C && !N1C->isNullValue())
1886 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1887 // If we know the sign bits of both operands are zero, strength reduce to a
1888 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1889 if (!VT.isVector()) {
1890 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1891 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1894 // If X/C can be simplified by the division-by-constant logic, lower
1895 // X%C to the equivalent of X-X/C*C.
1896 if (N1C && !N1C->isNullValue()) {
1897 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1898 AddToWorkList(Div.getNode());
1899 SDValue OptimizedDiv = combine(Div.getNode());
1900 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1901 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1903 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1904 AddToWorkList(Mul.getNode());
1910 if (N0.getOpcode() == ISD::UNDEF)
1911 return DAG.getConstant(0, VT);
1912 // X % undef -> undef
1913 if (N1.getOpcode() == ISD::UNDEF)
1919 SDValue DAGCombiner::visitUREM(SDNode *N) {
1920 SDValue N0 = N->getOperand(0);
1921 SDValue N1 = N->getOperand(1);
1922 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1923 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1924 EVT VT = N->getValueType(0);
1926 // fold (urem c1, c2) -> c1%c2
1927 if (N0C && N1C && !N1C->isNullValue())
1928 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1929 // fold (urem x, pow2) -> (and x, pow2-1)
1930 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1931 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1932 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1933 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1934 if (N1.getOpcode() == ISD::SHL) {
1935 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1936 if (SHC->getAPIntValue().isPowerOf2()) {
1938 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1939 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1941 AddToWorkList(Add.getNode());
1942 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1947 // If X/C can be simplified by the division-by-constant logic, lower
1948 // X%C to the equivalent of X-X/C*C.
1949 if (N1C && !N1C->isNullValue()) {
1950 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1951 AddToWorkList(Div.getNode());
1952 SDValue OptimizedDiv = combine(Div.getNode());
1953 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1954 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1956 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1957 AddToWorkList(Mul.getNode());
1963 if (N0.getOpcode() == ISD::UNDEF)
1964 return DAG.getConstant(0, VT);
1965 // X % undef -> undef
1966 if (N1.getOpcode() == ISD::UNDEF)
1972 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
1975 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1976 EVT VT = N->getValueType(0);
1977 DebugLoc DL = N->getDebugLoc();
1979 // fold (mulhs x, 0) -> 0
1980 if (N1C && N1C->isNullValue())
1982 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1983 if (N1C && N1C->getAPIntValue() == 1)
1984 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1985 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1986 getShiftAmountTy(N0.getValueType())));
1987 // fold (mulhs x, undef) -> 0
1988 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1989 return DAG.getConstant(0, VT);
1991 // If the type twice as wide is legal, transform the mulhs to a wider multiply
1993 if (VT.isSimple() && !VT.isVector()) {
1994 MVT Simple = VT.getSimpleVT();
1995 unsigned SimpleSize = Simple.getSizeInBits();
1996 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1997 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1998 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
1999 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2000 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2001 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2002 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2003 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2010 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2011 SDValue N0 = N->getOperand(0);
2012 SDValue N1 = N->getOperand(1);
2013 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2014 EVT VT = N->getValueType(0);
2015 DebugLoc DL = N->getDebugLoc();
2017 // fold (mulhu x, 0) -> 0
2018 if (N1C && N1C->isNullValue())
2020 // fold (mulhu x, 1) -> 0
2021 if (N1C && N1C->getAPIntValue() == 1)
2022 return DAG.getConstant(0, N0.getValueType());
2023 // fold (mulhu x, undef) -> 0
2024 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2025 return DAG.getConstant(0, VT);
2027 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2029 if (VT.isSimple() && !VT.isVector()) {
2030 MVT Simple = VT.getSimpleVT();
2031 unsigned SimpleSize = Simple.getSizeInBits();
2032 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2033 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2034 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2035 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2036 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2037 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2038 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2039 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2046 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2047 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2048 /// that are being performed. Return true if a simplification was made.
2050 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2052 // If the high half is not needed, just compute the low half.
2053 bool HiExists = N->hasAnyUseOfValue(1);
2055 (!LegalOperations ||
2056 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2057 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2058 N->op_begin(), N->getNumOperands());
2059 return CombineTo(N, Res, Res);
2062 // If the low half is not needed, just compute the high half.
2063 bool LoExists = N->hasAnyUseOfValue(0);
2065 (!LegalOperations ||
2066 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2067 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2068 N->op_begin(), N->getNumOperands());
2069 return CombineTo(N, Res, Res);
2072 // If both halves are used, return as it is.
2073 if (LoExists && HiExists)
2076 // If the two computed results can be simplified separately, separate them.
2078 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2079 N->op_begin(), N->getNumOperands());
2080 AddToWorkList(Lo.getNode());
2081 SDValue LoOpt = combine(Lo.getNode());
2082 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2083 (!LegalOperations ||
2084 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2085 return CombineTo(N, LoOpt, LoOpt);
2089 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2090 N->op_begin(), N->getNumOperands());
2091 AddToWorkList(Hi.getNode());
2092 SDValue HiOpt = combine(Hi.getNode());
2093 if (HiOpt.getNode() && HiOpt != Hi &&
2094 (!LegalOperations ||
2095 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2096 return CombineTo(N, HiOpt, HiOpt);
2102 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2103 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2104 if (Res.getNode()) return Res;
2106 EVT VT = N->getValueType(0);
2107 DebugLoc DL = N->getDebugLoc();
2109 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2111 if (VT.isSimple() && !VT.isVector()) {
2112 MVT Simple = VT.getSimpleVT();
2113 unsigned SimpleSize = Simple.getSizeInBits();
2114 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2115 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2116 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2117 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2118 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2119 // Compute the high part as N1.
2120 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2121 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2122 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2123 // Compute the low part as N0.
2124 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2125 return CombineTo(N, Lo, Hi);
2132 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2133 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2134 if (Res.getNode()) return Res;
2136 EVT VT = N->getValueType(0);
2137 DebugLoc DL = N->getDebugLoc();
2139 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2141 if (VT.isSimple() && !VT.isVector()) {
2142 MVT Simple = VT.getSimpleVT();
2143 unsigned SimpleSize = Simple.getSizeInBits();
2144 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2145 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2146 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2147 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2148 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2149 // Compute the high part as N1.
2150 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2151 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2152 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2153 // Compute the low part as N0.
2154 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2155 return CombineTo(N, Lo, Hi);
2162 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2163 // (smulo x, 2) -> (saddo x, x)
2164 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2165 if (C2->getAPIntValue() == 2)
2166 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2167 N->getOperand(0), N->getOperand(0));
2172 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2173 // (umulo x, 2) -> (uaddo x, x)
2174 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2175 if (C2->getAPIntValue() == 2)
2176 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2177 N->getOperand(0), N->getOperand(0));
2182 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2183 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2184 if (Res.getNode()) return Res;
2189 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2190 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2191 if (Res.getNode()) return Res;
2196 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2197 /// two operands of the same opcode, try to simplify it.
2198 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2199 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2200 EVT VT = N0.getValueType();
2201 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2203 // Bail early if none of these transforms apply.
2204 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2206 // For each of OP in AND/OR/XOR:
2207 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2208 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2209 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2210 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2212 // do not sink logical op inside of a vector extend, since it may combine
2214 EVT Op0VT = N0.getOperand(0).getValueType();
2215 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2216 N0.getOpcode() == ISD::SIGN_EXTEND ||
2217 // Avoid infinite looping with PromoteIntBinOp.
2218 (N0.getOpcode() == ISD::ANY_EXTEND &&
2219 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2220 (N0.getOpcode() == ISD::TRUNCATE &&
2221 (!TLI.isZExtFree(VT, Op0VT) ||
2222 !TLI.isTruncateFree(Op0VT, VT)) &&
2223 TLI.isTypeLegal(Op0VT))) &&
2225 Op0VT == N1.getOperand(0).getValueType() &&
2226 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2227 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2228 N0.getOperand(0).getValueType(),
2229 N0.getOperand(0), N1.getOperand(0));
2230 AddToWorkList(ORNode.getNode());
2231 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2234 // For each of OP in SHL/SRL/SRA/AND...
2235 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2236 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2237 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2238 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2239 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2240 N0.getOperand(1) == N1.getOperand(1)) {
2241 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2242 N0.getOperand(0).getValueType(),
2243 N0.getOperand(0), N1.getOperand(0));
2244 AddToWorkList(ORNode.getNode());
2245 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2246 ORNode, N0.getOperand(1));
2252 SDValue DAGCombiner::visitAND(SDNode *N) {
2253 SDValue N0 = N->getOperand(0);
2254 SDValue N1 = N->getOperand(1);
2255 SDValue LL, LR, RL, RR, CC0, CC1;
2256 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2258 EVT VT = N1.getValueType();
2259 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2262 if (VT.isVector()) {
2263 SDValue FoldedVOp = SimplifyVBinOp(N);
2264 if (FoldedVOp.getNode()) return FoldedVOp;
2267 // fold (and x, undef) -> 0
2268 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2269 return DAG.getConstant(0, VT);
2270 // fold (and c1, c2) -> c1&c2
2272 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2273 // canonicalize constant to RHS
2275 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2276 // fold (and x, -1) -> x
2277 if (N1C && N1C->isAllOnesValue())
2279 // if (and x, c) is known to be zero, return 0
2280 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2281 APInt::getAllOnesValue(BitWidth)))
2282 return DAG.getConstant(0, VT);
2284 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2285 if (RAND.getNode() != 0)
2287 // fold (and (or x, C), D) -> D if (C & D) == D
2288 if (N1C && N0.getOpcode() == ISD::OR)
2289 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2290 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2292 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2293 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2294 SDValue N0Op0 = N0.getOperand(0);
2295 APInt Mask = ~N1C->getAPIntValue();
2296 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2297 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2298 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2299 N0.getValueType(), N0Op0);
2301 // Replace uses of the AND with uses of the Zero extend node.
2304 // We actually want to replace all uses of the any_extend with the
2305 // zero_extend, to avoid duplicating things. This will later cause this
2306 // AND to be folded.
2307 CombineTo(N0.getNode(), Zext);
2308 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2311 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2312 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2313 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2314 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2316 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2317 LL.getValueType().isInteger()) {
2318 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2319 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2320 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2321 LR.getValueType(), LL, RL);
2322 AddToWorkList(ORNode.getNode());
2323 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2325 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2326 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2327 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2328 LR.getValueType(), LL, RL);
2329 AddToWorkList(ANDNode.getNode());
2330 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2332 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2333 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2334 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2335 LR.getValueType(), LL, RL);
2336 AddToWorkList(ORNode.getNode());
2337 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2340 // canonicalize equivalent to ll == rl
2341 if (LL == RR && LR == RL) {
2342 Op1 = ISD::getSetCCSwappedOperands(Op1);
2345 if (LL == RL && LR == RR) {
2346 bool isInteger = LL.getValueType().isInteger();
2347 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2348 if (Result != ISD::SETCC_INVALID &&
2349 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2350 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2355 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2356 if (N0.getOpcode() == N1.getOpcode()) {
2357 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2358 if (Tmp.getNode()) return Tmp;
2361 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2362 // fold (and (sra)) -> (and (srl)) when possible.
2363 if (!VT.isVector() &&
2364 SimplifyDemandedBits(SDValue(N, 0)))
2365 return SDValue(N, 0);
2367 // fold (zext_inreg (extload x)) -> (zextload x)
2368 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2369 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2370 EVT MemVT = LN0->getMemoryVT();
2371 // If we zero all the possible extended bits, then we can turn this into
2372 // a zextload if we are running before legalize or the operation is legal.
2373 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2374 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2375 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2376 ((!LegalOperations && !LN0->isVolatile()) ||
2377 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2378 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2379 LN0->getChain(), LN0->getBasePtr(),
2380 LN0->getPointerInfo(), MemVT,
2381 LN0->isVolatile(), LN0->isNonTemporal(),
2382 LN0->getAlignment());
2384 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2385 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2388 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2389 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2391 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2392 EVT MemVT = LN0->getMemoryVT();
2393 // If we zero all the possible extended bits, then we can turn this into
2394 // a zextload if we are running before legalize or the operation is legal.
2395 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2396 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2397 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2398 ((!LegalOperations && !LN0->isVolatile()) ||
2399 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2400 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2402 LN0->getBasePtr(), LN0->getPointerInfo(),
2404 LN0->isVolatile(), LN0->isNonTemporal(),
2405 LN0->getAlignment());
2407 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2408 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2412 // fold (and (load x), 255) -> (zextload x, i8)
2413 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2414 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2415 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2416 (N0.getOpcode() == ISD::ANY_EXTEND &&
2417 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2418 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2419 LoadSDNode *LN0 = HasAnyExt
2420 ? cast<LoadSDNode>(N0.getOperand(0))
2421 : cast<LoadSDNode>(N0);
2422 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2423 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2424 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2425 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2426 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2427 EVT LoadedVT = LN0->getMemoryVT();
2429 if (ExtVT == LoadedVT &&
2430 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2431 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2434 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2435 LN0->getChain(), LN0->getBasePtr(),
2436 LN0->getPointerInfo(),
2437 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2438 LN0->getAlignment());
2440 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2441 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2444 // Do not change the width of a volatile load.
2445 // Do not generate loads of non-round integer types since these can
2446 // be expensive (and would be wrong if the type is not byte sized).
2447 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2448 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2449 EVT PtrType = LN0->getOperand(1).getValueType();
2451 unsigned Alignment = LN0->getAlignment();
2452 SDValue NewPtr = LN0->getBasePtr();
2454 // For big endian targets, we need to add an offset to the pointer
2455 // to load the correct bytes. For little endian systems, we merely
2456 // need to read fewer bytes from the same pointer.
2457 if (TLI.isBigEndian()) {
2458 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2459 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2460 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2461 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2462 NewPtr, DAG.getConstant(PtrOff, PtrType));
2463 Alignment = MinAlign(Alignment, PtrOff);
2466 AddToWorkList(NewPtr.getNode());
2468 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2470 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2471 LN0->getChain(), NewPtr,
2472 LN0->getPointerInfo(),
2473 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2476 CombineTo(LN0, Load, Load.getValue(1));
2477 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2486 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2488 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2489 bool DemandHighBits) {
2490 if (!LegalOperations)
2493 EVT VT = N->getValueType(0);
2494 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2496 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2499 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2500 bool LookPassAnd0 = false;
2501 bool LookPassAnd1 = false;
2502 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2504 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2506 if (N0.getOpcode() == ISD::AND) {
2507 if (!N0.getNode()->hasOneUse())
2509 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2510 if (!N01C || N01C->getZExtValue() != 0xFF00)
2512 N0 = N0.getOperand(0);
2513 LookPassAnd0 = true;
2516 if (N1.getOpcode() == ISD::AND) {
2517 if (!N1.getNode()->hasOneUse())
2519 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2520 if (!N11C || N11C->getZExtValue() != 0xFF)
2522 N1 = N1.getOperand(0);
2523 LookPassAnd1 = true;
2526 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2528 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2530 if (!N0.getNode()->hasOneUse() ||
2531 !N1.getNode()->hasOneUse())
2534 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2535 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2538 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2541 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2542 SDValue N00 = N0->getOperand(0);
2543 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2544 if (!N00.getNode()->hasOneUse())
2546 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2547 if (!N001C || N001C->getZExtValue() != 0xFF)
2549 N00 = N00.getOperand(0);
2550 LookPassAnd0 = true;
2553 SDValue N10 = N1->getOperand(0);
2554 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2555 if (!N10.getNode()->hasOneUse())
2557 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2558 if (!N101C || N101C->getZExtValue() != 0xFF00)
2560 N10 = N10.getOperand(0);
2561 LookPassAnd1 = true;
2567 // Make sure everything beyond the low halfword is zero since the SRL 16
2568 // will clear the top bits.
2569 unsigned OpSizeInBits = VT.getSizeInBits();
2570 if (DemandHighBits && OpSizeInBits > 16 &&
2571 (!LookPassAnd0 || !LookPassAnd1) &&
2572 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2575 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2576 if (OpSizeInBits > 16)
2577 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2578 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2582 /// isBSwapHWordElement - Return true if the specified node is an element
2583 /// that makes up a 32-bit packed halfword byteswap. i.e.
2584 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2585 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2586 if (!N.getNode()->hasOneUse())
2589 unsigned Opc = N.getOpcode();
2590 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2598 switch (N1C->getZExtValue()) {
2601 case 0xFF: Num = 0; break;
2602 case 0xFF00: Num = 1; break;
2603 case 0xFF0000: Num = 2; break;
2604 case 0xFF000000: Num = 3; break;
2607 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2608 SDValue N0 = N.getOperand(0);
2609 if (Opc == ISD::AND) {
2610 if (Num == 0 || Num == 2) {
2612 // (x >> 8) & 0xff0000
2613 if (N0.getOpcode() != ISD::SRL)
2615 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2616 if (!C || C->getZExtValue() != 8)
2619 // (x << 8) & 0xff00
2620 // (x << 8) & 0xff000000
2621 if (N0.getOpcode() != ISD::SHL)
2623 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2624 if (!C || C->getZExtValue() != 8)
2627 } else if (Opc == ISD::SHL) {
2629 // (x & 0xff0000) << 8
2630 if (Num != 0 && Num != 2)
2632 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2633 if (!C || C->getZExtValue() != 8)
2635 } else { // Opc == ISD::SRL
2636 // (x & 0xff00) >> 8
2637 // (x & 0xff000000) >> 8
2638 if (Num != 1 && Num != 3)
2640 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2641 if (!C || C->getZExtValue() != 8)
2648 Parts[Num] = N0.getOperand(0).getNode();
2652 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2653 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2654 /// => (rotl (bswap x), 16)
2655 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2656 if (!LegalOperations)
2659 EVT VT = N->getValueType(0);
2662 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2665 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2667 // (or (or (and), (and)), (or (and), (and)))
2668 // (or (or (or (and), (and)), (and)), (and))
2669 if (N0.getOpcode() != ISD::OR)
2671 SDValue N00 = N0.getOperand(0);
2672 SDValue N01 = N0.getOperand(1);
2674 if (N1.getOpcode() == ISD::OR) {
2675 // (or (or (and), (and)), (or (and), (and)))
2676 SDValue N000 = N00.getOperand(0);
2677 if (!isBSwapHWordElement(N000, Parts))
2680 SDValue N001 = N00.getOperand(1);
2681 if (!isBSwapHWordElement(N001, Parts))
2683 SDValue N010 = N01.getOperand(0);
2684 if (!isBSwapHWordElement(N010, Parts))
2686 SDValue N011 = N01.getOperand(1);
2687 if (!isBSwapHWordElement(N011, Parts))
2690 // (or (or (or (and), (and)), (and)), (and))
2691 if (!isBSwapHWordElement(N1, Parts))
2693 if (!isBSwapHWordElement(N01, Parts))
2695 if (N00.getOpcode() != ISD::OR)
2697 SDValue N000 = N00.getOperand(0);
2698 if (!isBSwapHWordElement(N000, Parts))
2700 SDValue N001 = N00.getOperand(1);
2701 if (!isBSwapHWordElement(N001, Parts))
2705 // Make sure the parts are all coming from the same node.
2706 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2709 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2710 SDValue(Parts[0],0));
2712 // Result of the bswap should be rotated by 16. If it's not legal, than
2713 // do (x << 16) | (x >> 16).
2714 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2715 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2716 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2717 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2718 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2719 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2720 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2721 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2724 SDValue DAGCombiner::visitOR(SDNode *N) {
2725 SDValue N0 = N->getOperand(0);
2726 SDValue N1 = N->getOperand(1);
2727 SDValue LL, LR, RL, RR, CC0, CC1;
2728 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2729 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2730 EVT VT = N1.getValueType();
2733 if (VT.isVector()) {
2734 SDValue FoldedVOp = SimplifyVBinOp(N);
2735 if (FoldedVOp.getNode()) return FoldedVOp;
2738 // fold (or x, undef) -> -1
2739 if (!LegalOperations &&
2740 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2741 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2742 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2744 // fold (or c1, c2) -> c1|c2
2746 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2747 // canonicalize constant to RHS
2749 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2750 // fold (or x, 0) -> x
2751 if (N1C && N1C->isNullValue())
2753 // fold (or x, -1) -> -1
2754 if (N1C && N1C->isAllOnesValue())
2756 // fold (or x, c) -> c iff (x & ~c) == 0
2757 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2760 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
2761 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
2762 if (BSwap.getNode() != 0)
2764 BSwap = MatchBSwapHWordLow(N, N0, N1);
2765 if (BSwap.getNode() != 0)
2769 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2770 if (ROR.getNode() != 0)
2772 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2773 // iff (c1 & c2) == 0.
2774 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2775 isa<ConstantSDNode>(N0.getOperand(1))) {
2776 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2777 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2778 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2779 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2780 N0.getOperand(0), N1),
2781 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2783 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2784 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2785 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2786 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2788 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2789 LL.getValueType().isInteger()) {
2790 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2791 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2792 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2793 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2794 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2795 LR.getValueType(), LL, RL);
2796 AddToWorkList(ORNode.getNode());
2797 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2799 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2800 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2801 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2802 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2803 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2804 LR.getValueType(), LL, RL);
2805 AddToWorkList(ANDNode.getNode());
2806 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2809 // canonicalize equivalent to ll == rl
2810 if (LL == RR && LR == RL) {
2811 Op1 = ISD::getSetCCSwappedOperands(Op1);
2814 if (LL == RL && LR == RR) {
2815 bool isInteger = LL.getValueType().isInteger();
2816 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2817 if (Result != ISD::SETCC_INVALID &&
2818 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2819 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2824 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2825 if (N0.getOpcode() == N1.getOpcode()) {
2826 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2827 if (Tmp.getNode()) return Tmp;
2830 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2831 if (N0.getOpcode() == ISD::AND &&
2832 N1.getOpcode() == ISD::AND &&
2833 N0.getOperand(1).getOpcode() == ISD::Constant &&
2834 N1.getOperand(1).getOpcode() == ISD::Constant &&
2835 // Don't increase # computations.
2836 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2837 // We can only do this xform if we know that bits from X that are set in C2
2838 // but not in C1 are already zero. Likewise for Y.
2839 const APInt &LHSMask =
2840 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2841 const APInt &RHSMask =
2842 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2844 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2845 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2846 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2847 N0.getOperand(0), N1.getOperand(0));
2848 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2849 DAG.getConstant(LHSMask | RHSMask, VT));
2853 // See if this is some rotate idiom.
2854 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2855 return SDValue(Rot, 0);
2857 // Simplify the operands using demanded-bits information.
2858 if (!VT.isVector() &&
2859 SimplifyDemandedBits(SDValue(N, 0)))
2860 return SDValue(N, 0);
2865 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2866 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2867 if (Op.getOpcode() == ISD::AND) {
2868 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2869 Mask = Op.getOperand(1);
2870 Op = Op.getOperand(0);
2876 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2884 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2885 // idioms for rotate, and if the target supports rotation instructions, generate
2887 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2888 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2889 EVT VT = LHS.getValueType();
2890 if (!TLI.isTypeLegal(VT)) return 0;
2892 // The target must have at least one rotate flavor.
2893 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2894 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2895 if (!HasROTL && !HasROTR) return 0;
2897 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2898 SDValue LHSShift; // The shift.
2899 SDValue LHSMask; // AND value if any.
2900 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2901 return 0; // Not part of a rotate.
2903 SDValue RHSShift; // The shift.
2904 SDValue RHSMask; // AND value if any.
2905 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2906 return 0; // Not part of a rotate.
2908 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2909 return 0; // Not shifting the same value.
2911 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2912 return 0; // Shifts must disagree.
2914 // Canonicalize shl to left side in a shl/srl pair.
2915 if (RHSShift.getOpcode() == ISD::SHL) {
2916 std::swap(LHS, RHS);
2917 std::swap(LHSShift, RHSShift);
2918 std::swap(LHSMask , RHSMask );
2921 unsigned OpSizeInBits = VT.getSizeInBits();
2922 SDValue LHSShiftArg = LHSShift.getOperand(0);
2923 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2924 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2926 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2927 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2928 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2929 RHSShiftAmt.getOpcode() == ISD::Constant) {
2930 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2931 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2932 if ((LShVal + RShVal) != OpSizeInBits)
2937 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2939 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2941 // If there is an AND of either shifted operand, apply it to the result.
2942 if (LHSMask.getNode() || RHSMask.getNode()) {
2943 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2945 if (LHSMask.getNode()) {
2946 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2947 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2949 if (RHSMask.getNode()) {
2950 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2951 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2954 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2957 return Rot.getNode();
2960 // If there is a mask here, and we have a variable shift, we can't be sure
2961 // that we're masking out the right stuff.
2962 if (LHSMask.getNode() || RHSMask.getNode())
2965 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2966 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2967 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2968 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2969 if (ConstantSDNode *SUBC =
2970 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2971 if (SUBC->getAPIntValue() == OpSizeInBits) {
2973 return DAG.getNode(ISD::ROTL, DL, VT,
2974 LHSShiftArg, LHSShiftAmt).getNode();
2976 return DAG.getNode(ISD::ROTR, DL, VT,
2977 LHSShiftArg, RHSShiftAmt).getNode();
2982 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2983 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2984 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2985 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2986 if (ConstantSDNode *SUBC =
2987 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2988 if (SUBC->getAPIntValue() == OpSizeInBits) {
2990 return DAG.getNode(ISD::ROTR, DL, VT,
2991 LHSShiftArg, RHSShiftAmt).getNode();
2993 return DAG.getNode(ISD::ROTL, DL, VT,
2994 LHSShiftArg, LHSShiftAmt).getNode();
2999 // Look for sign/zext/any-extended or truncate cases:
3000 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3001 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3002 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3003 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3004 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3005 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3006 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3007 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3008 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3009 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3010 if (RExtOp0.getOpcode() == ISD::SUB &&
3011 RExtOp0.getOperand(1) == LExtOp0) {
3012 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3014 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3015 // (rotr x, (sub 32, y))
3016 if (ConstantSDNode *SUBC =
3017 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3018 if (SUBC->getAPIntValue() == OpSizeInBits) {
3019 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3021 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3024 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3025 RExtOp0 == LExtOp0.getOperand(1)) {
3026 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3028 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3029 // (rotl x, (sub 32, y))
3030 if (ConstantSDNode *SUBC =
3031 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3032 if (SUBC->getAPIntValue() == OpSizeInBits) {
3033 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3035 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3044 SDValue DAGCombiner::visitXOR(SDNode *N) {
3045 SDValue N0 = N->getOperand(0);
3046 SDValue N1 = N->getOperand(1);
3047 SDValue LHS, RHS, CC;
3048 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3050 EVT VT = N0.getValueType();
3053 if (VT.isVector()) {
3054 SDValue FoldedVOp = SimplifyVBinOp(N);
3055 if (FoldedVOp.getNode()) return FoldedVOp;
3058 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3059 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3060 return DAG.getConstant(0, VT);
3061 // fold (xor x, undef) -> undef
3062 if (N0.getOpcode() == ISD::UNDEF)
3064 if (N1.getOpcode() == ISD::UNDEF)
3066 // fold (xor c1, c2) -> c1^c2
3068 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3069 // canonicalize constant to RHS
3071 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3072 // fold (xor x, 0) -> x
3073 if (N1C && N1C->isNullValue())
3076 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3077 if (RXOR.getNode() != 0)
3080 // fold !(x cc y) -> (x !cc y)
3081 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3082 bool isInt = LHS.getValueType().isInteger();
3083 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3086 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3087 switch (N0.getOpcode()) {
3089 llvm_unreachable("Unhandled SetCC Equivalent!");
3091 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3092 case ISD::SELECT_CC:
3093 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3094 N0.getOperand(3), NotCC);
3099 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3100 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3101 N0.getNode()->hasOneUse() &&
3102 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3103 SDValue V = N0.getOperand(0);
3104 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3105 DAG.getConstant(1, V.getValueType()));
3106 AddToWorkList(V.getNode());
3107 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3110 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3111 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3112 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3113 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3114 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3115 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3116 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3117 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3118 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3119 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3122 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3123 if (N1C && N1C->isAllOnesValue() &&
3124 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3125 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3126 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(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 (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3135 if (N1C && N0.getOpcode() == ISD::XOR) {
3136 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3137 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3139 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3140 DAG.getConstant(N1C->getAPIntValue() ^
3141 N00C->getAPIntValue(), VT));
3143 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3144 DAG.getConstant(N1C->getAPIntValue() ^
3145 N01C->getAPIntValue(), VT));
3147 // fold (xor x, x) -> 0
3149 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3151 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3152 if (N0.getOpcode() == N1.getOpcode()) {
3153 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3154 if (Tmp.getNode()) return Tmp;
3157 // Simplify the expression using non-local knowledge.
3158 if (!VT.isVector() &&
3159 SimplifyDemandedBits(SDValue(N, 0)))
3160 return SDValue(N, 0);
3165 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3166 /// the shift amount is a constant.
3167 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3168 SDNode *LHS = N->getOperand(0).getNode();
3169 if (!LHS->hasOneUse()) return SDValue();
3171 // We want to pull some binops through shifts, so that we have (and (shift))
3172 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3173 // thing happens with address calculations, so it's important to canonicalize
3175 bool HighBitSet = false; // Can we transform this if the high bit is set?
3177 switch (LHS->getOpcode()) {
3178 default: return SDValue();
3181 HighBitSet = false; // We can only transform sra if the high bit is clear.
3184 HighBitSet = true; // We can only transform sra if the high bit is set.
3187 if (N->getOpcode() != ISD::SHL)
3188 return SDValue(); // only shl(add) not sr[al](add).
3189 HighBitSet = false; // We can only transform sra if the high bit is clear.
3193 // We require the RHS of the binop to be a constant as well.
3194 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3195 if (!BinOpCst) return SDValue();
3197 // FIXME: disable this unless the input to the binop is a shift by a constant.
3198 // If it is not a shift, it pessimizes some common cases like:
3200 // void foo(int *X, int i) { X[i & 1235] = 1; }
3201 // int bar(int *X, int i) { return X[i & 255]; }
3202 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3203 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3204 BinOpLHSVal->getOpcode() != ISD::SRA &&
3205 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3206 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3209 EVT VT = N->getValueType(0);
3211 // If this is a signed shift right, and the high bit is modified by the
3212 // logical operation, do not perform the transformation. The highBitSet
3213 // boolean indicates the value of the high bit of the constant which would
3214 // cause it to be modified for this operation.
3215 if (N->getOpcode() == ISD::SRA) {
3216 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3217 if (BinOpRHSSignSet != HighBitSet)
3221 // Fold the constants, shifting the binop RHS by the shift amount.
3222 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3224 LHS->getOperand(1), N->getOperand(1));
3226 // Create the new shift.
3227 SDValue NewShift = DAG.getNode(N->getOpcode(),
3228 LHS->getOperand(0).getDebugLoc(),
3229 VT, LHS->getOperand(0), N->getOperand(1));
3231 // Create the new binop.
3232 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3235 SDValue DAGCombiner::visitSHL(SDNode *N) {
3236 SDValue N0 = N->getOperand(0);
3237 SDValue N1 = N->getOperand(1);
3238 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3240 EVT VT = N0.getValueType();
3241 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3243 // fold (shl c1, c2) -> c1<<c2
3245 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3246 // fold (shl 0, x) -> 0
3247 if (N0C && N0C->isNullValue())
3249 // fold (shl x, c >= size(x)) -> undef
3250 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3251 return DAG.getUNDEF(VT);
3252 // fold (shl x, 0) -> x
3253 if (N1C && N1C->isNullValue())
3255 // fold (shl undef, x) -> 0
3256 if (N0.getOpcode() == ISD::UNDEF)
3257 return DAG.getConstant(0, VT);
3258 // if (shl x, c) is known to be zero, return 0
3259 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3260 APInt::getAllOnesValue(OpSizeInBits)))
3261 return DAG.getConstant(0, VT);
3262 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3263 if (N1.getOpcode() == ISD::TRUNCATE &&
3264 N1.getOperand(0).getOpcode() == ISD::AND &&
3265 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3266 SDValue N101 = N1.getOperand(0).getOperand(1);
3267 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3268 EVT TruncVT = N1.getValueType();
3269 SDValue N100 = N1.getOperand(0).getOperand(0);
3270 APInt TruncC = N101C->getAPIntValue();
3271 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3272 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3273 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3274 DAG.getNode(ISD::TRUNCATE,
3277 DAG.getConstant(TruncC, TruncVT)));
3281 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3282 return SDValue(N, 0);
3284 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3285 if (N1C && N0.getOpcode() == ISD::SHL &&
3286 N0.getOperand(1).getOpcode() == ISD::Constant) {
3287 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3288 uint64_t c2 = N1C->getZExtValue();
3289 if (c1 + c2 >= OpSizeInBits)
3290 return DAG.getConstant(0, VT);
3291 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3292 DAG.getConstant(c1 + c2, N1.getValueType()));
3295 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3296 // For this to be valid, the second form must not preserve any of the bits
3297 // that are shifted out by the inner shift in the first form. This means
3298 // the outer shift size must be >= the number of bits added by the ext.
3299 // As a corollary, we don't care what kind of ext it is.
3300 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3301 N0.getOpcode() == ISD::ANY_EXTEND ||
3302 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3303 N0.getOperand(0).getOpcode() == ISD::SHL &&
3304 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3306 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3307 uint64_t c2 = N1C->getZExtValue();
3308 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3309 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3310 if (c2 >= OpSizeInBits - InnerShiftSize) {
3311 if (c1 + c2 >= OpSizeInBits)
3312 return DAG.getConstant(0, VT);
3313 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3314 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3315 N0.getOperand(0)->getOperand(0)),
3316 DAG.getConstant(c1 + c2, N1.getValueType()));
3320 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3321 // (and (srl x, (sub c1, c2), MASK)
3322 if (N1C && N0.getOpcode() == ISD::SRL &&
3323 N0.getOperand(1).getOpcode() == ISD::Constant) {
3324 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3325 if (c1 < VT.getSizeInBits()) {
3326 uint64_t c2 = N1C->getZExtValue();
3327 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3328 VT.getSizeInBits() - c1);
3331 Mask = Mask.shl(c2-c1);
3332 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3333 DAG.getConstant(c2-c1, N1.getValueType()));
3335 Mask = Mask.lshr(c1-c2);
3336 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3337 DAG.getConstant(c1-c2, N1.getValueType()));
3339 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3340 DAG.getConstant(Mask, VT));
3343 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3344 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3345 SDValue HiBitsMask =
3346 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3347 VT.getSizeInBits() -
3348 N1C->getZExtValue()),
3350 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3355 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3356 if (NewSHL.getNode())
3363 SDValue DAGCombiner::visitSRA(SDNode *N) {
3364 SDValue N0 = N->getOperand(0);
3365 SDValue N1 = N->getOperand(1);
3366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3368 EVT VT = N0.getValueType();
3369 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3371 // fold (sra c1, c2) -> (sra c1, c2)
3373 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3374 // fold (sra 0, x) -> 0
3375 if (N0C && N0C->isNullValue())
3377 // fold (sra -1, x) -> -1
3378 if (N0C && N0C->isAllOnesValue())
3380 // fold (sra x, (setge c, size(x))) -> undef
3381 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3382 return DAG.getUNDEF(VT);
3383 // fold (sra x, 0) -> x
3384 if (N1C && N1C->isNullValue())
3386 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3388 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3389 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3390 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3392 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3393 ExtVT, VT.getVectorNumElements());
3394 if ((!LegalOperations ||
3395 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3396 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3397 N0.getOperand(0), DAG.getValueType(ExtVT));
3400 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3401 if (N1C && N0.getOpcode() == ISD::SRA) {
3402 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3403 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3404 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3405 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3406 DAG.getConstant(Sum, N1C->getValueType(0)));
3410 // fold (sra (shl X, m), (sub result_size, n))
3411 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3412 // result_size - n != m.
3413 // If truncate is free for the target sext(shl) is likely to result in better
3415 if (N0.getOpcode() == ISD::SHL) {
3416 // Get the two constanst of the shifts, CN0 = m, CN = n.
3417 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3419 // Determine what the truncate's result bitsize and type would be.
3421 EVT::getIntegerVT(*DAG.getContext(),
3422 OpSizeInBits - N1C->getZExtValue());
3423 // Determine the residual right-shift amount.
3424 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3426 // If the shift is not a no-op (in which case this should be just a sign
3427 // extend already), the truncated to type is legal, sign_extend is legal
3428 // on that type, and the truncate to that type is both legal and free,
3429 // perform the transform.
3430 if ((ShiftAmt > 0) &&
3431 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3432 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3433 TLI.isTruncateFree(VT, TruncVT)) {
3435 SDValue Amt = DAG.getConstant(ShiftAmt,
3436 getShiftAmountTy(N0.getOperand(0).getValueType()));
3437 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3438 N0.getOperand(0), Amt);
3439 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3441 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3442 N->getValueType(0), Trunc);
3447 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3448 if (N1.getOpcode() == ISD::TRUNCATE &&
3449 N1.getOperand(0).getOpcode() == ISD::AND &&
3450 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3451 SDValue N101 = N1.getOperand(0).getOperand(1);
3452 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3453 EVT TruncVT = N1.getValueType();
3454 SDValue N100 = N1.getOperand(0).getOperand(0);
3455 APInt TruncC = N101C->getAPIntValue();
3456 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3457 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3458 DAG.getNode(ISD::AND, N->getDebugLoc(),
3460 DAG.getNode(ISD::TRUNCATE,
3463 DAG.getConstant(TruncC, TruncVT)));
3467 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3468 // if c1 is equal to the number of bits the trunc removes
3469 if (N0.getOpcode() == ISD::TRUNCATE &&
3470 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3471 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3472 N0.getOperand(0).hasOneUse() &&
3473 N0.getOperand(0).getOperand(1).hasOneUse() &&
3474 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3475 EVT LargeVT = N0.getOperand(0).getValueType();
3476 ConstantSDNode *LargeShiftAmt =
3477 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3479 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3480 LargeShiftAmt->getZExtValue()) {
3482 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3483 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3484 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3485 N0.getOperand(0).getOperand(0), Amt);
3486 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3490 // Simplify, based on bits shifted out of the LHS.
3491 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3492 return SDValue(N, 0);
3495 // If the sign bit is known to be zero, switch this to a SRL.
3496 if (DAG.SignBitIsZero(N0))
3497 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3500 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3501 if (NewSRA.getNode())
3508 SDValue DAGCombiner::visitSRL(SDNode *N) {
3509 SDValue N0 = N->getOperand(0);
3510 SDValue N1 = N->getOperand(1);
3511 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3512 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3513 EVT VT = N0.getValueType();
3514 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3516 // fold (srl c1, c2) -> c1 >>u c2
3518 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3519 // fold (srl 0, x) -> 0
3520 if (N0C && N0C->isNullValue())
3522 // fold (srl x, c >= size(x)) -> undef
3523 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3524 return DAG.getUNDEF(VT);
3525 // fold (srl x, 0) -> x
3526 if (N1C && N1C->isNullValue())
3528 // if (srl x, c) is known to be zero, return 0
3529 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3530 APInt::getAllOnesValue(OpSizeInBits)))
3531 return DAG.getConstant(0, VT);
3533 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3534 if (N1C && N0.getOpcode() == ISD::SRL &&
3535 N0.getOperand(1).getOpcode() == ISD::Constant) {
3536 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3537 uint64_t c2 = N1C->getZExtValue();
3538 if (c1 + c2 >= OpSizeInBits)
3539 return DAG.getConstant(0, VT);
3540 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3541 DAG.getConstant(c1 + c2, N1.getValueType()));
3544 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3545 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3546 N0.getOperand(0).getOpcode() == ISD::SRL &&
3547 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3549 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3550 uint64_t c2 = N1C->getZExtValue();
3551 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3552 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3553 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3554 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3555 if (c1 + OpSizeInBits == InnerShiftSize) {
3556 if (c1 + c2 >= InnerShiftSize)
3557 return DAG.getConstant(0, VT);
3558 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3559 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3560 N0.getOperand(0)->getOperand(0),
3561 DAG.getConstant(c1 + c2, ShiftCountVT)));
3565 // fold (srl (shl x, c), c) -> (and x, cst2)
3566 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3567 N0.getValueSizeInBits() <= 64) {
3568 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3569 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3570 DAG.getConstant(~0ULL >> ShAmt, VT));
3574 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3575 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3576 // Shifting in all undef bits?
3577 EVT SmallVT = N0.getOperand(0).getValueType();
3578 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3579 return DAG.getUNDEF(VT);
3581 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3582 uint64_t ShiftAmt = N1C->getZExtValue();
3583 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3585 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3586 AddToWorkList(SmallShift.getNode());
3587 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3591 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3592 // bit, which is unmodified by sra.
3593 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3594 if (N0.getOpcode() == ISD::SRA)
3595 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3598 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3599 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3600 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3601 APInt KnownZero, KnownOne;
3602 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3603 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3605 // If any of the input bits are KnownOne, then the input couldn't be all
3606 // zeros, thus the result of the srl will always be zero.
3607 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3609 // If all of the bits input the to ctlz node are known to be zero, then
3610 // the result of the ctlz is "32" and the result of the shift is one.
3611 APInt UnknownBits = ~KnownZero & Mask;
3612 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3614 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3615 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3616 // Okay, we know that only that the single bit specified by UnknownBits
3617 // could be set on input to the CTLZ node. If this bit is set, the SRL
3618 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3619 // to an SRL/XOR pair, which is likely to simplify more.
3620 unsigned ShAmt = UnknownBits.countTrailingZeros();
3621 SDValue Op = N0.getOperand(0);
3624 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3625 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3626 AddToWorkList(Op.getNode());
3629 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3630 Op, DAG.getConstant(1, VT));
3634 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3635 if (N1.getOpcode() == ISD::TRUNCATE &&
3636 N1.getOperand(0).getOpcode() == ISD::AND &&
3637 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3638 SDValue N101 = N1.getOperand(0).getOperand(1);
3639 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3640 EVT TruncVT = N1.getValueType();
3641 SDValue N100 = N1.getOperand(0).getOperand(0);
3642 APInt TruncC = N101C->getAPIntValue();
3643 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3644 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3645 DAG.getNode(ISD::AND, N->getDebugLoc(),
3647 DAG.getNode(ISD::TRUNCATE,
3650 DAG.getConstant(TruncC, TruncVT)));
3654 // fold operands of srl based on knowledge that the low bits are not
3656 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3657 return SDValue(N, 0);
3660 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3661 if (NewSRL.getNode())
3665 // Attempt to convert a srl of a load into a narrower zero-extending load.
3666 SDValue NarrowLoad = ReduceLoadWidth(N);
3667 if (NarrowLoad.getNode())
3670 // Here is a common situation. We want to optimize:
3673 // %b = and i32 %a, 2
3674 // %c = srl i32 %b, 1
3675 // brcond i32 %c ...
3681 // %c = setcc eq %b, 0
3684 // However when after the source operand of SRL is optimized into AND, the SRL
3685 // itself may not be optimized further. Look for it and add the BRCOND into
3687 if (N->hasOneUse()) {
3688 SDNode *Use = *N->use_begin();
3689 if (Use->getOpcode() == ISD::BRCOND)
3691 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3692 // Also look pass the truncate.
3693 Use = *Use->use_begin();
3694 if (Use->getOpcode() == ISD::BRCOND)
3702 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3703 SDValue N0 = N->getOperand(0);
3704 EVT VT = N->getValueType(0);
3706 // fold (ctlz c1) -> c2
3707 if (isa<ConstantSDNode>(N0))
3708 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3712 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3713 SDValue N0 = N->getOperand(0);
3714 EVT VT = N->getValueType(0);
3716 // fold (cttz c1) -> c2
3717 if (isa<ConstantSDNode>(N0))
3718 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3722 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3723 SDValue N0 = N->getOperand(0);
3724 EVT VT = N->getValueType(0);
3726 // fold (ctpop c1) -> c2
3727 if (isa<ConstantSDNode>(N0))
3728 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3732 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3733 SDValue N0 = N->getOperand(0);
3734 SDValue N1 = N->getOperand(1);
3735 SDValue N2 = N->getOperand(2);
3736 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3737 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3738 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3739 EVT VT = N->getValueType(0);
3740 EVT VT0 = N0.getValueType();
3742 // fold (select C, X, X) -> X
3745 // fold (select true, X, Y) -> X
3746 if (N0C && !N0C->isNullValue())
3748 // fold (select false, X, Y) -> Y
3749 if (N0C && N0C->isNullValue())
3751 // fold (select C, 1, X) -> (or C, X)
3752 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3753 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3754 // fold (select C, 0, 1) -> (xor C, 1)
3755 if (VT.isInteger() &&
3758 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
3759 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3762 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3763 N0, DAG.getConstant(1, VT0));
3764 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3765 N0, DAG.getConstant(1, VT0));
3766 AddToWorkList(XORNode.getNode());
3768 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3769 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3771 // fold (select C, 0, X) -> (and (not C), X)
3772 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3773 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3774 AddToWorkList(NOTNode.getNode());
3775 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3777 // fold (select C, X, 1) -> (or (not C), X)
3778 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3779 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3780 AddToWorkList(NOTNode.getNode());
3781 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3783 // fold (select C, X, 0) -> (and C, X)
3784 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3785 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3786 // fold (select X, X, Y) -> (or X, Y)
3787 // fold (select X, 1, Y) -> (or X, Y)
3788 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3789 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3790 // fold (select X, Y, X) -> (and X, Y)
3791 // fold (select X, Y, 0) -> (and X, Y)
3792 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3793 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3795 // If we can fold this based on the true/false value, do so.
3796 if (SimplifySelectOps(N, N1, N2))
3797 return SDValue(N, 0); // Don't revisit N.
3799 // fold selects based on a setcc into other things, such as min/max/abs
3800 if (N0.getOpcode() == ISD::SETCC) {
3802 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3803 // having to say they don't support SELECT_CC on every type the DAG knows
3804 // about, since there is no way to mark an opcode illegal at all value types
3805 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3806 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3807 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3808 N0.getOperand(0), N0.getOperand(1),
3809 N1, N2, N0.getOperand(2));
3810 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3816 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3817 SDValue N0 = N->getOperand(0);
3818 SDValue N1 = N->getOperand(1);
3819 SDValue N2 = N->getOperand(2);
3820 SDValue N3 = N->getOperand(3);
3821 SDValue N4 = N->getOperand(4);
3822 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3824 // fold select_cc lhs, rhs, x, x, cc -> x
3828 // Determine if the condition we're dealing with is constant
3829 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3830 N0, N1, CC, N->getDebugLoc(), false);
3831 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3833 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3834 if (!SCCC->isNullValue())
3835 return N2; // cond always true -> true val
3837 return N3; // cond always false -> false val
3840 // Fold to a simpler select_cc
3841 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3842 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3843 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3846 // If we can fold this based on the true/false value, do so.
3847 if (SimplifySelectOps(N, N2, N3))
3848 return SDValue(N, 0); // Don't revisit N.
3850 // fold select_cc into other things, such as min/max/abs
3851 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3854 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3855 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3856 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3860 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3861 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3862 // transformation. Returns true if extension are possible and the above
3863 // mentioned transformation is profitable.
3864 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3866 SmallVector<SDNode*, 4> &ExtendNodes,
3867 const TargetLowering &TLI) {
3868 bool HasCopyToRegUses = false;
3869 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3870 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3871 UE = N0.getNode()->use_end();
3876 if (UI.getUse().getResNo() != N0.getResNo())
3878 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3879 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3880 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3881 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3882 // Sign bits will be lost after a zext.
3885 for (unsigned i = 0; i != 2; ++i) {
3886 SDValue UseOp = User->getOperand(i);
3889 if (!isa<ConstantSDNode>(UseOp))
3894 ExtendNodes.push_back(User);
3897 // If truncates aren't free and there are users we can't
3898 // extend, it isn't worthwhile.
3901 // Remember if this value is live-out.
3902 if (User->getOpcode() == ISD::CopyToReg)
3903 HasCopyToRegUses = true;
3906 if (HasCopyToRegUses) {
3907 bool BothLiveOut = false;
3908 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3910 SDUse &Use = UI.getUse();
3911 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3917 // Both unextended and extended values are live out. There had better be
3918 // a good reason for the transformation.
3919 return ExtendNodes.size();
3924 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
3925 SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
3926 ISD::NodeType ExtType) {
3927 // Extend SetCC uses if necessary.
3928 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3929 SDNode *SetCC = SetCCs[i];
3930 SmallVector<SDValue, 4> Ops;
3932 for (unsigned j = 0; j != 2; ++j) {
3933 SDValue SOp = SetCC->getOperand(j);
3935 Ops.push_back(ExtLoad);
3937 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
3940 Ops.push_back(SetCC->getOperand(2));
3941 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
3942 &Ops[0], Ops.size()));
3946 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3947 SDValue N0 = N->getOperand(0);
3948 EVT VT = N->getValueType(0);
3950 // fold (sext c1) -> c1
3951 if (isa<ConstantSDNode>(N0))
3952 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3954 // fold (sext (sext x)) -> (sext x)
3955 // fold (sext (aext x)) -> (sext x)
3956 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3957 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3960 if (N0.getOpcode() == ISD::TRUNCATE) {
3961 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3962 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3963 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3964 if (NarrowLoad.getNode()) {
3965 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3966 if (NarrowLoad.getNode() != N0.getNode()) {
3967 CombineTo(N0.getNode(), NarrowLoad);
3968 // CombineTo deleted the truncate, if needed, but not what's under it.
3971 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3974 // See if the value being truncated is already sign extended. If so, just
3975 // eliminate the trunc/sext pair.
3976 SDValue Op = N0.getOperand(0);
3977 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3978 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3979 unsigned DestBits = VT.getScalarType().getSizeInBits();
3980 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3982 if (OpBits == DestBits) {
3983 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3984 // bits, it is already ready.
3985 if (NumSignBits > DestBits-MidBits)
3987 } else if (OpBits < DestBits) {
3988 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3989 // bits, just sext from i32.
3990 if (NumSignBits > OpBits-MidBits)
3991 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3993 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3994 // bits, just truncate to i32.
3995 if (NumSignBits > OpBits-MidBits)
3996 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3999 // fold (sext (truncate x)) -> (sextinreg x).
4000 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4001 N0.getValueType())) {
4002 if (OpBits < DestBits)
4003 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4004 else if (OpBits > DestBits)
4005 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4006 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4007 DAG.getValueType(N0.getValueType()));
4011 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4012 // None of the supported targets knows how to perform load and sign extend
4013 // on vectors in one instruction. We only perform this transformation on
4015 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4016 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4017 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4018 bool DoXform = true;
4019 SmallVector<SDNode*, 4> SetCCs;
4020 if (!N0.hasOneUse())
4021 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4023 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4024 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4026 LN0->getBasePtr(), LN0->getPointerInfo(),
4028 LN0->isVolatile(), LN0->isNonTemporal(),
4029 LN0->getAlignment());
4030 CombineTo(N, ExtLoad);
4031 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4032 N0.getValueType(), ExtLoad);
4033 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4034 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4040 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4041 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4042 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4043 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4044 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4045 EVT MemVT = LN0->getMemoryVT();
4046 if ((!LegalOperations && !LN0->isVolatile()) ||
4047 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4048 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4050 LN0->getBasePtr(), LN0->getPointerInfo(),
4052 LN0->isVolatile(), LN0->isNonTemporal(),
4053 LN0->getAlignment());
4054 CombineTo(N, ExtLoad);
4055 CombineTo(N0.getNode(),
4056 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4057 N0.getValueType(), ExtLoad),
4058 ExtLoad.getValue(1));
4059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4063 // fold (sext (and/or/xor (load x), cst)) ->
4064 // (and/or/xor (sextload x), (sext cst))
4065 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4066 N0.getOpcode() == ISD::XOR) &&
4067 isa<LoadSDNode>(N0.getOperand(0)) &&
4068 N0.getOperand(1).getOpcode() == ISD::Constant &&
4069 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4070 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4071 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4072 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4073 bool DoXform = true;
4074 SmallVector<SDNode*, 4> SetCCs;
4075 if (!N0.hasOneUse())
4076 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4079 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4080 LN0->getChain(), LN0->getBasePtr(),
4081 LN0->getPointerInfo(),
4084 LN0->isNonTemporal(),
4085 LN0->getAlignment());
4086 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4087 Mask = Mask.sext(VT.getSizeInBits());
4088 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4089 ExtLoad, DAG.getConstant(Mask, VT));
4090 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4091 N0.getOperand(0).getDebugLoc(),
4092 N0.getOperand(0).getValueType(), ExtLoad);
4094 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4095 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4097 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4102 if (N0.getOpcode() == ISD::SETCC) {
4103 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4104 // Only do this before legalize for now.
4105 if (VT.isVector() && !LegalOperations) {
4106 EVT N0VT = N0.getOperand(0).getValueType();
4107 // We know that the # elements of the results is the same as the
4108 // # elements of the compare (and the # elements of the compare result
4109 // for that matter). Check to see that they are the same size. If so,
4110 // we know that the element size of the sext'd result matches the
4111 // element size of the compare operands.
4112 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4113 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4115 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4116 // If the desired elements are smaller or larger than the source
4117 // elements we can use a matching integer vector type and then
4118 // truncate/sign extend
4120 EVT MatchingElementType =
4121 EVT::getIntegerVT(*DAG.getContext(),
4122 N0VT.getScalarType().getSizeInBits());
4123 EVT MatchingVectorType =
4124 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4125 N0VT.getVectorNumElements());
4127 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4129 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4130 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4134 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4135 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4137 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4139 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4140 NegOne, DAG.getConstant(0, VT),
4141 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4142 if (SCC.getNode()) return SCC;
4143 if (!LegalOperations ||
4144 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4145 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4146 DAG.getSetCC(N->getDebugLoc(),
4147 TLI.getSetCCResultType(VT),
4148 N0.getOperand(0), N0.getOperand(1),
4149 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4150 NegOne, DAG.getConstant(0, VT));
4153 // fold (sext x) -> (zext x) if the sign bit is known zero.
4154 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4155 DAG.SignBitIsZero(N0))
4156 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4161 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4162 SDValue N0 = N->getOperand(0);
4163 EVT VT = N->getValueType(0);
4165 // fold (zext c1) -> c1
4166 if (isa<ConstantSDNode>(N0))
4167 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4168 // fold (zext (zext x)) -> (zext x)
4169 // fold (zext (aext x)) -> (zext x)
4170 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4171 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4174 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4175 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4176 if (N0.getOpcode() == ISD::TRUNCATE) {
4177 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4178 if (NarrowLoad.getNode()) {
4179 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4180 if (NarrowLoad.getNode() != N0.getNode()) {
4181 CombineTo(N0.getNode(), NarrowLoad);
4182 // CombineTo deleted the truncate, if needed, but not what's under it.
4185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4189 // fold (zext (truncate x)) -> (and x, mask)
4190 if (N0.getOpcode() == ISD::TRUNCATE &&
4191 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4193 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4194 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4195 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4196 if (NarrowLoad.getNode()) {
4197 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4198 if (NarrowLoad.getNode() != N0.getNode()) {
4199 CombineTo(N0.getNode(), NarrowLoad);
4200 // CombineTo deleted the truncate, if needed, but not what's under it.
4203 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4206 SDValue Op = N0.getOperand(0);
4207 if (Op.getValueType().bitsLT(VT)) {
4208 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4209 } else if (Op.getValueType().bitsGT(VT)) {
4210 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4212 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4213 N0.getValueType().getScalarType());
4216 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4217 // if either of the casts is not free.
4218 if (N0.getOpcode() == ISD::AND &&
4219 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4220 N0.getOperand(1).getOpcode() == ISD::Constant &&
4221 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4222 N0.getValueType()) ||
4223 !TLI.isZExtFree(N0.getValueType(), VT))) {
4224 SDValue X = N0.getOperand(0).getOperand(0);
4225 if (X.getValueType().bitsLT(VT)) {
4226 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4227 } else if (X.getValueType().bitsGT(VT)) {
4228 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4230 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4231 Mask = Mask.zext(VT.getSizeInBits());
4232 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4233 X, DAG.getConstant(Mask, VT));
4236 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4237 // None of the supported targets knows how to perform load and vector_zext
4238 // on vectors in one instruction. We only perform this transformation on
4240 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4241 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4242 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4243 bool DoXform = true;
4244 SmallVector<SDNode*, 4> SetCCs;
4245 if (!N0.hasOneUse())
4246 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4248 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4249 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4251 LN0->getBasePtr(), LN0->getPointerInfo(),
4253 LN0->isVolatile(), LN0->isNonTemporal(),
4254 LN0->getAlignment());
4255 CombineTo(N, ExtLoad);
4256 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4257 N0.getValueType(), ExtLoad);
4258 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4260 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4266 // fold (zext (and/or/xor (load x), cst)) ->
4267 // (and/or/xor (zextload x), (zext cst))
4268 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4269 N0.getOpcode() == ISD::XOR) &&
4270 isa<LoadSDNode>(N0.getOperand(0)) &&
4271 N0.getOperand(1).getOpcode() == ISD::Constant &&
4272 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4273 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4274 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4275 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4276 bool DoXform = true;
4277 SmallVector<SDNode*, 4> SetCCs;
4278 if (!N0.hasOneUse())
4279 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4282 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4283 LN0->getChain(), LN0->getBasePtr(),
4284 LN0->getPointerInfo(),
4287 LN0->isNonTemporal(),
4288 LN0->getAlignment());
4289 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4290 Mask = Mask.zext(VT.getSizeInBits());
4291 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4292 ExtLoad, DAG.getConstant(Mask, VT));
4293 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4294 N0.getOperand(0).getDebugLoc(),
4295 N0.getOperand(0).getValueType(), ExtLoad);
4297 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4298 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4300 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4305 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4306 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4307 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4308 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4309 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4310 EVT MemVT = LN0->getMemoryVT();
4311 if ((!LegalOperations && !LN0->isVolatile()) ||
4312 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4313 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4315 LN0->getBasePtr(), LN0->getPointerInfo(),
4317 LN0->isVolatile(), LN0->isNonTemporal(),
4318 LN0->getAlignment());
4319 CombineTo(N, ExtLoad);
4320 CombineTo(N0.getNode(),
4321 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4323 ExtLoad.getValue(1));
4324 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4328 if (N0.getOpcode() == ISD::SETCC) {
4329 if (!LegalOperations && VT.isVector()) {
4330 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4331 // Only do this before legalize for now.
4332 EVT N0VT = N0.getOperand(0).getValueType();
4333 EVT EltVT = VT.getVectorElementType();
4334 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4335 DAG.getConstant(1, EltVT));
4336 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4337 // We know that the # elements of the results is the same as the
4338 // # elements of the compare (and the # elements of the compare result
4339 // for that matter). Check to see that they are the same size. If so,
4340 // we know that the element size of the sext'd result matches the
4341 // element size of the compare operands.
4342 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4343 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4345 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4346 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4347 &OneOps[0], OneOps.size()));
4349 // If the desired elements are smaller or larger than the source
4350 // elements we can use a matching integer vector type and then
4351 // truncate/sign extend
4352 EVT MatchingElementType =
4353 EVT::getIntegerVT(*DAG.getContext(),
4354 N0VT.getScalarType().getSizeInBits());
4355 EVT MatchingVectorType =
4356 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4357 N0VT.getVectorNumElements());
4359 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4361 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4362 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4363 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4364 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4365 &OneOps[0], OneOps.size()));
4368 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4370 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4371 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4372 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4373 if (SCC.getNode()) return SCC;
4376 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4377 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4378 isa<ConstantSDNode>(N0.getOperand(1)) &&
4379 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4381 SDValue ShAmt = N0.getOperand(1);
4382 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4383 if (N0.getOpcode() == ISD::SHL) {
4384 SDValue InnerZExt = N0.getOperand(0);
4385 // If the original shl may be shifting out bits, do not perform this
4387 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4388 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4389 if (ShAmtVal > KnownZeroBits)
4393 DebugLoc DL = N->getDebugLoc();
4395 // Ensure that the shift amount is wide enough for the shifted value.
4396 if (VT.getSizeInBits() >= 256)
4397 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4399 return DAG.getNode(N0.getOpcode(), DL, VT,
4400 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4407 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4408 SDValue N0 = N->getOperand(0);
4409 EVT VT = N->getValueType(0);
4411 // fold (aext c1) -> c1
4412 if (isa<ConstantSDNode>(N0))
4413 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4414 // fold (aext (aext x)) -> (aext x)
4415 // fold (aext (zext x)) -> (zext x)
4416 // fold (aext (sext x)) -> (sext x)
4417 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4418 N0.getOpcode() == ISD::ZERO_EXTEND ||
4419 N0.getOpcode() == ISD::SIGN_EXTEND)
4420 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4422 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4423 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4424 if (N0.getOpcode() == ISD::TRUNCATE) {
4425 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4426 if (NarrowLoad.getNode()) {
4427 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4428 if (NarrowLoad.getNode() != N0.getNode()) {
4429 CombineTo(N0.getNode(), NarrowLoad);
4430 // CombineTo deleted the truncate, if needed, but not what's under it.
4433 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4437 // fold (aext (truncate x))
4438 if (N0.getOpcode() == ISD::TRUNCATE) {
4439 SDValue TruncOp = N0.getOperand(0);
4440 if (TruncOp.getValueType() == VT)
4441 return TruncOp; // x iff x size == zext size.
4442 if (TruncOp.getValueType().bitsGT(VT))
4443 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4444 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4447 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4448 // if the trunc is not free.
4449 if (N0.getOpcode() == ISD::AND &&
4450 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4451 N0.getOperand(1).getOpcode() == ISD::Constant &&
4452 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4453 N0.getValueType())) {
4454 SDValue X = N0.getOperand(0).getOperand(0);
4455 if (X.getValueType().bitsLT(VT)) {
4456 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4457 } else if (X.getValueType().bitsGT(VT)) {
4458 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4460 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4461 Mask = Mask.zext(VT.getSizeInBits());
4462 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4463 X, DAG.getConstant(Mask, VT));
4466 // fold (aext (load x)) -> (aext (truncate (extload x)))
4467 // None of the supported targets knows how to perform load and any_ext
4468 // on vectors in one instruction. We only perform this transformation on
4470 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4471 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4472 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4473 bool DoXform = true;
4474 SmallVector<SDNode*, 4> SetCCs;
4475 if (!N0.hasOneUse())
4476 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4478 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4479 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4481 LN0->getBasePtr(), LN0->getPointerInfo(),
4483 LN0->isVolatile(), LN0->isNonTemporal(),
4484 LN0->getAlignment());
4485 CombineTo(N, ExtLoad);
4486 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4487 N0.getValueType(), ExtLoad);
4488 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4489 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4491 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4495 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4496 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4497 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4498 if (N0.getOpcode() == ISD::LOAD &&
4499 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4501 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4502 EVT MemVT = LN0->getMemoryVT();
4503 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4504 VT, LN0->getChain(), LN0->getBasePtr(),
4505 LN0->getPointerInfo(), MemVT,
4506 LN0->isVolatile(), LN0->isNonTemporal(),
4507 LN0->getAlignment());
4508 CombineTo(N, ExtLoad);
4509 CombineTo(N0.getNode(),
4510 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4511 N0.getValueType(), ExtLoad),
4512 ExtLoad.getValue(1));
4513 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4516 if (N0.getOpcode() == ISD::SETCC) {
4517 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4518 // Only do this before legalize for now.
4519 if (VT.isVector() && !LegalOperations) {
4520 EVT N0VT = N0.getOperand(0).getValueType();
4521 // We know that the # elements of the results is the same as the
4522 // # elements of the compare (and the # elements of the compare result
4523 // for that matter). Check to see that they are the same size. If so,
4524 // we know that the element size of the sext'd result matches the
4525 // element size of the compare operands.
4526 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4527 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4529 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4530 // If the desired elements are smaller or larger than the source
4531 // elements we can use a matching integer vector type and then
4532 // truncate/sign extend
4534 EVT MatchingElementType =
4535 EVT::getIntegerVT(*DAG.getContext(),
4536 N0VT.getScalarType().getSizeInBits());
4537 EVT MatchingVectorType =
4538 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4539 N0VT.getVectorNumElements());
4541 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4543 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4544 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4548 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4550 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4551 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4552 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4560 /// GetDemandedBits - See if the specified operand can be simplified with the
4561 /// knowledge that only the bits specified by Mask are used. If so, return the
4562 /// simpler operand, otherwise return a null SDValue.
4563 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4564 switch (V.getOpcode()) {
4566 case ISD::Constant: {
4567 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4568 assert(CV != 0 && "Const value should be ConstSDNode.");
4569 const APInt &CVal = CV->getAPIntValue();
4570 APInt NewVal = CVal & Mask;
4571 if (NewVal != CVal) {
4572 return DAG.getConstant(NewVal, V.getValueType());
4578 // If the LHS or RHS don't contribute bits to the or, drop them.
4579 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4580 return V.getOperand(1);
4581 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4582 return V.getOperand(0);
4585 // Only look at single-use SRLs.
4586 if (!V.getNode()->hasOneUse())
4588 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4589 // See if we can recursively simplify the LHS.
4590 unsigned Amt = RHSC->getZExtValue();
4592 // Watch out for shift count overflow though.
4593 if (Amt >= Mask.getBitWidth()) break;
4594 APInt NewMask = Mask << Amt;
4595 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4596 if (SimplifyLHS.getNode())
4597 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4598 SimplifyLHS, V.getOperand(1));
4604 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4605 /// bits and then truncated to a narrower type and where N is a multiple
4606 /// of number of bits of the narrower type, transform it to a narrower load
4607 /// from address + N / num of bits of new type. If the result is to be
4608 /// extended, also fold the extension to form a extending load.
4609 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4610 unsigned Opc = N->getOpcode();
4612 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4613 SDValue N0 = N->getOperand(0);
4614 EVT VT = N->getValueType(0);
4617 // This transformation isn't valid for vector loads.
4621 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4623 if (Opc == ISD::SIGN_EXTEND_INREG) {
4624 ExtType = ISD::SEXTLOAD;
4625 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4626 } else if (Opc == ISD::SRL) {
4627 // Another special-case: SRL is basically zero-extending a narrower value.
4628 ExtType = ISD::ZEXTLOAD;
4630 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4631 if (!N01) return SDValue();
4632 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4633 VT.getSizeInBits() - N01->getZExtValue());
4635 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4638 unsigned EVTBits = ExtVT.getSizeInBits();
4640 // Do not generate loads of non-round integer types since these can
4641 // be expensive (and would be wrong if the type is not byte sized).
4642 if (!ExtVT.isRound())
4646 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4647 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4648 ShAmt = N01->getZExtValue();
4649 // Is the shift amount a multiple of size of VT?
4650 if ((ShAmt & (EVTBits-1)) == 0) {
4651 N0 = N0.getOperand(0);
4652 // Is the load width a multiple of size of VT?
4653 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4657 // At this point, we must have a load or else we can't do the transform.
4658 if (!isa<LoadSDNode>(N0)) return SDValue();
4660 // If the shift amount is larger than the input type then we're not
4661 // accessing any of the loaded bytes. If the load was a zextload/extload
4662 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4663 // If the load was a sextload then the result is a splat of the sign bit
4664 // of the extended byte. This is not worth optimizing for.
4665 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4670 // If the load is shifted left (and the result isn't shifted back right),
4671 // we can fold the truncate through the shift.
4672 unsigned ShLeftAmt = 0;
4673 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4674 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4675 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4676 ShLeftAmt = N01->getZExtValue();
4677 N0 = N0.getOperand(0);
4681 // If we haven't found a load, we can't narrow it. Don't transform one with
4682 // multiple uses, this would require adding a new load.
4683 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4684 // Don't change the width of a volatile load.
4685 cast<LoadSDNode>(N0)->isVolatile())
4688 // Verify that we are actually reducing a load width here.
4689 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4692 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4693 EVT PtrType = N0.getOperand(1).getValueType();
4695 // For big endian targets, we need to adjust the offset to the pointer to
4696 // load the correct bytes.
4697 if (TLI.isBigEndian()) {
4698 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4699 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4700 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4703 uint64_t PtrOff = ShAmt / 8;
4704 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4705 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4706 PtrType, LN0->getBasePtr(),
4707 DAG.getConstant(PtrOff, PtrType));
4708 AddToWorkList(NewPtr.getNode());
4711 if (ExtType == ISD::NON_EXTLOAD)
4712 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4713 LN0->getPointerInfo().getWithOffset(PtrOff),
4714 LN0->isVolatile(), LN0->isNonTemporal(),
4715 LN0->isInvariant(), NewAlign);
4717 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
4718 LN0->getPointerInfo().getWithOffset(PtrOff),
4719 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4722 // Replace the old load's chain with the new load's chain.
4723 WorkListRemover DeadNodes(*this);
4724 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4727 // Shift the result left, if we've swallowed a left shift.
4728 SDValue Result = Load;
4729 if (ShLeftAmt != 0) {
4730 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
4731 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4733 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4734 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4737 // Return the new loaded value.
4741 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4742 SDValue N0 = N->getOperand(0);
4743 SDValue N1 = N->getOperand(1);
4744 EVT VT = N->getValueType(0);
4745 EVT EVT = cast<VTSDNode>(N1)->getVT();
4746 unsigned VTBits = VT.getScalarType().getSizeInBits();
4747 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4749 // fold (sext_in_reg c1) -> c1
4750 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4751 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4753 // If the input is already sign extended, just drop the extension.
4754 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4757 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4758 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4759 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4760 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4761 N0.getOperand(0), N1);
4764 // fold (sext_in_reg (sext x)) -> (sext x)
4765 // fold (sext_in_reg (aext x)) -> (sext x)
4766 // if x is small enough.
4767 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4768 SDValue N00 = N0.getOperand(0);
4769 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4770 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4771 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4774 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4775 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4776 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4778 // fold operands of sext_in_reg based on knowledge that the top bits are not
4780 if (SimplifyDemandedBits(SDValue(N, 0)))
4781 return SDValue(N, 0);
4783 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4784 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4785 SDValue NarrowLoad = ReduceLoadWidth(N);
4786 if (NarrowLoad.getNode())
4789 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4790 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4791 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4792 if (N0.getOpcode() == ISD::SRL) {
4793 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4794 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4795 // We can turn this into an SRA iff the input to the SRL is already sign
4797 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4798 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4799 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4800 N0.getOperand(0), N0.getOperand(1));
4804 // fold (sext_inreg (extload x)) -> (sextload x)
4805 if (ISD::isEXTLoad(N0.getNode()) &&
4806 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4807 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4808 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4809 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4810 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4811 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4813 LN0->getBasePtr(), LN0->getPointerInfo(),
4815 LN0->isVolatile(), LN0->isNonTemporal(),
4816 LN0->getAlignment());
4817 CombineTo(N, ExtLoad);
4818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4821 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4822 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4824 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4825 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4826 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4827 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4828 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4830 LN0->getBasePtr(), LN0->getPointerInfo(),
4832 LN0->isVolatile(), LN0->isNonTemporal(),
4833 LN0->getAlignment());
4834 CombineTo(N, ExtLoad);
4835 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4839 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
4840 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
4841 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4842 N0.getOperand(1), false);
4843 if (BSwap.getNode() != 0)
4844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4851 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4852 SDValue N0 = N->getOperand(0);
4853 EVT VT = N->getValueType(0);
4856 if (N0.getValueType() == N->getValueType(0))
4858 // fold (truncate c1) -> c1
4859 if (isa<ConstantSDNode>(N0))
4860 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4861 // fold (truncate (truncate x)) -> (truncate x)
4862 if (N0.getOpcode() == ISD::TRUNCATE)
4863 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4864 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4865 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4866 N0.getOpcode() == ISD::SIGN_EXTEND ||
4867 N0.getOpcode() == ISD::ANY_EXTEND) {
4868 if (N0.getOperand(0).getValueType().bitsLT(VT))
4869 // if the source is smaller than the dest, we still need an extend
4870 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4872 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4873 // if the source is larger than the dest, than we just need the truncate
4874 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4876 // if the source and dest are the same type, we can drop both the extend
4877 // and the truncate.
4878 return N0.getOperand(0);
4881 // See if we can simplify the input to this truncate through knowledge that
4882 // only the low bits are being used.
4883 // For example "trunc (or (shl x, 8), y)" // -> trunc y
4884 // Currently we only perform this optimization on scalars because vectors
4885 // may have different active low bits.
4886 if (!VT.isVector()) {
4888 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4889 VT.getSizeInBits()));
4890 if (Shorter.getNode())
4891 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4893 // fold (truncate (load x)) -> (smaller load x)
4894 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4895 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4896 SDValue Reduced = ReduceLoadWidth(N);
4897 if (Reduced.getNode())
4901 // Simplify the operands using demanded-bits information.
4902 if (!VT.isVector() &&
4903 SimplifyDemandedBits(SDValue(N, 0)))
4904 return SDValue(N, 0);
4909 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4910 SDValue Elt = N->getOperand(i);
4911 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4912 return Elt.getNode();
4913 return Elt.getOperand(Elt.getResNo()).getNode();
4916 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4917 /// if load locations are consecutive.
4918 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4919 assert(N->getOpcode() == ISD::BUILD_PAIR);
4921 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4922 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4923 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4924 LD1->getPointerInfo().getAddrSpace() !=
4925 LD2->getPointerInfo().getAddrSpace())
4927 EVT LD1VT = LD1->getValueType(0);
4929 if (ISD::isNON_EXTLoad(LD2) &&
4931 // If both are volatile this would reduce the number of volatile loads.
4932 // If one is volatile it might be ok, but play conservative and bail out.
4933 !LD1->isVolatile() &&
4934 !LD2->isVolatile() &&
4935 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4936 unsigned Align = LD1->getAlignment();
4937 unsigned NewAlign = TLI.getTargetData()->
4938 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4940 if (NewAlign <= Align &&
4941 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4942 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4943 LD1->getBasePtr(), LD1->getPointerInfo(),
4944 false, false, false, Align);
4950 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4951 SDValue N0 = N->getOperand(0);
4952 EVT VT = N->getValueType(0);
4954 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4955 // Only do this before legalize, since afterward the target may be depending
4956 // on the bitconvert.
4957 // First check to see if this is all constant.
4959 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4961 bool isSimple = true;
4962 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4963 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4964 N0.getOperand(i).getOpcode() != ISD::Constant &&
4965 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4970 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4971 assert(!DestEltVT.isVector() &&
4972 "Element type of vector ValueType must not be vector!");
4974 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4977 // If the input is a constant, let getNode fold it.
4978 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4979 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4980 if (Res.getNode() != N) {
4981 if (!LegalOperations ||
4982 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4985 // Folding it resulted in an illegal node, and it's too late to
4986 // do that. Clean up the old node and forego the transformation.
4987 // Ideally this won't happen very often, because instcombine
4988 // and the earlier dagcombine runs (where illegal nodes are
4989 // permitted) should have folded most of them already.
4990 DAG.DeleteNode(Res.getNode());
4994 // (conv (conv x, t1), t2) -> (conv x, t2)
4995 if (N0.getOpcode() == ISD::BITCAST)
4996 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4999 // fold (conv (load x)) -> (load (conv*)x)
5000 // If the resultant load doesn't need a higher alignment than the original!
5001 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5002 // Do not change the width of a volatile load.
5003 !cast<LoadSDNode>(N0)->isVolatile() &&
5004 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5005 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5006 unsigned Align = TLI.getTargetData()->
5007 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5008 unsigned OrigAlign = LN0->getAlignment();
5010 if (Align <= OrigAlign) {
5011 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5012 LN0->getBasePtr(), LN0->getPointerInfo(),
5013 LN0->isVolatile(), LN0->isNonTemporal(),
5014 LN0->isInvariant(), OrigAlign);
5016 CombineTo(N0.getNode(),
5017 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5018 N0.getValueType(), Load),
5024 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5025 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5026 // This often reduces constant pool loads.
5027 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
5028 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5029 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5031 AddToWorkList(NewConv.getNode());
5033 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5034 if (N0.getOpcode() == ISD::FNEG)
5035 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5036 NewConv, DAG.getConstant(SignBit, VT));
5037 assert(N0.getOpcode() == ISD::FABS);
5038 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5039 NewConv, DAG.getConstant(~SignBit, VT));
5042 // fold (bitconvert (fcopysign cst, x)) ->
5043 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5044 // Note that we don't handle (copysign x, cst) because this can always be
5045 // folded to an fneg or fabs.
5046 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5047 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5048 VT.isInteger() && !VT.isVector()) {
5049 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5050 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5051 if (isTypeLegal(IntXVT)) {
5052 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5053 IntXVT, N0.getOperand(1));
5054 AddToWorkList(X.getNode());
5056 // If X has a different width than the result/lhs, sext it or truncate it.
5057 unsigned VTWidth = VT.getSizeInBits();
5058 if (OrigXWidth < VTWidth) {
5059 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5060 AddToWorkList(X.getNode());
5061 } else if (OrigXWidth > VTWidth) {
5062 // To get the sign bit in the right place, we have to shift it right
5063 // before truncating.
5064 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5065 X.getValueType(), X,
5066 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5067 AddToWorkList(X.getNode());
5068 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5069 AddToWorkList(X.getNode());
5072 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5073 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5074 X, DAG.getConstant(SignBit, VT));
5075 AddToWorkList(X.getNode());
5077 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5078 VT, N0.getOperand(0));
5079 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5080 Cst, DAG.getConstant(~SignBit, VT));
5081 AddToWorkList(Cst.getNode());
5083 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5087 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5088 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5089 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5090 if (CombineLD.getNode())
5097 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5098 EVT VT = N->getValueType(0);
5099 return CombineConsecutiveLoads(N, VT);
5102 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5103 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5104 /// destination element value type.
5105 SDValue DAGCombiner::
5106 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5107 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5109 // If this is already the right type, we're done.
5110 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5112 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5113 unsigned DstBitSize = DstEltVT.getSizeInBits();
5115 // If this is a conversion of N elements of one type to N elements of another
5116 // type, convert each element. This handles FP<->INT cases.
5117 if (SrcBitSize == DstBitSize) {
5118 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5119 BV->getValueType(0).getVectorNumElements());
5121 // Due to the FP element handling below calling this routine recursively,
5122 // we can end up with a scalar-to-vector node here.
5123 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5124 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5125 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5126 DstEltVT, BV->getOperand(0)));
5128 SmallVector<SDValue, 8> Ops;
5129 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5130 SDValue Op = BV->getOperand(i);
5131 // If the vector element type is not legal, the BUILD_VECTOR operands
5132 // are promoted and implicitly truncated. Make that explicit here.
5133 if (Op.getValueType() != SrcEltVT)
5134 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5135 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5137 AddToWorkList(Ops.back().getNode());
5139 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5140 &Ops[0], Ops.size());
5143 // Otherwise, we're growing or shrinking the elements. To avoid having to
5144 // handle annoying details of growing/shrinking FP values, we convert them to
5146 if (SrcEltVT.isFloatingPoint()) {
5147 // Convert the input float vector to a int vector where the elements are the
5149 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5150 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5151 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5155 // Now we know the input is an integer vector. If the output is a FP type,
5156 // convert to integer first, then to FP of the right size.
5157 if (DstEltVT.isFloatingPoint()) {
5158 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5159 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5160 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5162 // Next, convert to FP elements of the same size.
5163 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5166 // Okay, we know the src/dst types are both integers of differing types.
5167 // Handling growing first.
5168 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5169 if (SrcBitSize < DstBitSize) {
5170 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5172 SmallVector<SDValue, 8> Ops;
5173 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5174 i += NumInputsPerOutput) {
5175 bool isLE = TLI.isLittleEndian();
5176 APInt NewBits = APInt(DstBitSize, 0);
5177 bool EltIsUndef = true;
5178 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5179 // Shift the previously computed bits over.
5180 NewBits <<= SrcBitSize;
5181 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5182 if (Op.getOpcode() == ISD::UNDEF) continue;
5185 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5186 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5190 Ops.push_back(DAG.getUNDEF(DstEltVT));
5192 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5195 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5196 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5197 &Ops[0], Ops.size());
5200 // Finally, this must be the case where we are shrinking elements: each input
5201 // turns into multiple outputs.
5202 bool isS2V = ISD::isScalarToVector(BV);
5203 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5204 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5205 NumOutputsPerInput*BV->getNumOperands());
5206 SmallVector<SDValue, 8> Ops;
5208 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5209 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5210 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5211 Ops.push_back(DAG.getUNDEF(DstEltVT));
5215 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5216 getAPIntValue().zextOrTrunc(SrcBitSize);
5218 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5219 APInt ThisVal = OpVal.trunc(DstBitSize);
5220 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5221 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5222 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5223 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5225 OpVal = OpVal.lshr(DstBitSize);
5228 // For big endian targets, swap the order of the pieces of each element.
5229 if (TLI.isBigEndian())
5230 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5233 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5234 &Ops[0], Ops.size());
5237 SDValue DAGCombiner::visitFADD(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
5239 SDValue N1 = N->getOperand(1);
5240 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5241 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5242 EVT VT = N->getValueType(0);
5245 if (VT.isVector()) {
5246 SDValue FoldedVOp = SimplifyVBinOp(N);
5247 if (FoldedVOp.getNode()) return FoldedVOp;
5250 // fold (fadd c1, c2) -> (fadd c1, c2)
5251 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5252 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5253 // canonicalize constant to RHS
5254 if (N0CFP && !N1CFP)
5255 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5256 // fold (fadd A, 0) -> A
5257 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5259 // fold (fadd A, (fneg B)) -> (fsub A, B)
5260 if (isNegatibleForFree(N1, LegalOperations) == 2)
5261 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5262 GetNegatedExpression(N1, DAG, LegalOperations));
5263 // fold (fadd (fneg A), B) -> (fsub B, A)
5264 if (isNegatibleForFree(N0, LegalOperations) == 2)
5265 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5266 GetNegatedExpression(N0, DAG, LegalOperations));
5268 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5269 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
5270 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5271 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5272 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5273 N0.getOperand(1), N1));
5278 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5279 SDValue N0 = N->getOperand(0);
5280 SDValue N1 = N->getOperand(1);
5281 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5282 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5283 EVT VT = N->getValueType(0);
5286 if (VT.isVector()) {
5287 SDValue FoldedVOp = SimplifyVBinOp(N);
5288 if (FoldedVOp.getNode()) return FoldedVOp;
5291 // fold (fsub c1, c2) -> c1-c2
5292 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5293 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5294 // fold (fsub A, 0) -> A
5295 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5297 // fold (fsub 0, B) -> -B
5298 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
5299 if (isNegatibleForFree(N1, LegalOperations))
5300 return GetNegatedExpression(N1, DAG, LegalOperations);
5301 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5302 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
5304 // fold (fsub A, (fneg B)) -> (fadd A, B)
5305 if (isNegatibleForFree(N1, LegalOperations))
5306 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
5307 GetNegatedExpression(N1, DAG, LegalOperations));
5312 SDValue DAGCombiner::visitFMUL(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 (fmul c1, c2) -> c1*c2
5326 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5327 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5328 // canonicalize constant to RHS
5329 if (N0CFP && !N1CFP)
5330 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5331 // fold (fmul A, 0) -> 0
5332 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5334 // fold (fmul A, 0) -> 0, vector edition.
5335 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
5337 // fold (fmul X, 2.0) -> (fadd X, X)
5338 if (N1CFP && N1CFP->isExactlyValue(+2.0))
5339 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5340 // fold (fmul X, -1.0) -> (fneg X)
5341 if (N1CFP && N1CFP->isExactlyValue(-1.0))
5342 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5343 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5345 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5346 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5347 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
5348 // Both can be negated for free, check to see if at least one is cheaper
5350 if (LHSNeg == 2 || RHSNeg == 2)
5351 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5352 GetNegatedExpression(N0, DAG, LegalOperations),
5353 GetNegatedExpression(N1, DAG, LegalOperations));
5357 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5358 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
5359 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5360 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5361 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5362 N0.getOperand(1), N1));
5367 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5368 SDValue N0 = N->getOperand(0);
5369 SDValue N1 = N->getOperand(1);
5370 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5371 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5372 EVT VT = N->getValueType(0);
5375 if (VT.isVector()) {
5376 SDValue FoldedVOp = SimplifyVBinOp(N);
5377 if (FoldedVOp.getNode()) return FoldedVOp;
5380 // fold (fdiv c1, c2) -> c1/c2
5381 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5382 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5385 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5386 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5387 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
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::FDIV, N->getDebugLoc(), VT,
5392 GetNegatedExpression(N0, DAG, LegalOperations),
5393 GetNegatedExpression(N1, DAG, LegalOperations));
5400 SDValue DAGCombiner::visitFREM(SDNode *N) {
5401 SDValue N0 = N->getOperand(0);
5402 SDValue N1 = N->getOperand(1);
5403 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5404 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5405 EVT VT = N->getValueType(0);
5407 // fold (frem c1, c2) -> fmod(c1,c2)
5408 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5409 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5414 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5415 SDValue N0 = N->getOperand(0);
5416 SDValue N1 = N->getOperand(1);
5417 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5418 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5419 EVT VT = N->getValueType(0);
5421 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5422 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5425 const APFloat& V = N1CFP->getValueAPF();
5426 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5427 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5428 if (!V.isNegative()) {
5429 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5430 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5432 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5433 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5434 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5438 // copysign(fabs(x), y) -> copysign(x, y)
5439 // copysign(fneg(x), y) -> copysign(x, y)
5440 // copysign(copysign(x,z), y) -> copysign(x, y)
5441 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5442 N0.getOpcode() == ISD::FCOPYSIGN)
5443 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5444 N0.getOperand(0), N1);
5446 // copysign(x, abs(y)) -> abs(x)
5447 if (N1.getOpcode() == ISD::FABS)
5448 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5450 // copysign(x, copysign(y,z)) -> copysign(x, z)
5451 if (N1.getOpcode() == ISD::FCOPYSIGN)
5452 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5453 N0, N1.getOperand(1));
5455 // copysign(x, fp_extend(y)) -> copysign(x, y)
5456 // copysign(x, fp_round(y)) -> copysign(x, y)
5457 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5458 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5459 N0, N1.getOperand(0));
5464 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5465 SDValue N0 = N->getOperand(0);
5466 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5467 EVT VT = N->getValueType(0);
5468 EVT OpVT = N0.getValueType();
5470 // fold (sint_to_fp c1) -> c1fp
5471 if (N0C && OpVT != MVT::ppcf128 &&
5472 // ...but only if the target supports immediate floating-point values
5473 (!LegalOperations ||
5474 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5475 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5477 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5478 // but UINT_TO_FP is legal on this target, try to convert.
5479 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5480 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5481 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5482 if (DAG.SignBitIsZero(N0))
5483 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5489 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5490 SDValue N0 = N->getOperand(0);
5491 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5492 EVT VT = N->getValueType(0);
5493 EVT OpVT = N0.getValueType();
5495 // fold (uint_to_fp c1) -> c1fp
5496 if (N0C && OpVT != MVT::ppcf128 &&
5497 // ...but only if the target supports immediate floating-point values
5498 (!LegalOperations ||
5499 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5500 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5502 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5503 // but SINT_TO_FP is legal on this target, try to convert.
5504 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5505 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5506 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5507 if (DAG.SignBitIsZero(N0))
5508 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5514 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5515 SDValue N0 = N->getOperand(0);
5516 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5517 EVT VT = N->getValueType(0);
5519 // fold (fp_to_sint c1fp) -> c1
5521 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5526 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5527 SDValue N0 = N->getOperand(0);
5528 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5529 EVT VT = N->getValueType(0);
5531 // fold (fp_to_uint c1fp) -> c1
5532 if (N0CFP && VT != MVT::ppcf128)
5533 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5538 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5539 SDValue N0 = N->getOperand(0);
5540 SDValue N1 = N->getOperand(1);
5541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5542 EVT VT = N->getValueType(0);
5544 // fold (fp_round c1fp) -> c1fp
5545 if (N0CFP && N0.getValueType() != MVT::ppcf128)
5546 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5548 // fold (fp_round (fp_extend x)) -> x
5549 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5550 return N0.getOperand(0);
5552 // fold (fp_round (fp_round x)) -> (fp_round x)
5553 if (N0.getOpcode() == ISD::FP_ROUND) {
5554 // This is a value preserving truncation if both round's are.
5555 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5556 N0.getNode()->getConstantOperandVal(1) == 1;
5557 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5558 DAG.getIntPtrConstant(IsTrunc));
5561 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5562 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5563 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5564 N0.getOperand(0), N1);
5565 AddToWorkList(Tmp.getNode());
5566 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5567 Tmp, N0.getOperand(1));
5573 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5574 SDValue N0 = N->getOperand(0);
5575 EVT VT = N->getValueType(0);
5576 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5577 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5579 // fold (fp_round_inreg c1fp) -> c1fp
5580 if (N0CFP && isTypeLegal(EVT)) {
5581 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5582 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5588 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5589 SDValue N0 = N->getOperand(0);
5590 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5591 EVT VT = N->getValueType(0);
5593 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5594 if (N->hasOneUse() &&
5595 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5598 // fold (fp_extend c1fp) -> c1fp
5599 if (N0CFP && VT != MVT::ppcf128)
5600 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5602 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5604 if (N0.getOpcode() == ISD::FP_ROUND
5605 && N0.getNode()->getConstantOperandVal(1) == 1) {
5606 SDValue In = N0.getOperand(0);
5607 if (In.getValueType() == VT) return In;
5608 if (VT.bitsLT(In.getValueType()))
5609 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5610 In, N0.getOperand(1));
5611 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5614 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5615 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5616 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5617 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5618 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5619 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
5621 LN0->getBasePtr(), LN0->getPointerInfo(),
5623 LN0->isVolatile(), LN0->isNonTemporal(),
5624 LN0->getAlignment());
5625 CombineTo(N, ExtLoad);
5626 CombineTo(N0.getNode(),
5627 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5628 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5629 ExtLoad.getValue(1));
5630 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5636 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5637 SDValue N0 = N->getOperand(0);
5638 EVT VT = N->getValueType(0);
5640 if (isNegatibleForFree(N0, LegalOperations))
5641 return GetNegatedExpression(N0, DAG, LegalOperations);
5643 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5644 // constant pool values.
5645 if (N0.getOpcode() == ISD::BITCAST &&
5647 N0.getNode()->hasOneUse() &&
5648 N0.getOperand(0).getValueType().isInteger()) {
5649 SDValue Int = N0.getOperand(0);
5650 EVT IntVT = Int.getValueType();
5651 if (IntVT.isInteger() && !IntVT.isVector()) {
5652 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5653 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5654 AddToWorkList(Int.getNode());
5655 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5663 SDValue DAGCombiner::visitFABS(SDNode *N) {
5664 SDValue N0 = N->getOperand(0);
5665 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5666 EVT VT = N->getValueType(0);
5668 // fold (fabs c1) -> fabs(c1)
5669 if (N0CFP && VT != MVT::ppcf128)
5670 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5671 // fold (fabs (fabs x)) -> (fabs x)
5672 if (N0.getOpcode() == ISD::FABS)
5673 return N->getOperand(0);
5674 // fold (fabs (fneg x)) -> (fabs x)
5675 // fold (fabs (fcopysign x, y)) -> (fabs x)
5676 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5677 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5679 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5680 // constant pool values.
5681 if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5682 N0.getOperand(0).getValueType().isInteger() &&
5683 !N0.getOperand(0).getValueType().isVector()) {
5684 SDValue Int = N0.getOperand(0);
5685 EVT IntVT = Int.getValueType();
5686 if (IntVT.isInteger() && !IntVT.isVector()) {
5687 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5688 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5689 AddToWorkList(Int.getNode());
5690 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5691 N->getValueType(0), Int);
5698 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5699 SDValue Chain = N->getOperand(0);
5700 SDValue N1 = N->getOperand(1);
5701 SDValue N2 = N->getOperand(2);
5703 // If N is a constant we could fold this into a fallthrough or unconditional
5704 // branch. However that doesn't happen very often in normal code, because
5705 // Instcombine/SimplifyCFG should have handled the available opportunities.
5706 // If we did this folding here, it would be necessary to update the
5707 // MachineBasicBlock CFG, which is awkward.
5709 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5711 if (N1.getOpcode() == ISD::SETCC &&
5712 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5713 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5714 Chain, N1.getOperand(2),
5715 N1.getOperand(0), N1.getOperand(1), N2);
5718 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5719 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5720 (N1.getOperand(0).hasOneUse() &&
5721 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5723 if (N1.getOpcode() == ISD::TRUNCATE) {
5724 // Look pass the truncate.
5725 Trunc = N1.getNode();
5726 N1 = N1.getOperand(0);
5729 // Match this pattern so that we can generate simpler code:
5732 // %b = and i32 %a, 2
5733 // %c = srl i32 %b, 1
5734 // brcond i32 %c ...
5739 // %b = and i32 %a, 2
5740 // %c = setcc eq %b, 0
5743 // This applies only when the AND constant value has one bit set and the
5744 // SRL constant is equal to the log2 of the AND constant. The back-end is
5745 // smart enough to convert the result into a TEST/JMP sequence.
5746 SDValue Op0 = N1.getOperand(0);
5747 SDValue Op1 = N1.getOperand(1);
5749 if (Op0.getOpcode() == ISD::AND &&
5750 Op1.getOpcode() == ISD::Constant) {
5751 SDValue AndOp1 = Op0.getOperand(1);
5753 if (AndOp1.getOpcode() == ISD::Constant) {
5754 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5756 if (AndConst.isPowerOf2() &&
5757 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5759 DAG.getSetCC(N->getDebugLoc(),
5760 TLI.getSetCCResultType(Op0.getValueType()),
5761 Op0, DAG.getConstant(0, Op0.getValueType()),
5764 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5765 MVT::Other, Chain, SetCC, N2);
5766 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5767 // will convert it back to (X & C1) >> C2.
5768 CombineTo(N, NewBRCond, false);
5769 // Truncate is dead.
5771 removeFromWorkList(Trunc);
5772 DAG.DeleteNode(Trunc);
5774 // Replace the uses of SRL with SETCC
5775 WorkListRemover DeadNodes(*this);
5776 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5777 removeFromWorkList(N1.getNode());
5778 DAG.DeleteNode(N1.getNode());
5779 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5785 // Restore N1 if the above transformation doesn't match.
5786 N1 = N->getOperand(1);
5789 // Transform br(xor(x, y)) -> br(x != y)
5790 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5791 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5792 SDNode *TheXor = N1.getNode();
5793 SDValue Op0 = TheXor->getOperand(0);
5794 SDValue Op1 = TheXor->getOperand(1);
5795 if (Op0.getOpcode() == Op1.getOpcode()) {
5796 // Avoid missing important xor optimizations.
5797 SDValue Tmp = visitXOR(TheXor);
5798 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5799 DEBUG(dbgs() << "\nReplacing.8 ";
5801 dbgs() << "\nWith: ";
5802 Tmp.getNode()->dump(&DAG);
5804 WorkListRemover DeadNodes(*this);
5805 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5806 removeFromWorkList(TheXor);
5807 DAG.DeleteNode(TheXor);
5808 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5809 MVT::Other, Chain, Tmp, N2);
5813 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5815 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5816 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5817 Op0.getOpcode() == ISD::XOR) {
5818 TheXor = Op0.getNode();
5822 EVT SetCCVT = N1.getValueType();
5824 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5825 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5828 Equal ? ISD::SETEQ : ISD::SETNE);
5829 // Replace the uses of XOR with SETCC
5830 WorkListRemover DeadNodes(*this);
5831 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5832 removeFromWorkList(N1.getNode());
5833 DAG.DeleteNode(N1.getNode());
5834 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5835 MVT::Other, Chain, SetCC, N2);
5842 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5844 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5845 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5846 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5848 // If N is a constant we could fold this into a fallthrough or unconditional
5849 // branch. However that doesn't happen very often in normal code, because
5850 // Instcombine/SimplifyCFG should have handled the available opportunities.
5851 // If we did this folding here, it would be necessary to update the
5852 // MachineBasicBlock CFG, which is awkward.
5854 // Use SimplifySetCC to simplify SETCC's.
5855 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5856 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5858 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5860 // fold to a simpler setcc
5861 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5862 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5863 N->getOperand(0), Simp.getOperand(2),
5864 Simp.getOperand(0), Simp.getOperand(1),
5870 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5871 /// pre-indexed load / store when the base pointer is an add or subtract
5872 /// and it has other uses besides the load / store. After the
5873 /// transformation, the new indexed load / store has effectively folded
5874 /// the add / subtract in and all of its other uses are redirected to the
5875 /// new load / store.
5876 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5877 if (Level < AfterLegalizeDAG)
5883 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5884 if (LD->isIndexed())
5886 VT = LD->getMemoryVT();
5887 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5888 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5890 Ptr = LD->getBasePtr();
5891 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5892 if (ST->isIndexed())
5894 VT = ST->getMemoryVT();
5895 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5896 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5898 Ptr = ST->getBasePtr();
5904 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5905 // out. There is no reason to make this a preinc/predec.
5906 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5907 Ptr.getNode()->hasOneUse())
5910 // Ask the target to do addressing mode selection.
5913 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5914 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5916 // Don't create a indexed load / store with zero offset.
5917 if (isa<ConstantSDNode>(Offset) &&
5918 cast<ConstantSDNode>(Offset)->isNullValue())
5921 // Try turning it into a pre-indexed load / store except when:
5922 // 1) The new base ptr is a frame index.
5923 // 2) If N is a store and the new base ptr is either the same as or is a
5924 // predecessor of the value being stored.
5925 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5926 // that would create a cycle.
5927 // 4) All uses are load / store ops that use it as old base ptr.
5929 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5930 // (plus the implicit offset) to a register to preinc anyway.
5931 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5936 SDValue Val = cast<StoreSDNode>(N)->getValue();
5937 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5941 // Now check for #3 and #4.
5942 bool RealUse = false;
5944 // Caches for hasPredecessorHelper
5945 SmallPtrSet<const SDNode *, 32> Visited;
5946 SmallVector<const SDNode *, 16> Worklist;
5948 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5949 E = Ptr.getNode()->use_end(); I != E; ++I) {
5953 if (N->hasPredecessorHelper(Use, Visited, Worklist))
5956 if (!((Use->getOpcode() == ISD::LOAD &&
5957 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5958 (Use->getOpcode() == ISD::STORE &&
5959 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5968 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5969 BasePtr, Offset, AM);
5971 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5972 BasePtr, Offset, AM);
5975 DEBUG(dbgs() << "\nReplacing.4 ";
5977 dbgs() << "\nWith: ";
5978 Result.getNode()->dump(&DAG);
5980 WorkListRemover DeadNodes(*this);
5982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5984 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5987 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5991 // Finally, since the node is now dead, remove it from the graph.
5994 // Replace the uses of Ptr with uses of the updated base value.
5995 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5997 removeFromWorkList(Ptr.getNode());
5998 DAG.DeleteNode(Ptr.getNode());
6003 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6004 /// add / sub of the base pointer node into a post-indexed load / store.
6005 /// The transformation folded the add / subtract into the new indexed
6006 /// load / store effectively and all of its uses are redirected to the
6007 /// new load / store.
6008 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6009 if (Level < AfterLegalizeDAG)
6015 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6016 if (LD->isIndexed())
6018 VT = LD->getMemoryVT();
6019 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6020 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6022 Ptr = LD->getBasePtr();
6023 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6024 if (ST->isIndexed())
6026 VT = ST->getMemoryVT();
6027 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6028 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6030 Ptr = ST->getBasePtr();
6036 if (Ptr.getNode()->hasOneUse())
6039 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6040 E = Ptr.getNode()->use_end(); I != E; ++I) {
6043 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6048 ISD::MemIndexedMode AM = ISD::UNINDEXED;
6049 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6050 // Don't create a indexed load / store with zero offset.
6051 if (isa<ConstantSDNode>(Offset) &&
6052 cast<ConstantSDNode>(Offset)->isNullValue())
6055 // Try turning it into a post-indexed load / store except when
6056 // 1) All uses are load / store ops that use it as base ptr.
6057 // 2) Op must be independent of N, i.e. Op is neither a predecessor
6058 // nor a successor of N. Otherwise, if Op is folded that would
6061 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6065 bool TryNext = false;
6066 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6067 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6069 if (Use == Ptr.getNode())
6072 // If all the uses are load / store addresses, then don't do the
6074 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6075 bool RealUse = false;
6076 for (SDNode::use_iterator III = Use->use_begin(),
6077 EEE = Use->use_end(); III != EEE; ++III) {
6078 SDNode *UseUse = *III;
6079 if (!((UseUse->getOpcode() == ISD::LOAD &&
6080 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
6081 (UseUse->getOpcode() == ISD::STORE &&
6082 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
6097 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6098 SDValue Result = isLoad
6099 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6100 BasePtr, Offset, AM)
6101 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6102 BasePtr, Offset, AM);
6105 DEBUG(dbgs() << "\nReplacing.5 ";
6107 dbgs() << "\nWith: ";
6108 Result.getNode()->dump(&DAG);
6110 WorkListRemover DeadNodes(*this);
6112 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
6114 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
6117 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
6121 // Finally, since the node is now dead, remove it from the graph.
6124 // Replace the uses of Use with uses of the updated base value.
6125 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6126 Result.getValue(isLoad ? 1 : 0),
6128 removeFromWorkList(Op);
6138 SDValue DAGCombiner::visitLOAD(SDNode *N) {
6139 LoadSDNode *LD = cast<LoadSDNode>(N);
6140 SDValue Chain = LD->getChain();
6141 SDValue Ptr = LD->getBasePtr();
6143 // If load is not volatile and there are no uses of the loaded value (and
6144 // the updated indexed value in case of indexed loads), change uses of the
6145 // chain value into uses of the chain input (i.e. delete the dead load).
6146 if (!LD->isVolatile()) {
6147 if (N->getValueType(1) == MVT::Other) {
6149 if (N->hasNUsesOfValue(0, 0)) {
6150 // It's not safe to use the two value CombineTo variant here. e.g.
6151 // v1, chain2 = load chain1, loc
6152 // v2, chain3 = load chain2, loc
6154 // Now we replace use of chain2 with chain1. This makes the second load
6155 // isomorphic to the one we are deleting, and thus makes this load live.
6156 DEBUG(dbgs() << "\nReplacing.6 ";
6158 dbgs() << "\nWith chain: ";
6159 Chain.getNode()->dump(&DAG);
6161 WorkListRemover DeadNodes(*this);
6162 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
6164 if (N->use_empty()) {
6165 removeFromWorkList(N);
6169 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6173 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6174 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
6175 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6176 DEBUG(dbgs() << "\nReplacing.7 ";
6178 dbgs() << "\nWith: ";
6179 Undef.getNode()->dump(&DAG);
6180 dbgs() << " and 2 other values\n");
6181 WorkListRemover DeadNodes(*this);
6182 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
6183 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6184 DAG.getUNDEF(N->getValueType(1)),
6186 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
6187 removeFromWorkList(N);
6189 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6194 // If this load is directly stored, replace the load value with the stored
6196 // TODO: Handle store large -> read small portion.
6197 // TODO: Handle TRUNCSTORE/LOADEXT
6198 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6199 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6200 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6201 if (PrevST->getBasePtr() == Ptr &&
6202 PrevST->getValue().getValueType() == N->getValueType(0))
6203 return CombineTo(N, Chain.getOperand(1), Chain);
6207 // Try to infer better alignment information than the load already has.
6208 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6209 unsigned ABIAlign = TLI.getTargetData()->
6210 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
6211 unsigned LDAlign = LD->getAlignment();
6212 // Do not touch loads with explicit alignments that are smaller than ABI
6213 // alignment to avoid breaking loads from "packed" types.
6214 if (!LDAlign || LDAlign >= ABIAlign) {
6215 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6216 if (Align > LDAlign)
6217 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6218 LD->getValueType(0),
6219 Chain, Ptr, LD->getPointerInfo(),
6221 LD->isVolatile(), LD->isNonTemporal(), Align);
6227 // Walk up chain skipping non-aliasing memory nodes.
6228 SDValue BetterChain = FindBetterChain(N, Chain);
6230 // If there is a better chain.
6231 if (Chain != BetterChain) {
6234 // Replace the chain to void dependency.
6235 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6236 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6237 BetterChain, Ptr, LD->getPointerInfo(),
6238 LD->isVolatile(), LD->isNonTemporal(),
6239 LD->isInvariant(), LD->getAlignment());
6241 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6242 LD->getValueType(0),
6243 BetterChain, Ptr, LD->getPointerInfo(),
6246 LD->isNonTemporal(),
6247 LD->getAlignment());
6250 // Create token factor to keep old chain connected.
6251 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6252 MVT::Other, Chain, ReplLoad.getValue(1));
6254 // Make sure the new and old chains are cleaned up.
6255 AddToWorkList(Token.getNode());
6257 // Replace uses with load result and token factor. Don't add users
6259 return CombineTo(N, ReplLoad.getValue(0), Token, false);
6263 // Try transforming N to an indexed load.
6264 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6265 return SDValue(N, 0);
6270 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6271 /// load is having specific bytes cleared out. If so, return the byte size
6272 /// being masked out and the shift amount.
6273 static std::pair<unsigned, unsigned>
6274 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6275 std::pair<unsigned, unsigned> Result(0, 0);
6277 // Check for the structure we're looking for.
6278 if (V->getOpcode() != ISD::AND ||
6279 !isa<ConstantSDNode>(V->getOperand(1)) ||
6280 !ISD::isNormalLoad(V->getOperand(0).getNode()))
6283 // Check the chain and pointer.
6284 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6285 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
6287 // The store should be chained directly to the load or be an operand of a
6289 if (LD == Chain.getNode())
6291 else if (Chain->getOpcode() != ISD::TokenFactor)
6292 return Result; // Fail.
6295 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6296 if (Chain->getOperand(i).getNode() == LD) {
6300 if (!isOk) return Result;
6303 // This only handles simple types.
6304 if (V.getValueType() != MVT::i16 &&
6305 V.getValueType() != MVT::i32 &&
6306 V.getValueType() != MVT::i64)
6309 // Check the constant mask. Invert it so that the bits being masked out are
6310 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
6311 // follow the sign bit for uniformity.
6312 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6313 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6314 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
6315 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6316 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
6317 if (NotMaskLZ == 64) return Result; // All zero mask.
6319 // See if we have a continuous run of bits. If so, we have 0*1+0*
6320 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6323 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6324 if (V.getValueType() != MVT::i64 && NotMaskLZ)
6325 NotMaskLZ -= 64-V.getValueSizeInBits();
6327 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6328 switch (MaskedBytes) {
6332 default: return Result; // All one mask, or 5-byte mask.
6335 // Verify that the first bit starts at a multiple of mask so that the access
6336 // is aligned the same as the access width.
6337 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6339 Result.first = MaskedBytes;
6340 Result.second = NotMaskTZ/8;
6345 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6346 /// provides a value as specified by MaskInfo. If so, replace the specified
6347 /// store with a narrower store of truncated IVal.
6349 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6350 SDValue IVal, StoreSDNode *St,
6352 unsigned NumBytes = MaskInfo.first;
6353 unsigned ByteShift = MaskInfo.second;
6354 SelectionDAG &DAG = DC->getDAG();
6356 // Check to see if IVal is all zeros in the part being masked in by the 'or'
6357 // that uses this. If not, this is not a replacement.
6358 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6359 ByteShift*8, (ByteShift+NumBytes)*8);
6360 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6362 // Check that it is legal on the target to do this. It is legal if the new
6363 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6365 MVT VT = MVT::getIntegerVT(NumBytes*8);
6366 if (!DC->isTypeLegal(VT))
6369 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
6370 // shifted by ByteShift and truncated down to NumBytes.
6372 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6373 DAG.getConstant(ByteShift*8,
6374 DC->getShiftAmountTy(IVal.getValueType())));
6376 // Figure out the offset for the store and the alignment of the access.
6378 unsigned NewAlign = St->getAlignment();
6380 if (DAG.getTargetLoweringInfo().isLittleEndian())
6381 StOffset = ByteShift;
6383 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6385 SDValue Ptr = St->getBasePtr();
6387 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6388 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6389 NewAlign = MinAlign(NewAlign, StOffset);
6392 // Truncate down to the new size.
6393 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6396 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6397 St->getPointerInfo().getWithOffset(StOffset),
6398 false, false, NewAlign).getNode();
6402 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6403 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6404 /// of the loaded bits, try narrowing the load and store if it would end up
6405 /// being a win for performance or code size.
6406 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6407 StoreSDNode *ST = cast<StoreSDNode>(N);
6408 if (ST->isVolatile())
6411 SDValue Chain = ST->getChain();
6412 SDValue Value = ST->getValue();
6413 SDValue Ptr = ST->getBasePtr();
6414 EVT VT = Value.getValueType();
6416 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6419 unsigned Opc = Value.getOpcode();
6421 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6422 // is a byte mask indicating a consecutive number of bytes, check to see if
6423 // Y is known to provide just those bytes. If so, we try to replace the
6424 // load + replace + store sequence with a single (narrower) store, which makes
6426 if (Opc == ISD::OR) {
6427 std::pair<unsigned, unsigned> MaskedLoad;
6428 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6429 if (MaskedLoad.first)
6430 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6431 Value.getOperand(1), ST,this))
6432 return SDValue(NewST, 0);
6434 // Or is commutative, so try swapping X and Y.
6435 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6436 if (MaskedLoad.first)
6437 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6438 Value.getOperand(0), ST,this))
6439 return SDValue(NewST, 0);
6442 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6443 Value.getOperand(1).getOpcode() != ISD::Constant)
6446 SDValue N0 = Value.getOperand(0);
6447 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6448 Chain == SDValue(N0.getNode(), 1)) {
6449 LoadSDNode *LD = cast<LoadSDNode>(N0);
6450 if (LD->getBasePtr() != Ptr ||
6451 LD->getPointerInfo().getAddrSpace() !=
6452 ST->getPointerInfo().getAddrSpace())
6455 // Find the type to narrow it the load / op / store to.
6456 SDValue N1 = Value.getOperand(1);
6457 unsigned BitWidth = N1.getValueSizeInBits();
6458 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6459 if (Opc == ISD::AND)
6460 Imm ^= APInt::getAllOnesValue(BitWidth);
6461 if (Imm == 0 || Imm.isAllOnesValue())
6463 unsigned ShAmt = Imm.countTrailingZeros();
6464 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6465 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6466 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6467 while (NewBW < BitWidth &&
6468 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6469 TLI.isNarrowingProfitable(VT, NewVT))) {
6470 NewBW = NextPowerOf2(NewBW);
6471 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6473 if (NewBW >= BitWidth)
6476 // If the lsb changed does not start at the type bitwidth boundary,
6477 // start at the previous one.
6479 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6480 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6481 if ((Imm & Mask) == Imm) {
6482 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6483 if (Opc == ISD::AND)
6484 NewImm ^= APInt::getAllOnesValue(NewBW);
6485 uint64_t PtrOff = ShAmt / 8;
6486 // For big endian targets, we need to adjust the offset to the pointer to
6487 // load the correct bytes.
6488 if (TLI.isBigEndian())
6489 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6491 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6492 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6493 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6496 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6497 Ptr.getValueType(), Ptr,
6498 DAG.getConstant(PtrOff, Ptr.getValueType()));
6499 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6500 LD->getChain(), NewPtr,
6501 LD->getPointerInfo().getWithOffset(PtrOff),
6502 LD->isVolatile(), LD->isNonTemporal(),
6503 LD->isInvariant(), NewAlign);
6504 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6505 DAG.getConstant(NewImm, NewVT));
6506 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6508 ST->getPointerInfo().getWithOffset(PtrOff),
6509 false, false, NewAlign);
6511 AddToWorkList(NewPtr.getNode());
6512 AddToWorkList(NewLD.getNode());
6513 AddToWorkList(NewVal.getNode());
6514 WorkListRemover DeadNodes(*this);
6515 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6525 /// TransformFPLoadStorePair - For a given floating point load / store pair,
6526 /// if the load value isn't used by any other operations, then consider
6527 /// transforming the pair to integer load / store operations if the target
6528 /// deems the transformation profitable.
6529 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6530 StoreSDNode *ST = cast<StoreSDNode>(N);
6531 SDValue Chain = ST->getChain();
6532 SDValue Value = ST->getValue();
6533 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6534 Value.hasOneUse() &&
6535 Chain == SDValue(Value.getNode(), 1)) {
6536 LoadSDNode *LD = cast<LoadSDNode>(Value);
6537 EVT VT = LD->getMemoryVT();
6538 if (!VT.isFloatingPoint() ||
6539 VT != ST->getMemoryVT() ||
6540 LD->isNonTemporal() ||
6541 ST->isNonTemporal() ||
6542 LD->getPointerInfo().getAddrSpace() != 0 ||
6543 ST->getPointerInfo().getAddrSpace() != 0)
6546 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6547 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6548 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6549 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6550 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6553 unsigned LDAlign = LD->getAlignment();
6554 unsigned STAlign = ST->getAlignment();
6555 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6556 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6557 if (LDAlign < ABIAlign || STAlign < ABIAlign)
6560 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6561 LD->getChain(), LD->getBasePtr(),
6562 LD->getPointerInfo(),
6563 false, false, false, LDAlign);
6565 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6566 NewLD, ST->getBasePtr(),
6567 ST->getPointerInfo(),
6568 false, false, STAlign);
6570 AddToWorkList(NewLD.getNode());
6571 AddToWorkList(NewST.getNode());
6572 WorkListRemover DeadNodes(*this);
6573 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
6582 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6583 StoreSDNode *ST = cast<StoreSDNode>(N);
6584 SDValue Chain = ST->getChain();
6585 SDValue Value = ST->getValue();
6586 SDValue Ptr = ST->getBasePtr();
6588 // If this is a store of a bit convert, store the input value if the
6589 // resultant store does not need a higher alignment than the original.
6590 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6591 ST->isUnindexed()) {
6592 unsigned OrigAlign = ST->getAlignment();
6593 EVT SVT = Value.getOperand(0).getValueType();
6594 unsigned Align = TLI.getTargetData()->
6595 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6596 if (Align <= OrigAlign &&
6597 ((!LegalOperations && !ST->isVolatile()) ||
6598 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6599 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6600 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6601 ST->isNonTemporal(), OrigAlign);
6604 // Turn 'store undef, Ptr' -> nothing.
6605 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
6608 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6609 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6610 // NOTE: If the original store is volatile, this transform must not increase
6611 // the number of stores. For example, on x86-32 an f64 can be stored in one
6612 // processor operation but an i64 (which is not legal) requires two. So the
6613 // transform should not be done in this case.
6614 if (Value.getOpcode() != ISD::TargetConstantFP) {
6616 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6617 default: llvm_unreachable("Unknown FP type");
6618 case MVT::f80: // We don't do this for these yet.
6623 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6624 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6625 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6626 bitcastToAPInt().getZExtValue(), MVT::i32);
6627 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6628 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6629 ST->isNonTemporal(), ST->getAlignment());
6633 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6634 !ST->isVolatile()) ||
6635 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6636 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6637 getZExtValue(), MVT::i64);
6638 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6639 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6640 ST->isNonTemporal(), ST->getAlignment());
6643 if (!ST->isVolatile() &&
6644 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6645 // Many FP stores are not made apparent until after legalize, e.g. for
6646 // argument passing. Since this is so common, custom legalize the
6647 // 64-bit integer store into two 32-bit stores.
6648 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6649 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6650 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6651 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6653 unsigned Alignment = ST->getAlignment();
6654 bool isVolatile = ST->isVolatile();
6655 bool isNonTemporal = ST->isNonTemporal();
6657 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6658 Ptr, ST->getPointerInfo(),
6659 isVolatile, isNonTemporal,
6660 ST->getAlignment());
6661 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6662 DAG.getConstant(4, Ptr.getValueType()));
6663 Alignment = MinAlign(Alignment, 4U);
6664 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6665 Ptr, ST->getPointerInfo().getWithOffset(4),
6666 isVolatile, isNonTemporal,
6668 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6677 // Try to infer better alignment information than the store already has.
6678 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6679 unsigned ABIAlign = TLI.getTargetData()->
6680 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
6681 unsigned STAlign = ST->getAlignment();
6682 // Do not touch stores with explicit alignments that are smaller than ABI
6683 // alignment to avoid breaking stores from "packed" types.
6684 if (!STAlign || STAlign >= ABIAlign) {
6685 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6686 if (Align > STAlign)
6687 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6688 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6689 ST->isVolatile(), ST->isNonTemporal(),Align);
6694 // Try transforming a pair floating point load / store ops to integer
6695 // load / store ops.
6696 SDValue NewST = TransformFPLoadStorePair(N);
6697 if (NewST.getNode())
6701 // Walk up chain skipping non-aliasing memory nodes.
6702 SDValue BetterChain = FindBetterChain(N, Chain);
6704 // If there is a better chain.
6705 if (Chain != BetterChain) {
6708 // Replace the chain to avoid dependency.
6709 if (ST->isTruncatingStore()) {
6710 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6711 ST->getPointerInfo(),
6712 ST->getMemoryVT(), ST->isVolatile(),
6713 ST->isNonTemporal(), ST->getAlignment());
6715 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6716 ST->getPointerInfo(),
6717 ST->isVolatile(), ST->isNonTemporal(),
6718 ST->getAlignment());
6721 // Create token to keep both nodes around.
6722 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6723 MVT::Other, Chain, ReplStore);
6725 // Make sure the new and old chains are cleaned up.
6726 AddToWorkList(Token.getNode());
6728 // Don't add users to work list.
6729 return CombineTo(N, Token, false);
6733 // Try transforming N to an indexed store.
6734 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6735 return SDValue(N, 0);
6737 // FIXME: is there such a thing as a truncating indexed store?
6738 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6739 Value.getValueType().isInteger()) {
6740 // See if we can simplify the input to this truncstore with knowledge that
6741 // only the low bits are being used. For example:
6742 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6744 GetDemandedBits(Value,
6745 APInt::getLowBitsSet(
6746 Value.getValueType().getScalarType().getSizeInBits(),
6747 ST->getMemoryVT().getScalarType().getSizeInBits()));
6748 AddToWorkList(Value.getNode());
6749 if (Shorter.getNode())
6750 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6751 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6752 ST->isVolatile(), ST->isNonTemporal(),
6753 ST->getAlignment());
6755 // Otherwise, see if we can simplify the operation with
6756 // SimplifyDemandedBits, which only works if the value has a single use.
6757 if (SimplifyDemandedBits(Value,
6758 APInt::getLowBitsSet(
6759 Value.getValueType().getScalarType().getSizeInBits(),
6760 ST->getMemoryVT().getScalarType().getSizeInBits())))
6761 return SDValue(N, 0);
6764 // If this is a load followed by a store to the same location, then the store
6766 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6767 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6768 ST->isUnindexed() && !ST->isVolatile() &&
6769 // There can't be any side effects between the load and store, such as
6771 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6772 // The store is dead, remove it.
6777 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6778 // truncating store. We can do this even if this is already a truncstore.
6779 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6780 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6781 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6782 ST->getMemoryVT())) {
6783 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6784 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6785 ST->isVolatile(), ST->isNonTemporal(),
6786 ST->getAlignment());
6789 return ReduceLoadOpStoreWidth(N);
6792 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6793 SDValue InVec = N->getOperand(0);
6794 SDValue InVal = N->getOperand(1);
6795 SDValue EltNo = N->getOperand(2);
6796 DebugLoc dl = N->getDebugLoc();
6798 // If the inserted element is an UNDEF, just use the input vector.
6799 if (InVal.getOpcode() == ISD::UNDEF)
6802 EVT VT = InVec.getValueType();
6804 // If we can't generate a legal BUILD_VECTOR, exit
6805 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
6808 // Check that we know which element is being inserted
6809 if (!isa<ConstantSDNode>(EltNo))
6811 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6813 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
6814 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
6816 SmallVector<SDValue, 8> Ops;
6817 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
6818 Ops.append(InVec.getNode()->op_begin(),
6819 InVec.getNode()->op_end());
6820 } else if (InVec.getOpcode() == ISD::UNDEF) {
6821 unsigned NElts = VT.getVectorNumElements();
6822 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
6827 // Insert the element
6828 if (Elt < Ops.size()) {
6829 // All the operands of BUILD_VECTOR must have the same type;
6830 // we enforce that here.
6831 EVT OpVT = Ops[0].getValueType();
6832 if (InVal.getValueType() != OpVT)
6833 InVal = OpVT.bitsGT(InVal.getValueType()) ?
6834 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
6835 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
6839 // Return the new vector
6840 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6841 VT, &Ops[0], Ops.size());
6844 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6845 // (vextract (scalar_to_vector val, 0) -> val
6846 SDValue InVec = N->getOperand(0);
6848 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6849 // Check if the result type doesn't match the inserted element type. A
6850 // SCALAR_TO_VECTOR may truncate the inserted element and the
6851 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6852 SDValue InOp = InVec.getOperand(0);
6853 EVT NVT = N->getValueType(0);
6854 if (InOp.getValueType() != NVT) {
6855 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6856 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6861 // Perform only after legalization to ensure build_vector / vector_shuffle
6862 // optimizations have already been done.
6863 if (!LegalOperations) return SDValue();
6865 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6866 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6867 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6868 SDValue EltNo = N->getOperand(1);
6870 if (isa<ConstantSDNode>(EltNo)) {
6871 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6872 bool NewLoad = false;
6873 bool BCNumEltsChanged = false;
6874 EVT VT = InVec.getValueType();
6875 EVT ExtVT = VT.getVectorElementType();
6878 if (InVec.getOpcode() == ISD::BITCAST) {
6879 EVT BCVT = InVec.getOperand(0).getValueType();
6880 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6882 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6883 BCNumEltsChanged = true;
6884 InVec = InVec.getOperand(0);
6885 ExtVT = BCVT.getVectorElementType();
6889 LoadSDNode *LN0 = NULL;
6890 const ShuffleVectorSDNode *SVN = NULL;
6891 if (ISD::isNormalLoad(InVec.getNode())) {
6892 LN0 = cast<LoadSDNode>(InVec);
6893 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6894 InVec.getOperand(0).getValueType() == ExtVT &&
6895 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6896 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6897 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6898 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6900 // (load $addr+1*size)
6902 // If the bit convert changed the number of elements, it is unsafe
6903 // to examine the mask.
6904 if (BCNumEltsChanged)
6907 // Select the input vector, guarding against out of range extract vector.
6908 unsigned NumElems = VT.getVectorNumElements();
6909 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6910 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6912 if (InVec.getOpcode() == ISD::BITCAST)
6913 InVec = InVec.getOperand(0);
6914 if (ISD::isNormalLoad(InVec.getNode())) {
6915 LN0 = cast<LoadSDNode>(InVec);
6916 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6920 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
6923 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6925 return DAG.getUNDEF(LVT);
6927 unsigned Align = LN0->getAlignment();
6929 // Check the resultant load doesn't need a higher alignment than the
6933 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6935 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6941 SDValue NewPtr = LN0->getBasePtr();
6942 unsigned PtrOff = 0;
6945 PtrOff = LVT.getSizeInBits() * Elt / 8;
6946 EVT PtrType = NewPtr.getValueType();
6947 if (TLI.isBigEndian())
6948 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6949 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6950 DAG.getConstant(PtrOff, PtrType));
6953 // The replacement we need to do here is a little tricky: we need to
6954 // replace an extractelement of a load with a load.
6955 // Use ReplaceAllUsesOfValuesWith to do the replacement.
6956 SDValue Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6957 LN0->getPointerInfo().getWithOffset(PtrOff),
6958 LN0->isVolatile(), LN0->isNonTemporal(),
6959 LN0->isInvariant(), Align);
6960 WorkListRemover DeadNodes(*this);
6961 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
6962 SDValue To[] = { Load.getValue(0), Load.getValue(1) };
6963 DAG.ReplaceAllUsesOfValuesWith(From, To, 2, &DeadNodes);
6964 // Since we're explcitly calling ReplaceAllUses, add the new node to the
6965 // worklist explicitly as well.
6966 AddToWorkList(Load.getNode());
6967 // Make sure to revisit this node to clean it up; it will usually be dead.
6969 return SDValue(N, 0);
6975 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6976 unsigned NumInScalars = N->getNumOperands();
6977 DebugLoc dl = N->getDebugLoc();
6978 EVT VT = N->getValueType(0);
6979 // Check to see if this is a BUILD_VECTOR of a bunch of values
6980 // which come from any_extend or zero_extend nodes. If so, we can create
6981 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
6982 // optimizations. We do not handle sign-extend because we can't fill the sign
6984 EVT SourceType = MVT::Other;
6985 bool allAnyExt = true;
6986 for (unsigned i = 0; i < NumInScalars; ++i) {
6987 SDValue In = N->getOperand(i);
6988 // Ignore undef inputs.
6989 if (In.getOpcode() == ISD::UNDEF) continue;
6991 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
6992 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
6994 // Abort if the element is not an extension.
6995 if (!ZeroExt && !AnyExt) {
6996 SourceType = MVT::Other;
7000 // The input is a ZeroExt or AnyExt. Check the original type.
7001 EVT InTy = In.getOperand(0).getValueType();
7003 // Check that all of the widened source types are the same.
7004 if (SourceType == MVT::Other)
7007 else if (InTy != SourceType) {
7008 // Multiple income types. Abort.
7009 SourceType = MVT::Other;
7013 // Check if all of the extends are ANY_EXTENDs.
7014 allAnyExt &= AnyExt;
7018 // In order to have valid types, all of the inputs must be extended from the
7019 // same source type and all of the inputs must be any or zero extend.
7020 // Scalar sizes must be a power of two.
7021 EVT OutScalarTy = N->getValueType(0).getScalarType();
7022 bool validTypes = SourceType != MVT::Other &&
7023 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7024 isPowerOf2_32(SourceType.getSizeInBits());
7026 // We perform this optimization post type-legalization because
7027 // the type-legalizer often scalarizes integer-promoted vectors.
7028 // Performing this optimization before may create bit-casts which
7029 // will be type-legalized to complex code sequences.
7030 // We perform this optimization only before the operation legalizer because we
7031 // may introduce illegal operations.
7032 if (LegalTypes && !LegalOperations && validTypes) {
7033 bool isLE = TLI.isLittleEndian();
7034 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7035 assert(ElemRatio > 1 && "Invalid element size ratio");
7036 SDValue Filler = allAnyExt ? DAG.getUNDEF(SourceType):
7037 DAG.getConstant(0, SourceType);
7039 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7040 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7042 // Populate the new build_vector
7043 for (unsigned i=0; i < N->getNumOperands(); ++i) {
7044 SDValue Cast = N->getOperand(i);
7045 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7046 Cast.getOpcode() == ISD::ZERO_EXTEND ||
7047 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7049 if (Cast.getOpcode() == ISD::UNDEF)
7050 In = DAG.getUNDEF(SourceType);
7052 In = Cast->getOperand(0);
7053 unsigned Index = isLE ? (i * ElemRatio) :
7054 (i * ElemRatio + (ElemRatio - 1));
7056 assert(Index < Ops.size() && "Invalid index");
7060 // The type of the new BUILD_VECTOR node.
7061 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7062 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7063 "Invalid vector size");
7064 // Check if the new vector type is legal.
7065 if (!isTypeLegal(VecVT)) return SDValue();
7067 // Make the new BUILD_VECTOR.
7068 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7069 VecVT, &Ops[0], Ops.size());
7071 // Bitcast to the desired type.
7072 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7075 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7076 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7077 // at most two distinct vectors, turn this into a shuffle node.
7078 SDValue VecIn1, VecIn2;
7079 for (unsigned i = 0; i != NumInScalars; ++i) {
7080 // Ignore undef inputs.
7081 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7083 // If this input is something other than a EXTRACT_VECTOR_ELT with a
7084 // constant index, bail out.
7085 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7086 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7087 VecIn1 = VecIn2 = SDValue(0, 0);
7091 // If the input vector type disagrees with the result of the build_vector,
7092 // we can't make a shuffle.
7093 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7094 if (ExtractedFromVec.getValueType() != VT) {
7095 VecIn1 = VecIn2 = SDValue(0, 0);
7099 // Otherwise, remember this. We allow up to two distinct input vectors.
7100 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7103 if (VecIn1.getNode() == 0) {
7104 VecIn1 = ExtractedFromVec;
7105 } else if (VecIn2.getNode() == 0) {
7106 VecIn2 = ExtractedFromVec;
7109 VecIn1 = VecIn2 = SDValue(0, 0);
7114 // If everything is good, we can make a shuffle operation.
7115 if (VecIn1.getNode()) {
7116 SmallVector<int, 8> Mask;
7117 for (unsigned i = 0; i != NumInScalars; ++i) {
7118 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7123 // If extracting from the first vector, just use the index directly.
7124 SDValue Extract = N->getOperand(i);
7125 SDValue ExtVal = Extract.getOperand(1);
7126 if (Extract.getOperand(0) == VecIn1) {
7127 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7128 if (ExtIndex > VT.getVectorNumElements())
7131 Mask.push_back(ExtIndex);
7135 // Otherwise, use InIdx + VecSize
7136 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7137 Mask.push_back(Idx+NumInScalars);
7140 // Add count and size info.
7141 if (!isTypeLegal(VT))
7144 // Return the new VECTOR_SHUFFLE node.
7147 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7148 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7154 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7155 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7156 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
7157 // inputs come from at most two distinct vectors, turn this into a shuffle
7160 // If we only have one input vector, we don't need to do any concatenation.
7161 if (N->getNumOperands() == 1)
7162 return N->getOperand(0);
7167 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7168 EVT NVT = N->getValueType(0);
7169 SDValue V = N->getOperand(0);
7171 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7172 // Handle only simple case where vector being inserted and vector
7173 // being extracted are of same type, and are half size of larger vectors.
7174 EVT BigVT = V->getOperand(0).getValueType();
7175 EVT SmallVT = V->getOperand(1).getValueType();
7176 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7180 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7182 // indicies are equal => V1
7183 // otherwise => (extract_subvec V1, ExtIdx)
7185 SDValue InsIdx = N->getOperand(1);
7186 SDValue ExtIdx = V->getOperand(2);
7188 if (InsIdx == ExtIdx)
7189 return V->getOperand(1);
7190 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7191 V->getOperand(0), N->getOperand(1));
7197 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7198 EVT VT = N->getValueType(0);
7199 unsigned NumElts = VT.getVectorNumElements();
7201 SDValue N0 = N->getOperand(0);
7203 assert(N0.getValueType().getVectorNumElements() == NumElts &&
7204 "Vector shuffle must be normalized in DAG");
7206 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
7208 // If it is a splat, check if the argument vector is another splat or a
7209 // build_vector with all scalar elements the same.
7210 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7211 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7212 SDNode *V = N0.getNode();
7214 // If this is a bit convert that changes the element type of the vector but
7215 // not the number of vector elements, look through it. Be careful not to
7216 // look though conversions that change things like v4f32 to v2f64.
7217 if (V->getOpcode() == ISD::BITCAST) {
7218 SDValue ConvInput = V->getOperand(0);
7219 if (ConvInput.getValueType().isVector() &&
7220 ConvInput.getValueType().getVectorNumElements() == NumElts)
7221 V = ConvInput.getNode();
7224 if (V->getOpcode() == ISD::BUILD_VECTOR) {
7225 assert(V->getNumOperands() == NumElts &&
7226 "BUILD_VECTOR has wrong number of operands");
7228 bool AllSame = true;
7229 for (unsigned i = 0; i != NumElts; ++i) {
7230 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7231 Base = V->getOperand(i);
7235 // Splat of <u, u, u, u>, return <u, u, u, u>
7236 if (!Base.getNode())
7238 for (unsigned i = 0; i != NumElts; ++i) {
7239 if (V->getOperand(i) != Base) {
7244 // Splat of <x, x, x, x>, return <x, x, x, x>
7252 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
7253 if (!TLI.getShouldFoldAtomicFences())
7256 SDValue atomic = N->getOperand(0);
7257 switch (atomic.getOpcode()) {
7258 case ISD::ATOMIC_CMP_SWAP:
7259 case ISD::ATOMIC_SWAP:
7260 case ISD::ATOMIC_LOAD_ADD:
7261 case ISD::ATOMIC_LOAD_SUB:
7262 case ISD::ATOMIC_LOAD_AND:
7263 case ISD::ATOMIC_LOAD_OR:
7264 case ISD::ATOMIC_LOAD_XOR:
7265 case ISD::ATOMIC_LOAD_NAND:
7266 case ISD::ATOMIC_LOAD_MIN:
7267 case ISD::ATOMIC_LOAD_MAX:
7268 case ISD::ATOMIC_LOAD_UMIN:
7269 case ISD::ATOMIC_LOAD_UMAX:
7275 SDValue fence = atomic.getOperand(0);
7276 if (fence.getOpcode() != ISD::MEMBARRIER)
7279 switch (atomic.getOpcode()) {
7280 case ISD::ATOMIC_CMP_SWAP:
7281 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7282 fence.getOperand(0),
7283 atomic.getOperand(1), atomic.getOperand(2),
7284 atomic.getOperand(3)), atomic.getResNo());
7285 case ISD::ATOMIC_SWAP:
7286 case ISD::ATOMIC_LOAD_ADD:
7287 case ISD::ATOMIC_LOAD_SUB:
7288 case ISD::ATOMIC_LOAD_AND:
7289 case ISD::ATOMIC_LOAD_OR:
7290 case ISD::ATOMIC_LOAD_XOR:
7291 case ISD::ATOMIC_LOAD_NAND:
7292 case ISD::ATOMIC_LOAD_MIN:
7293 case ISD::ATOMIC_LOAD_MAX:
7294 case ISD::ATOMIC_LOAD_UMIN:
7295 case ISD::ATOMIC_LOAD_UMAX:
7296 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7297 fence.getOperand(0),
7298 atomic.getOperand(1), atomic.getOperand(2)),
7305 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
7306 /// an AND to a vector_shuffle with the destination vector and a zero vector.
7307 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
7308 /// vector_shuffle V, Zero, <0, 4, 2, 4>
7309 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
7310 EVT VT = N->getValueType(0);
7311 DebugLoc dl = N->getDebugLoc();
7312 SDValue LHS = N->getOperand(0);
7313 SDValue RHS = N->getOperand(1);
7314 if (N->getOpcode() == ISD::AND) {
7315 if (RHS.getOpcode() == ISD::BITCAST)
7316 RHS = RHS.getOperand(0);
7317 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
7318 SmallVector<int, 8> Indices;
7319 unsigned NumElts = RHS.getNumOperands();
7320 for (unsigned i = 0; i != NumElts; ++i) {
7321 SDValue Elt = RHS.getOperand(i);
7322 if (!isa<ConstantSDNode>(Elt))
7324 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
7325 Indices.push_back(i);
7326 else if (cast<ConstantSDNode>(Elt)->isNullValue())
7327 Indices.push_back(NumElts);
7332 // Let's see if the target supports this vector_shuffle.
7333 EVT RVT = RHS.getValueType();
7334 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
7337 // Return the new VECTOR_SHUFFLE node.
7338 EVT EltVT = RVT.getVectorElementType();
7339 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
7340 DAG.getConstant(0, EltVT));
7341 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7342 RVT, &ZeroOps[0], ZeroOps.size());
7343 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
7344 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
7345 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
7352 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
7353 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
7354 // After legalize, the target may be depending on adds and other
7355 // binary ops to provide legal ways to construct constants or other
7356 // things. Simplifying them may result in a loss of legality.
7357 if (LegalOperations) return SDValue();
7359 assert(N->getValueType(0).isVector() &&
7360 "SimplifyVBinOp only works on vectors!");
7362 SDValue LHS = N->getOperand(0);
7363 SDValue RHS = N->getOperand(1);
7364 SDValue Shuffle = XformToShuffleWithZero(N);
7365 if (Shuffle.getNode()) return Shuffle;
7367 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
7369 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
7370 RHS.getOpcode() == ISD::BUILD_VECTOR) {
7371 SmallVector<SDValue, 8> Ops;
7372 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
7373 SDValue LHSOp = LHS.getOperand(i);
7374 SDValue RHSOp = RHS.getOperand(i);
7375 // If these two elements can't be folded, bail out.
7376 if ((LHSOp.getOpcode() != ISD::UNDEF &&
7377 LHSOp.getOpcode() != ISD::Constant &&
7378 LHSOp.getOpcode() != ISD::ConstantFP) ||
7379 (RHSOp.getOpcode() != ISD::UNDEF &&
7380 RHSOp.getOpcode() != ISD::Constant &&
7381 RHSOp.getOpcode() != ISD::ConstantFP))
7384 // Can't fold divide by zero.
7385 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
7386 N->getOpcode() == ISD::FDIV) {
7387 if ((RHSOp.getOpcode() == ISD::Constant &&
7388 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
7389 (RHSOp.getOpcode() == ISD::ConstantFP &&
7390 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
7394 EVT VT = LHSOp.getValueType();
7395 EVT RVT = RHSOp.getValueType();
7397 // Integer BUILD_VECTOR operands may have types larger than the element
7398 // size (e.g., when the element type is not legal). Prior to type
7399 // legalization, the types may not match between the two BUILD_VECTORS.
7400 // Truncate one of the operands to make them match.
7401 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
7402 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
7404 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
7408 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
7410 if (FoldOp.getOpcode() != ISD::UNDEF &&
7411 FoldOp.getOpcode() != ISD::Constant &&
7412 FoldOp.getOpcode() != ISD::ConstantFP)
7414 Ops.push_back(FoldOp);
7415 AddToWorkList(FoldOp.getNode());
7418 if (Ops.size() == LHS.getNumOperands())
7419 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7420 LHS.getValueType(), &Ops[0], Ops.size());
7426 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
7427 SDValue N1, SDValue N2){
7428 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
7430 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
7431 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7433 // If we got a simplified select_cc node back from SimplifySelectCC, then
7434 // break it down into a new SETCC node, and a new SELECT node, and then return
7435 // the SELECT node, since we were called with a SELECT node.
7436 if (SCC.getNode()) {
7437 // Check to see if we got a select_cc back (to turn into setcc/select).
7438 // Otherwise, just return whatever node we got back, like fabs.
7439 if (SCC.getOpcode() == ISD::SELECT_CC) {
7440 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
7442 SCC.getOperand(0), SCC.getOperand(1),
7444 AddToWorkList(SETCC.getNode());
7445 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
7446 SCC.getOperand(2), SCC.getOperand(3), SETCC);
7454 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
7455 /// are the two values being selected between, see if we can simplify the
7456 /// select. Callers of this should assume that TheSelect is deleted if this
7457 /// returns true. As such, they should return the appropriate thing (e.g. the
7458 /// node) back to the top-level of the DAG combiner loop to avoid it being
7460 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
7463 // Cannot simplify select with vector condition
7464 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
7466 // If this is a select from two identical things, try to pull the operation
7467 // through the select.
7468 if (LHS.getOpcode() != RHS.getOpcode() ||
7469 !LHS.hasOneUse() || !RHS.hasOneUse())
7472 // If this is a load and the token chain is identical, replace the select
7473 // of two loads with a load through a select of the address to load from.
7474 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
7475 // constants have been dropped into the constant pool.
7476 if (LHS.getOpcode() == ISD::LOAD) {
7477 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
7478 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
7480 // Token chains must be identical.
7481 if (LHS.getOperand(0) != RHS.getOperand(0) ||
7482 // Do not let this transformation reduce the number of volatile loads.
7483 LLD->isVolatile() || RLD->isVolatile() ||
7484 // If this is an EXTLOAD, the VT's must match.
7485 LLD->getMemoryVT() != RLD->getMemoryVT() ||
7486 // If this is an EXTLOAD, the kind of extension must match.
7487 (LLD->getExtensionType() != RLD->getExtensionType() &&
7488 // The only exception is if one of the extensions is anyext.
7489 LLD->getExtensionType() != ISD::EXTLOAD &&
7490 RLD->getExtensionType() != ISD::EXTLOAD) ||
7491 // FIXME: this discards src value information. This is
7492 // over-conservative. It would be beneficial to be able to remember
7493 // both potential memory locations. Since we are discarding
7494 // src value info, don't do the transformation if the memory
7495 // locations are not in the default address space.
7496 LLD->getPointerInfo().getAddrSpace() != 0 ||
7497 RLD->getPointerInfo().getAddrSpace() != 0)
7500 // Check that the select condition doesn't reach either load. If so,
7501 // folding this will induce a cycle into the DAG. If not, this is safe to
7502 // xform, so create a select of the addresses.
7504 if (TheSelect->getOpcode() == ISD::SELECT) {
7505 SDNode *CondNode = TheSelect->getOperand(0).getNode();
7506 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
7507 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
7509 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
7510 LLD->getBasePtr().getValueType(),
7511 TheSelect->getOperand(0), LLD->getBasePtr(),
7513 } else { // Otherwise SELECT_CC
7514 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
7515 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
7517 if ((LLD->hasAnyUseOfValue(1) &&
7518 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
7519 (LLD->hasAnyUseOfValue(1) &&
7520 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
7523 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
7524 LLD->getBasePtr().getValueType(),
7525 TheSelect->getOperand(0),
7526 TheSelect->getOperand(1),
7527 LLD->getBasePtr(), RLD->getBasePtr(),
7528 TheSelect->getOperand(4));
7532 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
7533 Load = DAG.getLoad(TheSelect->getValueType(0),
7534 TheSelect->getDebugLoc(),
7535 // FIXME: Discards pointer info.
7536 LLD->getChain(), Addr, MachinePointerInfo(),
7537 LLD->isVolatile(), LLD->isNonTemporal(),
7538 LLD->isInvariant(), LLD->getAlignment());
7540 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
7541 RLD->getExtensionType() : LLD->getExtensionType(),
7542 TheSelect->getDebugLoc(),
7543 TheSelect->getValueType(0),
7544 // FIXME: Discards pointer info.
7545 LLD->getChain(), Addr, MachinePointerInfo(),
7546 LLD->getMemoryVT(), LLD->isVolatile(),
7547 LLD->isNonTemporal(), LLD->getAlignment());
7550 // Users of the select now use the result of the load.
7551 CombineTo(TheSelect, Load);
7553 // Users of the old loads now use the new load's chain. We know the
7554 // old-load value is dead now.
7555 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
7556 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
7563 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
7564 /// where 'cond' is the comparison specified by CC.
7565 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
7566 SDValue N2, SDValue N3,
7567 ISD::CondCode CC, bool NotExtCompare) {
7568 // (x ? y : y) -> y.
7569 if (N2 == N3) return N2;
7571 EVT VT = N2.getValueType();
7572 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
7573 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
7574 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
7576 // Determine if the condition we're dealing with is constant
7577 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
7578 N0, N1, CC, DL, false);
7579 if (SCC.getNode()) AddToWorkList(SCC.getNode());
7580 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
7582 // fold select_cc true, x, y -> x
7583 if (SCCC && !SCCC->isNullValue())
7585 // fold select_cc false, x, y -> y
7586 if (SCCC && SCCC->isNullValue())
7589 // Check to see if we can simplify the select into an fabs node
7590 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
7591 // Allow either -0.0 or 0.0
7592 if (CFP->getValueAPF().isZero()) {
7593 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
7594 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
7595 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
7596 N2 == N3.getOperand(0))
7597 return DAG.getNode(ISD::FABS, DL, VT, N0);
7599 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
7600 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
7601 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
7602 N2.getOperand(0) == N3)
7603 return DAG.getNode(ISD::FABS, DL, VT, N3);
7607 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
7608 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
7609 // in it. This is a win when the constant is not otherwise available because
7610 // it replaces two constant pool loads with one. We only do this if the FP
7611 // type is known to be legal, because if it isn't, then we are before legalize
7612 // types an we want the other legalization to happen first (e.g. to avoid
7613 // messing with soft float) and if the ConstantFP is not legal, because if
7614 // it is legal, we may not need to store the FP constant in a constant pool.
7615 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
7616 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
7617 if (TLI.isTypeLegal(N2.getValueType()) &&
7618 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
7619 TargetLowering::Legal) &&
7620 // If both constants have multiple uses, then we won't need to do an
7621 // extra load, they are likely around in registers for other users.
7622 (TV->hasOneUse() || FV->hasOneUse())) {
7623 Constant *Elts[] = {
7624 const_cast<ConstantFP*>(FV->getConstantFPValue()),
7625 const_cast<ConstantFP*>(TV->getConstantFPValue())
7627 Type *FPTy = Elts[0]->getType();
7628 const TargetData &TD = *TLI.getTargetData();
7630 // Create a ConstantArray of the two constants.
7631 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
7632 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
7633 TD.getPrefTypeAlignment(FPTy));
7634 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
7636 // Get the offsets to the 0 and 1 element of the array so that we can
7637 // select between them.
7638 SDValue Zero = DAG.getIntPtrConstant(0);
7639 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
7640 SDValue One = DAG.getIntPtrConstant(EltSize);
7642 SDValue Cond = DAG.getSetCC(DL,
7643 TLI.getSetCCResultType(N0.getValueType()),
7645 AddToWorkList(Cond.getNode());
7646 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
7648 AddToWorkList(CstOffset.getNode());
7649 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
7651 AddToWorkList(CPIdx.getNode());
7652 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
7653 MachinePointerInfo::getConstantPool(), false,
7654 false, false, Alignment);
7659 // Check to see if we can perform the "gzip trick", transforming
7660 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7661 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7662 (N1C->isNullValue() || // (a < 0) ? b : 0
7663 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
7664 EVT XType = N0.getValueType();
7665 EVT AType = N2.getValueType();
7666 if (XType.bitsGE(AType)) {
7667 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7668 // single-bit constant.
7669 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7670 unsigned ShCtV = N2C->getAPIntValue().logBase2();
7671 ShCtV = XType.getSizeInBits()-ShCtV-1;
7672 SDValue ShCt = DAG.getConstant(ShCtV,
7673 getShiftAmountTy(N0.getValueType()));
7674 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7676 AddToWorkList(Shift.getNode());
7678 if (XType.bitsGT(AType)) {
7679 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7680 AddToWorkList(Shift.getNode());
7683 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7686 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7688 DAG.getConstant(XType.getSizeInBits()-1,
7689 getShiftAmountTy(N0.getValueType())));
7690 AddToWorkList(Shift.getNode());
7692 if (XType.bitsGT(AType)) {
7693 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7694 AddToWorkList(Shift.getNode());
7697 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7701 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7702 // where y is has a single bit set.
7703 // A plaintext description would be, we can turn the SELECT_CC into an AND
7704 // when the condition can be materialized as an all-ones register. Any
7705 // single bit-test can be materialized as an all-ones register with
7706 // shift-left and shift-right-arith.
7707 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7708 N0->getValueType(0) == VT &&
7709 N1C && N1C->isNullValue() &&
7710 N2C && N2C->isNullValue()) {
7711 SDValue AndLHS = N0->getOperand(0);
7712 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7713 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7714 // Shift the tested bit over the sign bit.
7715 APInt AndMask = ConstAndRHS->getAPIntValue();
7717 DAG.getConstant(AndMask.countLeadingZeros(),
7718 getShiftAmountTy(AndLHS.getValueType()));
7719 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7721 // Now arithmetic right shift it all the way over, so the result is either
7722 // all-ones, or zero.
7724 DAG.getConstant(AndMask.getBitWidth()-1,
7725 getShiftAmountTy(Shl.getValueType()));
7726 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7728 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7732 // fold select C, 16, 0 -> shl C, 4
7733 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7734 TLI.getBooleanContents(N0.getValueType().isVector()) ==
7735 TargetLowering::ZeroOrOneBooleanContent) {
7737 // If the caller doesn't want us to simplify this into a zext of a compare,
7739 if (NotExtCompare && N2C->getAPIntValue() == 1)
7742 // Get a SetCC of the condition
7743 // FIXME: Should probably make sure that setcc is legal if we ever have a
7744 // target where it isn't.
7746 // cast from setcc result type to select result type
7748 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7750 if (N2.getValueType().bitsLT(SCC.getValueType()))
7751 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7753 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7754 N2.getValueType(), SCC);
7756 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7757 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7758 N2.getValueType(), SCC);
7761 AddToWorkList(SCC.getNode());
7762 AddToWorkList(Temp.getNode());
7764 if (N2C->getAPIntValue() == 1)
7767 // shl setcc result by log2 n2c
7768 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7769 DAG.getConstant(N2C->getAPIntValue().logBase2(),
7770 getShiftAmountTy(Temp.getValueType())));
7773 // Check to see if this is the equivalent of setcc
7774 // FIXME: Turn all of these into setcc if setcc if setcc is legal
7775 // otherwise, go ahead with the folds.
7776 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7777 EVT XType = N0.getValueType();
7778 if (!LegalOperations ||
7779 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7780 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7781 if (Res.getValueType() != VT)
7782 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7786 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7787 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7788 (!LegalOperations ||
7789 TLI.isOperationLegal(ISD::CTLZ, XType))) {
7790 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7791 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7792 DAG.getConstant(Log2_32(XType.getSizeInBits()),
7793 getShiftAmountTy(Ctlz.getValueType())));
7795 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7796 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7797 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7798 XType, DAG.getConstant(0, XType), N0);
7799 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7800 return DAG.getNode(ISD::SRL, DL, XType,
7801 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7802 DAG.getConstant(XType.getSizeInBits()-1,
7803 getShiftAmountTy(XType)));
7805 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7806 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7807 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7808 DAG.getConstant(XType.getSizeInBits()-1,
7809 getShiftAmountTy(N0.getValueType())));
7810 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7814 // Check to see if this is an integer abs.
7815 // select_cc setg[te] X, 0, X, -X ->
7816 // select_cc setgt X, -1, X, -X ->
7817 // select_cc setl[te] X, 0, -X, X ->
7818 // select_cc setlt X, 1, -X, X ->
7819 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7821 ConstantSDNode *SubC = NULL;
7822 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7823 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7824 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7825 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7826 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7827 (N1C->isOne() && CC == ISD::SETLT)) &&
7828 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7829 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7831 EVT XType = N0.getValueType();
7832 if (SubC && SubC->isNullValue() && XType.isInteger()) {
7833 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7835 DAG.getConstant(XType.getSizeInBits()-1,
7836 getShiftAmountTy(N0.getValueType())));
7837 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7839 AddToWorkList(Shift.getNode());
7840 AddToWorkList(Add.getNode());
7841 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7848 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7849 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7850 SDValue N1, ISD::CondCode Cond,
7851 DebugLoc DL, bool foldBooleans) {
7852 TargetLowering::DAGCombinerInfo
7853 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7854 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7857 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7858 /// return a DAG expression to select that will generate the same value by
7859 /// multiplying by a magic number. See:
7860 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7861 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7862 std::vector<SDNode*> Built;
7863 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
7865 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7871 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7872 /// return a DAG expression to select that will generate the same value by
7873 /// multiplying by a magic number. See:
7874 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7875 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7876 std::vector<SDNode*> Built;
7877 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
7879 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7885 /// FindBaseOffset - Return true if base is a frame index, which is known not
7886 // to alias with anything but itself. Provides base object and offset as
7888 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7889 const GlobalValue *&GV, void *&CV) {
7890 // Assume it is a primitive operation.
7891 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7893 // If it's an adding a simple constant then integrate the offset.
7894 if (Base.getOpcode() == ISD::ADD) {
7895 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7896 Base = Base.getOperand(0);
7897 Offset += C->getZExtValue();
7901 // Return the underlying GlobalValue, and update the Offset. Return false
7902 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7903 // by multiple nodes with different offsets.
7904 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7905 GV = G->getGlobal();
7906 Offset += G->getOffset();
7910 // Return the underlying Constant value, and update the Offset. Return false
7911 // for ConstantSDNodes since the same constant pool entry may be represented
7912 // by multiple nodes with different offsets.
7913 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7914 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7915 : (void *)C->getConstVal();
7916 Offset += C->getOffset();
7919 // If it's any of the following then it can't alias with anything but itself.
7920 return isa<FrameIndexSDNode>(Base);
7923 /// isAlias - Return true if there is any possibility that the two addresses
7925 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7926 const Value *SrcValue1, int SrcValueOffset1,
7927 unsigned SrcValueAlign1,
7928 const MDNode *TBAAInfo1,
7929 SDValue Ptr2, int64_t Size2,
7930 const Value *SrcValue2, int SrcValueOffset2,
7931 unsigned SrcValueAlign2,
7932 const MDNode *TBAAInfo2) const {
7933 // If they are the same then they must be aliases.
7934 if (Ptr1 == Ptr2) return true;
7936 // Gather base node and offset information.
7937 SDValue Base1, Base2;
7938 int64_t Offset1, Offset2;
7939 const GlobalValue *GV1, *GV2;
7941 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7942 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7944 // If they have a same base address then check to see if they overlap.
7945 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7946 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7948 // It is possible for different frame indices to alias each other, mostly
7949 // when tail call optimization reuses return address slots for arguments.
7950 // To catch this case, look up the actual index of frame indices to compute
7951 // the real alias relationship.
7952 if (isFrameIndex1 && isFrameIndex2) {
7953 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7954 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7955 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7956 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7959 // Otherwise, if we know what the bases are, and they aren't identical, then
7960 // we know they cannot alias.
7961 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7964 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7965 // compared to the size and offset of the access, we may be able to prove they
7966 // do not alias. This check is conservative for now to catch cases created by
7967 // splitting vector types.
7968 if ((SrcValueAlign1 == SrcValueAlign2) &&
7969 (SrcValueOffset1 != SrcValueOffset2) &&
7970 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7971 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7972 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7974 // There is no overlap between these relatively aligned accesses of similar
7975 // size, return no alias.
7976 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7980 if (CombinerGlobalAA) {
7981 // Use alias analysis information.
7982 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7983 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7984 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7985 AliasAnalysis::AliasResult AAResult =
7986 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7987 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7988 if (AAResult == AliasAnalysis::NoAlias)
7992 // Otherwise we have to assume they alias.
7996 /// FindAliasInfo - Extracts the relevant alias information from the memory
7997 /// node. Returns true if the operand was a load.
7998 bool DAGCombiner::FindAliasInfo(SDNode *N,
7999 SDValue &Ptr, int64_t &Size,
8000 const Value *&SrcValue,
8001 int &SrcValueOffset,
8002 unsigned &SrcValueAlign,
8003 const MDNode *&TBAAInfo) const {
8004 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8005 Ptr = LD->getBasePtr();
8006 Size = LD->getMemoryVT().getSizeInBits() >> 3;
8007 SrcValue = LD->getSrcValue();
8008 SrcValueOffset = LD->getSrcValueOffset();
8009 SrcValueAlign = LD->getOriginalAlignment();
8010 TBAAInfo = LD->getTBAAInfo();
8013 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8014 Ptr = ST->getBasePtr();
8015 Size = ST->getMemoryVT().getSizeInBits() >> 3;
8016 SrcValue = ST->getSrcValue();
8017 SrcValueOffset = ST->getSrcValueOffset();
8018 SrcValueAlign = ST->getOriginalAlignment();
8019 TBAAInfo = ST->getTBAAInfo();
8022 llvm_unreachable("FindAliasInfo expected a memory operand");
8025 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8026 /// looking for aliasing nodes and adding them to the Aliases vector.
8027 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8028 SmallVector<SDValue, 8> &Aliases) {
8029 SmallVector<SDValue, 8> Chains; // List of chains to visit.
8030 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
8032 // Get alias information for node.
8035 const Value *SrcValue;
8037 unsigned SrcValueAlign;
8038 const MDNode *SrcTBAAInfo;
8039 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8040 SrcValueAlign, SrcTBAAInfo);
8043 Chains.push_back(OriginalChain);
8046 // Look at each chain and determine if it is an alias. If so, add it to the
8047 // aliases list. If not, then continue up the chain looking for the next
8049 while (!Chains.empty()) {
8050 SDValue Chain = Chains.back();
8053 // For TokenFactor nodes, look at each operand and only continue up the
8054 // chain until we find two aliases. If we've seen two aliases, assume we'll
8055 // find more and revert to original chain since the xform is unlikely to be
8058 // FIXME: The depth check could be made to return the last non-aliasing
8059 // chain we found before we hit a tokenfactor rather than the original
8061 if (Depth > 6 || Aliases.size() == 2) {
8063 Aliases.push_back(OriginalChain);
8067 // Don't bother if we've been before.
8068 if (!Visited.insert(Chain.getNode()))
8071 switch (Chain.getOpcode()) {
8072 case ISD::EntryToken:
8073 // Entry token is ideal chain operand, but handled in FindBetterChain.
8078 // Get alias information for Chain.
8081 const Value *OpSrcValue;
8082 int OpSrcValueOffset;
8083 unsigned OpSrcValueAlign;
8084 const MDNode *OpSrcTBAAInfo;
8085 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8086 OpSrcValue, OpSrcValueOffset,
8090 // If chain is alias then stop here.
8091 if (!(IsLoad && IsOpLoad) &&
8092 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8094 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8095 OpSrcValueAlign, OpSrcTBAAInfo)) {
8096 Aliases.push_back(Chain);
8098 // Look further up the chain.
8099 Chains.push_back(Chain.getOperand(0));
8105 case ISD::TokenFactor:
8106 // We have to check each of the operands of the token factor for "small"
8107 // token factors, so we queue them up. Adding the operands to the queue
8108 // (stack) in reverse order maintains the original order and increases the
8109 // likelihood that getNode will find a matching token factor (CSE.)
8110 if (Chain.getNumOperands() > 16) {
8111 Aliases.push_back(Chain);
8114 for (unsigned n = Chain.getNumOperands(); n;)
8115 Chains.push_back(Chain.getOperand(--n));
8120 // For all other instructions we will just have to take what we can get.
8121 Aliases.push_back(Chain);
8127 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8128 /// for a better chain (aliasing node.)
8129 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8130 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
8132 // Accumulate all the aliases to this node.
8133 GatherAllAliases(N, OldChain, Aliases);
8135 // If no operands then chain to entry token.
8136 if (Aliases.size() == 0)
8137 return DAG.getEntryNode();
8139 // If a single operand then chain to it. We don't need to revisit it.
8140 if (Aliases.size() == 1)
8143 // Construct a custom tailored token factor.
8144 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8145 &Aliases[0], Aliases.size());
8148 // SelectionDAG::Combine - This is the entry point for the file.
8150 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8151 CodeGenOpt::Level OptLevel) {
8152 /// run - This is the main entry point to this class.
8154 DAGCombiner(*this, AA, OptLevel).Run(Level);