File: | llvm/include/llvm/CodeGen/SelectionDAGNodes.h |
Warning: | line 1110, column 10 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run | |||
10 | // both before and after the DAG is legalized. | |||
11 | // | |||
12 | // This pass is not a substitute for the LLVM IR instcombine pass. This pass is | |||
13 | // primarily intended to handle simplification opportunities that are implicit | |||
14 | // in the LLVM IR and exposed by the various codegen lowering phases. | |||
15 | // | |||
16 | //===----------------------------------------------------------------------===// | |||
17 | ||||
18 | #include "llvm/ADT/APFloat.h" | |||
19 | #include "llvm/ADT/APInt.h" | |||
20 | #include "llvm/ADT/ArrayRef.h" | |||
21 | #include "llvm/ADT/DenseMap.h" | |||
22 | #include "llvm/ADT/IntervalMap.h" | |||
23 | #include "llvm/ADT/None.h" | |||
24 | #include "llvm/ADT/Optional.h" | |||
25 | #include "llvm/ADT/STLExtras.h" | |||
26 | #include "llvm/ADT/SetVector.h" | |||
27 | #include "llvm/ADT/SmallBitVector.h" | |||
28 | #include "llvm/ADT/SmallPtrSet.h" | |||
29 | #include "llvm/ADT/SmallSet.h" | |||
30 | #include "llvm/ADT/SmallVector.h" | |||
31 | #include "llvm/ADT/Statistic.h" | |||
32 | #include "llvm/Analysis/AliasAnalysis.h" | |||
33 | #include "llvm/Analysis/MemoryLocation.h" | |||
34 | #include "llvm/Analysis/TargetLibraryInfo.h" | |||
35 | #include "llvm/Analysis/VectorUtils.h" | |||
36 | #include "llvm/CodeGen/DAGCombine.h" | |||
37 | #include "llvm/CodeGen/ISDOpcodes.h" | |||
38 | #include "llvm/CodeGen/MachineFrameInfo.h" | |||
39 | #include "llvm/CodeGen/MachineFunction.h" | |||
40 | #include "llvm/CodeGen/MachineMemOperand.h" | |||
41 | #include "llvm/CodeGen/RuntimeLibcalls.h" | |||
42 | #include "llvm/CodeGen/SelectionDAG.h" | |||
43 | #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" | |||
44 | #include "llvm/CodeGen/SelectionDAGNodes.h" | |||
45 | #include "llvm/CodeGen/SelectionDAGTargetInfo.h" | |||
46 | #include "llvm/CodeGen/TargetLowering.h" | |||
47 | #include "llvm/CodeGen/TargetRegisterInfo.h" | |||
48 | #include "llvm/CodeGen/TargetSubtargetInfo.h" | |||
49 | #include "llvm/CodeGen/ValueTypes.h" | |||
50 | #include "llvm/IR/Attributes.h" | |||
51 | #include "llvm/IR/Constant.h" | |||
52 | #include "llvm/IR/DataLayout.h" | |||
53 | #include "llvm/IR/DerivedTypes.h" | |||
54 | #include "llvm/IR/Function.h" | |||
55 | #include "llvm/IR/LLVMContext.h" | |||
56 | #include "llvm/IR/Metadata.h" | |||
57 | #include "llvm/Support/Casting.h" | |||
58 | #include "llvm/Support/CodeGen.h" | |||
59 | #include "llvm/Support/CommandLine.h" | |||
60 | #include "llvm/Support/Compiler.h" | |||
61 | #include "llvm/Support/Debug.h" | |||
62 | #include "llvm/Support/ErrorHandling.h" | |||
63 | #include "llvm/Support/KnownBits.h" | |||
64 | #include "llvm/Support/MachineValueType.h" | |||
65 | #include "llvm/Support/MathExtras.h" | |||
66 | #include "llvm/Support/raw_ostream.h" | |||
67 | #include "llvm/Target/TargetMachine.h" | |||
68 | #include "llvm/Target/TargetOptions.h" | |||
69 | #include <algorithm> | |||
70 | #include <cassert> | |||
71 | #include <cstdint> | |||
72 | #include <functional> | |||
73 | #include <iterator> | |||
74 | #include <string> | |||
75 | #include <tuple> | |||
76 | #include <utility> | |||
77 | ||||
78 | using namespace llvm; | |||
79 | ||||
80 | #define DEBUG_TYPE"dagcombine" "dagcombine" | |||
81 | ||||
82 | STATISTIC(NodesCombined , "Number of dag nodes combined")static llvm::Statistic NodesCombined = {"dagcombine", "NodesCombined" , "Number of dag nodes combined"}; | |||
83 | STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created")static llvm::Statistic PreIndexedNodes = {"dagcombine", "PreIndexedNodes" , "Number of pre-indexed nodes created"}; | |||
84 | STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created")static llvm::Statistic PostIndexedNodes = {"dagcombine", "PostIndexedNodes" , "Number of post-indexed nodes created"}; | |||
85 | STATISTIC(OpsNarrowed , "Number of load/op/store narrowed")static llvm::Statistic OpsNarrowed = {"dagcombine", "OpsNarrowed" , "Number of load/op/store narrowed"}; | |||
86 | STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int")static llvm::Statistic LdStFP2Int = {"dagcombine", "LdStFP2Int" , "Number of fp load/store pairs transformed to int"}; | |||
87 | STATISTIC(SlicedLoads, "Number of load sliced")static llvm::Statistic SlicedLoads = {"dagcombine", "SlicedLoads" , "Number of load sliced"}; | |||
88 | STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops")static llvm::Statistic NumFPLogicOpsConv = {"dagcombine", "NumFPLogicOpsConv" , "Number of logic ops converted to fp ops"}; | |||
89 | ||||
90 | static cl::opt<bool> | |||
91 | CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, | |||
92 | cl::desc("Enable DAG combiner's use of IR alias analysis")); | |||
93 | ||||
94 | static cl::opt<bool> | |||
95 | UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), | |||
96 | cl::desc("Enable DAG combiner's use of TBAA")); | |||
97 | ||||
98 | #ifndef NDEBUG | |||
99 | static cl::opt<std::string> | |||
100 | CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, | |||
101 | cl::desc("Only use DAG-combiner alias analysis in this" | |||
102 | " function")); | |||
103 | #endif | |||
104 | ||||
105 | /// Hidden option to stress test load slicing, i.e., when this option | |||
106 | /// is enabled, load slicing bypasses most of its profitability guards. | |||
107 | static cl::opt<bool> | |||
108 | StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, | |||
109 | cl::desc("Bypass the profitability model of load slicing"), | |||
110 | cl::init(false)); | |||
111 | ||||
112 | static cl::opt<bool> | |||
113 | MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), | |||
114 | cl::desc("DAG combiner may split indexing from loads")); | |||
115 | ||||
116 | static cl::opt<bool> | |||
117 | EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true), | |||
118 | cl::desc("DAG combiner enable merging multiple stores " | |||
119 | "into a wider store")); | |||
120 | ||||
121 | static cl::opt<unsigned> TokenFactorInlineLimit( | |||
122 | "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048), | |||
123 | cl::desc("Limit the number of operands to inline for Token Factors")); | |||
124 | ||||
125 | static cl::opt<unsigned> StoreMergeDependenceLimit( | |||
126 | "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10), | |||
127 | cl::desc("Limit the number of times for the same StoreNode and RootNode " | |||
128 | "to bail out in store merging dependence check")); | |||
129 | ||||
130 | static cl::opt<bool> EnableReduceLoadOpStoreWidth( | |||
131 | "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true), | |||
132 | cl::desc("DAG cominber enable reducing the width of load/op/store " | |||
133 | "sequence")); | |||
134 | ||||
135 | static cl::opt<bool> EnableShrinkLoadReplaceStoreWithStore( | |||
136 | "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true), | |||
137 | cl::desc("DAG cominber enable load/<replace bytes>/store with " | |||
138 | "a narrower store")); | |||
139 | ||||
140 | namespace { | |||
141 | ||||
142 | class DAGCombiner { | |||
143 | SelectionDAG &DAG; | |||
144 | const TargetLowering &TLI; | |||
145 | const SelectionDAGTargetInfo *STI; | |||
146 | CombineLevel Level; | |||
147 | CodeGenOpt::Level OptLevel; | |||
148 | bool LegalDAG = false; | |||
149 | bool LegalOperations = false; | |||
150 | bool LegalTypes = false; | |||
151 | bool ForCodeSize; | |||
152 | bool DisableGenericCombines; | |||
153 | ||||
154 | /// Worklist of all of the nodes that need to be simplified. | |||
155 | /// | |||
156 | /// This must behave as a stack -- new nodes to process are pushed onto the | |||
157 | /// back and when processing we pop off of the back. | |||
158 | /// | |||
159 | /// The worklist will not contain duplicates but may contain null entries | |||
160 | /// due to nodes being deleted from the underlying DAG. | |||
161 | SmallVector<SDNode *, 64> Worklist; | |||
162 | ||||
163 | /// Mapping from an SDNode to its position on the worklist. | |||
164 | /// | |||
165 | /// This is used to find and remove nodes from the worklist (by nulling | |||
166 | /// them) when they are deleted from the underlying DAG. It relies on | |||
167 | /// stable indices of nodes within the worklist. | |||
168 | DenseMap<SDNode *, unsigned> WorklistMap; | |||
169 | /// This records all nodes attempted to add to the worklist since we | |||
170 | /// considered a new worklist entry. As we keep do not add duplicate nodes | |||
171 | /// in the worklist, this is different from the tail of the worklist. | |||
172 | SmallSetVector<SDNode *, 32> PruningList; | |||
173 | ||||
174 | /// Set of nodes which have been combined (at least once). | |||
175 | /// | |||
176 | /// This is used to allow us to reliably add any operands of a DAG node | |||
177 | /// which have not yet been combined to the worklist. | |||
178 | SmallPtrSet<SDNode *, 32> CombinedNodes; | |||
179 | ||||
180 | /// Map from candidate StoreNode to the pair of RootNode and count. | |||
181 | /// The count is used to track how many times we have seen the StoreNode | |||
182 | /// with the same RootNode bail out in dependence check. If we have seen | |||
183 | /// the bail out for the same pair many times over a limit, we won't | |||
184 | /// consider the StoreNode with the same RootNode as store merging | |||
185 | /// candidate again. | |||
186 | DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap; | |||
187 | ||||
188 | // AA - Used for DAG load/store alias analysis. | |||
189 | AliasAnalysis *AA; | |||
190 | ||||
191 | /// When an instruction is simplified, add all users of the instruction to | |||
192 | /// the work lists because they might get more simplified now. | |||
193 | void AddUsersToWorklist(SDNode *N) { | |||
194 | for (SDNode *Node : N->uses()) | |||
195 | AddToWorklist(Node); | |||
196 | } | |||
197 | ||||
198 | /// Convenient shorthand to add a node and all of its user to the worklist. | |||
199 | void AddToWorklistWithUsers(SDNode *N) { | |||
200 | AddUsersToWorklist(N); | |||
201 | AddToWorklist(N); | |||
202 | } | |||
203 | ||||
204 | // Prune potentially dangling nodes. This is called after | |||
205 | // any visit to a node, but should also be called during a visit after any | |||
206 | // failed combine which may have created a DAG node. | |||
207 | void clearAddedDanglingWorklistEntries() { | |||
208 | // Check any nodes added to the worklist to see if they are prunable. | |||
209 | while (!PruningList.empty()) { | |||
210 | auto *N = PruningList.pop_back_val(); | |||
211 | if (N->use_empty()) | |||
212 | recursivelyDeleteUnusedNodes(N); | |||
213 | } | |||
214 | } | |||
215 | ||||
216 | SDNode *getNextWorklistEntry() { | |||
217 | // Before we do any work, remove nodes that are not in use. | |||
218 | clearAddedDanglingWorklistEntries(); | |||
219 | SDNode *N = nullptr; | |||
220 | // The Worklist holds the SDNodes in order, but it may contain null | |||
221 | // entries. | |||
222 | while (!N && !Worklist.empty()) { | |||
223 | N = Worklist.pop_back_val(); | |||
224 | } | |||
225 | ||||
226 | if (N) { | |||
227 | bool GoodWorklistEntry = WorklistMap.erase(N); | |||
228 | (void)GoodWorklistEntry; | |||
229 | assert(GoodWorklistEntry &&((GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!" ) ? static_cast<void> (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 230, __PRETTY_FUNCTION__)) | |||
230 | "Found a worklist entry without a corresponding map entry!")((GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!" ) ? static_cast<void> (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 230, __PRETTY_FUNCTION__)); | |||
231 | } | |||
232 | return N; | |||
233 | } | |||
234 | ||||
235 | /// Call the node-specific routine that folds each particular type of node. | |||
236 | SDValue visit(SDNode *N); | |||
237 | ||||
238 | public: | |||
239 | DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) | |||
240 | : DAG(D), TLI(D.getTargetLoweringInfo()), | |||
241 | STI(D.getSubtarget().getSelectionDAGInfo()), | |||
242 | Level(BeforeLegalizeTypes), OptLevel(OL), AA(AA) { | |||
243 | ForCodeSize = DAG.shouldOptForSize(); | |||
244 | DisableGenericCombines = STI && STI->disableGenericCombines(OptLevel); | |||
245 | ||||
246 | MaximumLegalStoreInBits = 0; | |||
247 | // We use the minimum store size here, since that's all we can guarantee | |||
248 | // for the scalable vector types. | |||
249 | for (MVT VT : MVT::all_valuetypes()) | |||
250 | if (EVT(VT).isSimple() && VT != MVT::Other && | |||
251 | TLI.isTypeLegal(EVT(VT)) && | |||
252 | VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits) | |||
253 | MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize(); | |||
254 | } | |||
255 | ||||
256 | void ConsiderForPruning(SDNode *N) { | |||
257 | // Mark this for potential pruning. | |||
258 | PruningList.insert(N); | |||
259 | } | |||
260 | ||||
261 | /// Add to the worklist making sure its instance is at the back (next to be | |||
262 | /// processed.) | |||
263 | void AddToWorklist(SDNode *N) { | |||
264 | assert(N->getOpcode() != ISD::DELETED_NODE &&((N->getOpcode() != ISD::DELETED_NODE && "Deleted Node added to Worklist" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 265, __PRETTY_FUNCTION__)) | |||
265 | "Deleted Node added to Worklist")((N->getOpcode() != ISD::DELETED_NODE && "Deleted Node added to Worklist" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 265, __PRETTY_FUNCTION__)); | |||
266 | ||||
267 | // Skip handle nodes as they can't usefully be combined and confuse the | |||
268 | // zero-use deletion strategy. | |||
269 | if (N->getOpcode() == ISD::HANDLENODE) | |||
270 | return; | |||
271 | ||||
272 | ConsiderForPruning(N); | |||
273 | ||||
274 | if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) | |||
275 | Worklist.push_back(N); | |||
276 | } | |||
277 | ||||
278 | /// Remove all instances of N from the worklist. | |||
279 | void removeFromWorklist(SDNode *N) { | |||
280 | CombinedNodes.erase(N); | |||
281 | PruningList.remove(N); | |||
282 | StoreRootCountMap.erase(N); | |||
283 | ||||
284 | auto It = WorklistMap.find(N); | |||
285 | if (It == WorklistMap.end()) | |||
286 | return; // Not in the worklist. | |||
287 | ||||
288 | // Null out the entry rather than erasing it to avoid a linear operation. | |||
289 | Worklist[It->second] = nullptr; | |||
290 | WorklistMap.erase(It); | |||
291 | } | |||
292 | ||||
293 | void deleteAndRecombine(SDNode *N); | |||
294 | bool recursivelyDeleteUnusedNodes(SDNode *N); | |||
295 | ||||
296 | /// Replaces all uses of the results of one DAG node with new values. | |||
297 | SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, | |||
298 | bool AddTo = true); | |||
299 | ||||
300 | /// Replaces all uses of the results of one DAG node with new values. | |||
301 | SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { | |||
302 | return CombineTo(N, &Res, 1, AddTo); | |||
303 | } | |||
304 | ||||
305 | /// Replaces all uses of the results of one DAG node with new values. | |||
306 | SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, | |||
307 | bool AddTo = true) { | |||
308 | SDValue To[] = { Res0, Res1 }; | |||
309 | return CombineTo(N, To, 2, AddTo); | |||
310 | } | |||
311 | ||||
312 | void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); | |||
313 | ||||
314 | private: | |||
315 | unsigned MaximumLegalStoreInBits; | |||
316 | ||||
317 | /// Check the specified integer node value to see if it can be simplified or | |||
318 | /// if things it uses can be simplified by bit propagation. | |||
319 | /// If so, return true. | |||
320 | bool SimplifyDemandedBits(SDValue Op) { | |||
321 | unsigned BitWidth = Op.getScalarValueSizeInBits(); | |||
322 | APInt DemandedBits = APInt::getAllOnesValue(BitWidth); | |||
323 | return SimplifyDemandedBits(Op, DemandedBits); | |||
324 | } | |||
325 | ||||
326 | bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) { | |||
327 | TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); | |||
328 | KnownBits Known; | |||
329 | if (!TLI.SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, false)) | |||
330 | return false; | |||
331 | ||||
332 | // Revisit the node. | |||
333 | AddToWorklist(Op.getNode()); | |||
334 | ||||
335 | CommitTargetLoweringOpt(TLO); | |||
336 | return true; | |||
337 | } | |||
338 | ||||
339 | /// Check the specified vector node value to see if it can be simplified or | |||
340 | /// if things it uses can be simplified as it only uses some of the | |||
341 | /// elements. If so, return true. | |||
342 | bool SimplifyDemandedVectorElts(SDValue Op) { | |||
343 | // TODO: For now just pretend it cannot be simplified. | |||
344 | if (Op.getValueType().isScalableVector()) | |||
345 | return false; | |||
346 | ||||
347 | unsigned NumElts = Op.getValueType().getVectorNumElements(); | |||
348 | APInt DemandedElts = APInt::getAllOnesValue(NumElts); | |||
349 | return SimplifyDemandedVectorElts(Op, DemandedElts); | |||
350 | } | |||
351 | ||||
352 | bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, | |||
353 | const APInt &DemandedElts, | |||
354 | bool AssumeSingleUse = false); | |||
355 | bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts, | |||
356 | bool AssumeSingleUse = false); | |||
357 | ||||
358 | bool CombineToPreIndexedLoadStore(SDNode *N); | |||
359 | bool CombineToPostIndexedLoadStore(SDNode *N); | |||
360 | SDValue SplitIndexingFromLoad(LoadSDNode *LD); | |||
361 | bool SliceUpLoad(SDNode *N); | |||
362 | ||||
363 | // Scalars have size 0 to distinguish from singleton vectors. | |||
364 | SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD); | |||
365 | bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val); | |||
366 | bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val); | |||
367 | ||||
368 | /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed | |||
369 | /// load. | |||
370 | /// | |||
371 | /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. | |||
372 | /// \param InVecVT type of the input vector to EVE with bitcasts resolved. | |||
373 | /// \param EltNo index of the vector element to load. | |||
374 | /// \param OriginalLoad load that EVE came from to be replaced. | |||
375 | /// \returns EVE on success SDValue() on failure. | |||
376 | SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, | |||
377 | SDValue EltNo, | |||
378 | LoadSDNode *OriginalLoad); | |||
379 | void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); | |||
380 | SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); | |||
381 | SDValue SExtPromoteOperand(SDValue Op, EVT PVT); | |||
382 | SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); | |||
383 | SDValue PromoteIntBinOp(SDValue Op); | |||
384 | SDValue PromoteIntShiftOp(SDValue Op); | |||
385 | SDValue PromoteExtend(SDValue Op); | |||
386 | bool PromoteLoad(SDValue Op); | |||
387 | ||||
388 | /// Call the node-specific routine that knows how to fold each | |||
389 | /// particular type of node. If that doesn't do anything, try the | |||
390 | /// target-specific DAG combines. | |||
391 | SDValue combine(SDNode *N); | |||
392 | ||||
393 | // Visitation implementation - Implement dag node combining for different | |||
394 | // node types. The semantics are as follows: | |||
395 | // Return Value: | |||
396 | // SDValue.getNode() == 0 - No change was made | |||
397 | // SDValue.getNode() == N - N was replaced, is dead and has been handled. | |||
398 | // otherwise - N should be replaced by the returned Operand. | |||
399 | // | |||
400 | SDValue visitTokenFactor(SDNode *N); | |||
401 | SDValue visitMERGE_VALUES(SDNode *N); | |||
402 | SDValue visitADD(SDNode *N); | |||
403 | SDValue visitADDLike(SDNode *N); | |||
404 | SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference); | |||
405 | SDValue visitSUB(SDNode *N); | |||
406 | SDValue visitADDSAT(SDNode *N); | |||
407 | SDValue visitSUBSAT(SDNode *N); | |||
408 | SDValue visitADDC(SDNode *N); | |||
409 | SDValue visitADDO(SDNode *N); | |||
410 | SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); | |||
411 | SDValue visitSUBC(SDNode *N); | |||
412 | SDValue visitSUBO(SDNode *N); | |||
413 | SDValue visitADDE(SDNode *N); | |||
414 | SDValue visitADDCARRY(SDNode *N); | |||
415 | SDValue visitSADDO_CARRY(SDNode *N); | |||
416 | SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); | |||
417 | SDValue visitSUBE(SDNode *N); | |||
418 | SDValue visitSUBCARRY(SDNode *N); | |||
419 | SDValue visitSSUBO_CARRY(SDNode *N); | |||
420 | SDValue visitMUL(SDNode *N); | |||
421 | SDValue visitMULFIX(SDNode *N); | |||
422 | SDValue useDivRem(SDNode *N); | |||
423 | SDValue visitSDIV(SDNode *N); | |||
424 | SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N); | |||
425 | SDValue visitUDIV(SDNode *N); | |||
426 | SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N); | |||
427 | SDValue visitREM(SDNode *N); | |||
428 | SDValue visitMULHU(SDNode *N); | |||
429 | SDValue visitMULHS(SDNode *N); | |||
430 | SDValue visitSMUL_LOHI(SDNode *N); | |||
431 | SDValue visitUMUL_LOHI(SDNode *N); | |||
432 | SDValue visitMULO(SDNode *N); | |||
433 | SDValue visitIMINMAX(SDNode *N); | |||
434 | SDValue visitAND(SDNode *N); | |||
435 | SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N); | |||
436 | SDValue visitOR(SDNode *N); | |||
437 | SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N); | |||
438 | SDValue visitXOR(SDNode *N); | |||
439 | SDValue SimplifyVBinOp(SDNode *N); | |||
440 | SDValue visitSHL(SDNode *N); | |||
441 | SDValue visitSRA(SDNode *N); | |||
442 | SDValue visitSRL(SDNode *N); | |||
443 | SDValue visitFunnelShift(SDNode *N); | |||
444 | SDValue visitRotate(SDNode *N); | |||
445 | SDValue visitABS(SDNode *N); | |||
446 | SDValue visitBSWAP(SDNode *N); | |||
447 | SDValue visitBITREVERSE(SDNode *N); | |||
448 | SDValue visitCTLZ(SDNode *N); | |||
449 | SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); | |||
450 | SDValue visitCTTZ(SDNode *N); | |||
451 | SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); | |||
452 | SDValue visitCTPOP(SDNode *N); | |||
453 | SDValue visitSELECT(SDNode *N); | |||
454 | SDValue visitVSELECT(SDNode *N); | |||
455 | SDValue visitSELECT_CC(SDNode *N); | |||
456 | SDValue visitSETCC(SDNode *N); | |||
457 | SDValue visitSETCCCARRY(SDNode *N); | |||
458 | SDValue visitSIGN_EXTEND(SDNode *N); | |||
459 | SDValue visitZERO_EXTEND(SDNode *N); | |||
460 | SDValue visitANY_EXTEND(SDNode *N); | |||
461 | SDValue visitAssertExt(SDNode *N); | |||
462 | SDValue visitAssertAlign(SDNode *N); | |||
463 | SDValue visitSIGN_EXTEND_INREG(SDNode *N); | |||
464 | SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); | |||
465 | SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); | |||
466 | SDValue visitTRUNCATE(SDNode *N); | |||
467 | SDValue visitBITCAST(SDNode *N); | |||
468 | SDValue visitFREEZE(SDNode *N); | |||
469 | SDValue visitBUILD_PAIR(SDNode *N); | |||
470 | SDValue visitFADD(SDNode *N); | |||
471 | SDValue visitSTRICT_FADD(SDNode *N); | |||
472 | SDValue visitFSUB(SDNode *N); | |||
473 | SDValue visitFMUL(SDNode *N); | |||
474 | SDValue visitFMA(SDNode *N); | |||
475 | SDValue visitFDIV(SDNode *N); | |||
476 | SDValue visitFREM(SDNode *N); | |||
477 | SDValue visitFSQRT(SDNode *N); | |||
478 | SDValue visitFCOPYSIGN(SDNode *N); | |||
479 | SDValue visitFPOW(SDNode *N); | |||
480 | SDValue visitSINT_TO_FP(SDNode *N); | |||
481 | SDValue visitUINT_TO_FP(SDNode *N); | |||
482 | SDValue visitFP_TO_SINT(SDNode *N); | |||
483 | SDValue visitFP_TO_UINT(SDNode *N); | |||
484 | SDValue visitFP_ROUND(SDNode *N); | |||
485 | SDValue visitFP_EXTEND(SDNode *N); | |||
486 | SDValue visitFNEG(SDNode *N); | |||
487 | SDValue visitFABS(SDNode *N); | |||
488 | SDValue visitFCEIL(SDNode *N); | |||
489 | SDValue visitFTRUNC(SDNode *N); | |||
490 | SDValue visitFFLOOR(SDNode *N); | |||
491 | SDValue visitFMINNUM(SDNode *N); | |||
492 | SDValue visitFMAXNUM(SDNode *N); | |||
493 | SDValue visitFMINIMUM(SDNode *N); | |||
494 | SDValue visitFMAXIMUM(SDNode *N); | |||
495 | SDValue visitBRCOND(SDNode *N); | |||
496 | SDValue visitBR_CC(SDNode *N); | |||
497 | SDValue visitLOAD(SDNode *N); | |||
498 | ||||
499 | SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); | |||
500 | SDValue replaceStoreOfFPConstant(StoreSDNode *ST); | |||
501 | ||||
502 | SDValue visitSTORE(SDNode *N); | |||
503 | SDValue visitLIFETIME_END(SDNode *N); | |||
504 | SDValue visitINSERT_VECTOR_ELT(SDNode *N); | |||
505 | SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); | |||
506 | SDValue visitBUILD_VECTOR(SDNode *N); | |||
507 | SDValue visitCONCAT_VECTORS(SDNode *N); | |||
508 | SDValue visitEXTRACT_SUBVECTOR(SDNode *N); | |||
509 | SDValue visitVECTOR_SHUFFLE(SDNode *N); | |||
510 | SDValue visitSCALAR_TO_VECTOR(SDNode *N); | |||
511 | SDValue visitINSERT_SUBVECTOR(SDNode *N); | |||
512 | SDValue visitMLOAD(SDNode *N); | |||
513 | SDValue visitMSTORE(SDNode *N); | |||
514 | SDValue visitMGATHER(SDNode *N); | |||
515 | SDValue visitMSCATTER(SDNode *N); | |||
516 | SDValue visitFP_TO_FP16(SDNode *N); | |||
517 | SDValue visitFP16_TO_FP(SDNode *N); | |||
518 | SDValue visitVECREDUCE(SDNode *N); | |||
519 | ||||
520 | SDValue visitFADDForFMACombine(SDNode *N); | |||
521 | SDValue visitFSUBForFMACombine(SDNode *N); | |||
522 | SDValue visitFMULForFMADistributiveCombine(SDNode *N); | |||
523 | ||||
524 | SDValue XformToShuffleWithZero(SDNode *N); | |||
525 | bool reassociationCanBreakAddressingModePattern(unsigned Opc, | |||
526 | const SDLoc &DL, SDValue N0, | |||
527 | SDValue N1); | |||
528 | SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0, | |||
529 | SDValue N1); | |||
530 | SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, | |||
531 | SDValue N1, SDNodeFlags Flags); | |||
532 | ||||
533 | SDValue visitShiftByConstant(SDNode *N); | |||
534 | ||||
535 | SDValue foldSelectOfConstants(SDNode *N); | |||
536 | SDValue foldVSelectOfConstants(SDNode *N); | |||
537 | SDValue foldBinOpIntoSelect(SDNode *BO); | |||
538 | bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); | |||
539 | SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N); | |||
540 | SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); | |||
541 | SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, | |||
542 | SDValue N2, SDValue N3, ISD::CondCode CC, | |||
543 | bool NotExtCompare = false); | |||
544 | SDValue convertSelectOfFPConstantsToLoadOffset( | |||
545 | const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, | |||
546 | ISD::CondCode CC); | |||
547 | SDValue foldSignChangeInBitcast(SDNode *N); | |||
548 | SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, | |||
549 | SDValue N2, SDValue N3, ISD::CondCode CC); | |||
550 | SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, | |||
551 | const SDLoc &DL); | |||
552 | SDValue foldSubToUSubSat(EVT DstVT, SDNode *N); | |||
553 | SDValue unfoldMaskedMerge(SDNode *N); | |||
554 | SDValue unfoldExtremeBitClearingToShifts(SDNode *N); | |||
555 | SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, | |||
556 | const SDLoc &DL, bool foldBooleans); | |||
557 | SDValue rebuildSetCC(SDValue N); | |||
558 | ||||
559 | bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, | |||
560 | SDValue &CC, bool MatchStrict = false) const; | |||
561 | bool isOneUseSetCC(SDValue N) const; | |||
562 | ||||
563 | SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, | |||
564 | unsigned HiOp); | |||
565 | SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); | |||
566 | SDValue CombineExtLoad(SDNode *N); | |||
567 | SDValue CombineZExtLogicopShiftLoad(SDNode *N); | |||
568 | SDValue combineRepeatedFPDivisors(SDNode *N); | |||
569 | SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); | |||
570 | SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); | |||
571 | SDValue BuildSDIV(SDNode *N); | |||
572 | SDValue BuildSDIVPow2(SDNode *N); | |||
573 | SDValue BuildUDIV(SDNode *N); | |||
574 | SDValue BuildLogBase2(SDValue V, const SDLoc &DL); | |||
575 | SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags); | |||
576 | SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); | |||
577 | SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); | |||
578 | SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); | |||
579 | SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, | |||
580 | SDNodeFlags Flags, bool Reciprocal); | |||
581 | SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, | |||
582 | SDNodeFlags Flags, bool Reciprocal); | |||
583 | SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, | |||
584 | bool DemandHighBits = true); | |||
585 | SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); | |||
586 | SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, | |||
587 | SDValue InnerPos, SDValue InnerNeg, | |||
588 | unsigned PosOpcode, unsigned NegOpcode, | |||
589 | const SDLoc &DL); | |||
590 | SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg, | |||
591 | SDValue InnerPos, SDValue InnerNeg, | |||
592 | unsigned PosOpcode, unsigned NegOpcode, | |||
593 | const SDLoc &DL); | |||
594 | SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); | |||
595 | SDValue MatchLoadCombine(SDNode *N); | |||
596 | SDValue mergeTruncStores(StoreSDNode *N); | |||
597 | SDValue ReduceLoadWidth(SDNode *N); | |||
598 | SDValue ReduceLoadOpStoreWidth(SDNode *N); | |||
599 | SDValue splitMergedValStore(StoreSDNode *ST); | |||
600 | SDValue TransformFPLoadStorePair(SDNode *N); | |||
601 | SDValue convertBuildVecZextToZext(SDNode *N); | |||
602 | SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); | |||
603 | SDValue reduceBuildVecTruncToBitCast(SDNode *N); | |||
604 | SDValue reduceBuildVecToShuffle(SDNode *N); | |||
605 | SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, | |||
606 | ArrayRef<int> VectorMask, SDValue VecIn1, | |||
607 | SDValue VecIn2, unsigned LeftIdx, | |||
608 | bool DidSplitVec); | |||
609 | SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); | |||
610 | ||||
611 | /// Walk up chain skipping non-aliasing memory nodes, | |||
612 | /// looking for aliasing nodes and adding them to the Aliases vector. | |||
613 | void GatherAllAliases(SDNode *N, SDValue OriginalChain, | |||
614 | SmallVectorImpl<SDValue> &Aliases); | |||
615 | ||||
616 | /// Return true if there is any possibility that the two addresses overlap. | |||
617 | bool isAlias(SDNode *Op0, SDNode *Op1) const; | |||
618 | ||||
619 | /// Walk up chain skipping non-aliasing memory nodes, looking for a better | |||
620 | /// chain (aliasing node.) | |||
621 | SDValue FindBetterChain(SDNode *N, SDValue Chain); | |||
622 | ||||
623 | /// Try to replace a store and any possibly adjacent stores on | |||
624 | /// consecutive chains with better chains. Return true only if St is | |||
625 | /// replaced. | |||
626 | /// | |||
627 | /// Notice that other chains may still be replaced even if the function | |||
628 | /// returns false. | |||
629 | bool findBetterNeighborChains(StoreSDNode *St); | |||
630 | ||||
631 | // Helper for findBetterNeighborChains. Walk up store chain add additional | |||
632 | // chained stores that do not overlap and can be parallelized. | |||
633 | bool parallelizeChainedStores(StoreSDNode *St); | |||
634 | ||||
635 | /// Holds a pointer to an LSBaseSDNode as well as information on where it | |||
636 | /// is located in a sequence of memory operations connected by a chain. | |||
637 | struct MemOpLink { | |||
638 | // Ptr to the mem node. | |||
639 | LSBaseSDNode *MemNode; | |||
640 | ||||
641 | // Offset from the base ptr. | |||
642 | int64_t OffsetFromBase; | |||
643 | ||||
644 | MemOpLink(LSBaseSDNode *N, int64_t Offset) | |||
645 | : MemNode(N), OffsetFromBase(Offset) {} | |||
646 | }; | |||
647 | ||||
648 | // Classify the origin of a stored value. | |||
649 | enum class StoreSource { Unknown, Constant, Extract, Load }; | |||
650 | StoreSource getStoreSource(SDValue StoreVal) { | |||
651 | switch (StoreVal.getOpcode()) { | |||
652 | case ISD::Constant: | |||
653 | case ISD::ConstantFP: | |||
654 | return StoreSource::Constant; | |||
655 | case ISD::EXTRACT_VECTOR_ELT: | |||
656 | case ISD::EXTRACT_SUBVECTOR: | |||
657 | return StoreSource::Extract; | |||
658 | case ISD::LOAD: | |||
659 | return StoreSource::Load; | |||
660 | default: | |||
661 | return StoreSource::Unknown; | |||
662 | } | |||
663 | } | |||
664 | ||||
665 | /// This is a helper function for visitMUL to check the profitability | |||
666 | /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). | |||
667 | /// MulNode is the original multiply, AddNode is (add x, c1), | |||
668 | /// and ConstNode is c2. | |||
669 | bool isMulAddWithConstProfitable(SDNode *MulNode, | |||
670 | SDValue &AddNode, | |||
671 | SDValue &ConstNode); | |||
672 | ||||
673 | /// This is a helper function for visitAND and visitZERO_EXTEND. Returns | |||
674 | /// true if the (and (load x) c) pattern matches an extload. ExtVT returns | |||
675 | /// the type of the loaded value to be extended. | |||
676 | bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, | |||
677 | EVT LoadResultTy, EVT &ExtVT); | |||
678 | ||||
679 | /// Helper function to calculate whether the given Load/Store can have its | |||
680 | /// width reduced to ExtVT. | |||
681 | bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, | |||
682 | EVT &MemVT, unsigned ShAmt = 0); | |||
683 | ||||
684 | /// Used by BackwardsPropagateMask to find suitable loads. | |||
685 | bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads, | |||
686 | SmallPtrSetImpl<SDNode*> &NodesWithConsts, | |||
687 | ConstantSDNode *Mask, SDNode *&NodeToMask); | |||
688 | /// Attempt to propagate a given AND node back to load leaves so that they | |||
689 | /// can be combined into narrow loads. | |||
690 | bool BackwardsPropagateMask(SDNode *N); | |||
691 | ||||
692 | /// Helper function for mergeConsecutiveStores which merges the component | |||
693 | /// store chains. | |||
694 | SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
695 | unsigned NumStores); | |||
696 | ||||
697 | /// This is a helper function for mergeConsecutiveStores. When the source | |||
698 | /// elements of the consecutive stores are all constants or all extracted | |||
699 | /// vector elements, try to merge them into one larger store introducing | |||
700 | /// bitcasts if necessary. \return True if a merged store was created. | |||
701 | bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
702 | EVT MemVT, unsigned NumStores, | |||
703 | bool IsConstantSrc, bool UseVector, | |||
704 | bool UseTrunc); | |||
705 | ||||
706 | /// This is a helper function for mergeConsecutiveStores. Stores that | |||
707 | /// potentially may be merged with St are placed in StoreNodes. RootNode is | |||
708 | /// a chain predecessor to all store candidates. | |||
709 | void getStoreMergeCandidates(StoreSDNode *St, | |||
710 | SmallVectorImpl<MemOpLink> &StoreNodes, | |||
711 | SDNode *&Root); | |||
712 | ||||
713 | /// Helper function for mergeConsecutiveStores. Checks if candidate stores | |||
714 | /// have indirect dependency through their operands. RootNode is the | |||
715 | /// predecessor to all stores calculated by getStoreMergeCandidates and is | |||
716 | /// used to prune the dependency check. \return True if safe to merge. | |||
717 | bool checkMergeStoreCandidatesForDependencies( | |||
718 | SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, | |||
719 | SDNode *RootNode); | |||
720 | ||||
721 | /// This is a helper function for mergeConsecutiveStores. Given a list of | |||
722 | /// store candidates, find the first N that are consecutive in memory. | |||
723 | /// Returns 0 if there are not at least 2 consecutive stores to try merging. | |||
724 | unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
725 | int64_t ElementSizeBytes) const; | |||
726 | ||||
727 | /// This is a helper function for mergeConsecutiveStores. It is used for | |||
728 | /// store chains that are composed entirely of constant values. | |||
729 | bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
730 | unsigned NumConsecutiveStores, | |||
731 | EVT MemVT, SDNode *Root, bool AllowVectors); | |||
732 | ||||
733 | /// This is a helper function for mergeConsecutiveStores. It is used for | |||
734 | /// store chains that are composed entirely of extracted vector elements. | |||
735 | /// When extracting multiple vector elements, try to store them in one | |||
736 | /// vector store rather than a sequence of scalar stores. | |||
737 | bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
738 | unsigned NumConsecutiveStores, EVT MemVT, | |||
739 | SDNode *Root); | |||
740 | ||||
741 | /// This is a helper function for mergeConsecutiveStores. It is used for | |||
742 | /// store chains that are composed entirely of loaded values. | |||
743 | bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
744 | unsigned NumConsecutiveStores, EVT MemVT, | |||
745 | SDNode *Root, bool AllowVectors, | |||
746 | bool IsNonTemporalStore, bool IsNonTemporalLoad); | |||
747 | ||||
748 | /// Merge consecutive store operations into a wide store. | |||
749 | /// This optimization uses wide integers or vectors when possible. | |||
750 | /// \return true if stores were merged. | |||
751 | bool mergeConsecutiveStores(StoreSDNode *St); | |||
752 | ||||
753 | /// Try to transform a truncation where C is a constant: | |||
754 | /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) | |||
755 | /// | |||
756 | /// \p N needs to be a truncation and its first operand an AND. Other | |||
757 | /// requirements are checked by the function (e.g. that trunc is | |||
758 | /// single-use) and if missed an empty SDValue is returned. | |||
759 | SDValue distributeTruncateThroughAnd(SDNode *N); | |||
760 | ||||
761 | /// Helper function to determine whether the target supports operation | |||
762 | /// given by \p Opcode for type \p VT, that is, whether the operation | |||
763 | /// is legal or custom before legalizing operations, and whether is | |||
764 | /// legal (but not custom) after legalization. | |||
765 | bool hasOperation(unsigned Opcode, EVT VT) { | |||
766 | return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations); | |||
767 | } | |||
768 | ||||
769 | public: | |||
770 | /// Runs the dag combiner on all nodes in the work list | |||
771 | void Run(CombineLevel AtLevel); | |||
772 | ||||
773 | SelectionDAG &getDAG() const { return DAG; } | |||
774 | ||||
775 | /// Returns a type large enough to hold any valid shift amount - before type | |||
776 | /// legalization these can be huge. | |||
777 | EVT getShiftAmountTy(EVT LHSTy) { | |||
778 | assert(LHSTy.isInteger() && "Shift amount is not an integer type!")((LHSTy.isInteger() && "Shift amount is not an integer type!" ) ? static_cast<void> (0) : __assert_fail ("LHSTy.isInteger() && \"Shift amount is not an integer type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 778, __PRETTY_FUNCTION__)); | |||
779 | return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); | |||
780 | } | |||
781 | ||||
782 | /// This method returns true if we are running before type legalization or | |||
783 | /// if the specified VT is legal. | |||
784 | bool isTypeLegal(const EVT &VT) { | |||
785 | if (!LegalTypes) return true; | |||
786 | return TLI.isTypeLegal(VT); | |||
787 | } | |||
788 | ||||
789 | /// Convenience wrapper around TargetLowering::getSetCCResultType | |||
790 | EVT getSetCCResultType(EVT VT) const { | |||
791 | return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); | |||
792 | } | |||
793 | ||||
794 | void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, | |||
795 | SDValue OrigLoad, SDValue ExtLoad, | |||
796 | ISD::NodeType ExtType); | |||
797 | }; | |||
798 | ||||
799 | /// This class is a DAGUpdateListener that removes any deleted | |||
800 | /// nodes from the worklist. | |||
801 | class WorklistRemover : public SelectionDAG::DAGUpdateListener { | |||
802 | DAGCombiner &DC; | |||
803 | ||||
804 | public: | |||
805 | explicit WorklistRemover(DAGCombiner &dc) | |||
806 | : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} | |||
807 | ||||
808 | void NodeDeleted(SDNode *N, SDNode *E) override { | |||
809 | DC.removeFromWorklist(N); | |||
810 | } | |||
811 | }; | |||
812 | ||||
813 | class WorklistInserter : public SelectionDAG::DAGUpdateListener { | |||
814 | DAGCombiner &DC; | |||
815 | ||||
816 | public: | |||
817 | explicit WorklistInserter(DAGCombiner &dc) | |||
818 | : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} | |||
819 | ||||
820 | // FIXME: Ideally we could add N to the worklist, but this causes exponential | |||
821 | // compile time costs in large DAGs, e.g. Halide. | |||
822 | void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); } | |||
823 | }; | |||
824 | ||||
825 | } // end anonymous namespace | |||
826 | ||||
827 | //===----------------------------------------------------------------------===// | |||
828 | // TargetLowering::DAGCombinerInfo implementation | |||
829 | //===----------------------------------------------------------------------===// | |||
830 | ||||
831 | void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { | |||
832 | ((DAGCombiner*)DC)->AddToWorklist(N); | |||
833 | } | |||
834 | ||||
835 | SDValue TargetLowering::DAGCombinerInfo:: | |||
836 | CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { | |||
837 | return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); | |||
838 | } | |||
839 | ||||
840 | SDValue TargetLowering::DAGCombinerInfo:: | |||
841 | CombineTo(SDNode *N, SDValue Res, bool AddTo) { | |||
842 | return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); | |||
843 | } | |||
844 | ||||
845 | SDValue TargetLowering::DAGCombinerInfo:: | |||
846 | CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { | |||
847 | return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); | |||
848 | } | |||
849 | ||||
850 | bool TargetLowering::DAGCombinerInfo:: | |||
851 | recursivelyDeleteUnusedNodes(SDNode *N) { | |||
852 | return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N); | |||
853 | } | |||
854 | ||||
855 | void TargetLowering::DAGCombinerInfo:: | |||
856 | CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { | |||
857 | return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); | |||
858 | } | |||
859 | ||||
860 | //===----------------------------------------------------------------------===// | |||
861 | // Helper Functions | |||
862 | //===----------------------------------------------------------------------===// | |||
863 | ||||
864 | void DAGCombiner::deleteAndRecombine(SDNode *N) { | |||
865 | removeFromWorklist(N); | |||
866 | ||||
867 | // If the operands of this node are only used by the node, they will now be | |||
868 | // dead. Make sure to re-visit them and recursively delete dead nodes. | |||
869 | for (const SDValue &Op : N->ops()) | |||
870 | // For an operand generating multiple values, one of the values may | |||
871 | // become dead allowing further simplification (e.g. split index | |||
872 | // arithmetic from an indexed load). | |||
873 | if (Op->hasOneUse() || Op->getNumValues() > 1) | |||
874 | AddToWorklist(Op.getNode()); | |||
875 | ||||
876 | DAG.DeleteNode(N); | |||
877 | } | |||
878 | ||||
879 | // APInts must be the same size for most operations, this helper | |||
880 | // function zero extends the shorter of the pair so that they match. | |||
881 | // We provide an Offset so that we can create bitwidths that won't overflow. | |||
882 | static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { | |||
883 | unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); | |||
884 | LHS = LHS.zextOrSelf(Bits); | |||
885 | RHS = RHS.zextOrSelf(Bits); | |||
886 | } | |||
887 | ||||
888 | // Return true if this node is a setcc, or is a select_cc | |||
889 | // that selects between the target values used for true and false, making it | |||
890 | // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to | |||
891 | // the appropriate nodes based on the type of node we are checking. This | |||
892 | // simplifies life a bit for the callers. | |||
893 | bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, | |||
894 | SDValue &CC, bool MatchStrict) const { | |||
895 | if (N.getOpcode() == ISD::SETCC) { | |||
896 | LHS = N.getOperand(0); | |||
897 | RHS = N.getOperand(1); | |||
898 | CC = N.getOperand(2); | |||
899 | return true; | |||
900 | } | |||
901 | ||||
902 | if (MatchStrict && | |||
903 | (N.getOpcode() == ISD::STRICT_FSETCC || | |||
904 | N.getOpcode() == ISD::STRICT_FSETCCS)) { | |||
905 | LHS = N.getOperand(1); | |||
906 | RHS = N.getOperand(2); | |||
907 | CC = N.getOperand(3); | |||
908 | return true; | |||
909 | } | |||
910 | ||||
911 | if (N.getOpcode() != ISD::SELECT_CC || | |||
912 | !TLI.isConstTrueVal(N.getOperand(2).getNode()) || | |||
913 | !TLI.isConstFalseVal(N.getOperand(3).getNode())) | |||
914 | return false; | |||
915 | ||||
916 | if (TLI.getBooleanContents(N.getValueType()) == | |||
917 | TargetLowering::UndefinedBooleanContent) | |||
918 | return false; | |||
919 | ||||
920 | LHS = N.getOperand(0); | |||
921 | RHS = N.getOperand(1); | |||
922 | CC = N.getOperand(4); | |||
923 | return true; | |||
924 | } | |||
925 | ||||
926 | /// Return true if this is a SetCC-equivalent operation with only one use. | |||
927 | /// If this is true, it allows the users to invert the operation for free when | |||
928 | /// it is profitable to do so. | |||
929 | bool DAGCombiner::isOneUseSetCC(SDValue N) const { | |||
930 | SDValue N0, N1, N2; | |||
931 | if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) | |||
932 | return true; | |||
933 | return false; | |||
934 | } | |||
935 | ||||
936 | static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) { | |||
937 | if (!ScalarTy.isSimple()) | |||
938 | return false; | |||
939 | ||||
940 | uint64_t MaskForTy = 0ULL; | |||
941 | switch (ScalarTy.getSimpleVT().SimpleTy) { | |||
942 | case MVT::i8: | |||
943 | MaskForTy = 0xFFULL; | |||
944 | break; | |||
945 | case MVT::i16: | |||
946 | MaskForTy = 0xFFFFULL; | |||
947 | break; | |||
948 | case MVT::i32: | |||
949 | MaskForTy = 0xFFFFFFFFULL; | |||
950 | break; | |||
951 | default: | |||
952 | return false; | |||
953 | break; | |||
954 | } | |||
955 | ||||
956 | APInt Val; | |||
957 | if (ISD::isConstantSplatVector(N, Val)) | |||
958 | return Val.getLimitedValue() == MaskForTy; | |||
959 | ||||
960 | return false; | |||
961 | } | |||
962 | ||||
963 | // Determines if it is a constant integer or a splat/build vector of constant | |||
964 | // integers (and undefs). | |||
965 | // Do not permit build vector implicit truncation. | |||
966 | static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { | |||
967 | if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) | |||
968 | return !(Const->isOpaque() && NoOpaques); | |||
969 | if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR) | |||
970 | return false; | |||
971 | unsigned BitWidth = N.getScalarValueSizeInBits(); | |||
972 | for (const SDValue &Op : N->op_values()) { | |||
973 | if (Op.isUndef()) | |||
974 | continue; | |||
975 | ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); | |||
976 | if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || | |||
977 | (Const->isOpaque() && NoOpaques)) | |||
978 | return false; | |||
979 | } | |||
980 | return true; | |||
981 | } | |||
982 | ||||
983 | // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with | |||
984 | // undef's. | |||
985 | static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) { | |||
986 | if (V.getOpcode() != ISD::BUILD_VECTOR) | |||
987 | return false; | |||
988 | return isConstantOrConstantVector(V, NoOpaques) || | |||
989 | ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()); | |||
990 | } | |||
991 | ||||
992 | // Determine if this an indexed load with an opaque target constant index. | |||
993 | static bool canSplitIdx(LoadSDNode *LD) { | |||
994 | return MaySplitLoadIndex && | |||
995 | (LD->getOperand(2).getOpcode() != ISD::TargetConstant || | |||
996 | !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque()); | |||
997 | } | |||
998 | ||||
999 | bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc, | |||
1000 | const SDLoc &DL, | |||
1001 | SDValue N0, | |||
1002 | SDValue N1) { | |||
1003 | // Currently this only tries to ensure we don't undo the GEP splits done by | |||
1004 | // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this, | |||
1005 | // we check if the following transformation would be problematic: | |||
1006 | // (load/store (add, (add, x, offset1), offset2)) -> | |||
1007 | // (load/store (add, x, offset1+offset2)). | |||
1008 | ||||
1009 | if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD) | |||
1010 | return false; | |||
1011 | ||||
1012 | if (N0.hasOneUse()) | |||
1013 | return false; | |||
1014 | ||||
1015 | auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
1016 | auto *C2 = dyn_cast<ConstantSDNode>(N1); | |||
1017 | if (!C1 || !C2) | |||
1018 | return false; | |||
1019 | ||||
1020 | const APInt &C1APIntVal = C1->getAPIntValue(); | |||
1021 | const APInt &C2APIntVal = C2->getAPIntValue(); | |||
1022 | if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64) | |||
1023 | return false; | |||
1024 | ||||
1025 | const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal; | |||
1026 | if (CombinedValueIntVal.getBitWidth() > 64) | |||
1027 | return false; | |||
1028 | const int64_t CombinedValue = CombinedValueIntVal.getSExtValue(); | |||
1029 | ||||
1030 | for (SDNode *Node : N0->uses()) { | |||
1031 | auto LoadStore = dyn_cast<MemSDNode>(Node); | |||
1032 | if (LoadStore) { | |||
1033 | // Is x[offset2] already not a legal addressing mode? If so then | |||
1034 | // reassociating the constants breaks nothing (we test offset2 because | |||
1035 | // that's the one we hope to fold into the load or store). | |||
1036 | TargetLoweringBase::AddrMode AM; | |||
1037 | AM.HasBaseReg = true; | |||
1038 | AM.BaseOffs = C2APIntVal.getSExtValue(); | |||
1039 | EVT VT = LoadStore->getMemoryVT(); | |||
1040 | unsigned AS = LoadStore->getAddressSpace(); | |||
1041 | Type *AccessTy = VT.getTypeForEVT(*DAG.getContext()); | |||
1042 | if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) | |||
1043 | continue; | |||
1044 | ||||
1045 | // Would x[offset1+offset2] still be a legal addressing mode? | |||
1046 | AM.BaseOffs = CombinedValue; | |||
1047 | if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) | |||
1048 | return true; | |||
1049 | } | |||
1050 | } | |||
1051 | ||||
1052 | return false; | |||
1053 | } | |||
1054 | ||||
1055 | // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression | |||
1056 | // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc. | |||
1057 | SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, | |||
1058 | SDValue N0, SDValue N1) { | |||
1059 | EVT VT = N0.getValueType(); | |||
1060 | ||||
1061 | if (N0.getOpcode() != Opc) | |||
1062 | return SDValue(); | |||
1063 | ||||
1064 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { | |||
1065 | if (DAG.isConstantIntBuildVectorOrConstantInt(N1)) { | |||
1066 | // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2)) | |||
1067 | if (SDValue OpNode = | |||
1068 | DAG.FoldConstantArithmetic(Opc, DL, VT, {N0.getOperand(1), N1})) | |||
1069 | return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); | |||
1070 | return SDValue(); | |||
1071 | } | |||
1072 | if (N0.hasOneUse()) { | |||
1073 | // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1) | |||
1074 | // iff (op x, c1) has one use | |||
1075 | SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); | |||
1076 | if (!OpNode.getNode()) | |||
1077 | return SDValue(); | |||
1078 | return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); | |||
1079 | } | |||
1080 | } | |||
1081 | return SDValue(); | |||
1082 | } | |||
1083 | ||||
1084 | // Try to reassociate commutative binops. | |||
1085 | SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, | |||
1086 | SDValue N1, SDNodeFlags Flags) { | |||
1087 | assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.")((TLI.isCommutativeBinOp(Opc) && "Operation not commutative." ) ? static_cast<void> (0) : __assert_fail ("TLI.isCommutativeBinOp(Opc) && \"Operation not commutative.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1087, __PRETTY_FUNCTION__)); | |||
1088 | ||||
1089 | // Floating-point reassociation is not allowed without loose FP math. | |||
1090 | if (N0.getValueType().isFloatingPoint() || | |||
1091 | N1.getValueType().isFloatingPoint()) | |||
1092 | if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros()) | |||
1093 | return SDValue(); | |||
1094 | ||||
1095 | if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1)) | |||
1096 | return Combined; | |||
1097 | if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0)) | |||
1098 | return Combined; | |||
1099 | return SDValue(); | |||
1100 | } | |||
1101 | ||||
1102 | SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, | |||
1103 | bool AddTo) { | |||
1104 | assert(N->getNumValues() == NumTo && "Broken CombineTo call!")((N->getNumValues() == NumTo && "Broken CombineTo call!" ) ? static_cast<void> (0) : __assert_fail ("N->getNumValues() == NumTo && \"Broken CombineTo call!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1104, __PRETTY_FUNCTION__)); | |||
1105 | ++NodesCombined; | |||
1106 | LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump (&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump (&DAG); dbgs() << " and " << NumTo - 1 << " other values\n"; } } while (false) | |||
1107 | To[0].getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump (&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump (&DAG); dbgs() << " and " << NumTo - 1 << " other values\n"; } } while (false) | |||
1108 | dbgs() << " and " << NumTo - 1 << " other values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump (&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump (&DAG); dbgs() << " and " << NumTo - 1 << " other values\n"; } } while (false); | |||
1109 | for (unsigned i = 0, e = NumTo; i != e; ++i) | |||
1110 | assert((!To[i].getNode() ||(((!To[i].getNode() || N->getValueType(i) == To[i].getValueType ()) && "Cannot combine value to value of different type!" ) ? static_cast<void> (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1112, __PRETTY_FUNCTION__)) | |||
1111 | N->getValueType(i) == To[i].getValueType()) &&(((!To[i].getNode() || N->getValueType(i) == To[i].getValueType ()) && "Cannot combine value to value of different type!" ) ? static_cast<void> (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1112, __PRETTY_FUNCTION__)) | |||
1112 | "Cannot combine value to value of different type!")(((!To[i].getNode() || N->getValueType(i) == To[i].getValueType ()) && "Cannot combine value to value of different type!" ) ? static_cast<void> (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1112, __PRETTY_FUNCTION__)); | |||
1113 | ||||
1114 | WorklistRemover DeadNodes(*this); | |||
1115 | DAG.ReplaceAllUsesWith(N, To); | |||
1116 | if (AddTo) { | |||
1117 | // Push the new nodes and any users onto the worklist | |||
1118 | for (unsigned i = 0, e = NumTo; i != e; ++i) { | |||
1119 | if (To[i].getNode()) { | |||
1120 | AddToWorklist(To[i].getNode()); | |||
1121 | AddUsersToWorklist(To[i].getNode()); | |||
1122 | } | |||
1123 | } | |||
1124 | } | |||
1125 | ||||
1126 | // Finally, if the node is now dead, remove it from the graph. The node | |||
1127 | // may not be dead if the replacement process recursively simplified to | |||
1128 | // something else needing this node. | |||
1129 | if (N->use_empty()) | |||
1130 | deleteAndRecombine(N); | |||
1131 | return SDValue(N, 0); | |||
1132 | } | |||
1133 | ||||
1134 | void DAGCombiner:: | |||
1135 | CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { | |||
1136 | // Replace the old value with the new one. | |||
1137 | ++NodesCombined; | |||
1138 | LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode ()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode ()->dump(&DAG); dbgs() << '\n'; } } while (false ) | |||
1139 | dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode ()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode ()->dump(&DAG); dbgs() << '\n'; } } while (false ) | |||
1140 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode ()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode ()->dump(&DAG); dbgs() << '\n'; } } while (false ); | |||
1141 | ||||
1142 | // Replace all uses. If any nodes become isomorphic to other nodes and | |||
1143 | // are deleted, make sure to remove them from our worklist. | |||
1144 | WorklistRemover DeadNodes(*this); | |||
1145 | DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); | |||
1146 | ||||
1147 | // Push the new node and any (possibly new) users onto the worklist. | |||
1148 | AddToWorklistWithUsers(TLO.New.getNode()); | |||
1149 | ||||
1150 | // Finally, if the node is now dead, remove it from the graph. The node | |||
1151 | // may not be dead if the replacement process recursively simplified to | |||
1152 | // something else needing this node. | |||
1153 | if (TLO.Old.getNode()->use_empty()) | |||
1154 | deleteAndRecombine(TLO.Old.getNode()); | |||
1155 | } | |||
1156 | ||||
1157 | /// Check the specified integer node value to see if it can be simplified or if | |||
1158 | /// things it uses can be simplified by bit propagation. If so, return true. | |||
1159 | bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, | |||
1160 | const APInt &DemandedElts, | |||
1161 | bool AssumeSingleUse) { | |||
1162 | TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); | |||
1163 | KnownBits Known; | |||
1164 | if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0, | |||
1165 | AssumeSingleUse)) | |||
1166 | return false; | |||
1167 | ||||
1168 | // Revisit the node. | |||
1169 | AddToWorklist(Op.getNode()); | |||
1170 | ||||
1171 | CommitTargetLoweringOpt(TLO); | |||
1172 | return true; | |||
1173 | } | |||
1174 | ||||
1175 | /// Check the specified vector node value to see if it can be simplified or | |||
1176 | /// if things it uses can be simplified as it only uses some of the elements. | |||
1177 | /// If so, return true. | |||
1178 | bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, | |||
1179 | const APInt &DemandedElts, | |||
1180 | bool AssumeSingleUse) { | |||
1181 | TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); | |||
1182 | APInt KnownUndef, KnownZero; | |||
1183 | if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, | |||
1184 | TLO, 0, AssumeSingleUse)) | |||
1185 | return false; | |||
1186 | ||||
1187 | // Revisit the node. | |||
1188 | AddToWorklist(Op.getNode()); | |||
1189 | ||||
1190 | CommitTargetLoweringOpt(TLO); | |||
1191 | return true; | |||
1192 | } | |||
1193 | ||||
1194 | void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { | |||
1195 | SDLoc DL(Load); | |||
1196 | EVT VT = Load->getValueType(0); | |||
1197 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); | |||
1198 | ||||
1199 | LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.9 "; Load-> dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false) | |||
1200 | Trunc.getNode()->dump(&DAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.9 "; Load-> dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false); | |||
1201 | WorklistRemover DeadNodes(*this); | |||
1202 | DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); | |||
1203 | DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); | |||
1204 | deleteAndRecombine(Load); | |||
1205 | AddToWorklist(Trunc.getNode()); | |||
1206 | } | |||
1207 | ||||
1208 | SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { | |||
1209 | Replace = false; | |||
1210 | SDLoc DL(Op); | |||
1211 | if (ISD::isUNINDEXEDLoad(Op.getNode())) { | |||
1212 | LoadSDNode *LD = cast<LoadSDNode>(Op); | |||
1213 | EVT MemVT = LD->getMemoryVT(); | |||
1214 | ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD | |||
1215 | : LD->getExtensionType(); | |||
1216 | Replace = true; | |||
1217 | return DAG.getExtLoad(ExtType, DL, PVT, | |||
1218 | LD->getChain(), LD->getBasePtr(), | |||
1219 | MemVT, LD->getMemOperand()); | |||
1220 | } | |||
1221 | ||||
1222 | unsigned Opc = Op.getOpcode(); | |||
1223 | switch (Opc) { | |||
1224 | default: break; | |||
1225 | case ISD::AssertSext: | |||
1226 | if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) | |||
1227 | return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); | |||
1228 | break; | |||
1229 | case ISD::AssertZext: | |||
1230 | if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) | |||
1231 | return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); | |||
1232 | break; | |||
1233 | case ISD::Constant: { | |||
1234 | unsigned ExtOpc = | |||
1235 | Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; | |||
1236 | return DAG.getNode(ExtOpc, DL, PVT, Op); | |||
1237 | } | |||
1238 | } | |||
1239 | ||||
1240 | if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) | |||
1241 | return SDValue(); | |||
1242 | return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); | |||
1243 | } | |||
1244 | ||||
1245 | SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { | |||
1246 | if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) | |||
1247 | return SDValue(); | |||
1248 | EVT OldVT = Op.getValueType(); | |||
1249 | SDLoc DL(Op); | |||
1250 | bool Replace = false; | |||
1251 | SDValue NewOp = PromoteOperand(Op, PVT, Replace); | |||
1252 | if (!NewOp.getNode()) | |||
1253 | return SDValue(); | |||
1254 | AddToWorklist(NewOp.getNode()); | |||
1255 | ||||
1256 | if (Replace) | |||
1257 | ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); | |||
1258 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, | |||
1259 | DAG.getValueType(OldVT)); | |||
1260 | } | |||
1261 | ||||
1262 | SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { | |||
1263 | EVT OldVT = Op.getValueType(); | |||
1264 | SDLoc DL(Op); | |||
1265 | bool Replace = false; | |||
1266 | SDValue NewOp = PromoteOperand(Op, PVT, Replace); | |||
1267 | if (!NewOp.getNode()) | |||
1268 | return SDValue(); | |||
1269 | AddToWorklist(NewOp.getNode()); | |||
1270 | ||||
1271 | if (Replace) | |||
1272 | ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); | |||
1273 | return DAG.getZeroExtendInReg(NewOp, DL, OldVT); | |||
1274 | } | |||
1275 | ||||
1276 | /// Promote the specified integer binary operation if the target indicates it is | |||
1277 | /// beneficial. e.g. On x86, it's usually better to promote i16 operations to | |||
1278 | /// i32 since i16 instructions are longer. | |||
1279 | SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { | |||
1280 | if (!LegalOperations) | |||
1281 | return SDValue(); | |||
1282 | ||||
1283 | EVT VT = Op.getValueType(); | |||
1284 | if (VT.isVector() || !VT.isInteger()) | |||
1285 | return SDValue(); | |||
1286 | ||||
1287 | // If operation type is 'undesirable', e.g. i16 on x86, consider | |||
1288 | // promoting it. | |||
1289 | unsigned Opc = Op.getOpcode(); | |||
1290 | if (TLI.isTypeDesirableForOp(Opc, VT)) | |||
1291 | return SDValue(); | |||
1292 | ||||
1293 | EVT PVT = VT; | |||
1294 | // Consult target whether it is a good idea to promote this operation and | |||
1295 | // what's the right type to promote it to. | |||
1296 | if (TLI.IsDesirableToPromoteOp(Op, PVT)) { | |||
1297 | assert(PVT != VT && "Don't know what type to promote to!")((PVT != VT && "Don't know what type to promote to!") ? static_cast<void> (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1297, __PRETTY_FUNCTION__)); | |||
1298 | ||||
1299 | LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode( )->dump(&DAG); } } while (false); | |||
1300 | ||||
1301 | bool Replace0 = false; | |||
1302 | SDValue N0 = Op.getOperand(0); | |||
1303 | SDValue NN0 = PromoteOperand(N0, PVT, Replace0); | |||
1304 | ||||
1305 | bool Replace1 = false; | |||
1306 | SDValue N1 = Op.getOperand(1); | |||
1307 | SDValue NN1 = PromoteOperand(N1, PVT, Replace1); | |||
1308 | SDLoc DL(Op); | |||
1309 | ||||
1310 | SDValue RV = | |||
1311 | DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); | |||
1312 | ||||
1313 | // We are always replacing N0/N1's use in N and only need additional | |||
1314 | // replacements if there are additional uses. | |||
1315 | // Note: We are checking uses of the *nodes* (SDNode) rather than values | |||
1316 | // (SDValue) here because the node may reference multiple values | |||
1317 | // (for example, the chain value of a load node). | |||
1318 | Replace0 &= !N0->hasOneUse(); | |||
1319 | Replace1 &= (N0 != N1) && !N1->hasOneUse(); | |||
1320 | ||||
1321 | // Combine Op here so it is preserved past replacements. | |||
1322 | CombineTo(Op.getNode(), RV); | |||
1323 | ||||
1324 | // If operands have a use ordering, make sure we deal with | |||
1325 | // predecessor first. | |||
1326 | if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { | |||
1327 | std::swap(N0, N1); | |||
1328 | std::swap(NN0, NN1); | |||
1329 | } | |||
1330 | ||||
1331 | if (Replace0) { | |||
1332 | AddToWorklist(NN0.getNode()); | |||
1333 | ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); | |||
1334 | } | |||
1335 | if (Replace1) { | |||
1336 | AddToWorklist(NN1.getNode()); | |||
1337 | ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); | |||
1338 | } | |||
1339 | return Op; | |||
1340 | } | |||
1341 | return SDValue(); | |||
1342 | } | |||
1343 | ||||
1344 | /// Promote the specified integer shift operation if the target indicates it is | |||
1345 | /// beneficial. e.g. On x86, it's usually better to promote i16 operations to | |||
1346 | /// i32 since i16 instructions are longer. | |||
1347 | SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { | |||
1348 | if (!LegalOperations) | |||
1349 | return SDValue(); | |||
1350 | ||||
1351 | EVT VT = Op.getValueType(); | |||
1352 | if (VT.isVector() || !VT.isInteger()) | |||
1353 | return SDValue(); | |||
1354 | ||||
1355 | // If operation type is 'undesirable', e.g. i16 on x86, consider | |||
1356 | // promoting it. | |||
1357 | unsigned Opc = Op.getOpcode(); | |||
1358 | if (TLI.isTypeDesirableForOp(Opc, VT)) | |||
1359 | return SDValue(); | |||
1360 | ||||
1361 | EVT PVT = VT; | |||
1362 | // Consult target whether it is a good idea to promote this operation and | |||
1363 | // what's the right type to promote it to. | |||
1364 | if (TLI.IsDesirableToPromoteOp(Op, PVT)) { | |||
1365 | assert(PVT != VT && "Don't know what type to promote to!")((PVT != VT && "Don't know what type to promote to!") ? static_cast<void> (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1365, __PRETTY_FUNCTION__)); | |||
1366 | ||||
1367 | LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode( )->dump(&DAG); } } while (false); | |||
1368 | ||||
1369 | bool Replace = false; | |||
1370 | SDValue N0 = Op.getOperand(0); | |||
1371 | SDValue N1 = Op.getOperand(1); | |||
1372 | if (Opc == ISD::SRA) | |||
1373 | N0 = SExtPromoteOperand(N0, PVT); | |||
1374 | else if (Opc == ISD::SRL) | |||
1375 | N0 = ZExtPromoteOperand(N0, PVT); | |||
1376 | else | |||
1377 | N0 = PromoteOperand(N0, PVT, Replace); | |||
1378 | ||||
1379 | if (!N0.getNode()) | |||
1380 | return SDValue(); | |||
1381 | ||||
1382 | SDLoc DL(Op); | |||
1383 | SDValue RV = | |||
1384 | DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); | |||
1385 | ||||
1386 | if (Replace) | |||
1387 | ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); | |||
1388 | ||||
1389 | // Deal with Op being deleted. | |||
1390 | if (Op && Op.getOpcode() != ISD::DELETED_NODE) | |||
1391 | return RV; | |||
1392 | } | |||
1393 | return SDValue(); | |||
1394 | } | |||
1395 | ||||
1396 | SDValue DAGCombiner::PromoteExtend(SDValue Op) { | |||
1397 | if (!LegalOperations) | |||
1398 | return SDValue(); | |||
1399 | ||||
1400 | EVT VT = Op.getValueType(); | |||
1401 | if (VT.isVector() || !VT.isInteger()) | |||
1402 | return SDValue(); | |||
1403 | ||||
1404 | // If operation type is 'undesirable', e.g. i16 on x86, consider | |||
1405 | // promoting it. | |||
1406 | unsigned Opc = Op.getOpcode(); | |||
1407 | if (TLI.isTypeDesirableForOp(Opc, VT)) | |||
1408 | return SDValue(); | |||
1409 | ||||
1410 | EVT PVT = VT; | |||
1411 | // Consult target whether it is a good idea to promote this operation and | |||
1412 | // what's the right type to promote it to. | |||
1413 | if (TLI.IsDesirableToPromoteOp(Op, PVT)) { | |||
1414 | assert(PVT != VT && "Don't know what type to promote to!")((PVT != VT && "Don't know what type to promote to!") ? static_cast<void> (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1414, __PRETTY_FUNCTION__)); | |||
1415 | // fold (aext (aext x)) -> (aext x) | |||
1416 | // fold (aext (zext x)) -> (zext x) | |||
1417 | // fold (aext (sext x)) -> (sext x) | |||
1418 | LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode( )->dump(&DAG); } } while (false); | |||
1419 | return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); | |||
1420 | } | |||
1421 | return SDValue(); | |||
1422 | } | |||
1423 | ||||
1424 | bool DAGCombiner::PromoteLoad(SDValue Op) { | |||
1425 | if (!LegalOperations) | |||
1426 | return false; | |||
1427 | ||||
1428 | if (!ISD::isUNINDEXEDLoad(Op.getNode())) | |||
1429 | return false; | |||
1430 | ||||
1431 | EVT VT = Op.getValueType(); | |||
1432 | if (VT.isVector() || !VT.isInteger()) | |||
1433 | return false; | |||
1434 | ||||
1435 | // If operation type is 'undesirable', e.g. i16 on x86, consider | |||
1436 | // promoting it. | |||
1437 | unsigned Opc = Op.getOpcode(); | |||
1438 | if (TLI.isTypeDesirableForOp(Opc, VT)) | |||
1439 | return false; | |||
1440 | ||||
1441 | EVT PVT = VT; | |||
1442 | // Consult target whether it is a good idea to promote this operation and | |||
1443 | // what's the right type to promote it to. | |||
1444 | if (TLI.IsDesirableToPromoteOp(Op, PVT)) { | |||
1445 | assert(PVT != VT && "Don't know what type to promote to!")((PVT != VT && "Don't know what type to promote to!") ? static_cast<void> (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1445, __PRETTY_FUNCTION__)); | |||
1446 | ||||
1447 | SDLoc DL(Op); | |||
1448 | SDNode *N = Op.getNode(); | |||
1449 | LoadSDNode *LD = cast<LoadSDNode>(N); | |||
1450 | EVT MemVT = LD->getMemoryVT(); | |||
1451 | ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD | |||
1452 | : LD->getExtensionType(); | |||
1453 | SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, | |||
1454 | LD->getChain(), LD->getBasePtr(), | |||
1455 | MemVT, LD->getMemOperand()); | |||
1456 | SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); | |||
1457 | ||||
1458 | LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nPromoting "; N->dump( &DAG); dbgs() << "\nTo: "; Result.getNode()->dump (&DAG); dbgs() << '\n'; } } while (false) | |||
1459 | Result.getNode()->dump(&DAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nPromoting "; N->dump( &DAG); dbgs() << "\nTo: "; Result.getNode()->dump (&DAG); dbgs() << '\n'; } } while (false); | |||
1460 | WorklistRemover DeadNodes(*this); | |||
1461 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); | |||
1462 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); | |||
1463 | deleteAndRecombine(N); | |||
1464 | AddToWorklist(Result.getNode()); | |||
1465 | return true; | |||
1466 | } | |||
1467 | return false; | |||
1468 | } | |||
1469 | ||||
1470 | /// Recursively delete a node which has no uses and any operands for | |||
1471 | /// which it is the only use. | |||
1472 | /// | |||
1473 | /// Note that this both deletes the nodes and removes them from the worklist. | |||
1474 | /// It also adds any nodes who have had a user deleted to the worklist as they | |||
1475 | /// may now have only one use and subject to other combines. | |||
1476 | bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { | |||
1477 | if (!N->use_empty()) | |||
1478 | return false; | |||
1479 | ||||
1480 | SmallSetVector<SDNode *, 16> Nodes; | |||
1481 | Nodes.insert(N); | |||
1482 | do { | |||
1483 | N = Nodes.pop_back_val(); | |||
1484 | if (!N) | |||
1485 | continue; | |||
1486 | ||||
1487 | if (N->use_empty()) { | |||
1488 | for (const SDValue &ChildN : N->op_values()) | |||
1489 | Nodes.insert(ChildN.getNode()); | |||
1490 | ||||
1491 | removeFromWorklist(N); | |||
1492 | DAG.DeleteNode(N); | |||
1493 | } else { | |||
1494 | AddToWorklist(N); | |||
1495 | } | |||
1496 | } while (!Nodes.empty()); | |||
1497 | return true; | |||
1498 | } | |||
1499 | ||||
1500 | //===----------------------------------------------------------------------===// | |||
1501 | // Main DAG Combiner implementation | |||
1502 | //===----------------------------------------------------------------------===// | |||
1503 | ||||
1504 | void DAGCombiner::Run(CombineLevel AtLevel) { | |||
1505 | // set the instance variables, so that the various visit routines may use it. | |||
1506 | Level = AtLevel; | |||
1507 | LegalDAG = Level >= AfterLegalizeDAG; | |||
1508 | LegalOperations = Level >= AfterLegalizeVectorOps; | |||
1509 | LegalTypes = Level >= AfterLegalizeTypes; | |||
1510 | ||||
1511 | WorklistInserter AddNodes(*this); | |||
1512 | ||||
1513 | // Add all the dag nodes to the worklist. | |||
1514 | for (SDNode &Node : DAG.allnodes()) | |||
1515 | AddToWorklist(&Node); | |||
1516 | ||||
1517 | // Create a dummy node (which is not added to allnodes), that adds a reference | |||
1518 | // to the root node, preventing it from being deleted, and tracking any | |||
1519 | // changes of the root. | |||
1520 | HandleSDNode Dummy(DAG.getRoot()); | |||
1521 | ||||
1522 | // While we have a valid worklist entry node, try to combine it. | |||
1523 | while (SDNode *N = getNextWorklistEntry()) { | |||
1524 | // If N has no uses, it is dead. Make sure to revisit all N's operands once | |||
1525 | // N is deleted from the DAG, since they too may now be dead or may have a | |||
1526 | // reduced number of uses, allowing other xforms. | |||
1527 | if (recursivelyDeleteUnusedNodes(N)) | |||
1528 | continue; | |||
1529 | ||||
1530 | WorklistRemover DeadNodes(*this); | |||
1531 | ||||
1532 | // If this combine is running after legalizing the DAG, re-legalize any | |||
1533 | // nodes pulled off the worklist. | |||
1534 | if (LegalDAG) { | |||
1535 | SmallSetVector<SDNode *, 16> UpdatedNodes; | |||
1536 | bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); | |||
1537 | ||||
1538 | for (SDNode *LN : UpdatedNodes) | |||
1539 | AddToWorklistWithUsers(LN); | |||
1540 | ||||
1541 | if (!NIsValid) | |||
1542 | continue; | |||
1543 | } | |||
1544 | ||||
1545 | LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nCombining: "; N->dump (&DAG); } } while (false); | |||
1546 | ||||
1547 | // Add any operands of the new node which have not yet been combined to the | |||
1548 | // worklist as well. Because the worklist uniques things already, this | |||
1549 | // won't repeatedly process the same operand. | |||
1550 | CombinedNodes.insert(N); | |||
1551 | for (const SDValue &ChildN : N->op_values()) | |||
1552 | if (!CombinedNodes.count(ChildN.getNode())) | |||
1553 | AddToWorklist(ChildN.getNode()); | |||
1554 | ||||
1555 | SDValue RV = combine(N); | |||
1556 | ||||
1557 | if (!RV.getNode()) | |||
1558 | continue; | |||
1559 | ||||
1560 | ++NodesCombined; | |||
1561 | ||||
1562 | // If we get back the same node we passed in, rather than a new node or | |||
1563 | // zero, we know that the node must have defined multiple values and | |||
1564 | // CombineTo was used. Since CombineTo takes care of the worklist | |||
1565 | // mechanics for us, we have no work to do in this case. | |||
1566 | if (RV.getNode() == N) | |||
1567 | continue; | |||
1568 | ||||
1569 | assert(N->getOpcode() != ISD::DELETED_NODE &&((N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode () != ISD::DELETED_NODE && "Node was deleted but visit returned new node!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1571, __PRETTY_FUNCTION__)) | |||
1570 | RV.getOpcode() != ISD::DELETED_NODE &&((N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode () != ISD::DELETED_NODE && "Node was deleted but visit returned new node!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1571, __PRETTY_FUNCTION__)) | |||
1571 | "Node was deleted but visit returned new node!")((N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode () != ISD::DELETED_NODE && "Node was deleted but visit returned new node!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1571, __PRETTY_FUNCTION__)); | |||
1572 | ||||
1573 | LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << " ... into: "; RV.getNode() ->dump(&DAG); } } while (false); | |||
1574 | ||||
1575 | if (N->getNumValues() == RV.getNode()->getNumValues()) | |||
1576 | DAG.ReplaceAllUsesWith(N, RV.getNode()); | |||
1577 | else { | |||
1578 | assert(N->getValueType(0) == RV.getValueType() &&((N->getValueType(0) == RV.getValueType() && N-> getNumValues() == 1 && "Type mismatch") ? static_cast <void> (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1579, __PRETTY_FUNCTION__)) | |||
1579 | N->getNumValues() == 1 && "Type mismatch")((N->getValueType(0) == RV.getValueType() && N-> getNumValues() == 1 && "Type mismatch") ? static_cast <void> (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1579, __PRETTY_FUNCTION__)); | |||
1580 | DAG.ReplaceAllUsesWith(N, &RV); | |||
1581 | } | |||
1582 | ||||
1583 | // Push the new node and any users onto the worklist. Omit this if the | |||
1584 | // new node is the EntryToken (e.g. if a store managed to get optimized | |||
1585 | // out), because re-visiting the EntryToken and its users will not uncover | |||
1586 | // any additional opportunities, but there may be a large number of such | |||
1587 | // users, potentially causing compile time explosion. | |||
1588 | if (RV.getOpcode() != ISD::EntryToken) { | |||
1589 | AddToWorklist(RV.getNode()); | |||
1590 | AddUsersToWorklist(RV.getNode()); | |||
1591 | } | |||
1592 | ||||
1593 | // Finally, if the node is now dead, remove it from the graph. The node | |||
1594 | // may not be dead if the replacement process recursively simplified to | |||
1595 | // something else needing this node. This will also take care of adding any | |||
1596 | // operands which have lost a user to the worklist. | |||
1597 | recursivelyDeleteUnusedNodes(N); | |||
1598 | } | |||
1599 | ||||
1600 | // If the root changed (e.g. it was a dead load, update the root). | |||
1601 | DAG.setRoot(Dummy.getValue()); | |||
1602 | DAG.RemoveDeadNodes(); | |||
1603 | } | |||
1604 | ||||
1605 | SDValue DAGCombiner::visit(SDNode *N) { | |||
1606 | switch (N->getOpcode()) { | |||
1607 | default: break; | |||
1608 | case ISD::TokenFactor: return visitTokenFactor(N); | |||
1609 | case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); | |||
1610 | case ISD::ADD: return visitADD(N); | |||
1611 | case ISD::SUB: return visitSUB(N); | |||
1612 | case ISD::SADDSAT: | |||
1613 | case ISD::UADDSAT: return visitADDSAT(N); | |||
1614 | case ISD::SSUBSAT: | |||
1615 | case ISD::USUBSAT: return visitSUBSAT(N); | |||
1616 | case ISD::ADDC: return visitADDC(N); | |||
1617 | case ISD::SADDO: | |||
1618 | case ISD::UADDO: return visitADDO(N); | |||
1619 | case ISD::SUBC: return visitSUBC(N); | |||
1620 | case ISD::SSUBO: | |||
1621 | case ISD::USUBO: return visitSUBO(N); | |||
1622 | case ISD::ADDE: return visitADDE(N); | |||
1623 | case ISD::ADDCARRY: return visitADDCARRY(N); | |||
1624 | case ISD::SADDO_CARRY: return visitSADDO_CARRY(N); | |||
1625 | case ISD::SUBE: return visitSUBE(N); | |||
1626 | case ISD::SUBCARRY: return visitSUBCARRY(N); | |||
1627 | case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N); | |||
1628 | case ISD::SMULFIX: | |||
1629 | case ISD::SMULFIXSAT: | |||
1630 | case ISD::UMULFIX: | |||
1631 | case ISD::UMULFIXSAT: return visitMULFIX(N); | |||
1632 | case ISD::MUL: return visitMUL(N); | |||
1633 | case ISD::SDIV: return visitSDIV(N); | |||
1634 | case ISD::UDIV: return visitUDIV(N); | |||
1635 | case ISD::SREM: | |||
1636 | case ISD::UREM: return visitREM(N); | |||
1637 | case ISD::MULHU: return visitMULHU(N); | |||
1638 | case ISD::MULHS: return visitMULHS(N); | |||
1639 | case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); | |||
1640 | case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); | |||
1641 | case ISD::SMULO: | |||
1642 | case ISD::UMULO: return visitMULO(N); | |||
1643 | case ISD::SMIN: | |||
1644 | case ISD::SMAX: | |||
1645 | case ISD::UMIN: | |||
1646 | case ISD::UMAX: return visitIMINMAX(N); | |||
1647 | case ISD::AND: return visitAND(N); | |||
1648 | case ISD::OR: return visitOR(N); | |||
1649 | case ISD::XOR: return visitXOR(N); | |||
1650 | case ISD::SHL: return visitSHL(N); | |||
1651 | case ISD::SRA: return visitSRA(N); | |||
1652 | case ISD::SRL: return visitSRL(N); | |||
1653 | case ISD::ROTR: | |||
1654 | case ISD::ROTL: return visitRotate(N); | |||
1655 | case ISD::FSHL: | |||
1656 | case ISD::FSHR: return visitFunnelShift(N); | |||
1657 | case ISD::ABS: return visitABS(N); | |||
1658 | case ISD::BSWAP: return visitBSWAP(N); | |||
1659 | case ISD::BITREVERSE: return visitBITREVERSE(N); | |||
1660 | case ISD::CTLZ: return visitCTLZ(N); | |||
1661 | case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); | |||
1662 | case ISD::CTTZ: return visitCTTZ(N); | |||
1663 | case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); | |||
1664 | case ISD::CTPOP: return visitCTPOP(N); | |||
1665 | case ISD::SELECT: return visitSELECT(N); | |||
1666 | case ISD::VSELECT: return visitVSELECT(N); | |||
1667 | case ISD::SELECT_CC: return visitSELECT_CC(N); | |||
1668 | case ISD::SETCC: return visitSETCC(N); | |||
1669 | case ISD::SETCCCARRY: return visitSETCCCARRY(N); | |||
1670 | case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); | |||
1671 | case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); | |||
1672 | case ISD::ANY_EXTEND: return visitANY_EXTEND(N); | |||
1673 | case ISD::AssertSext: | |||
1674 | case ISD::AssertZext: return visitAssertExt(N); | |||
1675 | case ISD::AssertAlign: return visitAssertAlign(N); | |||
1676 | case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); | |||
1677 | case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); | |||
1678 | case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); | |||
1679 | case ISD::TRUNCATE: return visitTRUNCATE(N); | |||
1680 | case ISD::BITCAST: return visitBITCAST(N); | |||
1681 | case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); | |||
1682 | case ISD::FADD: return visitFADD(N); | |||
1683 | case ISD::STRICT_FADD: return visitSTRICT_FADD(N); | |||
1684 | case ISD::FSUB: return visitFSUB(N); | |||
1685 | case ISD::FMUL: return visitFMUL(N); | |||
1686 | case ISD::FMA: return visitFMA(N); | |||
1687 | case ISD::FDIV: return visitFDIV(N); | |||
1688 | case ISD::FREM: return visitFREM(N); | |||
1689 | case ISD::FSQRT: return visitFSQRT(N); | |||
1690 | case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); | |||
1691 | case ISD::FPOW: return visitFPOW(N); | |||
1692 | case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); | |||
1693 | case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); | |||
1694 | case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); | |||
1695 | case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); | |||
1696 | case ISD::FP_ROUND: return visitFP_ROUND(N); | |||
1697 | case ISD::FP_EXTEND: return visitFP_EXTEND(N); | |||
1698 | case ISD::FNEG: return visitFNEG(N); | |||
1699 | case ISD::FABS: return visitFABS(N); | |||
1700 | case ISD::FFLOOR: return visitFFLOOR(N); | |||
1701 | case ISD::FMINNUM: return visitFMINNUM(N); | |||
1702 | case ISD::FMAXNUM: return visitFMAXNUM(N); | |||
1703 | case ISD::FMINIMUM: return visitFMINIMUM(N); | |||
1704 | case ISD::FMAXIMUM: return visitFMAXIMUM(N); | |||
1705 | case ISD::FCEIL: return visitFCEIL(N); | |||
1706 | case ISD::FTRUNC: return visitFTRUNC(N); | |||
1707 | case ISD::BRCOND: return visitBRCOND(N); | |||
1708 | case ISD::BR_CC: return visitBR_CC(N); | |||
1709 | case ISD::LOAD: return visitLOAD(N); | |||
1710 | case ISD::STORE: return visitSTORE(N); | |||
1711 | case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); | |||
1712 | case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); | |||
1713 | case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); | |||
1714 | case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); | |||
1715 | case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); | |||
1716 | case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); | |||
1717 | case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); | |||
1718 | case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); | |||
1719 | case ISD::MGATHER: return visitMGATHER(N); | |||
1720 | case ISD::MLOAD: return visitMLOAD(N); | |||
1721 | case ISD::MSCATTER: return visitMSCATTER(N); | |||
1722 | case ISD::MSTORE: return visitMSTORE(N); | |||
1723 | case ISD::LIFETIME_END: return visitLIFETIME_END(N); | |||
1724 | case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); | |||
1725 | case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); | |||
1726 | case ISD::FREEZE: return visitFREEZE(N); | |||
1727 | case ISD::VECREDUCE_FADD: | |||
1728 | case ISD::VECREDUCE_FMUL: | |||
1729 | case ISD::VECREDUCE_ADD: | |||
1730 | case ISD::VECREDUCE_MUL: | |||
1731 | case ISD::VECREDUCE_AND: | |||
1732 | case ISD::VECREDUCE_OR: | |||
1733 | case ISD::VECREDUCE_XOR: | |||
1734 | case ISD::VECREDUCE_SMAX: | |||
1735 | case ISD::VECREDUCE_SMIN: | |||
1736 | case ISD::VECREDUCE_UMAX: | |||
1737 | case ISD::VECREDUCE_UMIN: | |||
1738 | case ISD::VECREDUCE_FMAX: | |||
1739 | case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N); | |||
1740 | } | |||
1741 | return SDValue(); | |||
1742 | } | |||
1743 | ||||
1744 | SDValue DAGCombiner::combine(SDNode *N) { | |||
1745 | SDValue RV; | |||
1746 | if (!DisableGenericCombines) | |||
1747 | RV = visit(N); | |||
1748 | ||||
1749 | // If nothing happened, try a target-specific DAG combine. | |||
1750 | if (!RV.getNode()) { | |||
1751 | assert(N->getOpcode() != ISD::DELETED_NODE &&((N->getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned NULL!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1752, __PRETTY_FUNCTION__)) | |||
1752 | "Node was deleted but visit returned NULL!")((N->getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned NULL!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1752, __PRETTY_FUNCTION__)); | |||
1753 | ||||
1754 | if (N->getOpcode() >= ISD::BUILTIN_OP_END || | |||
1755 | TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { | |||
1756 | ||||
1757 | // Expose the DAG combiner to the target combiner impls. | |||
1758 | TargetLowering::DAGCombinerInfo | |||
1759 | DagCombineInfo(DAG, Level, false, this); | |||
1760 | ||||
1761 | RV = TLI.PerformDAGCombine(N, DagCombineInfo); | |||
1762 | } | |||
1763 | } | |||
1764 | ||||
1765 | // If nothing happened still, try promoting the operation. | |||
1766 | if (!RV.getNode()) { | |||
1767 | switch (N->getOpcode()) { | |||
1768 | default: break; | |||
1769 | case ISD::ADD: | |||
1770 | case ISD::SUB: | |||
1771 | case ISD::MUL: | |||
1772 | case ISD::AND: | |||
1773 | case ISD::OR: | |||
1774 | case ISD::XOR: | |||
1775 | RV = PromoteIntBinOp(SDValue(N, 0)); | |||
1776 | break; | |||
1777 | case ISD::SHL: | |||
1778 | case ISD::SRA: | |||
1779 | case ISD::SRL: | |||
1780 | RV = PromoteIntShiftOp(SDValue(N, 0)); | |||
1781 | break; | |||
1782 | case ISD::SIGN_EXTEND: | |||
1783 | case ISD::ZERO_EXTEND: | |||
1784 | case ISD::ANY_EXTEND: | |||
1785 | RV = PromoteExtend(SDValue(N, 0)); | |||
1786 | break; | |||
1787 | case ISD::LOAD: | |||
1788 | if (PromoteLoad(SDValue(N, 0))) | |||
1789 | RV = SDValue(N, 0); | |||
1790 | break; | |||
1791 | } | |||
1792 | } | |||
1793 | ||||
1794 | // If N is a commutative binary node, try to eliminate it if the commuted | |||
1795 | // version is already present in the DAG. | |||
1796 | if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && | |||
1797 | N->getNumValues() == 1) { | |||
1798 | SDValue N0 = N->getOperand(0); | |||
1799 | SDValue N1 = N->getOperand(1); | |||
1800 | ||||
1801 | // Constant operands are canonicalized to RHS. | |||
1802 | if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { | |||
1803 | SDValue Ops[] = {N1, N0}; | |||
1804 | SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, | |||
1805 | N->getFlags()); | |||
1806 | if (CSENode) | |||
1807 | return SDValue(CSENode, 0); | |||
1808 | } | |||
1809 | } | |||
1810 | ||||
1811 | return RV; | |||
1812 | } | |||
1813 | ||||
1814 | /// Given a node, return its input chain if it has one, otherwise return a null | |||
1815 | /// sd operand. | |||
1816 | static SDValue getInputChainForNode(SDNode *N) { | |||
1817 | if (unsigned NumOps = N->getNumOperands()) { | |||
1818 | if (N->getOperand(0).getValueType() == MVT::Other) | |||
1819 | return N->getOperand(0); | |||
1820 | if (N->getOperand(NumOps-1).getValueType() == MVT::Other) | |||
1821 | return N->getOperand(NumOps-1); | |||
1822 | for (unsigned i = 1; i < NumOps-1; ++i) | |||
1823 | if (N->getOperand(i).getValueType() == MVT::Other) | |||
1824 | return N->getOperand(i); | |||
1825 | } | |||
1826 | return SDValue(); | |||
1827 | } | |||
1828 | ||||
1829 | SDValue DAGCombiner::visitTokenFactor(SDNode *N) { | |||
1830 | // If N has two operands, where one has an input chain equal to the other, | |||
1831 | // the 'other' chain is redundant. | |||
1832 | if (N->getNumOperands() == 2) { | |||
1833 | if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) | |||
1834 | return N->getOperand(0); | |||
1835 | if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) | |||
1836 | return N->getOperand(1); | |||
1837 | } | |||
1838 | ||||
1839 | // Don't simplify token factors if optnone. | |||
1840 | if (OptLevel == CodeGenOpt::None) | |||
1841 | return SDValue(); | |||
1842 | ||||
1843 | // Don't simplify the token factor if the node itself has too many operands. | |||
1844 | if (N->getNumOperands() > TokenFactorInlineLimit) | |||
1845 | return SDValue(); | |||
1846 | ||||
1847 | // If the sole user is a token factor, we should make sure we have a | |||
1848 | // chance to merge them together. This prevents TF chains from inhibiting | |||
1849 | // optimizations. | |||
1850 | if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor) | |||
1851 | AddToWorklist(*(N->use_begin())); | |||
1852 | ||||
1853 | SmallVector<SDNode *, 8> TFs; // List of token factors to visit. | |||
1854 | SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. | |||
1855 | SmallPtrSet<SDNode*, 16> SeenOps; | |||
1856 | bool Changed = false; // If we should replace this token factor. | |||
1857 | ||||
1858 | // Start out with this token factor. | |||
1859 | TFs.push_back(N); | |||
1860 | ||||
1861 | // Iterate through token factors. The TFs grows when new token factors are | |||
1862 | // encountered. | |||
1863 | for (unsigned i = 0; i < TFs.size(); ++i) { | |||
1864 | // Limit number of nodes to inline, to avoid quadratic compile times. | |||
1865 | // We have to add the outstanding Token Factors to Ops, otherwise we might | |||
1866 | // drop Ops from the resulting Token Factors. | |||
1867 | if (Ops.size() > TokenFactorInlineLimit) { | |||
1868 | for (unsigned j = i; j < TFs.size(); j++) | |||
1869 | Ops.emplace_back(TFs[j], 0); | |||
1870 | // Drop unprocessed Token Factors from TFs, so we do not add them to the | |||
1871 | // combiner worklist later. | |||
1872 | TFs.resize(i); | |||
1873 | break; | |||
1874 | } | |||
1875 | ||||
1876 | SDNode *TF = TFs[i]; | |||
1877 | // Check each of the operands. | |||
1878 | for (const SDValue &Op : TF->op_values()) { | |||
1879 | switch (Op.getOpcode()) { | |||
1880 | case ISD::EntryToken: | |||
1881 | // Entry tokens don't need to be added to the list. They are | |||
1882 | // redundant. | |||
1883 | Changed = true; | |||
1884 | break; | |||
1885 | ||||
1886 | case ISD::TokenFactor: | |||
1887 | if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { | |||
1888 | // Queue up for processing. | |||
1889 | TFs.push_back(Op.getNode()); | |||
1890 | Changed = true; | |||
1891 | break; | |||
1892 | } | |||
1893 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1894 | ||||
1895 | default: | |||
1896 | // Only add if it isn't already in the list. | |||
1897 | if (SeenOps.insert(Op.getNode()).second) | |||
1898 | Ops.push_back(Op); | |||
1899 | else | |||
1900 | Changed = true; | |||
1901 | break; | |||
1902 | } | |||
1903 | } | |||
1904 | } | |||
1905 | ||||
1906 | // Re-visit inlined Token Factors, to clean them up in case they have been | |||
1907 | // removed. Skip the first Token Factor, as this is the current node. | |||
1908 | for (unsigned i = 1, e = TFs.size(); i < e; i++) | |||
1909 | AddToWorklist(TFs[i]); | |||
1910 | ||||
1911 | // Remove Nodes that are chained to another node in the list. Do so | |||
1912 | // by walking up chains breath-first stopping when we've seen | |||
1913 | // another operand. In general we must climb to the EntryNode, but we can exit | |||
1914 | // early if we find all remaining work is associated with just one operand as | |||
1915 | // no further pruning is possible. | |||
1916 | ||||
1917 | // List of nodes to search through and original Ops from which they originate. | |||
1918 | SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; | |||
1919 | SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. | |||
1920 | SmallPtrSet<SDNode *, 16> SeenChains; | |||
1921 | bool DidPruneOps = false; | |||
1922 | ||||
1923 | unsigned NumLeftToConsider = 0; | |||
1924 | for (const SDValue &Op : Ops) { | |||
1925 | Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); | |||
1926 | OpWorkCount.push_back(1); | |||
1927 | } | |||
1928 | ||||
1929 | auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { | |||
1930 | // If this is an Op, we can remove the op from the list. Remark any | |||
1931 | // search associated with it as from the current OpNumber. | |||
1932 | if (SeenOps.contains(Op)) { | |||
1933 | Changed = true; | |||
1934 | DidPruneOps = true; | |||
1935 | unsigned OrigOpNumber = 0; | |||
1936 | while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) | |||
1937 | OrigOpNumber++; | |||
1938 | assert((OrigOpNumber != Ops.size()) &&(((OrigOpNumber != Ops.size()) && "expected to find TokenFactor Operand" ) ? static_cast<void> (0) : __assert_fail ("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1939, __PRETTY_FUNCTION__)) | |||
1939 | "expected to find TokenFactor Operand")(((OrigOpNumber != Ops.size()) && "expected to find TokenFactor Operand" ) ? static_cast<void> (0) : __assert_fail ("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1939, __PRETTY_FUNCTION__)); | |||
1940 | // Re-mark worklist from OrigOpNumber to OpNumber | |||
1941 | for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { | |||
1942 | if (Worklist[i].second == OrigOpNumber) { | |||
1943 | Worklist[i].second = OpNumber; | |||
1944 | } | |||
1945 | } | |||
1946 | OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; | |||
1947 | OpWorkCount[OrigOpNumber] = 0; | |||
1948 | NumLeftToConsider--; | |||
1949 | } | |||
1950 | // Add if it's a new chain | |||
1951 | if (SeenChains.insert(Op).second) { | |||
1952 | OpWorkCount[OpNumber]++; | |||
1953 | Worklist.push_back(std::make_pair(Op, OpNumber)); | |||
1954 | } | |||
1955 | }; | |||
1956 | ||||
1957 | for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { | |||
1958 | // We need at least be consider at least 2 Ops to prune. | |||
1959 | if (NumLeftToConsider <= 1) | |||
1960 | break; | |||
1961 | auto CurNode = Worklist[i].first; | |||
1962 | auto CurOpNumber = Worklist[i].second; | |||
1963 | assert((OpWorkCount[CurOpNumber] > 0) &&(((OpWorkCount[CurOpNumber] > 0) && "Node should not appear in worklist" ) ? static_cast<void> (0) : __assert_fail ("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1964, __PRETTY_FUNCTION__)) | |||
1964 | "Node should not appear in worklist")(((OpWorkCount[CurOpNumber] > 0) && "Node should not appear in worklist" ) ? static_cast<void> (0) : __assert_fail ("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 1964, __PRETTY_FUNCTION__)); | |||
1965 | switch (CurNode->getOpcode()) { | |||
1966 | case ISD::EntryToken: | |||
1967 | // Hitting EntryToken is the only way for the search to terminate without | |||
1968 | // hitting | |||
1969 | // another operand's search. Prevent us from marking this operand | |||
1970 | // considered. | |||
1971 | NumLeftToConsider++; | |||
1972 | break; | |||
1973 | case ISD::TokenFactor: | |||
1974 | for (const SDValue &Op : CurNode->op_values()) | |||
1975 | AddToWorklist(i, Op.getNode(), CurOpNumber); | |||
1976 | break; | |||
1977 | case ISD::LIFETIME_START: | |||
1978 | case ISD::LIFETIME_END: | |||
1979 | case ISD::CopyFromReg: | |||
1980 | case ISD::CopyToReg: | |||
1981 | AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); | |||
1982 | break; | |||
1983 | default: | |||
1984 | if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) | |||
1985 | AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); | |||
1986 | break; | |||
1987 | } | |||
1988 | OpWorkCount[CurOpNumber]--; | |||
1989 | if (OpWorkCount[CurOpNumber] == 0) | |||
1990 | NumLeftToConsider--; | |||
1991 | } | |||
1992 | ||||
1993 | // If we've changed things around then replace token factor. | |||
1994 | if (Changed) { | |||
1995 | SDValue Result; | |||
1996 | if (Ops.empty()) { | |||
1997 | // The entry token is the only possible outcome. | |||
1998 | Result = DAG.getEntryNode(); | |||
1999 | } else { | |||
2000 | if (DidPruneOps) { | |||
2001 | SmallVector<SDValue, 8> PrunedOps; | |||
2002 | // | |||
2003 | for (const SDValue &Op : Ops) { | |||
2004 | if (SeenChains.count(Op.getNode()) == 0) | |||
2005 | PrunedOps.push_back(Op); | |||
2006 | } | |||
2007 | Result = DAG.getTokenFactor(SDLoc(N), PrunedOps); | |||
2008 | } else { | |||
2009 | Result = DAG.getTokenFactor(SDLoc(N), Ops); | |||
2010 | } | |||
2011 | } | |||
2012 | return Result; | |||
2013 | } | |||
2014 | return SDValue(); | |||
2015 | } | |||
2016 | ||||
2017 | /// MERGE_VALUES can always be eliminated. | |||
2018 | SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { | |||
2019 | WorklistRemover DeadNodes(*this); | |||
2020 | // Replacing results may cause a different MERGE_VALUES to suddenly | |||
2021 | // be CSE'd with N, and carry its uses with it. Iterate until no | |||
2022 | // uses remain, to ensure that the node can be safely deleted. | |||
2023 | // First add the users of this node to the work list so that they | |||
2024 | // can be tried again once they have new operands. | |||
2025 | AddUsersToWorklist(N); | |||
2026 | do { | |||
2027 | // Do as a single replacement to avoid rewalking use lists. | |||
2028 | SmallVector<SDValue, 8> Ops; | |||
2029 | for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) | |||
2030 | Ops.push_back(N->getOperand(i)); | |||
2031 | DAG.ReplaceAllUsesWith(N, Ops.data()); | |||
2032 | } while (!N->use_empty()); | |||
2033 | deleteAndRecombine(N); | |||
2034 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
2035 | } | |||
2036 | ||||
2037 | /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a | |||
2038 | /// ConstantSDNode pointer else nullptr. | |||
2039 | static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { | |||
2040 | ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); | |||
2041 | return Const != nullptr && !Const->isOpaque() ? Const : nullptr; | |||
2042 | } | |||
2043 | ||||
2044 | /// Return true if 'Use' is a load or a store that uses N as its base pointer | |||
2045 | /// and that N may be folded in the load / store addressing mode. | |||
2046 | static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG, | |||
2047 | const TargetLowering &TLI) { | |||
2048 | EVT VT; | |||
2049 | unsigned AS; | |||
2050 | ||||
2051 | if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { | |||
2052 | if (LD->isIndexed() || LD->getBasePtr().getNode() != N) | |||
2053 | return false; | |||
2054 | VT = LD->getMemoryVT(); | |||
2055 | AS = LD->getAddressSpace(); | |||
2056 | } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { | |||
2057 | if (ST->isIndexed() || ST->getBasePtr().getNode() != N) | |||
2058 | return false; | |||
2059 | VT = ST->getMemoryVT(); | |||
2060 | AS = ST->getAddressSpace(); | |||
2061 | } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) { | |||
2062 | if (LD->isIndexed() || LD->getBasePtr().getNode() != N) | |||
2063 | return false; | |||
2064 | VT = LD->getMemoryVT(); | |||
2065 | AS = LD->getAddressSpace(); | |||
2066 | } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) { | |||
2067 | if (ST->isIndexed() || ST->getBasePtr().getNode() != N) | |||
2068 | return false; | |||
2069 | VT = ST->getMemoryVT(); | |||
2070 | AS = ST->getAddressSpace(); | |||
2071 | } else | |||
2072 | return false; | |||
2073 | ||||
2074 | TargetLowering::AddrMode AM; | |||
2075 | if (N->getOpcode() == ISD::ADD) { | |||
2076 | AM.HasBaseReg = true; | |||
2077 | ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); | |||
2078 | if (Offset) | |||
2079 | // [reg +/- imm] | |||
2080 | AM.BaseOffs = Offset->getSExtValue(); | |||
2081 | else | |||
2082 | // [reg +/- reg] | |||
2083 | AM.Scale = 1; | |||
2084 | } else if (N->getOpcode() == ISD::SUB) { | |||
2085 | AM.HasBaseReg = true; | |||
2086 | ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); | |||
2087 | if (Offset) | |||
2088 | // [reg +/- imm] | |||
2089 | AM.BaseOffs = -Offset->getSExtValue(); | |||
2090 | else | |||
2091 | // [reg +/- reg] | |||
2092 | AM.Scale = 1; | |||
2093 | } else | |||
2094 | return false; | |||
2095 | ||||
2096 | return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, | |||
2097 | VT.getTypeForEVT(*DAG.getContext()), AS); | |||
2098 | } | |||
2099 | ||||
2100 | SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { | |||
2101 | assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&((TLI.isBinOp(BO->getOpcode()) && BO->getNumValues () == 1 && "Unexpected binary operator") ? static_cast <void> (0) : __assert_fail ("TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && \"Unexpected binary operator\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2102, __PRETTY_FUNCTION__)) | |||
2102 | "Unexpected binary operator")((TLI.isBinOp(BO->getOpcode()) && BO->getNumValues () == 1 && "Unexpected binary operator") ? static_cast <void> (0) : __assert_fail ("TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && \"Unexpected binary operator\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2102, __PRETTY_FUNCTION__)); | |||
2103 | ||||
2104 | // Don't do this unless the old select is going away. We want to eliminate the | |||
2105 | // binary operator, not replace a binop with a select. | |||
2106 | // TODO: Handle ISD::SELECT_CC. | |||
2107 | unsigned SelOpNo = 0; | |||
2108 | SDValue Sel = BO->getOperand(0); | |||
2109 | if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { | |||
2110 | SelOpNo = 1; | |||
2111 | Sel = BO->getOperand(1); | |||
2112 | } | |||
2113 | ||||
2114 | if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) | |||
2115 | return SDValue(); | |||
2116 | ||||
2117 | SDValue CT = Sel.getOperand(1); | |||
2118 | if (!isConstantOrConstantVector(CT, true) && | |||
2119 | !DAG.isConstantFPBuildVectorOrConstantFP(CT)) | |||
2120 | return SDValue(); | |||
2121 | ||||
2122 | SDValue CF = Sel.getOperand(2); | |||
2123 | if (!isConstantOrConstantVector(CF, true) && | |||
2124 | !DAG.isConstantFPBuildVectorOrConstantFP(CF)) | |||
2125 | return SDValue(); | |||
2126 | ||||
2127 | // Bail out if any constants are opaque because we can't constant fold those. | |||
2128 | // The exception is "and" and "or" with either 0 or -1 in which case we can | |||
2129 | // propagate non constant operands into select. I.e.: | |||
2130 | // and (select Cond, 0, -1), X --> select Cond, 0, X | |||
2131 | // or X, (select Cond, -1, 0) --> select Cond, -1, X | |||
2132 | auto BinOpcode = BO->getOpcode(); | |||
2133 | bool CanFoldNonConst = | |||
2134 | (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && | |||
2135 | (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) && | |||
2136 | (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF)); | |||
2137 | ||||
2138 | SDValue CBO = BO->getOperand(SelOpNo ^ 1); | |||
2139 | if (!CanFoldNonConst && | |||
2140 | !isConstantOrConstantVector(CBO, true) && | |||
2141 | !DAG.isConstantFPBuildVectorOrConstantFP(CBO)) | |||
2142 | return SDValue(); | |||
2143 | ||||
2144 | EVT VT = BO->getValueType(0); | |||
2145 | ||||
2146 | // We have a select-of-constants followed by a binary operator with a | |||
2147 | // constant. Eliminate the binop by pulling the constant math into the select. | |||
2148 | // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO | |||
2149 | SDLoc DL(Sel); | |||
2150 | SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) | |||
2151 | : DAG.getNode(BinOpcode, DL, VT, CT, CBO); | |||
2152 | if (!CanFoldNonConst && !NewCT.isUndef() && | |||
2153 | !isConstantOrConstantVector(NewCT, true) && | |||
2154 | !DAG.isConstantFPBuildVectorOrConstantFP(NewCT)) | |||
2155 | return SDValue(); | |||
2156 | ||||
2157 | SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) | |||
2158 | : DAG.getNode(BinOpcode, DL, VT, CF, CBO); | |||
2159 | if (!CanFoldNonConst && !NewCF.isUndef() && | |||
2160 | !isConstantOrConstantVector(NewCF, true) && | |||
2161 | !DAG.isConstantFPBuildVectorOrConstantFP(NewCF)) | |||
2162 | return SDValue(); | |||
2163 | ||||
2164 | SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); | |||
2165 | SelectOp->setFlags(BO->getFlags()); | |||
2166 | return SelectOp; | |||
2167 | } | |||
2168 | ||||
2169 | static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { | |||
2170 | assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD:: SUB) && "Expecting add or sub") ? static_cast<void > (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2171, __PRETTY_FUNCTION__)) | |||
2171 | "Expecting add or sub")(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD:: SUB) && "Expecting add or sub") ? static_cast<void > (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2171, __PRETTY_FUNCTION__)); | |||
2172 | ||||
2173 | // Match a constant operand and a zext operand for the math instruction: | |||
2174 | // add Z, C | |||
2175 | // sub C, Z | |||
2176 | bool IsAdd = N->getOpcode() == ISD::ADD; | |||
2177 | SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); | |||
2178 | SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); | |||
2179 | auto *CN = dyn_cast<ConstantSDNode>(C); | |||
2180 | if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) | |||
2181 | return SDValue(); | |||
2182 | ||||
2183 | // Match the zext operand as a setcc of a boolean. | |||
2184 | if (Z.getOperand(0).getOpcode() != ISD::SETCC || | |||
2185 | Z.getOperand(0).getValueType() != MVT::i1) | |||
2186 | return SDValue(); | |||
2187 | ||||
2188 | // Match the compare as: setcc (X & 1), 0, eq. | |||
2189 | SDValue SetCC = Z.getOperand(0); | |||
2190 | ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); | |||
2191 | if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || | |||
2192 | SetCC.getOperand(0).getOpcode() != ISD::AND || | |||
2193 | !isOneConstant(SetCC.getOperand(0).getOperand(1))) | |||
2194 | return SDValue(); | |||
2195 | ||||
2196 | // We are adding/subtracting a constant and an inverted low bit. Turn that | |||
2197 | // into a subtract/add of the low bit with incremented/decremented constant: | |||
2198 | // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) | |||
2199 | // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) | |||
2200 | EVT VT = C.getValueType(); | |||
2201 | SDLoc DL(N); | |||
2202 | SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); | |||
2203 | SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : | |||
2204 | DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); | |||
2205 | return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); | |||
2206 | } | |||
2207 | ||||
2208 | /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into | |||
2209 | /// a shift and add with a different constant. | |||
2210 | static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { | |||
2211 | assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD:: SUB) && "Expecting add or sub") ? static_cast<void > (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2212, __PRETTY_FUNCTION__)) | |||
2212 | "Expecting add or sub")(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD:: SUB) && "Expecting add or sub") ? static_cast<void > (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Expecting add or sub\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2212, __PRETTY_FUNCTION__)); | |||
2213 | ||||
2214 | // We need a constant operand for the add/sub, and the other operand is a | |||
2215 | // logical shift right: add (srl), C or sub C, (srl). | |||
2216 | bool IsAdd = N->getOpcode() == ISD::ADD; | |||
2217 | SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); | |||
2218 | SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); | |||
2219 | if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) || | |||
2220 | ShiftOp.getOpcode() != ISD::SRL) | |||
2221 | return SDValue(); | |||
2222 | ||||
2223 | // The shift must be of a 'not' value. | |||
2224 | SDValue Not = ShiftOp.getOperand(0); | |||
2225 | if (!Not.hasOneUse() || !isBitwiseNot(Not)) | |||
2226 | return SDValue(); | |||
2227 | ||||
2228 | // The shift must be moving the sign bit to the least-significant-bit. | |||
2229 | EVT VT = ShiftOp.getValueType(); | |||
2230 | SDValue ShAmt = ShiftOp.getOperand(1); | |||
2231 | ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); | |||
2232 | if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1)) | |||
2233 | return SDValue(); | |||
2234 | ||||
2235 | // Eliminate the 'not' by adjusting the shift and add/sub constant: | |||
2236 | // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) | |||
2237 | // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) | |||
2238 | SDLoc DL(N); | |||
2239 | auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; | |||
2240 | SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); | |||
2241 | if (SDValue NewC = | |||
2242 | DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT, | |||
2243 | {ConstantOp, DAG.getConstant(1, DL, VT)})) | |||
2244 | return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC); | |||
2245 | return SDValue(); | |||
2246 | } | |||
2247 | ||||
2248 | /// Try to fold a node that behaves like an ADD (note that N isn't necessarily | |||
2249 | /// an ISD::ADD here, it could for example be an ISD::OR if we know that there | |||
2250 | /// are no common bits set in the operands). | |||
2251 | SDValue DAGCombiner::visitADDLike(SDNode *N) { | |||
2252 | SDValue N0 = N->getOperand(0); | |||
2253 | SDValue N1 = N->getOperand(1); | |||
2254 | EVT VT = N0.getValueType(); | |||
2255 | SDLoc DL(N); | |||
2256 | ||||
2257 | // fold vector ops | |||
2258 | if (VT.isVector()) { | |||
2259 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
2260 | return FoldedVOp; | |||
2261 | ||||
2262 | // fold (add x, 0) -> x, vector edition | |||
2263 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
2264 | return N0; | |||
2265 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
2266 | return N1; | |||
2267 | } | |||
2268 | ||||
2269 | // fold (add x, undef) -> undef | |||
2270 | if (N0.isUndef()) | |||
2271 | return N0; | |||
2272 | ||||
2273 | if (N1.isUndef()) | |||
2274 | return N1; | |||
2275 | ||||
2276 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { | |||
2277 | // canonicalize constant to RHS | |||
2278 | if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
2279 | return DAG.getNode(ISD::ADD, DL, VT, N1, N0); | |||
2280 | // fold (add c1, c2) -> c1+c2 | |||
2281 | return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}); | |||
2282 | } | |||
2283 | ||||
2284 | // fold (add x, 0) -> x | |||
2285 | if (isNullConstant(N1)) | |||
2286 | return N0; | |||
2287 | ||||
2288 | if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { | |||
2289 | // fold ((A-c1)+c2) -> (A+(c2-c1)) | |||
2290 | if (N0.getOpcode() == ISD::SUB && | |||
2291 | isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) { | |||
2292 | SDValue Sub = | |||
2293 | DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)}); | |||
2294 | assert(Sub && "Constant folding failed")((Sub && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("Sub && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2294, __PRETTY_FUNCTION__)); | |||
2295 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub); | |||
2296 | } | |||
2297 | ||||
2298 | // fold ((c1-A)+c2) -> (c1+c2)-A | |||
2299 | if (N0.getOpcode() == ISD::SUB && | |||
2300 | isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { | |||
2301 | SDValue Add = | |||
2302 | DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)}); | |||
2303 | assert(Add && "Constant folding failed")((Add && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("Add && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 2303, __PRETTY_FUNCTION__)); | |||
2304 | return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); | |||
2305 | } | |||
2306 | ||||
2307 | // add (sext i1 X), 1 -> zext (not i1 X) | |||
2308 | // We don't transform this pattern: | |||
2309 | // add (zext i1 X), -1 -> sext (not i1 X) | |||
2310 | // because most (?) targets generate better code for the zext form. | |||
2311 | if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && | |||
2312 | isOneOrOneSplat(N1)) { | |||
2313 | SDValue X = N0.getOperand(0); | |||
2314 | if ((!LegalOperations || | |||
2315 | (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && | |||
2316 | TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && | |||
2317 | X.getScalarValueSizeInBits() == 1) { | |||
2318 | SDValue Not = DAG.getNOT(DL, X, X.getValueType()); | |||
2319 | return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); | |||
2320 | } | |||
2321 | } | |||
2322 | ||||
2323 | // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is | |||
2324 | // equivalent to (add x, c0). | |||
2325 | if (N0.getOpcode() == ISD::OR && | |||
2326 | isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) && | |||
2327 | DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { | |||
2328 | if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, | |||
2329 | {N1, N0.getOperand(1)})) | |||
2330 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); | |||
2331 | } | |||
2332 | } | |||
2333 | ||||
2334 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
2335 | return NewSel; | |||
2336 | ||||
2337 | // reassociate add | |||
2338 | if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) { | |||
2339 | if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) | |||
2340 | return RADD; | |||
2341 | } | |||
2342 | // fold ((0-A) + B) -> B-A | |||
2343 | if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0))) | |||
2344 | return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); | |||
2345 | ||||
2346 | // fold (A + (0-B)) -> A-B | |||
2347 | if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) | |||
2348 | return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); | |||
2349 | ||||
2350 | // fold (A+(B-A)) -> B | |||
2351 | if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) | |||
2352 | return N1.getOperand(0); | |||
2353 | ||||
2354 | // fold ((B-A)+A) -> B | |||
2355 | if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) | |||
2356 | return N0.getOperand(0); | |||
2357 | ||||
2358 | // fold ((A-B)+(C-A)) -> (C-B) | |||
2359 | if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && | |||
2360 | N0.getOperand(0) == N1.getOperand(1)) | |||
2361 | return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), | |||
2362 | N0.getOperand(1)); | |||
2363 | ||||
2364 | // fold ((A-B)+(B-C)) -> (A-C) | |||
2365 | if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && | |||
2366 | N0.getOperand(1) == N1.getOperand(0)) | |||
2367 | return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), | |||
2368 | N1.getOperand(1)); | |||
2369 | ||||
2370 | // fold (A+(B-(A+C))) to (B-C) | |||
2371 | if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && | |||
2372 | N0 == N1.getOperand(1).getOperand(0)) | |||
2373 | return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), | |||
2374 | N1.getOperand(1).getOperand(1)); | |||
2375 | ||||
2376 | // fold (A+(B-(C+A))) to (B-C) | |||
2377 | if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && | |||
2378 | N0 == N1.getOperand(1).getOperand(1)) | |||
2379 | return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), | |||
2380 | N1.getOperand(1).getOperand(0)); | |||
2381 | ||||
2382 | // fold (A+((B-A)+or-C)) to (B+or-C) | |||
2383 | if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && | |||
2384 | N1.getOperand(0).getOpcode() == ISD::SUB && | |||
2385 | N0 == N1.getOperand(0).getOperand(1)) | |||
2386 | return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), | |||
2387 | N1.getOperand(1)); | |||
2388 | ||||
2389 | // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant | |||
2390 | if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { | |||
2391 | SDValue N00 = N0.getOperand(0); | |||
2392 | SDValue N01 = N0.getOperand(1); | |||
2393 | SDValue N10 = N1.getOperand(0); | |||
2394 | SDValue N11 = N1.getOperand(1); | |||
2395 | ||||
2396 | if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) | |||
2397 | return DAG.getNode(ISD::SUB, DL, VT, | |||
2398 | DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), | |||
2399 | DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); | |||
2400 | } | |||
2401 | ||||
2402 | // fold (add (umax X, C), -C) --> (usubsat X, C) | |||
2403 | if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) { | |||
2404 | auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) { | |||
2405 | return (!Max && !Op) || | |||
2406 | (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue())); | |||
2407 | }; | |||
2408 | if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT, | |||
2409 | /*AllowUndefs*/ true)) | |||
2410 | return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), | |||
2411 | N0.getOperand(1)); | |||
2412 | } | |||
2413 | ||||
2414 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
2415 | return SDValue(N, 0); | |||
2416 | ||||
2417 | if (isOneOrOneSplat(N1)) { | |||
2418 | // fold (add (xor a, -1), 1) -> (sub 0, a) | |||
2419 | if (isBitwiseNot(N0)) | |||
2420 | return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), | |||
2421 | N0.getOperand(0)); | |||
2422 | ||||
2423 | // fold (add (add (xor a, -1), b), 1) -> (sub b, a) | |||
2424 | if (N0.getOpcode() == ISD::ADD || | |||
2425 | N0.getOpcode() == ISD::UADDO || | |||
2426 | N0.getOpcode() == ISD::SADDO) { | |||
2427 | SDValue A, Xor; | |||
2428 | ||||
2429 | if (isBitwiseNot(N0.getOperand(0))) { | |||
2430 | A = N0.getOperand(1); | |||
2431 | Xor = N0.getOperand(0); | |||
2432 | } else if (isBitwiseNot(N0.getOperand(1))) { | |||
2433 | A = N0.getOperand(0); | |||
2434 | Xor = N0.getOperand(1); | |||
2435 | } | |||
2436 | ||||
2437 | if (Xor) | |||
2438 | return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0)); | |||
2439 | } | |||
2440 | ||||
2441 | // Look for: | |||
2442 | // add (add x, y), 1 | |||
2443 | // And if the target does not like this form then turn into: | |||
2444 | // sub y, (xor x, -1) | |||
2445 | if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && | |||
2446 | N0.getOpcode() == ISD::ADD) { | |||
2447 | SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), | |||
2448 | DAG.getAllOnesConstant(DL, VT)); | |||
2449 | return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not); | |||
2450 | } | |||
2451 | } | |||
2452 | ||||
2453 | // (x - y) + -1 -> add (xor y, -1), x | |||
2454 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && | |||
2455 | isAllOnesOrAllOnesSplat(N1)) { | |||
2456 | SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1); | |||
2457 | return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); | |||
2458 | } | |||
2459 | ||||
2460 | if (SDValue Combined = visitADDLikeCommutative(N0, N1, N)) | |||
2461 | return Combined; | |||
2462 | ||||
2463 | if (SDValue Combined = visitADDLikeCommutative(N1, N0, N)) | |||
2464 | return Combined; | |||
2465 | ||||
2466 | return SDValue(); | |||
2467 | } | |||
2468 | ||||
2469 | SDValue DAGCombiner::visitADD(SDNode *N) { | |||
2470 | SDValue N0 = N->getOperand(0); | |||
2471 | SDValue N1 = N->getOperand(1); | |||
2472 | EVT VT = N0.getValueType(); | |||
2473 | SDLoc DL(N); | |||
2474 | ||||
2475 | if (SDValue Combined = visitADDLike(N)) | |||
2476 | return Combined; | |||
2477 | ||||
2478 | if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) | |||
2479 | return V; | |||
2480 | ||||
2481 | if (SDValue V = foldAddSubOfSignBit(N, DAG)) | |||
2482 | return V; | |||
2483 | ||||
2484 | // fold (a+b) -> (a|b) iff a and b share no bits. | |||
2485 | if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && | |||
2486 | DAG.haveNoCommonBitsSet(N0, N1)) | |||
2487 | return DAG.getNode(ISD::OR, DL, VT, N0, N1); | |||
2488 | ||||
2489 | // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)). | |||
2490 | if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) { | |||
2491 | const APInt &C0 = N0->getConstantOperandAPInt(0); | |||
2492 | const APInt &C1 = N1->getConstantOperandAPInt(0); | |||
2493 | return DAG.getVScale(DL, VT, C0 + C1); | |||
2494 | } | |||
2495 | ||||
2496 | // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2) | |||
2497 | if ((N0.getOpcode() == ISD::ADD) && | |||
2498 | (N0.getOperand(1).getOpcode() == ISD::VSCALE) && | |||
2499 | (N1.getOpcode() == ISD::VSCALE)) { | |||
2500 | const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0); | |||
2501 | const APInt &VS1 = N1->getConstantOperandAPInt(0); | |||
2502 | SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1); | |||
2503 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS); | |||
2504 | } | |||
2505 | ||||
2506 | return SDValue(); | |||
2507 | } | |||
2508 | ||||
2509 | SDValue DAGCombiner::visitADDSAT(SDNode *N) { | |||
2510 | unsigned Opcode = N->getOpcode(); | |||
2511 | SDValue N0 = N->getOperand(0); | |||
2512 | SDValue N1 = N->getOperand(1); | |||
2513 | EVT VT = N0.getValueType(); | |||
2514 | SDLoc DL(N); | |||
2515 | ||||
2516 | // fold vector ops | |||
2517 | if (VT.isVector()) { | |||
2518 | // TODO SimplifyVBinOp | |||
2519 | ||||
2520 | // fold (add_sat x, 0) -> x, vector edition | |||
2521 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
2522 | return N0; | |||
2523 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
2524 | return N1; | |||
2525 | } | |||
2526 | ||||
2527 | // fold (add_sat x, undef) -> -1 | |||
2528 | if (N0.isUndef() || N1.isUndef()) | |||
2529 | return DAG.getAllOnesConstant(DL, VT); | |||
2530 | ||||
2531 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { | |||
2532 | // canonicalize constant to RHS | |||
2533 | if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
2534 | return DAG.getNode(Opcode, DL, VT, N1, N0); | |||
2535 | // fold (add_sat c1, c2) -> c3 | |||
2536 | return DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}); | |||
2537 | } | |||
2538 | ||||
2539 | // fold (add_sat x, 0) -> x | |||
2540 | if (isNullConstant(N1)) | |||
2541 | return N0; | |||
2542 | ||||
2543 | // If it cannot overflow, transform into an add. | |||
2544 | if (Opcode == ISD::UADDSAT) | |||
2545 | if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) | |||
2546 | return DAG.getNode(ISD::ADD, DL, VT, N0, N1); | |||
2547 | ||||
2548 | return SDValue(); | |||
2549 | } | |||
2550 | ||||
2551 | static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { | |||
2552 | bool Masked = false; | |||
2553 | ||||
2554 | // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. | |||
2555 | while (true) { | |||
2556 | if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { | |||
2557 | V = V.getOperand(0); | |||
2558 | continue; | |||
2559 | } | |||
2560 | ||||
2561 | if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { | |||
2562 | Masked = true; | |||
2563 | V = V.getOperand(0); | |||
2564 | continue; | |||
2565 | } | |||
2566 | ||||
2567 | break; | |||
2568 | } | |||
2569 | ||||
2570 | // If this is not a carry, return. | |||
2571 | if (V.getResNo() != 1) | |||
2572 | return SDValue(); | |||
2573 | ||||
2574 | if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && | |||
2575 | V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) | |||
2576 | return SDValue(); | |||
2577 | ||||
2578 | EVT VT = V.getNode()->getValueType(0); | |||
2579 | if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT)) | |||
2580 | return SDValue(); | |||
2581 | ||||
2582 | // If the result is masked, then no matter what kind of bool it is we can | |||
2583 | // return. If it isn't, then we need to make sure the bool type is either 0 or | |||
2584 | // 1 and not other values. | |||
2585 | if (Masked || | |||
2586 | TLI.getBooleanContents(V.getValueType()) == | |||
2587 | TargetLoweringBase::ZeroOrOneBooleanContent) | |||
2588 | return V; | |||
2589 | ||||
2590 | return SDValue(); | |||
2591 | } | |||
2592 | ||||
2593 | /// Given the operands of an add/sub operation, see if the 2nd operand is a | |||
2594 | /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert | |||
2595 | /// the opcode and bypass the mask operation. | |||
2596 | static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1, | |||
2597 | SelectionDAG &DAG, const SDLoc &DL) { | |||
2598 | if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1))) | |||
2599 | return SDValue(); | |||
2600 | ||||
2601 | EVT VT = N0.getValueType(); | |||
2602 | if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits()) | |||
2603 | return SDValue(); | |||
2604 | ||||
2605 | // add N0, (and (AssertSext X, i1), 1) --> sub N0, X | |||
2606 | // sub N0, (and (AssertSext X, i1), 1) --> add N0, X | |||
2607 | return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0)); | |||
2608 | } | |||
2609 | ||||
2610 | /// Helper for doing combines based on N0 and N1 being added to each other. | |||
2611 | SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1, | |||
2612 | SDNode *LocReference) { | |||
2613 | EVT VT = N0.getValueType(); | |||
2614 | SDLoc DL(LocReference); | |||
2615 | ||||
2616 | // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) | |||
2617 | if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && | |||
2618 | isNullOrNullSplat(N1.getOperand(0).getOperand(0))) | |||
2619 | return DAG.getNode(ISD::SUB, DL, VT, N0, | |||
2620 | DAG.getNode(ISD::SHL, DL, VT, | |||
2621 | N1.getOperand(0).getOperand(1), | |||
2622 | N1.getOperand(1))); | |||
2623 | ||||
2624 | if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL)) | |||
2625 | return V; | |||
2626 | ||||
2627 | // Look for: | |||
2628 | // add (add x, 1), y | |||
2629 | // And if the target does not like this form then turn into: | |||
2630 | // sub y, (xor x, -1) | |||
2631 | if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && | |||
2632 | N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) { | |||
2633 | SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), | |||
2634 | DAG.getAllOnesConstant(DL, VT)); | |||
2635 | return DAG.getNode(ISD::SUB, DL, VT, N1, Not); | |||
2636 | } | |||
2637 | ||||
2638 | // Hoist one-use subtraction by non-opaque constant: | |||
2639 | // (x - C) + y -> (x + y) - C | |||
2640 | // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. | |||
2641 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && | |||
2642 | isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { | |||
2643 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1); | |||
2644 | return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); | |||
2645 | } | |||
2646 | // Hoist one-use subtraction from non-opaque constant: | |||
2647 | // (C - x) + y -> (y - x) + C | |||
2648 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && | |||
2649 | isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { | |||
2650 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); | |||
2651 | return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0)); | |||
2652 | } | |||
2653 | ||||
2654 | // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1' | |||
2655 | // rather than 'add 0/-1' (the zext should get folded). | |||
2656 | // add (sext i1 Y), X --> sub X, (zext i1 Y) | |||
2657 | if (N0.getOpcode() == ISD::SIGN_EXTEND && | |||
2658 | N0.getOperand(0).getScalarValueSizeInBits() == 1 && | |||
2659 | TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) { | |||
2660 | SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); | |||
2661 | return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); | |||
2662 | } | |||
2663 | ||||
2664 | // add X, (sextinreg Y i1) -> sub X, (and Y 1) | |||
2665 | if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { | |||
2666 | VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); | |||
2667 | if (TN->getVT() == MVT::i1) { | |||
2668 | SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), | |||
2669 | DAG.getConstant(1, DL, VT)); | |||
2670 | return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); | |||
2671 | } | |||
2672 | } | |||
2673 | ||||
2674 | // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) | |||
2675 | if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && | |||
2676 | N1.getResNo() == 0) | |||
2677 | return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), | |||
2678 | N0, N1.getOperand(0), N1.getOperand(2)); | |||
2679 | ||||
2680 | // (add X, Carry) -> (addcarry X, 0, Carry) | |||
2681 | if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) | |||
2682 | if (SDValue Carry = getAsCarry(TLI, N1)) | |||
2683 | return DAG.getNode(ISD::ADDCARRY, DL, | |||
2684 | DAG.getVTList(VT, Carry.getValueType()), N0, | |||
2685 | DAG.getConstant(0, DL, VT), Carry); | |||
2686 | ||||
2687 | return SDValue(); | |||
2688 | } | |||
2689 | ||||
2690 | SDValue DAGCombiner::visitADDC(SDNode *N) { | |||
2691 | SDValue N0 = N->getOperand(0); | |||
2692 | SDValue N1 = N->getOperand(1); | |||
2693 | EVT VT = N0.getValueType(); | |||
2694 | SDLoc DL(N); | |||
2695 | ||||
2696 | // If the flag result is dead, turn this into an ADD. | |||
2697 | if (!N->hasAnyUseOfValue(1)) | |||
2698 | return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), | |||
2699 | DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
2700 | ||||
2701 | // canonicalize constant to RHS. | |||
2702 | ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); | |||
2703 | ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); | |||
2704 | if (N0C && !N1C) | |||
2705 | return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); | |||
2706 | ||||
2707 | // fold (addc x, 0) -> x + no carry out | |||
2708 | if (isNullConstant(N1)) | |||
2709 | return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, | |||
2710 | DL, MVT::Glue)); | |||
2711 | ||||
2712 | // If it cannot overflow, transform into an add. | |||
2713 | if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) | |||
2714 | return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), | |||
2715 | DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
2716 | ||||
2717 | return SDValue(); | |||
2718 | } | |||
2719 | ||||
2720 | /** | |||
2721 | * Flips a boolean if it is cheaper to compute. If the Force parameters is set, | |||
2722 | * then the flip also occurs if computing the inverse is the same cost. | |||
2723 | * This function returns an empty SDValue in case it cannot flip the boolean | |||
2724 | * without increasing the cost of the computation. If you want to flip a boolean | |||
2725 | * no matter what, use DAG.getLogicalNOT. | |||
2726 | */ | |||
2727 | static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG, | |||
2728 | const TargetLowering &TLI, | |||
2729 | bool Force) { | |||
2730 | if (Force && isa<ConstantSDNode>(V)) | |||
2731 | return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); | |||
2732 | ||||
2733 | if (V.getOpcode() != ISD::XOR) | |||
2734 | return SDValue(); | |||
2735 | ||||
2736 | ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false); | |||
2737 | if (!Const) | |||
2738 | return SDValue(); | |||
2739 | ||||
2740 | EVT VT = V.getValueType(); | |||
2741 | ||||
2742 | bool IsFlip = false; | |||
2743 | switch(TLI.getBooleanContents(VT)) { | |||
2744 | case TargetLowering::ZeroOrOneBooleanContent: | |||
2745 | IsFlip = Const->isOne(); | |||
2746 | break; | |||
2747 | case TargetLowering::ZeroOrNegativeOneBooleanContent: | |||
2748 | IsFlip = Const->isAllOnesValue(); | |||
2749 | break; | |||
2750 | case TargetLowering::UndefinedBooleanContent: | |||
2751 | IsFlip = (Const->getAPIntValue() & 0x01) == 1; | |||
2752 | break; | |||
2753 | } | |||
2754 | ||||
2755 | if (IsFlip) | |||
2756 | return V.getOperand(0); | |||
2757 | if (Force) | |||
2758 | return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); | |||
2759 | return SDValue(); | |||
2760 | } | |||
2761 | ||||
2762 | SDValue DAGCombiner::visitADDO(SDNode *N) { | |||
2763 | SDValue N0 = N->getOperand(0); | |||
2764 | SDValue N1 = N->getOperand(1); | |||
2765 | EVT VT = N0.getValueType(); | |||
2766 | bool IsSigned = (ISD::SADDO == N->getOpcode()); | |||
2767 | ||||
2768 | EVT CarryVT = N->getValueType(1); | |||
2769 | SDLoc DL(N); | |||
2770 | ||||
2771 | // If the flag result is dead, turn this into an ADD. | |||
2772 | if (!N->hasAnyUseOfValue(1)) | |||
2773 | return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), | |||
2774 | DAG.getUNDEF(CarryVT)); | |||
2775 | ||||
2776 | // canonicalize constant to RHS. | |||
2777 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
2778 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
2779 | return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); | |||
2780 | ||||
2781 | // fold (addo x, 0) -> x + no carry out | |||
2782 | if (isNullOrNullSplat(N1)) | |||
2783 | return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); | |||
2784 | ||||
2785 | if (!IsSigned) { | |||
2786 | // If it cannot overflow, transform into an add. | |||
2787 | if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) | |||
2788 | return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), | |||
2789 | DAG.getConstant(0, DL, CarryVT)); | |||
2790 | ||||
2791 | // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. | |||
2792 | if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) { | |||
2793 | SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), | |||
2794 | DAG.getConstant(0, DL, VT), N0.getOperand(0)); | |||
2795 | return CombineTo( | |||
2796 | N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); | |||
2797 | } | |||
2798 | ||||
2799 | if (SDValue Combined = visitUADDOLike(N0, N1, N)) | |||
2800 | return Combined; | |||
2801 | ||||
2802 | if (SDValue Combined = visitUADDOLike(N1, N0, N)) | |||
2803 | return Combined; | |||
2804 | } | |||
2805 | ||||
2806 | return SDValue(); | |||
2807 | } | |||
2808 | ||||
2809 | SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { | |||
2810 | EVT VT = N0.getValueType(); | |||
2811 | if (VT.isVector()) | |||
2812 | return SDValue(); | |||
2813 | ||||
2814 | // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) | |||
2815 | // If Y + 1 cannot overflow. | |||
2816 | if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { | |||
2817 | SDValue Y = N1.getOperand(0); | |||
2818 | SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); | |||
2819 | if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) | |||
2820 | return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, | |||
2821 | N1.getOperand(2)); | |||
2822 | } | |||
2823 | ||||
2824 | // (uaddo X, Carry) -> (addcarry X, 0, Carry) | |||
2825 | if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) | |||
2826 | if (SDValue Carry = getAsCarry(TLI, N1)) | |||
2827 | return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, | |||
2828 | DAG.getConstant(0, SDLoc(N), VT), Carry); | |||
2829 | ||||
2830 | return SDValue(); | |||
2831 | } | |||
2832 | ||||
2833 | SDValue DAGCombiner::visitADDE(SDNode *N) { | |||
2834 | SDValue N0 = N->getOperand(0); | |||
2835 | SDValue N1 = N->getOperand(1); | |||
2836 | SDValue CarryIn = N->getOperand(2); | |||
2837 | ||||
2838 | // canonicalize constant to RHS | |||
2839 | ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); | |||
2840 | ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); | |||
2841 | if (N0C && !N1C) | |||
2842 | return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), | |||
2843 | N1, N0, CarryIn); | |||
2844 | ||||
2845 | // fold (adde x, y, false) -> (addc x, y) | |||
2846 | if (CarryIn.getOpcode() == ISD::CARRY_FALSE) | |||
2847 | return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); | |||
2848 | ||||
2849 | return SDValue(); | |||
2850 | } | |||
2851 | ||||
2852 | SDValue DAGCombiner::visitADDCARRY(SDNode *N) { | |||
2853 | SDValue N0 = N->getOperand(0); | |||
2854 | SDValue N1 = N->getOperand(1); | |||
2855 | SDValue CarryIn = N->getOperand(2); | |||
2856 | SDLoc DL(N); | |||
2857 | ||||
2858 | // canonicalize constant to RHS | |||
2859 | ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); | |||
2860 | ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); | |||
2861 | if (N0C && !N1C) | |||
| ||||
2862 | return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); | |||
2863 | ||||
2864 | // fold (addcarry x, y, false) -> (uaddo x, y) | |||
2865 | if (isNullConstant(CarryIn)) { | |||
2866 | if (!LegalOperations || | |||
2867 | TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) | |||
2868 | return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); | |||
2869 | } | |||
2870 | ||||
2871 | // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. | |||
2872 | if (isNullConstant(N0) && isNullConstant(N1)) { | |||
2873 | EVT VT = N0.getValueType(); | |||
2874 | EVT CarryVT = CarryIn.getValueType(); | |||
2875 | SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); | |||
2876 | AddToWorklist(CarryExt.getNode()); | |||
2877 | return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, | |||
2878 | DAG.getConstant(1, DL, VT)), | |||
2879 | DAG.getConstant(0, DL, CarryVT)); | |||
2880 | } | |||
2881 | ||||
2882 | if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) | |||
2883 | return Combined; | |||
2884 | ||||
2885 | if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) | |||
2886 | return Combined; | |||
2887 | ||||
2888 | return SDValue(); | |||
2889 | } | |||
2890 | ||||
2891 | SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) { | |||
2892 | SDValue N0 = N->getOperand(0); | |||
2893 | SDValue N1 = N->getOperand(1); | |||
2894 | SDValue CarryIn = N->getOperand(2); | |||
2895 | SDLoc DL(N); | |||
2896 | ||||
2897 | // canonicalize constant to RHS | |||
2898 | ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); | |||
2899 | ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); | |||
2900 | if (N0C && !N1C) | |||
2901 | return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn); | |||
2902 | ||||
2903 | // fold (saddo_carry x, y, false) -> (saddo x, y) | |||
2904 | if (isNullConstant(CarryIn)) { | |||
2905 | if (!LegalOperations || | |||
2906 | TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0))) | |||
2907 | return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1); | |||
2908 | } | |||
2909 | ||||
2910 | return SDValue(); | |||
2911 | } | |||
2912 | ||||
2913 | /** | |||
2914 | * If we are facing some sort of diamond carry propapagtion pattern try to | |||
2915 | * break it up to generate something like: | |||
2916 | * (addcarry X, 0, (addcarry A, B, Z):Carry) | |||
2917 | * | |||
2918 | * The end result is usually an increase in operation required, but because the | |||
2919 | * carry is now linearized, other tranforms can kick in and optimize the DAG. | |||
2920 | * | |||
2921 | * Patterns typically look something like | |||
2922 | * (uaddo A, B) | |||
2923 | * / \ | |||
2924 | * Carry Sum | |||
2925 | * | \ | |||
2926 | * | (addcarry *, 0, Z) | |||
2927 | * | / | |||
2928 | * \ Carry | |||
2929 | * | / | |||
2930 | * (addcarry X, *, *) | |||
2931 | * | |||
2932 | * But numerous variation exist. Our goal is to identify A, B, X and Z and | |||
2933 | * produce a combine with a single path for carry propagation. | |||
2934 | */ | |||
2935 | static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, | |||
2936 | SDValue X, SDValue Carry0, SDValue Carry1, | |||
2937 | SDNode *N) { | |||
2938 | if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1) | |||
2939 | return SDValue(); | |||
2940 | if (Carry1.getOpcode() != ISD::UADDO) | |||
2941 | return SDValue(); | |||
2942 | ||||
2943 | SDValue Z; | |||
2944 | ||||
2945 | /** | |||
2946 | * First look for a suitable Z. It will present itself in the form of | |||
2947 | * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true | |||
2948 | */ | |||
2949 | if (Carry0.getOpcode() == ISD::ADDCARRY && | |||
2950 | isNullConstant(Carry0.getOperand(1))) { | |||
2951 | Z = Carry0.getOperand(2); | |||
2952 | } else if (Carry0.getOpcode() == ISD::UADDO && | |||
2953 | isOneConstant(Carry0.getOperand(1))) { | |||
2954 | EVT VT = Combiner.getSetCCResultType(Carry0.getValueType()); | |||
2955 | Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT); | |||
2956 | } else { | |||
2957 | // We couldn't find a suitable Z. | |||
2958 | return SDValue(); | |||
2959 | } | |||
2960 | ||||
2961 | ||||
2962 | auto cancelDiamond = [&](SDValue A,SDValue B) { | |||
2963 | SDLoc DL(N); | |||
2964 | SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z); | |||
2965 | Combiner.AddToWorklist(NewY.getNode()); | |||
2966 | return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X, | |||
2967 | DAG.getConstant(0, DL, X.getValueType()), | |||
2968 | NewY.getValue(1)); | |||
2969 | }; | |||
2970 | ||||
2971 | /** | |||
2972 | * (uaddo A, B) | |||
2973 | * | | |||
2974 | * Sum | |||
2975 | * | | |||
2976 | * (addcarry *, 0, Z) | |||
2977 | */ | |||
2978 | if (Carry0.getOperand(0) == Carry1.getValue(0)) { | |||
2979 | return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1)); | |||
2980 | } | |||
2981 | ||||
2982 | /** | |||
2983 | * (addcarry A, 0, Z) | |||
2984 | * | | |||
2985 | * Sum | |||
2986 | * | | |||
2987 | * (uaddo *, B) | |||
2988 | */ | |||
2989 | if (Carry1.getOperand(0) == Carry0.getValue(0)) { | |||
2990 | return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1)); | |||
2991 | } | |||
2992 | ||||
2993 | if (Carry1.getOperand(1) == Carry0.getValue(0)) { | |||
2994 | return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0)); | |||
2995 | } | |||
2996 | ||||
2997 | return SDValue(); | |||
2998 | } | |||
2999 | ||||
3000 | // If we are facing some sort of diamond carry/borrow in/out pattern try to | |||
3001 | // match patterns like: | |||
3002 | // | |||
3003 | // (uaddo A, B) CarryIn | |||
3004 | // | \ | | |||
3005 | // | \ | | |||
3006 | // PartialSum PartialCarryOutX / | |||
3007 | // | | / | |||
3008 | // | ____|____________/ | |||
3009 | // | / | | |||
3010 | // (uaddo *, *) \________ | |||
3011 | // | \ \ | |||
3012 | // | \ | | |||
3013 | // | PartialCarryOutY | | |||
3014 | // | \ | | |||
3015 | // | \ / | |||
3016 | // AddCarrySum | ______/ | |||
3017 | // | / | |||
3018 | // CarryOut = (or *, *) | |||
3019 | // | |||
3020 | // And generate ADDCARRY (or SUBCARRY) with two result values: | |||
3021 | // | |||
3022 | // {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn) | |||
3023 | // | |||
3024 | // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with | |||
3025 | // a single path for carry/borrow out propagation: | |||
3026 | static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, | |||
3027 | const TargetLowering &TLI, SDValue Carry0, | |||
3028 | SDValue Carry1, SDNode *N) { | |||
3029 | if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1) | |||
3030 | return SDValue(); | |||
3031 | unsigned Opcode = Carry0.getOpcode(); | |||
3032 | if (Opcode != Carry1.getOpcode()) | |||
3033 | return SDValue(); | |||
3034 | if (Opcode != ISD::UADDO && Opcode != ISD::USUBO) | |||
3035 | return SDValue(); | |||
3036 | ||||
3037 | // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the | |||
3038 | // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in | |||
3039 | // the above ASCII art.) | |||
3040 | if (Carry1.getOperand(0) != Carry0.getValue(0) && | |||
3041 | Carry1.getOperand(1) != Carry0.getValue(0)) | |||
3042 | std::swap(Carry0, Carry1); | |||
3043 | if (Carry1.getOperand(0) != Carry0.getValue(0) && | |||
3044 | Carry1.getOperand(1) != Carry0.getValue(0)) | |||
3045 | return SDValue(); | |||
3046 | ||||
3047 | // The carry in value must be on the righthand side for subtraction. | |||
3048 | unsigned CarryInOperandNum = | |||
3049 | Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0; | |||
3050 | if (Opcode == ISD::USUBO && CarryInOperandNum != 1) | |||
3051 | return SDValue(); | |||
3052 | SDValue CarryIn = Carry1.getOperand(CarryInOperandNum); | |||
3053 | ||||
3054 | unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY; | |||
3055 | if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType())) | |||
3056 | return SDValue(); | |||
3057 | ||||
3058 | // Verify that the carry/borrow in is plausibly a carry/borrow bit. | |||
3059 | // TODO: make getAsCarry() aware of how partial carries are merged. | |||
3060 | if (CarryIn.getOpcode() != ISD::ZERO_EXTEND) | |||
3061 | return SDValue(); | |||
3062 | CarryIn = CarryIn.getOperand(0); | |||
3063 | if (CarryIn.getValueType() != MVT::i1) | |||
3064 | return SDValue(); | |||
3065 | ||||
3066 | SDLoc DL(N); | |||
3067 | SDValue Merged = | |||
3068 | DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0), | |||
3069 | Carry0.getOperand(1), CarryIn); | |||
3070 | ||||
3071 | // Please note that because we have proven that the result of the UADDO/USUBO | |||
3072 | // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can | |||
3073 | // therefore prove that if the first UADDO/USUBO overflows, the second | |||
3074 | // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the | |||
3075 | // maximum value. | |||
3076 | // | |||
3077 | // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry | |||
3078 | // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow) | |||
3079 | // | |||
3080 | // This is important because it means that OR and XOR can be used to merge | |||
3081 | // carry flags; and that AND can return a constant zero. | |||
3082 | // | |||
3083 | // TODO: match other operations that can merge flags (ADD, etc) | |||
3084 | DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0)); | |||
3085 | if (N->getOpcode() == ISD::AND) | |||
3086 | return DAG.getConstant(0, DL, MVT::i1); | |||
3087 | return Merged.getValue(1); | |||
3088 | } | |||
3089 | ||||
3090 | SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, | |||
3091 | SDNode *N) { | |||
3092 | // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry. | |||
3093 | if (isBitwiseNot(N0)) | |||
3094 | if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) { | |||
3095 | SDLoc DL(N); | |||
3096 | SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1, | |||
3097 | N0.getOperand(0), NotC); | |||
3098 | return CombineTo( | |||
3099 | N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); | |||
3100 | } | |||
3101 | ||||
3102 | // Iff the flag result is dead: | |||
3103 | // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) | |||
3104 | // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo | |||
3105 | // or the dependency between the instructions. | |||
3106 | if ((N0.getOpcode() == ISD::ADD || | |||
3107 | (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 && | |||
3108 | N0.getValue(1) != CarryIn)) && | |||
3109 | isNullConstant(N1) && !N->hasAnyUseOfValue(1)) | |||
3110 | return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), | |||
3111 | N0.getOperand(0), N0.getOperand(1), CarryIn); | |||
3112 | ||||
3113 | /** | |||
3114 | * When one of the addcarry argument is itself a carry, we may be facing | |||
3115 | * a diamond carry propagation. In which case we try to transform the DAG | |||
3116 | * to ensure linear carry propagation if that is possible. | |||
3117 | */ | |||
3118 | if (auto Y = getAsCarry(TLI, N1)) { | |||
3119 | // Because both are carries, Y and Z can be swapped. | |||
3120 | if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N)) | |||
3121 | return R; | |||
3122 | if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N)) | |||
3123 | return R; | |||
3124 | } | |||
3125 | ||||
3126 | return SDValue(); | |||
3127 | } | |||
3128 | ||||
3129 | // Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a | |||
3130 | // clamp/truncation if necessary. | |||
3131 | static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS, | |||
3132 | SDValue RHS, SelectionDAG &DAG, | |||
3133 | const SDLoc &DL) { | |||
3134 | assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&((DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits () && "Illegal truncation") ? static_cast<void> (0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3135, __PRETTY_FUNCTION__)) | |||
3135 | "Illegal truncation")((DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits () && "Illegal truncation") ? static_cast<void> (0) : __assert_fail ("DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && \"Illegal truncation\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3135, __PRETTY_FUNCTION__)); | |||
3136 | ||||
3137 | if (DstVT == SrcVT) | |||
3138 | return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); | |||
3139 | ||||
3140 | // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by | |||
3141 | // clamping RHS. | |||
3142 | APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(), | |||
3143 | DstVT.getScalarSizeInBits()); | |||
3144 | if (!DAG.MaskedValueIsZero(LHS, UpperBits)) | |||
3145 | return SDValue(); | |||
3146 | ||||
3147 | SDValue SatLimit = | |||
3148 | DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(), | |||
3149 | DstVT.getScalarSizeInBits()), | |||
3150 | DL, SrcVT); | |||
3151 | RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit); | |||
3152 | RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS); | |||
3153 | LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS); | |||
3154 | return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); | |||
3155 | } | |||
3156 | ||||
3157 | // Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to | |||
3158 | // usubsat(a,b), optionally as a truncated type. | |||
3159 | SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) { | |||
3160 | if (N->getOpcode() != ISD::SUB || | |||
3161 | !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT))) | |||
3162 | return SDValue(); | |||
3163 | ||||
3164 | EVT SubVT = N->getValueType(0); | |||
3165 | SDValue Op0 = N->getOperand(0); | |||
3166 | SDValue Op1 = N->getOperand(1); | |||
3167 | ||||
3168 | // Try to find umax(a,b) - b or a - umin(a,b) patterns | |||
3169 | // they may be converted to usubsat(a,b). | |||
3170 | if (Op0.getOpcode() == ISD::UMAX) { | |||
3171 | SDValue MaxLHS = Op0.getOperand(0); | |||
3172 | SDValue MaxRHS = Op0.getOperand(1); | |||
3173 | if (MaxLHS == Op1) | |||
3174 | return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N)); | |||
3175 | if (MaxRHS == Op1) | |||
3176 | return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N)); | |||
3177 | } | |||
3178 | ||||
3179 | if (Op1.getOpcode() == ISD::UMIN) { | |||
3180 | SDValue MinLHS = Op1.getOperand(0); | |||
3181 | SDValue MinRHS = Op1.getOperand(1); | |||
3182 | if (MinLHS == Op0) | |||
3183 | return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N)); | |||
3184 | if (MinRHS == Op0) | |||
3185 | return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N)); | |||
3186 | } | |||
3187 | ||||
3188 | // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit))) | |||
3189 | if (Op1.getOpcode() == ISD::TRUNCATE && | |||
3190 | Op1.getOperand(0).getOpcode() == ISD::UMIN) { | |||
3191 | SDValue MinLHS = Op1.getOperand(0).getOperand(0); | |||
3192 | SDValue MinRHS = Op1.getOperand(0).getOperand(1); | |||
3193 | if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0) | |||
3194 | return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS, | |||
3195 | DAG, SDLoc(N)); | |||
3196 | if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0) | |||
3197 | return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS, | |||
3198 | DAG, SDLoc(N)); | |||
3199 | } | |||
3200 | ||||
3201 | return SDValue(); | |||
3202 | } | |||
3203 | ||||
3204 | // Since it may not be valid to emit a fold to zero for vector initializers | |||
3205 | // check if we can before folding. | |||
3206 | static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, | |||
3207 | SelectionDAG &DAG, bool LegalOperations) { | |||
3208 | if (!VT.isVector()) | |||
3209 | return DAG.getConstant(0, DL, VT); | |||
3210 | if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) | |||
3211 | return DAG.getConstant(0, DL, VT); | |||
3212 | return SDValue(); | |||
3213 | } | |||
3214 | ||||
3215 | SDValue DAGCombiner::visitSUB(SDNode *N) { | |||
3216 | SDValue N0 = N->getOperand(0); | |||
3217 | SDValue N1 = N->getOperand(1); | |||
3218 | EVT VT = N0.getValueType(); | |||
3219 | SDLoc DL(N); | |||
3220 | ||||
3221 | // fold vector ops | |||
3222 | if (VT.isVector()) { | |||
3223 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
3224 | return FoldedVOp; | |||
3225 | ||||
3226 | // fold (sub x, 0) -> x, vector edition | |||
3227 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
3228 | return N0; | |||
3229 | } | |||
3230 | ||||
3231 | // fold (sub x, x) -> 0 | |||
3232 | // FIXME: Refactor this and xor and other similar operations together. | |||
3233 | if (N0 == N1) | |||
3234 | return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); | |||
3235 | ||||
3236 | // fold (sub c1, c2) -> c3 | |||
3237 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1})) | |||
3238 | return C; | |||
3239 | ||||
3240 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
3241 | return NewSel; | |||
3242 | ||||
3243 | ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); | |||
3244 | ||||
3245 | // fold (sub x, c) -> (add x, -c) | |||
3246 | if (N1C) { | |||
3247 | return DAG.getNode(ISD::ADD, DL, VT, N0, | |||
3248 | DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); | |||
3249 | } | |||
3250 | ||||
3251 | if (isNullOrNullSplat(N0)) { | |||
3252 | unsigned BitWidth = VT.getScalarSizeInBits(); | |||
3253 | // Right-shifting everything out but the sign bit followed by negation is | |||
3254 | // the same as flipping arithmetic/logical shift type without the negation: | |||
3255 | // -(X >>u 31) -> (X >>s 31) | |||
3256 | // -(X >>s 31) -> (X >>u 31) | |||
3257 | if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { | |||
3258 | ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); | |||
3259 | if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) { | |||
3260 | auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; | |||
3261 | if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) | |||
3262 | return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); | |||
3263 | } | |||
3264 | } | |||
3265 | ||||
3266 | // 0 - X --> 0 if the sub is NUW. | |||
3267 | if (N->getFlags().hasNoUnsignedWrap()) | |||
3268 | return N0; | |||
3269 | ||||
3270 | if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { | |||
3271 | // N1 is either 0 or the minimum signed value. If the sub is NSW, then | |||
3272 | // N1 must be 0 because negating the minimum signed value is undefined. | |||
3273 | if (N->getFlags().hasNoSignedWrap()) | |||
3274 | return N0; | |||
3275 | ||||
3276 | // 0 - X --> X if X is 0 or the minimum signed value. | |||
3277 | return N1; | |||
3278 | } | |||
3279 | ||||
3280 | // Convert 0 - abs(x). | |||
3281 | SDValue Result; | |||
3282 | if (N1->getOpcode() == ISD::ABS && | |||
3283 | !TLI.isOperationLegalOrCustom(ISD::ABS, VT) && | |||
3284 | TLI.expandABS(N1.getNode(), Result, DAG, true)) | |||
3285 | return Result; | |||
3286 | } | |||
3287 | ||||
3288 | // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) | |||
3289 | if (isAllOnesOrAllOnesSplat(N0)) | |||
3290 | return DAG.getNode(ISD::XOR, DL, VT, N1, N0); | |||
3291 | ||||
3292 | // fold (A - (0-B)) -> A+B | |||
3293 | if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) | |||
3294 | return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); | |||
3295 | ||||
3296 | // fold A-(A-B) -> B | |||
3297 | if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) | |||
3298 | return N1.getOperand(1); | |||
3299 | ||||
3300 | // fold (A+B)-A -> B | |||
3301 | if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) | |||
3302 | return N0.getOperand(1); | |||
3303 | ||||
3304 | // fold (A+B)-B -> A | |||
3305 | if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) | |||
3306 | return N0.getOperand(0); | |||
3307 | ||||
3308 | // fold (A+C1)-C2 -> A+(C1-C2) | |||
3309 | if (N0.getOpcode() == ISD::ADD && | |||
3310 | isConstantOrConstantVector(N1, /* NoOpaques */ true) && | |||
3311 | isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { | |||
3312 | SDValue NewC = | |||
3313 | DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1}); | |||
3314 | assert(NewC && "Constant folding failed")((NewC && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("NewC && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3314, __PRETTY_FUNCTION__)); | |||
3315 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC); | |||
3316 | } | |||
3317 | ||||
3318 | // fold C2-(A+C1) -> (C2-C1)-A | |||
3319 | if (N1.getOpcode() == ISD::ADD) { | |||
3320 | SDValue N11 = N1.getOperand(1); | |||
3321 | if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && | |||
3322 | isConstantOrConstantVector(N11, /* NoOpaques */ true)) { | |||
3323 | SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}); | |||
3324 | assert(NewC && "Constant folding failed")((NewC && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("NewC && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3324, __PRETTY_FUNCTION__)); | |||
3325 | return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); | |||
3326 | } | |||
3327 | } | |||
3328 | ||||
3329 | // fold (A-C1)-C2 -> A-(C1+C2) | |||
3330 | if (N0.getOpcode() == ISD::SUB && | |||
3331 | isConstantOrConstantVector(N1, /* NoOpaques */ true) && | |||
3332 | isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { | |||
3333 | SDValue NewC = | |||
3334 | DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1}); | |||
3335 | assert(NewC && "Constant folding failed")((NewC && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("NewC && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3335, __PRETTY_FUNCTION__)); | |||
3336 | return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC); | |||
3337 | } | |||
3338 | ||||
3339 | // fold (c1-A)-c2 -> (c1-c2)-A | |||
3340 | if (N0.getOpcode() == ISD::SUB && | |||
3341 | isConstantOrConstantVector(N1, /* NoOpaques */ true) && | |||
3342 | isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) { | |||
3343 | SDValue NewC = | |||
3344 | DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1}); | |||
3345 | assert(NewC && "Constant folding failed")((NewC && "Constant folding failed") ? static_cast< void> (0) : __assert_fail ("NewC && \"Constant folding failed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3345, __PRETTY_FUNCTION__)); | |||
3346 | return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1)); | |||
3347 | } | |||
3348 | ||||
3349 | // fold ((A+(B+or-C))-B) -> A+or-C | |||
3350 | if (N0.getOpcode() == ISD::ADD && | |||
3351 | (N0.getOperand(1).getOpcode() == ISD::SUB || | |||
3352 | N0.getOperand(1).getOpcode() == ISD::ADD) && | |||
3353 | N0.getOperand(1).getOperand(0) == N1) | |||
3354 | return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), | |||
3355 | N0.getOperand(1).getOperand(1)); | |||
3356 | ||||
3357 | // fold ((A+(C+B))-B) -> A+C | |||
3358 | if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && | |||
3359 | N0.getOperand(1).getOperand(1) == N1) | |||
3360 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), | |||
3361 | N0.getOperand(1).getOperand(0)); | |||
3362 | ||||
3363 | // fold ((A-(B-C))-C) -> A-B | |||
3364 | if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && | |||
3365 | N0.getOperand(1).getOperand(1) == N1) | |||
3366 | return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), | |||
3367 | N0.getOperand(1).getOperand(0)); | |||
3368 | ||||
3369 | // fold (A-(B-C)) -> A+(C-B) | |||
3370 | if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) | |||
3371 | return DAG.getNode(ISD::ADD, DL, VT, N0, | |||
3372 | DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), | |||
3373 | N1.getOperand(0))); | |||
3374 | ||||
3375 | // A - (A & B) -> A & (~B) | |||
3376 | if (N1.getOpcode() == ISD::AND) { | |||
3377 | SDValue A = N1.getOperand(0); | |||
3378 | SDValue B = N1.getOperand(1); | |||
3379 | if (A != N0) | |||
3380 | std::swap(A, B); | |||
3381 | if (A == N0 && | |||
3382 | (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) { | |||
3383 | SDValue InvB = | |||
3384 | DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT)); | |||
3385 | return DAG.getNode(ISD::AND, DL, VT, A, InvB); | |||
3386 | } | |||
3387 | } | |||
3388 | ||||
3389 | // fold (X - (-Y * Z)) -> (X + (Y * Z)) | |||
3390 | if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { | |||
3391 | if (N1.getOperand(0).getOpcode() == ISD::SUB && | |||
3392 | isNullOrNullSplat(N1.getOperand(0).getOperand(0))) { | |||
3393 | SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, | |||
3394 | N1.getOperand(0).getOperand(1), | |||
3395 | N1.getOperand(1)); | |||
3396 | return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); | |||
3397 | } | |||
3398 | if (N1.getOperand(1).getOpcode() == ISD::SUB && | |||
3399 | isNullOrNullSplat(N1.getOperand(1).getOperand(0))) { | |||
3400 | SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, | |||
3401 | N1.getOperand(0), | |||
3402 | N1.getOperand(1).getOperand(1)); | |||
3403 | return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); | |||
3404 | } | |||
3405 | } | |||
3406 | ||||
3407 | // If either operand of a sub is undef, the result is undef | |||
3408 | if (N0.isUndef()) | |||
3409 | return N0; | |||
3410 | if (N1.isUndef()) | |||
3411 | return N1; | |||
3412 | ||||
3413 | if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) | |||
3414 | return V; | |||
3415 | ||||
3416 | if (SDValue V = foldAddSubOfSignBit(N, DAG)) | |||
3417 | return V; | |||
3418 | ||||
3419 | if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N))) | |||
3420 | return V; | |||
3421 | ||||
3422 | if (SDValue V = foldSubToUSubSat(VT, N)) | |||
3423 | return V; | |||
3424 | ||||
3425 | // (x - y) - 1 -> add (xor y, -1), x | |||
3426 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) { | |||
3427 | SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), | |||
3428 | DAG.getAllOnesConstant(DL, VT)); | |||
3429 | return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); | |||
3430 | } | |||
3431 | ||||
3432 | // Look for: | |||
3433 | // sub y, (xor x, -1) | |||
3434 | // And if the target does not like this form then turn into: | |||
3435 | // add (add x, y), 1 | |||
3436 | if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) { | |||
3437 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0)); | |||
3438 | return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT)); | |||
3439 | } | |||
3440 | ||||
3441 | // Hoist one-use addition by non-opaque constant: | |||
3442 | // (x + C) - y -> (x - y) + C | |||
3443 | if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD && | |||
3444 | isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { | |||
3445 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); | |||
3446 | return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1)); | |||
3447 | } | |||
3448 | // y - (x + C) -> (y - x) - C | |||
3449 | if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD && | |||
3450 | isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) { | |||
3451 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0)); | |||
3452 | return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1)); | |||
3453 | } | |||
3454 | // (x - C) - y -> (x - y) - C | |||
3455 | // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. | |||
3456 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && | |||
3457 | isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { | |||
3458 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); | |||
3459 | return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1)); | |||
3460 | } | |||
3461 | // (C - x) - y -> C - (x + y) | |||
3462 | if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && | |||
3463 | isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { | |||
3464 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1); | |||
3465 | return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add); | |||
3466 | } | |||
3467 | ||||
3468 | // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1' | |||
3469 | // rather than 'sub 0/1' (the sext should get folded). | |||
3470 | // sub X, (zext i1 Y) --> add X, (sext i1 Y) | |||
3471 | if (N1.getOpcode() == ISD::ZERO_EXTEND && | |||
3472 | N1.getOperand(0).getScalarValueSizeInBits() == 1 && | |||
3473 | TLI.getBooleanContents(VT) == | |||
3474 | TargetLowering::ZeroOrNegativeOneBooleanContent) { | |||
3475 | SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0)); | |||
3476 | return DAG.getNode(ISD::ADD, DL, VT, N0, SExt); | |||
3477 | } | |||
3478 | ||||
3479 | // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) | |||
3480 | if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { | |||
3481 | if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { | |||
3482 | SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); | |||
3483 | SDValue S0 = N1.getOperand(0); | |||
3484 | if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) | |||
3485 | if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) | |||
3486 | if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) | |||
3487 | return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); | |||
3488 | } | |||
3489 | } | |||
3490 | ||||
3491 | // If the relocation model supports it, consider symbol offsets. | |||
3492 | if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) | |||
3493 | if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { | |||
3494 | // fold (sub Sym, c) -> Sym-c | |||
3495 | if (N1C && GA->getOpcode() == ISD::GlobalAddress) | |||
3496 | return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, | |||
3497 | GA->getOffset() - | |||
3498 | (uint64_t)N1C->getSExtValue()); | |||
3499 | // fold (sub Sym+c1, Sym+c2) -> c1-c2 | |||
3500 | if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) | |||
3501 | if (GA->getGlobal() == GB->getGlobal()) | |||
3502 | return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), | |||
3503 | DL, VT); | |||
3504 | } | |||
3505 | ||||
3506 | // sub X, (sextinreg Y i1) -> add X, (and Y 1) | |||
3507 | if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { | |||
3508 | VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); | |||
3509 | if (TN->getVT() == MVT::i1) { | |||
3510 | SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), | |||
3511 | DAG.getConstant(1, DL, VT)); | |||
3512 | return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); | |||
3513 | } | |||
3514 | } | |||
3515 | ||||
3516 | // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C)) | |||
3517 | if (N1.getOpcode() == ISD::VSCALE) { | |||
3518 | const APInt &IntVal = N1.getConstantOperandAPInt(0); | |||
3519 | return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal)); | |||
3520 | } | |||
3521 | ||||
3522 | // Prefer an add for more folding potential and possibly better codegen: | |||
3523 | // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) | |||
3524 | if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { | |||
3525 | SDValue ShAmt = N1.getOperand(1); | |||
3526 | ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); | |||
3527 | if (ShAmtC && | |||
3528 | ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) { | |||
3529 | SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); | |||
3530 | return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); | |||
3531 | } | |||
3532 | } | |||
3533 | ||||
3534 | if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) { | |||
3535 | // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry) | |||
3536 | if (SDValue Carry = getAsCarry(TLI, N0)) { | |||
3537 | SDValue X = N1; | |||
3538 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
3539 | SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X); | |||
3540 | return DAG.getNode(ISD::ADDCARRY, DL, | |||
3541 | DAG.getVTList(VT, Carry.getValueType()), NegX, Zero, | |||
3542 | Carry); | |||
3543 | } | |||
3544 | } | |||
3545 | ||||
3546 | return SDValue(); | |||
3547 | } | |||
3548 | ||||
3549 | SDValue DAGCombiner::visitSUBSAT(SDNode *N) { | |||
3550 | SDValue N0 = N->getOperand(0); | |||
3551 | SDValue N1 = N->getOperand(1); | |||
3552 | EVT VT = N0.getValueType(); | |||
3553 | SDLoc DL(N); | |||
3554 | ||||
3555 | // fold vector ops | |||
3556 | if (VT.isVector()) { | |||
3557 | // TODO SimplifyVBinOp | |||
3558 | ||||
3559 | // fold (sub_sat x, 0) -> x, vector edition | |||
3560 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
3561 | return N0; | |||
3562 | } | |||
3563 | ||||
3564 | // fold (sub_sat x, undef) -> 0 | |||
3565 | if (N0.isUndef() || N1.isUndef()) | |||
3566 | return DAG.getConstant(0, DL, VT); | |||
3567 | ||||
3568 | // fold (sub_sat x, x) -> 0 | |||
3569 | if (N0 == N1) | |||
3570 | return DAG.getConstant(0, DL, VT); | |||
3571 | ||||
3572 | // fold (sub_sat c1, c2) -> c3 | |||
3573 | if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1})) | |||
3574 | return C; | |||
3575 | ||||
3576 | // fold (sub_sat x, 0) -> x | |||
3577 | if (isNullConstant(N1)) | |||
3578 | return N0; | |||
3579 | ||||
3580 | return SDValue(); | |||
3581 | } | |||
3582 | ||||
3583 | SDValue DAGCombiner::visitSUBC(SDNode *N) { | |||
3584 | SDValue N0 = N->getOperand(0); | |||
3585 | SDValue N1 = N->getOperand(1); | |||
3586 | EVT VT = N0.getValueType(); | |||
3587 | SDLoc DL(N); | |||
3588 | ||||
3589 | // If the flag result is dead, turn this into an SUB. | |||
3590 | if (!N->hasAnyUseOfValue(1)) | |||
3591 | return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), | |||
3592 | DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
3593 | ||||
3594 | // fold (subc x, x) -> 0 + no borrow | |||
3595 | if (N0 == N1) | |||
3596 | return CombineTo(N, DAG.getConstant(0, DL, VT), | |||
3597 | DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
3598 | ||||
3599 | // fold (subc x, 0) -> x + no borrow | |||
3600 | if (isNullConstant(N1)) | |||
3601 | return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
3602 | ||||
3603 | // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow | |||
3604 | if (isAllOnesConstant(N0)) | |||
3605 | return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), | |||
3606 | DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); | |||
3607 | ||||
3608 | return SDValue(); | |||
3609 | } | |||
3610 | ||||
3611 | SDValue DAGCombiner::visitSUBO(SDNode *N) { | |||
3612 | SDValue N0 = N->getOperand(0); | |||
3613 | SDValue N1 = N->getOperand(1); | |||
3614 | EVT VT = N0.getValueType(); | |||
3615 | bool IsSigned = (ISD::SSUBO == N->getOpcode()); | |||
3616 | ||||
3617 | EVT CarryVT = N->getValueType(1); | |||
3618 | SDLoc DL(N); | |||
3619 | ||||
3620 | // If the flag result is dead, turn this into an SUB. | |||
3621 | if (!N->hasAnyUseOfValue(1)) | |||
3622 | return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), | |||
3623 | DAG.getUNDEF(CarryVT)); | |||
3624 | ||||
3625 | // fold (subo x, x) -> 0 + no borrow | |||
3626 | if (N0 == N1) | |||
3627 | return CombineTo(N, DAG.getConstant(0, DL, VT), | |||
3628 | DAG.getConstant(0, DL, CarryVT)); | |||
3629 | ||||
3630 | ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); | |||
3631 | ||||
3632 | // fold (subox, c) -> (addo x, -c) | |||
3633 | if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) { | |||
3634 | return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, | |||
3635 | DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); | |||
3636 | } | |||
3637 | ||||
3638 | // fold (subo x, 0) -> x + no borrow | |||
3639 | if (isNullOrNullSplat(N1)) | |||
3640 | return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); | |||
3641 | ||||
3642 | // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow | |||
3643 | if (!IsSigned && isAllOnesOrAllOnesSplat(N0)) | |||
3644 | return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), | |||
3645 | DAG.getConstant(0, DL, CarryVT)); | |||
3646 | ||||
3647 | return SDValue(); | |||
3648 | } | |||
3649 | ||||
3650 | SDValue DAGCombiner::visitSUBE(SDNode *N) { | |||
3651 | SDValue N0 = N->getOperand(0); | |||
3652 | SDValue N1 = N->getOperand(1); | |||
3653 | SDValue CarryIn = N->getOperand(2); | |||
3654 | ||||
3655 | // fold (sube x, y, false) -> (subc x, y) | |||
3656 | if (CarryIn.getOpcode() == ISD::CARRY_FALSE) | |||
3657 | return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); | |||
3658 | ||||
3659 | return SDValue(); | |||
3660 | } | |||
3661 | ||||
3662 | SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { | |||
3663 | SDValue N0 = N->getOperand(0); | |||
3664 | SDValue N1 = N->getOperand(1); | |||
3665 | SDValue CarryIn = N->getOperand(2); | |||
3666 | ||||
3667 | // fold (subcarry x, y, false) -> (usubo x, y) | |||
3668 | if (isNullConstant(CarryIn)) { | |||
3669 | if (!LegalOperations || | |||
3670 | TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) | |||
3671 | return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); | |||
3672 | } | |||
3673 | ||||
3674 | return SDValue(); | |||
3675 | } | |||
3676 | ||||
3677 | SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) { | |||
3678 | SDValue N0 = N->getOperand(0); | |||
3679 | SDValue N1 = N->getOperand(1); | |||
3680 | SDValue CarryIn = N->getOperand(2); | |||
3681 | ||||
3682 | // fold (ssubo_carry x, y, false) -> (ssubo x, y) | |||
3683 | if (isNullConstant(CarryIn)) { | |||
3684 | if (!LegalOperations || | |||
3685 | TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0))) | |||
3686 | return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1); | |||
3687 | } | |||
3688 | ||||
3689 | return SDValue(); | |||
3690 | } | |||
3691 | ||||
3692 | // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and | |||
3693 | // UMULFIXSAT here. | |||
3694 | SDValue DAGCombiner::visitMULFIX(SDNode *N) { | |||
3695 | SDValue N0 = N->getOperand(0); | |||
3696 | SDValue N1 = N->getOperand(1); | |||
3697 | SDValue Scale = N->getOperand(2); | |||
3698 | EVT VT = N0.getValueType(); | |||
3699 | ||||
3700 | // fold (mulfix x, undef, scale) -> 0 | |||
3701 | if (N0.isUndef() || N1.isUndef()) | |||
3702 | return DAG.getConstant(0, SDLoc(N), VT); | |||
3703 | ||||
3704 | // Canonicalize constant to RHS (vector doesn't have to splat) | |||
3705 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
3706 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
3707 | return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale); | |||
3708 | ||||
3709 | // fold (mulfix x, 0, scale) -> 0 | |||
3710 | if (isNullConstant(N1)) | |||
3711 | return DAG.getConstant(0, SDLoc(N), VT); | |||
3712 | ||||
3713 | return SDValue(); | |||
3714 | } | |||
3715 | ||||
3716 | SDValue DAGCombiner::visitMUL(SDNode *N) { | |||
3717 | SDValue N0 = N->getOperand(0); | |||
3718 | SDValue N1 = N->getOperand(1); | |||
3719 | EVT VT = N0.getValueType(); | |||
3720 | ||||
3721 | // fold (mul x, undef) -> 0 | |||
3722 | if (N0.isUndef() || N1.isUndef()) | |||
3723 | return DAG.getConstant(0, SDLoc(N), VT); | |||
3724 | ||||
3725 | bool N1IsConst = false; | |||
3726 | bool N1IsOpaqueConst = false; | |||
3727 | APInt ConstValue1; | |||
3728 | ||||
3729 | // fold vector ops | |||
3730 | if (VT.isVector()) { | |||
3731 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
3732 | return FoldedVOp; | |||
3733 | ||||
3734 | N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); | |||
3735 | assert((!N1IsConst ||(((!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits ()) && "Splat APInt should be element width") ? static_cast <void> (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3737, __PRETTY_FUNCTION__)) | |||
3736 | ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&(((!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits ()) && "Splat APInt should be element width") ? static_cast <void> (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3737, __PRETTY_FUNCTION__)) | |||
3737 | "Splat APInt should be element width")(((!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits ()) && "Splat APInt should be element width") ? static_cast <void> (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3737, __PRETTY_FUNCTION__)); | |||
3738 | } else { | |||
3739 | N1IsConst = isa<ConstantSDNode>(N1); | |||
3740 | if (N1IsConst) { | |||
3741 | ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); | |||
3742 | N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); | |||
3743 | } | |||
3744 | } | |||
3745 | ||||
3746 | // fold (mul c1, c2) -> c1*c2 | |||
3747 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1})) | |||
3748 | return C; | |||
3749 | ||||
3750 | // canonicalize constant to RHS (vector doesn't have to splat) | |||
3751 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
3752 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
3753 | return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); | |||
3754 | ||||
3755 | // fold (mul x, 0) -> 0 | |||
3756 | if (N1IsConst && ConstValue1.isNullValue()) | |||
3757 | return N1; | |||
3758 | ||||
3759 | // fold (mul x, 1) -> x | |||
3760 | if (N1IsConst && ConstValue1.isOneValue()) | |||
3761 | return N0; | |||
3762 | ||||
3763 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
3764 | return NewSel; | |||
3765 | ||||
3766 | // fold (mul x, -1) -> 0-x | |||
3767 | if (N1IsConst && ConstValue1.isAllOnesValue()) { | |||
3768 | SDLoc DL(N); | |||
3769 | return DAG.getNode(ISD::SUB, DL, VT, | |||
3770 | DAG.getConstant(0, DL, VT), N0); | |||
3771 | } | |||
3772 | ||||
3773 | // fold (mul x, (1 << c)) -> x << c | |||
3774 | if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && | |||
3775 | DAG.isKnownToBeAPowerOfTwo(N1) && | |||
3776 | (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { | |||
3777 | SDLoc DL(N); | |||
3778 | SDValue LogBase2 = BuildLogBase2(N1, DL); | |||
3779 | EVT ShiftVT = getShiftAmountTy(N0.getValueType()); | |||
3780 | SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); | |||
3781 | return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); | |||
3782 | } | |||
3783 | ||||
3784 | // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c | |||
3785 | if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { | |||
3786 | unsigned Log2Val = (-ConstValue1).logBase2(); | |||
3787 | SDLoc DL(N); | |||
3788 | // FIXME: If the input is something that is easily negated (e.g. a | |||
3789 | // single-use add), we should put the negate there. | |||
3790 | return DAG.getNode(ISD::SUB, DL, VT, | |||
3791 | DAG.getConstant(0, DL, VT), | |||
3792 | DAG.getNode(ISD::SHL, DL, VT, N0, | |||
3793 | DAG.getConstant(Log2Val, DL, | |||
3794 | getShiftAmountTy(N0.getValueType())))); | |||
3795 | } | |||
3796 | ||||
3797 | // Try to transform: | |||
3798 | // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub. | |||
3799 | // mul x, (2^N + 1) --> add (shl x, N), x | |||
3800 | // mul x, (2^N - 1) --> sub (shl x, N), x | |||
3801 | // Examples: x * 33 --> (x << 5) + x | |||
3802 | // x * 15 --> (x << 4) - x | |||
3803 | // x * -33 --> -((x << 5) + x) | |||
3804 | // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4) | |||
3805 | // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub. | |||
3806 | // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M)) | |||
3807 | // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M)) | |||
3808 | // Examples: x * 0x8800 --> (x << 15) + (x << 11) | |||
3809 | // x * 0xf800 --> (x << 16) - (x << 11) | |||
3810 | // x * -0x8800 --> -((x << 15) + (x << 11)) | |||
3811 | // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16) | |||
3812 | if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) { | |||
3813 | // TODO: We could handle more general decomposition of any constant by | |||
3814 | // having the target set a limit on number of ops and making a | |||
3815 | // callback to determine that sequence (similar to sqrt expansion). | |||
3816 | unsigned MathOp = ISD::DELETED_NODE; | |||
3817 | APInt MulC = ConstValue1.abs(); | |||
3818 | // The constant `2` should be treated as (2^0 + 1). | |||
3819 | unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros(); | |||
3820 | MulC.lshrInPlace(TZeros); | |||
3821 | if ((MulC - 1).isPowerOf2()) | |||
3822 | MathOp = ISD::ADD; | |||
3823 | else if ((MulC + 1).isPowerOf2()) | |||
3824 | MathOp = ISD::SUB; | |||
3825 | ||||
3826 | if (MathOp != ISD::DELETED_NODE) { | |||
3827 | unsigned ShAmt = | |||
3828 | MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2(); | |||
3829 | ShAmt += TZeros; | |||
3830 | assert(ShAmt < VT.getScalarSizeInBits() &&((ShAmt < VT.getScalarSizeInBits() && "multiply-by-constant generated out of bounds shift" ) ? static_cast<void> (0) : __assert_fail ("ShAmt < VT.getScalarSizeInBits() && \"multiply-by-constant generated out of bounds shift\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3831, __PRETTY_FUNCTION__)) | |||
3831 | "multiply-by-constant generated out of bounds shift")((ShAmt < VT.getScalarSizeInBits() && "multiply-by-constant generated out of bounds shift" ) ? static_cast<void> (0) : __assert_fail ("ShAmt < VT.getScalarSizeInBits() && \"multiply-by-constant generated out of bounds shift\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3831, __PRETTY_FUNCTION__)); | |||
3832 | SDLoc DL(N); | |||
3833 | SDValue Shl = | |||
3834 | DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT)); | |||
3835 | SDValue R = | |||
3836 | TZeros ? DAG.getNode(MathOp, DL, VT, Shl, | |||
3837 | DAG.getNode(ISD::SHL, DL, VT, N0, | |||
3838 | DAG.getConstant(TZeros, DL, VT))) | |||
3839 | : DAG.getNode(MathOp, DL, VT, Shl, N0); | |||
3840 | if (ConstValue1.isNegative()) | |||
3841 | R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R); | |||
3842 | return R; | |||
3843 | } | |||
3844 | } | |||
3845 | ||||
3846 | // (mul (shl X, c1), c2) -> (mul X, c2 << c1) | |||
3847 | if (N0.getOpcode() == ISD::SHL && | |||
3848 | isConstantOrConstantVector(N1, /* NoOpaques */ true) && | |||
3849 | isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { | |||
3850 | SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); | |||
3851 | if (isConstantOrConstantVector(C3)) | |||
3852 | return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); | |||
3853 | } | |||
3854 | ||||
3855 | // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one | |||
3856 | // use. | |||
3857 | { | |||
3858 | SDValue Sh(nullptr, 0), Y(nullptr, 0); | |||
3859 | ||||
3860 | // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). | |||
3861 | if (N0.getOpcode() == ISD::SHL && | |||
3862 | isConstantOrConstantVector(N0.getOperand(1)) && | |||
3863 | N0.getNode()->hasOneUse()) { | |||
3864 | Sh = N0; Y = N1; | |||
3865 | } else if (N1.getOpcode() == ISD::SHL && | |||
3866 | isConstantOrConstantVector(N1.getOperand(1)) && | |||
3867 | N1.getNode()->hasOneUse()) { | |||
3868 | Sh = N1; Y = N0; | |||
3869 | } | |||
3870 | ||||
3871 | if (Sh.getNode()) { | |||
3872 | SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); | |||
3873 | return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); | |||
3874 | } | |||
3875 | } | |||
3876 | ||||
3877 | // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) | |||
3878 | if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && | |||
3879 | N0.getOpcode() == ISD::ADD && | |||
3880 | DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && | |||
3881 | isMulAddWithConstProfitable(N, N0, N1)) | |||
3882 | return DAG.getNode(ISD::ADD, SDLoc(N), VT, | |||
3883 | DAG.getNode(ISD::MUL, SDLoc(N0), VT, | |||
3884 | N0.getOperand(0), N1), | |||
3885 | DAG.getNode(ISD::MUL, SDLoc(N1), VT, | |||
3886 | N0.getOperand(1), N1)); | |||
3887 | ||||
3888 | // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)). | |||
3889 | if (N0.getOpcode() == ISD::VSCALE) | |||
3890 | if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) { | |||
3891 | const APInt &C0 = N0.getConstantOperandAPInt(0); | |||
3892 | const APInt &C1 = NC1->getAPIntValue(); | |||
3893 | return DAG.getVScale(SDLoc(N), VT, C0 * C1); | |||
3894 | } | |||
3895 | ||||
3896 | // Fold ((mul x, 0/undef) -> 0, | |||
3897 | // (mul x, 1) -> x) -> x) | |||
3898 | // -> and(x, mask) | |||
3899 | // We can replace vectors with '0' and '1' factors with a clearing mask. | |||
3900 | if (VT.isFixedLengthVector()) { | |||
3901 | unsigned NumElts = VT.getVectorNumElements(); | |||
3902 | SmallBitVector ClearMask; | |||
3903 | ClearMask.reserve(NumElts); | |||
3904 | auto IsClearMask = [&ClearMask](ConstantSDNode *V) { | |||
3905 | if (!V || V->isNullValue()) { | |||
3906 | ClearMask.push_back(true); | |||
3907 | return true; | |||
3908 | } | |||
3909 | ClearMask.push_back(false); | |||
3910 | return V->isOne(); | |||
3911 | }; | |||
3912 | if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) && | |||
3913 | ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) { | |||
3914 | assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector")((N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector" ) ? static_cast<void> (0) : __assert_fail ("N1.getOpcode() == ISD::BUILD_VECTOR && \"Unknown constant vector\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 3914, __PRETTY_FUNCTION__)); | |||
3915 | SDLoc DL(N); | |||
3916 | EVT LegalSVT = N1.getOperand(0).getValueType(); | |||
3917 | SDValue Zero = DAG.getConstant(0, DL, LegalSVT); | |||
3918 | SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT); | |||
3919 | SmallVector<SDValue, 16> Mask(NumElts, AllOnes); | |||
3920 | for (unsigned I = 0; I != NumElts; ++I) | |||
3921 | if (ClearMask[I]) | |||
3922 | Mask[I] = Zero; | |||
3923 | return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask)); | |||
3924 | } | |||
3925 | } | |||
3926 | ||||
3927 | // reassociate mul | |||
3928 | if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) | |||
3929 | return RMUL; | |||
3930 | ||||
3931 | return SDValue(); | |||
3932 | } | |||
3933 | ||||
3934 | /// Return true if divmod libcall is available. | |||
3935 | static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, | |||
3936 | const TargetLowering &TLI) { | |||
3937 | RTLIB::Libcall LC; | |||
3938 | EVT NodeType = Node->getValueType(0); | |||
3939 | if (!NodeType.isSimple()) | |||
3940 | return false; | |||
3941 | switch (NodeType.getSimpleVT().SimpleTy) { | |||
3942 | default: return false; // No libcall for vector types. | |||
3943 | case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; | |||
3944 | case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; | |||
3945 | case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; | |||
3946 | case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; | |||
3947 | case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; | |||
3948 | } | |||
3949 | ||||
3950 | return TLI.getLibcallName(LC) != nullptr; | |||
3951 | } | |||
3952 | ||||
3953 | /// Issue divrem if both quotient and remainder are needed. | |||
3954 | SDValue DAGCombiner::useDivRem(SDNode *Node) { | |||
3955 | if (Node->use_empty()) | |||
3956 | return SDValue(); // This is a dead node, leave it alone. | |||
3957 | ||||
3958 | unsigned Opcode = Node->getOpcode(); | |||
3959 | bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); | |||
3960 | unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; | |||
3961 | ||||
3962 | // DivMod lib calls can still work on non-legal types if using lib-calls. | |||
3963 | EVT VT = Node->getValueType(0); | |||
3964 | if (VT.isVector() || !VT.isInteger()) | |||
3965 | return SDValue(); | |||
3966 | ||||
3967 | if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) | |||
3968 | return SDValue(); | |||
3969 | ||||
3970 | // If DIVREM is going to get expanded into a libcall, | |||
3971 | // but there is no libcall available, then don't combine. | |||
3972 | if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && | |||
3973 | !isDivRemLibcallAvailable(Node, isSigned, TLI)) | |||
3974 | return SDValue(); | |||
3975 | ||||
3976 | // If div is legal, it's better to do the normal expansion | |||
3977 | unsigned OtherOpcode = 0; | |||
3978 | if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { | |||
3979 | OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; | |||
3980 | if (TLI.isOperationLegalOrCustom(Opcode, VT)) | |||
3981 | return SDValue(); | |||
3982 | } else { | |||
3983 | OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; | |||
3984 | if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) | |||
3985 | return SDValue(); | |||
3986 | } | |||
3987 | ||||
3988 | SDValue Op0 = Node->getOperand(0); | |||
3989 | SDValue Op1 = Node->getOperand(1); | |||
3990 | SDValue combined; | |||
3991 | for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), | |||
3992 | UE = Op0.getNode()->use_end(); UI != UE; ++UI) { | |||
3993 | SDNode *User = *UI; | |||
3994 | if (User == Node || User->getOpcode() == ISD::DELETED_NODE || | |||
3995 | User->use_empty()) | |||
3996 | continue; | |||
3997 | // Convert the other matching node(s), too; | |||
3998 | // otherwise, the DIVREM may get target-legalized into something | |||
3999 | // target-specific that we won't be able to recognize. | |||
4000 | unsigned UserOpc = User->getOpcode(); | |||
4001 | if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && | |||
4002 | User->getOperand(0) == Op0 && | |||
4003 | User->getOperand(1) == Op1) { | |||
4004 | if (!combined) { | |||
4005 | if (UserOpc == OtherOpcode) { | |||
4006 | SDVTList VTs = DAG.getVTList(VT, VT); | |||
4007 | combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); | |||
4008 | } else if (UserOpc == DivRemOpc) { | |||
4009 | combined = SDValue(User, 0); | |||
4010 | } else { | |||
4011 | assert(UserOpc == Opcode)((UserOpc == Opcode) ? static_cast<void> (0) : __assert_fail ("UserOpc == Opcode", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4011, __PRETTY_FUNCTION__)); | |||
4012 | continue; | |||
4013 | } | |||
4014 | } | |||
4015 | if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) | |||
4016 | CombineTo(User, combined); | |||
4017 | else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) | |||
4018 | CombineTo(User, combined.getValue(1)); | |||
4019 | } | |||
4020 | } | |||
4021 | return combined; | |||
4022 | } | |||
4023 | ||||
4024 | static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { | |||
4025 | SDValue N0 = N->getOperand(0); | |||
4026 | SDValue N1 = N->getOperand(1); | |||
4027 | EVT VT = N->getValueType(0); | |||
4028 | SDLoc DL(N); | |||
4029 | ||||
4030 | unsigned Opc = N->getOpcode(); | |||
4031 | bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); | |||
4032 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
4033 | ||||
4034 | // X / undef -> undef | |||
4035 | // X % undef -> undef | |||
4036 | // X / 0 -> undef | |||
4037 | // X % 0 -> undef | |||
4038 | // NOTE: This includes vectors where any divisor element is zero/undef. | |||
4039 | if (DAG.isUndef(Opc, {N0, N1})) | |||
4040 | return DAG.getUNDEF(VT); | |||
4041 | ||||
4042 | // undef / X -> 0 | |||
4043 | // undef % X -> 0 | |||
4044 | if (N0.isUndef()) | |||
4045 | return DAG.getConstant(0, DL, VT); | |||
4046 | ||||
4047 | // 0 / X -> 0 | |||
4048 | // 0 % X -> 0 | |||
4049 | ConstantSDNode *N0C = isConstOrConstSplat(N0); | |||
4050 | if (N0C && N0C->isNullValue()) | |||
4051 | return N0; | |||
4052 | ||||
4053 | // X / X -> 1 | |||
4054 | // X % X -> 0 | |||
4055 | if (N0 == N1) | |||
4056 | return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); | |||
4057 | ||||
4058 | // X / 1 -> X | |||
4059 | // X % 1 -> 0 | |||
4060 | // If this is a boolean op (single-bit element type), we can't have | |||
4061 | // division-by-zero or remainder-by-zero, so assume the divisor is 1. | |||
4062 | // TODO: Similarly, if we're zero-extending a boolean divisor, then assume | |||
4063 | // it's a 1. | |||
4064 | if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1)) | |||
4065 | return IsDiv ? N0 : DAG.getConstant(0, DL, VT); | |||
4066 | ||||
4067 | return SDValue(); | |||
4068 | } | |||
4069 | ||||
4070 | SDValue DAGCombiner::visitSDIV(SDNode *N) { | |||
4071 | SDValue N0 = N->getOperand(0); | |||
4072 | SDValue N1 = N->getOperand(1); | |||
4073 | EVT VT = N->getValueType(0); | |||
4074 | EVT CCVT = getSetCCResultType(VT); | |||
4075 | ||||
4076 | // fold vector ops | |||
4077 | if (VT.isVector()) | |||
4078 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
4079 | return FoldedVOp; | |||
4080 | ||||
4081 | SDLoc DL(N); | |||
4082 | ||||
4083 | // fold (sdiv c1, c2) -> c1/c2 | |||
4084 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
4085 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1})) | |||
4086 | return C; | |||
4087 | ||||
4088 | // fold (sdiv X, -1) -> 0-X | |||
4089 | if (N1C && N1C->isAllOnesValue()) | |||
4090 | return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); | |||
4091 | ||||
4092 | // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) | |||
4093 | if (N1C && N1C->getAPIntValue().isMinSignedValue()) | |||
4094 | return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), | |||
4095 | DAG.getConstant(1, DL, VT), | |||
4096 | DAG.getConstant(0, DL, VT)); | |||
4097 | ||||
4098 | if (SDValue V = simplifyDivRem(N, DAG)) | |||
4099 | return V; | |||
4100 | ||||
4101 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
4102 | return NewSel; | |||
4103 | ||||
4104 | // If we know the sign bits of both operands are zero, strength reduce to a | |||
4105 | // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 | |||
4106 | if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) | |||
4107 | return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); | |||
4108 | ||||
4109 | if (SDValue V = visitSDIVLike(N0, N1, N)) { | |||
4110 | // If the corresponding remainder node exists, update its users with | |||
4111 | // (Dividend - (Quotient * Divisor). | |||
4112 | if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(), | |||
4113 | { N0, N1 })) { | |||
4114 | SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); | |||
4115 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); | |||
4116 | AddToWorklist(Mul.getNode()); | |||
4117 | AddToWorklist(Sub.getNode()); | |||
4118 | CombineTo(RemNode, Sub); | |||
4119 | } | |||
4120 | return V; | |||
4121 | } | |||
4122 | ||||
4123 | // sdiv, srem -> sdivrem | |||
4124 | // If the divisor is constant, then return DIVREM only if isIntDivCheap() is | |||
4125 | // true. Otherwise, we break the simplification logic in visitREM(). | |||
4126 | AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); | |||
4127 | if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) | |||
4128 | if (SDValue DivRem = useDivRem(N)) | |||
4129 | return DivRem; | |||
4130 | ||||
4131 | return SDValue(); | |||
4132 | } | |||
4133 | ||||
4134 | SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { | |||
4135 | SDLoc DL(N); | |||
4136 | EVT VT = N->getValueType(0); | |||
4137 | EVT CCVT = getSetCCResultType(VT); | |||
4138 | unsigned BitWidth = VT.getScalarSizeInBits(); | |||
4139 | ||||
4140 | // Helper for determining whether a value is a power-2 constant scalar or a | |||
4141 | // vector of such elements. | |||
4142 | auto IsPowerOfTwo = [](ConstantSDNode *C) { | |||
4143 | if (C->isNullValue() || C->isOpaque()) | |||
4144 | return false; | |||
4145 | if (C->getAPIntValue().isPowerOf2()) | |||
4146 | return true; | |||
4147 | if ((-C->getAPIntValue()).isPowerOf2()) | |||
4148 | return true; | |||
4149 | return false; | |||
4150 | }; | |||
4151 | ||||
4152 | // fold (sdiv X, pow2) -> simple ops after legalize | |||
4153 | // FIXME: We check for the exact bit here because the generic lowering gives | |||
4154 | // better results in that case. The target-specific lowering should learn how | |||
4155 | // to handle exact sdivs efficiently. | |||
4156 | if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { | |||
4157 | // Target-specific implementation of sdiv x, pow2. | |||
4158 | if (SDValue Res = BuildSDIVPow2(N)) | |||
4159 | return Res; | |||
4160 | ||||
4161 | // Create constants that are functions of the shift amount value. | |||
4162 | EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); | |||
4163 | SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); | |||
4164 | SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); | |||
4165 | C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); | |||
4166 | SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); | |||
4167 | if (!isConstantOrConstantVector(Inexact)) | |||
4168 | return SDValue(); | |||
4169 | ||||
4170 | // Splat the sign bit into the register | |||
4171 | SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, | |||
4172 | DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); | |||
4173 | AddToWorklist(Sign.getNode()); | |||
4174 | ||||
4175 | // Add (N0 < 0) ? abs2 - 1 : 0; | |||
4176 | SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); | |||
4177 | AddToWorklist(Srl.getNode()); | |||
4178 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); | |||
4179 | AddToWorklist(Add.getNode()); | |||
4180 | SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); | |||
4181 | AddToWorklist(Sra.getNode()); | |||
4182 | ||||
4183 | // Special case: (sdiv X, 1) -> X | |||
4184 | // Special Case: (sdiv X, -1) -> 0-X | |||
4185 | SDValue One = DAG.getConstant(1, DL, VT); | |||
4186 | SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); | |||
4187 | SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); | |||
4188 | SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); | |||
4189 | SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); | |||
4190 | Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); | |||
4191 | ||||
4192 | // If dividing by a positive value, we're done. Otherwise, the result must | |||
4193 | // be negated. | |||
4194 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
4195 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); | |||
4196 | ||||
4197 | // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. | |||
4198 | SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); | |||
4199 | SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); | |||
4200 | return Res; | |||
4201 | } | |||
4202 | ||||
4203 | // If integer divide is expensive and we satisfy the requirements, emit an | |||
4204 | // alternate sequence. Targets may check function attributes for size/speed | |||
4205 | // trade-offs. | |||
4206 | AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); | |||
4207 | if (isConstantOrConstantVector(N1) && | |||
4208 | !TLI.isIntDivCheap(N->getValueType(0), Attr)) | |||
4209 | if (SDValue Op = BuildSDIV(N)) | |||
4210 | return Op; | |||
4211 | ||||
4212 | return SDValue(); | |||
4213 | } | |||
4214 | ||||
4215 | SDValue DAGCombiner::visitUDIV(SDNode *N) { | |||
4216 | SDValue N0 = N->getOperand(0); | |||
4217 | SDValue N1 = N->getOperand(1); | |||
4218 | EVT VT = N->getValueType(0); | |||
4219 | EVT CCVT = getSetCCResultType(VT); | |||
4220 | ||||
4221 | // fold vector ops | |||
4222 | if (VT.isVector()) | |||
4223 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
4224 | return FoldedVOp; | |||
4225 | ||||
4226 | SDLoc DL(N); | |||
4227 | ||||
4228 | // fold (udiv c1, c2) -> c1/c2 | |||
4229 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
4230 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1})) | |||
4231 | return C; | |||
4232 | ||||
4233 | // fold (udiv X, -1) -> select(X == -1, 1, 0) | |||
4234 | if (N1C && N1C->getAPIntValue().isAllOnesValue()) | |||
4235 | return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), | |||
4236 | DAG.getConstant(1, DL, VT), | |||
4237 | DAG.getConstant(0, DL, VT)); | |||
4238 | ||||
4239 | if (SDValue V = simplifyDivRem(N, DAG)) | |||
4240 | return V; | |||
4241 | ||||
4242 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
4243 | return NewSel; | |||
4244 | ||||
4245 | if (SDValue V = visitUDIVLike(N0, N1, N)) { | |||
4246 | // If the corresponding remainder node exists, update its users with | |||
4247 | // (Dividend - (Quotient * Divisor). | |||
4248 | if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(), | |||
4249 | { N0, N1 })) { | |||
4250 | SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); | |||
4251 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); | |||
4252 | AddToWorklist(Mul.getNode()); | |||
4253 | AddToWorklist(Sub.getNode()); | |||
4254 | CombineTo(RemNode, Sub); | |||
4255 | } | |||
4256 | return V; | |||
4257 | } | |||
4258 | ||||
4259 | // sdiv, srem -> sdivrem | |||
4260 | // If the divisor is constant, then return DIVREM only if isIntDivCheap() is | |||
4261 | // true. Otherwise, we break the simplification logic in visitREM(). | |||
4262 | AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); | |||
4263 | if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) | |||
4264 | if (SDValue DivRem = useDivRem(N)) | |||
4265 | return DivRem; | |||
4266 | ||||
4267 | return SDValue(); | |||
4268 | } | |||
4269 | ||||
4270 | SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { | |||
4271 | SDLoc DL(N); | |||
4272 | EVT VT = N->getValueType(0); | |||
4273 | ||||
4274 | // fold (udiv x, (1 << c)) -> x >>u c | |||
4275 | if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && | |||
4276 | DAG.isKnownToBeAPowerOfTwo(N1)) { | |||
4277 | SDValue LogBase2 = BuildLogBase2(N1, DL); | |||
4278 | AddToWorklist(LogBase2.getNode()); | |||
4279 | ||||
4280 | EVT ShiftVT = getShiftAmountTy(N0.getValueType()); | |||
4281 | SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); | |||
4282 | AddToWorklist(Trunc.getNode()); | |||
4283 | return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); | |||
4284 | } | |||
4285 | ||||
4286 | // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 | |||
4287 | if (N1.getOpcode() == ISD::SHL) { | |||
4288 | SDValue N10 = N1.getOperand(0); | |||
4289 | if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && | |||
4290 | DAG.isKnownToBeAPowerOfTwo(N10)) { | |||
4291 | SDValue LogBase2 = BuildLogBase2(N10, DL); | |||
4292 | AddToWorklist(LogBase2.getNode()); | |||
4293 | ||||
4294 | EVT ADDVT = N1.getOperand(1).getValueType(); | |||
4295 | SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); | |||
4296 | AddToWorklist(Trunc.getNode()); | |||
4297 | SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); | |||
4298 | AddToWorklist(Add.getNode()); | |||
4299 | return DAG.getNode(ISD::SRL, DL, VT, N0, Add); | |||
4300 | } | |||
4301 | } | |||
4302 | ||||
4303 | // fold (udiv x, c) -> alternate | |||
4304 | AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); | |||
4305 | if (isConstantOrConstantVector(N1) && | |||
4306 | !TLI.isIntDivCheap(N->getValueType(0), Attr)) | |||
4307 | if (SDValue Op = BuildUDIV(N)) | |||
4308 | return Op; | |||
4309 | ||||
4310 | return SDValue(); | |||
4311 | } | |||
4312 | ||||
4313 | // handles ISD::SREM and ISD::UREM | |||
4314 | SDValue DAGCombiner::visitREM(SDNode *N) { | |||
4315 | unsigned Opcode = N->getOpcode(); | |||
4316 | SDValue N0 = N->getOperand(0); | |||
4317 | SDValue N1 = N->getOperand(1); | |||
4318 | EVT VT = N->getValueType(0); | |||
4319 | EVT CCVT = getSetCCResultType(VT); | |||
4320 | ||||
4321 | bool isSigned = (Opcode == ISD::SREM); | |||
4322 | SDLoc DL(N); | |||
4323 | ||||
4324 | // fold (rem c1, c2) -> c1%c2 | |||
4325 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
4326 | if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1})) | |||
4327 | return C; | |||
4328 | ||||
4329 | // fold (urem X, -1) -> select(X == -1, 0, x) | |||
4330 | if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) | |||
4331 | return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), | |||
4332 | DAG.getConstant(0, DL, VT), N0); | |||
4333 | ||||
4334 | if (SDValue V = simplifyDivRem(N, DAG)) | |||
4335 | return V; | |||
4336 | ||||
4337 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
4338 | return NewSel; | |||
4339 | ||||
4340 | if (isSigned) { | |||
4341 | // If we know the sign bits of both operands are zero, strength reduce to a | |||
4342 | // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 | |||
4343 | if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) | |||
4344 | return DAG.getNode(ISD::UREM, DL, VT, N0, N1); | |||
4345 | } else { | |||
4346 | if (DAG.isKnownToBeAPowerOfTwo(N1)) { | |||
4347 | // fold (urem x, pow2) -> (and x, pow2-1) | |||
4348 | SDValue NegOne = DAG.getAllOnesConstant(DL, VT); | |||
4349 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); | |||
4350 | AddToWorklist(Add.getNode()); | |||
4351 | return DAG.getNode(ISD::AND, DL, VT, N0, Add); | |||
4352 | } | |||
4353 | if (N1.getOpcode() == ISD::SHL && | |||
4354 | DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { | |||
4355 | // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) | |||
4356 | SDValue NegOne = DAG.getAllOnesConstant(DL, VT); | |||
4357 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); | |||
4358 | AddToWorklist(Add.getNode()); | |||
4359 | return DAG.getNode(ISD::AND, DL, VT, N0, Add); | |||
4360 | } | |||
4361 | } | |||
4362 | ||||
4363 | AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); | |||
4364 | ||||
4365 | // If X/C can be simplified by the division-by-constant logic, lower | |||
4366 | // X%C to the equivalent of X-X/C*C. | |||
4367 | // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the | |||
4368 | // speculative DIV must not cause a DIVREM conversion. We guard against this | |||
4369 | // by skipping the simplification if isIntDivCheap(). When div is not cheap, | |||
4370 | // combine will not return a DIVREM. Regardless, checking cheapness here | |||
4371 | // makes sense since the simplification results in fatter code. | |||
4372 | if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { | |||
4373 | SDValue OptimizedDiv = | |||
4374 | isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); | |||
4375 | if (OptimizedDiv.getNode()) { | |||
4376 | // If the equivalent Div node also exists, update its users. | |||
4377 | unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; | |||
4378 | if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(), | |||
4379 | { N0, N1 })) | |||
4380 | CombineTo(DivNode, OptimizedDiv); | |||
4381 | SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); | |||
4382 | SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); | |||
4383 | AddToWorklist(OptimizedDiv.getNode()); | |||
4384 | AddToWorklist(Mul.getNode()); | |||
4385 | return Sub; | |||
4386 | } | |||
4387 | } | |||
4388 | ||||
4389 | // sdiv, srem -> sdivrem | |||
4390 | if (SDValue DivRem = useDivRem(N)) | |||
4391 | return DivRem.getValue(1); | |||
4392 | ||||
4393 | return SDValue(); | |||
4394 | } | |||
4395 | ||||
4396 | SDValue DAGCombiner::visitMULHS(SDNode *N) { | |||
4397 | SDValue N0 = N->getOperand(0); | |||
4398 | SDValue N1 = N->getOperand(1); | |||
4399 | EVT VT = N->getValueType(0); | |||
4400 | SDLoc DL(N); | |||
4401 | ||||
4402 | if (VT.isVector()) { | |||
4403 | // fold (mulhs x, 0) -> 0 | |||
4404 | // do not return N0/N1, because undef node may exist. | |||
4405 | if (ISD::isBuildVectorAllZeros(N0.getNode()) || | |||
4406 | ISD::isBuildVectorAllZeros(N1.getNode())) | |||
4407 | return DAG.getConstant(0, DL, VT); | |||
4408 | } | |||
4409 | ||||
4410 | // fold (mulhs x, 0) -> 0 | |||
4411 | if (isNullConstant(N1)) | |||
4412 | return N1; | |||
4413 | // fold (mulhs x, 1) -> (sra x, size(x)-1) | |||
4414 | if (isOneConstant(N1)) | |||
4415 | return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, | |||
4416 | DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL, | |||
4417 | getShiftAmountTy(N0.getValueType()))); | |||
4418 | ||||
4419 | // fold (mulhs x, undef) -> 0 | |||
4420 | if (N0.isUndef() || N1.isUndef()) | |||
4421 | return DAG.getConstant(0, DL, VT); | |||
4422 | ||||
4423 | // If the type twice as wide is legal, transform the mulhs to a wider multiply | |||
4424 | // plus a shift. | |||
4425 | if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() && | |||
4426 | !VT.isVector()) { | |||
4427 | MVT Simple = VT.getSimpleVT(); | |||
4428 | unsigned SimpleSize = Simple.getSizeInBits(); | |||
4429 | EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); | |||
4430 | if (TLI.isOperationLegal(ISD::MUL, NewVT)) { | |||
4431 | N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); | |||
4432 | N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); | |||
4433 | N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); | |||
4434 | N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, | |||
4435 | DAG.getConstant(SimpleSize, DL, | |||
4436 | getShiftAmountTy(N1.getValueType()))); | |||
4437 | return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); | |||
4438 | } | |||
4439 | } | |||
4440 | ||||
4441 | return SDValue(); | |||
4442 | } | |||
4443 | ||||
4444 | SDValue DAGCombiner::visitMULHU(SDNode *N) { | |||
4445 | SDValue N0 = N->getOperand(0); | |||
4446 | SDValue N1 = N->getOperand(1); | |||
4447 | EVT VT = N->getValueType(0); | |||
4448 | SDLoc DL(N); | |||
4449 | ||||
4450 | if (VT.isVector()) { | |||
4451 | // fold (mulhu x, 0) -> 0 | |||
4452 | // do not return N0/N1, because undef node may exist. | |||
4453 | if (ISD::isBuildVectorAllZeros(N0.getNode()) || | |||
4454 | ISD::isBuildVectorAllZeros(N1.getNode())) | |||
4455 | return DAG.getConstant(0, DL, VT); | |||
4456 | } | |||
4457 | ||||
4458 | // fold (mulhu x, 0) -> 0 | |||
4459 | if (isNullConstant(N1)) | |||
4460 | return N1; | |||
4461 | // fold (mulhu x, 1) -> 0 | |||
4462 | if (isOneConstant(N1)) | |||
4463 | return DAG.getConstant(0, DL, N0.getValueType()); | |||
4464 | // fold (mulhu x, undef) -> 0 | |||
4465 | if (N0.isUndef() || N1.isUndef()) | |||
4466 | return DAG.getConstant(0, DL, VT); | |||
4467 | ||||
4468 | // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) | |||
4469 | if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && | |||
4470 | DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { | |||
4471 | unsigned NumEltBits = VT.getScalarSizeInBits(); | |||
4472 | SDValue LogBase2 = BuildLogBase2(N1, DL); | |||
4473 | SDValue SRLAmt = DAG.getNode( | |||
4474 | ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); | |||
4475 | EVT ShiftVT = getShiftAmountTy(N0.getValueType()); | |||
4476 | SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); | |||
4477 | return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); | |||
4478 | } | |||
4479 | ||||
4480 | // If the type twice as wide is legal, transform the mulhu to a wider multiply | |||
4481 | // plus a shift. | |||
4482 | if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() && | |||
4483 | !VT.isVector()) { | |||
4484 | MVT Simple = VT.getSimpleVT(); | |||
4485 | unsigned SimpleSize = Simple.getSizeInBits(); | |||
4486 | EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); | |||
4487 | if (TLI.isOperationLegal(ISD::MUL, NewVT)) { | |||
4488 | N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); | |||
4489 | N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); | |||
4490 | N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); | |||
4491 | N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, | |||
4492 | DAG.getConstant(SimpleSize, DL, | |||
4493 | getShiftAmountTy(N1.getValueType()))); | |||
4494 | return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); | |||
4495 | } | |||
4496 | } | |||
4497 | ||||
4498 | return SDValue(); | |||
4499 | } | |||
4500 | ||||
4501 | /// Perform optimizations common to nodes that compute two values. LoOp and HiOp | |||
4502 | /// give the opcodes for the two computations that are being performed. Return | |||
4503 | /// true if a simplification was made. | |||
4504 | SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, | |||
4505 | unsigned HiOp) { | |||
4506 | // If the high half is not needed, just compute the low half. | |||
4507 | bool HiExists = N->hasAnyUseOfValue(1); | |||
4508 | if (!HiExists && (!LegalOperations || | |||
4509 | TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { | |||
4510 | SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); | |||
4511 | return CombineTo(N, Res, Res); | |||
4512 | } | |||
4513 | ||||
4514 | // If the low half is not needed, just compute the high half. | |||
4515 | bool LoExists = N->hasAnyUseOfValue(0); | |||
4516 | if (!LoExists && (!LegalOperations || | |||
4517 | TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) { | |||
4518 | SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); | |||
4519 | return CombineTo(N, Res, Res); | |||
4520 | } | |||
4521 | ||||
4522 | // If both halves are used, return as it is. | |||
4523 | if (LoExists && HiExists) | |||
4524 | return SDValue(); | |||
4525 | ||||
4526 | // If the two computed results can be simplified separately, separate them. | |||
4527 | if (LoExists) { | |||
4528 | SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); | |||
4529 | AddToWorklist(Lo.getNode()); | |||
4530 | SDValue LoOpt = combine(Lo.getNode()); | |||
4531 | if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && | |||
4532 | (!LegalOperations || | |||
4533 | TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType()))) | |||
4534 | return CombineTo(N, LoOpt, LoOpt); | |||
4535 | } | |||
4536 | ||||
4537 | if (HiExists) { | |||
4538 | SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); | |||
4539 | AddToWorklist(Hi.getNode()); | |||
4540 | SDValue HiOpt = combine(Hi.getNode()); | |||
4541 | if (HiOpt.getNode() && HiOpt != Hi && | |||
4542 | (!LegalOperations || | |||
4543 | TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType()))) | |||
4544 | return CombineTo(N, HiOpt, HiOpt); | |||
4545 | } | |||
4546 | ||||
4547 | return SDValue(); | |||
4548 | } | |||
4549 | ||||
4550 | SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { | |||
4551 | if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) | |||
4552 | return Res; | |||
4553 | ||||
4554 | EVT VT = N->getValueType(0); | |||
4555 | SDLoc DL(N); | |||
4556 | ||||
4557 | // If the type is twice as wide is legal, transform the mulhu to a wider | |||
4558 | // multiply plus a shift. | |||
4559 | if (VT.isSimple() && !VT.isVector()) { | |||
4560 | MVT Simple = VT.getSimpleVT(); | |||
4561 | unsigned SimpleSize = Simple.getSizeInBits(); | |||
4562 | EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); | |||
4563 | if (TLI.isOperationLegal(ISD::MUL, NewVT)) { | |||
4564 | SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); | |||
4565 | SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); | |||
4566 | Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); | |||
4567 | // Compute the high part as N1. | |||
4568 | Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, | |||
4569 | DAG.getConstant(SimpleSize, DL, | |||
4570 | getShiftAmountTy(Lo.getValueType()))); | |||
4571 | Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); | |||
4572 | // Compute the low part as N0. | |||
4573 | Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); | |||
4574 | return CombineTo(N, Lo, Hi); | |||
4575 | } | |||
4576 | } | |||
4577 | ||||
4578 | return SDValue(); | |||
4579 | } | |||
4580 | ||||
4581 | SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { | |||
4582 | if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) | |||
4583 | return Res; | |||
4584 | ||||
4585 | EVT VT = N->getValueType(0); | |||
4586 | SDLoc DL(N); | |||
4587 | ||||
4588 | // (umul_lohi N0, 0) -> (0, 0) | |||
4589 | if (isNullConstant(N->getOperand(1))) { | |||
4590 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
4591 | return CombineTo(N, Zero, Zero); | |||
4592 | } | |||
4593 | ||||
4594 | // (umul_lohi N0, 1) -> (N0, 0) | |||
4595 | if (isOneConstant(N->getOperand(1))) { | |||
4596 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
4597 | return CombineTo(N, N->getOperand(0), Zero); | |||
4598 | } | |||
4599 | ||||
4600 | // If the type is twice as wide is legal, transform the mulhu to a wider | |||
4601 | // multiply plus a shift. | |||
4602 | if (VT.isSimple() && !VT.isVector()) { | |||
4603 | MVT Simple = VT.getSimpleVT(); | |||
4604 | unsigned SimpleSize = Simple.getSizeInBits(); | |||
4605 | EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); | |||
4606 | if (TLI.isOperationLegal(ISD::MUL, NewVT)) { | |||
4607 | SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); | |||
4608 | SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); | |||
4609 | Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); | |||
4610 | // Compute the high part as N1. | |||
4611 | Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, | |||
4612 | DAG.getConstant(SimpleSize, DL, | |||
4613 | getShiftAmountTy(Lo.getValueType()))); | |||
4614 | Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); | |||
4615 | // Compute the low part as N0. | |||
4616 | Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); | |||
4617 | return CombineTo(N, Lo, Hi); | |||
4618 | } | |||
4619 | } | |||
4620 | ||||
4621 | return SDValue(); | |||
4622 | } | |||
4623 | ||||
4624 | SDValue DAGCombiner::visitMULO(SDNode *N) { | |||
4625 | SDValue N0 = N->getOperand(0); | |||
4626 | SDValue N1 = N->getOperand(1); | |||
4627 | EVT VT = N0.getValueType(); | |||
4628 | bool IsSigned = (ISD::SMULO == N->getOpcode()); | |||
4629 | ||||
4630 | EVT CarryVT = N->getValueType(1); | |||
4631 | SDLoc DL(N); | |||
4632 | ||||
4633 | ConstantSDNode *N0C = isConstOrConstSplat(N0); | |||
4634 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
4635 | ||||
4636 | // fold operation with constant operands. | |||
4637 | // TODO: Move this to FoldConstantArithmetic when it supports nodes with | |||
4638 | // multiple results. | |||
4639 | if (N0C && N1C) { | |||
4640 | bool Overflow; | |||
4641 | APInt Result = | |||
4642 | IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow) | |||
4643 | : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow); | |||
4644 | return CombineTo(N, DAG.getConstant(Result, DL, VT), | |||
4645 | DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT)); | |||
4646 | } | |||
4647 | ||||
4648 | // canonicalize constant to RHS. | |||
4649 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
4650 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
4651 | return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); | |||
4652 | ||||
4653 | // fold (mulo x, 0) -> 0 + no carry out | |||
4654 | if (isNullOrNullSplat(N1)) | |||
4655 | return CombineTo(N, DAG.getConstant(0, DL, VT), | |||
4656 | DAG.getConstant(0, DL, CarryVT)); | |||
4657 | ||||
4658 | // (mulo x, 2) -> (addo x, x) | |||
4659 | if (N1C && N1C->getAPIntValue() == 2) | |||
4660 | return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL, | |||
4661 | N->getVTList(), N0, N0); | |||
4662 | ||||
4663 | if (IsSigned) { | |||
4664 | // A 1 bit SMULO overflows if both inputs are 1. | |||
4665 | if (VT.getScalarSizeInBits() == 1) { | |||
4666 | SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1); | |||
4667 | return CombineTo(N, And, | |||
4668 | DAG.getSetCC(DL, CarryVT, And, | |||
4669 | DAG.getConstant(0, DL, VT), ISD::SETNE)); | |||
4670 | } | |||
4671 | ||||
4672 | // Multiplying n * m significant bits yields a result of n + m significant | |||
4673 | // bits. If the total number of significant bits does not exceed the | |||
4674 | // result bit width (minus 1), there is no overflow. | |||
4675 | unsigned SignBits = DAG.ComputeNumSignBits(N0); | |||
4676 | if (SignBits > 1) | |||
4677 | SignBits += DAG.ComputeNumSignBits(N1); | |||
4678 | if (SignBits > VT.getScalarSizeInBits() + 1) | |||
4679 | return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), | |||
4680 | DAG.getConstant(0, DL, CarryVT)); | |||
4681 | } else { | |||
4682 | KnownBits N1Known = DAG.computeKnownBits(N1); | |||
4683 | KnownBits N0Known = DAG.computeKnownBits(N0); | |||
4684 | bool Overflow; | |||
4685 | (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow); | |||
4686 | if (!Overflow) | |||
4687 | return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), | |||
4688 | DAG.getConstant(0, DL, CarryVT)); | |||
4689 | } | |||
4690 | ||||
4691 | return SDValue(); | |||
4692 | } | |||
4693 | ||||
4694 | SDValue DAGCombiner::visitIMINMAX(SDNode *N) { | |||
4695 | SDValue N0 = N->getOperand(0); | |||
4696 | SDValue N1 = N->getOperand(1); | |||
4697 | EVT VT = N0.getValueType(); | |||
4698 | unsigned Opcode = N->getOpcode(); | |||
4699 | ||||
4700 | // fold vector ops | |||
4701 | if (VT.isVector()) | |||
4702 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
4703 | return FoldedVOp; | |||
4704 | ||||
4705 | // fold operation with constant operands. | |||
4706 | if (SDValue C = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT, {N0, N1})) | |||
4707 | return C; | |||
4708 | ||||
4709 | // canonicalize constant to RHS | |||
4710 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
4711 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
4712 | return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); | |||
4713 | ||||
4714 | // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. | |||
4715 | // Only do this if the current op isn't legal and the flipped is. | |||
4716 | if (!TLI.isOperationLegal(Opcode, VT) && | |||
4717 | (N0.isUndef() || DAG.SignBitIsZero(N0)) && | |||
4718 | (N1.isUndef() || DAG.SignBitIsZero(N1))) { | |||
4719 | unsigned AltOpcode; | |||
4720 | switch (Opcode) { | |||
4721 | case ISD::SMIN: AltOpcode = ISD::UMIN; break; | |||
4722 | case ISD::SMAX: AltOpcode = ISD::UMAX; break; | |||
4723 | case ISD::UMIN: AltOpcode = ISD::SMIN; break; | |||
4724 | case ISD::UMAX: AltOpcode = ISD::SMAX; break; | |||
4725 | default: llvm_unreachable("Unknown MINMAX opcode")::llvm::llvm_unreachable_internal("Unknown MINMAX opcode", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4725); | |||
4726 | } | |||
4727 | if (TLI.isOperationLegal(AltOpcode, VT)) | |||
4728 | return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); | |||
4729 | } | |||
4730 | ||||
4731 | // Simplify the operands using demanded-bits information. | |||
4732 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
4733 | return SDValue(N, 0); | |||
4734 | ||||
4735 | return SDValue(); | |||
4736 | } | |||
4737 | ||||
4738 | /// If this is a bitwise logic instruction and both operands have the same | |||
4739 | /// opcode, try to sink the other opcode after the logic instruction. | |||
4740 | SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) { | |||
4741 | SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); | |||
4742 | EVT VT = N0.getValueType(); | |||
4743 | unsigned LogicOpcode = N->getOpcode(); | |||
4744 | unsigned HandOpcode = N0.getOpcode(); | |||
4745 | assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||(((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && "Expected logic opcode") ? static_cast <void> (0) : __assert_fail ("(LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && \"Expected logic opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4746, __PRETTY_FUNCTION__)) | |||
4746 | LogicOpcode == ISD::XOR) && "Expected logic opcode")(((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && "Expected logic opcode") ? static_cast <void> (0) : __assert_fail ("(LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || LogicOpcode == ISD::XOR) && \"Expected logic opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4746, __PRETTY_FUNCTION__)); | |||
4747 | assert(HandOpcode == N1.getOpcode() && "Bad input!")((HandOpcode == N1.getOpcode() && "Bad input!") ? static_cast <void> (0) : __assert_fail ("HandOpcode == N1.getOpcode() && \"Bad input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4747, __PRETTY_FUNCTION__)); | |||
4748 | ||||
4749 | // Bail early if none of these transforms apply. | |||
4750 | if (N0.getNumOperands() == 0) | |||
4751 | return SDValue(); | |||
4752 | ||||
4753 | // FIXME: We should check number of uses of the operands to not increase | |||
4754 | // the instruction count for all transforms. | |||
4755 | ||||
4756 | // Handle size-changing casts. | |||
4757 | SDValue X = N0.getOperand(0); | |||
4758 | SDValue Y = N1.getOperand(0); | |||
4759 | EVT XVT = X.getValueType(); | |||
4760 | SDLoc DL(N); | |||
4761 | if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND || | |||
4762 | HandOpcode == ISD::SIGN_EXTEND) { | |||
4763 | // If both operands have other uses, this transform would create extra | |||
4764 | // instructions without eliminating anything. | |||
4765 | if (!N0.hasOneUse() && !N1.hasOneUse()) | |||
4766 | return SDValue(); | |||
4767 | // We need matching integer source types. | |||
4768 | if (XVT != Y.getValueType()) | |||
4769 | return SDValue(); | |||
4770 | // Don't create an illegal op during or after legalization. Don't ever | |||
4771 | // create an unsupported vector op. | |||
4772 | if ((VT.isVector() || LegalOperations) && | |||
4773 | !TLI.isOperationLegalOrCustom(LogicOpcode, XVT)) | |||
4774 | return SDValue(); | |||
4775 | // Avoid infinite looping with PromoteIntBinOp. | |||
4776 | // TODO: Should we apply desirable/legal constraints to all opcodes? | |||
4777 | if (HandOpcode == ISD::ANY_EXTEND && LegalTypes && | |||
4778 | !TLI.isTypeDesirableForOp(LogicOpcode, XVT)) | |||
4779 | return SDValue(); | |||
4780 | // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y) | |||
4781 | SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); | |||
4782 | return DAG.getNode(HandOpcode, DL, VT, Logic); | |||
4783 | } | |||
4784 | ||||
4785 | // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y) | |||
4786 | if (HandOpcode == ISD::TRUNCATE) { | |||
4787 | // If both operands have other uses, this transform would create extra | |||
4788 | // instructions without eliminating anything. | |||
4789 | if (!N0.hasOneUse() && !N1.hasOneUse()) | |||
4790 | return SDValue(); | |||
4791 | // We need matching source types. | |||
4792 | if (XVT != Y.getValueType()) | |||
4793 | return SDValue(); | |||
4794 | // Don't create an illegal op during or after legalization. | |||
4795 | if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT)) | |||
4796 | return SDValue(); | |||
4797 | // Be extra careful sinking truncate. If it's free, there's no benefit in | |||
4798 | // widening a binop. Also, don't create a logic op on an illegal type. | |||
4799 | if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT)) | |||
4800 | return SDValue(); | |||
4801 | if (!TLI.isTypeLegal(XVT)) | |||
4802 | return SDValue(); | |||
4803 | SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); | |||
4804 | return DAG.getNode(HandOpcode, DL, VT, Logic); | |||
4805 | } | |||
4806 | ||||
4807 | // For binops SHL/SRL/SRA/AND: | |||
4808 | // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z | |||
4809 | if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL || | |||
4810 | HandOpcode == ISD::SRA || HandOpcode == ISD::AND) && | |||
4811 | N0.getOperand(1) == N1.getOperand(1)) { | |||
4812 | // If either operand has other uses, this transform is not an improvement. | |||
4813 | if (!N0.hasOneUse() || !N1.hasOneUse()) | |||
4814 | return SDValue(); | |||
4815 | SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); | |||
4816 | return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1)); | |||
4817 | } | |||
4818 | ||||
4819 | // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y) | |||
4820 | if (HandOpcode == ISD::BSWAP) { | |||
4821 | // If either operand has other uses, this transform is not an improvement. | |||
4822 | if (!N0.hasOneUse() || !N1.hasOneUse()) | |||
4823 | return SDValue(); | |||
4824 | SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); | |||
4825 | return DAG.getNode(HandOpcode, DL, VT, Logic); | |||
4826 | } | |||
4827 | ||||
4828 | // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) | |||
4829 | // Only perform this optimization up until type legalization, before | |||
4830 | // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by | |||
4831 | // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and | |||
4832 | // we don't want to undo this promotion. | |||
4833 | // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper | |||
4834 | // on scalars. | |||
4835 | if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) && | |||
4836 | Level <= AfterLegalizeTypes) { | |||
4837 | // Input types must be integer and the same. | |||
4838 | if (XVT.isInteger() && XVT == Y.getValueType() && | |||
4839 | !(VT.isVector() && TLI.isTypeLegal(VT) && | |||
4840 | !XVT.isVector() && !TLI.isTypeLegal(XVT))) { | |||
4841 | SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); | |||
4842 | return DAG.getNode(HandOpcode, DL, VT, Logic); | |||
4843 | } | |||
4844 | } | |||
4845 | ||||
4846 | // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). | |||
4847 | // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) | |||
4848 | // If both shuffles use the same mask, and both shuffle within a single | |||
4849 | // vector, then it is worthwhile to move the swizzle after the operation. | |||
4850 | // The type-legalizer generates this pattern when loading illegal | |||
4851 | // vector types from memory. In many cases this allows additional shuffle | |||
4852 | // optimizations. | |||
4853 | // There are other cases where moving the shuffle after the xor/and/or | |||
4854 | // is profitable even if shuffles don't perform a swizzle. | |||
4855 | // If both shuffles use the same mask, and both shuffles have the same first | |||
4856 | // or second operand, then it might still be profitable to move the shuffle | |||
4857 | // after the xor/and/or operation. | |||
4858 | if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { | |||
4859 | auto *SVN0 = cast<ShuffleVectorSDNode>(N0); | |||
4860 | auto *SVN1 = cast<ShuffleVectorSDNode>(N1); | |||
4861 | assert(X.getValueType() == Y.getValueType() &&((X.getValueType() == Y.getValueType() && "Inputs to shuffles are not the same type" ) ? static_cast<void> (0) : __assert_fail ("X.getValueType() == Y.getValueType() && \"Inputs to shuffles are not the same type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4862, __PRETTY_FUNCTION__)) | |||
4862 | "Inputs to shuffles are not the same type")((X.getValueType() == Y.getValueType() && "Inputs to shuffles are not the same type" ) ? static_cast<void> (0) : __assert_fail ("X.getValueType() == Y.getValueType() && \"Inputs to shuffles are not the same type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4862, __PRETTY_FUNCTION__)); | |||
4863 | ||||
4864 | // Check that both shuffles use the same mask. The masks are known to be of | |||
4865 | // the same length because the result vector type is the same. | |||
4866 | // Check also that shuffles have only one use to avoid introducing extra | |||
4867 | // instructions. | |||
4868 | if (!SVN0->hasOneUse() || !SVN1->hasOneUse() || | |||
4869 | !SVN0->getMask().equals(SVN1->getMask())) | |||
4870 | return SDValue(); | |||
4871 | ||||
4872 | // Don't try to fold this node if it requires introducing a | |||
4873 | // build vector of all zeros that might be illegal at this stage. | |||
4874 | SDValue ShOp = N0.getOperand(1); | |||
4875 | if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) | |||
4876 | ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); | |||
4877 | ||||
4878 | // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C) | |||
4879 | if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { | |||
4880 | SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, | |||
4881 | N0.getOperand(0), N1.getOperand(0)); | |||
4882 | return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask()); | |||
4883 | } | |||
4884 | ||||
4885 | // Don't try to fold this node if it requires introducing a | |||
4886 | // build vector of all zeros that might be illegal at this stage. | |||
4887 | ShOp = N0.getOperand(0); | |||
4888 | if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) | |||
4889 | ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); | |||
4890 | ||||
4891 | // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B)) | |||
4892 | if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) { | |||
4893 | SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1), | |||
4894 | N1.getOperand(1)); | |||
4895 | return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask()); | |||
4896 | } | |||
4897 | } | |||
4898 | ||||
4899 | return SDValue(); | |||
4900 | } | |||
4901 | ||||
4902 | /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. | |||
4903 | SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, | |||
4904 | const SDLoc &DL) { | |||
4905 | SDValue LL, LR, RL, RR, N0CC, N1CC; | |||
4906 | if (!isSetCCEquivalent(N0, LL, LR, N0CC) || | |||
4907 | !isSetCCEquivalent(N1, RL, RR, N1CC)) | |||
4908 | return SDValue(); | |||
4909 | ||||
4910 | assert(N0.getValueType() == N1.getValueType() &&((N0.getValueType() == N1.getValueType() && "Unexpected operand types for bitwise logic op" ) ? static_cast<void> (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4911, __PRETTY_FUNCTION__)) | |||
4911 | "Unexpected operand types for bitwise logic op")((N0.getValueType() == N1.getValueType() && "Unexpected operand types for bitwise logic op" ) ? static_cast<void> (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4911, __PRETTY_FUNCTION__)); | |||
4912 | assert(LL.getValueType() == LR.getValueType() &&((LL.getValueType() == LR.getValueType() && RL.getValueType () == RR.getValueType() && "Unexpected operand types for setcc" ) ? static_cast<void> (0) : __assert_fail ("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4914, __PRETTY_FUNCTION__)) | |||
4913 | RL.getValueType() == RR.getValueType() &&((LL.getValueType() == LR.getValueType() && RL.getValueType () == RR.getValueType() && "Unexpected operand types for setcc" ) ? static_cast<void> (0) : __assert_fail ("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4914, __PRETTY_FUNCTION__)) | |||
4914 | "Unexpected operand types for setcc")((LL.getValueType() == LR.getValueType() && RL.getValueType () == RR.getValueType() && "Unexpected operand types for setcc" ) ? static_cast<void> (0) : __assert_fail ("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 4914, __PRETTY_FUNCTION__)); | |||
4915 | ||||
4916 | // If we're here post-legalization or the logic op type is not i1, the logic | |||
4917 | // op type must match a setcc result type. Also, all folds require new | |||
4918 | // operations on the left and right operands, so those types must match. | |||
4919 | EVT VT = N0.getValueType(); | |||
4920 | EVT OpVT = LL.getValueType(); | |||
4921 | if (LegalOperations || VT.getScalarType() != MVT::i1) | |||
4922 | if (VT != getSetCCResultType(OpVT)) | |||
4923 | return SDValue(); | |||
4924 | if (OpVT != RL.getValueType()) | |||
4925 | return SDValue(); | |||
4926 | ||||
4927 | ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); | |||
4928 | ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); | |||
4929 | bool IsInteger = OpVT.isInteger(); | |||
4930 | if (LR == RR && CC0 == CC1 && IsInteger) { | |||
4931 | bool IsZero = isNullOrNullSplat(LR); | |||
4932 | bool IsNeg1 = isAllOnesOrAllOnesSplat(LR); | |||
4933 | ||||
4934 | // All bits clear? | |||
4935 | bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; | |||
4936 | // All sign bits clear? | |||
4937 | bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; | |||
4938 | // Any bits set? | |||
4939 | bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; | |||
4940 | // Any sign bits set? | |||
4941 | bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; | |||
4942 | ||||
4943 | // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) | |||
4944 | // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) | |||
4945 | // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) | |||
4946 | // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) | |||
4947 | if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { | |||
4948 | SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); | |||
4949 | AddToWorklist(Or.getNode()); | |||
4950 | return DAG.getSetCC(DL, VT, Or, LR, CC1); | |||
4951 | } | |||
4952 | ||||
4953 | // All bits set? | |||
4954 | bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; | |||
4955 | // All sign bits set? | |||
4956 | bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; | |||
4957 | // Any bits clear? | |||
4958 | bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; | |||
4959 | // Any sign bits clear? | |||
4960 | bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; | |||
4961 | ||||
4962 | // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) | |||
4963 | // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) | |||
4964 | // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) | |||
4965 | // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) | |||
4966 | if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { | |||
4967 | SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); | |||
4968 | AddToWorklist(And.getNode()); | |||
4969 | return DAG.getSetCC(DL, VT, And, LR, CC1); | |||
4970 | } | |||
4971 | } | |||
4972 | ||||
4973 | // TODO: What is the 'or' equivalent of this fold? | |||
4974 | // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) | |||
4975 | if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && | |||
4976 | IsInteger && CC0 == ISD::SETNE && | |||
4977 | ((isNullConstant(LR) && isAllOnesConstant(RR)) || | |||
4978 | (isAllOnesConstant(LR) && isNullConstant(RR)))) { | |||
4979 | SDValue One = DAG.getConstant(1, DL, OpVT); | |||
4980 | SDValue Two = DAG.getConstant(2, DL, OpVT); | |||
4981 | SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); | |||
4982 | AddToWorklist(Add.getNode()); | |||
4983 | return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); | |||
4984 | } | |||
4985 | ||||
4986 | // Try more general transforms if the predicates match and the only user of | |||
4987 | // the compares is the 'and' or 'or'. | |||
4988 | if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && | |||
4989 | N0.hasOneUse() && N1.hasOneUse()) { | |||
4990 | // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 | |||
4991 | // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 | |||
4992 | if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { | |||
4993 | SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); | |||
4994 | SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); | |||
4995 | SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); | |||
4996 | SDValue Zero = DAG.getConstant(0, DL, OpVT); | |||
4997 | return DAG.getSetCC(DL, VT, Or, Zero, CC1); | |||
4998 | } | |||
4999 | ||||
5000 | // Turn compare of constants whose difference is 1 bit into add+and+setcc. | |||
5001 | // TODO - support non-uniform vector amounts. | |||
5002 | if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) { | |||
5003 | // Match a shared variable operand and 2 non-opaque constant operands. | |||
5004 | ConstantSDNode *C0 = isConstOrConstSplat(LR); | |||
5005 | ConstantSDNode *C1 = isConstOrConstSplat(RR); | |||
5006 | if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) { | |||
5007 | const APInt &CMax = | |||
5008 | APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue()); | |||
5009 | const APInt &CMin = | |||
5010 | APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue()); | |||
5011 | // The difference of the constants must be a single bit. | |||
5012 | if ((CMax - CMin).isPowerOf2()) { | |||
5013 | // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) --> | |||
5014 | // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq | |||
5015 | SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR); | |||
5016 | SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR); | |||
5017 | SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min); | |||
5018 | SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min); | |||
5019 | SDValue Mask = DAG.getNOT(DL, Diff, OpVT); | |||
5020 | SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask); | |||
5021 | SDValue Zero = DAG.getConstant(0, DL, OpVT); | |||
5022 | return DAG.getSetCC(DL, VT, And, Zero, CC0); | |||
5023 | } | |||
5024 | } | |||
5025 | } | |||
5026 | } | |||
5027 | ||||
5028 | // Canonicalize equivalent operands to LL == RL. | |||
5029 | if (LL == RR && LR == RL) { | |||
5030 | CC1 = ISD::getSetCCSwappedOperands(CC1); | |||
5031 | std::swap(RL, RR); | |||
5032 | } | |||
5033 | ||||
5034 | // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) | |||
5035 | // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) | |||
5036 | if (LL == RL && LR == RR) { | |||
5037 | ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT) | |||
5038 | : ISD::getSetCCOrOperation(CC0, CC1, OpVT); | |||
5039 | if (NewCC != ISD::SETCC_INVALID && | |||
5040 | (!LegalOperations || | |||
5041 | (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && | |||
5042 | TLI.isOperationLegal(ISD::SETCC, OpVT)))) | |||
5043 | return DAG.getSetCC(DL, VT, LL, LR, NewCC); | |||
5044 | } | |||
5045 | ||||
5046 | return SDValue(); | |||
5047 | } | |||
5048 | ||||
5049 | /// This contains all DAGCombine rules which reduce two values combined by | |||
5050 | /// an And operation to a single value. This makes them reusable in the context | |||
5051 | /// of visitSELECT(). Rules involving constants are not included as | |||
5052 | /// visitSELECT() already handles those cases. | |||
5053 | SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { | |||
5054 | EVT VT = N1.getValueType(); | |||
5055 | SDLoc DL(N); | |||
5056 | ||||
5057 | // fold (and x, undef) -> 0 | |||
5058 | if (N0.isUndef() || N1.isUndef()) | |||
5059 | return DAG.getConstant(0, DL, VT); | |||
5060 | ||||
5061 | if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) | |||
5062 | return V; | |||
5063 | ||||
5064 | if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && | |||
5065 | VT.getSizeInBits() <= 64) { | |||
5066 | if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { | |||
5067 | if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { | |||
5068 | // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal | |||
5069 | // immediate for an add, but it is legal if its top c2 bits are set, | |||
5070 | // transform the ADD so the immediate doesn't need to be materialized | |||
5071 | // in a register. | |||
5072 | APInt ADDC = ADDI->getAPIntValue(); | |||
5073 | APInt SRLC = SRLI->getAPIntValue(); | |||
5074 | if (ADDC.getMinSignedBits() <= 64 && | |||
5075 | SRLC.ult(VT.getSizeInBits()) && | |||
5076 | !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { | |||
5077 | APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), | |||
5078 | SRLC.getZExtValue()); | |||
5079 | if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { | |||
5080 | ADDC |= Mask; | |||
5081 | if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { | |||
5082 | SDLoc DL0(N0); | |||
5083 | SDValue NewAdd = | |||
5084 | DAG.getNode(ISD::ADD, DL0, VT, | |||
5085 | N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); | |||
5086 | CombineTo(N0.getNode(), NewAdd); | |||
5087 | // Return N so it doesn't get rechecked! | |||
5088 | return SDValue(N, 0); | |||
5089 | } | |||
5090 | } | |||
5091 | } | |||
5092 | } | |||
5093 | } | |||
5094 | } | |||
5095 | ||||
5096 | // Reduce bit extract of low half of an integer to the narrower type. | |||
5097 | // (and (srl i64:x, K), KMask) -> | |||
5098 | // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) | |||
5099 | if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { | |||
5100 | if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { | |||
5101 | if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { | |||
5102 | unsigned Size = VT.getSizeInBits(); | |||
5103 | const APInt &AndMask = CAnd->getAPIntValue(); | |||
5104 | unsigned ShiftBits = CShift->getZExtValue(); | |||
5105 | ||||
5106 | // Bail out, this node will probably disappear anyway. | |||
5107 | if (ShiftBits == 0) | |||
5108 | return SDValue(); | |||
5109 | ||||
5110 | unsigned MaskBits = AndMask.countTrailingOnes(); | |||
5111 | EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); | |||
5112 | ||||
5113 | if (AndMask.isMask() && | |||
5114 | // Required bits must not span the two halves of the integer and | |||
5115 | // must fit in the half size type. | |||
5116 | (ShiftBits + MaskBits <= Size / 2) && | |||
5117 | TLI.isNarrowingProfitable(VT, HalfVT) && | |||
5118 | TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && | |||
5119 | TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && | |||
5120 | TLI.isTruncateFree(VT, HalfVT) && | |||
5121 | TLI.isZExtFree(HalfVT, VT)) { | |||
5122 | // The isNarrowingProfitable is to avoid regressions on PPC and | |||
5123 | // AArch64 which match a few 64-bit bit insert / bit extract patterns | |||
5124 | // on downstream users of this. Those patterns could probably be | |||
5125 | // extended to handle extensions mixed in. | |||
5126 | ||||
5127 | SDValue SL(N0); | |||
5128 | assert(MaskBits <= Size)((MaskBits <= Size) ? static_cast<void> (0) : __assert_fail ("MaskBits <= Size", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5128, __PRETTY_FUNCTION__)); | |||
5129 | ||||
5130 | // Extracting the highest bit of the low half. | |||
5131 | EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); | |||
5132 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, | |||
5133 | N0.getOperand(0)); | |||
5134 | ||||
5135 | SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); | |||
5136 | SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); | |||
5137 | SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); | |||
5138 | SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); | |||
5139 | return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); | |||
5140 | } | |||
5141 | } | |||
5142 | } | |||
5143 | } | |||
5144 | ||||
5145 | return SDValue(); | |||
5146 | } | |||
5147 | ||||
5148 | bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, | |||
5149 | EVT LoadResultTy, EVT &ExtVT) { | |||
5150 | if (!AndC->getAPIntValue().isMask()) | |||
5151 | return false; | |||
5152 | ||||
5153 | unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); | |||
5154 | ||||
5155 | ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); | |||
5156 | EVT LoadedVT = LoadN->getMemoryVT(); | |||
5157 | ||||
5158 | if (ExtVT == LoadedVT && | |||
5159 | (!LegalOperations || | |||
5160 | TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { | |||
5161 | // ZEXTLOAD will match without needing to change the size of the value being | |||
5162 | // loaded. | |||
5163 | return true; | |||
5164 | } | |||
5165 | ||||
5166 | // Do not change the width of a volatile or atomic loads. | |||
5167 | if (!LoadN->isSimple()) | |||
5168 | return false; | |||
5169 | ||||
5170 | // Do not generate loads of non-round integer types since these can | |||
5171 | // be expensive (and would be wrong if the type is not byte sized). | |||
5172 | if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) | |||
5173 | return false; | |||
5174 | ||||
5175 | if (LegalOperations && | |||
5176 | !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) | |||
5177 | return false; | |||
5178 | ||||
5179 | if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) | |||
5180 | return false; | |||
5181 | ||||
5182 | return true; | |||
5183 | } | |||
5184 | ||||
5185 | bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, | |||
5186 | ISD::LoadExtType ExtType, EVT &MemVT, | |||
5187 | unsigned ShAmt) { | |||
5188 | if (!LDST) | |||
5189 | return false; | |||
5190 | // Only allow byte offsets. | |||
5191 | if (ShAmt % 8) | |||
5192 | return false; | |||
5193 | ||||
5194 | // Do not generate loads of non-round integer types since these can | |||
5195 | // be expensive (and would be wrong if the type is not byte sized). | |||
5196 | if (!MemVT.isRound()) | |||
5197 | return false; | |||
5198 | ||||
5199 | // Don't change the width of a volatile or atomic loads. | |||
5200 | if (!LDST->isSimple()) | |||
5201 | return false; | |||
5202 | ||||
5203 | EVT LdStMemVT = LDST->getMemoryVT(); | |||
5204 | ||||
5205 | // Bail out when changing the scalable property, since we can't be sure that | |||
5206 | // we're actually narrowing here. | |||
5207 | if (LdStMemVT.isScalableVector() != MemVT.isScalableVector()) | |||
5208 | return false; | |||
5209 | ||||
5210 | // Verify that we are actually reducing a load width here. | |||
5211 | if (LdStMemVT.bitsLT(MemVT)) | |||
5212 | return false; | |||
5213 | ||||
5214 | // Ensure that this isn't going to produce an unsupported memory access. | |||
5215 | if (ShAmt) { | |||
5216 | assert(ShAmt % 8 == 0 && "ShAmt is byte offset")((ShAmt % 8 == 0 && "ShAmt is byte offset") ? static_cast <void> (0) : __assert_fail ("ShAmt % 8 == 0 && \"ShAmt is byte offset\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5216, __PRETTY_FUNCTION__)); | |||
5217 | const unsigned ByteShAmt = ShAmt / 8; | |||
5218 | const Align LDSTAlign = LDST->getAlign(); | |||
5219 | const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt); | |||
5220 | if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, | |||
5221 | LDST->getAddressSpace(), NarrowAlign, | |||
5222 | LDST->getMemOperand()->getFlags())) | |||
5223 | return false; | |||
5224 | } | |||
5225 | ||||
5226 | // It's not possible to generate a constant of extended or untyped type. | |||
5227 | EVT PtrType = LDST->getBasePtr().getValueType(); | |||
5228 | if (PtrType == MVT::Untyped || PtrType.isExtended()) | |||
5229 | return false; | |||
5230 | ||||
5231 | if (isa<LoadSDNode>(LDST)) { | |||
5232 | LoadSDNode *Load = cast<LoadSDNode>(LDST); | |||
5233 | // Don't transform one with multiple uses, this would require adding a new | |||
5234 | // load. | |||
5235 | if (!SDValue(Load, 0).hasOneUse()) | |||
5236 | return false; | |||
5237 | ||||
5238 | if (LegalOperations && | |||
5239 | !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) | |||
5240 | return false; | |||
5241 | ||||
5242 | // For the transform to be legal, the load must produce only two values | |||
5243 | // (the value loaded and the chain). Don't transform a pre-increment | |||
5244 | // load, for example, which produces an extra value. Otherwise the | |||
5245 | // transformation is not equivalent, and the downstream logic to replace | |||
5246 | // uses gets things wrong. | |||
5247 | if (Load->getNumValues() > 2) | |||
5248 | return false; | |||
5249 | ||||
5250 | // If the load that we're shrinking is an extload and we're not just | |||
5251 | // discarding the extension we can't simply shrink the load. Bail. | |||
5252 | // TODO: It would be possible to merge the extensions in some cases. | |||
5253 | if (Load->getExtensionType() != ISD::NON_EXTLOAD && | |||
5254 | Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) | |||
5255 | return false; | |||
5256 | ||||
5257 | if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) | |||
5258 | return false; | |||
5259 | } else { | |||
5260 | assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode")((isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode" ) ? static_cast<void> (0) : __assert_fail ("isa<StoreSDNode>(LDST) && \"It is not a Load nor a Store SDNode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5260, __PRETTY_FUNCTION__)); | |||
5261 | StoreSDNode *Store = cast<StoreSDNode>(LDST); | |||
5262 | // Can't write outside the original store | |||
5263 | if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) | |||
5264 | return false; | |||
5265 | ||||
5266 | if (LegalOperations && | |||
5267 | !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) | |||
5268 | return false; | |||
5269 | } | |||
5270 | return true; | |||
5271 | } | |||
5272 | ||||
5273 | bool DAGCombiner::SearchForAndLoads(SDNode *N, | |||
5274 | SmallVectorImpl<LoadSDNode*> &Loads, | |||
5275 | SmallPtrSetImpl<SDNode*> &NodesWithConsts, | |||
5276 | ConstantSDNode *Mask, | |||
5277 | SDNode *&NodeToMask) { | |||
5278 | // Recursively search for the operands, looking for loads which can be | |||
5279 | // narrowed. | |||
5280 | for (SDValue Op : N->op_values()) { | |||
5281 | if (Op.getValueType().isVector()) | |||
5282 | return false; | |||
5283 | ||||
5284 | // Some constants may need fixing up later if they are too large. | |||
5285 | if (auto *C = dyn_cast<ConstantSDNode>(Op)) { | |||
5286 | if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && | |||
5287 | (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) | |||
5288 | NodesWithConsts.insert(N); | |||
5289 | continue; | |||
5290 | } | |||
5291 | ||||
5292 | if (!Op.hasOneUse()) | |||
5293 | return false; | |||
5294 | ||||
5295 | switch(Op.getOpcode()) { | |||
5296 | case ISD::LOAD: { | |||
5297 | auto *Load = cast<LoadSDNode>(Op); | |||
5298 | EVT ExtVT; | |||
5299 | if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && | |||
5300 | isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { | |||
5301 | ||||
5302 | // ZEXTLOAD is already small enough. | |||
5303 | if (Load->getExtensionType() == ISD::ZEXTLOAD && | |||
5304 | ExtVT.bitsGE(Load->getMemoryVT())) | |||
5305 | continue; | |||
5306 | ||||
5307 | // Use LE to convert equal sized loads to zext. | |||
5308 | if (ExtVT.bitsLE(Load->getMemoryVT())) | |||
5309 | Loads.push_back(Load); | |||
5310 | ||||
5311 | continue; | |||
5312 | } | |||
5313 | return false; | |||
5314 | } | |||
5315 | case ISD::ZERO_EXTEND: | |||
5316 | case ISD::AssertZext: { | |||
5317 | unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); | |||
5318 | EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); | |||
5319 | EVT VT = Op.getOpcode() == ISD::AssertZext ? | |||
5320 | cast<VTSDNode>(Op.getOperand(1))->getVT() : | |||
5321 | Op.getOperand(0).getValueType(); | |||
5322 | ||||
5323 | // We can accept extending nodes if the mask is wider or an equal | |||
5324 | // width to the original type. | |||
5325 | if (ExtVT.bitsGE(VT)) | |||
5326 | continue; | |||
5327 | break; | |||
5328 | } | |||
5329 | case ISD::OR: | |||
5330 | case ISD::XOR: | |||
5331 | case ISD::AND: | |||
5332 | if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, | |||
5333 | NodeToMask)) | |||
5334 | return false; | |||
5335 | continue; | |||
5336 | } | |||
5337 | ||||
5338 | // Allow one node which will masked along with any loads found. | |||
5339 | if (NodeToMask) | |||
5340 | return false; | |||
5341 | ||||
5342 | // Also ensure that the node to be masked only produces one data result. | |||
5343 | NodeToMask = Op.getNode(); | |||
5344 | if (NodeToMask->getNumValues() > 1) { | |||
5345 | bool HasValue = false; | |||
5346 | for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { | |||
5347 | MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); | |||
5348 | if (VT != MVT::Glue && VT != MVT::Other) { | |||
5349 | if (HasValue) { | |||
5350 | NodeToMask = nullptr; | |||
5351 | return false; | |||
5352 | } | |||
5353 | HasValue = true; | |||
5354 | } | |||
5355 | } | |||
5356 | assert(HasValue && "Node to be masked has no data result?")((HasValue && "Node to be masked has no data result?" ) ? static_cast<void> (0) : __assert_fail ("HasValue && \"Node to be masked has no data result?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5356, __PRETTY_FUNCTION__)); | |||
5357 | } | |||
5358 | } | |||
5359 | return true; | |||
5360 | } | |||
5361 | ||||
5362 | bool DAGCombiner::BackwardsPropagateMask(SDNode *N) { | |||
5363 | auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); | |||
5364 | if (!Mask) | |||
5365 | return false; | |||
5366 | ||||
5367 | if (!Mask->getAPIntValue().isMask()) | |||
5368 | return false; | |||
5369 | ||||
5370 | // No need to do anything if the and directly uses a load. | |||
5371 | if (isa<LoadSDNode>(N->getOperand(0))) | |||
5372 | return false; | |||
5373 | ||||
5374 | SmallVector<LoadSDNode*, 8> Loads; | |||
5375 | SmallPtrSet<SDNode*, 2> NodesWithConsts; | |||
5376 | SDNode *FixupNode = nullptr; | |||
5377 | if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { | |||
5378 | if (Loads.size() == 0) | |||
5379 | return false; | |||
5380 | ||||
5381 | LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "Backwards propagate AND: " ; N->dump(); } } while (false); | |||
5382 | SDValue MaskOp = N->getOperand(1); | |||
5383 | ||||
5384 | // If it exists, fixup the single node we allow in the tree that needs | |||
5385 | // masking. | |||
5386 | if (FixupNode) { | |||
5387 | LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "First, need to fix up: "; FixupNode ->dump(); } } while (false); | |||
5388 | SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), | |||
5389 | FixupNode->getValueType(0), | |||
5390 | SDValue(FixupNode, 0), MaskOp); | |||
5391 | DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); | |||
5392 | if (And.getOpcode() == ISD ::AND) | |||
5393 | DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); | |||
5394 | } | |||
5395 | ||||
5396 | // Narrow any constants that need it. | |||
5397 | for (auto *LogicN : NodesWithConsts) { | |||
5398 | SDValue Op0 = LogicN->getOperand(0); | |||
5399 | SDValue Op1 = LogicN->getOperand(1); | |||
5400 | ||||
5401 | if (isa<ConstantSDNode>(Op0)) | |||
5402 | std::swap(Op0, Op1); | |||
5403 | ||||
5404 | SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), | |||
5405 | Op1, MaskOp); | |||
5406 | ||||
5407 | DAG.UpdateNodeOperands(LogicN, Op0, And); | |||
5408 | } | |||
5409 | ||||
5410 | // Create narrow loads. | |||
5411 | for (auto *Load : Loads) { | |||
5412 | LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "Propagate AND back to: "; Load ->dump(); } } while (false); | |||
5413 | SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), | |||
5414 | SDValue(Load, 0), MaskOp); | |||
5415 | DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); | |||
5416 | if (And.getOpcode() == ISD ::AND) | |||
5417 | And = SDValue( | |||
5418 | DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); | |||
5419 | SDValue NewLoad = ReduceLoadWidth(And.getNode()); | |||
5420 | assert(NewLoad &&((NewLoad && "Shouldn't be masking the load if it can't be narrowed" ) ? static_cast<void> (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5421, __PRETTY_FUNCTION__)) | |||
5421 | "Shouldn't be masking the load if it can't be narrowed")((NewLoad && "Shouldn't be masking the load if it can't be narrowed" ) ? static_cast<void> (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5421, __PRETTY_FUNCTION__)); | |||
5422 | CombineTo(Load, NewLoad, NewLoad.getValue(1)); | |||
5423 | } | |||
5424 | DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); | |||
5425 | return true; | |||
5426 | } | |||
5427 | return false; | |||
5428 | } | |||
5429 | ||||
5430 | // Unfold | |||
5431 | // x & (-1 'logical shift' y) | |||
5432 | // To | |||
5433 | // (x 'opposite logical shift' y) 'logical shift' y | |||
5434 | // if it is better for performance. | |||
5435 | SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { | |||
5436 | assert(N->getOpcode() == ISD::AND)((N->getOpcode() == ISD::AND) ? static_cast<void> (0 ) : __assert_fail ("N->getOpcode() == ISD::AND", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5436, __PRETTY_FUNCTION__)); | |||
5437 | ||||
5438 | SDValue N0 = N->getOperand(0); | |||
5439 | SDValue N1 = N->getOperand(1); | |||
5440 | ||||
5441 | // Do we actually prefer shifts over mask? | |||
5442 | if (!TLI.shouldFoldMaskToVariableShiftPair(N0)) | |||
5443 | return SDValue(); | |||
5444 | ||||
5445 | // Try to match (-1 '[outer] logical shift' y) | |||
5446 | unsigned OuterShift; | |||
5447 | unsigned InnerShift; // The opposite direction to the OuterShift. | |||
5448 | SDValue Y; // Shift amount. | |||
5449 | auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { | |||
5450 | if (!M.hasOneUse()) | |||
5451 | return false; | |||
5452 | OuterShift = M->getOpcode(); | |||
5453 | if (OuterShift == ISD::SHL) | |||
5454 | InnerShift = ISD::SRL; | |||
5455 | else if (OuterShift == ISD::SRL) | |||
5456 | InnerShift = ISD::SHL; | |||
5457 | else | |||
5458 | return false; | |||
5459 | if (!isAllOnesConstant(M->getOperand(0))) | |||
5460 | return false; | |||
5461 | Y = M->getOperand(1); | |||
5462 | return true; | |||
5463 | }; | |||
5464 | ||||
5465 | SDValue X; | |||
5466 | if (matchMask(N1)) | |||
5467 | X = N0; | |||
5468 | else if (matchMask(N0)) | |||
5469 | X = N1; | |||
5470 | else | |||
5471 | return SDValue(); | |||
5472 | ||||
5473 | SDLoc DL(N); | |||
5474 | EVT VT = N->getValueType(0); | |||
5475 | ||||
5476 | // tmp = x 'opposite logical shift' y | |||
5477 | SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); | |||
5478 | // ret = tmp 'logical shift' y | |||
5479 | SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); | |||
5480 | ||||
5481 | return T1; | |||
5482 | } | |||
5483 | ||||
5484 | /// Try to replace shift/logic that tests if a bit is clear with mask + setcc. | |||
5485 | /// For a target with a bit test, this is expected to become test + set and save | |||
5486 | /// at least 1 instruction. | |||
5487 | static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) { | |||
5488 | assert(And->getOpcode() == ISD::AND && "Expected an 'and' op")((And->getOpcode() == ISD::AND && "Expected an 'and' op" ) ? static_cast<void> (0) : __assert_fail ("And->getOpcode() == ISD::AND && \"Expected an 'and' op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 5488, __PRETTY_FUNCTION__)); | |||
5489 | ||||
5490 | // This is probably not worthwhile without a supported type. | |||
5491 | EVT VT = And->getValueType(0); | |||
5492 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
5493 | if (!TLI.isTypeLegal(VT)) | |||
5494 | return SDValue(); | |||
5495 | ||||
5496 | // Look through an optional extension and find a 'not'. | |||
5497 | // TODO: Should we favor test+set even without the 'not' op? | |||
5498 | SDValue Not = And->getOperand(0), And1 = And->getOperand(1); | |||
5499 | if (Not.getOpcode() == ISD::ANY_EXTEND) | |||
5500 | Not = Not.getOperand(0); | |||
5501 | if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1)) | |||
5502 | return SDValue(); | |||
5503 | ||||
5504 | // Look though an optional truncation. The source operand may not be the same | |||
5505 | // type as the original 'and', but that is ok because we are masking off | |||
5506 | // everything but the low bit. | |||
5507 | SDValue Srl = Not.getOperand(0); | |||
5508 | if (Srl.getOpcode() == ISD::TRUNCATE) | |||
5509 | Srl = Srl.getOperand(0); | |||
5510 | ||||
5511 | // Match a shift-right by constant. | |||
5512 | if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() || | |||
5513 | !isa<ConstantSDNode>(Srl.getOperand(1))) | |||
5514 | return SDValue(); | |||
5515 | ||||
5516 | // We might have looked through casts that make this transform invalid. | |||
5517 | // TODO: If the source type is wider than the result type, do the mask and | |||
5518 | // compare in the source type. | |||
5519 | const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1); | |||
5520 | unsigned VTBitWidth = VT.getSizeInBits(); | |||
5521 | if (ShiftAmt.uge(VTBitWidth)) | |||
5522 | return SDValue(); | |||
5523 | ||||
5524 | // Turn this into a bit-test pattern using mask op + setcc: | |||
5525 | // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0 | |||
5526 | SDLoc DL(And); | |||
5527 | SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT); | |||
5528 | EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); | |||
5529 | SDValue Mask = DAG.getConstant( | |||
5530 | APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT); | |||
5531 | SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask); | |||
5532 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
5533 | SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ); | |||
5534 | return DAG.getZExtOrTrunc(Setcc, DL, VT); | |||
5535 | } | |||
5536 | ||||
5537 | SDValue DAGCombiner::visitAND(SDNode *N) { | |||
5538 | SDValue N0 = N->getOperand(0); | |||
5539 | SDValue N1 = N->getOperand(1); | |||
5540 | EVT VT = N1.getValueType(); | |||
5541 | ||||
5542 | // x & x --> x | |||
5543 | if (N0 == N1) | |||
5544 | return N0; | |||
5545 | ||||
5546 | // fold vector ops | |||
5547 | if (VT.isVector()) { | |||
5548 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
5549 | return FoldedVOp; | |||
5550 | ||||
5551 | // fold (and x, 0) -> 0, vector edition | |||
5552 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
5553 | // do not return N0, because undef node may exist in N0 | |||
5554 | return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), | |||
5555 | SDLoc(N), N0.getValueType()); | |||
5556 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
5557 | // do not return N1, because undef node may exist in N1 | |||
5558 | return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), | |||
5559 | SDLoc(N), N1.getValueType()); | |||
5560 | ||||
5561 | // fold (and x, -1) -> x, vector edition | |||
5562 | if (ISD::isBuildVectorAllOnes(N0.getNode())) | |||
5563 | return N1; | |||
5564 | if (ISD::isBuildVectorAllOnes(N1.getNode())) | |||
5565 | return N0; | |||
5566 | ||||
5567 | // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load | |||
5568 | auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0); | |||
5569 | auto *BVec = dyn_cast<BuildVectorSDNode>(N1); | |||
5570 | if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD && | |||
5571 | N0.hasOneUse() && N1.hasOneUse()) { | |||
5572 | EVT LoadVT = MLoad->getMemoryVT(); | |||
5573 | EVT ExtVT = VT; | |||
5574 | if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) { | |||
5575 | // For this AND to be a zero extension of the masked load the elements | |||
5576 | // of the BuildVec must mask the bottom bits of the extended element | |||
5577 | // type | |||
5578 | if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) { | |||
5579 | uint64_t ElementSize = | |||
5580 | LoadVT.getVectorElementType().getScalarSizeInBits(); | |||
5581 | if (Splat->getAPIntValue().isMask(ElementSize)) { | |||
5582 | return DAG.getMaskedLoad( | |||
5583 | ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(), | |||
5584 | MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), | |||
5585 | LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(), | |||
5586 | ISD::ZEXTLOAD, MLoad->isExpandingLoad()); | |||
5587 | } | |||
5588 | } | |||
5589 | } | |||
5590 | } | |||
5591 | } | |||
5592 | ||||
5593 | // fold (and c1, c2) -> c1&c2 | |||
5594 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
5595 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1})) | |||
5596 | return C; | |||
5597 | ||||
5598 | // canonicalize constant to RHS | |||
5599 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
5600 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
5601 | return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); | |||
5602 | ||||
5603 | // fold (and x, -1) -> x | |||
5604 | if (isAllOnesConstant(N1)) | |||
5605 | return N0; | |||
5606 | ||||
5607 | // if (and x, c) is known to be zero, return 0 | |||
5608 | unsigned BitWidth = VT.getScalarSizeInBits(); | |||
5609 | if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), | |||
5610 | APInt::getAllOnesValue(BitWidth))) | |||
5611 | return DAG.getConstant(0, SDLoc(N), VT); | |||
5612 | ||||
5613 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
5614 | return NewSel; | |||
5615 | ||||
5616 | // reassociate and | |||
5617 | if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) | |||
5618 | return RAND; | |||
5619 | ||||
5620 | // Try to convert a constant mask AND into a shuffle clear mask. | |||
5621 | if (VT.isVector()) | |||
5622 | if (SDValue Shuffle = XformToShuffleWithZero(N)) | |||
5623 | return Shuffle; | |||
5624 | ||||
5625 | if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) | |||
5626 | return Combined; | |||
5627 | ||||
5628 | // fold (and (or x, C), D) -> D if (C & D) == D | |||
5629 | auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { | |||
5630 | return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); | |||
5631 | }; | |||
5632 | if (N0.getOpcode() == ISD::OR && | |||
5633 | ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) | |||
5634 | return N1; | |||
5635 | // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. | |||
5636 | if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { | |||
5637 | SDValue N0Op0 = N0.getOperand(0); | |||
5638 | APInt Mask = ~N1C->getAPIntValue(); | |||
5639 | Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); | |||
5640 | if (DAG.MaskedValueIsZero(N0Op0, Mask)) { | |||
5641 | SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), | |||
5642 | N0.getValueType(), N0Op0); | |||
5643 | ||||
5644 | // Replace uses of the AND with uses of the Zero extend node. | |||
5645 | CombineTo(N, Zext); | |||
5646 | ||||
5647 | // We actually want to replace all uses of the any_extend with the | |||
5648 | // zero_extend, to avoid duplicating things. This will later cause this | |||
5649 | // AND to be folded. | |||
5650 | CombineTo(N0.getNode(), Zext); | |||
5651 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
5652 | } | |||
5653 | } | |||
5654 | ||||
5655 | // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> | |||
5656 | // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must | |||
5657 | // already be zero by virtue of the width of the base type of the load. | |||
5658 | // | |||
5659 | // the 'X' node here can either be nothing or an extract_vector_elt to catch | |||
5660 | // more cases. | |||
5661 | if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
5662 | N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && | |||
5663 | N0.getOperand(0).getOpcode() == ISD::LOAD && | |||
5664 | N0.getOperand(0).getResNo() == 0) || | |||
5665 | (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { | |||
5666 | LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? | |||
5667 | N0 : N0.getOperand(0) ); | |||
5668 | ||||
5669 | // Get the constant (if applicable) the zero'th operand is being ANDed with. | |||
5670 | // This can be a pure constant or a vector splat, in which case we treat the | |||
5671 | // vector as a scalar and use the splat value. | |||
5672 | APInt Constant = APInt::getNullValue(1); | |||
5673 | if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { | |||
5674 | Constant = C->getAPIntValue(); | |||
5675 | } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { | |||
5676 | APInt SplatValue, SplatUndef; | |||
5677 | unsigned SplatBitSize; | |||
5678 | bool HasAnyUndefs; | |||
5679 | bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, | |||
5680 | SplatBitSize, HasAnyUndefs); | |||
5681 | if (IsSplat) { | |||
5682 | // Undef bits can contribute to a possible optimisation if set, so | |||
5683 | // set them. | |||
5684 | SplatValue |= SplatUndef; | |||
5685 | ||||
5686 | // The splat value may be something like "0x00FFFFFF", which means 0 for | |||
5687 | // the first vector value and FF for the rest, repeating. We need a mask | |||
5688 | // that will apply equally to all members of the vector, so AND all the | |||
5689 | // lanes of the constant together. | |||
5690 | unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits(); | |||
5691 | ||||
5692 | // If the splat value has been compressed to a bitlength lower | |||
5693 | // than the size of the vector lane, we need to re-expand it to | |||
5694 | // the lane size. | |||
5695 | if (EltBitWidth > SplatBitSize) | |||
5696 | for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth); | |||
5697 | SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2) | |||
5698 | SplatValue |= SplatValue.shl(SplatBitSize); | |||
5699 | ||||
5700 | // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a | |||
5701 | // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. | |||
5702 | if ((SplatBitSize % EltBitWidth) == 0) { | |||
5703 | Constant = APInt::getAllOnesValue(EltBitWidth); | |||
5704 | for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i) | |||
5705 | Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth); | |||
5706 | } | |||
5707 | } | |||
5708 | } | |||
5709 | ||||
5710 | // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is | |||
5711 | // actually legal and isn't going to get expanded, else this is a false | |||
5712 | // optimisation. | |||
5713 | bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, | |||
5714 | Load->getValueType(0), | |||
5715 | Load->getMemoryVT()); | |||
5716 | ||||
5717 | // Resize the constant to the same size as the original memory access before | |||
5718 | // extension. If it is still the AllOnesValue then this AND is completely | |||
5719 | // unneeded. | |||
5720 | Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); | |||
5721 | ||||
5722 | bool B; | |||
5723 | switch (Load->getExtensionType()) { | |||
5724 | default: B = false; break; | |||
5725 | case ISD::EXTLOAD: B = CanZextLoadProfitably; break; | |||
5726 | case ISD::ZEXTLOAD: | |||
5727 | case ISD::NON_EXTLOAD: B = true; break; | |||
5728 | } | |||
5729 | ||||
5730 | if (B && Constant.isAllOnesValue()) { | |||
5731 | // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to | |||
5732 | // preserve semantics once we get rid of the AND. | |||
5733 | SDValue NewLoad(Load, 0); | |||
5734 | ||||
5735 | // Fold the AND away. NewLoad may get replaced immediately. | |||
5736 | CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); | |||
5737 | ||||
5738 | if (Load->getExtensionType() == ISD::EXTLOAD) { | |||
5739 | NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, | |||
5740 | Load->getValueType(0), SDLoc(Load), | |||
5741 | Load->getChain(), Load->getBasePtr(), | |||
5742 | Load->getOffset(), Load->getMemoryVT(), | |||
5743 | Load->getMemOperand()); | |||
5744 | // Replace uses of the EXTLOAD with the new ZEXTLOAD. | |||
5745 | if (Load->getNumValues() == 3) { | |||
5746 | // PRE/POST_INC loads have 3 values. | |||
5747 | SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), | |||
5748 | NewLoad.getValue(2) }; | |||
5749 | CombineTo(Load, To, 3, true); | |||
5750 | } else { | |||
5751 | CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); | |||
5752 | } | |||
5753 | } | |||
5754 | ||||
5755 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
5756 | } | |||
5757 | } | |||
5758 | ||||
5759 | // fold (and (masked_gather x)) -> (zext_masked_gather x) | |||
5760 | if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { | |||
5761 | EVT MemVT = GN0->getMemoryVT(); | |||
5762 | EVT ScalarVT = MemVT.getScalarType(); | |||
5763 | ||||
5764 | if (SDValue(GN0, 0).hasOneUse() && | |||
5765 | isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) && | |||
5766 | TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { | |||
5767 | SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), | |||
5768 | GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; | |||
5769 | ||||
5770 | SDValue ZExtLoad = DAG.getMaskedGather( | |||
5771 | DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops, | |||
5772 | GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD); | |||
5773 | ||||
5774 | CombineTo(N, ZExtLoad); | |||
5775 | AddToWorklist(ZExtLoad.getNode()); | |||
5776 | // Avoid recheck of N. | |||
5777 | return SDValue(N, 0); | |||
5778 | } | |||
5779 | } | |||
5780 | ||||
5781 | // fold (and (load x), 255) -> (zextload x, i8) | |||
5782 | // fold (and (extload x, i16), 255) -> (zextload x, i8) | |||
5783 | // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) | |||
5784 | if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || | |||
5785 | (N0.getOpcode() == ISD::ANY_EXTEND && | |||
5786 | N0.getOperand(0).getOpcode() == ISD::LOAD))) { | |||
5787 | if (SDValue Res = ReduceLoadWidth(N)) { | |||
5788 | LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND | |||
5789 | ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); | |||
5790 | AddToWorklist(N); | |||
5791 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res); | |||
5792 | return SDValue(N, 0); | |||
5793 | } | |||
5794 | } | |||
5795 | ||||
5796 | if (LegalTypes) { | |||
5797 | // Attempt to propagate the AND back up to the leaves which, if they're | |||
5798 | // loads, can be combined to narrow loads and the AND node can be removed. | |||
5799 | // Perform after legalization so that extend nodes will already be | |||
5800 | // combined into the loads. | |||
5801 | if (BackwardsPropagateMask(N)) | |||
5802 | return SDValue(N, 0); | |||
5803 | } | |||
5804 | ||||
5805 | if (SDValue Combined = visitANDLike(N0, N1, N)) | |||
5806 | return Combined; | |||
5807 | ||||
5808 | // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) | |||
5809 | if (N0.getOpcode() == N1.getOpcode()) | |||
5810 | if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) | |||
5811 | return V; | |||
5812 | ||||
5813 | // Masking the negated extension of a boolean is just the zero-extended | |||
5814 | // boolean: | |||
5815 | // and (sub 0, zext(bool X)), 1 --> zext(bool X) | |||
5816 | // and (sub 0, sext(bool X)), 1 --> zext(bool X) | |||
5817 | // | |||
5818 | // Note: the SimplifyDemandedBits fold below can make an information-losing | |||
5819 | // transform, and then we have no way to find this better fold. | |||
5820 | if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { | |||
5821 | if (isNullOrNullSplat(N0.getOperand(0))) { | |||
5822 | SDValue SubRHS = N0.getOperand(1); | |||
5823 | if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && | |||
5824 | SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) | |||
5825 | return SubRHS; | |||
5826 | if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && | |||
5827 | SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) | |||
5828 | return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); | |||
5829 | } | |||
5830 | } | |||
5831 | ||||
5832 | // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) | |||
5833 | // fold (and (sra)) -> (and (srl)) when possible. | |||
5834 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
5835 | return SDValue(N, 0); | |||
5836 | ||||
5837 | // fold (zext_inreg (extload x)) -> (zextload x) | |||
5838 | // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use | |||
5839 | if (ISD::isUNINDEXEDLoad(N0.getNode()) && | |||
5840 | (ISD::isEXTLoad(N0.getNode()) || | |||
5841 | (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) { | |||
5842 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
5843 | EVT MemVT = LN0->getMemoryVT(); | |||
5844 | // If we zero all the possible extended bits, then we can turn this into | |||
5845 | // a zextload if we are running before legalize or the operation is legal. | |||
5846 | unsigned ExtBitSize = N1.getScalarValueSizeInBits(); | |||
5847 | unsigned MemBitSize = MemVT.getScalarSizeInBits(); | |||
5848 | APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize); | |||
5849 | if (DAG.MaskedValueIsZero(N1, ExtBits) && | |||
5850 | ((!LegalOperations && LN0->isSimple()) || | |||
5851 | TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { | |||
5852 | SDValue ExtLoad = | |||
5853 | DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(), | |||
5854 | LN0->getBasePtr(), MemVT, LN0->getMemOperand()); | |||
5855 | AddToWorklist(N); | |||
5856 | CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); | |||
5857 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
5858 | } | |||
5859 | } | |||
5860 | ||||
5861 | // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) | |||
5862 | if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { | |||
5863 | if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), | |||
5864 | N0.getOperand(1), false)) | |||
5865 | return BSwap; | |||
5866 | } | |||
5867 | ||||
5868 | if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) | |||
5869 | return Shifts; | |||
5870 | ||||
5871 | if (TLI.hasBitTest(N0, N1)) | |||
5872 | if (SDValue V = combineShiftAnd1ToBitTest(N, DAG)) | |||
5873 | return V; | |||
5874 | ||||
5875 | // Recognize the following pattern: | |||
5876 | // | |||
5877 | // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask) | |||
5878 | // | |||
5879 | // where bitmask is a mask that clears the upper bits of AndVT. The | |||
5880 | // number of bits in bitmask must be a power of two. | |||
5881 | auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) { | |||
5882 | if (LHS->getOpcode() != ISD::SIGN_EXTEND) | |||
5883 | return false; | |||
5884 | ||||
5885 | auto *C = dyn_cast<ConstantSDNode>(RHS); | |||
5886 | if (!C) | |||
5887 | return false; | |||
5888 | ||||
5889 | if (!C->getAPIntValue().isMask( | |||
5890 | LHS.getOperand(0).getValueType().getFixedSizeInBits())) | |||
5891 | return false; | |||
5892 | ||||
5893 | return true; | |||
5894 | }; | |||
5895 | ||||
5896 | // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...). | |||
5897 | if (IsAndZeroExtMask(N0, N1)) | |||
5898 | return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0)); | |||
5899 | ||||
5900 | return SDValue(); | |||
5901 | } | |||
5902 | ||||
5903 | /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. | |||
5904 | SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, | |||
5905 | bool DemandHighBits) { | |||
5906 | if (!LegalOperations) | |||
5907 | return SDValue(); | |||
5908 | ||||
5909 | EVT VT = N->getValueType(0); | |||
5910 | if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) | |||
5911 | return SDValue(); | |||
5912 | if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) | |||
5913 | return SDValue(); | |||
5914 | ||||
5915 | // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) | |||
5916 | bool LookPassAnd0 = false; | |||
5917 | bool LookPassAnd1 = false; | |||
5918 | if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) | |||
5919 | std::swap(N0, N1); | |||
5920 | if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) | |||
5921 | std::swap(N0, N1); | |||
5922 | if (N0.getOpcode() == ISD::AND) { | |||
5923 | if (!N0.getNode()->hasOneUse()) | |||
5924 | return SDValue(); | |||
5925 | ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
5926 | // Also handle 0xffff since the LHS is guaranteed to have zeros there. | |||
5927 | // This is needed for X86. | |||
5928 | if (!N01C || (N01C->getZExtValue() != 0xFF00 && | |||
5929 | N01C->getZExtValue() != 0xFFFF)) | |||
5930 | return SDValue(); | |||
5931 | N0 = N0.getOperand(0); | |||
5932 | LookPassAnd0 = true; | |||
5933 | } | |||
5934 | ||||
5935 | if (N1.getOpcode() == ISD::AND) { | |||
5936 | if (!N1.getNode()->hasOneUse()) | |||
5937 | return SDValue(); | |||
5938 | ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); | |||
5939 | if (!N11C || N11C->getZExtValue() != 0xFF) | |||
5940 | return SDValue(); | |||
5941 | N1 = N1.getOperand(0); | |||
5942 | LookPassAnd1 = true; | |||
5943 | } | |||
5944 | ||||
5945 | if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) | |||
5946 | std::swap(N0, N1); | |||
5947 | if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) | |||
5948 | return SDValue(); | |||
5949 | if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) | |||
5950 | return SDValue(); | |||
5951 | ||||
5952 | ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
5953 | ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); | |||
5954 | if (!N01C || !N11C) | |||
5955 | return SDValue(); | |||
5956 | if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) | |||
5957 | return SDValue(); | |||
5958 | ||||
5959 | // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) | |||
5960 | SDValue N00 = N0->getOperand(0); | |||
5961 | if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { | |||
5962 | if (!N00.getNode()->hasOneUse()) | |||
5963 | return SDValue(); | |||
5964 | ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); | |||
5965 | if (!N001C || N001C->getZExtValue() != 0xFF) | |||
5966 | return SDValue(); | |||
5967 | N00 = N00.getOperand(0); | |||
5968 | LookPassAnd0 = true; | |||
5969 | } | |||
5970 | ||||
5971 | SDValue N10 = N1->getOperand(0); | |||
5972 | if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { | |||
5973 | if (!N10.getNode()->hasOneUse()) | |||
5974 | return SDValue(); | |||
5975 | ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); | |||
5976 | // Also allow 0xFFFF since the bits will be shifted out. This is needed | |||
5977 | // for X86. | |||
5978 | if (!N101C || (N101C->getZExtValue() != 0xFF00 && | |||
5979 | N101C->getZExtValue() != 0xFFFF)) | |||
5980 | return SDValue(); | |||
5981 | N10 = N10.getOperand(0); | |||
5982 | LookPassAnd1 = true; | |||
5983 | } | |||
5984 | ||||
5985 | if (N00 != N10) | |||
5986 | return SDValue(); | |||
5987 | ||||
5988 | // Make sure everything beyond the low halfword gets set to zero since the SRL | |||
5989 | // 16 will clear the top bits. | |||
5990 | unsigned OpSizeInBits = VT.getSizeInBits(); | |||
5991 | if (DemandHighBits && OpSizeInBits > 16) { | |||
5992 | // If the left-shift isn't masked out then the only way this is a bswap is | |||
5993 | // if all bits beyond the low 8 are 0. In that case the entire pattern | |||
5994 | // reduces to a left shift anyway: leave it for other parts of the combiner. | |||
5995 | if (!LookPassAnd0) | |||
5996 | return SDValue(); | |||
5997 | ||||
5998 | // However, if the right shift isn't masked out then it might be because | |||
5999 | // it's not needed. See if we can spot that too. | |||
6000 | if (!LookPassAnd1 && | |||
6001 | !DAG.MaskedValueIsZero( | |||
6002 | N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) | |||
6003 | return SDValue(); | |||
6004 | } | |||
6005 | ||||
6006 | SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); | |||
6007 | if (OpSizeInBits > 16) { | |||
6008 | SDLoc DL(N); | |||
6009 | Res = DAG.getNode(ISD::SRL, DL, VT, Res, | |||
6010 | DAG.getConstant(OpSizeInBits - 16, DL, | |||
6011 | getShiftAmountTy(VT))); | |||
6012 | } | |||
6013 | return Res; | |||
6014 | } | |||
6015 | ||||
6016 | /// Return true if the specified node is an element that makes up a 32-bit | |||
6017 | /// packed halfword byteswap. | |||
6018 | /// ((x & 0x000000ff) << 8) | | |||
6019 | /// ((x & 0x0000ff00) >> 8) | | |||
6020 | /// ((x & 0x00ff0000) << 8) | | |||
6021 | /// ((x & 0xff000000) >> 8) | |||
6022 | static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { | |||
6023 | if (!N.getNode()->hasOneUse()) | |||
6024 | return false; | |||
6025 | ||||
6026 | unsigned Opc = N.getOpcode(); | |||
6027 | if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) | |||
6028 | return false; | |||
6029 | ||||
6030 | SDValue N0 = N.getOperand(0); | |||
6031 | unsigned Opc0 = N0.getOpcode(); | |||
6032 | if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) | |||
6033 | return false; | |||
6034 | ||||
6035 | ConstantSDNode *N1C = nullptr; | |||
6036 | // SHL or SRL: look upstream for AND mask operand | |||
6037 | if (Opc == ISD::AND) | |||
6038 | N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); | |||
6039 | else if (Opc0 == ISD::AND) | |||
6040 | N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
6041 | if (!N1C) | |||
6042 | return false; | |||
6043 | ||||
6044 | unsigned MaskByteOffset; | |||
6045 | switch (N1C->getZExtValue()) { | |||
6046 | default: | |||
6047 | return false; | |||
6048 | case 0xFF: MaskByteOffset = 0; break; | |||
6049 | case 0xFF00: MaskByteOffset = 1; break; | |||
6050 | case 0xFFFF: | |||
6051 | // In case demanded bits didn't clear the bits that will be shifted out. | |||
6052 | // This is needed for X86. | |||
6053 | if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { | |||
6054 | MaskByteOffset = 1; | |||
6055 | break; | |||
6056 | } | |||
6057 | return false; | |||
6058 | case 0xFF0000: MaskByteOffset = 2; break; | |||
6059 | case 0xFF000000: MaskByteOffset = 3; break; | |||
6060 | } | |||
6061 | ||||
6062 | // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). | |||
6063 | if (Opc == ISD::AND) { | |||
6064 | if (MaskByteOffset == 0 || MaskByteOffset == 2) { | |||
6065 | // (x >> 8) & 0xff | |||
6066 | // (x >> 8) & 0xff0000 | |||
6067 | if (Opc0 != ISD::SRL) | |||
6068 | return false; | |||
6069 | ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
6070 | if (!C || C->getZExtValue() != 8) | |||
6071 | return false; | |||
6072 | } else { | |||
6073 | // (x << 8) & 0xff00 | |||
6074 | // (x << 8) & 0xff000000 | |||
6075 | if (Opc0 != ISD::SHL) | |||
6076 | return false; | |||
6077 | ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
6078 | if (!C || C->getZExtValue() != 8) | |||
6079 | return false; | |||
6080 | } | |||
6081 | } else if (Opc == ISD::SHL) { | |||
6082 | // (x & 0xff) << 8 | |||
6083 | // (x & 0xff0000) << 8 | |||
6084 | if (MaskByteOffset != 0 && MaskByteOffset != 2) | |||
6085 | return false; | |||
6086 | ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); | |||
6087 | if (!C || C->getZExtValue() != 8) | |||
6088 | return false; | |||
6089 | } else { // Opc == ISD::SRL | |||
6090 | // (x & 0xff00) >> 8 | |||
6091 | // (x & 0xff000000) >> 8 | |||
6092 | if (MaskByteOffset != 1 && MaskByteOffset != 3) | |||
6093 | return false; | |||
6094 | ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); | |||
6095 | if (!C || C->getZExtValue() != 8) | |||
6096 | return false; | |||
6097 | } | |||
6098 | ||||
6099 | if (Parts[MaskByteOffset]) | |||
6100 | return false; | |||
6101 | ||||
6102 | Parts[MaskByteOffset] = N0.getOperand(0).getNode(); | |||
6103 | return true; | |||
6104 | } | |||
6105 | ||||
6106 | // Match 2 elements of a packed halfword bswap. | |||
6107 | static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) { | |||
6108 | if (N.getOpcode() == ISD::OR) | |||
6109 | return isBSwapHWordElement(N.getOperand(0), Parts) && | |||
6110 | isBSwapHWordElement(N.getOperand(1), Parts); | |||
6111 | ||||
6112 | if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) { | |||
6113 | ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1)); | |||
6114 | if (!C || C->getAPIntValue() != 16) | |||
6115 | return false; | |||
6116 | Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode(); | |||
6117 | return true; | |||
6118 | } | |||
6119 | ||||
6120 | return false; | |||
6121 | } | |||
6122 | ||||
6123 | // Match this pattern: | |||
6124 | // (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff)) | |||
6125 | // And rewrite this to: | |||
6126 | // (rotr (bswap A), 16) | |||
6127 | static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI, | |||
6128 | SelectionDAG &DAG, SDNode *N, SDValue N0, | |||
6129 | SDValue N1, EVT VT, EVT ShiftAmountTy) { | |||
6130 | assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&((N->getOpcode() == ISD::OR && VT == MVT::i32 && "MatchBSwapHWordOrAndAnd: expecting i32") ? static_cast<void > (0) : __assert_fail ("N->getOpcode() == ISD::OR && VT == MVT::i32 && \"MatchBSwapHWordOrAndAnd: expecting i32\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6131, __PRETTY_FUNCTION__)) | |||
6131 | "MatchBSwapHWordOrAndAnd: expecting i32")((N->getOpcode() == ISD::OR && VT == MVT::i32 && "MatchBSwapHWordOrAndAnd: expecting i32") ? static_cast<void > (0) : __assert_fail ("N->getOpcode() == ISD::OR && VT == MVT::i32 && \"MatchBSwapHWordOrAndAnd: expecting i32\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6131, __PRETTY_FUNCTION__)); | |||
6132 | if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) | |||
6133 | return SDValue(); | |||
6134 | if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND) | |||
6135 | return SDValue(); | |||
6136 | // TODO: this is too restrictive; lifting this restriction requires more tests | |||
6137 | if (!N0->hasOneUse() || !N1->hasOneUse()) | |||
6138 | return SDValue(); | |||
6139 | ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1)); | |||
6140 | ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1)); | |||
6141 | if (!Mask0 || !Mask1) | |||
6142 | return SDValue(); | |||
6143 | if (Mask0->getAPIntValue() != 0xff00ff00 || | |||
6144 | Mask1->getAPIntValue() != 0x00ff00ff) | |||
6145 | return SDValue(); | |||
6146 | SDValue Shift0 = N0.getOperand(0); | |||
6147 | SDValue Shift1 = N1.getOperand(0); | |||
6148 | if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL) | |||
6149 | return SDValue(); | |||
6150 | ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1)); | |||
6151 | ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1)); | |||
6152 | if (!ShiftAmt0 || !ShiftAmt1) | |||
6153 | return SDValue(); | |||
6154 | if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8) | |||
6155 | return SDValue(); | |||
6156 | if (Shift0.getOperand(0) != Shift1.getOperand(0)) | |||
6157 | return SDValue(); | |||
6158 | ||||
6159 | SDLoc DL(N); | |||
6160 | SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0)); | |||
6161 | SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy); | |||
6162 | return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); | |||
6163 | } | |||
6164 | ||||
6165 | /// Match a 32-bit packed halfword bswap. That is | |||
6166 | /// ((x & 0x000000ff) << 8) | | |||
6167 | /// ((x & 0x0000ff00) >> 8) | | |||
6168 | /// ((x & 0x00ff0000) << 8) | | |||
6169 | /// ((x & 0xff000000) >> 8) | |||
6170 | /// => (rotl (bswap x), 16) | |||
6171 | SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { | |||
6172 | if (!LegalOperations) | |||
6173 | return SDValue(); | |||
6174 | ||||
6175 | EVT VT = N->getValueType(0); | |||
6176 | if (VT != MVT::i32) | |||
6177 | return SDValue(); | |||
6178 | if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) | |||
6179 | return SDValue(); | |||
6180 | ||||
6181 | if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT, | |||
6182 | getShiftAmountTy(VT))) | |||
6183 | return BSwap; | |||
6184 | ||||
6185 | // Try again with commuted operands. | |||
6186 | if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT, | |||
6187 | getShiftAmountTy(VT))) | |||
6188 | return BSwap; | |||
6189 | ||||
6190 | ||||
6191 | // Look for either | |||
6192 | // (or (bswaphpair), (bswaphpair)) | |||
6193 | // (or (or (bswaphpair), (and)), (and)) | |||
6194 | // (or (or (and), (bswaphpair)), (and)) | |||
6195 | SDNode *Parts[4] = {}; | |||
6196 | ||||
6197 | if (isBSwapHWordPair(N0, Parts)) { | |||
6198 | // (or (or (and), (and)), (or (and), (and))) | |||
6199 | if (!isBSwapHWordPair(N1, Parts)) | |||
6200 | return SDValue(); | |||
6201 | } else if (N0.getOpcode() == ISD::OR) { | |||
6202 | // (or (or (or (and), (and)), (and)), (and)) | |||
6203 | if (!isBSwapHWordElement(N1, Parts)) | |||
6204 | return SDValue(); | |||
6205 | SDValue N00 = N0.getOperand(0); | |||
6206 | SDValue N01 = N0.getOperand(1); | |||
6207 | if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) && | |||
6208 | !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts))) | |||
6209 | return SDValue(); | |||
6210 | } else | |||
6211 | return SDValue(); | |||
6212 | ||||
6213 | // Make sure the parts are all coming from the same node. | |||
6214 | if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) | |||
6215 | return SDValue(); | |||
6216 | ||||
6217 | SDLoc DL(N); | |||
6218 | SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, | |||
6219 | SDValue(Parts[0], 0)); | |||
6220 | ||||
6221 | // Result of the bswap should be rotated by 16. If it's not legal, then | |||
6222 | // do (x << 16) | (x >> 16). | |||
6223 | SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); | |||
6224 | if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) | |||
6225 | return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); | |||
6226 | if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) | |||
6227 | return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); | |||
6228 | return DAG.getNode(ISD::OR, DL, VT, | |||
6229 | DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), | |||
6230 | DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); | |||
6231 | } | |||
6232 | ||||
6233 | /// This contains all DAGCombine rules which reduce two values combined by | |||
6234 | /// an Or operation to a single value \see visitANDLike(). | |||
6235 | SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { | |||
6236 | EVT VT = N1.getValueType(); | |||
6237 | SDLoc DL(N); | |||
6238 | ||||
6239 | // fold (or x, undef) -> -1 | |||
6240 | if (!LegalOperations && (N0.isUndef() || N1.isUndef())) | |||
6241 | return DAG.getAllOnesConstant(DL, VT); | |||
6242 | ||||
6243 | if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) | |||
6244 | return V; | |||
6245 | ||||
6246 | // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. | |||
6247 | if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && | |||
6248 | // Don't increase # computations. | |||
6249 | (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { | |||
6250 | // We can only do this xform if we know that bits from X that are set in C2 | |||
6251 | // but not in C1 are already zero. Likewise for Y. | |||
6252 | if (const ConstantSDNode *N0O1C = | |||
6253 | getAsNonOpaqueConstant(N0.getOperand(1))) { | |||
6254 | if (const ConstantSDNode *N1O1C = | |||
6255 | getAsNonOpaqueConstant(N1.getOperand(1))) { | |||
6256 | // We can only do this xform if we know that bits from X that are set in | |||
6257 | // C2 but not in C1 are already zero. Likewise for Y. | |||
6258 | const APInt &LHSMask = N0O1C->getAPIntValue(); | |||
6259 | const APInt &RHSMask = N1O1C->getAPIntValue(); | |||
6260 | ||||
6261 | if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && | |||
6262 | DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { | |||
6263 | SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, | |||
6264 | N0.getOperand(0), N1.getOperand(0)); | |||
6265 | return DAG.getNode(ISD::AND, DL, VT, X, | |||
6266 | DAG.getConstant(LHSMask | RHSMask, DL, VT)); | |||
6267 | } | |||
6268 | } | |||
6269 | } | |||
6270 | } | |||
6271 | ||||
6272 | // (or (and X, M), (and X, N)) -> (and X, (or M, N)) | |||
6273 | if (N0.getOpcode() == ISD::AND && | |||
6274 | N1.getOpcode() == ISD::AND && | |||
6275 | N0.getOperand(0) == N1.getOperand(0) && | |||
6276 | // Don't increase # computations. | |||
6277 | (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { | |||
6278 | SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, | |||
6279 | N0.getOperand(1), N1.getOperand(1)); | |||
6280 | return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); | |||
6281 | } | |||
6282 | ||||
6283 | return SDValue(); | |||
6284 | } | |||
6285 | ||||
6286 | /// OR combines for which the commuted variant will be tried as well. | |||
6287 | static SDValue visitORCommutative( | |||
6288 | SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) { | |||
6289 | EVT VT = N0.getValueType(); | |||
6290 | if (N0.getOpcode() == ISD::AND) { | |||
6291 | // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y) | |||
6292 | if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1) | |||
6293 | return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1); | |||
6294 | ||||
6295 | // fold (or (and (xor Y, -1), X), Y) -> (or X, Y) | |||
6296 | if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1) | |||
6297 | return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1); | |||
6298 | } | |||
6299 | ||||
6300 | return SDValue(); | |||
6301 | } | |||
6302 | ||||
6303 | SDValue DAGCombiner::visitOR(SDNode *N) { | |||
6304 | SDValue N0 = N->getOperand(0); | |||
6305 | SDValue N1 = N->getOperand(1); | |||
6306 | EVT VT = N1.getValueType(); | |||
6307 | ||||
6308 | // x | x --> x | |||
6309 | if (N0 == N1) | |||
6310 | return N0; | |||
6311 | ||||
6312 | // fold vector ops | |||
6313 | if (VT.isVector()) { | |||
6314 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
6315 | return FoldedVOp; | |||
6316 | ||||
6317 | // fold (or x, 0) -> x, vector edition | |||
6318 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
6319 | return N1; | |||
6320 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
6321 | return N0; | |||
6322 | ||||
6323 | // fold (or x, -1) -> -1, vector edition | |||
6324 | if (ISD::isBuildVectorAllOnes(N0.getNode())) | |||
6325 | // do not return N0, because undef node may exist in N0 | |||
6326 | return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); | |||
6327 | if (ISD::isBuildVectorAllOnes(N1.getNode())) | |||
6328 | // do not return N1, because undef node may exist in N1 | |||
6329 | return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); | |||
6330 | ||||
6331 | // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) | |||
6332 | // Do this only if the resulting shuffle is legal. | |||
6333 | if (isa<ShuffleVectorSDNode>(N0) && | |||
6334 | isa<ShuffleVectorSDNode>(N1) && | |||
6335 | // Avoid folding a node with illegal type. | |||
6336 | TLI.isTypeLegal(VT)) { | |||
6337 | bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); | |||
6338 | bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); | |||
6339 | bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); | |||
6340 | bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); | |||
6341 | // Ensure both shuffles have a zero input. | |||
6342 | if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { | |||
6343 | assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!")(((!ZeroN00 || !ZeroN01) && "Both inputs zero!") ? static_cast <void> (0) : __assert_fail ("(!ZeroN00 || !ZeroN01) && \"Both inputs zero!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6343, __PRETTY_FUNCTION__)); | |||
6344 | assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!")(((!ZeroN10 || !ZeroN11) && "Both inputs zero!") ? static_cast <void> (0) : __assert_fail ("(!ZeroN10 || !ZeroN11) && \"Both inputs zero!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6344, __PRETTY_FUNCTION__)); | |||
6345 | const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); | |||
6346 | const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); | |||
6347 | bool CanFold = true; | |||
6348 | int NumElts = VT.getVectorNumElements(); | |||
6349 | SmallVector<int, 4> Mask(NumElts); | |||
6350 | ||||
6351 | for (int i = 0; i != NumElts; ++i) { | |||
6352 | int M0 = SV0->getMaskElt(i); | |||
6353 | int M1 = SV1->getMaskElt(i); | |||
6354 | ||||
6355 | // Determine if either index is pointing to a zero vector. | |||
6356 | bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); | |||
6357 | bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); | |||
6358 | ||||
6359 | // If one element is zero and the otherside is undef, keep undef. | |||
6360 | // This also handles the case that both are undef. | |||
6361 | if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { | |||
6362 | Mask[i] = -1; | |||
6363 | continue; | |||
6364 | } | |||
6365 | ||||
6366 | // Make sure only one of the elements is zero. | |||
6367 | if (M0Zero == M1Zero) { | |||
6368 | CanFold = false; | |||
6369 | break; | |||
6370 | } | |||
6371 | ||||
6372 | assert((M0 >= 0 || M1 >= 0) && "Undef index!")(((M0 >= 0 || M1 >= 0) && "Undef index!") ? static_cast <void> (0) : __assert_fail ("(M0 >= 0 || M1 >= 0) && \"Undef index!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6372, __PRETTY_FUNCTION__)); | |||
6373 | ||||
6374 | // We have a zero and non-zero element. If the non-zero came from | |||
6375 | // SV0 make the index a LHS index. If it came from SV1, make it | |||
6376 | // a RHS index. We need to mod by NumElts because we don't care | |||
6377 | // which operand it came from in the original shuffles. | |||
6378 | Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; | |||
6379 | } | |||
6380 | ||||
6381 | if (CanFold) { | |||
6382 | SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); | |||
6383 | SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); | |||
6384 | ||||
6385 | SDValue LegalShuffle = | |||
6386 | TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, | |||
6387 | Mask, DAG); | |||
6388 | if (LegalShuffle) | |||
6389 | return LegalShuffle; | |||
6390 | } | |||
6391 | } | |||
6392 | } | |||
6393 | } | |||
6394 | ||||
6395 | // fold (or c1, c2) -> c1|c2 | |||
6396 | ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); | |||
6397 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1})) | |||
6398 | return C; | |||
6399 | ||||
6400 | // canonicalize constant to RHS | |||
6401 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
6402 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
6403 | return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); | |||
6404 | ||||
6405 | // fold (or x, 0) -> x | |||
6406 | if (isNullConstant(N1)) | |||
6407 | return N0; | |||
6408 | ||||
6409 | // fold (or x, -1) -> -1 | |||
6410 | if (isAllOnesConstant(N1)) | |||
6411 | return N1; | |||
6412 | ||||
6413 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
6414 | return NewSel; | |||
6415 | ||||
6416 | // fold (or x, c) -> c iff (x & ~c) == 0 | |||
6417 | if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) | |||
6418 | return N1; | |||
6419 | ||||
6420 | if (SDValue Combined = visitORLike(N0, N1, N)) | |||
6421 | return Combined; | |||
6422 | ||||
6423 | if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) | |||
6424 | return Combined; | |||
6425 | ||||
6426 | // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) | |||
6427 | if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) | |||
6428 | return BSwap; | |||
6429 | if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) | |||
6430 | return BSwap; | |||
6431 | ||||
6432 | // reassociate or | |||
6433 | if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) | |||
6434 | return ROR; | |||
6435 | ||||
6436 | // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) | |||
6437 | // iff (c1 & c2) != 0 or c1/c2 are undef. | |||
6438 | auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) { | |||
6439 | return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue()); | |||
6440 | }; | |||
6441 | if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && | |||
6442 | ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) { | |||
6443 | if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, | |||
6444 | {N1, N0.getOperand(1)})) { | |||
6445 | SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); | |||
6446 | AddToWorklist(IOR.getNode()); | |||
6447 | return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); | |||
6448 | } | |||
6449 | } | |||
6450 | ||||
6451 | if (SDValue Combined = visitORCommutative(DAG, N0, N1, N)) | |||
6452 | return Combined; | |||
6453 | if (SDValue Combined = visitORCommutative(DAG, N1, N0, N)) | |||
6454 | return Combined; | |||
6455 | ||||
6456 | // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) | |||
6457 | if (N0.getOpcode() == N1.getOpcode()) | |||
6458 | if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) | |||
6459 | return V; | |||
6460 | ||||
6461 | // See if this is some rotate idiom. | |||
6462 | if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N))) | |||
6463 | return Rot; | |||
6464 | ||||
6465 | if (SDValue Load = MatchLoadCombine(N)) | |||
6466 | return Load; | |||
6467 | ||||
6468 | // Simplify the operands using demanded-bits information. | |||
6469 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
6470 | return SDValue(N, 0); | |||
6471 | ||||
6472 | // If OR can be rewritten into ADD, try combines based on ADD. | |||
6473 | if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) && | |||
6474 | DAG.haveNoCommonBitsSet(N0, N1)) | |||
6475 | if (SDValue Combined = visitADDLike(N)) | |||
6476 | return Combined; | |||
6477 | ||||
6478 | return SDValue(); | |||
6479 | } | |||
6480 | ||||
6481 | static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { | |||
6482 | if (Op.getOpcode() == ISD::AND && | |||
6483 | DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { | |||
6484 | Mask = Op.getOperand(1); | |||
6485 | return Op.getOperand(0); | |||
6486 | } | |||
6487 | return Op; | |||
6488 | } | |||
6489 | ||||
6490 | /// Match "(X shl/srl V1) & V2" where V2 may not be present. | |||
6491 | static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, | |||
6492 | SDValue &Mask) { | |||
6493 | Op = stripConstantMask(DAG, Op, Mask); | |||
6494 | if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { | |||
6495 | Shift = Op; | |||
6496 | return true; | |||
6497 | } | |||
6498 | return false; | |||
6499 | } | |||
6500 | ||||
6501 | /// Helper function for visitOR to extract the needed side of a rotate idiom | |||
6502 | /// from a shl/srl/mul/udiv. This is meant to handle cases where | |||
6503 | /// InstCombine merged some outside op with one of the shifts from | |||
6504 | /// the rotate pattern. | |||
6505 | /// \returns An empty \c SDValue if the needed shift couldn't be extracted. | |||
6506 | /// Otherwise, returns an expansion of \p ExtractFrom based on the following | |||
6507 | /// patterns: | |||
6508 | /// | |||
6509 | /// (or (add v v) (shrl v bitwidth-1)): | |||
6510 | /// expands (add v v) -> (shl v 1) | |||
6511 | /// | |||
6512 | /// (or (mul v c0) (shrl (mul v c1) c2)): | |||
6513 | /// expands (mul v c0) -> (shl (mul v c1) c3) | |||
6514 | /// | |||
6515 | /// (or (udiv v c0) (shl (udiv v c1) c2)): | |||
6516 | /// expands (udiv v c0) -> (shrl (udiv v c1) c3) | |||
6517 | /// | |||
6518 | /// (or (shl v c0) (shrl (shl v c1) c2)): | |||
6519 | /// expands (shl v c0) -> (shl (shl v c1) c3) | |||
6520 | /// | |||
6521 | /// (or (shrl v c0) (shl (shrl v c1) c2)): | |||
6522 | /// expands (shrl v c0) -> (shrl (shrl v c1) c3) | |||
6523 | /// | |||
6524 | /// Such that in all cases, c3+c2==bitwidth(op v c1). | |||
6525 | static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, | |||
6526 | SDValue ExtractFrom, SDValue &Mask, | |||
6527 | const SDLoc &DL) { | |||
6528 | assert(OppShift && ExtractFrom && "Empty SDValue")((OppShift && ExtractFrom && "Empty SDValue") ? static_cast<void> (0) : __assert_fail ("OppShift && ExtractFrom && \"Empty SDValue\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6528, __PRETTY_FUNCTION__)); | |||
6529 | assert((((OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && "Existing shift must be valid as a rotate half" ) ? static_cast<void> (0) : __assert_fail ("(OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && \"Existing shift must be valid as a rotate half\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6531, __PRETTY_FUNCTION__)) | |||
6530 | (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) &&(((OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && "Existing shift must be valid as a rotate half" ) ? static_cast<void> (0) : __assert_fail ("(OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && \"Existing shift must be valid as a rotate half\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6531, __PRETTY_FUNCTION__)) | |||
6531 | "Existing shift must be valid as a rotate half")(((OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && "Existing shift must be valid as a rotate half" ) ? static_cast<void> (0) : __assert_fail ("(OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && \"Existing shift must be valid as a rotate half\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6531, __PRETTY_FUNCTION__)); | |||
6532 | ||||
6533 | ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); | |||
6534 | ||||
6535 | // Value and Type of the shift. | |||
6536 | SDValue OppShiftLHS = OppShift.getOperand(0); | |||
6537 | EVT ShiftedVT = OppShiftLHS.getValueType(); | |||
6538 | ||||
6539 | // Amount of the existing shift. | |||
6540 | ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); | |||
6541 | ||||
6542 | // (add v v) -> (shl v 1) | |||
6543 | // TODO: Should this be a general DAG canonicalization? | |||
6544 | if (OppShift.getOpcode() == ISD::SRL && OppShiftCst && | |||
6545 | ExtractFrom.getOpcode() == ISD::ADD && | |||
6546 | ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) && | |||
6547 | ExtractFrom.getOperand(0) == OppShiftLHS && | |||
6548 | OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1) | |||
6549 | return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS, | |||
6550 | DAG.getShiftAmountConstant(1, ShiftedVT, DL)); | |||
6551 | ||||
6552 | // Preconditions: | |||
6553 | // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) | |||
6554 | // | |||
6555 | // Find opcode of the needed shift to be extracted from (op0 v c0). | |||
6556 | unsigned Opcode = ISD::DELETED_NODE; | |||
6557 | bool IsMulOrDiv = false; | |||
6558 | // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift | |||
6559 | // opcode or its arithmetic (mul or udiv) variant. | |||
6560 | auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { | |||
6561 | IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; | |||
6562 | if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) | |||
6563 | return false; | |||
6564 | Opcode = NeededShift; | |||
6565 | return true; | |||
6566 | }; | |||
6567 | // op0 must be either the needed shift opcode or the mul/udiv equivalent | |||
6568 | // that the needed shift can be extracted from. | |||
6569 | if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && | |||
6570 | (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) | |||
6571 | return SDValue(); | |||
6572 | ||||
6573 | // op0 must be the same opcode on both sides, have the same LHS argument, | |||
6574 | // and produce the same value type. | |||
6575 | if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || | |||
6576 | OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || | |||
6577 | ShiftedVT != ExtractFrom.getValueType()) | |||
6578 | return SDValue(); | |||
6579 | ||||
6580 | // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. | |||
6581 | ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); | |||
6582 | // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. | |||
6583 | ConstantSDNode *ExtractFromCst = | |||
6584 | isConstOrConstSplat(ExtractFrom.getOperand(1)); | |||
6585 | // TODO: We should be able to handle non-uniform constant vectors for these values | |||
6586 | // Check that we have constant values. | |||
6587 | if (!OppShiftCst || !OppShiftCst->getAPIntValue() || | |||
6588 | !OppLHSCst || !OppLHSCst->getAPIntValue() || | |||
6589 | !ExtractFromCst || !ExtractFromCst->getAPIntValue()) | |||
6590 | return SDValue(); | |||
6591 | ||||
6592 | // Compute the shift amount we need to extract to complete the rotate. | |||
6593 | const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); | |||
6594 | if (OppShiftCst->getAPIntValue().ugt(VTWidth)) | |||
6595 | return SDValue(); | |||
6596 | APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); | |||
6597 | // Normalize the bitwidth of the two mul/udiv/shift constant operands. | |||
6598 | APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); | |||
6599 | APInt OppLHSAmt = OppLHSCst->getAPIntValue(); | |||
6600 | zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); | |||
6601 | ||||
6602 | // Now try extract the needed shift from the ExtractFrom op and see if the | |||
6603 | // result matches up with the existing shift's LHS op. | |||
6604 | if (IsMulOrDiv) { | |||
6605 | // Op to extract from is a mul or udiv by a constant. | |||
6606 | // Check: | |||
6607 | // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 | |||
6608 | // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 | |||
6609 | const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), | |||
6610 | NeededShiftAmt.getZExtValue()); | |||
6611 | APInt ResultAmt; | |||
6612 | APInt Rem; | |||
6613 | APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); | |||
6614 | if (Rem != 0 || ResultAmt != OppLHSAmt) | |||
6615 | return SDValue(); | |||
6616 | } else { | |||
6617 | // Op to extract from is a shift by a constant. | |||
6618 | // Check: | |||
6619 | // c2 - (bitwidth(op0 v c0) - c1) == c0 | |||
6620 | if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( | |||
6621 | ExtractFromAmt.getBitWidth())) | |||
6622 | return SDValue(); | |||
6623 | } | |||
6624 | ||||
6625 | // Return the expanded shift op that should allow a rotate to be formed. | |||
6626 | EVT ShiftVT = OppShift.getOperand(1).getValueType(); | |||
6627 | EVT ResVT = ExtractFrom.getValueType(); | |||
6628 | SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); | |||
6629 | return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); | |||
6630 | } | |||
6631 | ||||
6632 | // Return true if we can prove that, whenever Neg and Pos are both in the | |||
6633 | // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that | |||
6634 | // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: | |||
6635 | // | |||
6636 | // (or (shift1 X, Neg), (shift2 X, Pos)) | |||
6637 | // | |||
6638 | // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate | |||
6639 | // in direction shift1 by Neg. The range [0, EltSize) means that we only need | |||
6640 | // to consider shift amounts with defined behavior. | |||
6641 | // | |||
6642 | // The IsRotate flag should be set when the LHS of both shifts is the same. | |||
6643 | // Otherwise if matching a general funnel shift, it should be clear. | |||
6644 | static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, | |||
6645 | SelectionDAG &DAG, bool IsRotate) { | |||
6646 | // If EltSize is a power of 2 then: | |||
6647 | // | |||
6648 | // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) | |||
6649 | // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). | |||
6650 | // | |||
6651 | // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check | |||
6652 | // for the stronger condition: | |||
6653 | // | |||
6654 | // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] | |||
6655 | // | |||
6656 | // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) | |||
6657 | // we can just replace Neg with Neg' for the rest of the function. | |||
6658 | // | |||
6659 | // In other cases we check for the even stronger condition: | |||
6660 | // | |||
6661 | // Neg == EltSize - Pos [B] | |||
6662 | // | |||
6663 | // for all Neg and Pos. Note that the (or ...) then invokes undefined | |||
6664 | // behavior if Pos == 0 (and consequently Neg == EltSize). | |||
6665 | // | |||
6666 | // We could actually use [A] whenever EltSize is a power of 2, but the | |||
6667 | // only extra cases that it would match are those uninteresting ones | |||
6668 | // where Neg and Pos are never in range at the same time. E.g. for | |||
6669 | // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) | |||
6670 | // as well as (sub 32, Pos), but: | |||
6671 | // | |||
6672 | // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) | |||
6673 | // | |||
6674 | // always invokes undefined behavior for 32-bit X. | |||
6675 | // | |||
6676 | // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. | |||
6677 | // | |||
6678 | // NOTE: We can only do this when matching an AND and not a general | |||
6679 | // funnel shift. | |||
6680 | unsigned MaskLoBits = 0; | |||
6681 | if (IsRotate && Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { | |||
6682 | if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { | |||
6683 | KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0)); | |||
6684 | unsigned Bits = Log2_64(EltSize); | |||
6685 | if (NegC->getAPIntValue().getActiveBits() <= Bits && | |||
6686 | ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { | |||
6687 | Neg = Neg.getOperand(0); | |||
6688 | MaskLoBits = Bits; | |||
6689 | } | |||
6690 | } | |||
6691 | } | |||
6692 | ||||
6693 | // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. | |||
6694 | if (Neg.getOpcode() != ISD::SUB) | |||
6695 | return false; | |||
6696 | ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); | |||
6697 | if (!NegC) | |||
6698 | return false; | |||
6699 | SDValue NegOp1 = Neg.getOperand(1); | |||
6700 | ||||
6701 | // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with | |||
6702 | // Pos'. The truncation is redundant for the purpose of the equality. | |||
6703 | if (MaskLoBits && Pos.getOpcode() == ISD::AND) { | |||
6704 | if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { | |||
6705 | KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0)); | |||
6706 | if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && | |||
6707 | ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= | |||
6708 | MaskLoBits)) | |||
6709 | Pos = Pos.getOperand(0); | |||
6710 | } | |||
6711 | } | |||
6712 | ||||
6713 | // The condition we need is now: | |||
6714 | // | |||
6715 | // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask | |||
6716 | // | |||
6717 | // If NegOp1 == Pos then we need: | |||
6718 | // | |||
6719 | // EltSize & Mask == NegC & Mask | |||
6720 | // | |||
6721 | // (because "x & Mask" is a truncation and distributes through subtraction). | |||
6722 | // | |||
6723 | // We also need to account for a potential truncation of NegOp1 if the amount | |||
6724 | // has already been legalized to a shift amount type. | |||
6725 | APInt Width; | |||
6726 | if ((Pos == NegOp1) || | |||
6727 | (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0))) | |||
6728 | Width = NegC->getAPIntValue(); | |||
6729 | ||||
6730 | // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. | |||
6731 | // Then the condition we want to prove becomes: | |||
6732 | // | |||
6733 | // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask | |||
6734 | // | |||
6735 | // which, again because "x & Mask" is a truncation, becomes: | |||
6736 | // | |||
6737 | // NegC & Mask == (EltSize - PosC) & Mask | |||
6738 | // EltSize & Mask == (NegC + PosC) & Mask | |||
6739 | else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { | |||
6740 | if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) | |||
6741 | Width = PosC->getAPIntValue() + NegC->getAPIntValue(); | |||
6742 | else | |||
6743 | return false; | |||
6744 | } else | |||
6745 | return false; | |||
6746 | ||||
6747 | // Now we just need to check that EltSize & Mask == Width & Mask. | |||
6748 | if (MaskLoBits) | |||
6749 | // EltSize & Mask is 0 since Mask is EltSize - 1. | |||
6750 | return Width.getLoBits(MaskLoBits) == 0; | |||
6751 | return Width == EltSize; | |||
6752 | } | |||
6753 | ||||
6754 | // A subroutine of MatchRotate used once we have found an OR of two opposite | |||
6755 | // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces | |||
6756 | // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the | |||
6757 | // former being preferred if supported. InnerPos and InnerNeg are Pos and | |||
6758 | // Neg with outer conversions stripped away. | |||
6759 | SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, | |||
6760 | SDValue Neg, SDValue InnerPos, | |||
6761 | SDValue InnerNeg, unsigned PosOpcode, | |||
6762 | unsigned NegOpcode, const SDLoc &DL) { | |||
6763 | // fold (or (shl x, (*ext y)), | |||
6764 | // (srl x, (*ext (sub 32, y)))) -> | |||
6765 | // (rotl x, y) or (rotr x, (sub 32, y)) | |||
6766 | // | |||
6767 | // fold (or (shl x, (*ext (sub 32, y))), | |||
6768 | // (srl x, (*ext y))) -> | |||
6769 | // (rotr x, y) or (rotl x, (sub 32, y)) | |||
6770 | EVT VT = Shifted.getValueType(); | |||
6771 | if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG, | |||
6772 | /*IsRotate*/ true)) { | |||
6773 | bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); | |||
6774 | return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, | |||
6775 | HasPos ? Pos : Neg); | |||
6776 | } | |||
6777 | ||||
6778 | return SDValue(); | |||
6779 | } | |||
6780 | ||||
6781 | // A subroutine of MatchRotate used once we have found an OR of two opposite | |||
6782 | // shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces | |||
6783 | // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the | |||
6784 | // former being preferred if supported. InnerPos and InnerNeg are Pos and | |||
6785 | // Neg with outer conversions stripped away. | |||
6786 | // TODO: Merge with MatchRotatePosNeg. | |||
6787 | SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, | |||
6788 | SDValue Neg, SDValue InnerPos, | |||
6789 | SDValue InnerNeg, unsigned PosOpcode, | |||
6790 | unsigned NegOpcode, const SDLoc &DL) { | |||
6791 | EVT VT = N0.getValueType(); | |||
6792 | unsigned EltBits = VT.getScalarSizeInBits(); | |||
6793 | ||||
6794 | // fold (or (shl x0, (*ext y)), | |||
6795 | // (srl x1, (*ext (sub 32, y)))) -> | |||
6796 | // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y)) | |||
6797 | // | |||
6798 | // fold (or (shl x0, (*ext (sub 32, y))), | |||
6799 | // (srl x1, (*ext y))) -> | |||
6800 | // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y)) | |||
6801 | if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1)) { | |||
6802 | bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); | |||
6803 | return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1, | |||
6804 | HasPos ? Pos : Neg); | |||
6805 | } | |||
6806 | ||||
6807 | // Matching the shift+xor cases, we can't easily use the xor'd shift amount | |||
6808 | // so for now just use the PosOpcode case if its legal. | |||
6809 | // TODO: When can we use the NegOpcode case? | |||
6810 | if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) { | |||
6811 | auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) { | |||
6812 | if (Op.getOpcode() != BinOpc) | |||
6813 | return false; | |||
6814 | ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1)); | |||
6815 | return Cst && (Cst->getAPIntValue() == Imm); | |||
6816 | }; | |||
6817 | ||||
6818 | // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31))) | |||
6819 | // -> (fshl x0, x1, y) | |||
6820 | if (IsBinOpImm(N1, ISD::SRL, 1) && | |||
6821 | IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) && | |||
6822 | InnerPos == InnerNeg.getOperand(0) && | |||
6823 | TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) { | |||
6824 | return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos); | |||
6825 | } | |||
6826 | ||||
6827 | // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y)) | |||
6828 | // -> (fshr x0, x1, y) | |||
6829 | if (IsBinOpImm(N0, ISD::SHL, 1) && | |||
6830 | IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && | |||
6831 | InnerNeg == InnerPos.getOperand(0) && | |||
6832 | TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { | |||
6833 | return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); | |||
6834 | } | |||
6835 | ||||
6836 | // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y)) | |||
6837 | // -> (fshr x0, x1, y) | |||
6838 | // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization? | |||
6839 | if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) && | |||
6840 | IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && | |||
6841 | InnerNeg == InnerPos.getOperand(0) && | |||
6842 | TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { | |||
6843 | return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); | |||
6844 | } | |||
6845 | } | |||
6846 | ||||
6847 | return SDValue(); | |||
6848 | } | |||
6849 | ||||
6850 | // MatchRotate - Handle an 'or' of two operands. If this is one of the many | |||
6851 | // idioms for rotate, and if the target supports rotation instructions, generate | |||
6852 | // a rot[lr]. This also matches funnel shift patterns, similar to rotation but | |||
6853 | // with different shifted sources. | |||
6854 | SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { | |||
6855 | // Must be a legal type. Expanded 'n promoted things won't work with rotates. | |||
6856 | EVT VT = LHS.getValueType(); | |||
6857 | if (!TLI.isTypeLegal(VT)) | |||
6858 | return SDValue(); | |||
6859 | ||||
6860 | // The target must have at least one rotate/funnel flavor. | |||
6861 | bool HasROTL = hasOperation(ISD::ROTL, VT); | |||
6862 | bool HasROTR = hasOperation(ISD::ROTR, VT); | |||
6863 | bool HasFSHL = hasOperation(ISD::FSHL, VT); | |||
6864 | bool HasFSHR = hasOperation(ISD::FSHR, VT); | |||
6865 | if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR) | |||
6866 | return SDValue(); | |||
6867 | ||||
6868 | // Check for truncated rotate. | |||
6869 | if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && | |||
6870 | LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { | |||
6871 | assert(LHS.getValueType() == RHS.getValueType())((LHS.getValueType() == RHS.getValueType()) ? static_cast< void> (0) : __assert_fail ("LHS.getValueType() == RHS.getValueType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 6871, __PRETTY_FUNCTION__)); | |||
6872 | if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { | |||
6873 | return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot); | |||
6874 | } | |||
6875 | } | |||
6876 | ||||
6877 | // Match "(X shl/srl V1) & V2" where V2 may not be present. | |||
6878 | SDValue LHSShift; // The shift. | |||
6879 | SDValue LHSMask; // AND value if any. | |||
6880 | matchRotateHalf(DAG, LHS, LHSShift, LHSMask); | |||
6881 | ||||
6882 | SDValue RHSShift; // The shift. | |||
6883 | SDValue RHSMask; // AND value if any. | |||
6884 | matchRotateHalf(DAG, RHS, RHSShift, RHSMask); | |||
6885 | ||||
6886 | // If neither side matched a rotate half, bail | |||
6887 | if (!LHSShift && !RHSShift) | |||
6888 | return SDValue(); | |||
6889 | ||||
6890 | // InstCombine may have combined a constant shl, srl, mul, or udiv with one | |||
6891 | // side of the rotate, so try to handle that here. In all cases we need to | |||
6892 | // pass the matched shift from the opposite side to compute the opcode and | |||
6893 | // needed shift amount to extract. We still want to do this if both sides | |||
6894 | // matched a rotate half because one half may be a potential overshift that | |||
6895 | // can be broken down (ie if InstCombine merged two shl or srl ops into a | |||
6896 | // single one). | |||
6897 | ||||
6898 | // Have LHS side of the rotate, try to extract the needed shift from the RHS. | |||
6899 | if (LHSShift) | |||
6900 | if (SDValue NewRHSShift = | |||
6901 | extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) | |||
6902 | RHSShift = NewRHSShift; | |||
6903 | // Have RHS side of the rotate, try to extract the needed shift from the LHS. | |||
6904 | if (RHSShift) | |||
6905 | if (SDValue NewLHSShift = | |||
6906 | extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) | |||
6907 | LHSShift = NewLHSShift; | |||
6908 | ||||
6909 | // If a side is still missing, nothing else we can do. | |||
6910 | if (!RHSShift || !LHSShift) | |||
6911 | return SDValue(); | |||
6912 | ||||
6913 | // At this point we've matched or extracted a shift op on each side. | |||
6914 | ||||
6915 | if (LHSShift.getOpcode() == RHSShift.getOpcode()) | |||
6916 | return SDValue(); // Shifts must disagree. | |||
6917 | ||||
6918 | bool IsRotate = LHSShift.getOperand(0) == RHSShift.getOperand(0); | |||
6919 | if (!IsRotate && !(HasFSHL || HasFSHR)) | |||
6920 | return SDValue(); // Requires funnel shift support. | |||
6921 | ||||
6922 | // Canonicalize shl to left side in a shl/srl pair. | |||
6923 | if (RHSShift.getOpcode() == ISD::SHL) { | |||
6924 | std::swap(LHS, RHS); | |||
6925 | std::swap(LHSShift, RHSShift); | |||
6926 | std::swap(LHSMask, RHSMask); | |||
6927 | } | |||
6928 | ||||
6929 | unsigned EltSizeInBits = VT.getScalarSizeInBits(); | |||
6930 | SDValue LHSShiftArg = LHSShift.getOperand(0); | |||
6931 | SDValue LHSShiftAmt = LHSShift.getOperand(1); | |||
6932 | SDValue RHSShiftArg = RHSShift.getOperand(0); | |||
6933 | SDValue RHSShiftAmt = RHSShift.getOperand(1); | |||
6934 | ||||
6935 | // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) | |||
6936 | // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) | |||
6937 | // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1) | |||
6938 | // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2) | |||
6939 | // iff C1+C2 == EltSizeInBits | |||
6940 | auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, | |||
6941 | ConstantSDNode *RHS) { | |||
6942 | return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; | |||
6943 | }; | |||
6944 | if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { | |||
6945 | SDValue Res; | |||
6946 | if (IsRotate && (HasROTL || HasROTR)) | |||
6947 | Res = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, | |||
6948 | HasROTL ? LHSShiftAmt : RHSShiftAmt); | |||
6949 | else | |||
6950 | Res = DAG.getNode(HasFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg, | |||
6951 | RHSShiftArg, HasFSHL ? LHSShiftAmt : RHSShiftAmt); | |||
6952 | ||||
6953 | // If there is an AND of either shifted operand, apply it to the result. | |||
6954 | if (LHSMask.getNode() || RHSMask.getNode()) { | |||
6955 | SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); | |||
6956 | SDValue Mask = AllOnes; | |||
6957 | ||||
6958 | if (LHSMask.getNode()) { | |||
6959 | SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); | |||
6960 | Mask = DAG.getNode(ISD::AND, DL, VT, Mask, | |||
6961 | DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); | |||
6962 | } | |||
6963 | if (RHSMask.getNode()) { | |||
6964 | SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); | |||
6965 | Mask = DAG.getNode(ISD::AND, DL, VT, Mask, | |||
6966 | DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); | |||
6967 | } | |||
6968 | ||||
6969 | Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask); | |||
6970 | } | |||
6971 | ||||
6972 | return Res; | |||
6973 | } | |||
6974 | ||||
6975 | // If there is a mask here, and we have a variable shift, we can't be sure | |||
6976 | // that we're masking out the right stuff. | |||
6977 | if (LHSMask.getNode() || RHSMask.getNode()) | |||
6978 | return SDValue(); | |||
6979 | ||||
6980 | // If the shift amount is sign/zext/any-extended just peel it off. | |||
6981 | SDValue LExtOp0 = LHSShiftAmt; | |||
6982 | SDValue RExtOp0 = RHSShiftAmt; | |||
6983 | if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || | |||
6984 | LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || | |||
6985 | LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || | |||
6986 | LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && | |||
6987 | (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || | |||
6988 | RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || | |||
6989 | RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || | |||
6990 | RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { | |||
6991 | LExtOp0 = LHSShiftAmt.getOperand(0); | |||
6992 | RExtOp0 = RHSShiftAmt.getOperand(0); | |||
6993 | } | |||
6994 | ||||
6995 | if (IsRotate && (HasROTL || HasROTR)) { | |||
6996 | SDValue TryL = | |||
6997 | MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0, | |||
6998 | RExtOp0, ISD::ROTL, ISD::ROTR, DL); | |||
6999 | if (TryL) | |||
7000 | return TryL; | |||
7001 | ||||
7002 | SDValue TryR = | |||
7003 | MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0, | |||
7004 | LExtOp0, ISD::ROTR, ISD::ROTL, DL); | |||
7005 | if (TryR) | |||
7006 | return TryR; | |||
7007 | } | |||
7008 | ||||
7009 | SDValue TryL = | |||
7010 | MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt, | |||
7011 | LExtOp0, RExtOp0, ISD::FSHL, ISD::FSHR, DL); | |||
7012 | if (TryL) | |||
7013 | return TryL; | |||
7014 | ||||
7015 | SDValue TryR = | |||
7016 | MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt, | |||
7017 | RExtOp0, LExtOp0, ISD::FSHR, ISD::FSHL, DL); | |||
7018 | if (TryR) | |||
7019 | return TryR; | |||
7020 | ||||
7021 | return SDValue(); | |||
7022 | } | |||
7023 | ||||
7024 | namespace { | |||
7025 | ||||
7026 | /// Represents known origin of an individual byte in load combine pattern. The | |||
7027 | /// value of the byte is either constant zero or comes from memory. | |||
7028 | struct ByteProvider { | |||
7029 | // For constant zero providers Load is set to nullptr. For memory providers | |||
7030 | // Load represents the node which loads the byte from memory. | |||
7031 | // ByteOffset is the offset of the byte in the value produced by the load. | |||
7032 | LoadSDNode *Load = nullptr; | |||
7033 | unsigned ByteOffset = 0; | |||
7034 | ||||
7035 | ByteProvider() = default; | |||
7036 | ||||
7037 | static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { | |||
7038 | return ByteProvider(Load, ByteOffset); | |||
7039 | } | |||
7040 | ||||
7041 | static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } | |||
7042 | ||||
7043 | bool isConstantZero() const { return !Load; } | |||
7044 | bool isMemory() const { return Load; } | |||
7045 | ||||
7046 | bool operator==(const ByteProvider &Other) const { | |||
7047 | return Other.Load == Load && Other.ByteOffset == ByteOffset; | |||
7048 | } | |||
7049 | ||||
7050 | private: | |||
7051 | ByteProvider(LoadSDNode *Load, unsigned ByteOffset) | |||
7052 | : Load(Load), ByteOffset(ByteOffset) {} | |||
7053 | }; | |||
7054 | ||||
7055 | } // end anonymous namespace | |||
7056 | ||||
7057 | /// Recursively traverses the expression calculating the origin of the requested | |||
7058 | /// byte of the given value. Returns None if the provider can't be calculated. | |||
7059 | /// | |||
7060 | /// For all the values except the root of the expression verifies that the value | |||
7061 | /// has exactly one use and if it's not true return None. This way if the origin | |||
7062 | /// of the byte is returned it's guaranteed that the values which contribute to | |||
7063 | /// the byte are not used outside of this expression. | |||
7064 | /// | |||
7065 | /// Because the parts of the expression are not allowed to have more than one | |||
7066 | /// use this function iterates over trees, not DAGs. So it never visits the same | |||
7067 | /// node more than once. | |||
7068 | static const Optional<ByteProvider> | |||
7069 | calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, | |||
7070 | bool Root = false) { | |||
7071 | // Typical i64 by i8 pattern requires recursion up to 8 calls depth | |||
7072 | if (Depth == 10) | |||
7073 | return None; | |||
7074 | ||||
7075 | if (!Root && !Op.hasOneUse()) | |||
7076 | return None; | |||
7077 | ||||
7078 | assert(Op.getValueType().isScalarInteger() && "can't handle other types")((Op.getValueType().isScalarInteger() && "can't handle other types" ) ? static_cast<void> (0) : __assert_fail ("Op.getValueType().isScalarInteger() && \"can't handle other types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7078, __PRETTY_FUNCTION__)); | |||
7079 | unsigned BitWidth = Op.getValueSizeInBits(); | |||
7080 | if (BitWidth % 8 != 0) | |||
7081 | return None; | |||
7082 | unsigned ByteWidth = BitWidth / 8; | |||
7083 | assert(Index < ByteWidth && "invalid index requested")((Index < ByteWidth && "invalid index requested") ? static_cast<void> (0) : __assert_fail ("Index < ByteWidth && \"invalid index requested\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7083, __PRETTY_FUNCTION__)); | |||
7084 | (void) ByteWidth; | |||
7085 | ||||
7086 | switch (Op.getOpcode()) { | |||
7087 | case ISD::OR: { | |||
7088 | auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); | |||
7089 | if (!LHS) | |||
7090 | return None; | |||
7091 | auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); | |||
7092 | if (!RHS) | |||
7093 | return None; | |||
7094 | ||||
7095 | if (LHS->isConstantZero()) | |||
7096 | return RHS; | |||
7097 | if (RHS->isConstantZero()) | |||
7098 | return LHS; | |||
7099 | return None; | |||
7100 | } | |||
7101 | case ISD::SHL: { | |||
7102 | auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); | |||
7103 | if (!ShiftOp) | |||
7104 | return None; | |||
7105 | ||||
7106 | uint64_t BitShift = ShiftOp->getZExtValue(); | |||
7107 | if (BitShift % 8 != 0) | |||
7108 | return None; | |||
7109 | uint64_t ByteShift = BitShift / 8; | |||
7110 | ||||
7111 | return Index < ByteShift | |||
7112 | ? ByteProvider::getConstantZero() | |||
7113 | : calculateByteProvider(Op->getOperand(0), Index - ByteShift, | |||
7114 | Depth + 1); | |||
7115 | } | |||
7116 | case ISD::ANY_EXTEND: | |||
7117 | case ISD::SIGN_EXTEND: | |||
7118 | case ISD::ZERO_EXTEND: { | |||
7119 | SDValue NarrowOp = Op->getOperand(0); | |||
7120 | unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); | |||
7121 | if (NarrowBitWidth % 8 != 0) | |||
7122 | return None; | |||
7123 | uint64_t NarrowByteWidth = NarrowBitWidth / 8; | |||
7124 | ||||
7125 | if (Index >= NarrowByteWidth) | |||
7126 | return Op.getOpcode() == ISD::ZERO_EXTEND | |||
7127 | ? Optional<ByteProvider>(ByteProvider::getConstantZero()) | |||
7128 | : None; | |||
7129 | return calculateByteProvider(NarrowOp, Index, Depth + 1); | |||
7130 | } | |||
7131 | case ISD::BSWAP: | |||
7132 | return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, | |||
7133 | Depth + 1); | |||
7134 | case ISD::LOAD: { | |||
7135 | auto L = cast<LoadSDNode>(Op.getNode()); | |||
7136 | if (!L->isSimple() || L->isIndexed()) | |||
7137 | return None; | |||
7138 | ||||
7139 | unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); | |||
7140 | if (NarrowBitWidth % 8 != 0) | |||
7141 | return None; | |||
7142 | uint64_t NarrowByteWidth = NarrowBitWidth / 8; | |||
7143 | ||||
7144 | if (Index >= NarrowByteWidth) | |||
7145 | return L->getExtensionType() == ISD::ZEXTLOAD | |||
7146 | ? Optional<ByteProvider>(ByteProvider::getConstantZero()) | |||
7147 | : None; | |||
7148 | return ByteProvider::getMemory(L, Index); | |||
7149 | } | |||
7150 | } | |||
7151 | ||||
7152 | return None; | |||
7153 | } | |||
7154 | ||||
7155 | static unsigned littleEndianByteAt(unsigned BW, unsigned i) { | |||
7156 | return i; | |||
7157 | } | |||
7158 | ||||
7159 | static unsigned bigEndianByteAt(unsigned BW, unsigned i) { | |||
7160 | return BW - i - 1; | |||
7161 | } | |||
7162 | ||||
7163 | // Check if the bytes offsets we are looking at match with either big or | |||
7164 | // little endian value loaded. Return true for big endian, false for little | |||
7165 | // endian, and None if match failed. | |||
7166 | static Optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets, | |||
7167 | int64_t FirstOffset) { | |||
7168 | // The endian can be decided only when it is 2 bytes at least. | |||
7169 | unsigned Width = ByteOffsets.size(); | |||
7170 | if (Width < 2) | |||
7171 | return None; | |||
7172 | ||||
7173 | bool BigEndian = true, LittleEndian = true; | |||
7174 | for (unsigned i = 0; i < Width; i++) { | |||
7175 | int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; | |||
7176 | LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i); | |||
7177 | BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i); | |||
7178 | if (!BigEndian && !LittleEndian) | |||
7179 | return None; | |||
7180 | } | |||
7181 | ||||
7182 | assert((BigEndian != LittleEndian) && "It should be either big endian or"(((BigEndian != LittleEndian) && "It should be either big endian or" "little endian") ? static_cast<void> (0) : __assert_fail ("(BigEndian != LittleEndian) && \"It should be either big endian or\" \"little endian\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7183, __PRETTY_FUNCTION__)) | |||
7183 | "little endian")(((BigEndian != LittleEndian) && "It should be either big endian or" "little endian") ? static_cast<void> (0) : __assert_fail ("(BigEndian != LittleEndian) && \"It should be either big endian or\" \"little endian\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7183, __PRETTY_FUNCTION__)); | |||
7184 | return BigEndian; | |||
7185 | } | |||
7186 | ||||
7187 | static SDValue stripTruncAndExt(SDValue Value) { | |||
7188 | switch (Value.getOpcode()) { | |||
7189 | case ISD::TRUNCATE: | |||
7190 | case ISD::ZERO_EXTEND: | |||
7191 | case ISD::SIGN_EXTEND: | |||
7192 | case ISD::ANY_EXTEND: | |||
7193 | return stripTruncAndExt(Value.getOperand(0)); | |||
7194 | } | |||
7195 | return Value; | |||
7196 | } | |||
7197 | ||||
7198 | /// Match a pattern where a wide type scalar value is stored by several narrow | |||
7199 | /// stores. Fold it into a single store or a BSWAP and a store if the targets | |||
7200 | /// supports it. | |||
7201 | /// | |||
7202 | /// Assuming little endian target: | |||
7203 | /// i8 *p = ... | |||
7204 | /// i32 val = ... | |||
7205 | /// p[0] = (val >> 0) & 0xFF; | |||
7206 | /// p[1] = (val >> 8) & 0xFF; | |||
7207 | /// p[2] = (val >> 16) & 0xFF; | |||
7208 | /// p[3] = (val >> 24) & 0xFF; | |||
7209 | /// => | |||
7210 | /// *((i32)p) = val; | |||
7211 | /// | |||
7212 | /// i8 *p = ... | |||
7213 | /// i32 val = ... | |||
7214 | /// p[0] = (val >> 24) & 0xFF; | |||
7215 | /// p[1] = (val >> 16) & 0xFF; | |||
7216 | /// p[2] = (val >> 8) & 0xFF; | |||
7217 | /// p[3] = (val >> 0) & 0xFF; | |||
7218 | /// => | |||
7219 | /// *((i32)p) = BSWAP(val); | |||
7220 | SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) { | |||
7221 | // The matching looks for "store (trunc x)" patterns that appear early but are | |||
7222 | // likely to be replaced by truncating store nodes during combining. | |||
7223 | // TODO: If there is evidence that running this later would help, this | |||
7224 | // limitation could be removed. Legality checks may need to be added | |||
7225 | // for the created store and optional bswap/rotate. | |||
7226 | if (LegalOperations) | |||
7227 | return SDValue(); | |||
7228 | ||||
7229 | // Collect all the stores in the chain. | |||
7230 | SDValue Chain; | |||
7231 | SmallVector<StoreSDNode *, 8> Stores; | |||
7232 | for (StoreSDNode *Store = N; Store; Store = dyn_cast<StoreSDNode>(Chain)) { | |||
7233 | // TODO: Allow unordered atomics when wider type is legal (see D66309) | |||
7234 | EVT MemVT = Store->getMemoryVT(); | |||
7235 | if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) || | |||
7236 | !Store->isSimple() || Store->isIndexed()) | |||
7237 | return SDValue(); | |||
7238 | Stores.push_back(Store); | |||
7239 | Chain = Store->getChain(); | |||
7240 | } | |||
7241 | // There is no reason to continue if we do not have at least a pair of stores. | |||
7242 | if (Stores.size() < 2) | |||
7243 | return SDValue(); | |||
7244 | ||||
7245 | // Handle simple types only. | |||
7246 | LLVMContext &Context = *DAG.getContext(); | |||
7247 | unsigned NumStores = Stores.size(); | |||
7248 | unsigned NarrowNumBits = N->getMemoryVT().getScalarSizeInBits(); | |||
7249 | unsigned WideNumBits = NumStores * NarrowNumBits; | |||
7250 | EVT WideVT = EVT::getIntegerVT(Context, WideNumBits); | |||
7251 | if (WideVT != MVT::i16 && WideVT != MVT::i32 && WideVT != MVT::i64) | |||
7252 | return SDValue(); | |||
7253 | ||||
7254 | // Check if all bytes of the source value that we are looking at are stored | |||
7255 | // to the same base address. Collect offsets from Base address into OffsetMap. | |||
7256 | SDValue SourceValue; | |||
7257 | SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX(9223372036854775807L)); | |||
7258 | int64_t FirstOffset = INT64_MAX(9223372036854775807L); | |||
7259 | StoreSDNode *FirstStore = nullptr; | |||
7260 | Optional<BaseIndexOffset> Base; | |||
7261 | for (auto Store : Stores) { | |||
7262 | // All the stores store different parts of the CombinedValue. A truncate is | |||
7263 | // required to get the partial value. | |||
7264 | SDValue Trunc = Store->getValue(); | |||
7265 | if (Trunc.getOpcode() != ISD::TRUNCATE) | |||
7266 | return SDValue(); | |||
7267 | // Other than the first/last part, a shift operation is required to get the | |||
7268 | // offset. | |||
7269 | int64_t Offset = 0; | |||
7270 | SDValue WideVal = Trunc.getOperand(0); | |||
7271 | if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) && | |||
7272 | isa<ConstantSDNode>(WideVal.getOperand(1))) { | |||
7273 | // The shift amount must be a constant multiple of the narrow type. | |||
7274 | // It is translated to the offset address in the wide source value "y". | |||
7275 | // | |||
7276 | // x = srl y, ShiftAmtC | |||
7277 | // i8 z = trunc x | |||
7278 | // store z, ... | |||
7279 | uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1); | |||
7280 | if (ShiftAmtC % NarrowNumBits != 0) | |||
7281 | return SDValue(); | |||
7282 | ||||
7283 | Offset = ShiftAmtC / NarrowNumBits; | |||
7284 | WideVal = WideVal.getOperand(0); | |||
7285 | } | |||
7286 | ||||
7287 | // Stores must share the same source value with different offsets. | |||
7288 | // Truncate and extends should be stripped to get the single source value. | |||
7289 | if (!SourceValue) | |||
7290 | SourceValue = WideVal; | |||
7291 | else if (stripTruncAndExt(SourceValue) != stripTruncAndExt(WideVal)) | |||
7292 | return SDValue(); | |||
7293 | else if (SourceValue.getValueType() != WideVT) { | |||
7294 | if (WideVal.getValueType() == WideVT || | |||
7295 | WideVal.getScalarValueSizeInBits() > | |||
7296 | SourceValue.getScalarValueSizeInBits()) | |||
7297 | SourceValue = WideVal; | |||
7298 | // Give up if the source value type is smaller than the store size. | |||
7299 | if (SourceValue.getScalarValueSizeInBits() < WideVT.getScalarSizeInBits()) | |||
7300 | return SDValue(); | |||
7301 | } | |||
7302 | ||||
7303 | // Stores must share the same base address. | |||
7304 | BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG); | |||
7305 | int64_t ByteOffsetFromBase = 0; | |||
7306 | if (!Base) | |||
7307 | Base = Ptr; | |||
7308 | else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) | |||
7309 | return SDValue(); | |||
7310 | ||||
7311 | // Remember the first store. | |||
7312 | if (ByteOffsetFromBase < FirstOffset) { | |||
7313 | FirstStore = Store; | |||
7314 | FirstOffset = ByteOffsetFromBase; | |||
7315 | } | |||
7316 | // Map the offset in the store and the offset in the combined value, and | |||
7317 | // early return if it has been set before. | |||
7318 | if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX(9223372036854775807L)) | |||
7319 | return SDValue(); | |||
7320 | OffsetMap[Offset] = ByteOffsetFromBase; | |||
7321 | } | |||
7322 | ||||
7323 | assert(FirstOffset != INT64_MAX && "First byte offset must be set")((FirstOffset != (9223372036854775807L) && "First byte offset must be set" ) ? static_cast<void> (0) : __assert_fail ("FirstOffset != INT64_MAX && \"First byte offset must be set\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7323, __PRETTY_FUNCTION__)); | |||
7324 | assert(FirstStore && "First store must be set")((FirstStore && "First store must be set") ? static_cast <void> (0) : __assert_fail ("FirstStore && \"First store must be set\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7324, __PRETTY_FUNCTION__)); | |||
7325 | ||||
7326 | // Check that a store of the wide type is both allowed and fast on the target | |||
7327 | const DataLayout &Layout = DAG.getDataLayout(); | |||
7328 | bool Fast = false; | |||
7329 | bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT, | |||
7330 | *FirstStore->getMemOperand(), &Fast); | |||
7331 | if (!Allowed || !Fast) | |||
7332 | return SDValue(); | |||
7333 | ||||
7334 | // Check if the pieces of the value are going to the expected places in memory | |||
7335 | // to merge the stores. | |||
7336 | auto checkOffsets = [&](bool MatchLittleEndian) { | |||
7337 | if (MatchLittleEndian) { | |||
7338 | for (unsigned i = 0; i != NumStores; ++i) | |||
7339 | if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset) | |||
7340 | return false; | |||
7341 | } else { // MatchBigEndian by reversing loop counter. | |||
7342 | for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j) | |||
7343 | if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset) | |||
7344 | return false; | |||
7345 | } | |||
7346 | return true; | |||
7347 | }; | |||
7348 | ||||
7349 | // Check if the offsets line up for the native data layout of this target. | |||
7350 | bool NeedBswap = false; | |||
7351 | bool NeedRotate = false; | |||
7352 | if (!checkOffsets(Layout.isLittleEndian())) { | |||
7353 | // Special-case: check if byte offsets line up for the opposite endian. | |||
7354 | if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian())) | |||
7355 | NeedBswap = true; | |||
7356 | else if (NumStores == 2 && checkOffsets(Layout.isBigEndian())) | |||
7357 | NeedRotate = true; | |||
7358 | else | |||
7359 | return SDValue(); | |||
7360 | } | |||
7361 | ||||
7362 | SDLoc DL(N); | |||
7363 | if (WideVT != SourceValue.getValueType()) { | |||
7364 | assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&((SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && "Unexpected store value to merge") ? static_cast< void> (0) : __assert_fail ("SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && \"Unexpected store value to merge\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7365, __PRETTY_FUNCTION__)) | |||
7365 | "Unexpected store value to merge")((SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && "Unexpected store value to merge") ? static_cast< void> (0) : __assert_fail ("SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && \"Unexpected store value to merge\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7365, __PRETTY_FUNCTION__)); | |||
7366 | SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue); | |||
7367 | } | |||
7368 | ||||
7369 | // Before legalize we can introduce illegal bswaps/rotates which will be later | |||
7370 | // converted to an explicit bswap sequence. This way we end up with a single | |||
7371 | // store and byte shuffling instead of several stores and byte shuffling. | |||
7372 | if (NeedBswap) { | |||
7373 | SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue); | |||
7374 | } else if (NeedRotate) { | |||
7375 | assert(WideNumBits % 2 == 0 && "Unexpected type for rotate")((WideNumBits % 2 == 0 && "Unexpected type for rotate" ) ? static_cast<void> (0) : __assert_fail ("WideNumBits % 2 == 0 && \"Unexpected type for rotate\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7375, __PRETTY_FUNCTION__)); | |||
7376 | SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT); | |||
7377 | SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt); | |||
7378 | } | |||
7379 | ||||
7380 | SDValue NewStore = | |||
7381 | DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(), | |||
7382 | FirstStore->getPointerInfo(), FirstStore->getAlign()); | |||
7383 | ||||
7384 | // Rely on other DAG combine rules to remove the other individual stores. | |||
7385 | DAG.ReplaceAllUsesWith(N, NewStore.getNode()); | |||
7386 | return NewStore; | |||
7387 | } | |||
7388 | ||||
7389 | /// Match a pattern where a wide type scalar value is loaded by several narrow | |||
7390 | /// loads and combined by shifts and ors. Fold it into a single load or a load | |||
7391 | /// and a BSWAP if the targets supports it. | |||
7392 | /// | |||
7393 | /// Assuming little endian target: | |||
7394 | /// i8 *a = ... | |||
7395 | /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) | |||
7396 | /// => | |||
7397 | /// i32 val = *((i32)a) | |||
7398 | /// | |||
7399 | /// i8 *a = ... | |||
7400 | /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] | |||
7401 | /// => | |||
7402 | /// i32 val = BSWAP(*((i32)a)) | |||
7403 | /// | |||
7404 | /// TODO: This rule matches complex patterns with OR node roots and doesn't | |||
7405 | /// interact well with the worklist mechanism. When a part of the pattern is | |||
7406 | /// updated (e.g. one of the loads) its direct users are put into the worklist, | |||
7407 | /// but the root node of the pattern which triggers the load combine is not | |||
7408 | /// necessarily a direct user of the changed node. For example, once the address | |||
7409 | /// of t28 load is reassociated load combine won't be triggered: | |||
7410 | /// t25: i32 = add t4, Constant:i32<2> | |||
7411 | /// t26: i64 = sign_extend t25 | |||
7412 | /// t27: i64 = add t2, t26 | |||
7413 | /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 | |||
7414 | /// t29: i32 = zero_extend t28 | |||
7415 | /// t32: i32 = shl t29, Constant:i8<8> | |||
7416 | /// t33: i32 = or t23, t32 | |||
7417 | /// As a possible fix visitLoad can check if the load can be a part of a load | |||
7418 | /// combine pattern and add corresponding OR roots to the worklist. | |||
7419 | SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { | |||
7420 | assert(N->getOpcode() == ISD::OR &&((N->getOpcode() == ISD::OR && "Can only match load combining against OR nodes" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Can only match load combining against OR nodes\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7421, __PRETTY_FUNCTION__)) | |||
7421 | "Can only match load combining against OR nodes")((N->getOpcode() == ISD::OR && "Can only match load combining against OR nodes" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Can only match load combining against OR nodes\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7421, __PRETTY_FUNCTION__)); | |||
7422 | ||||
7423 | // Handles simple types only | |||
7424 | EVT VT = N->getValueType(0); | |||
7425 | if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) | |||
7426 | return SDValue(); | |||
7427 | unsigned ByteWidth = VT.getSizeInBits() / 8; | |||
7428 | ||||
7429 | bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); | |||
7430 | auto MemoryByteOffset = [&] (ByteProvider P) { | |||
7431 | assert(P.isMemory() && "Must be a memory byte provider")((P.isMemory() && "Must be a memory byte provider") ? static_cast<void> (0) : __assert_fail ("P.isMemory() && \"Must be a memory byte provider\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7431, __PRETTY_FUNCTION__)); | |||
7432 | unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); | |||
7433 | assert(LoadBitWidth % 8 == 0 &&((LoadBitWidth % 8 == 0 && "can only analyze providers for individual bytes not bit" ) ? static_cast<void> (0) : __assert_fail ("LoadBitWidth % 8 == 0 && \"can only analyze providers for individual bytes not bit\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7434, __PRETTY_FUNCTION__)) | |||
7434 | "can only analyze providers for individual bytes not bit")((LoadBitWidth % 8 == 0 && "can only analyze providers for individual bytes not bit" ) ? static_cast<void> (0) : __assert_fail ("LoadBitWidth % 8 == 0 && \"can only analyze providers for individual bytes not bit\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7434, __PRETTY_FUNCTION__)); | |||
7435 | unsigned LoadByteWidth = LoadBitWidth / 8; | |||
7436 | return IsBigEndianTarget | |||
7437 | ? bigEndianByteAt(LoadByteWidth, P.ByteOffset) | |||
7438 | : littleEndianByteAt(LoadByteWidth, P.ByteOffset); | |||
7439 | }; | |||
7440 | ||||
7441 | Optional<BaseIndexOffset> Base; | |||
7442 | SDValue Chain; | |||
7443 | ||||
7444 | SmallPtrSet<LoadSDNode *, 8> Loads; | |||
7445 | Optional<ByteProvider> FirstByteProvider; | |||
7446 | int64_t FirstOffset = INT64_MAX(9223372036854775807L); | |||
7447 | ||||
7448 | // Check if all the bytes of the OR we are looking at are loaded from the same | |||
7449 | // base address. Collect bytes offsets from Base address in ByteOffsets. | |||
7450 | SmallVector<int64_t, 8> ByteOffsets(ByteWidth); | |||
7451 | unsigned ZeroExtendedBytes = 0; | |||
7452 | for (int i = ByteWidth - 1; i >= 0; --i) { | |||
7453 | auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); | |||
7454 | if (!P) | |||
7455 | return SDValue(); | |||
7456 | ||||
7457 | if (P->isConstantZero()) { | |||
7458 | // It's OK for the N most significant bytes to be 0, we can just | |||
7459 | // zero-extend the load. | |||
7460 | if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i))) | |||
7461 | return SDValue(); | |||
7462 | continue; | |||
7463 | } | |||
7464 | assert(P->isMemory() && "provenance should either be memory or zero")((P->isMemory() && "provenance should either be memory or zero" ) ? static_cast<void> (0) : __assert_fail ("P->isMemory() && \"provenance should either be memory or zero\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7464, __PRETTY_FUNCTION__)); | |||
7465 | ||||
7466 | LoadSDNode *L = P->Load; | |||
7467 | assert(L->hasNUsesOfValue(1, 0) && L->isSimple() &&((L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && "Must be enforced by calculateByteProvider" ) ? static_cast<void> (0) : __assert_fail ("L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && \"Must be enforced by calculateByteProvider\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7469, __PRETTY_FUNCTION__)) | |||
7468 | !L->isIndexed() &&((L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && "Must be enforced by calculateByteProvider" ) ? static_cast<void> (0) : __assert_fail ("L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && \"Must be enforced by calculateByteProvider\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7469, __PRETTY_FUNCTION__)) | |||
7469 | "Must be enforced by calculateByteProvider")((L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && "Must be enforced by calculateByteProvider" ) ? static_cast<void> (0) : __assert_fail ("L->hasNUsesOfValue(1, 0) && L->isSimple() && !L->isIndexed() && \"Must be enforced by calculateByteProvider\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7469, __PRETTY_FUNCTION__)); | |||
7470 | assert(L->getOffset().isUndef() && "Unindexed load must have undef offset")((L->getOffset().isUndef() && "Unindexed load must have undef offset" ) ? static_cast<void> (0) : __assert_fail ("L->getOffset().isUndef() && \"Unindexed load must have undef offset\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7470, __PRETTY_FUNCTION__)); | |||
7471 | ||||
7472 | // All loads must share the same chain | |||
7473 | SDValue LChain = L->getChain(); | |||
7474 | if (!Chain) | |||
7475 | Chain = LChain; | |||
7476 | else if (Chain != LChain) | |||
7477 | return SDValue(); | |||
7478 | ||||
7479 | // Loads must share the same base address | |||
7480 | BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); | |||
7481 | int64_t ByteOffsetFromBase = 0; | |||
7482 | if (!Base) | |||
7483 | Base = Ptr; | |||
7484 | else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) | |||
7485 | return SDValue(); | |||
7486 | ||||
7487 | // Calculate the offset of the current byte from the base address | |||
7488 | ByteOffsetFromBase += MemoryByteOffset(*P); | |||
7489 | ByteOffsets[i] = ByteOffsetFromBase; | |||
7490 | ||||
7491 | // Remember the first byte load | |||
7492 | if (ByteOffsetFromBase < FirstOffset) { | |||
7493 | FirstByteProvider = P; | |||
7494 | FirstOffset = ByteOffsetFromBase; | |||
7495 | } | |||
7496 | ||||
7497 | Loads.insert(L); | |||
7498 | } | |||
7499 | assert(!Loads.empty() && "All the bytes of the value must be loaded from "((!Loads.empty() && "All the bytes of the value must be loaded from " "memory, so there must be at least one load which produces the value" ) ? static_cast<void> (0) : __assert_fail ("!Loads.empty() && \"All the bytes of the value must be loaded from \" \"memory, so there must be at least one load which produces the value\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7500, __PRETTY_FUNCTION__)) | |||
7500 | "memory, so there must be at least one load which produces the value")((!Loads.empty() && "All the bytes of the value must be loaded from " "memory, so there must be at least one load which produces the value" ) ? static_cast<void> (0) : __assert_fail ("!Loads.empty() && \"All the bytes of the value must be loaded from \" \"memory, so there must be at least one load which produces the value\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7500, __PRETTY_FUNCTION__)); | |||
7501 | assert(Base && "Base address of the accessed memory location must be set")((Base && "Base address of the accessed memory location must be set" ) ? static_cast<void> (0) : __assert_fail ("Base && \"Base address of the accessed memory location must be set\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7501, __PRETTY_FUNCTION__)); | |||
7502 | assert(FirstOffset != INT64_MAX && "First byte offset must be set")((FirstOffset != (9223372036854775807L) && "First byte offset must be set" ) ? static_cast<void> (0) : __assert_fail ("FirstOffset != INT64_MAX && \"First byte offset must be set\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7502, __PRETTY_FUNCTION__)); | |||
7503 | ||||
7504 | bool NeedsZext = ZeroExtendedBytes > 0; | |||
7505 | ||||
7506 | EVT MemVT = | |||
7507 | EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8); | |||
7508 | ||||
7509 | if (!MemVT.isSimple()) | |||
7510 | return SDValue(); | |||
7511 | ||||
7512 | // Before legalize we can introduce too wide illegal loads which will be later | |||
7513 | // split into legal sized loads. This enables us to combine i64 load by i8 | |||
7514 | // patterns to a couple of i32 loads on 32 bit targets. | |||
7515 | if (LegalOperations && | |||
7516 | !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, | |||
7517 | MemVT)) | |||
7518 | return SDValue(); | |||
7519 | ||||
7520 | // Check if the bytes of the OR we are looking at match with either big or | |||
7521 | // little endian value load | |||
7522 | Optional<bool> IsBigEndian = isBigEndian( | |||
7523 | makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset); | |||
7524 | if (!IsBigEndian.hasValue()) | |||
7525 | return SDValue(); | |||
7526 | ||||
7527 | assert(FirstByteProvider && "must be set")((FirstByteProvider && "must be set") ? static_cast< void> (0) : __assert_fail ("FirstByteProvider && \"must be set\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7527, __PRETTY_FUNCTION__)); | |||
7528 | ||||
7529 | // Ensure that the first byte is loaded from zero offset of the first load. | |||
7530 | // So the combined value can be loaded from the first load address. | |||
7531 | if (MemoryByteOffset(*FirstByteProvider) != 0) | |||
7532 | return SDValue(); | |||
7533 | LoadSDNode *FirstLoad = FirstByteProvider->Load; | |||
7534 | ||||
7535 | // The node we are looking at matches with the pattern, check if we can | |||
7536 | // replace it with a single (possibly zero-extended) load and bswap + shift if | |||
7537 | // needed. | |||
7538 | ||||
7539 | // If the load needs byte swap check if the target supports it | |||
7540 | bool NeedsBswap = IsBigEndianTarget != *IsBigEndian; | |||
7541 | ||||
7542 | // Before legalize we can introduce illegal bswaps which will be later | |||
7543 | // converted to an explicit bswap sequence. This way we end up with a single | |||
7544 | // load and byte shuffling instead of several loads and byte shuffling. | |||
7545 | // We do not introduce illegal bswaps when zero-extending as this tends to | |||
7546 | // introduce too many arithmetic instructions. | |||
7547 | if (NeedsBswap && (LegalOperations || NeedsZext) && | |||
7548 | !TLI.isOperationLegal(ISD::BSWAP, VT)) | |||
7549 | return SDValue(); | |||
7550 | ||||
7551 | // If we need to bswap and zero extend, we have to insert a shift. Check that | |||
7552 | // it is legal. | |||
7553 | if (NeedsBswap && NeedsZext && LegalOperations && | |||
7554 | !TLI.isOperationLegal(ISD::SHL, VT)) | |||
7555 | return SDValue(); | |||
7556 | ||||
7557 | // Check that a load of the wide type is both allowed and fast on the target | |||
7558 | bool Fast = false; | |||
7559 | bool Allowed = | |||
7560 | TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, | |||
7561 | *FirstLoad->getMemOperand(), &Fast); | |||
7562 | if (!Allowed || !Fast) | |||
7563 | return SDValue(); | |||
7564 | ||||
7565 | SDValue NewLoad = | |||
7566 | DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT, | |||
7567 | Chain, FirstLoad->getBasePtr(), | |||
7568 | FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign()); | |||
7569 | ||||
7570 | // Transfer chain users from old loads to the new load. | |||
7571 | for (LoadSDNode *L : Loads) | |||
7572 | DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); | |||
7573 | ||||
7574 | if (!NeedsBswap) | |||
7575 | return NewLoad; | |||
7576 | ||||
7577 | SDValue ShiftedLoad = | |||
7578 | NeedsZext | |||
7579 | ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad, | |||
7580 | DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT, | |||
7581 | SDLoc(N), LegalOperations)) | |||
7582 | : NewLoad; | |||
7583 | return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad); | |||
7584 | } | |||
7585 | ||||
7586 | // If the target has andn, bsl, or a similar bit-select instruction, | |||
7587 | // we want to unfold masked merge, with canonical pattern of: | |||
7588 | // | A | |B| | |||
7589 | // ((x ^ y) & m) ^ y | |||
7590 | // | D | | |||
7591 | // Into: | |||
7592 | // (x & m) | (y & ~m) | |||
7593 | // If y is a constant, and the 'andn' does not work with immediates, | |||
7594 | // we unfold into a different pattern: | |||
7595 | // ~(~x & m) & (m | y) | |||
7596 | // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at | |||
7597 | // the very least that breaks andnpd / andnps patterns, and because those | |||
7598 | // patterns are simplified in IR and shouldn't be created in the DAG | |||
7599 | SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { | |||
7600 | assert(N->getOpcode() == ISD::XOR)((N->getOpcode() == ISD::XOR) ? static_cast<void> (0 ) : __assert_fail ("N->getOpcode() == ISD::XOR", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7600, __PRETTY_FUNCTION__)); | |||
7601 | ||||
7602 | // Don't touch 'not' (i.e. where y = -1). | |||
7603 | if (isAllOnesOrAllOnesSplat(N->getOperand(1))) | |||
7604 | return SDValue(); | |||
7605 | ||||
7606 | EVT VT = N->getValueType(0); | |||
7607 | ||||
7608 | // There are 3 commutable operators in the pattern, | |||
7609 | // so we have to deal with 8 possible variants of the basic pattern. | |||
7610 | SDValue X, Y, M; | |||
7611 | auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { | |||
7612 | if (And.getOpcode() != ISD::AND || !And.hasOneUse()) | |||
7613 | return false; | |||
7614 | SDValue Xor = And.getOperand(XorIdx); | |||
7615 | if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) | |||
7616 | return false; | |||
7617 | SDValue Xor0 = Xor.getOperand(0); | |||
7618 | SDValue Xor1 = Xor.getOperand(1); | |||
7619 | // Don't touch 'not' (i.e. where y = -1). | |||
7620 | if (isAllOnesOrAllOnesSplat(Xor1)) | |||
7621 | return false; | |||
7622 | if (Other == Xor0) | |||
7623 | std::swap(Xor0, Xor1); | |||
7624 | if (Other != Xor1) | |||
7625 | return false; | |||
7626 | X = Xor0; | |||
7627 | Y = Xor1; | |||
7628 | M = And.getOperand(XorIdx ? 0 : 1); | |||
7629 | return true; | |||
7630 | }; | |||
7631 | ||||
7632 | SDValue N0 = N->getOperand(0); | |||
7633 | SDValue N1 = N->getOperand(1); | |||
7634 | if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && | |||
7635 | !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) | |||
7636 | return SDValue(); | |||
7637 | ||||
7638 | // Don't do anything if the mask is constant. This should not be reachable. | |||
7639 | // InstCombine should have already unfolded this pattern, and DAGCombiner | |||
7640 | // probably shouldn't produce it, too. | |||
7641 | if (isa<ConstantSDNode>(M.getNode())) | |||
7642 | return SDValue(); | |||
7643 | ||||
7644 | // We can transform if the target has AndNot | |||
7645 | if (!TLI.hasAndNot(M)) | |||
7646 | return SDValue(); | |||
7647 | ||||
7648 | SDLoc DL(N); | |||
7649 | ||||
7650 | // If Y is a constant, check that 'andn' works with immediates. | |||
7651 | if (!TLI.hasAndNot(Y)) { | |||
7652 | assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.")((TLI.hasAndNot(X) && "Only mask is a variable? Unreachable." ) ? static_cast<void> (0) : __assert_fail ("TLI.hasAndNot(X) && \"Only mask is a variable? Unreachable.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7652, __PRETTY_FUNCTION__)); | |||
7653 | // If not, we need to do a bit more work to make sure andn is still used. | |||
7654 | SDValue NotX = DAG.getNOT(DL, X, VT); | |||
7655 | SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); | |||
7656 | SDValue NotLHS = DAG.getNOT(DL, LHS, VT); | |||
7657 | SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); | |||
7658 | return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); | |||
7659 | } | |||
7660 | ||||
7661 | SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); | |||
7662 | SDValue NotM = DAG.getNOT(DL, M, VT); | |||
7663 | SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); | |||
7664 | ||||
7665 | return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); | |||
7666 | } | |||
7667 | ||||
7668 | SDValue DAGCombiner::visitXOR(SDNode *N) { | |||
7669 | SDValue N0 = N->getOperand(0); | |||
7670 | SDValue N1 = N->getOperand(1); | |||
7671 | EVT VT = N0.getValueType(); | |||
7672 | ||||
7673 | // fold vector ops | |||
7674 | if (VT.isVector()) { | |||
7675 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
7676 | return FoldedVOp; | |||
7677 | ||||
7678 | // fold (xor x, 0) -> x, vector edition | |||
7679 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
7680 | return N1; | |||
7681 | if (ISD::isBuildVectorAllZeros(N1.getNode())) | |||
7682 | return N0; | |||
7683 | } | |||
7684 | ||||
7685 | // fold (xor undef, undef) -> 0. This is a common idiom (misuse). | |||
7686 | SDLoc DL(N); | |||
7687 | if (N0.isUndef() && N1.isUndef()) | |||
7688 | return DAG.getConstant(0, DL, VT); | |||
7689 | ||||
7690 | // fold (xor x, undef) -> undef | |||
7691 | if (N0.isUndef()) | |||
7692 | return N0; | |||
7693 | if (N1.isUndef()) | |||
7694 | return N1; | |||
7695 | ||||
7696 | // fold (xor c1, c2) -> c1^c2 | |||
7697 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1})) | |||
7698 | return C; | |||
7699 | ||||
7700 | // canonicalize constant to RHS | |||
7701 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
7702 | !DAG.isConstantIntBuildVectorOrConstantInt(N1)) | |||
7703 | return DAG.getNode(ISD::XOR, DL, VT, N1, N0); | |||
7704 | ||||
7705 | // fold (xor x, 0) -> x | |||
7706 | if (isNullConstant(N1)) | |||
7707 | return N0; | |||
7708 | ||||
7709 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
7710 | return NewSel; | |||
7711 | ||||
7712 | // reassociate xor | |||
7713 | if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags())) | |||
7714 | return RXOR; | |||
7715 | ||||
7716 | // fold !(x cc y) -> (x !cc y) | |||
7717 | unsigned N0Opcode = N0.getOpcode(); | |||
7718 | SDValue LHS, RHS, CC; | |||
7719 | if (TLI.isConstTrueVal(N1.getNode()) && | |||
7720 | isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/true)) { | |||
7721 | ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), | |||
7722 | LHS.getValueType()); | |||
7723 | if (!LegalOperations || | |||
7724 | TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { | |||
7725 | switch (N0Opcode) { | |||
7726 | default: | |||
7727 | llvm_unreachable("Unhandled SetCC Equivalent!")::llvm::llvm_unreachable_internal("Unhandled SetCC Equivalent!" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7727); | |||
7728 | case ISD::SETCC: | |||
7729 | return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); | |||
7730 | case ISD::SELECT_CC: | |||
7731 | return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), | |||
7732 | N0.getOperand(3), NotCC); | |||
7733 | case ISD::STRICT_FSETCC: | |||
7734 | case ISD::STRICT_FSETCCS: { | |||
7735 | if (N0.hasOneUse()) { | |||
7736 | // FIXME Can we handle multiple uses? Could we token factor the chain | |||
7737 | // results from the new/old setcc? | |||
7738 | SDValue SetCC = | |||
7739 | DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, | |||
7740 | N0.getOperand(0), N0Opcode == ISD::STRICT_FSETCCS); | |||
7741 | CombineTo(N, SetCC); | |||
7742 | DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1)); | |||
7743 | recursivelyDeleteUnusedNodes(N0.getNode()); | |||
7744 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
7745 | } | |||
7746 | break; | |||
7747 | } | |||
7748 | } | |||
7749 | } | |||
7750 | } | |||
7751 | ||||
7752 | // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) | |||
7753 | if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() && | |||
7754 | isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ | |||
7755 | SDValue V = N0.getOperand(0); | |||
7756 | SDLoc DL0(N0); | |||
7757 | V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V, | |||
7758 | DAG.getConstant(1, DL0, V.getValueType())); | |||
7759 | AddToWorklist(V.getNode()); | |||
7760 | return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V); | |||
7761 | } | |||
7762 | ||||
7763 | // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc | |||
7764 | if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && | |||
7765 | (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { | |||
7766 | SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); | |||
7767 | if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) { | |||
7768 | unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; | |||
7769 | N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 | |||
7770 | N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 | |||
7771 | AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); | |||
7772 | return DAG.getNode(NewOpcode, DL, VT, N00, N01); | |||
7773 | } | |||
7774 | } | |||
7775 | // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants | |||
7776 | if (isAllOnesConstant(N1) && N0.hasOneUse() && | |||
7777 | (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { | |||
7778 | SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); | |||
7779 | if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) { | |||
7780 | unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; | |||
7781 | N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 | |||
7782 | N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 | |||
7783 | AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); | |||
7784 | return DAG.getNode(NewOpcode, DL, VT, N00, N01); | |||
7785 | } | |||
7786 | } | |||
7787 | ||||
7788 | // fold (not (neg x)) -> (add X, -1) | |||
7789 | // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if | |||
7790 | // Y is a constant or the subtract has a single use. | |||
7791 | if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB && | |||
7792 | isNullConstant(N0.getOperand(0))) { | |||
7793 | return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), | |||
7794 | DAG.getAllOnesConstant(DL, VT)); | |||
7795 | } | |||
7796 | ||||
7797 | // fold (not (add X, -1)) -> (neg X) | |||
7798 | if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD && | |||
7799 | isAllOnesOrAllOnesSplat(N0.getOperand(1))) { | |||
7800 | return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), | |||
7801 | N0.getOperand(0)); | |||
7802 | } | |||
7803 | ||||
7804 | // fold (xor (and x, y), y) -> (and (not x), y) | |||
7805 | if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) { | |||
7806 | SDValue X = N0.getOperand(0); | |||
7807 | SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); | |||
7808 | AddToWorklist(NotX.getNode()); | |||
7809 | return DAG.getNode(ISD::AND, DL, VT, NotX, N1); | |||
7810 | } | |||
7811 | ||||
7812 | if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) { | |||
7813 | ConstantSDNode *XorC = isConstOrConstSplat(N1); | |||
7814 | ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1)); | |||
7815 | unsigned BitWidth = VT.getScalarSizeInBits(); | |||
7816 | if (XorC && ShiftC) { | |||
7817 | // Don't crash on an oversized shift. We can not guarantee that a bogus | |||
7818 | // shift has been simplified to undef. | |||
7819 | uint64_t ShiftAmt = ShiftC->getLimitedValue(); | |||
7820 | if (ShiftAmt < BitWidth) { | |||
7821 | APInt Ones = APInt::getAllOnesValue(BitWidth); | |||
7822 | Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt); | |||
7823 | if (XorC->getAPIntValue() == Ones) { | |||
7824 | // If the xor constant is a shifted -1, do a 'not' before the shift: | |||
7825 | // xor (X << ShiftC), XorC --> (not X) << ShiftC | |||
7826 | // xor (X >> ShiftC), XorC --> (not X) >> ShiftC | |||
7827 | SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT); | |||
7828 | return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1)); | |||
7829 | } | |||
7830 | } | |||
7831 | } | |||
7832 | } | |||
7833 | ||||
7834 | // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) | |||
7835 | if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { | |||
7836 | SDValue A = N0Opcode == ISD::ADD ? N0 : N1; | |||
7837 | SDValue S = N0Opcode == ISD::SRA ? N0 : N1; | |||
7838 | if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { | |||
7839 | SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); | |||
7840 | SDValue S0 = S.getOperand(0); | |||
7841 | if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) | |||
7842 | if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) | |||
7843 | if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) | |||
7844 | return DAG.getNode(ISD::ABS, DL, VT, S0); | |||
7845 | } | |||
7846 | } | |||
7847 | ||||
7848 | // fold (xor x, x) -> 0 | |||
7849 | if (N0 == N1) | |||
7850 | return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); | |||
7851 | ||||
7852 | // fold (xor (shl 1, x), -1) -> (rotl ~1, x) | |||
7853 | // Here is a concrete example of this equivalence: | |||
7854 | // i16 x == 14 | |||
7855 | // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 | |||
7856 | // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 | |||
7857 | // | |||
7858 | // => | |||
7859 | // | |||
7860 | // i16 ~1 == 0b1111111111111110 | |||
7861 | // i16 rol(~1, 14) == 0b1011111111111111 | |||
7862 | // | |||
7863 | // Some additional tips to help conceptualize this transform: | |||
7864 | // - Try to see the operation as placing a single zero in a value of all ones. | |||
7865 | // - There exists no value for x which would allow the result to contain zero. | |||
7866 | // - Values of x larger than the bitwidth are undefined and do not require a | |||
7867 | // consistent result. | |||
7868 | // - Pushing the zero left requires shifting one bits in from the right. | |||
7869 | // A rotate left of ~1 is a nice way of achieving the desired result. | |||
7870 | if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL && | |||
7871 | isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { | |||
7872 | return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), | |||
7873 | N0.getOperand(1)); | |||
7874 | } | |||
7875 | ||||
7876 | // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) | |||
7877 | if (N0Opcode == N1.getOpcode()) | |||
7878 | if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) | |||
7879 | return V; | |||
7880 | ||||
7881 | // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable | |||
7882 | if (SDValue MM = unfoldMaskedMerge(N)) | |||
7883 | return MM; | |||
7884 | ||||
7885 | // Simplify the expression using non-local knowledge. | |||
7886 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
7887 | return SDValue(N, 0); | |||
7888 | ||||
7889 | if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) | |||
7890 | return Combined; | |||
7891 | ||||
7892 | return SDValue(); | |||
7893 | } | |||
7894 | ||||
7895 | /// If we have a shift-by-constant of a bitwise logic op that itself has a | |||
7896 | /// shift-by-constant operand with identical opcode, we may be able to convert | |||
7897 | /// that into 2 independent shifts followed by the logic op. This is a | |||
7898 | /// throughput improvement. | |||
7899 | static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) { | |||
7900 | // Match a one-use bitwise logic op. | |||
7901 | SDValue LogicOp = Shift->getOperand(0); | |||
7902 | if (!LogicOp.hasOneUse()) | |||
7903 | return SDValue(); | |||
7904 | ||||
7905 | unsigned LogicOpcode = LogicOp.getOpcode(); | |||
7906 | if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR && | |||
7907 | LogicOpcode != ISD::XOR) | |||
7908 | return SDValue(); | |||
7909 | ||||
7910 | // Find a matching one-use shift by constant. | |||
7911 | unsigned ShiftOpcode = Shift->getOpcode(); | |||
7912 | SDValue C1 = Shift->getOperand(1); | |||
7913 | ConstantSDNode *C1Node = isConstOrConstSplat(C1); | |||
7914 | assert(C1Node && "Expected a shift with constant operand")((C1Node && "Expected a shift with constant operand") ? static_cast<void> (0) : __assert_fail ("C1Node && \"Expected a shift with constant operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7914, __PRETTY_FUNCTION__)); | |||
7915 | const APInt &C1Val = C1Node->getAPIntValue(); | |||
7916 | auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp, | |||
7917 | const APInt *&ShiftAmtVal) { | |||
7918 | if (V.getOpcode() != ShiftOpcode || !V.hasOneUse()) | |||
7919 | return false; | |||
7920 | ||||
7921 | ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1)); | |||
7922 | if (!ShiftCNode) | |||
7923 | return false; | |||
7924 | ||||
7925 | // Capture the shifted operand and shift amount value. | |||
7926 | ShiftOp = V.getOperand(0); | |||
7927 | ShiftAmtVal = &ShiftCNode->getAPIntValue(); | |||
7928 | ||||
7929 | // Shift amount types do not have to match their operand type, so check that | |||
7930 | // the constants are the same width. | |||
7931 | if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth()) | |||
7932 | return false; | |||
7933 | ||||
7934 | // The fold is not valid if the sum of the shift values exceeds bitwidth. | |||
7935 | if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits())) | |||
7936 | return false; | |||
7937 | ||||
7938 | return true; | |||
7939 | }; | |||
7940 | ||||
7941 | // Logic ops are commutative, so check each operand for a match. | |||
7942 | SDValue X, Y; | |||
7943 | const APInt *C0Val; | |||
7944 | if (matchFirstShift(LogicOp.getOperand(0), X, C0Val)) | |||
7945 | Y = LogicOp.getOperand(1); | |||
7946 | else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val)) | |||
7947 | Y = LogicOp.getOperand(0); | |||
7948 | else | |||
7949 | return SDValue(); | |||
7950 | ||||
7951 | // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1) | |||
7952 | SDLoc DL(Shift); | |||
7953 | EVT VT = Shift->getValueType(0); | |||
7954 | EVT ShiftAmtVT = Shift->getOperand(1).getValueType(); | |||
7955 | SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT); | |||
7956 | SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC); | |||
7957 | SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1); | |||
7958 | return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2); | |||
7959 | } | |||
7960 | ||||
7961 | /// Handle transforms common to the three shifts, when the shift amount is a | |||
7962 | /// constant. | |||
7963 | /// We are looking for: (shift being one of shl/sra/srl) | |||
7964 | /// shift (binop X, C0), C1 | |||
7965 | /// And want to transform into: | |||
7966 | /// binop (shift X, C1), (shift C0, C1) | |||
7967 | SDValue DAGCombiner::visitShiftByConstant(SDNode *N) { | |||
7968 | assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand")((isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand" ) ? static_cast<void> (0) : __assert_fail ("isConstOrConstSplat(N->getOperand(1)) && \"Expected constant operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 7968, __PRETTY_FUNCTION__)); | |||
7969 | ||||
7970 | // Do not turn a 'not' into a regular xor. | |||
7971 | if (isBitwiseNot(N->getOperand(0))) | |||
7972 | return SDValue(); | |||
7973 | ||||
7974 | // The inner binop must be one-use, since we want to replace it. | |||
7975 | SDValue LHS = N->getOperand(0); | |||
7976 | if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level)) | |||
7977 | return SDValue(); | |||
7978 | ||||
7979 | // TODO: This is limited to early combining because it may reveal regressions | |||
7980 | // otherwise. But since we just checked a target hook to see if this is | |||
7981 | // desirable, that should have filtered out cases where this interferes | |||
7982 | // with some other pattern matching. | |||
7983 | if (!LegalTypes) | |||
7984 | if (SDValue R = combineShiftOfShiftedLogic(N, DAG)) | |||
7985 | return R; | |||
7986 | ||||
7987 | // We want to pull some binops through shifts, so that we have (and (shift)) | |||
7988 | // instead of (shift (and)), likewise for add, or, xor, etc. This sort of | |||
7989 | // thing happens with address calculations, so it's important to canonicalize | |||
7990 | // it. | |||
7991 | switch (LHS.getOpcode()) { | |||
7992 | default: | |||
7993 | return SDValue(); | |||
7994 | case ISD::OR: | |||
7995 | case ISD::XOR: | |||
7996 | case ISD::AND: | |||
7997 | break; | |||
7998 | case ISD::ADD: | |||
7999 | if (N->getOpcode() != ISD::SHL) | |||
8000 | return SDValue(); // only shl(add) not sr[al](add). | |||
8001 | break; | |||
8002 | } | |||
8003 | ||||
8004 | // We require the RHS of the binop to be a constant and not opaque as well. | |||
8005 | ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS.getOperand(1)); | |||
8006 | if (!BinOpCst) | |||
8007 | return SDValue(); | |||
8008 | ||||
8009 | // FIXME: disable this unless the input to the binop is a shift by a constant | |||
8010 | // or is copy/select. Enable this in other cases when figure out it's exactly | |||
8011 | // profitable. | |||
8012 | SDValue BinOpLHSVal = LHS.getOperand(0); | |||
8013 | bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL || | |||
8014 | BinOpLHSVal.getOpcode() == ISD::SRA || | |||
8015 | BinOpLHSVal.getOpcode() == ISD::SRL) && | |||
8016 | isa<ConstantSDNode>(BinOpLHSVal.getOperand(1)); | |||
8017 | bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg || | |||
8018 | BinOpLHSVal.getOpcode() == ISD::SELECT; | |||
8019 | ||||
8020 | if (!IsShiftByConstant && !IsCopyOrSelect) | |||
8021 | return SDValue(); | |||
8022 | ||||
8023 | if (IsCopyOrSelect && N->hasOneUse()) | |||
8024 | return SDValue(); | |||
8025 | ||||
8026 | // Fold the constants, shifting the binop RHS by the shift amount. | |||
8027 | SDLoc DL(N); | |||
8028 | EVT VT = N->getValueType(0); | |||
8029 | SDValue NewRHS = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(1), | |||
8030 | N->getOperand(1)); | |||
8031 | assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!")((isa<ConstantSDNode>(NewRHS) && "Folding was not successful!" ) ? static_cast<void> (0) : __assert_fail ("isa<ConstantSDNode>(NewRHS) && \"Folding was not successful!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8031, __PRETTY_FUNCTION__)); | |||
8032 | ||||
8033 | SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0), | |||
8034 | N->getOperand(1)); | |||
8035 | return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS); | |||
8036 | } | |||
8037 | ||||
8038 | SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { | |||
8039 | assert(N->getOpcode() == ISD::TRUNCATE)((N->getOpcode() == ISD::TRUNCATE) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::TRUNCATE", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8039, __PRETTY_FUNCTION__)); | |||
8040 | assert(N->getOperand(0).getOpcode() == ISD::AND)((N->getOperand(0).getOpcode() == ISD::AND) ? static_cast< void> (0) : __assert_fail ("N->getOperand(0).getOpcode() == ISD::AND" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8040, __PRETTY_FUNCTION__)); | |||
8041 | ||||
8042 | // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) | |||
8043 | EVT TruncVT = N->getValueType(0); | |||
8044 | if (N->hasOneUse() && N->getOperand(0).hasOneUse() && | |||
8045 | TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) { | |||
8046 | SDValue N01 = N->getOperand(0).getOperand(1); | |||
8047 | if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { | |||
8048 | SDLoc DL(N); | |||
8049 | SDValue N00 = N->getOperand(0).getOperand(0); | |||
8050 | SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); | |||
8051 | SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); | |||
8052 | AddToWorklist(Trunc00.getNode()); | |||
8053 | AddToWorklist(Trunc01.getNode()); | |||
8054 | return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); | |||
8055 | } | |||
8056 | } | |||
8057 | ||||
8058 | return SDValue(); | |||
8059 | } | |||
8060 | ||||
8061 | SDValue DAGCombiner::visitRotate(SDNode *N) { | |||
8062 | SDLoc dl(N); | |||
8063 | SDValue N0 = N->getOperand(0); | |||
8064 | SDValue N1 = N->getOperand(1); | |||
8065 | EVT VT = N->getValueType(0); | |||
8066 | unsigned Bitsize = VT.getScalarSizeInBits(); | |||
8067 | ||||
8068 | // fold (rot x, 0) -> x | |||
8069 | if (isNullOrNullSplat(N1)) | |||
8070 | return N0; | |||
8071 | ||||
8072 | // fold (rot x, c) -> x iff (c % BitSize) == 0 | |||
8073 | if (isPowerOf2_32(Bitsize) && Bitsize > 1) { | |||
8074 | APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1); | |||
8075 | if (DAG.MaskedValueIsZero(N1, ModuloMask)) | |||
8076 | return N0; | |||
8077 | } | |||
8078 | ||||
8079 | // fold (rot x, c) -> (rot x, c % BitSize) | |||
8080 | bool OutOfRange = false; | |||
8081 | auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) { | |||
8082 | OutOfRange |= C->getAPIntValue().uge(Bitsize); | |||
8083 | return true; | |||
8084 | }; | |||
8085 | if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) { | |||
8086 | EVT AmtVT = N1.getValueType(); | |||
8087 | SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT); | |||
8088 | if (SDValue Amt = | |||
8089 | DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits})) | |||
8090 | return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt); | |||
8091 | } | |||
8092 | ||||
8093 | // rot i16 X, 8 --> bswap X | |||
8094 | auto *RotAmtC = isConstOrConstSplat(N1); | |||
8095 | if (RotAmtC && RotAmtC->getAPIntValue() == 8 && | |||
8096 | VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT)) | |||
8097 | return DAG.getNode(ISD::BSWAP, dl, VT, N0); | |||
8098 | ||||
8099 | // Simplify the operands using demanded-bits information. | |||
8100 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
8101 | return SDValue(N, 0); | |||
8102 | ||||
8103 | // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). | |||
8104 | if (N1.getOpcode() == ISD::TRUNCATE && | |||
8105 | N1.getOperand(0).getOpcode() == ISD::AND) { | |||
8106 | if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) | |||
8107 | return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); | |||
8108 | } | |||
8109 | ||||
8110 | unsigned NextOp = N0.getOpcode(); | |||
8111 | // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) | |||
8112 | if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { | |||
8113 | SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); | |||
8114 | SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); | |||
8115 | if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { | |||
8116 | EVT ShiftVT = C1->getValueType(0); | |||
8117 | bool SameSide = (N->getOpcode() == NextOp); | |||
8118 | unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; | |||
8119 | if (SDValue CombinedShift = DAG.FoldConstantArithmetic( | |||
8120 | CombineOp, dl, ShiftVT, {N1, N0.getOperand(1)})) { | |||
8121 | SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); | |||
8122 | SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( | |||
8123 | ISD::SREM, dl, ShiftVT, {CombinedShift, BitsizeC}); | |||
8124 | return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), | |||
8125 | CombinedShiftNorm); | |||
8126 | } | |||
8127 | } | |||
8128 | } | |||
8129 | return SDValue(); | |||
8130 | } | |||
8131 | ||||
8132 | SDValue DAGCombiner::visitSHL(SDNode *N) { | |||
8133 | SDValue N0 = N->getOperand(0); | |||
8134 | SDValue N1 = N->getOperand(1); | |||
8135 | if (SDValue V = DAG.simplifyShift(N0, N1)) | |||
8136 | return V; | |||
8137 | ||||
8138 | EVT VT = N0.getValueType(); | |||
8139 | EVT ShiftVT = N1.getValueType(); | |||
8140 | unsigned OpSizeInBits = VT.getScalarSizeInBits(); | |||
8141 | ||||
8142 | // fold vector ops | |||
8143 | if (VT.isVector()) { | |||
8144 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
8145 | return FoldedVOp; | |||
8146 | ||||
8147 | BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); | |||
8148 | // If setcc produces all-one true value then: | |||
8149 | // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) | |||
8150 | if (N1CV && N1CV->isConstant()) { | |||
8151 | if (N0.getOpcode() == ISD::AND) { | |||
8152 | SDValue N00 = N0->getOperand(0); | |||
8153 | SDValue N01 = N0->getOperand(1); | |||
8154 | BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); | |||
8155 | ||||
8156 | if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && | |||
8157 | TLI.getBooleanContents(N00.getOperand(0).getValueType()) == | |||
8158 | TargetLowering::ZeroOrNegativeOneBooleanContent) { | |||
8159 | if (SDValue C = | |||
8160 | DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1})) | |||
8161 | return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); | |||
8162 | } | |||
8163 | } | |||
8164 | } | |||
8165 | } | |||
8166 | ||||
8167 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
8168 | ||||
8169 | // fold (shl c1, c2) -> c1<<c2 | |||
8170 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1})) | |||
8171 | return C; | |||
8172 | ||||
8173 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
8174 | return NewSel; | |||
8175 | ||||
8176 | // if (shl x, c) is known to be zero, return 0 | |||
8177 | if (DAG.MaskedValueIsZero(SDValue(N, 0), | |||
8178 | APInt::getAllOnesValue(OpSizeInBits))) | |||
8179 | return DAG.getConstant(0, SDLoc(N), VT); | |||
8180 | ||||
8181 | // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). | |||
8182 | if (N1.getOpcode() == ISD::TRUNCATE && | |||
8183 | N1.getOperand(0).getOpcode() == ISD::AND) { | |||
8184 | if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) | |||
8185 | return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); | |||
8186 | } | |||
8187 | ||||
8188 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
8189 | return SDValue(N, 0); | |||
8190 | ||||
8191 | // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) | |||
8192 | if (N0.getOpcode() == ISD::SHL) { | |||
8193 | auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, | |||
8194 | ConstantSDNode *RHS) { | |||
8195 | APInt c1 = LHS->getAPIntValue(); | |||
8196 | APInt c2 = RHS->getAPIntValue(); | |||
8197 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8198 | return (c1 + c2).uge(OpSizeInBits); | |||
8199 | }; | |||
8200 | if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) | |||
8201 | return DAG.getConstant(0, SDLoc(N), VT); | |||
8202 | ||||
8203 | auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, | |||
8204 | ConstantSDNode *RHS) { | |||
8205 | APInt c1 = LHS->getAPIntValue(); | |||
8206 | APInt c2 = RHS->getAPIntValue(); | |||
8207 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8208 | return (c1 + c2).ult(OpSizeInBits); | |||
8209 | }; | |||
8210 | if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { | |||
8211 | SDLoc DL(N); | |||
8212 | SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); | |||
8213 | return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); | |||
8214 | } | |||
8215 | } | |||
8216 | ||||
8217 | // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2)) | |||
8218 | // For this to be valid, the second form must not preserve any of the bits | |||
8219 | // that are shifted out by the inner shift in the first form. This means | |||
8220 | // the outer shift size must be >= the number of bits added by the ext. | |||
8221 | // As a corollary, we don't care what kind of ext it is. | |||
8222 | if ((N0.getOpcode() == ISD::ZERO_EXTEND || | |||
8223 | N0.getOpcode() == ISD::ANY_EXTEND || | |||
8224 | N0.getOpcode() == ISD::SIGN_EXTEND) && | |||
8225 | N0.getOperand(0).getOpcode() == ISD::SHL) { | |||
8226 | SDValue N0Op0 = N0.getOperand(0); | |||
8227 | SDValue InnerShiftAmt = N0Op0.getOperand(1); | |||
8228 | EVT InnerVT = N0Op0.getValueType(); | |||
8229 | uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits(); | |||
8230 | ||||
8231 | auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, | |||
8232 | ConstantSDNode *RHS) { | |||
8233 | APInt c1 = LHS->getAPIntValue(); | |||
8234 | APInt c2 = RHS->getAPIntValue(); | |||
8235 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8236 | return c2.uge(OpSizeInBits - InnerBitwidth) && | |||
8237 | (c1 + c2).uge(OpSizeInBits); | |||
8238 | }; | |||
8239 | if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange, | |||
8240 | /*AllowUndefs*/ false, | |||
8241 | /*AllowTypeMismatch*/ true)) | |||
8242 | return DAG.getConstant(0, SDLoc(N), VT); | |||
8243 | ||||
8244 | auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, | |||
8245 | ConstantSDNode *RHS) { | |||
8246 | APInt c1 = LHS->getAPIntValue(); | |||
8247 | APInt c2 = RHS->getAPIntValue(); | |||
8248 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8249 | return c2.uge(OpSizeInBits - InnerBitwidth) && | |||
8250 | (c1 + c2).ult(OpSizeInBits); | |||
8251 | }; | |||
8252 | if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange, | |||
8253 | /*AllowUndefs*/ false, | |||
8254 | /*AllowTypeMismatch*/ true)) { | |||
8255 | SDLoc DL(N); | |||
8256 | SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0)); | |||
8257 | SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT); | |||
8258 | Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1); | |||
8259 | return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum); | |||
8260 | } | |||
8261 | } | |||
8262 | ||||
8263 | // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) | |||
8264 | // Only fold this if the inner zext has no other uses to avoid increasing | |||
8265 | // the total number of instructions. | |||
8266 | if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && | |||
8267 | N0.getOperand(0).getOpcode() == ISD::SRL) { | |||
8268 | SDValue N0Op0 = N0.getOperand(0); | |||
8269 | SDValue InnerShiftAmt = N0Op0.getOperand(1); | |||
8270 | ||||
8271 | auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) { | |||
8272 | APInt c1 = LHS->getAPIntValue(); | |||
8273 | APInt c2 = RHS->getAPIntValue(); | |||
8274 | zeroExtendToMatch(c1, c2); | |||
8275 | return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2); | |||
8276 | }; | |||
8277 | if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual, | |||
8278 | /*AllowUndefs*/ false, | |||
8279 | /*AllowTypeMismatch*/ true)) { | |||
8280 | SDLoc DL(N); | |||
8281 | EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType(); | |||
8282 | SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT); | |||
8283 | NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL); | |||
8284 | AddToWorklist(NewSHL.getNode()); | |||
8285 | return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); | |||
8286 | } | |||
8287 | } | |||
8288 | ||||
8289 | // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 | |||
8290 | // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 | |||
8291 | // TODO - support non-uniform vector shift amounts. | |||
8292 | if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && | |||
8293 | N0->getFlags().hasExact()) { | |||
8294 | if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { | |||
8295 | uint64_t C1 = N0C1->getZExtValue(); | |||
8296 | uint64_t C2 = N1C->getZExtValue(); | |||
8297 | SDLoc DL(N); | |||
8298 | if (C1 <= C2) | |||
8299 | return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), | |||
8300 | DAG.getConstant(C2 - C1, DL, ShiftVT)); | |||
8301 | return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), | |||
8302 | DAG.getConstant(C1 - C2, DL, ShiftVT)); | |||
8303 | } | |||
8304 | } | |||
8305 | ||||
8306 | // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or | |||
8307 | // (and (srl x, (sub c1, c2), MASK) | |||
8308 | // Only fold this if the inner shift has no other uses -- if it does, folding | |||
8309 | // this will increase the total number of instructions. | |||
8310 | // TODO - drop hasOneUse requirement if c1 == c2? | |||
8311 | // TODO - support non-uniform vector shift amounts. | |||
8312 | if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && | |||
8313 | TLI.shouldFoldConstantShiftPairToMask(N, Level)) { | |||
8314 | if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { | |||
8315 | if (N0C1->getAPIntValue().ult(OpSizeInBits)) { | |||
8316 | uint64_t c1 = N0C1->getZExtValue(); | |||
8317 | uint64_t c2 = N1C->getZExtValue(); | |||
8318 | APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); | |||
8319 | SDValue Shift; | |||
8320 | if (c2 > c1) { | |||
8321 | Mask <<= c2 - c1; | |||
8322 | SDLoc DL(N); | |||
8323 | Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), | |||
8324 | DAG.getConstant(c2 - c1, DL, ShiftVT)); | |||
8325 | } else { | |||
8326 | Mask.lshrInPlace(c1 - c2); | |||
8327 | SDLoc DL(N); | |||
8328 | Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), | |||
8329 | DAG.getConstant(c1 - c2, DL, ShiftVT)); | |||
8330 | } | |||
8331 | SDLoc DL(N0); | |||
8332 | return DAG.getNode(ISD::AND, DL, VT, Shift, | |||
8333 | DAG.getConstant(Mask, DL, VT)); | |||
8334 | } | |||
8335 | } | |||
8336 | } | |||
8337 | ||||
8338 | // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) | |||
8339 | if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && | |||
8340 | isConstantOrConstantVector(N1, /* No Opaques */ true)) { | |||
8341 | SDLoc DL(N); | |||
8342 | SDValue AllBits = DAG.getAllOnesConstant(DL, VT); | |||
8343 | SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); | |||
8344 | return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); | |||
8345 | } | |||
8346 | ||||
8347 | // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) | |||
8348 | // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) | |||
8349 | // Variant of version done on multiply, except mul by a power of 2 is turned | |||
8350 | // into a shift. | |||
8351 | if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && | |||
8352 | N0.getNode()->hasOneUse() && | |||
8353 | isConstantOrConstantVector(N1, /* No Opaques */ true) && | |||
8354 | isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && | |||
8355 | TLI.isDesirableToCommuteWithShift(N, Level)) { | |||
8356 | SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); | |||
8357 | SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); | |||
8358 | AddToWorklist(Shl0.getNode()); | |||
8359 | AddToWorklist(Shl1.getNode()); | |||
8360 | return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); | |||
8361 | } | |||
8362 | ||||
8363 | // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) | |||
8364 | if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && | |||
8365 | isConstantOrConstantVector(N1, /* No Opaques */ true) && | |||
8366 | isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { | |||
8367 | SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); | |||
8368 | if (isConstantOrConstantVector(Shl)) | |||
8369 | return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); | |||
8370 | } | |||
8371 | ||||
8372 | if (N1C && !N1C->isOpaque()) | |||
8373 | if (SDValue NewSHL = visitShiftByConstant(N)) | |||
8374 | return NewSHL; | |||
8375 | ||||
8376 | // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)). | |||
8377 | if (N0.getOpcode() == ISD::VSCALE) | |||
8378 | if (ConstantSDNode *NC1 = isConstOrConstSplat(N->getOperand(1))) { | |||
8379 | const APInt &C0 = N0.getConstantOperandAPInt(0); | |||
8380 | const APInt &C1 = NC1->getAPIntValue(); | |||
8381 | return DAG.getVScale(SDLoc(N), VT, C0 << C1); | |||
8382 | } | |||
8383 | ||||
8384 | return SDValue(); | |||
8385 | } | |||
8386 | ||||
8387 | // Transform a right shift of a multiply into a multiply-high. | |||
8388 | // Examples: | |||
8389 | // (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b) | |||
8390 | // (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b) | |||
8391 | static SDValue combineShiftToMULH(SDNode *N, SelectionDAG &DAG, | |||
8392 | const TargetLowering &TLI) { | |||
8393 | assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&(((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD:: SRA) && "SRL or SRA node is required here!") ? static_cast <void> (0) : __assert_fail ("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && \"SRL or SRA node is required here!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8394, __PRETTY_FUNCTION__)) | |||
8394 | "SRL or SRA node is required here!")(((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD:: SRA) && "SRL or SRA node is required here!") ? static_cast <void> (0) : __assert_fail ("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && \"SRL or SRA node is required here!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8394, __PRETTY_FUNCTION__)); | |||
8395 | ||||
8396 | // Check the shift amount. Proceed with the transformation if the shift | |||
8397 | // amount is constant. | |||
8398 | ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1)); | |||
8399 | if (!ShiftAmtSrc) | |||
8400 | return SDValue(); | |||
8401 | ||||
8402 | SDLoc DL(N); | |||
8403 | ||||
8404 | // The operation feeding into the shift must be a multiply. | |||
8405 | SDValue ShiftOperand = N->getOperand(0); | |||
8406 | if (ShiftOperand.getOpcode() != ISD::MUL) | |||
8407 | return SDValue(); | |||
8408 | ||||
8409 | // Both operands must be equivalent extend nodes. | |||
8410 | SDValue LeftOp = ShiftOperand.getOperand(0); | |||
8411 | SDValue RightOp = ShiftOperand.getOperand(1); | |||
8412 | bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND; | |||
8413 | bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND; | |||
8414 | ||||
8415 | if ((!(IsSignExt || IsZeroExt)) || LeftOp.getOpcode() != RightOp.getOpcode()) | |||
8416 | return SDValue(); | |||
8417 | ||||
8418 | EVT WideVT1 = LeftOp.getValueType(); | |||
8419 | EVT WideVT2 = RightOp.getValueType(); | |||
8420 | (void)WideVT2; | |||
8421 | // Proceed with the transformation if the wide types match. | |||
8422 | assert((WideVT1 == WideVT2) &&(((WideVT1 == WideVT2) && "Cannot have a multiply node with two different operand types." ) ? static_cast<void> (0) : __assert_fail ("(WideVT1 == WideVT2) && \"Cannot have a multiply node with two different operand types.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8423, __PRETTY_FUNCTION__)) | |||
8423 | "Cannot have a multiply node with two different operand types.")(((WideVT1 == WideVT2) && "Cannot have a multiply node with two different operand types." ) ? static_cast<void> (0) : __assert_fail ("(WideVT1 == WideVT2) && \"Cannot have a multiply node with two different operand types.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 8423, __PRETTY_FUNCTION__)); | |||
8424 | ||||
8425 | EVT NarrowVT = LeftOp.getOperand(0).getValueType(); | |||
8426 | // Check that the two extend nodes are the same type. | |||
8427 | if (NarrowVT != RightOp.getOperand(0).getValueType()) | |||
8428 | return SDValue(); | |||
8429 | ||||
8430 | // Proceed with the transformation if the wide type is twice as large | |||
8431 | // as the narrow type. | |||
8432 | unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits(); | |||
8433 | if (WideVT1.getScalarSizeInBits() != 2 * NarrowVTSize) | |||
8434 | return SDValue(); | |||
8435 | ||||
8436 | // Check the shift amount with the narrow type size. | |||
8437 | // Proceed with the transformation if the shift amount is the width | |||
8438 | // of the narrow type. | |||
8439 | unsigned ShiftAmt = ShiftAmtSrc->getZExtValue(); | |||
8440 | if (ShiftAmt != NarrowVTSize) | |||
8441 | return SDValue(); | |||
8442 | ||||
8443 | // If the operation feeding into the MUL is a sign extend (sext), | |||
8444 | // we use mulhs. Othewise, zero extends (zext) use mulhu. | |||
8445 | unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU; | |||
8446 | ||||
8447 | // Combine to mulh if mulh is legal/custom for the narrow type on the target. | |||
8448 | if (!TLI.isOperationLegalOrCustom(MulhOpcode, NarrowVT)) | |||
8449 | return SDValue(); | |||
8450 | ||||
8451 | SDValue Result = DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), | |||
8452 | RightOp.getOperand(0)); | |||
8453 | return (N->getOpcode() == ISD::SRA ? DAG.getSExtOrTrunc(Result, DL, WideVT1) | |||
8454 | : DAG.getZExtOrTrunc(Result, DL, WideVT1)); | |||
8455 | } | |||
8456 | ||||
8457 | SDValue DAGCombiner::visitSRA(SDNode *N) { | |||
8458 | SDValue N0 = N->getOperand(0); | |||
8459 | SDValue N1 = N->getOperand(1); | |||
8460 | if (SDValue V = DAG.simplifyShift(N0, N1)) | |||
8461 | return V; | |||
8462 | ||||
8463 | EVT VT = N0.getValueType(); | |||
8464 | unsigned OpSizeInBits = VT.getScalarSizeInBits(); | |||
8465 | ||||
8466 | // Arithmetic shifting an all-sign-bit value is a no-op. | |||
8467 | // fold (sra 0, x) -> 0 | |||
8468 | // fold (sra -1, x) -> -1 | |||
8469 | if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) | |||
8470 | return N0; | |||
8471 | ||||
8472 | // fold vector ops | |||
8473 | if (VT.isVector()) | |||
8474 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
8475 | return FoldedVOp; | |||
8476 | ||||
8477 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
8478 | ||||
8479 | // fold (sra c1, c2) -> (sra c1, c2) | |||
8480 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1})) | |||
8481 | return C; | |||
8482 | ||||
8483 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
8484 | return NewSel; | |||
8485 | ||||
8486 | // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports | |||
8487 | // sext_inreg. | |||
8488 | if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { | |||
8489 | unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); | |||
8490 | EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); | |||
8491 | if (VT.isVector()) | |||
8492 | ExtVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, | |||
8493 | VT.getVectorElementCount()); | |||
8494 | if (!LegalOperations || | |||
8495 | TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == | |||
8496 | TargetLowering::Legal) | |||
8497 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, | |||
8498 | N0.getOperand(0), DAG.getValueType(ExtVT)); | |||
8499 | // Even if we can't convert to sext_inreg, we might be able to remove | |||
8500 | // this shift pair if the input is already sign extended. | |||
8501 | if (DAG.ComputeNumSignBits(N0.getOperand(0)) > N1C->getZExtValue()) | |||
8502 | return N0.getOperand(0); | |||
8503 | } | |||
8504 | ||||
8505 | // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) | |||
8506 | // clamp (add c1, c2) to max shift. | |||
8507 | if (N0.getOpcode() == ISD::SRA) { | |||
8508 | SDLoc DL(N); | |||
8509 | EVT ShiftVT = N1.getValueType(); | |||
8510 | EVT ShiftSVT = ShiftVT.getScalarType(); | |||
8511 | SmallVector<SDValue, 16> ShiftValues; | |||
8512 | ||||
8513 | auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { | |||
8514 | APInt c1 = LHS->getAPIntValue(); | |||
8515 | APInt c2 = RHS->getAPIntValue(); | |||
8516 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8517 | APInt Sum = c1 + c2; | |||
8518 | unsigned ShiftSum = | |||
8519 | Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); | |||
8520 | ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); | |||
8521 | return true; | |||
8522 | }; | |||
8523 | if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { | |||
8524 | SDValue ShiftValue; | |||
8525 | if (VT.isVector()) | |||
8526 | ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); | |||
8527 | else | |||
8528 | ShiftValue = ShiftValues[0]; | |||
8529 | return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); | |||
8530 | } | |||
8531 | } | |||
8532 | ||||
8533 | // fold (sra (shl X, m), (sub result_size, n)) | |||
8534 | // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for | |||
8535 | // result_size - n != m. | |||
8536 | // If truncate is free for the target sext(shl) is likely to result in better | |||
8537 | // code. | |||
8538 | if (N0.getOpcode() == ISD::SHL && N1C) { | |||
8539 | // Get the two constanst of the shifts, CN0 = m, CN = n. | |||
8540 | const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); | |||
8541 | if (N01C) { | |||
8542 | LLVMContext &Ctx = *DAG.getContext(); | |||
8543 | // Determine what the truncate's result bitsize and type would be. | |||
8544 | EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); | |||
8545 | ||||
8546 | if (VT.isVector()) | |||
8547 | TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); | |||
8548 | ||||
8549 | // Determine the residual right-shift amount. | |||
8550 | int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); | |||
8551 | ||||
8552 | // If the shift is not a no-op (in which case this should be just a sign | |||
8553 | // extend already), the truncated to type is legal, sign_extend is legal | |||
8554 | // on that type, and the truncate to that type is both legal and free, | |||
8555 | // perform the transform. | |||
8556 | if ((ShiftAmt > 0) && | |||
8557 | TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && | |||
8558 | TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && | |||
8559 | TLI.isTruncateFree(VT, TruncVT)) { | |||
8560 | SDLoc DL(N); | |||
8561 | SDValue Amt = DAG.getConstant(ShiftAmt, DL, | |||
8562 | getShiftAmountTy(N0.getOperand(0).getValueType())); | |||
8563 | SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, | |||
8564 | N0.getOperand(0), Amt); | |||
8565 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, | |||
8566 | Shift); | |||
8567 | return DAG.getNode(ISD::SIGN_EXTEND, DL, | |||
8568 | N->getValueType(0), Trunc); | |||
8569 | } | |||
8570 | } | |||
8571 | } | |||
8572 | ||||
8573 | // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper. | |||
8574 | // sra (add (shl X, N1C), AddC), N1C --> | |||
8575 | // sext (add (trunc X to (width - N1C)), AddC') | |||
8576 | if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C && | |||
8577 | N0.getOperand(0).getOpcode() == ISD::SHL && | |||
8578 | N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) { | |||
8579 | if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) { | |||
8580 | SDValue Shl = N0.getOperand(0); | |||
8581 | // Determine what the truncate's type would be and ask the target if that | |||
8582 | // is a free operation. | |||
8583 | LLVMContext &Ctx = *DAG.getContext(); | |||
8584 | unsigned ShiftAmt = N1C->getZExtValue(); | |||
8585 | EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt); | |||
8586 | if (VT.isVector()) | |||
8587 | TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); | |||
8588 | ||||
8589 | // TODO: The simple type check probably belongs in the default hook | |||
8590 | // implementation and/or target-specific overrides (because | |||
8591 | // non-simple types likely require masking when legalized), but that | |||
8592 | // restriction may conflict with other transforms. | |||
8593 | if (TruncVT.isSimple() && isTypeLegal(TruncVT) && | |||
8594 | TLI.isTruncateFree(VT, TruncVT)) { | |||
8595 | SDLoc DL(N); | |||
8596 | SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT); | |||
8597 | SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt). | |||
8598 | trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT); | |||
8599 | SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC); | |||
8600 | return DAG.getSExtOrTrunc(Add, DL, VT); | |||
8601 | } | |||
8602 | } | |||
8603 | } | |||
8604 | ||||
8605 | // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). | |||
8606 | if (N1.getOpcode() == ISD::TRUNCATE && | |||
8607 | N1.getOperand(0).getOpcode() == ISD::AND) { | |||
8608 | if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) | |||
8609 | return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); | |||
8610 | } | |||
8611 | ||||
8612 | // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2)) | |||
8613 | // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) | |||
8614 | // if c1 is equal to the number of bits the trunc removes | |||
8615 | // TODO - support non-uniform vector shift amounts. | |||
8616 | if (N0.getOpcode() == ISD::TRUNCATE && | |||
8617 | (N0.getOperand(0).getOpcode() == ISD::SRL || | |||
8618 | N0.getOperand(0).getOpcode() == ISD::SRA) && | |||
8619 | N0.getOperand(0).hasOneUse() && | |||
8620 | N0.getOperand(0).getOperand(1).hasOneUse() && N1C) { | |||
8621 | SDValue N0Op0 = N0.getOperand(0); | |||
8622 | if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { | |||
8623 | EVT LargeVT = N0Op0.getValueType(); | |||
8624 | unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits; | |||
8625 | if (LargeShift->getAPIntValue() == TruncBits) { | |||
8626 | SDLoc DL(N); | |||
8627 | SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL, | |||
8628 | getShiftAmountTy(LargeVT)); | |||
8629 | SDValue SRA = | |||
8630 | DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt); | |||
8631 | return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); | |||
8632 | } | |||
8633 | } | |||
8634 | } | |||
8635 | ||||
8636 | // Simplify, based on bits shifted out of the LHS. | |||
8637 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
8638 | return SDValue(N, 0); | |||
8639 | ||||
8640 | // If the sign bit is known to be zero, switch this to a SRL. | |||
8641 | if (DAG.SignBitIsZero(N0)) | |||
8642 | return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); | |||
8643 | ||||
8644 | if (N1C && !N1C->isOpaque()) | |||
8645 | if (SDValue NewSRA = visitShiftByConstant(N)) | |||
8646 | return NewSRA; | |||
8647 | ||||
8648 | // Try to transform this shift into a multiply-high if | |||
8649 | // it matches the appropriate pattern detected in combineShiftToMULH. | |||
8650 | if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) | |||
8651 | return MULH; | |||
8652 | ||||
8653 | return SDValue(); | |||
8654 | } | |||
8655 | ||||
8656 | SDValue DAGCombiner::visitSRL(SDNode *N) { | |||
8657 | SDValue N0 = N->getOperand(0); | |||
8658 | SDValue N1 = N->getOperand(1); | |||
8659 | if (SDValue V = DAG.simplifyShift(N0, N1)) | |||
8660 | return V; | |||
8661 | ||||
8662 | EVT VT = N0.getValueType(); | |||
8663 | unsigned OpSizeInBits = VT.getScalarSizeInBits(); | |||
8664 | ||||
8665 | // fold vector ops | |||
8666 | if (VT.isVector()) | |||
8667 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
8668 | return FoldedVOp; | |||
8669 | ||||
8670 | ConstantSDNode *N1C = isConstOrConstSplat(N1); | |||
8671 | ||||
8672 | // fold (srl c1, c2) -> c1 >>u c2 | |||
8673 | if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1})) | |||
8674 | return C; | |||
8675 | ||||
8676 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
8677 | return NewSel; | |||
8678 | ||||
8679 | // if (srl x, c) is known to be zero, return 0 | |||
8680 | if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), | |||
8681 | APInt::getAllOnesValue(OpSizeInBits))) | |||
8682 | return DAG.getConstant(0, SDLoc(N), VT); | |||
8683 | ||||
8684 | // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) | |||
8685 | if (N0.getOpcode() == ISD::SRL) { | |||
8686 | auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, | |||
8687 | ConstantSDNode *RHS) { | |||
8688 | APInt c1 = LHS->getAPIntValue(); | |||
8689 | APInt c2 = RHS->getAPIntValue(); | |||
8690 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8691 | return (c1 + c2).uge(OpSizeInBits); | |||
8692 | }; | |||
8693 | if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) | |||
8694 | return DAG.getConstant(0, SDLoc(N), VT); | |||
8695 | ||||
8696 | auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, | |||
8697 | ConstantSDNode *RHS) { | |||
8698 | APInt c1 = LHS->getAPIntValue(); | |||
8699 | APInt c2 = RHS->getAPIntValue(); | |||
8700 | zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); | |||
8701 | return (c1 + c2).ult(OpSizeInBits); | |||
8702 | }; | |||
8703 | if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { | |||
8704 | SDLoc DL(N); | |||
8705 | EVT ShiftVT = N1.getValueType(); | |||
8706 | SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); | |||
8707 | return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); | |||
8708 | } | |||
8709 | } | |||
8710 | ||||
8711 | if (N1C && N0.getOpcode() == ISD::TRUNCATE && | |||
8712 | N0.getOperand(0).getOpcode() == ISD::SRL) { | |||
8713 | SDValue InnerShift = N0.getOperand(0); | |||
8714 | // TODO - support non-uniform vector shift amounts. | |||
8715 | if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) { | |||
8716 | uint64_t c1 = N001C->getZExtValue(); | |||
8717 | uint64_t c2 = N1C->getZExtValue(); | |||
8718 | EVT InnerShiftVT = InnerShift.getValueType(); | |||
8719 | EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType(); | |||
8720 | uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); | |||
8721 | // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2))) | |||
8722 | // This is only valid if the OpSizeInBits + c1 = size of inner shift. | |||
8723 | if (c1 + OpSizeInBits == InnerShiftSize) { | |||
8724 | SDLoc DL(N); | |||
8725 | if (c1 + c2 >= InnerShiftSize) | |||
8726 | return DAG.getConstant(0, DL, VT); | |||
8727 | SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); | |||
8728 | SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, | |||
8729 | InnerShift.getOperand(0), NewShiftAmt); | |||
8730 | return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift); | |||
8731 | } | |||
8732 | // In the more general case, we can clear the high bits after the shift: | |||
8733 | // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask) | |||
8734 | if (N0.hasOneUse() && InnerShift.hasOneUse() && | |||
8735 | c1 + c2 < InnerShiftSize) { | |||
8736 | SDLoc DL(N); | |||
8737 | SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); | |||
8738 | SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, | |||
8739 | InnerShift.getOperand(0), NewShiftAmt); | |||
8740 | SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize, | |||
8741 | OpSizeInBits - c2), | |||
8742 | DL, InnerShiftVT); | |||
8743 | SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask); | |||
8744 | return DAG.getNode(ISD::TRUNCATE, DL, VT, And); | |||
8745 | } | |||
8746 | } | |||
8747 | } | |||
8748 | ||||
8749 | // fold (srl (shl x, c), c) -> (and x, cst2) | |||
8750 | // TODO - (srl (shl x, c1), c2). | |||
8751 | if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && | |||
8752 | isConstantOrConstantVector(N1, /* NoOpaques */ true)) { | |||
8753 | SDLoc DL(N); | |||
8754 | SDValue Mask = | |||
8755 | DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); | |||
8756 | AddToWorklist(Mask.getNode()); | |||
8757 | return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); | |||
8758 | } | |||
8759 | ||||
8760 | // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) | |||
8761 | // TODO - support non-uniform vector shift amounts. | |||
8762 | if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { | |||
8763 | // Shifting in all undef bits? | |||
8764 | EVT SmallVT = N0.getOperand(0).getValueType(); | |||
8765 | unsigned BitSize = SmallVT.getScalarSizeInBits(); | |||
8766 | if (N1C->getAPIntValue().uge(BitSize)) | |||
8767 | return DAG.getUNDEF(VT); | |||
8768 | ||||
8769 | if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { | |||
8770 | uint64_t ShiftAmt = N1C->getZExtValue(); | |||
8771 | SDLoc DL0(N0); | |||
8772 | SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, | |||
8773 | N0.getOperand(0), | |||
8774 | DAG.getConstant(ShiftAmt, DL0, | |||
8775 | getShiftAmountTy(SmallVT))); | |||
8776 | AddToWorklist(SmallShift.getNode()); | |||
8777 | APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); | |||
8778 | SDLoc DL(N); | |||
8779 | return DAG.getNode(ISD::AND, DL, VT, | |||
8780 | DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), | |||
8781 | DAG.getConstant(Mask, DL, VT)); | |||
8782 | } | |||
8783 | } | |||
8784 | ||||
8785 | // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign | |||
8786 | // bit, which is unmodified by sra. | |||
8787 | if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) { | |||
8788 | if (N0.getOpcode() == ISD::SRA) | |||
8789 | return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); | |||
8790 | } | |||
8791 | ||||
8792 | // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). | |||
8793 | if (N1C && N0.getOpcode() == ISD::CTLZ && | |||
8794 | N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { | |||
8795 | KnownBits Known = DAG.computeKnownBits(N0.getOperand(0)); | |||
8796 | ||||
8797 | // If any of the input bits are KnownOne, then the input couldn't be all | |||
8798 | // zeros, thus the result of the srl will always be zero. | |||
8799 | if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); | |||
8800 | ||||
8801 | // If all of the bits input the to ctlz node are known to be zero, then | |||
8802 | // the result of the ctlz is "32" and the result of the shift is one. | |||
8803 | APInt UnknownBits = ~Known.Zero; | |||
8804 | if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); | |||
8805 | ||||
8806 | // Otherwise, check to see if there is exactly one bit input to the ctlz. | |||
8807 | if (UnknownBits.isPowerOf2()) { | |||
8808 | // Okay, we know that only that the single bit specified by UnknownBits | |||
8809 | // could be set on input to the CTLZ node. If this bit is set, the SRL | |||
8810 | // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair | |||
8811 | // to an SRL/XOR pair, which is likely to simplify more. | |||
8812 | unsigned ShAmt = UnknownBits.countTrailingZeros(); | |||
8813 | SDValue Op = N0.getOperand(0); | |||
8814 | ||||
8815 | if (ShAmt) { | |||
8816 | SDLoc DL(N0); | |||
8817 | Op = DAG.getNode(ISD::SRL, DL, VT, Op, | |||
8818 | DAG.getConstant(ShAmt, DL, | |||
8819 | getShiftAmountTy(Op.getValueType()))); | |||
8820 | AddToWorklist(Op.getNode()); | |||
8821 | } | |||
8822 | ||||
8823 | SDLoc DL(N); | |||
8824 | return DAG.getNode(ISD::XOR, DL, VT, | |||
8825 | Op, DAG.getConstant(1, DL, VT)); | |||
8826 | } | |||
8827 | } | |||
8828 | ||||
8829 | // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). | |||
8830 | if (N1.getOpcode() == ISD::TRUNCATE && | |||
8831 | N1.getOperand(0).getOpcode() == ISD::AND) { | |||
8832 | if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) | |||
8833 | return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); | |||
8834 | } | |||
8835 | ||||
8836 | // fold operands of srl based on knowledge that the low bits are not | |||
8837 | // demanded. | |||
8838 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
8839 | return SDValue(N, 0); | |||
8840 | ||||
8841 | if (N1C && !N1C->isOpaque()) | |||
8842 | if (SDValue NewSRL = visitShiftByConstant(N)) | |||
8843 | return NewSRL; | |||
8844 | ||||
8845 | // Attempt to convert a srl of a load into a narrower zero-extending load. | |||
8846 | if (SDValue NarrowLoad = ReduceLoadWidth(N)) | |||
8847 | return NarrowLoad; | |||
8848 | ||||
8849 | // Here is a common situation. We want to optimize: | |||
8850 | // | |||
8851 | // %a = ... | |||
8852 | // %b = and i32 %a, 2 | |||
8853 | // %c = srl i32 %b, 1 | |||
8854 | // brcond i32 %c ... | |||
8855 | // | |||
8856 | // into | |||
8857 | // | |||
8858 | // %a = ... | |||
8859 | // %b = and %a, 2 | |||
8860 | // %c = setcc eq %b, 0 | |||
8861 | // brcond %c ... | |||
8862 | // | |||
8863 | // However when after the source operand of SRL is optimized into AND, the SRL | |||
8864 | // itself may not be optimized further. Look for it and add the BRCOND into | |||
8865 | // the worklist. | |||
8866 | if (N->hasOneUse()) { | |||
8867 | SDNode *Use = *N->use_begin(); | |||
8868 | if (Use->getOpcode() == ISD::BRCOND) | |||
8869 | AddToWorklist(Use); | |||
8870 | else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { | |||
8871 | // Also look pass the truncate. | |||
8872 | Use = *Use->use_begin(); | |||
8873 | if (Use->getOpcode() == ISD::BRCOND) | |||
8874 | AddToWorklist(Use); | |||
8875 | } | |||
8876 | } | |||
8877 | ||||
8878 | // Try to transform this shift into a multiply-high if | |||
8879 | // it matches the appropriate pattern detected in combineShiftToMULH. | |||
8880 | if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) | |||
8881 | return MULH; | |||
8882 | ||||
8883 | return SDValue(); | |||
8884 | } | |||
8885 | ||||
8886 | SDValue DAGCombiner::visitFunnelShift(SDNode *N) { | |||
8887 | EVT VT = N->getValueType(0); | |||
8888 | SDValue N0 = N->getOperand(0); | |||
8889 | SDValue N1 = N->getOperand(1); | |||
8890 | SDValue N2 = N->getOperand(2); | |||
8891 | bool IsFSHL = N->getOpcode() == ISD::FSHL; | |||
8892 | unsigned BitWidth = VT.getScalarSizeInBits(); | |||
8893 | ||||
8894 | // fold (fshl N0, N1, 0) -> N0 | |||
8895 | // fold (fshr N0, N1, 0) -> N1 | |||
8896 | if (isPowerOf2_32(BitWidth)) | |||
8897 | if (DAG.MaskedValueIsZero( | |||
8898 | N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1))) | |||
8899 | return IsFSHL ? N0 : N1; | |||
8900 | ||||
8901 | auto IsUndefOrZero = [](SDValue V) { | |||
8902 | return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true); | |||
8903 | }; | |||
8904 | ||||
8905 | // TODO - support non-uniform vector shift amounts. | |||
8906 | if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) { | |||
8907 | EVT ShAmtTy = N2.getValueType(); | |||
8908 | ||||
8909 | // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth) | |||
8910 | if (Cst->getAPIntValue().uge(BitWidth)) { | |||
8911 | uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth); | |||
8912 | return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1, | |||
8913 | DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy)); | |||
8914 | } | |||
8915 | ||||
8916 | unsigned ShAmt = Cst->getZExtValue(); | |||
8917 | if (ShAmt == 0) | |||
8918 | return IsFSHL ? N0 : N1; | |||
8919 | ||||
8920 | // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C) | |||
8921 | // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C) | |||
8922 | // fold fshl(N0, undef_or_zero, C) -> shl(N0, C) | |||
8923 | // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C) | |||
8924 | if (IsUndefOrZero(N0)) | |||
8925 | return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, | |||
8926 | DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, | |||
8927 | SDLoc(N), ShAmtTy)); | |||
8928 | if (IsUndefOrZero(N1)) | |||
8929 | return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, | |||
8930 | DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, | |||
8931 | SDLoc(N), ShAmtTy)); | |||
8932 | ||||
8933 | // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. | |||
8934 | // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. | |||
8935 | // TODO - bigendian support once we have test coverage. | |||
8936 | // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine? | |||
8937 | // TODO - permit LHS EXTLOAD if extensions are shifted out. | |||
8938 | if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() && | |||
8939 | !DAG.getDataLayout().isBigEndian()) { | |||
8940 | auto *LHS = dyn_cast<LoadSDNode>(N0); | |||
8941 | auto *RHS = dyn_cast<LoadSDNode>(N1); | |||
8942 | if (LHS && RHS && LHS->isSimple() && RHS->isSimple() && | |||
8943 | LHS->getAddressSpace() == RHS->getAddressSpace() && | |||
8944 | (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) && | |||
8945 | ISD::isNON_EXTLoad(LHS)) { | |||
8946 | if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) { | |||
8947 | SDLoc DL(RHS); | |||
8948 | uint64_t PtrOff = | |||
8949 | IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8); | |||
8950 | Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff); | |||
8951 | bool Fast = false; | |||
8952 | if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, | |||
8953 | RHS->getAddressSpace(), NewAlign, | |||
8954 | RHS->getMemOperand()->getFlags(), &Fast) && | |||
8955 | Fast) { | |||
8956 | SDValue NewPtr = DAG.getMemBasePlusOffset( | |||
8957 | RHS->getBasePtr(), TypeSize::Fixed(PtrOff), DL); | |||
8958 | AddToWorklist(NewPtr.getNode()); | |||
8959 | SDValue Load = DAG.getLoad( | |||
8960 | VT, DL, RHS->getChain(), NewPtr, | |||
8961 | RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign, | |||
8962 | RHS->getMemOperand()->getFlags(), RHS->getAAInfo()); | |||
8963 | // Replace the old load's chain with the new load's chain. | |||
8964 | WorklistRemover DeadNodes(*this); | |||
8965 | DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1)); | |||
8966 | return Load; | |||
8967 | } | |||
8968 | } | |||
8969 | } | |||
8970 | } | |||
8971 | } | |||
8972 | ||||
8973 | // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2) | |||
8974 | // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2) | |||
8975 | // iff We know the shift amount is in range. | |||
8976 | // TODO: when is it worth doing SUB(BW, N2) as well? | |||
8977 | if (isPowerOf2_32(BitWidth)) { | |||
8978 | APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1); | |||
8979 | if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) | |||
8980 | return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2); | |||
8981 | if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) | |||
8982 | return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2); | |||
8983 | } | |||
8984 | ||||
8985 | // fold (fshl N0, N0, N2) -> (rotl N0, N2) | |||
8986 | // fold (fshr N0, N0, N2) -> (rotr N0, N2) | |||
8987 | // TODO: Investigate flipping this rotate if only one is legal, if funnel shift | |||
8988 | // is legal as well we might be better off avoiding non-constant (BW - N2). | |||
8989 | unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR; | |||
8990 | if (N0 == N1 && hasOperation(RotOpc, VT)) | |||
8991 | return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2); | |||
8992 | ||||
8993 | // Simplify, based on bits shifted out of N0/N1. | |||
8994 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
8995 | return SDValue(N, 0); | |||
8996 | ||||
8997 | return SDValue(); | |||
8998 | } | |||
8999 | ||||
9000 | SDValue DAGCombiner::visitABS(SDNode *N) { | |||
9001 | SDValue N0 = N->getOperand(0); | |||
9002 | EVT VT = N->getValueType(0); | |||
9003 | ||||
9004 | // fold (abs c1) -> c2 | |||
9005 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9006 | return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); | |||
9007 | // fold (abs (abs x)) -> (abs x) | |||
9008 | if (N0.getOpcode() == ISD::ABS) | |||
9009 | return N0; | |||
9010 | // fold (abs x) -> x iff not-negative | |||
9011 | if (DAG.SignBitIsZero(N0)) | |||
9012 | return N0; | |||
9013 | return SDValue(); | |||
9014 | } | |||
9015 | ||||
9016 | SDValue DAGCombiner::visitBSWAP(SDNode *N) { | |||
9017 | SDValue N0 = N->getOperand(0); | |||
9018 | EVT VT = N->getValueType(0); | |||
9019 | ||||
9020 | // fold (bswap c1) -> c2 | |||
9021 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9022 | return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); | |||
9023 | // fold (bswap (bswap x)) -> x | |||
9024 | if (N0.getOpcode() == ISD::BSWAP) | |||
9025 | return N0->getOperand(0); | |||
9026 | return SDValue(); | |||
9027 | } | |||
9028 | ||||
9029 | SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { | |||
9030 | SDValue N0 = N->getOperand(0); | |||
9031 | EVT VT = N->getValueType(0); | |||
9032 | ||||
9033 | // fold (bitreverse c1) -> c2 | |||
9034 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9035 | return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); | |||
9036 | // fold (bitreverse (bitreverse x)) -> x | |||
9037 | if (N0.getOpcode() == ISD::BITREVERSE) | |||
9038 | return N0.getOperand(0); | |||
9039 | return SDValue(); | |||
9040 | } | |||
9041 | ||||
9042 | SDValue DAGCombiner::visitCTLZ(SDNode *N) { | |||
9043 | SDValue N0 = N->getOperand(0); | |||
9044 | EVT VT = N->getValueType(0); | |||
9045 | ||||
9046 | // fold (ctlz c1) -> c2 | |||
9047 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9048 | return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); | |||
9049 | ||||
9050 | // If the value is known never to be zero, switch to the undef version. | |||
9051 | if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { | |||
9052 | if (DAG.isKnownNeverZero(N0)) | |||
9053 | return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); | |||
9054 | } | |||
9055 | ||||
9056 | return SDValue(); | |||
9057 | } | |||
9058 | ||||
9059 | SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { | |||
9060 | SDValue N0 = N->getOperand(0); | |||
9061 | EVT VT = N->getValueType(0); | |||
9062 | ||||
9063 | // fold (ctlz_zero_undef c1) -> c2 | |||
9064 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9065 | return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); | |||
9066 | return SDValue(); | |||
9067 | } | |||
9068 | ||||
9069 | SDValue DAGCombiner::visitCTTZ(SDNode *N) { | |||
9070 | SDValue N0 = N->getOperand(0); | |||
9071 | EVT VT = N->getValueType(0); | |||
9072 | ||||
9073 | // fold (cttz c1) -> c2 | |||
9074 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9075 | return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); | |||
9076 | ||||
9077 | // If the value is known never to be zero, switch to the undef version. | |||
9078 | if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { | |||
9079 | if (DAG.isKnownNeverZero(N0)) | |||
9080 | return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); | |||
9081 | } | |||
9082 | ||||
9083 | return SDValue(); | |||
9084 | } | |||
9085 | ||||
9086 | SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { | |||
9087 | SDValue N0 = N->getOperand(0); | |||
9088 | EVT VT = N->getValueType(0); | |||
9089 | ||||
9090 | // fold (cttz_zero_undef c1) -> c2 | |||
9091 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9092 | return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); | |||
9093 | return SDValue(); | |||
9094 | } | |||
9095 | ||||
9096 | SDValue DAGCombiner::visitCTPOP(SDNode *N) { | |||
9097 | SDValue N0 = N->getOperand(0); | |||
9098 | EVT VT = N->getValueType(0); | |||
9099 | ||||
9100 | // fold (ctpop c1) -> c2 | |||
9101 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
9102 | return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); | |||
9103 | return SDValue(); | |||
9104 | } | |||
9105 | ||||
9106 | // FIXME: This should be checking for no signed zeros on individual operands, as | |||
9107 | // well as no nans. | |||
9108 | static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, | |||
9109 | SDValue RHS, | |||
9110 | const TargetLowering &TLI) { | |||
9111 | const TargetOptions &Options = DAG.getTarget().Options; | |||
9112 | EVT VT = LHS.getValueType(); | |||
9113 | ||||
9114 | return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && | |||
9115 | TLI.isProfitableToCombineMinNumMaxNum(VT) && | |||
9116 | DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); | |||
9117 | } | |||
9118 | ||||
9119 | /// Generate Min/Max node | |||
9120 | static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, | |||
9121 | SDValue RHS, SDValue True, SDValue False, | |||
9122 | ISD::CondCode CC, const TargetLowering &TLI, | |||
9123 | SelectionDAG &DAG) { | |||
9124 | if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) | |||
9125 | return SDValue(); | |||
9126 | ||||
9127 | EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); | |||
9128 | switch (CC) { | |||
9129 | case ISD::SETOLT: | |||
9130 | case ISD::SETOLE: | |||
9131 | case ISD::SETLT: | |||
9132 | case ISD::SETLE: | |||
9133 | case ISD::SETULT: | |||
9134 | case ISD::SETULE: { | |||
9135 | // Since it's known never nan to get here already, either fminnum or | |||
9136 | // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is | |||
9137 | // expanded in terms of it. | |||
9138 | unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; | |||
9139 | if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) | |||
9140 | return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); | |||
9141 | ||||
9142 | unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; | |||
9143 | if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) | |||
9144 | return DAG.getNode(Opcode, DL, VT, LHS, RHS); | |||
9145 | return SDValue(); | |||
9146 | } | |||
9147 | case ISD::SETOGT: | |||
9148 | case ISD::SETOGE: | |||
9149 | case ISD::SETGT: | |||
9150 | case ISD::SETGE: | |||
9151 | case ISD::SETUGT: | |||
9152 | case ISD::SETUGE: { | |||
9153 | unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; | |||
9154 | if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) | |||
9155 | return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); | |||
9156 | ||||
9157 | unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; | |||
9158 | if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) | |||
9159 | return DAG.getNode(Opcode, DL, VT, LHS, RHS); | |||
9160 | return SDValue(); | |||
9161 | } | |||
9162 | default: | |||
9163 | return SDValue(); | |||
9164 | } | |||
9165 | } | |||
9166 | ||||
9167 | /// If a (v)select has a condition value that is a sign-bit test, try to smear | |||
9168 | /// the condition operand sign-bit across the value width and use it as a mask. | |||
9169 | static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) { | |||
9170 | SDValue Cond = N->getOperand(0); | |||
9171 | SDValue C1 = N->getOperand(1); | |||
9172 | SDValue C2 = N->getOperand(2); | |||
9173 | assert(isConstantOrConstantVector(C1) && isConstantOrConstantVector(C2) &&((isConstantOrConstantVector(C1) && isConstantOrConstantVector (C2) && "Expected select-of-constants") ? static_cast <void> (0) : __assert_fail ("isConstantOrConstantVector(C1) && isConstantOrConstantVector(C2) && \"Expected select-of-constants\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9174, __PRETTY_FUNCTION__)) | |||
9174 | "Expected select-of-constants")((isConstantOrConstantVector(C1) && isConstantOrConstantVector (C2) && "Expected select-of-constants") ? static_cast <void> (0) : __assert_fail ("isConstantOrConstantVector(C1) && isConstantOrConstantVector(C2) && \"Expected select-of-constants\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9174, __PRETTY_FUNCTION__)); | |||
9175 | ||||
9176 | EVT VT = N->getValueType(0); | |||
9177 | if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() || | |||
9178 | VT != Cond.getOperand(0).getValueType()) | |||
9179 | return SDValue(); | |||
9180 | ||||
9181 | // The inverted-condition + commuted-select variants of these patterns are | |||
9182 | // canonicalized to these forms in IR. | |||
9183 | SDValue X = Cond.getOperand(0); | |||
9184 | SDValue CondC = Cond.getOperand(1); | |||
9185 | ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); | |||
9186 | if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) && | |||
9187 | isAllOnesOrAllOnesSplat(C2)) { | |||
9188 | // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1 | |||
9189 | SDLoc DL(N); | |||
9190 | SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); | |||
9191 | SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); | |||
9192 | return DAG.getNode(ISD::OR, DL, VT, Sra, C1); | |||
9193 | } | |||
9194 | if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) { | |||
9195 | // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1 | |||
9196 | SDLoc DL(N); | |||
9197 | SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); | |||
9198 | SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); | |||
9199 | return DAG.getNode(ISD::AND, DL, VT, Sra, C1); | |||
9200 | } | |||
9201 | return SDValue(); | |||
9202 | } | |||
9203 | ||||
9204 | SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { | |||
9205 | SDValue Cond = N->getOperand(0); | |||
9206 | SDValue N1 = N->getOperand(1); | |||
9207 | SDValue N2 = N->getOperand(2); | |||
9208 | EVT VT = N->getValueType(0); | |||
9209 | EVT CondVT = Cond.getValueType(); | |||
9210 | SDLoc DL(N); | |||
9211 | ||||
9212 | if (!VT.isInteger()) | |||
9213 | return SDValue(); | |||
9214 | ||||
9215 | auto *C1 = dyn_cast<ConstantSDNode>(N1); | |||
9216 | auto *C2 = dyn_cast<ConstantSDNode>(N2); | |||
9217 | if (!C1 || !C2) | |||
9218 | return SDValue(); | |||
9219 | ||||
9220 | // Only do this before legalization to avoid conflicting with target-specific | |||
9221 | // transforms in the other direction (create a select from a zext/sext). There | |||
9222 | // is also a target-independent combine here in DAGCombiner in the other | |||
9223 | // direction for (select Cond, -1, 0) when the condition is not i1. | |||
9224 | if (CondVT == MVT::i1 && !LegalOperations) { | |||
9225 | if (C1->isNullValue() && C2->isOne()) { | |||
9226 | // select Cond, 0, 1 --> zext (!Cond) | |||
9227 | SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); | |||
9228 | if (VT != MVT::i1) | |||
9229 | NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); | |||
9230 | return NotCond; | |||
9231 | } | |||
9232 | if (C1->isNullValue() && C2->isAllOnesValue()) { | |||
9233 | // select Cond, 0, -1 --> sext (!Cond) | |||
9234 | SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); | |||
9235 | if (VT != MVT::i1) | |||
9236 | NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); | |||
9237 | return NotCond; | |||
9238 | } | |||
9239 | if (C1->isOne() && C2->isNullValue()) { | |||
9240 | // select Cond, 1, 0 --> zext (Cond) | |||
9241 | if (VT != MVT::i1) | |||
9242 | Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); | |||
9243 | return Cond; | |||
9244 | } | |||
9245 | if (C1->isAllOnesValue() && C2->isNullValue()) { | |||
9246 | // select Cond, -1, 0 --> sext (Cond) | |||
9247 | if (VT != MVT::i1) | |||
9248 | Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); | |||
9249 | return Cond; | |||
9250 | } | |||
9251 | ||||
9252 | // Use a target hook because some targets may prefer to transform in the | |||
9253 | // other direction. | |||
9254 | if (TLI.convertSelectOfConstantsToMath(VT)) { | |||
9255 | // For any constants that differ by 1, we can transform the select into an | |||
9256 | // extend and add. | |||
9257 | const APInt &C1Val = C1->getAPIntValue(); | |||
9258 | const APInt &C2Val = C2->getAPIntValue(); | |||
9259 | if (C1Val - 1 == C2Val) { | |||
9260 | // select Cond, C1, C1-1 --> add (zext Cond), C1-1 | |||
9261 | if (VT != MVT::i1) | |||
9262 | Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); | |||
9263 | return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); | |||
9264 | } | |||
9265 | if (C1Val + 1 == C2Val) { | |||
9266 | // select Cond, C1, C1+1 --> add (sext Cond), C1+1 | |||
9267 | if (VT != MVT::i1) | |||
9268 | Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); | |||
9269 | return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); | |||
9270 | } | |||
9271 | ||||
9272 | // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2) | |||
9273 | if (C1Val.isPowerOf2() && C2Val.isNullValue()) { | |||
9274 | if (VT != MVT::i1) | |||
9275 | Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); | |||
9276 | SDValue ShAmtC = DAG.getConstant(C1Val.exactLogBase2(), DL, VT); | |||
9277 | return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC); | |||
9278 | } | |||
9279 | ||||
9280 | if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) | |||
9281 | return V; | |||
9282 | } | |||
9283 | ||||
9284 | return SDValue(); | |||
9285 | } | |||
9286 | ||||
9287 | // fold (select Cond, 0, 1) -> (xor Cond, 1) | |||
9288 | // We can't do this reliably if integer based booleans have different contents | |||
9289 | // to floating point based booleans. This is because we can't tell whether we | |||
9290 | // have an integer-based boolean or a floating-point-based boolean unless we | |||
9291 | // can find the SETCC that produced it and inspect its operands. This is | |||
9292 | // fairly easy if C is the SETCC node, but it can potentially be | |||
9293 | // undiscoverable (or not reasonably discoverable). For example, it could be | |||
9294 | // in another basic block or it could require searching a complicated | |||
9295 | // expression. | |||
9296 | if (CondVT.isInteger() && | |||
9297 | TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == | |||
9298 | TargetLowering::ZeroOrOneBooleanContent && | |||
9299 | TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == | |||
9300 | TargetLowering::ZeroOrOneBooleanContent && | |||
9301 | C1->isNullValue() && C2->isOne()) { | |||
9302 | SDValue NotCond = | |||
9303 | DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); | |||
9304 | if (VT.bitsEq(CondVT)) | |||
9305 | return NotCond; | |||
9306 | return DAG.getZExtOrTrunc(NotCond, DL, VT); | |||
9307 | } | |||
9308 | ||||
9309 | return SDValue(); | |||
9310 | } | |||
9311 | ||||
9312 | static SDValue foldBoolSelectToLogic(SDNode *N, SelectionDAG &DAG) { | |||
9313 | assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) &&(((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD ::VSELECT) && "Expected a (v)select") ? static_cast< void> (0) : __assert_fail ("(N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) && \"Expected a (v)select\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9314, __PRETTY_FUNCTION__)) | |||
9314 | "Expected a (v)select")(((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD ::VSELECT) && "Expected a (v)select") ? static_cast< void> (0) : __assert_fail ("(N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) && \"Expected a (v)select\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9314, __PRETTY_FUNCTION__)); | |||
9315 | SDValue Cond = N->getOperand(0); | |||
9316 | SDValue T = N->getOperand(1), F = N->getOperand(2); | |||
9317 | EVT VT = N->getValueType(0); | |||
9318 | if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1) | |||
9319 | return SDValue(); | |||
9320 | ||||
9321 | // select Cond, Cond, F --> or Cond, F | |||
9322 | // select Cond, 1, F --> or Cond, F | |||
9323 | if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true)) | |||
9324 | return DAG.getNode(ISD::OR, SDLoc(N), VT, Cond, F); | |||
9325 | ||||
9326 | // select Cond, T, Cond --> and Cond, T | |||
9327 | // select Cond, T, 0 --> and Cond, T | |||
9328 | if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true)) | |||
9329 | return DAG.getNode(ISD::AND, SDLoc(N), VT, Cond, T); | |||
9330 | ||||
9331 | // select Cond, T, 1 --> or (not Cond), T | |||
9332 | if (isOneOrOneSplat(F, /* AllowUndefs */ true)) { | |||
9333 | SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); | |||
9334 | return DAG.getNode(ISD::OR, SDLoc(N), VT, NotCond, T); | |||
9335 | } | |||
9336 | ||||
9337 | // select Cond, 0, F --> and (not Cond), F | |||
9338 | if (isNullOrNullSplat(T, /* AllowUndefs */ true)) { | |||
9339 | SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); | |||
9340 | return DAG.getNode(ISD::AND, SDLoc(N), VT, NotCond, F); | |||
9341 | } | |||
9342 | ||||
9343 | return SDValue(); | |||
9344 | } | |||
9345 | ||||
9346 | SDValue DAGCombiner::visitSELECT(SDNode *N) { | |||
9347 | SDValue N0 = N->getOperand(0); | |||
9348 | SDValue N1 = N->getOperand(1); | |||
9349 | SDValue N2 = N->getOperand(2); | |||
9350 | EVT VT = N->getValueType(0); | |||
9351 | EVT VT0 = N0.getValueType(); | |||
9352 | SDLoc DL(N); | |||
9353 | SDNodeFlags Flags = N->getFlags(); | |||
9354 | ||||
9355 | if (SDValue V = DAG.simplifySelect(N0, N1, N2)) | |||
9356 | return V; | |||
9357 | ||||
9358 | if (SDValue V = foldSelectOfConstants(N)) | |||
9359 | return V; | |||
9360 | ||||
9361 | if (SDValue V = foldBoolSelectToLogic(N, DAG)) | |||
9362 | return V; | |||
9363 | ||||
9364 | // If we can fold this based on the true/false value, do so. | |||
9365 | if (SimplifySelectOps(N, N1, N2)) | |||
9366 | return SDValue(N, 0); // Don't revisit N. | |||
9367 | ||||
9368 | if (VT0 == MVT::i1) { | |||
9369 | // The code in this block deals with the following 2 equivalences: | |||
9370 | // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) | |||
9371 | // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) | |||
9372 | // The target can specify its preferred form with the | |||
9373 | // shouldNormalizeToSelectSequence() callback. However we always transform | |||
9374 | // to the right anyway if we find the inner select exists in the DAG anyway | |||
9375 | // and we always transform to the left side if we know that we can further | |||
9376 | // optimize the combination of the conditions. | |||
9377 | bool normalizeToSequence = | |||
9378 | TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); | |||
9379 | // select (and Cond0, Cond1), X, Y | |||
9380 | // -> select Cond0, (select Cond1, X, Y), Y | |||
9381 | if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { | |||
9382 | SDValue Cond0 = N0->getOperand(0); | |||
9383 | SDValue Cond1 = N0->getOperand(1); | |||
9384 | SDValue InnerSelect = | |||
9385 | DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags); | |||
9386 | if (normalizeToSequence || !InnerSelect.use_empty()) | |||
9387 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, | |||
9388 | InnerSelect, N2, Flags); | |||
9389 | // Cleanup on failure. | |||
9390 | if (InnerSelect.use_empty()) | |||
9391 | recursivelyDeleteUnusedNodes(InnerSelect.getNode()); | |||
9392 | } | |||
9393 | // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) | |||
9394 | if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { | |||
9395 | SDValue Cond0 = N0->getOperand(0); | |||
9396 | SDValue Cond1 = N0->getOperand(1); | |||
9397 | SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(), | |||
9398 | Cond1, N1, N2, Flags); | |||
9399 | if (normalizeToSequence || !InnerSelect.use_empty()) | |||
9400 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, | |||
9401 | InnerSelect, Flags); | |||
9402 | // Cleanup on failure. | |||
9403 | if (InnerSelect.use_empty()) | |||
9404 | recursivelyDeleteUnusedNodes(InnerSelect.getNode()); | |||
9405 | } | |||
9406 | ||||
9407 | // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y | |||
9408 | if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { | |||
9409 | SDValue N1_0 = N1->getOperand(0); | |||
9410 | SDValue N1_1 = N1->getOperand(1); | |||
9411 | SDValue N1_2 = N1->getOperand(2); | |||
9412 | if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { | |||
9413 | // Create the actual and node if we can generate good code for it. | |||
9414 | if (!normalizeToSequence) { | |||
9415 | SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); | |||
9416 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, | |||
9417 | N2, Flags); | |||
9418 | } | |||
9419 | // Otherwise see if we can optimize the "and" to a better pattern. | |||
9420 | if (SDValue Combined = visitANDLike(N0, N1_0, N)) { | |||
9421 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, | |||
9422 | N2, Flags); | |||
9423 | } | |||
9424 | } | |||
9425 | } | |||
9426 | // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y | |||
9427 | if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { | |||
9428 | SDValue N2_0 = N2->getOperand(0); | |||
9429 | SDValue N2_1 = N2->getOperand(1); | |||
9430 | SDValue N2_2 = N2->getOperand(2); | |||
9431 | if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { | |||
9432 | // Create the actual or node if we can generate good code for it. | |||
9433 | if (!normalizeToSequence) { | |||
9434 | SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); | |||
9435 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, | |||
9436 | N2_2, Flags); | |||
9437 | } | |||
9438 | // Otherwise see if we can optimize to a better pattern. | |||
9439 | if (SDValue Combined = visitORLike(N0, N2_0, N)) | |||
9440 | return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, | |||
9441 | N2_2, Flags); | |||
9442 | } | |||
9443 | } | |||
9444 | } | |||
9445 | ||||
9446 | // select (not Cond), N1, N2 -> select Cond, N2, N1 | |||
9447 | if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) { | |||
9448 | SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1); | |||
9449 | SelectOp->setFlags(Flags); | |||
9450 | return SelectOp; | |||
9451 | } | |||
9452 | ||||
9453 | // Fold selects based on a setcc into other things, such as min/max/abs. | |||
9454 | if (N0.getOpcode() == ISD::SETCC) { | |||
9455 | SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1); | |||
9456 | ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); | |||
9457 | ||||
9458 | // select (fcmp lt x, y), x, y -> fminnum x, y | |||
9459 | // select (fcmp gt x, y), x, y -> fmaxnum x, y | |||
9460 | // | |||
9461 | // This is OK if we don't care what happens if either operand is a NaN. | |||
9462 | if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI)) | |||
9463 | if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, | |||
9464 | CC, TLI, DAG)) | |||
9465 | return FMinMax; | |||
9466 | ||||
9467 | // Use 'unsigned add with overflow' to optimize an unsigned saturating add. | |||
9468 | // This is conservatively limited to pre-legal-operations to give targets | |||
9469 | // a chance to reverse the transform if they want to do that. Also, it is | |||
9470 | // unlikely that the pattern would be formed late, so it's probably not | |||
9471 | // worth going through the other checks. | |||
9472 | if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) && | |||
9473 | CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) && | |||
9474 | N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) { | |||
9475 | auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1)); | |||
9476 | auto *NotC = dyn_cast<ConstantSDNode>(Cond1); | |||
9477 | if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) { | |||
9478 | // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) --> | |||
9479 | // uaddo Cond0, C; select uaddo.1, -1, uaddo.0 | |||
9480 | // | |||
9481 | // The IR equivalent of this transform would have this form: | |||
9482 | // %a = add %x, C | |||
9483 | // %c = icmp ugt %x, ~C | |||
9484 | // %r = select %c, -1, %a | |||
9485 | // => | |||
9486 | // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C) | |||
9487 | // %u0 = extractvalue %u, 0 | |||
9488 | // %u1 = extractvalue %u, 1 | |||
9489 | // %r = select %u1, -1, %u0 | |||
9490 | SDVTList VTs = DAG.getVTList(VT, VT0); | |||
9491 | SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1)); | |||
9492 | return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0)); | |||
9493 | } | |||
9494 | } | |||
9495 | ||||
9496 | if (TLI.isOperationLegal(ISD::SELECT_CC, VT) || | |||
9497 | (!LegalOperations && | |||
9498 | TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) { | |||
9499 | // Any flags available in a select/setcc fold will be on the setcc as they | |||
9500 | // migrated from fcmp | |||
9501 | Flags = N0.getNode()->getFlags(); | |||
9502 | SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, | |||
9503 | N2, N0.getOperand(2)); | |||
9504 | SelectNode->setFlags(Flags); | |||
9505 | return SelectNode; | |||
9506 | } | |||
9507 | ||||
9508 | return SimplifySelect(DL, N0, N1, N2); | |||
9509 | } | |||
9510 | ||||
9511 | return SDValue(); | |||
9512 | } | |||
9513 | ||||
9514 | // This function assumes all the vselect's arguments are CONCAT_VECTOR | |||
9515 | // nodes and that the condition is a BV of ConstantSDNodes (or undefs). | |||
9516 | static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { | |||
9517 | SDLoc DL(N); | |||
9518 | SDValue Cond = N->getOperand(0); | |||
9519 | SDValue LHS = N->getOperand(1); | |||
9520 | SDValue RHS = N->getOperand(2); | |||
9521 | EVT VT = N->getValueType(0); | |||
9522 | int NumElems = VT.getVectorNumElements(); | |||
9523 | assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&((LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode () == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD:: BUILD_VECTOR) ? static_cast<void> (0) : __assert_fail ( "LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9525, __PRETTY_FUNCTION__)) | |||
9524 | RHS.getOpcode() == ISD::CONCAT_VECTORS &&((LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode () == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD:: BUILD_VECTOR) ? static_cast<void> (0) : __assert_fail ( "LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9525, __PRETTY_FUNCTION__)) | |||
9525 | Cond.getOpcode() == ISD::BUILD_VECTOR)((LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode () == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD:: BUILD_VECTOR) ? static_cast<void> (0) : __assert_fail ( "LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9525, __PRETTY_FUNCTION__)); | |||
9526 | ||||
9527 | // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about | |||
9528 | // binary ones here. | |||
9529 | if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) | |||
9530 | return SDValue(); | |||
9531 | ||||
9532 | // We're sure we have an even number of elements due to the | |||
9533 | // concat_vectors we have as arguments to vselect. | |||
9534 | // Skip BV elements until we find one that's not an UNDEF | |||
9535 | // After we find an UNDEF element, keep looping until we get to half the | |||
9536 | // length of the BV and see if all the non-undef nodes are the same. | |||
9537 | ConstantSDNode *BottomHalf = nullptr; | |||
9538 | for (int i = 0; i < NumElems / 2; ++i) { | |||
9539 | if (Cond->getOperand(i)->isUndef()) | |||
9540 | continue; | |||
9541 | ||||
9542 | if (BottomHalf == nullptr) | |||
9543 | BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); | |||
9544 | else if (Cond->getOperand(i).getNode() != BottomHalf) | |||
9545 | return SDValue(); | |||
9546 | } | |||
9547 | ||||
9548 | // Do the same for the second half of the BuildVector | |||
9549 | ConstantSDNode *TopHalf = nullptr; | |||
9550 | for (int i = NumElems / 2; i < NumElems; ++i) { | |||
9551 | if (Cond->getOperand(i)->isUndef()) | |||
9552 | continue; | |||
9553 | ||||
9554 | if (TopHalf == nullptr) | |||
9555 | TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); | |||
9556 | else if (Cond->getOperand(i).getNode() != TopHalf) | |||
9557 | return SDValue(); | |||
9558 | } | |||
9559 | ||||
9560 | assert(TopHalf && BottomHalf &&((TopHalf && BottomHalf && "One half of the selector was all UNDEFs and the other was all the " "same value. This should have been addressed before this function." ) ? static_cast<void> (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9562, __PRETTY_FUNCTION__)) | |||
9561 | "One half of the selector was all UNDEFs and the other was all the "((TopHalf && BottomHalf && "One half of the selector was all UNDEFs and the other was all the " "same value. This should have been addressed before this function." ) ? static_cast<void> (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9562, __PRETTY_FUNCTION__)) | |||
9562 | "same value. This should have been addressed before this function.")((TopHalf && BottomHalf && "One half of the selector was all UNDEFs and the other was all the " "same value. This should have been addressed before this function." ) ? static_cast<void> (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 9562, __PRETTY_FUNCTION__)); | |||
9563 | return DAG.getNode( | |||
9564 | ISD::CONCAT_VECTORS, DL, VT, | |||
9565 | BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), | |||
9566 | TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); | |||
9567 | } | |||
9568 | ||||
9569 | bool refineUniformBase(SDValue &BasePtr, SDValue &Index, SelectionDAG &DAG) { | |||
9570 | if (!isNullConstant(BasePtr) || Index.getOpcode() != ISD::ADD) | |||
9571 | return false; | |||
9572 | ||||
9573 | // For now we check only the LHS of the add. | |||
9574 | SDValue LHS = Index.getOperand(0); | |||
9575 | SDValue SplatVal = DAG.getSplatValue(LHS); | |||
9576 | if (!SplatVal) | |||
9577 | return false; | |||
9578 | ||||
9579 | BasePtr = SplatVal; | |||
9580 | Index = Index.getOperand(1); | |||
9581 | return true; | |||
9582 | } | |||
9583 | ||||
9584 | // Fold sext/zext of index into index type. | |||
9585 | bool refineIndexType(MaskedGatherScatterSDNode *MGS, SDValue &Index, | |||
9586 | bool Scaled, SelectionDAG &DAG) { | |||
9587 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
9588 | ||||
9589 | if (Index.getOpcode() == ISD::ZERO_EXTEND) { | |||
9590 | SDValue Op = Index.getOperand(0); | |||
9591 | MGS->setIndexType(Scaled ? ISD::UNSIGNED_SCALED : ISD::UNSIGNED_UNSCALED); | |||
9592 | if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { | |||
9593 | Index = Op; | |||
9594 | return true; | |||
9595 | } | |||
9596 | } | |||
9597 | ||||
9598 | if (Index.getOpcode() == ISD::SIGN_EXTEND) { | |||
9599 | SDValue Op = Index.getOperand(0); | |||
9600 | MGS->setIndexType(Scaled ? ISD::SIGNED_SCALED : ISD::SIGNED_UNSCALED); | |||
9601 | if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { | |||
9602 | Index = Op; | |||
9603 | return true; | |||
9604 | } | |||
9605 | } | |||
9606 | ||||
9607 | return false; | |||
9608 | } | |||
9609 | ||||
9610 | SDValue DAGCombiner::visitMSCATTER(SDNode *N) { | |||
9611 | MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); | |||
9612 | SDValue Mask = MSC->getMask(); | |||
9613 | SDValue Chain = MSC->getChain(); | |||
9614 | SDValue Index = MSC->getIndex(); | |||
9615 | SDValue Scale = MSC->getScale(); | |||
9616 | SDValue StoreVal = MSC->getValue(); | |||
9617 | SDValue BasePtr = MSC->getBasePtr(); | |||
9618 | SDLoc DL(N); | |||
9619 | ||||
9620 | // Zap scatters with a zero mask. | |||
9621 | if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) | |||
9622 | return Chain; | |||
9623 | ||||
9624 | if (refineUniformBase(BasePtr, Index, DAG)) { | |||
9625 | SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; | |||
9626 | return DAG.getMaskedScatter( | |||
9627 | DAG.getVTList(MVT::Other), StoreVal.getValueType(), DL, Ops, | |||
9628 | MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); | |||
9629 | } | |||
9630 | ||||
9631 | if (refineIndexType(MSC, Index, MSC->isIndexScaled(), DAG)) { | |||
9632 | SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; | |||
9633 | return DAG.getMaskedScatter( | |||
9634 | DAG.getVTList(MVT::Other), StoreVal.getValueType(), DL, Ops, | |||
9635 | MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); | |||
9636 | } | |||
9637 | ||||
9638 | return SDValue(); | |||
9639 | } | |||
9640 | ||||
9641 | SDValue DAGCombiner::visitMSTORE(SDNode *N) { | |||
9642 | MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); | |||
9643 | SDValue Mask = MST->getMask(); | |||
9644 | SDValue Chain = MST->getChain(); | |||
9645 | SDLoc DL(N); | |||
9646 | ||||
9647 | // Zap masked stores with a zero mask. | |||
9648 | if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) | |||
9649 | return Chain; | |||
9650 | ||||
9651 | // If this is a masked load with an all ones mask, we can use a unmasked load. | |||
9652 | // FIXME: Can we do this for indexed, compressing, or truncating stores? | |||
9653 | if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && | |||
9654 | MST->isUnindexed() && !MST->isCompressingStore() && | |||
9655 | !MST->isTruncatingStore()) | |||
9656 | return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(), | |||
9657 | MST->getBasePtr(), MST->getMemOperand()); | |||
9658 | ||||
9659 | // Try transforming N to an indexed store. | |||
9660 | if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) | |||
9661 | return SDValue(N, 0); | |||
9662 | ||||
9663 | return SDValue(); | |||
9664 | } | |||
9665 | ||||
9666 | SDValue DAGCombiner::visitMGATHER(SDNode *N) { | |||
9667 | MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); | |||
9668 | SDValue Mask = MGT->getMask(); | |||
9669 | SDValue Chain = MGT->getChain(); | |||
9670 | SDValue Index = MGT->getIndex(); | |||
9671 | SDValue Scale = MGT->getScale(); | |||
9672 | SDValue PassThru = MGT->getPassThru(); | |||
9673 | SDValue BasePtr = MGT->getBasePtr(); | |||
9674 | SDLoc DL(N); | |||
9675 | ||||
9676 | // Zap gathers with a zero mask. | |||
9677 | if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) | |||
9678 | return CombineTo(N, PassThru, MGT->getChain()); | |||
9679 | ||||
9680 | if (refineUniformBase(BasePtr, Index, DAG)) { | |||
9681 | SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; | |||
9682 | return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), | |||
9683 | PassThru.getValueType(), DL, Ops, | |||
9684 | MGT->getMemOperand(), MGT->getIndexType(), | |||
9685 | MGT->getExtensionType()); | |||
9686 | } | |||
9687 | ||||
9688 | if (refineIndexType(MGT, Index, MGT->isIndexScaled(), DAG)) { | |||
9689 | SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; | |||
9690 | return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), | |||
9691 | PassThru.getValueType(), DL, Ops, | |||
9692 | MGT->getMemOperand(), MGT->getIndexType(), | |||
9693 | MGT->getExtensionType()); | |||
9694 | } | |||
9695 | ||||
9696 | return SDValue(); | |||
9697 | } | |||
9698 | ||||
9699 | SDValue DAGCombiner::visitMLOAD(SDNode *N) { | |||
9700 | MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); | |||
9701 | SDValue Mask = MLD->getMask(); | |||
9702 | SDLoc DL(N); | |||
9703 | ||||
9704 | // Zap masked loads with a zero mask. | |||
9705 | if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) | |||
9706 | return CombineTo(N, MLD->getPassThru(), MLD->getChain()); | |||
9707 | ||||
9708 | // If this is a masked load with an all ones mask, we can use a unmasked load. | |||
9709 | // FIXME: Can we do this for indexed, expanding, or extending loads? | |||
9710 | if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && | |||
9711 | MLD->isUnindexed() && !MLD->isExpandingLoad() && | |||
9712 | MLD->getExtensionType() == ISD::NON_EXTLOAD) { | |||
9713 | SDValue NewLd = DAG.getLoad(N->getValueType(0), SDLoc(N), MLD->getChain(), | |||
9714 | MLD->getBasePtr(), MLD->getMemOperand()); | |||
9715 | return CombineTo(N, NewLd, NewLd.getValue(1)); | |||
9716 | } | |||
9717 | ||||
9718 | // Try transforming N to an indexed load. | |||
9719 | if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) | |||
9720 | return SDValue(N, 0); | |||
9721 | ||||
9722 | return SDValue(); | |||
9723 | } | |||
9724 | ||||
9725 | /// A vector select of 2 constant vectors can be simplified to math/logic to | |||
9726 | /// avoid a variable select instruction and possibly avoid constant loads. | |||
9727 | SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { | |||
9728 | SDValue Cond = N->getOperand(0); | |||
9729 | SDValue N1 = N->getOperand(1); | |||
9730 | SDValue N2 = N->getOperand(2); | |||
9731 | EVT VT = N->getValueType(0); | |||
9732 | if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || | |||
9733 | !TLI.convertSelectOfConstantsToMath(VT) || | |||
9734 | !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || | |||
9735 | !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) | |||
9736 | return SDValue(); | |||
9737 | ||||
9738 | // Check if we can use the condition value to increment/decrement a single | |||
9739 | // constant value. This simplifies a select to an add and removes a constant | |||
9740 | // load/materialization from the general case. | |||
9741 | bool AllAddOne = true; | |||
9742 | bool AllSubOne = true; | |||
9743 | unsigned Elts = VT.getVectorNumElements(); | |||
9744 | for (unsigned i = 0; i != Elts; ++i) { | |||
9745 | SDValue N1Elt = N1.getOperand(i); | |||
9746 | SDValue N2Elt = N2.getOperand(i); | |||
9747 | if (N1Elt.isUndef() || N2Elt.isUndef()) | |||
9748 | continue; | |||
9749 | if (N1Elt.getValueType() != N2Elt.getValueType()) | |||
9750 | continue; | |||
9751 | ||||
9752 | const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); | |||
9753 | const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); | |||
9754 | if (C1 != C2 + 1) | |||
9755 | AllAddOne = false; | |||
9756 | if (C1 != C2 - 1) | |||
9757 | AllSubOne = false; | |||
9758 | } | |||
9759 | ||||
9760 | // Further simplifications for the extra-special cases where the constants are | |||
9761 | // all 0 or all -1 should be implemented as folds of these patterns. | |||
9762 | SDLoc DL(N); | |||
9763 | if (AllAddOne || AllSubOne) { | |||
9764 | // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C | |||
9765 | // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C | |||
9766 | auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; | |||
9767 | SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); | |||
9768 | return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); | |||
9769 | } | |||
9770 | ||||
9771 | // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C) | |||
9772 | APInt Pow2C; | |||
9773 | if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() && | |||
9774 | isNullOrNullSplat(N2)) { | |||
9775 | SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT); | |||
9776 | SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT); | |||
9777 | return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC); | |||
9778 | } | |||
9779 | ||||
9780 | if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) | |||
9781 | return V; | |||
9782 | ||||
9783 | // The general case for select-of-constants: | |||
9784 | // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 | |||
9785 | // ...but that only makes sense if a vselect is slower than 2 logic ops, so | |||
9786 | // leave that to a machine-specific pass. | |||
9787 | return SDValue(); | |||
9788 | } | |||
9789 | ||||
9790 | SDValue DAGCombiner::visitVSELECT(SDNode *N) { | |||
9791 | SDValue N0 = N->getOperand(0); | |||
9792 | SDValue N1 = N->getOperand(1); | |||
9793 | SDValue N2 = N->getOperand(2); | |||
9794 | EVT VT = N->getValueType(0); | |||
9795 | SDLoc DL(N); | |||
9796 | ||||
9797 | if (SDValue V = DAG.simplifySelect(N0, N1, N2)) | |||
9798 | return V; | |||
9799 | ||||
9800 | if (SDValue V = foldBoolSelectToLogic(N, DAG)) | |||
9801 | return V; | |||
9802 | ||||
9803 | // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1 | |||
9804 | if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) | |||
9805 | return DAG.getSelect(DL, VT, F, N2, N1); | |||
9806 | ||||
9807 | // Canonicalize integer abs. | |||
9808 | // vselect (setg[te] X, 0), X, -X -> | |||
9809 | // vselect (setgt X, -1), X, -X -> | |||
9810 | // vselect (setl[te] X, 0), -X, X -> | |||
9811 | // Y = sra (X, size(X)-1); xor (add (X, Y), Y) | |||
9812 | if (N0.getOpcode() == ISD::SETCC) { | |||
9813 | SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); | |||
9814 | ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); | |||
9815 | bool isAbs = false; | |||
9816 | bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); | |||
9817 | ||||
9818 | if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || | |||
9819 | (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && | |||
9820 | N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) | |||
9821 | isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); | |||
9822 | else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && | |||
9823 | N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) | |||
9824 | isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); | |||
9825 | ||||
9826 | if (isAbs) { | |||
9827 | if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) | |||
9828 | return DAG.getNode(ISD::ABS, DL, VT, LHS); | |||
9829 | ||||
9830 | SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, | |||
9831 | DAG.getConstant(VT.getScalarSizeInBits() - 1, | |||
9832 | DL, getShiftAmountTy(VT))); | |||
9833 | SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); | |||
9834 | AddToWorklist(Shift.getNode()); | |||
9835 | AddToWorklist(Add.getNode()); | |||
9836 | return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); | |||
9837 | } | |||
9838 | ||||
9839 | // vselect x, y (fcmp lt x, y) -> fminnum x, y | |||
9840 | // vselect x, y (fcmp gt x, y) -> fmaxnum x, y | |||
9841 | // | |||
9842 | // This is OK if we don't care about what happens if either operand is a | |||
9843 | // NaN. | |||
9844 | // | |||
9845 | if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) { | |||
9846 | if (SDValue FMinMax = | |||
9847 | combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC, TLI, DAG)) | |||
9848 | return FMinMax; | |||
9849 | } | |||
9850 | ||||
9851 | // If this select has a condition (setcc) with narrower operands than the | |||
9852 | // select, try to widen the compare to match the select width. | |||
9853 | // TODO: This should be extended to handle any constant. | |||
9854 | // TODO: This could be extended to handle non-loading patterns, but that | |||
9855 | // requires thorough testing to avoid regressions. | |||
9856 | if (isNullOrNullSplat(RHS)) { | |||
9857 | EVT NarrowVT = LHS.getValueType(); | |||
9858 | EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); | |||
9859 | EVT SetCCVT = getSetCCResultType(LHS.getValueType()); | |||
9860 | unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); | |||
9861 | unsigned WideWidth = WideVT.getScalarSizeInBits(); | |||
9862 | bool IsSigned = isSignedIntSetCC(CC); | |||
9863 | auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; | |||
9864 | if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && | |||
9865 | SetCCWidth != 1 && SetCCWidth < WideWidth && | |||
9866 | TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && | |||
9867 | TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { | |||
9868 | // Both compare operands can be widened for free. The LHS can use an | |||
9869 | // extended load, and the RHS is a constant: | |||
9870 | // vselect (ext (setcc load(X), C)), N1, N2 --> | |||
9871 | // vselect (setcc extload(X), C'), N1, N2 | |||
9872 | auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; | |||
9873 | SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); | |||
9874 | SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); | |||
9875 | EVT WideSetCCVT = getSetCCResultType(WideVT); | |||
9876 | SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); | |||
9877 | return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); | |||
9878 | } | |||
9879 | } | |||
9880 | ||||
9881 | // Match VSELECTs into add with unsigned saturation. | |||
9882 | if (hasOperation(ISD::UADDSAT, VT)) { | |||
9883 | // Check if one of the arms of the VSELECT is vector with all bits set. | |||
9884 | // If it's on the left side invert the predicate to simplify logic below. | |||
9885 | SDValue Other; | |||
9886 | ISD::CondCode SatCC = CC; | |||
9887 | if (ISD::isBuildVectorAllOnes(N1.getNode())) { | |||
9888 | Other = N2; | |||
9889 | SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); | |||
9890 | } else if (ISD::isBuildVectorAllOnes(N2.getNode())) { | |||
9891 | Other = N1; | |||
9892 | } | |||
9893 | ||||
9894 | if (Other && Other.getOpcode() == ISD::ADD) { | |||
9895 | SDValue CondLHS = LHS, CondRHS = RHS; | |||
9896 | SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); | |||
9897 | ||||
9898 | // Canonicalize condition operands. | |||
9899 | if (SatCC == ISD::SETUGE) { | |||
9900 | std::swap(CondLHS, CondRHS); | |||
9901 | SatCC = ISD::SETULE; | |||
9902 | } | |||
9903 | ||||
9904 | // We can test against either of the addition operands. | |||
9905 | // x <= x+y ? x+y : ~0 --> uaddsat x, y | |||
9906 | // x+y >= x ? x+y : ~0 --> uaddsat x, y | |||
9907 | if (SatCC == ISD::SETULE && Other == CondRHS && | |||
9908 | (OpLHS == CondLHS || OpRHS == CondLHS)) | |||
9909 | return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); | |||
9910 | ||||
9911 | if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) && | |||
9912 | CondLHS == OpLHS) { | |||
9913 | // If the RHS is a constant we have to reverse the const | |||
9914 | // canonicalization. | |||
9915 | // x >= ~C ? x+C : ~0 --> uaddsat x, C | |||
9916 | auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { | |||
9917 | return Cond->getAPIntValue() == ~Op->getAPIntValue(); | |||
9918 | }; | |||
9919 | if (SatCC == ISD::SETULE && | |||
9920 | ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT)) | |||
9921 | return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); | |||
9922 | } | |||
9923 | } | |||
9924 | } | |||
9925 | ||||
9926 | // Match VSELECTs into sub with unsigned saturation. | |||
9927 | if (hasOperation(ISD::USUBSAT, VT)) { | |||
9928 | // Check if one of the arms of the VSELECT is a zero vector. If it's on | |||
9929 | // the left side invert the predicate to simplify logic below. | |||
9930 | SDValue Other; | |||
9931 | ISD::CondCode SatCC = CC; | |||
9932 | if (ISD::isBuildVectorAllZeros(N1.getNode())) { | |||
9933 | Other = N2; | |||
9934 | SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); | |||
9935 | } else if (ISD::isBuildVectorAllZeros(N2.getNode())) { | |||
9936 | Other = N1; | |||
9937 | } | |||
9938 | ||||
9939 | if (Other && Other.getNumOperands() == 2) { | |||
9940 | SDValue CondRHS = RHS; | |||
9941 | SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); | |||
9942 | ||||
9943 | if (Other.getOpcode() == ISD::SUB && | |||
9944 | LHS.getOpcode() == ISD::ZERO_EXTEND && LHS.getOperand(0) == OpLHS && | |||
9945 | OpRHS.getOpcode() == ISD::TRUNCATE && OpRHS.getOperand(0) == RHS) { | |||
9946 | // Look for a general sub with unsigned saturation first. | |||
9947 | // zext(x) >= y ? x - trunc(y) : 0 | |||
9948 | // --> usubsat(x,trunc(umin(y,SatLimit))) | |||
9949 | // zext(x) > y ? x - trunc(y) : 0 | |||
9950 | // --> usubsat(x,trunc(umin(y,SatLimit))) | |||
9951 | if (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) | |||
9952 | return getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS, DAG, | |||
9953 | DL); | |||
9954 | } | |||
9955 | ||||
9956 | if (OpLHS == LHS) { | |||
9957 | // Look for a general sub with unsigned saturation first. | |||
9958 | // x >= y ? x-y : 0 --> usubsat x, y | |||
9959 | // x > y ? x-y : 0 --> usubsat x, y | |||
9960 | if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) && | |||
9961 | Other.getOpcode() == ISD::SUB && OpRHS == CondRHS) | |||
9962 | return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); | |||
9963 | ||||
9964 | if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) { | |||
9965 | if (isa<BuildVectorSDNode>(CondRHS)) { | |||
9966 | // If the RHS is a constant we have to reverse the const | |||
9967 | // canonicalization. | |||
9968 | // x > C-1 ? x+-C : 0 --> usubsat x, C | |||
9969 | auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { | |||
9970 | return (!Op && !Cond) || | |||
9971 | (Op && Cond && | |||
9972 | Cond->getAPIntValue() == (-Op->getAPIntValue() - 1)); | |||
9973 | }; | |||
9974 | if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD && | |||
9975 | ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT, | |||
9976 | /*AllowUndefs*/ true)) { | |||
9977 | OpRHS = DAG.getNode(ISD::SUB, DL, VT, | |||
9978 | DAG.getConstant(0, DL, VT), OpRHS); | |||
9979 | return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); | |||
9980 | } | |||
9981 | ||||
9982 | // Another special case: If C was a sign bit, the sub has been | |||
9983 | // canonicalized into a xor. | |||
9984 | // FIXME: Would it be better to use computeKnownBits to determine | |||
9985 | // whether it's safe to decanonicalize the xor? | |||
9986 | // x s< 0 ? x^C : 0 --> usubsat x, C | |||
9987 | if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) { | |||
9988 | if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR && | |||
9989 | ISD::isBuildVectorAllZeros(CondRHS.getNode()) && | |||
9990 | OpRHSConst->getAPIntValue().isSignMask()) { | |||
9991 | // Note that we have to rebuild the RHS constant here to | |||
9992 | // ensure we don't rely on particular values of undef lanes. | |||
9993 | OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT); | |||
9994 | return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); | |||
9995 | } | |||
9996 | } | |||
9997 | } | |||
9998 | } | |||
9999 | } | |||
10000 | } | |||
10001 | } | |||
10002 | } | |||
10003 | ||||
10004 | if (SimplifySelectOps(N, N1, N2)) | |||
10005 | return SDValue(N, 0); // Don't revisit N. | |||
10006 | ||||
10007 | // Fold (vselect (build_vector all_ones), N1, N2) -> N1 | |||
10008 | if (ISD::isBuildVectorAllOnes(N0.getNode())) | |||
10009 | return N1; | |||
10010 | // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 | |||
10011 | if (ISD::isBuildVectorAllZeros(N0.getNode())) | |||
10012 | return N2; | |||
10013 | ||||
10014 | // The ConvertSelectToConcatVector function is assuming both the above | |||
10015 | // checks for (vselect (build_vector all{ones,zeros) ...) have been made | |||
10016 | // and addressed. | |||
10017 | if (N1.getOpcode() == ISD::CONCAT_VECTORS && | |||
10018 | N2.getOpcode() == ISD::CONCAT_VECTORS && | |||
10019 | ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { | |||
10020 | if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) | |||
10021 | return CV; | |||
10022 | } | |||
10023 | ||||
10024 | if (SDValue V = foldVSelectOfConstants(N)) | |||
10025 | return V; | |||
10026 | ||||
10027 | return SDValue(); | |||
10028 | } | |||
10029 | ||||
10030 | SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { | |||
10031 | SDValue N0 = N->getOperand(0); | |||
10032 | SDValue N1 = N->getOperand(1); | |||
10033 | SDValue N2 = N->getOperand(2); | |||
10034 | SDValue N3 = N->getOperand(3); | |||
10035 | SDValue N4 = N->getOperand(4); | |||
10036 | ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); | |||
10037 | ||||
10038 | // fold select_cc lhs, rhs, x, x, cc -> x | |||
10039 | if (N2 == N3) | |||
10040 | return N2; | |||
10041 | ||||
10042 | // Determine if the condition we're dealing with is constant | |||
10043 | if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, | |||
10044 | CC, SDLoc(N), false)) { | |||
10045 | AddToWorklist(SCC.getNode()); | |||
10046 | ||||
10047 | if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { | |||
10048 | if (!SCCC->isNullValue()) | |||
10049 | return N2; // cond always true -> true val | |||
10050 | else | |||
10051 | return N3; // cond always false -> false val | |||
10052 | } else if (SCC->isUndef()) { | |||
10053 | // When the condition is UNDEF, just return the first operand. This is | |||
10054 | // coherent the DAG creation, no setcc node is created in this case | |||
10055 | return N2; | |||
10056 | } else if (SCC.getOpcode() == ISD::SETCC) { | |||
10057 | // Fold to a simpler select_cc | |||
10058 | SDValue SelectOp = DAG.getNode( | |||
10059 | ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0), | |||
10060 | SCC.getOperand(1), N2, N3, SCC.getOperand(2)); | |||
10061 | SelectOp->setFlags(SCC->getFlags()); | |||
10062 | return SelectOp; | |||
10063 | } | |||
10064 | } | |||
10065 | ||||
10066 | // If we can fold this based on the true/false value, do so. | |||
10067 | if (SimplifySelectOps(N, N2, N3)) | |||
10068 | return SDValue(N, 0); // Don't revisit N. | |||
10069 | ||||
10070 | // fold select_cc into other things, such as min/max/abs | |||
10071 | return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); | |||
10072 | } | |||
10073 | ||||
10074 | SDValue DAGCombiner::visitSETCC(SDNode *N) { | |||
10075 | // setcc is very commonly used as an argument to brcond. This pattern | |||
10076 | // also lend itself to numerous combines and, as a result, it is desired | |||
10077 | // we keep the argument to a brcond as a setcc as much as possible. | |||
10078 | bool PreferSetCC = | |||
10079 | N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; | |||
10080 | ||||
10081 | SDValue Combined = SimplifySetCC( | |||
10082 | N->getValueType(0), N->getOperand(0), N->getOperand(1), | |||
10083 | cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); | |||
10084 | ||||
10085 | if (!Combined) | |||
10086 | return SDValue(); | |||
10087 | ||||
10088 | // If we prefer to have a setcc, and we don't, we'll try our best to | |||
10089 | // recreate one using rebuildSetCC. | |||
10090 | if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { | |||
10091 | SDValue NewSetCC = rebuildSetCC(Combined); | |||
10092 | ||||
10093 | // We don't have anything interesting to combine to. | |||
10094 | if (NewSetCC.getNode() == N) | |||
10095 | return SDValue(); | |||
10096 | ||||
10097 | if (NewSetCC) | |||
10098 | return NewSetCC; | |||
10099 | } | |||
10100 | ||||
10101 | return Combined; | |||
10102 | } | |||
10103 | ||||
10104 | SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { | |||
10105 | SDValue LHS = N->getOperand(0); | |||
10106 | SDValue RHS = N->getOperand(1); | |||
10107 | SDValue Carry = N->getOperand(2); | |||
10108 | SDValue Cond = N->getOperand(3); | |||
10109 | ||||
10110 | // If Carry is false, fold to a regular SETCC. | |||
10111 | if (isNullConstant(Carry)) | |||
10112 | return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); | |||
10113 | ||||
10114 | return SDValue(); | |||
10115 | } | |||
10116 | ||||
10117 | /// Check if N satisfies: | |||
10118 | /// N is used once. | |||
10119 | /// N is a Load. | |||
10120 | /// The load is compatible with ExtOpcode. It means | |||
10121 | /// If load has explicit zero/sign extension, ExpOpcode must have the same | |||
10122 | /// extension. | |||
10123 | /// Otherwise returns true. | |||
10124 | static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) { | |||
10125 | if (!N.hasOneUse()) | |||
10126 | return false; | |||
10127 | ||||
10128 | if (!isa<LoadSDNode>(N)) | |||
10129 | return false; | |||
10130 | ||||
10131 | LoadSDNode *Load = cast<LoadSDNode>(N); | |||
10132 | ISD::LoadExtType LoadExt = Load->getExtensionType(); | |||
10133 | if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD) | |||
10134 | return true; | |||
10135 | ||||
10136 | // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same | |||
10137 | // extension. | |||
10138 | if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) || | |||
10139 | (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND)) | |||
10140 | return false; | |||
10141 | ||||
10142 | return true; | |||
10143 | } | |||
10144 | ||||
10145 | /// Fold | |||
10146 | /// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y) | |||
10147 | /// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y) | |||
10148 | /// (aext (select c, load x, load y)) -> (select c, extload x, extload y) | |||
10149 | /// This function is called by the DAGCombiner when visiting sext/zext/aext | |||
10150 | /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). | |||
10151 | static SDValue tryToFoldExtendSelectLoad(SDNode *N, const TargetLowering &TLI, | |||
10152 | SelectionDAG &DAG) { | |||
10153 | unsigned Opcode = N->getOpcode(); | |||
10154 | SDValue N0 = N->getOperand(0); | |||
10155 | EVT VT = N->getValueType(0); | |||
10156 | SDLoc DL(N); | |||
10157 | ||||
10158 | assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10160, __PRETTY_FUNCTION__)) | |||
10159 | Opcode == ISD::ANY_EXTEND) &&(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10160, __PRETTY_FUNCTION__)) | |||
10160 | "Expected EXTEND dag node in input!")(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10160, __PRETTY_FUNCTION__)); | |||
10161 | ||||
10162 | if (!(N0->getOpcode() == ISD::SELECT || N0->getOpcode() == ISD::VSELECT) || | |||
10163 | !N0.hasOneUse()) | |||
10164 | return SDValue(); | |||
10165 | ||||
10166 | SDValue Op1 = N0->getOperand(1); | |||
10167 | SDValue Op2 = N0->getOperand(2); | |||
10168 | if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode)) | |||
10169 | return SDValue(); | |||
10170 | ||||
10171 | auto ExtLoadOpcode = ISD::EXTLOAD; | |||
10172 | if (Opcode == ISD::SIGN_EXTEND) | |||
10173 | ExtLoadOpcode = ISD::SEXTLOAD; | |||
10174 | else if (Opcode == ISD::ZERO_EXTEND) | |||
10175 | ExtLoadOpcode = ISD::ZEXTLOAD; | |||
10176 | ||||
10177 | LoadSDNode *Load1 = cast<LoadSDNode>(Op1); | |||
10178 | LoadSDNode *Load2 = cast<LoadSDNode>(Op2); | |||
10179 | if (!TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load1->getMemoryVT()) || | |||
10180 | !TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load2->getMemoryVT())) | |||
10181 | return SDValue(); | |||
10182 | ||||
10183 | SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1); | |||
10184 | SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2); | |||
10185 | return DAG.getSelect(DL, VT, N0->getOperand(0), Ext1, Ext2); | |||
10186 | } | |||
10187 | ||||
10188 | /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or | |||
10189 | /// a build_vector of constants. | |||
10190 | /// This function is called by the DAGCombiner when visiting sext/zext/aext | |||
10191 | /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). | |||
10192 | /// Vector extends are not folded if operations are legal; this is to | |||
10193 | /// avoid introducing illegal build_vector dag nodes. | |||
10194 | static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, | |||
10195 | SelectionDAG &DAG, bool LegalTypes) { | |||
10196 | unsigned Opcode = N->getOpcode(); | |||
10197 | SDValue N0 = N->getOperand(0); | |||
10198 | EVT VT = N->getValueType(0); | |||
10199 | SDLoc DL(N); | |||
10200 | ||||
10201 | assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10204, __PRETTY_FUNCTION__)) | |||
10202 | Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10204, __PRETTY_FUNCTION__)) | |||
10203 | Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10204, __PRETTY_FUNCTION__)) | |||
10204 | && "Expected EXTEND dag node in input!")(((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && "Expected EXTEND dag node in input!" ) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10204, __PRETTY_FUNCTION__)); | |||
10205 | ||||
10206 | // fold (sext c1) -> c1 | |||
10207 | // fold (zext c1) -> c1 | |||
10208 | // fold (aext c1) -> c1 | |||
10209 | if (isa<ConstantSDNode>(N0)) | |||
10210 | return DAG.getNode(Opcode, DL, VT, N0); | |||
10211 | ||||
10212 | // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) | |||
10213 | // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2) | |||
10214 | // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) | |||
10215 | if (N0->getOpcode() == ISD::SELECT) { | |||
10216 | SDValue Op1 = N0->getOperand(1); | |||
10217 | SDValue Op2 = N0->getOperand(2); | |||
10218 | if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) && | |||
10219 | (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) { | |||
10220 | // For any_extend, choose sign extension of the constants to allow a | |||
10221 | // possible further transform to sign_extend_inreg.i.e. | |||
10222 | // | |||
10223 | // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0> | |||
10224 | // t2: i64 = any_extend t1 | |||
10225 | // --> | |||
10226 | // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0> | |||
10227 | // --> | |||
10228 | // t4: i64 = sign_extend_inreg t3 | |||
10229 | unsigned FoldOpc = Opcode; | |||
10230 | if (FoldOpc == ISD::ANY_EXTEND) | |||
10231 | FoldOpc = ISD::SIGN_EXTEND; | |||
10232 | return DAG.getSelect(DL, VT, N0->getOperand(0), | |||
10233 | DAG.getNode(FoldOpc, DL, VT, Op1), | |||
10234 | DAG.getNode(FoldOpc, DL, VT, Op2)); | |||
10235 | } | |||
10236 | } | |||
10237 | ||||
10238 | // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) | |||
10239 | // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) | |||
10240 | // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) | |||
10241 | EVT SVT = VT.getScalarType(); | |||
10242 | if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) && | |||
10243 | ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) | |||
10244 | return SDValue(); | |||
10245 | ||||
10246 | // We can fold this node into a build_vector. | |||
10247 | unsigned VTBits = SVT.getSizeInBits(); | |||
10248 | unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); | |||
10249 | SmallVector<SDValue, 8> Elts; | |||
10250 | unsigned NumElts = VT.getVectorNumElements(); | |||
10251 | ||||
10252 | // For zero-extensions, UNDEF elements still guarantee to have the upper | |||
10253 | // bits set to zero. | |||
10254 | bool IsZext = | |||
10255 | Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG; | |||
10256 | ||||
10257 | for (unsigned i = 0; i != NumElts; ++i) { | |||
10258 | SDValue Op = N0.getOperand(i); | |||
10259 | if (Op.isUndef()) { | |||
10260 | Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT)); | |||
10261 | continue; | |||
10262 | } | |||
10263 | ||||
10264 | SDLoc DL(Op); | |||
10265 | // Get the constant value and if needed trunc it to the size of the type. | |||
10266 | // Nodes like build_vector might have constants wider than the scalar type. | |||
10267 | APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); | |||
10268 | if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) | |||
10269 | Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); | |||
10270 | else | |||
10271 | Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); | |||
10272 | } | |||
10273 | ||||
10274 | return DAG.getBuildVector(VT, DL, Elts); | |||
10275 | } | |||
10276 | ||||
10277 | // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: | |||
10278 | // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" | |||
10279 | // transformation. Returns true if extension are possible and the above | |||
10280 | // mentioned transformation is profitable. | |||
10281 | static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, | |||
10282 | unsigned ExtOpc, | |||
10283 | SmallVectorImpl<SDNode *> &ExtendNodes, | |||
10284 | const TargetLowering &TLI) { | |||
10285 | bool HasCopyToRegUses = false; | |||
10286 | bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); | |||
10287 | for (SDNode::use_iterator UI = N0.getNode()->use_begin(), | |||
10288 | UE = N0.getNode()->use_end(); | |||
10289 | UI != UE; ++UI) { | |||
10290 | SDNode *User = *UI; | |||
10291 | if (User == N) | |||
10292 | continue; | |||
10293 | if (UI.getUse().getResNo() != N0.getResNo()) | |||
10294 | continue; | |||
10295 | // FIXME: Only extend SETCC N, N and SETCC N, c for now. | |||
10296 | if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { | |||
10297 | ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); | |||
10298 | if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) | |||
10299 | // Sign bits will be lost after a zext. | |||
10300 | return false; | |||
10301 | bool Add = false; | |||
10302 | for (unsigned i = 0; i != 2; ++i) { | |||
10303 | SDValue UseOp = User->getOperand(i); | |||
10304 | if (UseOp == N0) | |||
10305 | continue; | |||
10306 | if (!isa<ConstantSDNode>(UseOp)) | |||
10307 | return false; | |||
10308 | Add = true; | |||
10309 | } | |||
10310 | if (Add) | |||
10311 | ExtendNodes.push_back(User); | |||
10312 | continue; | |||
10313 | } | |||
10314 | // If truncates aren't free and there are users we can't | |||
10315 | // extend, it isn't worthwhile. | |||
10316 | if (!isTruncFree) | |||
10317 | return false; | |||
10318 | // Remember if this value is live-out. | |||
10319 | if (User->getOpcode() == ISD::CopyToReg) | |||
10320 | HasCopyToRegUses = true; | |||
10321 | } | |||
10322 | ||||
10323 | if (HasCopyToRegUses) { | |||
10324 | bool BothLiveOut = false; | |||
10325 | for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); | |||
10326 | UI != UE; ++UI) { | |||
10327 | SDUse &Use = UI.getUse(); | |||
10328 | if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { | |||
10329 | BothLiveOut = true; | |||
10330 | break; | |||
10331 | } | |||
10332 | } | |||
10333 | if (BothLiveOut) | |||
10334 | // Both unextended and extended values are live out. There had better be | |||
10335 | // a good reason for the transformation. | |||
10336 | return ExtendNodes.size(); | |||
10337 | } | |||
10338 | return true; | |||
10339 | } | |||
10340 | ||||
10341 | void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, | |||
10342 | SDValue OrigLoad, SDValue ExtLoad, | |||
10343 | ISD::NodeType ExtType) { | |||
10344 | // Extend SetCC uses if necessary. | |||
10345 | SDLoc DL(ExtLoad); | |||
10346 | for (SDNode *SetCC : SetCCs) { | |||
10347 | SmallVector<SDValue, 4> Ops; | |||
10348 | ||||
10349 | for (unsigned j = 0; j != 2; ++j) { | |||
10350 | SDValue SOp = SetCC->getOperand(j); | |||
10351 | if (SOp == OrigLoad) | |||
10352 | Ops.push_back(ExtLoad); | |||
10353 | else | |||
10354 | Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); | |||
10355 | } | |||
10356 | ||||
10357 | Ops.push_back(SetCC->getOperand(2)); | |||
10358 | CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); | |||
10359 | } | |||
10360 | } | |||
10361 | ||||
10362 | // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). | |||
10363 | SDValue DAGCombiner::CombineExtLoad(SDNode *N) { | |||
10364 | SDValue N0 = N->getOperand(0); | |||
10365 | EVT DstVT = N->getValueType(0); | |||
10366 | EVT SrcVT = N0.getValueType(); | |||
10367 | ||||
10368 | assert((N->getOpcode() == ISD::SIGN_EXTEND ||(((N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!" ) ? static_cast<void> (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10370, __PRETTY_FUNCTION__)) | |||
10369 | N->getOpcode() == ISD::ZERO_EXTEND) &&(((N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!" ) ? static_cast<void> (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10370, __PRETTY_FUNCTION__)) | |||
10370 | "Unexpected node type (not an extend)!")(((N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!" ) ? static_cast<void> (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10370, __PRETTY_FUNCTION__)); | |||
10371 | ||||
10372 | // fold (sext (load x)) to multiple smaller sextloads; same for zext. | |||
10373 | // For example, on a target with legal v4i32, but illegal v8i32, turn: | |||
10374 | // (v8i32 (sext (v8i16 (load x)))) | |||
10375 | // into: | |||
10376 | // (v8i32 (concat_vectors (v4i32 (sextload x)), | |||
10377 | // (v4i32 (sextload (x + 16))))) | |||
10378 | // Where uses of the original load, i.e.: | |||
10379 | // (v8i16 (load x)) | |||
10380 | // are replaced with: | |||
10381 | // (v8i16 (truncate | |||
10382 | // (v8i32 (concat_vectors (v4i32 (sextload x)), | |||
10383 | // (v4i32 (sextload (x + 16))))))) | |||
10384 | // | |||
10385 | // This combine is only applicable to illegal, but splittable, vectors. | |||
10386 | // All legal types, and illegal non-vector types, are handled elsewhere. | |||
10387 | // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. | |||
10388 | // | |||
10389 | if (N0->getOpcode() != ISD::LOAD) | |||
10390 | return SDValue(); | |||
10391 | ||||
10392 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
10393 | ||||
10394 | if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || | |||
10395 | !N0.hasOneUse() || !LN0->isSimple() || | |||
10396 | !DstVT.isVector() || !DstVT.isPow2VectorType() || | |||
10397 | !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) | |||
10398 | return SDValue(); | |||
10399 | ||||
10400 | SmallVector<SDNode *, 4> SetCCs; | |||
10401 | if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) | |||
10402 | return SDValue(); | |||
10403 | ||||
10404 | ISD::LoadExtType ExtType = | |||
10405 | N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; | |||
10406 | ||||
10407 | // Try to split the vector types to get down to legal types. | |||
10408 | EVT SplitSrcVT = SrcVT; | |||
10409 | EVT SplitDstVT = DstVT; | |||
10410 | while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && | |||
10411 | SplitSrcVT.getVectorNumElements() > 1) { | |||
10412 | SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; | |||
10413 | SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; | |||
10414 | } | |||
10415 | ||||
10416 | if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) | |||
10417 | return SDValue(); | |||
10418 | ||||
10419 | assert(!DstVT.isScalableVector() && "Unexpected scalable vector type")((!DstVT.isScalableVector() && "Unexpected scalable vector type" ) ? static_cast<void> (0) : __assert_fail ("!DstVT.isScalableVector() && \"Unexpected scalable vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10419, __PRETTY_FUNCTION__)); | |||
10420 | ||||
10421 | SDLoc DL(N); | |||
10422 | const unsigned NumSplits = | |||
10423 | DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); | |||
10424 | const unsigned Stride = SplitSrcVT.getStoreSize(); | |||
10425 | SmallVector<SDValue, 4> Loads; | |||
10426 | SmallVector<SDValue, 4> Chains; | |||
10427 | ||||
10428 | SDValue BasePtr = LN0->getBasePtr(); | |||
10429 | for (unsigned Idx = 0; Idx < NumSplits; Idx++) { | |||
10430 | const unsigned Offset = Idx * Stride; | |||
10431 | const Align Align = commonAlignment(LN0->getAlign(), Offset); | |||
10432 | ||||
10433 | SDValue SplitLoad = DAG.getExtLoad( | |||
10434 | ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, | |||
10435 | LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, | |||
10436 | LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); | |||
10437 | ||||
10438 | BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(Stride), DL); | |||
10439 | ||||
10440 | Loads.push_back(SplitLoad.getValue(0)); | |||
10441 | Chains.push_back(SplitLoad.getValue(1)); | |||
10442 | } | |||
10443 | ||||
10444 | SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); | |||
10445 | SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); | |||
10446 | ||||
10447 | // Simplify TF. | |||
10448 | AddToWorklist(NewChain.getNode()); | |||
10449 | ||||
10450 | CombineTo(N, NewValue); | |||
10451 | ||||
10452 | // Replace uses of the original load (before extension) | |||
10453 | // with a truncate of the concatenated sextloaded vectors. | |||
10454 | SDValue Trunc = | |||
10455 | DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); | |||
10456 | ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); | |||
10457 | CombineTo(N0.getNode(), Trunc, NewChain); | |||
10458 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
10459 | } | |||
10460 | ||||
10461 | // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> | |||
10462 | // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) | |||
10463 | SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { | |||
10464 | assert(N->getOpcode() == ISD::ZERO_EXTEND)((N->getOpcode() == ISD::ZERO_EXTEND) ? static_cast<void > (0) : __assert_fail ("N->getOpcode() == ISD::ZERO_EXTEND" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10464, __PRETTY_FUNCTION__)); | |||
10465 | EVT VT = N->getValueType(0); | |||
10466 | EVT OrigVT = N->getOperand(0).getValueType(); | |||
10467 | if (TLI.isZExtFree(OrigVT, VT)) | |||
10468 | return SDValue(); | |||
10469 | ||||
10470 | // and/or/xor | |||
10471 | SDValue N0 = N->getOperand(0); | |||
10472 | if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || | |||
10473 | N0.getOpcode() == ISD::XOR) || | |||
10474 | N0.getOperand(1).getOpcode() != ISD::Constant || | |||
10475 | (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) | |||
10476 | return SDValue(); | |||
10477 | ||||
10478 | // shl/shr | |||
10479 | SDValue N1 = N0->getOperand(0); | |||
10480 | if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || | |||
10481 | N1.getOperand(1).getOpcode() != ISD::Constant || | |||
10482 | (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) | |||
10483 | return SDValue(); | |||
10484 | ||||
10485 | // load | |||
10486 | if (!isa<LoadSDNode>(N1.getOperand(0))) | |||
10487 | return SDValue(); | |||
10488 | LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); | |||
10489 | EVT MemVT = Load->getMemoryVT(); | |||
10490 | if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || | |||
10491 | Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) | |||
10492 | return SDValue(); | |||
10493 | ||||
10494 | ||||
10495 | // If the shift op is SHL, the logic op must be AND, otherwise the result | |||
10496 | // will be wrong. | |||
10497 | if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) | |||
10498 | return SDValue(); | |||
10499 | ||||
10500 | if (!N0.hasOneUse() || !N1.hasOneUse()) | |||
10501 | return SDValue(); | |||
10502 | ||||
10503 | SmallVector<SDNode*, 4> SetCCs; | |||
10504 | if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), | |||
10505 | ISD::ZERO_EXTEND, SetCCs, TLI)) | |||
10506 | return SDValue(); | |||
10507 | ||||
10508 | // Actually do the transformation. | |||
10509 | SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, | |||
10510 | Load->getChain(), Load->getBasePtr(), | |||
10511 | Load->getMemoryVT(), Load->getMemOperand()); | |||
10512 | ||||
10513 | SDLoc DL1(N1); | |||
10514 | SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, | |||
10515 | N1.getOperand(1)); | |||
10516 | ||||
10517 | APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); | |||
10518 | SDLoc DL0(N0); | |||
10519 | SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, | |||
10520 | DAG.getConstant(Mask, DL0, VT)); | |||
10521 | ||||
10522 | ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); | |||
10523 | CombineTo(N, And); | |||
10524 | if (SDValue(Load, 0).hasOneUse()) { | |||
10525 | DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); | |||
10526 | } else { | |||
10527 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), | |||
10528 | Load->getValueType(0), ExtLoad); | |||
10529 | CombineTo(Load, Trunc, ExtLoad.getValue(1)); | |||
10530 | } | |||
10531 | ||||
10532 | // N0 is dead at this point. | |||
10533 | recursivelyDeleteUnusedNodes(N0.getNode()); | |||
10534 | ||||
10535 | return SDValue(N,0); // Return N so it doesn't get rechecked! | |||
10536 | } | |||
10537 | ||||
10538 | /// If we're narrowing or widening the result of a vector select and the final | |||
10539 | /// size is the same size as a setcc (compare) feeding the select, then try to | |||
10540 | /// apply the cast operation to the select's operands because matching vector | |||
10541 | /// sizes for a select condition and other operands should be more efficient. | |||
10542 | SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { | |||
10543 | unsigned CastOpcode = Cast->getOpcode(); | |||
10544 | assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||(((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && "Unexpected opcode for vector select narrowing/widening" ) ? static_cast<void> (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10547, __PRETTY_FUNCTION__)) | |||
10545 | CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||(((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && "Unexpected opcode for vector select narrowing/widening" ) ? static_cast<void> (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10547, __PRETTY_FUNCTION__)) | |||
10546 | CastOpcode == ISD::FP_ROUND) &&(((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && "Unexpected opcode for vector select narrowing/widening" ) ? static_cast<void> (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10547, __PRETTY_FUNCTION__)) | |||
10547 | "Unexpected opcode for vector select narrowing/widening")(((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && "Unexpected opcode for vector select narrowing/widening" ) ? static_cast<void> (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10547, __PRETTY_FUNCTION__)); | |||
10548 | ||||
10549 | // We only do this transform before legal ops because the pattern may be | |||
10550 | // obfuscated by target-specific operations after legalization. Do not create | |||
10551 | // an illegal select op, however, because that may be difficult to lower. | |||
10552 | EVT VT = Cast->getValueType(0); | |||
10553 | if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) | |||
10554 | return SDValue(); | |||
10555 | ||||
10556 | SDValue VSel = Cast->getOperand(0); | |||
10557 | if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || | |||
10558 | VSel.getOperand(0).getOpcode() != ISD::SETCC) | |||
10559 | return SDValue(); | |||
10560 | ||||
10561 | // Does the setcc have the same vector size as the casted select? | |||
10562 | SDValue SetCC = VSel.getOperand(0); | |||
10563 | EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); | |||
10564 | if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) | |||
10565 | return SDValue(); | |||
10566 | ||||
10567 | // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) | |||
10568 | SDValue A = VSel.getOperand(1); | |||
10569 | SDValue B = VSel.getOperand(2); | |||
10570 | SDValue CastA, CastB; | |||
10571 | SDLoc DL(Cast); | |||
10572 | if (CastOpcode == ISD::FP_ROUND) { | |||
10573 | // FP_ROUND (fptrunc) has an extra flag operand to pass along. | |||
10574 | CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); | |||
10575 | CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); | |||
10576 | } else { | |||
10577 | CastA = DAG.getNode(CastOpcode, DL, VT, A); | |||
10578 | CastB = DAG.getNode(CastOpcode, DL, VT, B); | |||
10579 | } | |||
10580 | return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); | |||
10581 | } | |||
10582 | ||||
10583 | // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) | |||
10584 | // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) | |||
10585 | static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, | |||
10586 | const TargetLowering &TLI, EVT VT, | |||
10587 | bool LegalOperations, SDNode *N, | |||
10588 | SDValue N0, ISD::LoadExtType ExtLoadType) { | |||
10589 | SDNode *N0Node = N0.getNode(); | |||
10590 | bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) | |||
10591 | : ISD::isZEXTLoad(N0Node); | |||
10592 | if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || | |||
10593 | !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) | |||
10594 | return SDValue(); | |||
10595 | ||||
10596 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
10597 | EVT MemVT = LN0->getMemoryVT(); | |||
10598 | if ((LegalOperations || !LN0->isSimple() || | |||
10599 | VT.isVector()) && | |||
10600 | !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) | |||
10601 | return SDValue(); | |||
10602 | ||||
10603 | SDValue ExtLoad = | |||
10604 | DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), | |||
10605 | LN0->getBasePtr(), MemVT, LN0->getMemOperand()); | |||
10606 | Combiner.CombineTo(N, ExtLoad); | |||
10607 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); | |||
10608 | if (LN0->use_empty()) | |||
10609 | Combiner.recursivelyDeleteUnusedNodes(LN0); | |||
10610 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
10611 | } | |||
10612 | ||||
10613 | // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) | |||
10614 | // Only generate vector extloads when 1) they're legal, and 2) they are | |||
10615 | // deemed desirable by the target. | |||
10616 | static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, | |||
10617 | const TargetLowering &TLI, EVT VT, | |||
10618 | bool LegalOperations, SDNode *N, SDValue N0, | |||
10619 | ISD::LoadExtType ExtLoadType, | |||
10620 | ISD::NodeType ExtOpc) { | |||
10621 | if (!ISD::isNON_EXTLoad(N0.getNode()) || | |||
10622 | !ISD::isUNINDEXEDLoad(N0.getNode()) || | |||
10623 | ((LegalOperations || VT.isVector() || | |||
10624 | !cast<LoadSDNode>(N0)->isSimple()) && | |||
10625 | !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) | |||
10626 | return {}; | |||
10627 | ||||
10628 | bool DoXform = true; | |||
10629 | SmallVector<SDNode *, 4> SetCCs; | |||
10630 | if (!N0.hasOneUse()) | |||
10631 | DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); | |||
10632 | if (VT.isVector()) | |||
10633 | DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); | |||
10634 | if (!DoXform) | |||
10635 | return {}; | |||
10636 | ||||
10637 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
10638 | SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), | |||
10639 | LN0->getBasePtr(), N0.getValueType(), | |||
10640 | LN0->getMemOperand()); | |||
10641 | Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); | |||
10642 | // If the load value is used only by N, replace it via CombineTo N. | |||
10643 | bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); | |||
10644 | Combiner.CombineTo(N, ExtLoad); | |||
10645 | if (NoReplaceTrunc) { | |||
10646 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); | |||
10647 | Combiner.recursivelyDeleteUnusedNodes(LN0); | |||
10648 | } else { | |||
10649 | SDValue Trunc = | |||
10650 | DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); | |||
10651 | Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); | |||
10652 | } | |||
10653 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
10654 | } | |||
10655 | ||||
10656 | static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG, | |||
10657 | const TargetLowering &TLI, EVT VT, | |||
10658 | SDNode *N, SDValue N0, | |||
10659 | ISD::LoadExtType ExtLoadType, | |||
10660 | ISD::NodeType ExtOpc) { | |||
10661 | if (!N0.hasOneUse()) | |||
10662 | return SDValue(); | |||
10663 | ||||
10664 | MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0); | |||
10665 | if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD) | |||
10666 | return SDValue(); | |||
10667 | ||||
10668 | if (!TLI.isLoadExtLegal(ExtLoadType, VT, Ld->getValueType(0))) | |||
10669 | return SDValue(); | |||
10670 | ||||
10671 | if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0))) | |||
10672 | return SDValue(); | |||
10673 | ||||
10674 | SDLoc dl(Ld); | |||
10675 | SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru()); | |||
10676 | SDValue NewLoad = DAG.getMaskedLoad( | |||
10677 | VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(), | |||
10678 | PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(), | |||
10679 | ExtLoadType, Ld->isExpandingLoad()); | |||
10680 | DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1)); | |||
10681 | return NewLoad; | |||
10682 | } | |||
10683 | ||||
10684 | static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, | |||
10685 | bool LegalOperations) { | |||
10686 | assert((N->getOpcode() == ISD::SIGN_EXTEND ||(((N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext") ? static_cast <void> (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Expected sext or zext\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10687, __PRETTY_FUNCTION__)) | |||
10687 | N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext")(((N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext") ? static_cast <void> (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Expected sext or zext\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10687, __PRETTY_FUNCTION__)); | |||
10688 | ||||
10689 | SDValue SetCC = N->getOperand(0); | |||
10690 | if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || | |||
10691 | !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) | |||
10692 | return SDValue(); | |||
10693 | ||||
10694 | SDValue X = SetCC.getOperand(0); | |||
10695 | SDValue Ones = SetCC.getOperand(1); | |||
10696 | ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); | |||
10697 | EVT VT = N->getValueType(0); | |||
10698 | EVT XVT = X.getValueType(); | |||
10699 | // setge X, C is canonicalized to setgt, so we do not need to match that | |||
10700 | // pattern. The setlt sibling is folded in SimplifySelectCC() because it does | |||
10701 | // not require the 'not' op. | |||
10702 | if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { | |||
10703 | // Invert and smear/shift the sign bit: | |||
10704 | // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) | |||
10705 | // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) | |||
10706 | SDLoc DL(N); | |||
10707 | unsigned ShCt = VT.getSizeInBits() - 1; | |||
10708 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
10709 | if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { | |||
10710 | SDValue NotX = DAG.getNOT(DL, X, VT); | |||
10711 | SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT); | |||
10712 | auto ShiftOpcode = | |||
10713 | N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; | |||
10714 | return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); | |||
10715 | } | |||
10716 | } | |||
10717 | return SDValue(); | |||
10718 | } | |||
10719 | ||||
10720 | SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { | |||
10721 | SDValue N0 = N->getOperand(0); | |||
10722 | EVT VT = N->getValueType(0); | |||
10723 | SDLoc DL(N); | |||
10724 | ||||
10725 | if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) | |||
10726 | return Res; | |||
10727 | ||||
10728 | // fold (sext (sext x)) -> (sext x) | |||
10729 | // fold (sext (aext x)) -> (sext x) | |||
10730 | if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) | |||
10731 | return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); | |||
10732 | ||||
10733 | if (N0.getOpcode() == ISD::TRUNCATE) { | |||
10734 | // fold (sext (truncate (load x))) -> (sext (smaller load x)) | |||
10735 | // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) | |||
10736 | if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { | |||
10737 | SDNode *oye = N0.getOperand(0).getNode(); | |||
10738 | if (NarrowLoad.getNode() != N0.getNode()) { | |||
10739 | CombineTo(N0.getNode(), NarrowLoad); | |||
10740 | // CombineTo deleted the truncate, if needed, but not what's under it. | |||
10741 | AddToWorklist(oye); | |||
10742 | } | |||
10743 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
10744 | } | |||
10745 | ||||
10746 | // See if the value being truncated is already sign extended. If so, just | |||
10747 | // eliminate the trunc/sext pair. | |||
10748 | SDValue Op = N0.getOperand(0); | |||
10749 | unsigned OpBits = Op.getScalarValueSizeInBits(); | |||
10750 | unsigned MidBits = N0.getScalarValueSizeInBits(); | |||
10751 | unsigned DestBits = VT.getScalarSizeInBits(); | |||
10752 | unsigned NumSignBits = DAG.ComputeNumSignBits(Op); | |||
10753 | ||||
10754 | if (OpBits == DestBits) { | |||
10755 | // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign | |||
10756 | // bits, it is already ready. | |||
10757 | if (NumSignBits > DestBits-MidBits) | |||
10758 | return Op; | |||
10759 | } else if (OpBits < DestBits) { | |||
10760 | // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign | |||
10761 | // bits, just sext from i32. | |||
10762 | if (NumSignBits > OpBits-MidBits) | |||
10763 | return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); | |||
10764 | } else { | |||
10765 | // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign | |||
10766 | // bits, just truncate to i32. | |||
10767 | if (NumSignBits > OpBits-MidBits) | |||
10768 | return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); | |||
10769 | } | |||
10770 | ||||
10771 | // fold (sext (truncate x)) -> (sextinreg x). | |||
10772 | if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, | |||
10773 | N0.getValueType())) { | |||
10774 | if (OpBits < DestBits) | |||
10775 | Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); | |||
10776 | else if (OpBits > DestBits) | |||
10777 | Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); | |||
10778 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, | |||
10779 | DAG.getValueType(N0.getValueType())); | |||
10780 | } | |||
10781 | } | |||
10782 | ||||
10783 | // Try to simplify (sext (load x)). | |||
10784 | if (SDValue foldedExt = | |||
10785 | tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, | |||
10786 | ISD::SEXTLOAD, ISD::SIGN_EXTEND)) | |||
10787 | return foldedExt; | |||
10788 | ||||
10789 | if (SDValue foldedExt = | |||
10790 | tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD, | |||
10791 | ISD::SIGN_EXTEND)) | |||
10792 | return foldedExt; | |||
10793 | ||||
10794 | // fold (sext (load x)) to multiple smaller sextloads. | |||
10795 | // Only on illegal but splittable vectors. | |||
10796 | if (SDValue ExtLoad = CombineExtLoad(N)) | |||
10797 | return ExtLoad; | |||
10798 | ||||
10799 | // Try to simplify (sext (sextload x)). | |||
10800 | if (SDValue foldedExt = tryToFoldExtOfExtload( | |||
10801 | DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) | |||
10802 | return foldedExt; | |||
10803 | ||||
10804 | // fold (sext (and/or/xor (load x), cst)) -> | |||
10805 | // (and/or/xor (sextload x), (sext cst)) | |||
10806 | if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || | |||
10807 | N0.getOpcode() == ISD::XOR) && | |||
10808 | isa<LoadSDNode>(N0.getOperand(0)) && | |||
10809 | N0.getOperand(1).getOpcode() == ISD::Constant && | |||
10810 | (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { | |||
10811 | LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); | |||
10812 | EVT MemVT = LN00->getMemoryVT(); | |||
10813 | if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && | |||
10814 | LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { | |||
10815 | SmallVector<SDNode*, 4> SetCCs; | |||
10816 | bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), | |||
10817 | ISD::SIGN_EXTEND, SetCCs, TLI); | |||
10818 | if (DoXform) { | |||
10819 | SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, | |||
10820 | LN00->getChain(), LN00->getBasePtr(), | |||
10821 | LN00->getMemoryVT(), | |||
10822 | LN00->getMemOperand()); | |||
10823 | APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits()); | |||
10824 | SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, | |||
10825 | ExtLoad, DAG.getConstant(Mask, DL, VT)); | |||
10826 | ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); | |||
10827 | bool NoReplaceTruncAnd = !N0.hasOneUse(); | |||
10828 | bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); | |||
10829 | CombineTo(N, And); | |||
10830 | // If N0 has multiple uses, change other uses as well. | |||
10831 | if (NoReplaceTruncAnd) { | |||
10832 | SDValue TruncAnd = | |||
10833 | DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); | |||
10834 | CombineTo(N0.getNode(), TruncAnd); | |||
10835 | } | |||
10836 | if (NoReplaceTrunc) { | |||
10837 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); | |||
10838 | } else { | |||
10839 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), | |||
10840 | LN00->getValueType(0), ExtLoad); | |||
10841 | CombineTo(LN00, Trunc, ExtLoad.getValue(1)); | |||
10842 | } | |||
10843 | return SDValue(N,0); // Return N so it doesn't get rechecked! | |||
10844 | } | |||
10845 | } | |||
10846 | } | |||
10847 | ||||
10848 | if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) | |||
10849 | return V; | |||
10850 | ||||
10851 | if (N0.getOpcode() == ISD::SETCC) { | |||
10852 | SDValue N00 = N0.getOperand(0); | |||
10853 | SDValue N01 = N0.getOperand(1); | |||
10854 | ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); | |||
10855 | EVT N00VT = N00.getValueType(); | |||
10856 | ||||
10857 | // sext(setcc) -> sext_in_reg(vsetcc) for vectors. | |||
10858 | // Only do this before legalize for now. | |||
10859 | if (VT.isVector() && !LegalOperations && | |||
10860 | TLI.getBooleanContents(N00VT) == | |||
10861 | TargetLowering::ZeroOrNegativeOneBooleanContent) { | |||
10862 | // On some architectures (such as SSE/NEON/etc) the SETCC result type is | |||
10863 | // of the same size as the compared operands. Only optimize sext(setcc()) | |||
10864 | // if this is the case. | |||
10865 | EVT SVT = getSetCCResultType(N00VT); | |||
10866 | ||||
10867 | // If we already have the desired type, don't change it. | |||
10868 | if (SVT != N0.getValueType()) { | |||
10869 | // We know that the # elements of the results is the same as the | |||
10870 | // # elements of the compare (and the # elements of the compare result | |||
10871 | // for that matter). Check to see that they are the same size. If so, | |||
10872 | // we know that the element size of the sext'd result matches the | |||
10873 | // element size of the compare operands. | |||
10874 | if (VT.getSizeInBits() == SVT.getSizeInBits()) | |||
10875 | return DAG.getSetCC(DL, VT, N00, N01, CC); | |||
10876 | ||||
10877 | // If the desired elements are smaller or larger than the source | |||
10878 | // elements, we can use a matching integer vector type and then | |||
10879 | // truncate/sign extend. | |||
10880 | EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); | |||
10881 | if (SVT == MatchingVecType) { | |||
10882 | SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); | |||
10883 | return DAG.getSExtOrTrunc(VsetCC, DL, VT); | |||
10884 | } | |||
10885 | } | |||
10886 | } | |||
10887 | ||||
10888 | // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) | |||
10889 | // Here, T can be 1 or -1, depending on the type of the setcc and | |||
10890 | // getBooleanContents(). | |||
10891 | unsigned SetCCWidth = N0.getScalarValueSizeInBits(); | |||
10892 | ||||
10893 | // To determine the "true" side of the select, we need to know the high bit | |||
10894 | // of the value returned by the setcc if it evaluates to true. | |||
10895 | // If the type of the setcc is i1, then the true case of the select is just | |||
10896 | // sext(i1 1), that is, -1. | |||
10897 | // If the type of the setcc is larger (say, i8) then the value of the high | |||
10898 | // bit depends on getBooleanContents(), so ask TLI for a real "true" value | |||
10899 | // of the appropriate width. | |||
10900 | SDValue ExtTrueVal = (SetCCWidth == 1) | |||
10901 | ? DAG.getAllOnesConstant(DL, VT) | |||
10902 | : DAG.getBoolConstant(true, DL, VT, N00VT); | |||
10903 | SDValue Zero = DAG.getConstant(0, DL, VT); | |||
10904 | if (SDValue SCC = | |||
10905 | SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) | |||
10906 | return SCC; | |||
10907 | ||||
10908 | if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { | |||
10909 | EVT SetCCVT = getSetCCResultType(N00VT); | |||
10910 | // Don't do this transform for i1 because there's a select transform | |||
10911 | // that would reverse it. | |||
10912 | // TODO: We should not do this transform at all without a target hook | |||
10913 | // because a sext is likely cheaper than a select? | |||
10914 | if (SetCCVT.getScalarSizeInBits() != 1 && | |||
10915 | (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { | |||
10916 | SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); | |||
10917 | return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); | |||
10918 | } | |||
10919 | } | |||
10920 | } | |||
10921 | ||||
10922 | // fold (sext x) -> (zext x) if the sign bit is known zero. | |||
10923 | if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && | |||
10924 | DAG.SignBitIsZero(N0)) | |||
10925 | return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); | |||
10926 | ||||
10927 | if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) | |||
10928 | return NewVSel; | |||
10929 | ||||
10930 | // Eliminate this sign extend by doing a negation in the destination type: | |||
10931 | // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64) | |||
10932 | if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() && | |||
10933 | isNullOrNullSplat(N0.getOperand(0)) && | |||
10934 | N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND && | |||
10935 | TLI.isOperationLegalOrCustom(ISD::SUB, VT)) { | |||
10936 | SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT); | |||
10937 | return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext); | |||
10938 | } | |||
10939 | // Eliminate this sign extend by doing a decrement in the destination type: | |||
10940 | // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1) | |||
10941 | if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && | |||
10942 | isAllOnesOrAllOnesSplat(N0.getOperand(1)) && | |||
10943 | N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && | |||
10944 | TLI.isOperationLegalOrCustom(ISD::ADD, VT)) { | |||
10945 | SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT); | |||
10946 | return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); | |||
10947 | } | |||
10948 | ||||
10949 | // fold sext (not i1 X) -> add (zext i1 X), -1 | |||
10950 | // TODO: This could be extended to handle bool vectors. | |||
10951 | if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() && | |||
10952 | (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) && | |||
10953 | TLI.isOperationLegal(ISD::ADD, VT)))) { | |||
10954 | // If we can eliminate the 'not', the sext form should be better | |||
10955 | if (SDValue NewXor = visitXOR(N0.getNode())) { | |||
10956 | // Returning N0 is a form of in-visit replacement that may have | |||
10957 | // invalidated N0. | |||
10958 | if (NewXor.getNode() == N0.getNode()) { | |||
10959 | // Return SDValue here as the xor should have already been replaced in | |||
10960 | // this sext. | |||
10961 | return SDValue(); | |||
10962 | } else { | |||
10963 | // Return a new sext with the new xor. | |||
10964 | return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor); | |||
10965 | } | |||
10966 | } | |||
10967 | ||||
10968 | SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); | |||
10969 | return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); | |||
10970 | } | |||
10971 | ||||
10972 | if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) | |||
10973 | return Res; | |||
10974 | ||||
10975 | return SDValue(); | |||
10976 | } | |||
10977 | ||||
10978 | // isTruncateOf - If N is a truncate of some other value, return true, record | |||
10979 | // the value being truncated in Op and which of Op's bits are zero/one in Known. | |||
10980 | // This function computes KnownBits to avoid a duplicated call to | |||
10981 | // computeKnownBits in the caller. | |||
10982 | static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, | |||
10983 | KnownBits &Known) { | |||
10984 | if (N->getOpcode() == ISD::TRUNCATE) { | |||
10985 | Op = N->getOperand(0); | |||
10986 | Known = DAG.computeKnownBits(Op); | |||
10987 | return true; | |||
10988 | } | |||
10989 | ||||
10990 | if (N.getOpcode() != ISD::SETCC || | |||
10991 | N.getValueType().getScalarType() != MVT::i1 || | |||
10992 | cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE) | |||
10993 | return false; | |||
10994 | ||||
10995 | SDValue Op0 = N->getOperand(0); | |||
10996 | SDValue Op1 = N->getOperand(1); | |||
10997 | assert(Op0.getValueType() == Op1.getValueType())((Op0.getValueType() == Op1.getValueType()) ? static_cast< void> (0) : __assert_fail ("Op0.getValueType() == Op1.getValueType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 10997, __PRETTY_FUNCTION__)); | |||
10998 | ||||
10999 | if (isNullOrNullSplat(Op0)) | |||
11000 | Op = Op1; | |||
11001 | else if (isNullOrNullSplat(Op1)) | |||
11002 | Op = Op0; | |||
11003 | else | |||
11004 | return false; | |||
11005 | ||||
11006 | Known = DAG.computeKnownBits(Op); | |||
11007 | ||||
11008 | return (Known.Zero | 1).isAllOnesValue(); | |||
11009 | } | |||
11010 | ||||
11011 | /// Given an extending node with a pop-count operand, if the target does not | |||
11012 | /// support a pop-count in the narrow source type but does support it in the | |||
11013 | /// destination type, widen the pop-count to the destination type. | |||
11014 | static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) { | |||
11015 | assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||(((Extend->getOpcode() == ISD::ZERO_EXTEND || Extend->getOpcode () == ISD::ANY_EXTEND) && "Expected extend op") ? static_cast <void> (0) : __assert_fail ("(Extend->getOpcode() == ISD::ZERO_EXTEND || Extend->getOpcode() == ISD::ANY_EXTEND) && \"Expected extend op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11016, __PRETTY_FUNCTION__)) | |||
11016 | Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op")(((Extend->getOpcode() == ISD::ZERO_EXTEND || Extend->getOpcode () == ISD::ANY_EXTEND) && "Expected extend op") ? static_cast <void> (0) : __assert_fail ("(Extend->getOpcode() == ISD::ZERO_EXTEND || Extend->getOpcode() == ISD::ANY_EXTEND) && \"Expected extend op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11016, __PRETTY_FUNCTION__)); | |||
11017 | ||||
11018 | SDValue CtPop = Extend->getOperand(0); | |||
11019 | if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse()) | |||
11020 | return SDValue(); | |||
11021 | ||||
11022 | EVT VT = Extend->getValueType(0); | |||
11023 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
11024 | if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) || | |||
11025 | !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT)) | |||
11026 | return SDValue(); | |||
11027 | ||||
11028 | // zext (ctpop X) --> ctpop (zext X) | |||
11029 | SDLoc DL(Extend); | |||
11030 | SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT); | |||
11031 | return DAG.getNode(ISD::CTPOP, DL, VT, NewZext); | |||
11032 | } | |||
11033 | ||||
11034 | SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { | |||
11035 | SDValue N0 = N->getOperand(0); | |||
11036 | EVT VT = N->getValueType(0); | |||
11037 | ||||
11038 | if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) | |||
11039 | return Res; | |||
11040 | ||||
11041 | // fold (zext (zext x)) -> (zext x) | |||
11042 | // fold (zext (aext x)) -> (zext x) | |||
11043 | if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) | |||
11044 | return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, | |||
11045 | N0.getOperand(0)); | |||
11046 | ||||
11047 | // fold (zext (truncate x)) -> (zext x) or | |||
11048 | // (zext (truncate x)) -> (truncate x) | |||
11049 | // This is valid when the truncated bits of x are already zero. | |||
11050 | SDValue Op; | |||
11051 | KnownBits Known; | |||
11052 | if (isTruncateOf(DAG, N0, Op, Known)) { | |||
11053 | APInt TruncatedBits = | |||
11054 | (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ? | |||
11055 | APInt(Op.getScalarValueSizeInBits(), 0) : | |||
11056 | APInt::getBitsSet(Op.getScalarValueSizeInBits(), | |||
11057 | N0.getScalarValueSizeInBits(), | |||
11058 | std::min(Op.getScalarValueSizeInBits(), | |||
11059 | VT.getScalarSizeInBits())); | |||
11060 | if (TruncatedBits.isSubsetOf(Known.Zero)) | |||
11061 | return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); | |||
11062 | } | |||
11063 | ||||
11064 | // fold (zext (truncate x)) -> (and x, mask) | |||
11065 | if (N0.getOpcode() == ISD::TRUNCATE) { | |||
11066 | // fold (zext (truncate (load x))) -> (zext (smaller load x)) | |||
11067 | // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) | |||
11068 | if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { | |||
11069 | SDNode *oye = N0.getOperand(0).getNode(); | |||
11070 | if (NarrowLoad.getNode() != N0.getNode()) { | |||
11071 | CombineTo(N0.getNode(), NarrowLoad); | |||
11072 | // CombineTo deleted the truncate, if needed, but not what's under it. | |||
11073 | AddToWorklist(oye); | |||
11074 | } | |||
11075 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11076 | } | |||
11077 | ||||
11078 | EVT SrcVT = N0.getOperand(0).getValueType(); | |||
11079 | EVT MinVT = N0.getValueType(); | |||
11080 | ||||
11081 | // Try to mask before the extension to avoid having to generate a larger mask, | |||
11082 | // possibly over several sub-vectors. | |||
11083 | if (SrcVT.bitsLT(VT) && VT.isVector()) { | |||
11084 | if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && | |||
11085 | TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { | |||
11086 | SDValue Op = N0.getOperand(0); | |||
11087 | Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); | |||
11088 | AddToWorklist(Op.getNode()); | |||
11089 | SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); | |||
11090 | // Transfer the debug info; the new node is equivalent to N0. | |||
11091 | DAG.transferDbgValues(N0, ZExtOrTrunc); | |||
11092 | return ZExtOrTrunc; | |||
11093 | } | |||
11094 | } | |||
11095 | ||||
11096 | if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { | |||
11097 | SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); | |||
11098 | AddToWorklist(Op.getNode()); | |||
11099 | SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); | |||
11100 | // We may safely transfer the debug info describing the truncate node over | |||
11101 | // to the equivalent and operation. | |||
11102 | DAG.transferDbgValues(N0, And); | |||
11103 | return And; | |||
11104 | } | |||
11105 | } | |||
11106 | ||||
11107 | // Fold (zext (and (trunc x), cst)) -> (and x, cst), | |||
11108 | // if either of the casts is not free. | |||
11109 | if (N0.getOpcode() == ISD::AND && | |||
11110 | N0.getOperand(0).getOpcode() == ISD::TRUNCATE && | |||
11111 | N0.getOperand(1).getOpcode() == ISD::Constant && | |||
11112 | (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), | |||
11113 | N0.getValueType()) || | |||
11114 | !TLI.isZExtFree(N0.getValueType(), VT))) { | |||
11115 | SDValue X = N0.getOperand(0).getOperand(0); | |||
11116 | X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); | |||
11117 | APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); | |||
11118 | SDLoc DL(N); | |||
11119 | return DAG.getNode(ISD::AND, DL, VT, | |||
11120 | X, DAG.getConstant(Mask, DL, VT)); | |||
11121 | } | |||
11122 | ||||
11123 | // Try to simplify (zext (load x)). | |||
11124 | if (SDValue foldedExt = | |||
11125 | tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, | |||
11126 | ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) | |||
11127 | return foldedExt; | |||
11128 | ||||
11129 | if (SDValue foldedExt = | |||
11130 | tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD, | |||
11131 | ISD::ZERO_EXTEND)) | |||
11132 | return foldedExt; | |||
11133 | ||||
11134 | // fold (zext (load x)) to multiple smaller zextloads. | |||
11135 | // Only on illegal but splittable vectors. | |||
11136 | if (SDValue ExtLoad = CombineExtLoad(N)) | |||
11137 | return ExtLoad; | |||
11138 | ||||
11139 | // fold (zext (and/or/xor (load x), cst)) -> | |||
11140 | // (and/or/xor (zextload x), (zext cst)) | |||
11141 | // Unless (and (load x) cst) will match as a zextload already and has | |||
11142 | // additional users. | |||
11143 | if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || | |||
11144 | N0.getOpcode() == ISD::XOR) && | |||
11145 | isa<LoadSDNode>(N0.getOperand(0)) && | |||
11146 | N0.getOperand(1).getOpcode() == ISD::Constant && | |||
11147 | (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { | |||
11148 | LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); | |||
11149 | EVT MemVT = LN00->getMemoryVT(); | |||
11150 | if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && | |||
11151 | LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { | |||
11152 | bool DoXform = true; | |||
11153 | SmallVector<SDNode*, 4> SetCCs; | |||
11154 | if (!N0.hasOneUse()) { | |||
11155 | if (N0.getOpcode() == ISD::AND) { | |||
11156 | auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); | |||
11157 | EVT LoadResultTy = AndC->getValueType(0); | |||
11158 | EVT ExtVT; | |||
11159 | if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) | |||
11160 | DoXform = false; | |||
11161 | } | |||
11162 | } | |||
11163 | if (DoXform) | |||
11164 | DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), | |||
11165 | ISD::ZERO_EXTEND, SetCCs, TLI); | |||
11166 | if (DoXform) { | |||
11167 | SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, | |||
11168 | LN00->getChain(), LN00->getBasePtr(), | |||
11169 | LN00->getMemoryVT(), | |||
11170 | LN00->getMemOperand()); | |||
11171 | APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); | |||
11172 | SDLoc DL(N); | |||
11173 | SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, | |||
11174 | ExtLoad, DAG.getConstant(Mask, DL, VT)); | |||
11175 | ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); | |||
11176 | bool NoReplaceTruncAnd = !N0.hasOneUse(); | |||
11177 | bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); | |||
11178 | CombineTo(N, And); | |||
11179 | // If N0 has multiple uses, change other uses as well. | |||
11180 | if (NoReplaceTruncAnd) { | |||
11181 | SDValue TruncAnd = | |||
11182 | DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); | |||
11183 | CombineTo(N0.getNode(), TruncAnd); | |||
11184 | } | |||
11185 | if (NoReplaceTrunc) { | |||
11186 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); | |||
11187 | } else { | |||
11188 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), | |||
11189 | LN00->getValueType(0), ExtLoad); | |||
11190 | CombineTo(LN00, Trunc, ExtLoad.getValue(1)); | |||
11191 | } | |||
11192 | return SDValue(N,0); // Return N so it doesn't get rechecked! | |||
11193 | } | |||
11194 | } | |||
11195 | } | |||
11196 | ||||
11197 | // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> | |||
11198 | // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) | |||
11199 | if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) | |||
11200 | return ZExtLoad; | |||
11201 | ||||
11202 | // Try to simplify (zext (zextload x)). | |||
11203 | if (SDValue foldedExt = tryToFoldExtOfExtload( | |||
11204 | DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) | |||
11205 | return foldedExt; | |||
11206 | ||||
11207 | if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) | |||
11208 | return V; | |||
11209 | ||||
11210 | if (N0.getOpcode() == ISD::SETCC) { | |||
11211 | // Only do this before legalize for now. | |||
11212 | if (!LegalOperations && VT.isVector() && | |||
11213 | N0.getValueType().getVectorElementType() == MVT::i1) { | |||
11214 | EVT N00VT = N0.getOperand(0).getValueType(); | |||
11215 | if (getSetCCResultType(N00VT) == N0.getValueType()) | |||
11216 | return SDValue(); | |||
11217 | ||||
11218 | // We know that the # elements of the results is the same as the # | |||
11219 | // elements of the compare (and the # elements of the compare result for | |||
11220 | // that matter). Check to see that they are the same size. If so, we know | |||
11221 | // that the element size of the sext'd result matches the element size of | |||
11222 | // the compare operands. | |||
11223 | SDLoc DL(N); | |||
11224 | if (VT.getSizeInBits() == N00VT.getSizeInBits()) { | |||
11225 | // zext(setcc) -> zext_in_reg(vsetcc) for vectors. | |||
11226 | SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), | |||
11227 | N0.getOperand(1), N0.getOperand(2)); | |||
11228 | return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType()); | |||
11229 | } | |||
11230 | ||||
11231 | // If the desired elements are smaller or larger than the source | |||
11232 | // elements we can use a matching integer vector type and then | |||
11233 | // truncate/any extend followed by zext_in_reg. | |||
11234 | EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); | |||
11235 | SDValue VsetCC = | |||
11236 | DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), | |||
11237 | N0.getOperand(1), N0.getOperand(2)); | |||
11238 | return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL, | |||
11239 | N0.getValueType()); | |||
11240 | } | |||
11241 | ||||
11242 | // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc) | |||
11243 | SDLoc DL(N); | |||
11244 | EVT N0VT = N0.getValueType(); | |||
11245 | EVT N00VT = N0.getOperand(0).getValueType(); | |||
11246 | if (SDValue SCC = SimplifySelectCC( | |||
11247 | DL, N0.getOperand(0), N0.getOperand(1), | |||
11248 | DAG.getBoolConstant(true, DL, N0VT, N00VT), | |||
11249 | DAG.getBoolConstant(false, DL, N0VT, N00VT), | |||
11250 | cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) | |||
11251 | return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC); | |||
11252 | } | |||
11253 | ||||
11254 | // (zext (shl (zext x), cst)) -> (shl (zext x), cst) | |||
11255 | if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && | |||
11256 | isa<ConstantSDNode>(N0.getOperand(1)) && | |||
11257 | N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && | |||
11258 | N0.hasOneUse()) { | |||
11259 | SDValue ShAmt = N0.getOperand(1); | |||
11260 | if (N0.getOpcode() == ISD::SHL) { | |||
11261 | SDValue InnerZExt = N0.getOperand(0); | |||
11262 | // If the original shl may be shifting out bits, do not perform this | |||
11263 | // transformation. | |||
11264 | unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - | |||
11265 | InnerZExt.getOperand(0).getValueSizeInBits(); | |||
11266 | if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits)) | |||
11267 | return SDValue(); | |||
11268 | } | |||
11269 | ||||
11270 | SDLoc DL(N); | |||
11271 | ||||
11272 | // Ensure that the shift amount is wide enough for the shifted value. | |||
11273 | if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits()) | |||
11274 | ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); | |||
11275 | ||||
11276 | return DAG.getNode(N0.getOpcode(), DL, VT, | |||
11277 | DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), | |||
11278 | ShAmt); | |||
11279 | } | |||
11280 | ||||
11281 | if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) | |||
11282 | return NewVSel; | |||
11283 | ||||
11284 | if (SDValue NewCtPop = widenCtPop(N, DAG)) | |||
11285 | return NewCtPop; | |||
11286 | ||||
11287 | if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) | |||
11288 | return Res; | |||
11289 | ||||
11290 | return SDValue(); | |||
11291 | } | |||
11292 | ||||
11293 | SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { | |||
11294 | SDValue N0 = N->getOperand(0); | |||
11295 | EVT VT = N->getValueType(0); | |||
11296 | ||||
11297 | if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) | |||
11298 | return Res; | |||
11299 | ||||
11300 | // fold (aext (aext x)) -> (aext x) | |||
11301 | // fold (aext (zext x)) -> (zext x) | |||
11302 | // fold (aext (sext x)) -> (sext x) | |||
11303 | if (N0.getOpcode() == ISD::ANY_EXTEND || | |||
11304 | N0.getOpcode() == ISD::ZERO_EXTEND || | |||
11305 | N0.getOpcode() == ISD::SIGN_EXTEND) | |||
11306 | return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); | |||
11307 | ||||
11308 | // fold (aext (truncate (load x))) -> (aext (smaller load x)) | |||
11309 | // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) | |||
11310 | if (N0.getOpcode() == ISD::TRUNCATE) { | |||
11311 | if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { | |||
11312 | SDNode *oye = N0.getOperand(0).getNode(); | |||
11313 | if (NarrowLoad.getNode() != N0.getNode()) { | |||
11314 | CombineTo(N0.getNode(), NarrowLoad); | |||
11315 | // CombineTo deleted the truncate, if needed, but not what's under it. | |||
11316 | AddToWorklist(oye); | |||
11317 | } | |||
11318 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11319 | } | |||
11320 | } | |||
11321 | ||||
11322 | // fold (aext (truncate x)) | |||
11323 | if (N0.getOpcode() == ISD::TRUNCATE) | |||
11324 | return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); | |||
11325 | ||||
11326 | // Fold (aext (and (trunc x), cst)) -> (and x, cst) | |||
11327 | // if the trunc is not free. | |||
11328 | if (N0.getOpcode() == ISD::AND && | |||
11329 | N0.getOperand(0).getOpcode() == ISD::TRUNCATE && | |||
11330 | N0.getOperand(1).getOpcode() == ISD::Constant && | |||
11331 | !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), | |||
11332 | N0.getValueType())) { | |||
11333 | SDLoc DL(N); | |||
11334 | SDValue X = N0.getOperand(0).getOperand(0); | |||
11335 | X = DAG.getAnyExtOrTrunc(X, DL, VT); | |||
11336 | APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); | |||
11337 | return DAG.getNode(ISD::AND, DL, VT, | |||
11338 | X, DAG.getConstant(Mask, DL, VT)); | |||
11339 | } | |||
11340 | ||||
11341 | // fold (aext (load x)) -> (aext (truncate (extload x))) | |||
11342 | // None of the supported targets knows how to perform load and any_ext | |||
11343 | // on vectors in one instruction, so attempt to fold to zext instead. | |||
11344 | if (VT.isVector()) { | |||
11345 | // Try to simplify (zext (load x)). | |||
11346 | if (SDValue foldedExt = | |||
11347 | tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, | |||
11348 | ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) | |||
11349 | return foldedExt; | |||
11350 | } else if (ISD::isNON_EXTLoad(N0.getNode()) && | |||
11351 | ISD::isUNINDEXEDLoad(N0.getNode()) && | |||
11352 | TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { | |||
11353 | bool DoXform = true; | |||
11354 | SmallVector<SDNode *, 4> SetCCs; | |||
11355 | if (!N0.hasOneUse()) | |||
11356 | DoXform = | |||
11357 | ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI); | |||
11358 | if (DoXform) { | |||
11359 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
11360 | SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, | |||
11361 | LN0->getChain(), LN0->getBasePtr(), | |||
11362 | N0.getValueType(), LN0->getMemOperand()); | |||
11363 | ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); | |||
11364 | // If the load value is used only by N, replace it via CombineTo N. | |||
11365 | bool NoReplaceTrunc = N0.hasOneUse(); | |||
11366 | CombineTo(N, ExtLoad); | |||
11367 | if (NoReplaceTrunc) { | |||
11368 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); | |||
11369 | recursivelyDeleteUnusedNodes(LN0); | |||
11370 | } else { | |||
11371 | SDValue Trunc = | |||
11372 | DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); | |||
11373 | CombineTo(LN0, Trunc, ExtLoad.getValue(1)); | |||
11374 | } | |||
11375 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11376 | } | |||
11377 | } | |||
11378 | ||||
11379 | // fold (aext (zextload x)) -> (aext (truncate (zextload x))) | |||
11380 | // fold (aext (sextload x)) -> (aext (truncate (sextload x))) | |||
11381 | // fold (aext ( extload x)) -> (aext (truncate (extload x))) | |||
11382 | if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && | |||
11383 | ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { | |||
11384 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
11385 | ISD::LoadExtType ExtType = LN0->getExtensionType(); | |||
11386 | EVT MemVT = LN0->getMemoryVT(); | |||
11387 | if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { | |||
11388 | SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), | |||
11389 | VT, LN0->getChain(), LN0->getBasePtr(), | |||
11390 | MemVT, LN0->getMemOperand()); | |||
11391 | CombineTo(N, ExtLoad); | |||
11392 | DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); | |||
11393 | recursivelyDeleteUnusedNodes(LN0); | |||
11394 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11395 | } | |||
11396 | } | |||
11397 | ||||
11398 | if (N0.getOpcode() == ISD::SETCC) { | |||
11399 | // For vectors: | |||
11400 | // aext(setcc) -> vsetcc | |||
11401 | // aext(setcc) -> truncate(vsetcc) | |||
11402 | // aext(setcc) -> aext(vsetcc) | |||
11403 | // Only do this before legalize for now. | |||
11404 | if (VT.isVector() && !LegalOperations) { | |||
11405 | EVT N00VT = N0.getOperand(0).getValueType(); | |||
11406 | if (getSetCCResultType(N00VT) == N0.getValueType()) | |||
11407 | return SDValue(); | |||
11408 | ||||
11409 | // We know that the # elements of the results is the same as the | |||
11410 | // # elements of the compare (and the # elements of the compare result | |||
11411 | // for that matter). Check to see that they are the same size. If so, | |||
11412 | // we know that the element size of the sext'd result matches the | |||
11413 | // element size of the compare operands. | |||
11414 | if (VT.getSizeInBits() == N00VT.getSizeInBits()) | |||
11415 | return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), | |||
11416 | N0.getOperand(1), | |||
11417 | cast<CondCodeSDNode>(N0.getOperand(2))->get()); | |||
11418 | ||||
11419 | // If the desired elements are smaller or larger than the source | |||
11420 | // elements we can use a matching integer vector type and then | |||
11421 | // truncate/any extend | |||
11422 | EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); | |||
11423 | SDValue VsetCC = | |||
11424 | DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), | |||
11425 | N0.getOperand(1), | |||
11426 | cast<CondCodeSDNode>(N0.getOperand(2))->get()); | |||
11427 | return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); | |||
11428 | } | |||
11429 | ||||
11430 | // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc | |||
11431 | SDLoc DL(N); | |||
11432 | if (SDValue SCC = SimplifySelectCC( | |||
11433 | DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), | |||
11434 | DAG.getConstant(0, DL, VT), | |||
11435 | cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) | |||
11436 | return SCC; | |||
11437 | } | |||
11438 | ||||
11439 | if (SDValue NewCtPop = widenCtPop(N, DAG)) | |||
11440 | return NewCtPop; | |||
11441 | ||||
11442 | if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) | |||
11443 | return Res; | |||
11444 | ||||
11445 | return SDValue(); | |||
11446 | } | |||
11447 | ||||
11448 | SDValue DAGCombiner::visitAssertExt(SDNode *N) { | |||
11449 | unsigned Opcode = N->getOpcode(); | |||
11450 | SDValue N0 = N->getOperand(0); | |||
11451 | SDValue N1 = N->getOperand(1); | |||
11452 | EVT AssertVT = cast<VTSDNode>(N1)->getVT(); | |||
11453 | ||||
11454 | // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) | |||
11455 | if (N0.getOpcode() == Opcode && | |||
11456 | AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) | |||
11457 | return N0; | |||
11458 | ||||
11459 | if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && | |||
11460 | N0.getOperand(0).getOpcode() == Opcode) { | |||
11461 | // We have an assert, truncate, assert sandwich. Make one stronger assert | |||
11462 | // by asserting on the smallest asserted type to the larger source type. | |||
11463 | // This eliminates the later assert: | |||
11464 | // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN | |||
11465 | // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN | |||
11466 | SDValue BigA = N0.getOperand(0); | |||
11467 | EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); | |||
11468 | assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11470, __PRETTY_FUNCTION__)) | |||
11469 | "Asserting zero/sign-extended bits to a type larger than the "((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11470, __PRETTY_FUNCTION__)) | |||
11470 | "truncated destination does not provide information")((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11470, __PRETTY_FUNCTION__)); | |||
11471 | ||||
11472 | SDLoc DL(N); | |||
11473 | EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; | |||
11474 | SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); | |||
11475 | SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), | |||
11476 | BigA.getOperand(0), MinAssertVTVal); | |||
11477 | return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); | |||
11478 | } | |||
11479 | ||||
11480 | // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller | |||
11481 | // than X. Just move the AssertZext in front of the truncate and drop the | |||
11482 | // AssertSExt. | |||
11483 | if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && | |||
11484 | N0.getOperand(0).getOpcode() == ISD::AssertSext && | |||
11485 | Opcode == ISD::AssertZext) { | |||
11486 | SDValue BigA = N0.getOperand(0); | |||
11487 | EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); | |||
11488 | assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11490, __PRETTY_FUNCTION__)) | |||
11489 | "Asserting zero/sign-extended bits to a type larger than the "((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11490, __PRETTY_FUNCTION__)) | |||
11490 | "truncated destination does not provide information")((BigA_AssertVT.bitsLE(N0.getValueType()) && "Asserting zero/sign-extended bits to a type larger than the " "truncated destination does not provide information") ? static_cast <void> (0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 11490, __PRETTY_FUNCTION__)); | |||
11491 | ||||
11492 | if (AssertVT.bitsLT(BigA_AssertVT)) { | |||
11493 | SDLoc DL(N); | |||
11494 | SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), | |||
11495 | BigA.getOperand(0), N1); | |||
11496 | return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); | |||
11497 | } | |||
11498 | } | |||
11499 | ||||
11500 | return SDValue(); | |||
11501 | } | |||
11502 | ||||
11503 | SDValue DAGCombiner::visitAssertAlign(SDNode *N) { | |||
11504 | SDLoc DL(N); | |||
11505 | ||||
11506 | Align AL = cast<AssertAlignSDNode>(N)->getAlign(); | |||
11507 | SDValue N0 = N->getOperand(0); | |||
11508 | ||||
11509 | // Fold (assertalign (assertalign x, AL0), AL1) -> | |||
11510 | // (assertalign x, max(AL0, AL1)) | |||
11511 | if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0)) | |||
11512 | return DAG.getAssertAlign(DL, N0.getOperand(0), | |||
11513 | std::max(AL, AAN->getAlign())); | |||
11514 | ||||
11515 | // In rare cases, there are trivial arithmetic ops in source operands. Sink | |||
11516 | // this assert down to source operands so that those arithmetic ops could be | |||
11517 | // exposed to the DAG combining. | |||
11518 | switch (N0.getOpcode()) { | |||
11519 | default: | |||
11520 | break; | |||
11521 | case ISD::ADD: | |||
11522 | case ISD::SUB: { | |||
11523 | unsigned AlignShift = Log2(AL); | |||
11524 | SDValue LHS = N0.getOperand(0); | |||
11525 | SDValue RHS = N0.getOperand(1); | |||
11526 | unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros(); | |||
11527 | unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros(); | |||
11528 | if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) { | |||
11529 | if (LHSAlignShift < AlignShift) | |||
11530 | LHS = DAG.getAssertAlign(DL, LHS, AL); | |||
11531 | if (RHSAlignShift < AlignShift) | |||
11532 | RHS = DAG.getAssertAlign(DL, RHS, AL); | |||
11533 | return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS); | |||
11534 | } | |||
11535 | break; | |||
11536 | } | |||
11537 | } | |||
11538 | ||||
11539 | return SDValue(); | |||
11540 | } | |||
11541 | ||||
11542 | /// If the result of a wider load is shifted to right of N bits and then | |||
11543 | /// truncated to a narrower type and where N is a multiple of number of bits of | |||
11544 | /// the narrower type, transform it to a narrower load from address + N / num of | |||
11545 | /// bits of new type. Also narrow the load if the result is masked with an AND | |||
11546 | /// to effectively produce a smaller type. If the result is to be extended, also | |||
11547 | /// fold the extension to form a extending load. | |||
11548 | SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { | |||
11549 | unsigned Opc = N->getOpcode(); | |||
11550 | ||||
11551 | ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; | |||
11552 | SDValue N0 = N->getOperand(0); | |||
11553 | EVT VT = N->getValueType(0); | |||
11554 | EVT ExtVT = VT; | |||
11555 | ||||
11556 | // This transformation isn't valid for vector loads. | |||
11557 | if (VT.isVector()) | |||
11558 | return SDValue(); | |||
11559 | ||||
11560 | unsigned ShAmt = 0; | |||
11561 | bool HasShiftedOffset = false; | |||
11562 | // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then | |||
11563 | // extended to VT. | |||
11564 | if (Opc == ISD::SIGN_EXTEND_INREG) { | |||
11565 | ExtType = ISD::SEXTLOAD; | |||
11566 | ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); | |||
11567 | } else if (Opc == ISD::SRL) { | |||
11568 | // Another special-case: SRL is basically zero-extending a narrower value, | |||
11569 | // or it maybe shifting a higher subword, half or byte into the lowest | |||
11570 | // bits. | |||
11571 | ExtType = ISD::ZEXTLOAD; | |||
11572 | N0 = SDValue(N, 0); | |||
11573 | ||||
11574 | auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); | |||
11575 | auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); | |||
11576 | if (!N01 || !LN0) | |||
11577 | return SDValue(); | |||
11578 | ||||
11579 | uint64_t ShiftAmt = N01->getZExtValue(); | |||
11580 | uint64_t MemoryWidth = LN0->getMemoryVT().getScalarSizeInBits(); | |||
11581 | if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) | |||
11582 | ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); | |||
11583 | else | |||
11584 | ExtVT = EVT::getIntegerVT(*DAG.getContext(), | |||
11585 | VT.getScalarSizeInBits() - ShiftAmt); | |||
11586 | } else if (Opc == ISD::AND) { | |||
11587 | // An AND with a constant mask is the same as a truncate + zero-extend. | |||
11588 | auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); | |||
11589 | if (!AndC) | |||
11590 | return SDValue(); | |||
11591 | ||||
11592 | const APInt &Mask = AndC->getAPIntValue(); | |||
11593 | unsigned ActiveBits = 0; | |||
11594 | if (Mask.isMask()) { | |||
11595 | ActiveBits = Mask.countTrailingOnes(); | |||
11596 | } else if (Mask.isShiftedMask()) { | |||
11597 | ShAmt = Mask.countTrailingZeros(); | |||
11598 | APInt ShiftedMask = Mask.lshr(ShAmt); | |||
11599 | ActiveBits = ShiftedMask.countTrailingOnes(); | |||
11600 | HasShiftedOffset = true; | |||
11601 | } else | |||
11602 | return SDValue(); | |||
11603 | ||||
11604 | ExtType = ISD::ZEXTLOAD; | |||
11605 | ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); | |||
11606 | } | |||
11607 | ||||
11608 | if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { | |||
11609 | SDValue SRL = N0; | |||
11610 | if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { | |||
11611 | ShAmt = ConstShift->getZExtValue(); | |||
11612 | unsigned EVTBits = ExtVT.getScalarSizeInBits(); | |||
11613 | // Is the shift amount a multiple of size of VT? | |||
11614 | if ((ShAmt & (EVTBits-1)) == 0) { | |||
11615 | N0 = N0.getOperand(0); | |||
11616 | // Is the load width a multiple of size of VT? | |||
11617 | if ((N0.getScalarValueSizeInBits() & (EVTBits - 1)) != 0) | |||
11618 | return SDValue(); | |||
11619 | } | |||
11620 | ||||
11621 | // At this point, we must have a load or else we can't do the transform. | |||
11622 | auto *LN0 = dyn_cast<LoadSDNode>(N0); | |||
11623 | if (!LN0) return SDValue(); | |||
11624 | ||||
11625 | // Because a SRL must be assumed to *need* to zero-extend the high bits | |||
11626 | // (as opposed to anyext the high bits), we can't combine the zextload | |||
11627 | // lowering of SRL and an sextload. | |||
11628 | if (LN0->getExtensionType() == ISD::SEXTLOAD) | |||
11629 | return SDValue(); | |||
11630 | ||||
11631 | // If the shift amount is larger than the input type then we're not | |||
11632 | // accessing any of the loaded bytes. If the load was a zextload/extload | |||
11633 | // then the result of the shift+trunc is zero/undef (handled elsewhere). | |||
11634 | if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) | |||
11635 | return SDValue(); | |||
11636 | ||||
11637 | // If the SRL is only used by a masking AND, we may be able to adjust | |||
11638 | // the ExtVT to make the AND redundant. | |||
11639 | SDNode *Mask = *(SRL->use_begin()); | |||
11640 | if (Mask->getOpcode() == ISD::AND && | |||
11641 | isa<ConstantSDNode>(Mask->getOperand(1))) { | |||
11642 | const APInt& ShiftMask = Mask->getConstantOperandAPInt(1); | |||
11643 | if (ShiftMask.isMask()) { | |||
11644 | EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), | |||
11645 | ShiftMask.countTrailingOnes()); | |||
11646 | // If the mask is smaller, recompute the type. | |||
11647 | if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) && | |||
11648 | TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) | |||
11649 | ExtVT = MaskedVT; | |||
11650 | } | |||
11651 | } | |||
11652 | } | |||
11653 | } | |||
11654 | ||||
11655 | // If the load is shifted left (and the result isn't shifted back right), | |||
11656 | // we can fold the truncate through the shift. | |||
11657 | unsigned ShLeftAmt = 0; | |||
11658 | if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && | |||
11659 | ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { | |||
11660 | if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { | |||
11661 | ShLeftAmt = N01->getZExtValue(); | |||
11662 | N0 = N0.getOperand(0); | |||
11663 | } | |||
11664 | } | |||
11665 | ||||
11666 | // If we haven't found a load, we can't narrow it. | |||
11667 | if (!isa<LoadSDNode>(N0)) | |||
11668 | return SDValue(); | |||
11669 | ||||
11670 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
11671 | // Reducing the width of a volatile load is illegal. For atomics, we may be | |||
11672 | // able to reduce the width provided we never widen again. (see D66309) | |||
11673 | if (!LN0->isSimple() || | |||
11674 | !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) | |||
11675 | return SDValue(); | |||
11676 | ||||
11677 | auto AdjustBigEndianShift = [&](unsigned ShAmt) { | |||
11678 | unsigned LVTStoreBits = | |||
11679 | LN0->getMemoryVT().getStoreSizeInBits().getFixedSize(); | |||
11680 | unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedSize(); | |||
11681 | return LVTStoreBits - EVTStoreBits - ShAmt; | |||
11682 | }; | |||
11683 | ||||
11684 | // For big endian targets, we need to adjust the offset to the pointer to | |||
11685 | // load the correct bytes. | |||
11686 | if (DAG.getDataLayout().isBigEndian()) | |||
11687 | ShAmt = AdjustBigEndianShift(ShAmt); | |||
11688 | ||||
11689 | uint64_t PtrOff = ShAmt / 8; | |||
11690 | Align NewAlign = commonAlignment(LN0->getAlign(), PtrOff); | |||
11691 | SDLoc DL(LN0); | |||
11692 | // The original load itself didn't wrap, so an offset within it doesn't. | |||
11693 | SDNodeFlags Flags; | |||
11694 | Flags.setNoUnsignedWrap(true); | |||
11695 | SDValue NewPtr = DAG.getMemBasePlusOffset(LN0->getBasePtr(), | |||
11696 | TypeSize::Fixed(PtrOff), DL, Flags); | |||
11697 | AddToWorklist(NewPtr.getNode()); | |||
11698 | ||||
11699 | SDValue Load; | |||
11700 | if (ExtType == ISD::NON_EXTLOAD) | |||
11701 | Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr, | |||
11702 | LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, | |||
11703 | LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); | |||
11704 | else | |||
11705 | Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr, | |||
11706 | LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, | |||
11707 | NewAlign, LN0->getMemOperand()->getFlags(), | |||
11708 | LN0->getAAInfo()); | |||
11709 | ||||
11710 | // Replace the old load's chain with the new load's chain. | |||
11711 | WorklistRemover DeadNodes(*this); | |||
11712 | DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); | |||
11713 | ||||
11714 | // Shift the result left, if we've swallowed a left shift. | |||
11715 | SDValue Result = Load; | |||
11716 | if (ShLeftAmt != 0) { | |||
11717 | EVT ShImmTy = getShiftAmountTy(Result.getValueType()); | |||
11718 | if (!isUIntN(ShImmTy.getScalarSizeInBits(), ShLeftAmt)) | |||
11719 | ShImmTy = VT; | |||
11720 | // If the shift amount is as large as the result size (but, presumably, | |||
11721 | // no larger than the source) then the useful bits of the result are | |||
11722 | // zero; we can't simply return the shortened shift, because the result | |||
11723 | // of that operation is undefined. | |||
11724 | if (ShLeftAmt >= VT.getScalarSizeInBits()) | |||
11725 | Result = DAG.getConstant(0, DL, VT); | |||
11726 | else | |||
11727 | Result = DAG.getNode(ISD::SHL, DL, VT, | |||
11728 | Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); | |||
11729 | } | |||
11730 | ||||
11731 | if (HasShiftedOffset) { | |||
11732 | // Recalculate the shift amount after it has been altered to calculate | |||
11733 | // the offset. | |||
11734 | if (DAG.getDataLayout().isBigEndian()) | |||
11735 | ShAmt = AdjustBigEndianShift(ShAmt); | |||
11736 | ||||
11737 | // We're using a shifted mask, so the load now has an offset. This means | |||
11738 | // that data has been loaded into the lower bytes than it would have been | |||
11739 | // before, so we need to shl the loaded data into the correct position in the | |||
11740 | // register. | |||
11741 | SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); | |||
11742 | Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC); | |||
11743 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); | |||
11744 | } | |||
11745 | ||||
11746 | // Return the new loaded value. | |||
11747 | return Result; | |||
11748 | } | |||
11749 | ||||
11750 | SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { | |||
11751 | SDValue N0 = N->getOperand(0); | |||
11752 | SDValue N1 = N->getOperand(1); | |||
11753 | EVT VT = N->getValueType(0); | |||
11754 | EVT ExtVT = cast<VTSDNode>(N1)->getVT(); | |||
11755 | unsigned VTBits = VT.getScalarSizeInBits(); | |||
11756 | unsigned ExtVTBits = ExtVT.getScalarSizeInBits(); | |||
11757 | ||||
11758 | // sext_vector_inreg(undef) = 0 because the top bit will all be the same. | |||
11759 | if (N0.isUndef()) | |||
11760 | return DAG.getConstant(0, SDLoc(N), VT); | |||
11761 | ||||
11762 | // fold (sext_in_reg c1) -> c1 | |||
11763 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) | |||
11764 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); | |||
11765 | ||||
11766 | // If the input is already sign extended, just drop the extension. | |||
11767 | if (DAG.ComputeNumSignBits(N0) >= (VTBits - ExtVTBits + 1)) | |||
11768 | return N0; | |||
11769 | ||||
11770 | // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 | |||
11771 | if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && | |||
11772 | ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) | |||
11773 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0.getOperand(0), | |||
11774 | N1); | |||
11775 | ||||
11776 | // fold (sext_in_reg (sext x)) -> (sext x) | |||
11777 | // fold (sext_in_reg (aext x)) -> (sext x) | |||
11778 | // if x is small enough or if we know that x has more than 1 sign bit and the | |||
11779 | // sign_extend_inreg is extending from one of them. | |||
11780 | if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { | |||
11781 | SDValue N00 = N0.getOperand(0); | |||
11782 | unsigned N00Bits = N00.getScalarValueSizeInBits(); | |||
11783 | if ((N00Bits <= ExtVTBits || | |||
11784 | (N00Bits - DAG.ComputeNumSignBits(N00)) < ExtVTBits) && | |||
11785 | (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) | |||
11786 | return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00); | |||
11787 | } | |||
11788 | ||||
11789 | // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) | |||
11790 | // if x is small enough or if we know that x has more than 1 sign bit and the | |||
11791 | // sign_extend_inreg is extending from one of them. | |||
11792 | if (N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || | |||
11793 | N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || | |||
11794 | N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { | |||
11795 | SDValue N00 = N0.getOperand(0); | |||
11796 | unsigned N00Bits = N00.getScalarValueSizeInBits(); | |||
11797 | unsigned DstElts = N0.getValueType().getVectorMinNumElements(); | |||
11798 | unsigned SrcElts = N00.getValueType().getVectorMinNumElements(); | |||
11799 | bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; | |||
11800 | APInt DemandedSrcElts = APInt::getLowBitsSet(SrcElts, DstElts); | |||
11801 | if ((N00Bits == ExtVTBits || | |||
11802 | (!IsZext && (N00Bits < ExtVTBits || | |||
11803 | (N00Bits - DAG.ComputeNumSignBits(N00, DemandedSrcElts)) < | |||
11804 | ExtVTBits))) && | |||
11805 | (!LegalOperations || | |||
11806 | TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))) | |||
11807 | return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, N00); | |||
11808 | } | |||
11809 | ||||
11810 | // fold (sext_in_reg (zext x)) -> (sext x) | |||
11811 | // iff we are extending the source sign bit. | |||
11812 | if (N0.getOpcode() == ISD::ZERO_EXTEND) { | |||
11813 | SDValue N00 = N0.getOperand(0); | |||
11814 | if (N00.getScalarValueSizeInBits() == ExtVTBits && | |||
11815 | (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) | |||
11816 | return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); | |||
11817 | } | |||
11818 | ||||
11819 | // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. | |||
11820 | if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1))) | |||
11821 | return DAG.getZeroExtendInReg(N0, SDLoc(N), ExtVT); | |||
11822 | ||||
11823 | // fold operands of sext_in_reg based on knowledge that the top bits are not | |||
11824 | // demanded. | |||
11825 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
11826 | return SDValue(N, 0); | |||
11827 | ||||
11828 | // fold (sext_in_reg (load x)) -> (smaller sextload x) | |||
11829 | // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) | |||
11830 | if (SDValue NarrowLoad = ReduceLoadWidth(N)) | |||
11831 | return NarrowLoad; | |||
11832 | ||||
11833 | // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) | |||
11834 | // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. | |||
11835 | // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. | |||
11836 | if (N0.getOpcode() == ISD::SRL) { | |||
11837 | if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) | |||
11838 | if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) { | |||
11839 | // We can turn this into an SRA iff the input to the SRL is already sign | |||
11840 | // extended enough. | |||
11841 | unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); | |||
11842 | if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits) | |||
11843 | return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), | |||
11844 | N0.getOperand(1)); | |||
11845 | } | |||
11846 | } | |||
11847 | ||||
11848 | // fold (sext_inreg (extload x)) -> (sextload x) | |||
11849 | // If sextload is not supported by target, we can only do the combine when | |||
11850 | // load has one use. Doing otherwise can block folding the extload with other | |||
11851 | // extends that the target does support. | |||
11852 | if (ISD::isEXTLoad(N0.getNode()) && | |||
11853 | ISD::isUNINDEXEDLoad(N0.getNode()) && | |||
11854 | ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && | |||
11855 | ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() && | |||
11856 | N0.hasOneUse()) || | |||
11857 | TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { | |||
11858 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
11859 | SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, | |||
11860 | LN0->getChain(), | |||
11861 | LN0->getBasePtr(), ExtVT, | |||
11862 | LN0->getMemOperand()); | |||
11863 | CombineTo(N, ExtLoad); | |||
11864 | CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); | |||
11865 | AddToWorklist(ExtLoad.getNode()); | |||
11866 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11867 | } | |||
11868 | // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use | |||
11869 | if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && | |||
11870 | N0.hasOneUse() && | |||
11871 | ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && | |||
11872 | ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) && | |||
11873 | TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { | |||
11874 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
11875 | SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, | |||
11876 | LN0->getChain(), | |||
11877 | LN0->getBasePtr(), ExtVT, | |||
11878 | LN0->getMemOperand()); | |||
11879 | CombineTo(N, ExtLoad); | |||
11880 | CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); | |||
11881 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11882 | } | |||
11883 | ||||
11884 | // fold (sext_inreg (masked_load x)) -> (sext_masked_load x) | |||
11885 | // ignore it if the masked load is already sign extended | |||
11886 | if (MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0)) { | |||
11887 | if (ExtVT == Ld->getMemoryVT() && N0.hasOneUse() && | |||
11888 | Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD && | |||
11889 | TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT)) { | |||
11890 | SDValue ExtMaskedLoad = DAG.getMaskedLoad( | |||
11891 | VT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), | |||
11892 | Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(), | |||
11893 | Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad()); | |||
11894 | CombineTo(N, ExtMaskedLoad); | |||
11895 | CombineTo(N0.getNode(), ExtMaskedLoad, ExtMaskedLoad.getValue(1)); | |||
11896 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11897 | } | |||
11898 | } | |||
11899 | ||||
11900 | // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x) | |||
11901 | if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { | |||
11902 | if (SDValue(GN0, 0).hasOneUse() && | |||
11903 | ExtVT == GN0->getMemoryVT() && | |||
11904 | TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { | |||
11905 | SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), | |||
11906 | GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; | |||
11907 | ||||
11908 | SDValue ExtLoad = DAG.getMaskedGather( | |||
11909 | DAG.getVTList(VT, MVT::Other), ExtVT, SDLoc(N), Ops, | |||
11910 | GN0->getMemOperand(), GN0->getIndexType(), ISD::SEXTLOAD); | |||
11911 | ||||
11912 | CombineTo(N, ExtLoad); | |||
11913 | CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); | |||
11914 | AddToWorklist(ExtLoad.getNode()); | |||
11915 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
11916 | } | |||
11917 | } | |||
11918 | ||||
11919 | // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) | |||
11920 | if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) { | |||
11921 | if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), | |||
11922 | N0.getOperand(1), false)) | |||
11923 | return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, BSwap, N1); | |||
11924 | } | |||
11925 | ||||
11926 | return SDValue(); | |||
11927 | } | |||
11928 | ||||
11929 | SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { | |||
11930 | SDValue N0 = N->getOperand(0); | |||
11931 | EVT VT = N->getValueType(0); | |||
11932 | ||||
11933 | // sext_vector_inreg(undef) = 0 because the top bit will all be the same. | |||
11934 | if (N0.isUndef()) | |||
11935 | return DAG.getConstant(0, SDLoc(N), VT); | |||
11936 | ||||
11937 | if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) | |||
11938 | return Res; | |||
11939 | ||||
11940 | if (SimplifyDemandedVectorElts(SDValue(N, 0))) | |||
11941 | return SDValue(N, 0); | |||
11942 | ||||
11943 | return SDValue(); | |||
11944 | } | |||
11945 | ||||
11946 | SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { | |||
11947 | SDValue N0 = N->getOperand(0); | |||
11948 | EVT VT = N->getValueType(0); | |||
11949 | ||||
11950 | // zext_vector_inreg(undef) = 0 because the top bits will be zero. | |||
11951 | if (N0.isUndef()) | |||
11952 | return DAG.getConstant(0, SDLoc(N), VT); | |||
11953 | ||||
11954 | if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) | |||
11955 | return Res; | |||
11956 | ||||
11957 | if (SimplifyDemandedVectorElts(SDValue(N, 0))) | |||
11958 | return SDValue(N, 0); | |||
11959 | ||||
11960 | return SDValue(); | |||
11961 | } | |||
11962 | ||||
11963 | SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { | |||
11964 | SDValue N0 = N->getOperand(0); | |||
11965 | EVT VT = N->getValueType(0); | |||
11966 | EVT SrcVT = N0.getValueType(); | |||
11967 | bool isLE = DAG.getDataLayout().isLittleEndian(); | |||
11968 | ||||
11969 | // noop truncate | |||
11970 | if (SrcVT == VT) | |||
11971 | return N0; | |||
11972 | ||||
11973 | // fold (truncate (truncate x)) -> (truncate x) | |||
11974 | if (N0.getOpcode() == ISD::TRUNCATE) | |||
11975 | return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); | |||
11976 | ||||
11977 | // fold (truncate c1) -> c1 | |||
11978 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { | |||
11979 | SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); | |||
11980 | if (C.getNode() != N) | |||
11981 | return C; | |||
11982 | } | |||
11983 | ||||
11984 | // fold (truncate (ext x)) -> (ext x) or (truncate x) or x | |||
11985 | if (N0.getOpcode() == ISD::ZERO_EXTEND || | |||
11986 | N0.getOpcode() == ISD::SIGN_EXTEND || | |||
11987 | N0.getOpcode() == ISD::ANY_EXTEND) { | |||
11988 | // if the source is smaller than the dest, we still need an extend. | |||
11989 | if (N0.getOperand(0).getValueType().bitsLT(VT)) | |||
11990 | return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); | |||
11991 | // if the source is larger than the dest, than we just need the truncate. | |||
11992 | if (N0.getOperand(0).getValueType().bitsGT(VT)) | |||
11993 | return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); | |||
11994 | // if the source and dest are the same type, we can drop both the extend | |||
11995 | // and the truncate. | |||
11996 | return N0.getOperand(0); | |||
11997 | } | |||
11998 | ||||
11999 | // If this is anyext(trunc), don't fold it, allow ourselves to be folded. | |||
12000 | if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) | |||
12001 | return SDValue(); | |||
12002 | ||||
12003 | // Fold extract-and-trunc into a narrow extract. For example: | |||
12004 | // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) | |||
12005 | // i32 y = TRUNCATE(i64 x) | |||
12006 | // -- becomes -- | |||
12007 | // v16i8 b = BITCAST (v2i64 val) | |||
12008 | // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) | |||
12009 | // | |||
12010 | // Note: We only run this optimization after type legalization (which often | |||
12011 | // creates this pattern) and before operation legalization after which | |||
12012 | // we need to be more careful about the vector instructions that we generate. | |||
12013 | if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
12014 | LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { | |||
12015 | EVT VecTy = N0.getOperand(0).getValueType(); | |||
12016 | EVT ExTy = N0.getValueType(); | |||
12017 | EVT TrTy = N->getValueType(0); | |||
12018 | ||||
12019 | auto EltCnt = VecTy.getVectorElementCount(); | |||
12020 | unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); | |||
12021 | auto NewEltCnt = EltCnt * SizeRatio; | |||
12022 | ||||
12023 | EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt); | |||
12024 | assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size")((NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size" ) ? static_cast<void> (0) : __assert_fail ("NVT.getSizeInBits() == VecTy.getSizeInBits() && \"Invalid Size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12024, __PRETTY_FUNCTION__)); | |||
12025 | ||||
12026 | SDValue EltNo = N0->getOperand(1); | |||
12027 | if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { | |||
12028 | int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); | |||
12029 | int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); | |||
12030 | ||||
12031 | SDLoc DL(N); | |||
12032 | return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, | |||
12033 | DAG.getBitcast(NVT, N0.getOperand(0)), | |||
12034 | DAG.getVectorIdxConstant(Index, DL)); | |||
12035 | } | |||
12036 | } | |||
12037 | ||||
12038 | // trunc (select c, a, b) -> select c, (trunc a), (trunc b) | |||
12039 | if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { | |||
12040 | if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && | |||
12041 | TLI.isTruncateFree(SrcVT, VT)) { | |||
12042 | SDLoc SL(N0); | |||
12043 | SDValue Cond = N0.getOperand(0); | |||
12044 | SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); | |||
12045 | SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); | |||
12046 | return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); | |||
12047 | } | |||
12048 | } | |||
12049 | ||||
12050 | // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() | |||
12051 | if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && | |||
12052 | (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) && | |||
12053 | TLI.isTypeDesirableForOp(ISD::SHL, VT)) { | |||
12054 | SDValue Amt = N0.getOperand(1); | |||
12055 | KnownBits Known = DAG.computeKnownBits(Amt); | |||
12056 | unsigned Size = VT.getScalarSizeInBits(); | |||
12057 | if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { | |||
12058 | SDLoc SL(N); | |||
12059 | EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); | |||
12060 | ||||
12061 | SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); | |||
12062 | if (AmtVT != Amt.getValueType()) { | |||
12063 | Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); | |||
12064 | AddToWorklist(Amt.getNode()); | |||
12065 | } | |||
12066 | return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); | |||
12067 | } | |||
12068 | } | |||
12069 | ||||
12070 | if (SDValue V = foldSubToUSubSat(VT, N0.getNode())) | |||
12071 | return V; | |||
12072 | ||||
12073 | // Attempt to pre-truncate BUILD_VECTOR sources. | |||
12074 | if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations && | |||
12075 | TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) && | |||
12076 | // Avoid creating illegal types if running after type legalizer. | |||
12077 | (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) { | |||
12078 | SDLoc DL(N); | |||
12079 | EVT SVT = VT.getScalarType(); | |||
12080 | SmallVector<SDValue, 8> TruncOps; | |||
12081 | for (const SDValue &Op : N0->op_values()) { | |||
12082 | SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op); | |||
12083 | TruncOps.push_back(TruncOp); | |||
12084 | } | |||
12085 | return DAG.getBuildVector(VT, DL, TruncOps); | |||
12086 | } | |||
12087 | ||||
12088 | // Fold a series of buildvector, bitcast, and truncate if possible. | |||
12089 | // For example fold | |||
12090 | // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to | |||
12091 | // (2xi32 (buildvector x, y)). | |||
12092 | if (Level == AfterLegalizeVectorOps && VT.isVector() && | |||
12093 | N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && | |||
12094 | N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && | |||
12095 | N0.getOperand(0).hasOneUse()) { | |||
12096 | SDValue BuildVect = N0.getOperand(0); | |||
12097 | EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); | |||
12098 | EVT TruncVecEltTy = VT.getVectorElementType(); | |||
12099 | ||||
12100 | // Check that the element types match. | |||
12101 | if (BuildVectEltTy == TruncVecEltTy) { | |||
12102 | // Now we only need to compute the offset of the truncated elements. | |||
12103 | unsigned BuildVecNumElts = BuildVect.getNumOperands(); | |||
12104 | unsigned TruncVecNumElts = VT.getVectorNumElements(); | |||
12105 | unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; | |||
12106 | ||||
12107 | assert((BuildVecNumElts % TruncVecNumElts) == 0 &&(((BuildVecNumElts % TruncVecNumElts) == 0 && "Invalid number of elements" ) ? static_cast<void> (0) : __assert_fail ("(BuildVecNumElts % TruncVecNumElts) == 0 && \"Invalid number of elements\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12108, __PRETTY_FUNCTION__)) | |||
12108 | "Invalid number of elements")(((BuildVecNumElts % TruncVecNumElts) == 0 && "Invalid number of elements" ) ? static_cast<void> (0) : __assert_fail ("(BuildVecNumElts % TruncVecNumElts) == 0 && \"Invalid number of elements\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12108, __PRETTY_FUNCTION__)); | |||
12109 | ||||
12110 | SmallVector<SDValue, 8> Opnds; | |||
12111 | for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) | |||
12112 | Opnds.push_back(BuildVect.getOperand(i)); | |||
12113 | ||||
12114 | return DAG.getBuildVector(VT, SDLoc(N), Opnds); | |||
12115 | } | |||
12116 | } | |||
12117 | ||||
12118 | // See if we can simplify the input to this truncate through knowledge that | |||
12119 | // only the low bits are being used. | |||
12120 | // For example "trunc (or (shl x, 8), y)" // -> trunc y | |||
12121 | // Currently we only perform this optimization on scalars because vectors | |||
12122 | // may have different active low bits. | |||
12123 | if (!VT.isVector()) { | |||
12124 | APInt Mask = | |||
12125 | APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); | |||
12126 | if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) | |||
12127 | return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); | |||
12128 | } | |||
12129 | ||||
12130 | // fold (truncate (load x)) -> (smaller load x) | |||
12131 | // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) | |||
12132 | if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { | |||
12133 | if (SDValue Reduced = ReduceLoadWidth(N)) | |||
12134 | return Reduced; | |||
12135 | ||||
12136 | // Handle the case where the load remains an extending load even | |||
12137 | // after truncation. | |||
12138 | if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { | |||
12139 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
12140 | if (LN0->isSimple() && LN0->getMemoryVT().bitsLT(VT)) { | |||
12141 | SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), | |||
12142 | VT, LN0->getChain(), LN0->getBasePtr(), | |||
12143 | LN0->getMemoryVT(), | |||
12144 | LN0->getMemOperand()); | |||
12145 | DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); | |||
12146 | return NewLoad; | |||
12147 | } | |||
12148 | } | |||
12149 | } | |||
12150 | ||||
12151 | // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), | |||
12152 | // where ... are all 'undef'. | |||
12153 | if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { | |||
12154 | SmallVector<EVT, 8> VTs; | |||
12155 | SDValue V; | |||
12156 | unsigned Idx = 0; | |||
12157 | unsigned NumDefs = 0; | |||
12158 | ||||
12159 | for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { | |||
12160 | SDValue X = N0.getOperand(i); | |||
12161 | if (!X.isUndef()) { | |||
12162 | V = X; | |||
12163 | Idx = i; | |||
12164 | NumDefs++; | |||
12165 | } | |||
12166 | // Stop if more than one members are non-undef. | |||
12167 | if (NumDefs > 1) | |||
12168 | break; | |||
12169 | ||||
12170 | VTs.push_back(EVT::getVectorVT(*DAG.getContext(), | |||
12171 | VT.getVectorElementType(), | |||
12172 | X.getValueType().getVectorElementCount())); | |||
12173 | } | |||
12174 | ||||
12175 | if (NumDefs == 0) | |||
12176 | return DAG.getUNDEF(VT); | |||
12177 | ||||
12178 | if (NumDefs == 1) { | |||
12179 | assert(V.getNode() && "The single defined operand is empty!")((V.getNode() && "The single defined operand is empty!" ) ? static_cast<void> (0) : __assert_fail ("V.getNode() && \"The single defined operand is empty!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12179, __PRETTY_FUNCTION__)); | |||
12180 | SmallVector<SDValue, 8> Opnds; | |||
12181 | for (unsigned i = 0, e = VTs.size(); i != e; ++i) { | |||
12182 | if (i != Idx) { | |||
12183 | Opnds.push_back(DAG.getUNDEF(VTs[i])); | |||
12184 | continue; | |||
12185 | } | |||
12186 | SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); | |||
12187 | AddToWorklist(NV.getNode()); | |||
12188 | Opnds.push_back(NV); | |||
12189 | } | |||
12190 | return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); | |||
12191 | } | |||
12192 | } | |||
12193 | ||||
12194 | // Fold truncate of a bitcast of a vector to an extract of the low vector | |||
12195 | // element. | |||
12196 | // | |||
12197 | // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx | |||
12198 | if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { | |||
12199 | SDValue VecSrc = N0.getOperand(0); | |||
12200 | EVT VecSrcVT = VecSrc.getValueType(); | |||
12201 | if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT && | |||
12202 | (!LegalOperations || | |||
12203 | TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) { | |||
12204 | SDLoc SL(N); | |||
12205 | ||||
12206 | unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1; | |||
12207 | return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc, | |||
12208 | DAG.getVectorIdxConstant(Idx, SL)); | |||
12209 | } | |||
12210 | } | |||
12211 | ||||
12212 | // Simplify the operands using demanded-bits information. | |||
12213 | if (SimplifyDemandedBits(SDValue(N, 0))) | |||
12214 | return SDValue(N, 0); | |||
12215 | ||||
12216 | // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) | |||
12217 | // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) | |||
12218 | // When the adde's carry is not used. | |||
12219 | if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && | |||
12220 | N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && | |||
12221 | // We only do for addcarry before legalize operation | |||
12222 | ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) || | |||
12223 | TLI.isOperationLegal(N0.getOpcode(), VT))) { | |||
12224 | SDLoc SL(N); | |||
12225 | auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); | |||
12226 | auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); | |||
12227 | auto VTs = DAG.getVTList(VT, N0->getValueType(1)); | |||
12228 | return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); | |||
12229 | } | |||
12230 | ||||
12231 | // fold (truncate (extract_subvector(ext x))) -> | |||
12232 | // (extract_subvector x) | |||
12233 | // TODO: This can be generalized to cover cases where the truncate and extract | |||
12234 | // do not fully cancel each other out. | |||
12235 | if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { | |||
12236 | SDValue N00 = N0.getOperand(0); | |||
12237 | if (N00.getOpcode() == ISD::SIGN_EXTEND || | |||
12238 | N00.getOpcode() == ISD::ZERO_EXTEND || | |||
12239 | N00.getOpcode() == ISD::ANY_EXTEND) { | |||
12240 | if (N00.getOperand(0)->getValueType(0).getVectorElementType() == | |||
12241 | VT.getVectorElementType()) | |||
12242 | return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, | |||
12243 | N00.getOperand(0), N0.getOperand(1)); | |||
12244 | } | |||
12245 | } | |||
12246 | ||||
12247 | if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) | |||
12248 | return NewVSel; | |||
12249 | ||||
12250 | // Narrow a suitable binary operation with a non-opaque constant operand by | |||
12251 | // moving it ahead of the truncate. This is limited to pre-legalization | |||
12252 | // because targets may prefer a wider type during later combines and invert | |||
12253 | // this transform. | |||
12254 | switch (N0.getOpcode()) { | |||
12255 | case ISD::ADD: | |||
12256 | case ISD::SUB: | |||
12257 | case ISD::MUL: | |||
12258 | case ISD::AND: | |||
12259 | case ISD::OR: | |||
12260 | case ISD::XOR: | |||
12261 | if (!LegalOperations && N0.hasOneUse() && | |||
12262 | (isConstantOrConstantVector(N0.getOperand(0), true) || | |||
12263 | isConstantOrConstantVector(N0.getOperand(1), true))) { | |||
12264 | // TODO: We already restricted this to pre-legalization, but for vectors | |||
12265 | // we are extra cautious to not create an unsupported operation. | |||
12266 | // Target-specific changes are likely needed to avoid regressions here. | |||
12267 | if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) { | |||
12268 | SDLoc DL(N); | |||
12269 | SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0)); | |||
12270 | SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1)); | |||
12271 | return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR); | |||
12272 | } | |||
12273 | } | |||
12274 | break; | |||
12275 | case ISD::USUBSAT: | |||
12276 | // Truncate the USUBSAT only if LHS is a known zero-extension, its not | |||
12277 | // enough to know that the upper bits are zero we must ensure that we don't | |||
12278 | // introduce an extra truncate. | |||
12279 | if (!LegalOperations && N0.hasOneUse() && | |||
12280 | N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && | |||
12281 | N0.getOperand(0).getOperand(0).getScalarValueSizeInBits() <= | |||
12282 | VT.getScalarSizeInBits() && | |||
12283 | hasOperation(N0.getOpcode(), VT)) { | |||
12284 | return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1), | |||
12285 | DAG, SDLoc(N)); | |||
12286 | } | |||
12287 | break; | |||
12288 | } | |||
12289 | ||||
12290 | return SDValue(); | |||
12291 | } | |||
12292 | ||||
12293 | static SDNode *getBuildPairElt(SDNode *N, unsigned i) { | |||
12294 | SDValue Elt = N->getOperand(i); | |||
12295 | if (Elt.getOpcode() != ISD::MERGE_VALUES) | |||
12296 | return Elt.getNode(); | |||
12297 | return Elt.getOperand(Elt.getResNo()).getNode(); | |||
12298 | } | |||
12299 | ||||
12300 | /// build_pair (load, load) -> load | |||
12301 | /// if load locations are consecutive. | |||
12302 | SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { | |||
12303 | assert(N->getOpcode() == ISD::BUILD_PAIR)((N->getOpcode() == ISD::BUILD_PAIR) ? static_cast<void > (0) : __assert_fail ("N->getOpcode() == ISD::BUILD_PAIR" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12303, __PRETTY_FUNCTION__)); | |||
12304 | ||||
12305 | LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); | |||
12306 | LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); | |||
12307 | ||||
12308 | // A BUILD_PAIR is always having the least significant part in elt 0 and the | |||
12309 | // most significant part in elt 1. So when combining into one large load, we | |||
12310 | // need to consider the endianness. | |||
12311 | if (DAG.getDataLayout().isBigEndian()) | |||
12312 | std::swap(LD1, LD2); | |||
12313 | ||||
12314 | if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || | |||
12315 | LD1->getAddressSpace() != LD2->getAddressSpace()) | |||
12316 | return SDValue(); | |||
12317 | EVT LD1VT = LD1->getValueType(0); | |||
12318 | unsigned LD1Bytes = LD1VT.getStoreSize(); | |||
12319 | if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && | |||
12320 | DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { | |||
12321 | Align Alignment = LD1->getAlign(); | |||
12322 | Align NewAlign = DAG.getDataLayout().getABITypeAlign( | |||
12323 | VT.getTypeForEVT(*DAG.getContext())); | |||
12324 | ||||
12325 | if (NewAlign <= Alignment && | |||
12326 | (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) | |||
12327 | return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), | |||
12328 | LD1->getPointerInfo(), Alignment); | |||
12329 | } | |||
12330 | ||||
12331 | return SDValue(); | |||
12332 | } | |||
12333 | ||||
12334 | static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { | |||
12335 | // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi | |||
12336 | // and Lo parts; on big-endian machines it doesn't. | |||
12337 | return DAG.getDataLayout().isBigEndian() ? 1 : 0; | |||
12338 | } | |||
12339 | ||||
12340 | static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, | |||
12341 | const TargetLowering &TLI) { | |||
12342 | // If this is not a bitcast to an FP type or if the target doesn't have | |||
12343 | // IEEE754-compliant FP logic, we're done. | |||
12344 | EVT VT = N->getValueType(0); | |||
12345 | if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) | |||
12346 | return SDValue(); | |||
12347 | ||||
12348 | // TODO: Handle cases where the integer constant is a different scalar | |||
12349 | // bitwidth to the FP. | |||
12350 | SDValue N0 = N->getOperand(0); | |||
12351 | EVT SourceVT = N0.getValueType(); | |||
12352 | if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits()) | |||
12353 | return SDValue(); | |||
12354 | ||||
12355 | unsigned FPOpcode; | |||
12356 | APInt SignMask; | |||
12357 | switch (N0.getOpcode()) { | |||
12358 | case ISD::AND: | |||
12359 | FPOpcode = ISD::FABS; | |||
12360 | SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits()); | |||
12361 | break; | |||
12362 | case ISD::XOR: | |||
12363 | FPOpcode = ISD::FNEG; | |||
12364 | SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); | |||
12365 | break; | |||
12366 | case ISD::OR: | |||
12367 | FPOpcode = ISD::FABS; | |||
12368 | SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); | |||
12369 | break; | |||
12370 | default: | |||
12371 | return SDValue(); | |||
12372 | } | |||
12373 | ||||
12374 | // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X | |||
12375 | // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X | |||
12376 | // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) -> | |||
12377 | // fneg (fabs X) | |||
12378 | SDValue LogicOp0 = N0.getOperand(0); | |||
12379 | ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true); | |||
12380 | if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && | |||
12381 | LogicOp0.getOpcode() == ISD::BITCAST && | |||
12382 | LogicOp0.getOperand(0).getValueType() == VT) { | |||
12383 | SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0)); | |||
12384 | NumFPLogicOpsConv++; | |||
12385 | if (N0.getOpcode() == ISD::OR) | |||
12386 | return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp); | |||
12387 | return FPOp; | |||
12388 | } | |||
12389 | ||||
12390 | return SDValue(); | |||
12391 | } | |||
12392 | ||||
12393 | SDValue DAGCombiner::visitBITCAST(SDNode *N) { | |||
12394 | SDValue N0 = N->getOperand(0); | |||
12395 | EVT VT = N->getValueType(0); | |||
12396 | ||||
12397 | if (N0.isUndef()) | |||
12398 | return DAG.getUNDEF(VT); | |||
12399 | ||||
12400 | // If the input is a BUILD_VECTOR with all constant elements, fold this now. | |||
12401 | // Only do this before legalize types, unless both types are integer and the | |||
12402 | // scalar type is legal. Only do this before legalize ops, since the target | |||
12403 | // maybe depending on the bitcast. | |||
12404 | // First check to see if this is all constant. | |||
12405 | // TODO: Support FP bitcasts after legalize types. | |||
12406 | if (VT.isVector() && | |||
12407 | (!LegalTypes || | |||
12408 | (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() && | |||
12409 | TLI.isTypeLegal(VT.getVectorElementType()))) && | |||
12410 | N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && | |||
12411 | cast<BuildVectorSDNode>(N0)->isConstant()) | |||
12412 | return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), | |||
12413 | VT.getVectorElementType()); | |||
12414 | ||||
12415 | // If the input is a constant, let getNode fold it. | |||
12416 | if (isIntOrFPConstant(N0)) { | |||
12417 | // If we can't allow illegal operations, we need to check that this is just | |||
12418 | // a fp -> int or int -> conversion and that the resulting operation will | |||
12419 | // be legal. | |||
12420 | if (!LegalOperations || | |||
12421 | (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && | |||
12422 | TLI.isOperationLegal(ISD::ConstantFP, VT)) || | |||
12423 | (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && | |||
12424 | TLI.isOperationLegal(ISD::Constant, VT))) { | |||
12425 | SDValue C = DAG.getBitcast(VT, N0); | |||
12426 | if (C.getNode() != N) | |||
12427 | return C; | |||
12428 | } | |||
12429 | } | |||
12430 | ||||
12431 | // (conv (conv x, t1), t2) -> (conv x, t2) | |||
12432 | if (N0.getOpcode() == ISD::BITCAST) | |||
12433 | return DAG.getBitcast(VT, N0.getOperand(0)); | |||
12434 | ||||
12435 | // fold (conv (load x)) -> (load (conv*)x) | |||
12436 | // If the resultant load doesn't need a higher alignment than the original! | |||
12437 | if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && | |||
12438 | // Do not remove the cast if the types differ in endian layout. | |||
12439 | TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == | |||
12440 | TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && | |||
12441 | // If the load is volatile, we only want to change the load type if the | |||
12442 | // resulting load is legal. Otherwise we might increase the number of | |||
12443 | // memory accesses. We don't care if the original type was legal or not | |||
12444 | // as we assume software couldn't rely on the number of accesses of an | |||
12445 | // illegal type. | |||
12446 | ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) || | |||
12447 | TLI.isOperationLegal(ISD::LOAD, VT))) { | |||
12448 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
12449 | ||||
12450 | if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG, | |||
12451 | *LN0->getMemOperand())) { | |||
12452 | SDValue Load = | |||
12453 | DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), | |||
12454 | LN0->getPointerInfo(), LN0->getAlign(), | |||
12455 | LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); | |||
12456 | DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); | |||
12457 | return Load; | |||
12458 | } | |||
12459 | } | |||
12460 | ||||
12461 | if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) | |||
12462 | return V; | |||
12463 | ||||
12464 | // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) | |||
12465 | // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) | |||
12466 | // | |||
12467 | // For ppc_fp128: | |||
12468 | // fold (bitcast (fneg x)) -> | |||
12469 | // flipbit = signbit | |||
12470 | // (xor (bitcast x) (build_pair flipbit, flipbit)) | |||
12471 | // | |||
12472 | // fold (bitcast (fabs x)) -> | |||
12473 | // flipbit = (and (extract_element (bitcast x), 0), signbit) | |||
12474 | // (xor (bitcast x) (build_pair flipbit, flipbit)) | |||
12475 | // This often reduces constant pool loads. | |||
12476 | if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || | |||
12477 | (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && | |||
12478 | N0.getNode()->hasOneUse() && VT.isInteger() && | |||
12479 | !VT.isVector() && !N0.getValueType().isVector()) { | |||
12480 | SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); | |||
12481 | AddToWorklist(NewConv.getNode()); | |||
12482 | ||||
12483 | SDLoc DL(N); | |||
12484 | if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { | |||
12485 | assert(VT.getSizeInBits() == 128)((VT.getSizeInBits() == 128) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == 128", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12485, __PRETTY_FUNCTION__)); | |||
12486 | SDValue SignBit = DAG.getConstant( | |||
12487 | APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); | |||
12488 | SDValue FlipBit; | |||
12489 | if (N0.getOpcode() == ISD::FNEG) { | |||
12490 | FlipBit = SignBit; | |||
12491 | AddToWorklist(FlipBit.getNode()); | |||
12492 | } else { | |||
12493 | assert(N0.getOpcode() == ISD::FABS)((N0.getOpcode() == ISD::FABS) ? static_cast<void> (0) : __assert_fail ("N0.getOpcode() == ISD::FABS", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12493, __PRETTY_FUNCTION__)); | |||
12494 | SDValue Hi = | |||
12495 | DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, | |||
12496 | DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), | |||
12497 | SDLoc(NewConv))); | |||
12498 | AddToWorklist(Hi.getNode()); | |||
12499 | FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); | |||
12500 | AddToWorklist(FlipBit.getNode()); | |||
12501 | } | |||
12502 | SDValue FlipBits = | |||
12503 | DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); | |||
12504 | AddToWorklist(FlipBits.getNode()); | |||
12505 | return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); | |||
12506 | } | |||
12507 | APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); | |||
12508 | if (N0.getOpcode() == ISD::FNEG) | |||
12509 | return DAG.getNode(ISD::XOR, DL, VT, | |||
12510 | NewConv, DAG.getConstant(SignBit, DL, VT)); | |||
12511 | assert(N0.getOpcode() == ISD::FABS)((N0.getOpcode() == ISD::FABS) ? static_cast<void> (0) : __assert_fail ("N0.getOpcode() == ISD::FABS", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12511, __PRETTY_FUNCTION__)); | |||
12512 | return DAG.getNode(ISD::AND, DL, VT, | |||
12513 | NewConv, DAG.getConstant(~SignBit, DL, VT)); | |||
12514 | } | |||
12515 | ||||
12516 | // fold (bitconvert (fcopysign cst, x)) -> | |||
12517 | // (or (and (bitconvert x), sign), (and cst, (not sign))) | |||
12518 | // Note that we don't handle (copysign x, cst) because this can always be | |||
12519 | // folded to an fneg or fabs. | |||
12520 | // | |||
12521 | // For ppc_fp128: | |||
12522 | // fold (bitcast (fcopysign cst, x)) -> | |||
12523 | // flipbit = (and (extract_element | |||
12524 | // (xor (bitcast cst), (bitcast x)), 0), | |||
12525 | // signbit) | |||
12526 | // (xor (bitcast cst) (build_pair flipbit, flipbit)) | |||
12527 | if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && | |||
12528 | isa<ConstantFPSDNode>(N0.getOperand(0)) && | |||
12529 | VT.isInteger() && !VT.isVector()) { | |||
12530 | unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); | |||
12531 | EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); | |||
12532 | if (isTypeLegal(IntXVT)) { | |||
12533 | SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); | |||
12534 | AddToWorklist(X.getNode()); | |||
12535 | ||||
12536 | // If X has a different width than the result/lhs, sext it or truncate it. | |||
12537 | unsigned VTWidth = VT.getSizeInBits(); | |||
12538 | if (OrigXWidth < VTWidth) { | |||
12539 | X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); | |||
12540 | AddToWorklist(X.getNode()); | |||
12541 | } else if (OrigXWidth > VTWidth) { | |||
12542 | // To get the sign bit in the right place, we have to shift it right | |||
12543 | // before truncating. | |||
12544 | SDLoc DL(X); | |||
12545 | X = DAG.getNode(ISD::SRL, DL, | |||
12546 | X.getValueType(), X, | |||
12547 | DAG.getConstant(OrigXWidth-VTWidth, DL, | |||
12548 | X.getValueType())); | |||
12549 | AddToWorklist(X.getNode()); | |||
12550 | X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); | |||
12551 | AddToWorklist(X.getNode()); | |||
12552 | } | |||
12553 | ||||
12554 | if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { | |||
12555 | APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); | |||
12556 | SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); | |||
12557 | AddToWorklist(Cst.getNode()); | |||
12558 | SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); | |||
12559 | AddToWorklist(X.getNode()); | |||
12560 | SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); | |||
12561 | AddToWorklist(XorResult.getNode()); | |||
12562 | SDValue XorResult64 = DAG.getNode( | |||
12563 | ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, | |||
12564 | DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), | |||
12565 | SDLoc(XorResult))); | |||
12566 | AddToWorklist(XorResult64.getNode()); | |||
12567 | SDValue FlipBit = | |||
12568 | DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, | |||
12569 | DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); | |||
12570 | AddToWorklist(FlipBit.getNode()); | |||
12571 | SDValue FlipBits = | |||
12572 | DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); | |||
12573 | AddToWorklist(FlipBits.getNode()); | |||
12574 | return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); | |||
12575 | } | |||
12576 | APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); | |||
12577 | X = DAG.getNode(ISD::AND, SDLoc(X), VT, | |||
12578 | X, DAG.getConstant(SignBit, SDLoc(X), VT)); | |||
12579 | AddToWorklist(X.getNode()); | |||
12580 | ||||
12581 | SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); | |||
12582 | Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, | |||
12583 | Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); | |||
12584 | AddToWorklist(Cst.getNode()); | |||
12585 | ||||
12586 | return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); | |||
12587 | } | |||
12588 | } | |||
12589 | ||||
12590 | // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. | |||
12591 | if (N0.getOpcode() == ISD::BUILD_PAIR) | |||
12592 | if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) | |||
12593 | return CombineLD; | |||
12594 | ||||
12595 | // Remove double bitcasts from shuffles - this is often a legacy of | |||
12596 | // XformToShuffleWithZero being used to combine bitmaskings (of | |||
12597 | // float vectors bitcast to integer vectors) into shuffles. | |||
12598 | // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) | |||
12599 | if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && | |||
12600 | N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() && | |||
12601 | VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && | |||
12602 | !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { | |||
12603 | ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); | |||
12604 | ||||
12605 | // If operands are a bitcast, peek through if it casts the original VT. | |||
12606 | // If operands are a constant, just bitcast back to original VT. | |||
12607 | auto PeekThroughBitcast = [&](SDValue Op) { | |||
12608 | if (Op.getOpcode() == ISD::BITCAST && | |||
12609 | Op.getOperand(0).getValueType() == VT) | |||
12610 | return SDValue(Op.getOperand(0)); | |||
12611 | if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || | |||
12612 | ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) | |||
12613 | return DAG.getBitcast(VT, Op); | |||
12614 | return SDValue(); | |||
12615 | }; | |||
12616 | ||||
12617 | // FIXME: If either input vector is bitcast, try to convert the shuffle to | |||
12618 | // the result type of this bitcast. This would eliminate at least one | |||
12619 | // bitcast. See the transform in InstCombine. | |||
12620 | SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); | |||
12621 | SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); | |||
12622 | if (!(SV0 && SV1)) | |||
12623 | return SDValue(); | |||
12624 | ||||
12625 | int MaskScale = | |||
12626 | VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); | |||
12627 | SmallVector<int, 8> NewMask; | |||
12628 | for (int M : SVN->getMask()) | |||
12629 | for (int i = 0; i != MaskScale; ++i) | |||
12630 | NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); | |||
12631 | ||||
12632 | SDValue LegalShuffle = | |||
12633 | TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG); | |||
12634 | if (LegalShuffle) | |||
12635 | return LegalShuffle; | |||
12636 | } | |||
12637 | ||||
12638 | return SDValue(); | |||
12639 | } | |||
12640 | ||||
12641 | SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { | |||
12642 | EVT VT = N->getValueType(0); | |||
12643 | return CombineConsecutiveLoads(N, VT); | |||
12644 | } | |||
12645 | ||||
12646 | SDValue DAGCombiner::visitFREEZE(SDNode *N) { | |||
12647 | SDValue N0 = N->getOperand(0); | |||
12648 | ||||
12649 | // (freeze (freeze x)) -> (freeze x) | |||
12650 | if (N0.getOpcode() == ISD::FREEZE) | |||
12651 | return N0; | |||
12652 | ||||
12653 | // If the input is a constant, return it. | |||
12654 | if (isIntOrFPConstant(N0)) | |||
12655 | return N0; | |||
12656 | ||||
12657 | return SDValue(); | |||
12658 | } | |||
12659 | ||||
12660 | /// We know that BV is a build_vector node with Constant, ConstantFP or Undef | |||
12661 | /// operands. DstEltVT indicates the destination element value type. | |||
12662 | SDValue DAGCombiner:: | |||
12663 | ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { | |||
12664 | EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); | |||
12665 | ||||
12666 | // If this is already the right type, we're done. | |||
12667 | if (SrcEltVT == DstEltVT) return SDValue(BV, 0); | |||
12668 | ||||
12669 | unsigned SrcBitSize = SrcEltVT.getSizeInBits(); | |||
12670 | unsigned DstBitSize = DstEltVT.getSizeInBits(); | |||
12671 | ||||
12672 | // If this is a conversion of N elements of one type to N elements of another | |||
12673 | // type, convert each element. This handles FP<->INT cases. | |||
12674 | if (SrcBitSize == DstBitSize) { | |||
12675 | SmallVector<SDValue, 8> Ops; | |||
12676 | for (SDValue Op : BV->op_values()) { | |||
12677 | // If the vector element type is not legal, the BUILD_VECTOR operands | |||
12678 | // are promoted and implicitly truncated. Make that explicit here. | |||
12679 | if (Op.getValueType() != SrcEltVT) | |||
12680 | Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); | |||
12681 | Ops.push_back(DAG.getBitcast(DstEltVT, Op)); | |||
12682 | AddToWorklist(Ops.back().getNode()); | |||
12683 | } | |||
12684 | EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, | |||
12685 | BV->getValueType(0).getVectorNumElements()); | |||
12686 | return DAG.getBuildVector(VT, SDLoc(BV), Ops); | |||
12687 | } | |||
12688 | ||||
12689 | // Otherwise, we're growing or shrinking the elements. To avoid having to | |||
12690 | // handle annoying details of growing/shrinking FP values, we convert them to | |||
12691 | // int first. | |||
12692 | if (SrcEltVT.isFloatingPoint()) { | |||
12693 | // Convert the input float vector to a int vector where the elements are the | |||
12694 | // same sizes. | |||
12695 | EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); | |||
12696 | BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); | |||
12697 | SrcEltVT = IntVT; | |||
12698 | } | |||
12699 | ||||
12700 | // Now we know the input is an integer vector. If the output is a FP type, | |||
12701 | // convert to integer first, then to FP of the right size. | |||
12702 | if (DstEltVT.isFloatingPoint()) { | |||
12703 | EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); | |||
12704 | SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); | |||
12705 | ||||
12706 | // Next, convert to FP elements of the same size. | |||
12707 | return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); | |||
12708 | } | |||
12709 | ||||
12710 | SDLoc DL(BV); | |||
12711 | ||||
12712 | // Okay, we know the src/dst types are both integers of differing types. | |||
12713 | // Handling growing first. | |||
12714 | assert(SrcEltVT.isInteger() && DstEltVT.isInteger())((SrcEltVT.isInteger() && DstEltVT.isInteger()) ? static_cast <void> (0) : __assert_fail ("SrcEltVT.isInteger() && DstEltVT.isInteger()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 12714, __PRETTY_FUNCTION__)); | |||
12715 | if (SrcBitSize < DstBitSize) { | |||
12716 | unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; | |||
12717 | ||||
12718 | SmallVector<SDValue, 8> Ops; | |||
12719 | for (unsigned i = 0, e = BV->getNumOperands(); i != e; | |||
12720 | i += NumInputsPerOutput) { | |||
12721 | bool isLE = DAG.getDataLayout().isLittleEndian(); | |||
12722 | APInt NewBits = APInt(DstBitSize, 0); | |||
12723 | bool EltIsUndef = true; | |||
12724 | for (unsigned j = 0; j != NumInputsPerOutput; ++j) { | |||
12725 | // Shift the previously computed bits over. | |||
12726 | NewBits <<= SrcBitSize; | |||
12727 | SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); | |||
12728 | if (Op.isUndef()) continue; | |||
12729 | EltIsUndef = false; | |||
12730 | ||||
12731 | NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). | |||
12732 | zextOrTrunc(SrcBitSize).zext(DstBitSize); | |||
12733 | } | |||
12734 | ||||
12735 | if (EltIsUndef) | |||
12736 | Ops.push_back(DAG.getUNDEF(DstEltVT)); | |||
12737 | else | |||
12738 | Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); | |||
12739 | } | |||
12740 | ||||
12741 | EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); | |||
12742 | return DAG.getBuildVector(VT, DL, Ops); | |||
12743 | } | |||
12744 | ||||
12745 | // Finally, this must be the case where we are shrinking elements: each input | |||
12746 | // turns into multiple outputs. | |||
12747 | unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; | |||
12748 | EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, | |||
12749 | NumOutputsPerInput*BV->getNumOperands()); | |||
12750 | SmallVector<SDValue, 8> Ops; | |||
12751 | ||||
12752 | for (const SDValue &Op : BV->op_values()) { | |||
12753 | if (Op.isUndef()) { | |||
12754 | Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); | |||
12755 | continue; | |||
12756 | } | |||
12757 | ||||
12758 | APInt OpVal = cast<ConstantSDNode>(Op)-> | |||
12759 | getAPIntValue().zextOrTrunc(SrcBitSize); | |||
12760 | ||||
12761 | for (unsigned j = 0; j != NumOutputsPerInput; ++j) { | |||
12762 | APInt ThisVal = OpVal.trunc(DstBitSize); | |||
12763 | Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); | |||
12764 | OpVal.lshrInPlace(DstBitSize); | |||
12765 | } | |||
12766 | ||||
12767 | // For big endian targets, swap the order of the pieces of each element. | |||
12768 | if (DAG.getDataLayout().isBigEndian()) | |||
12769 | std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); | |||
12770 | } | |||
12771 | ||||
12772 | return DAG.getBuildVector(VT, DL, Ops); | |||
12773 | } | |||
12774 | ||||
12775 | static bool isContractable(SDNode *N) { | |||
12776 | SDNodeFlags F = N->getFlags(); | |||
12777 | return F.hasAllowContract() || F.hasAllowReassociation(); | |||
12778 | } | |||
12779 | ||||
12780 | /// Try to perform FMA combining on a given FADD node. | |||
12781 | SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { | |||
12782 | SDValue N0 = N->getOperand(0); | |||
12783 | SDValue N1 = N->getOperand(1); | |||
12784 | EVT VT = N->getValueType(0); | |||
12785 | SDLoc SL(N); | |||
12786 | ||||
12787 | const TargetOptions &Options = DAG.getTarget().Options; | |||
12788 | ||||
12789 | // Floating-point multiply-add with intermediate rounding. | |||
12790 | bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); | |||
12791 | ||||
12792 | // Floating-point multiply-add without intermediate rounding. | |||
12793 | bool HasFMA = | |||
12794 | TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && | |||
12795 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); | |||
12796 | ||||
12797 | // No valid opcode, do not combine. | |||
12798 | if (!HasFMAD && !HasFMA) | |||
12799 | return SDValue(); | |||
12800 | ||||
12801 | bool CanFuse = Options.UnsafeFPMath || isContractable(N); | |||
12802 | bool CanReassociate = | |||
12803 | Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); | |||
12804 | bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || | |||
12805 | CanFuse || HasFMAD); | |||
12806 | // If the addition is not contractable, do not combine. | |||
12807 | if (!AllowFusionGlobally && !isContractable(N)) | |||
12808 | return SDValue(); | |||
12809 | ||||
12810 | if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) | |||
12811 | return SDValue(); | |||
12812 | ||||
12813 | // Always prefer FMAD to FMA for precision. | |||
12814 | unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; | |||
12815 | bool Aggressive = TLI.enableAggressiveFMAFusion(VT); | |||
12816 | ||||
12817 | // Is the node an FMUL and contractable either due to global flags or | |||
12818 | // SDNodeFlags. | |||
12819 | auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { | |||
12820 | if (N.getOpcode() != ISD::FMUL) | |||
12821 | return false; | |||
12822 | return AllowFusionGlobally || isContractable(N.getNode()); | |||
12823 | }; | |||
12824 | // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), | |||
12825 | // prefer to fold the multiply with fewer uses. | |||
12826 | if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { | |||
12827 | if (N0.getNode()->use_size() > N1.getNode()->use_size()) | |||
12828 | std::swap(N0, N1); | |||
12829 | } | |||
12830 | ||||
12831 | // fold (fadd (fmul x, y), z) -> (fma x, y, z) | |||
12832 | if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { | |||
12833 | return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), | |||
12834 | N0.getOperand(1), N1); | |||
12835 | } | |||
12836 | ||||
12837 | // fold (fadd x, (fmul y, z)) -> (fma y, z, x) | |||
12838 | // Note: Commutes FADD operands. | |||
12839 | if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { | |||
12840 | return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0), | |||
12841 | N1.getOperand(1), N0); | |||
12842 | } | |||
12843 | ||||
12844 | // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E) | |||
12845 | // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E) | |||
12846 | // This requires reassociation because it changes the order of operations. | |||
12847 | SDValue FMA, E; | |||
12848 | if (CanReassociate && N0.getOpcode() == PreferredFusedOpcode && | |||
12849 | N0.getOperand(2).getOpcode() == ISD::FMUL && N0.hasOneUse() && | |||
12850 | N0.getOperand(2).hasOneUse()) { | |||
12851 | FMA = N0; | |||
12852 | E = N1; | |||
12853 | } else if (CanReassociate && N1.getOpcode() == PreferredFusedOpcode && | |||
12854 | N1.getOperand(2).getOpcode() == ISD::FMUL && N1.hasOneUse() && | |||
12855 | N1.getOperand(2).hasOneUse()) { | |||
12856 | FMA = N1; | |||
12857 | E = N0; | |||
12858 | } | |||
12859 | if (FMA && E) { | |||
12860 | SDValue A = FMA.getOperand(0); | |||
12861 | SDValue B = FMA.getOperand(1); | |||
12862 | SDValue C = FMA.getOperand(2).getOperand(0); | |||
12863 | SDValue D = FMA.getOperand(2).getOperand(1); | |||
12864 | SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E); | |||
12865 | return DAG.getNode(PreferredFusedOpcode, SL, VT, A, B, CDE); | |||
12866 | } | |||
12867 | ||||
12868 | // Look through FP_EXTEND nodes to do more combining. | |||
12869 | ||||
12870 | // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) | |||
12871 | if (N0.getOpcode() == ISD::FP_EXTEND) { | |||
12872 | SDValue N00 = N0.getOperand(0); | |||
12873 | if (isContractableFMUL(N00) && | |||
12874 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12875 | N00.getValueType())) { | |||
12876 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
12877 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), | |||
12878 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), | |||
12879 | N1); | |||
12880 | } | |||
12881 | } | |||
12882 | ||||
12883 | // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) | |||
12884 | // Note: Commutes FADD operands. | |||
12885 | if (N1.getOpcode() == ISD::FP_EXTEND) { | |||
12886 | SDValue N10 = N1.getOperand(0); | |||
12887 | if (isContractableFMUL(N10) && | |||
12888 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12889 | N10.getValueType())) { | |||
12890 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
12891 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)), | |||
12892 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), | |||
12893 | N0); | |||
12894 | } | |||
12895 | } | |||
12896 | ||||
12897 | // More folding opportunities when target permits. | |||
12898 | if (Aggressive) { | |||
12899 | // fold (fadd (fma x, y, (fpext (fmul u, v))), z) | |||
12900 | // -> (fma x, y, (fma (fpext u), (fpext v), z)) | |||
12901 | auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, | |||
12902 | SDValue Z) { | |||
12903 | return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, | |||
12904 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
12905 | DAG.getNode(ISD::FP_EXTEND, SL, VT, U), | |||
12906 | DAG.getNode(ISD::FP_EXTEND, SL, VT, V), | |||
12907 | Z)); | |||
12908 | }; | |||
12909 | if (N0.getOpcode() == PreferredFusedOpcode) { | |||
12910 | SDValue N02 = N0.getOperand(2); | |||
12911 | if (N02.getOpcode() == ISD::FP_EXTEND) { | |||
12912 | SDValue N020 = N02.getOperand(0); | |||
12913 | if (isContractableFMUL(N020) && | |||
12914 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12915 | N020.getValueType())) { | |||
12916 | return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), | |||
12917 | N020.getOperand(0), N020.getOperand(1), | |||
12918 | N1); | |||
12919 | } | |||
12920 | } | |||
12921 | } | |||
12922 | ||||
12923 | // fold (fadd (fpext (fma x, y, (fmul u, v))), z) | |||
12924 | // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) | |||
12925 | // FIXME: This turns two single-precision and one double-precision | |||
12926 | // operation into two double-precision operations, which might not be | |||
12927 | // interesting for all targets, especially GPUs. | |||
12928 | auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, | |||
12929 | SDValue Z) { | |||
12930 | return DAG.getNode( | |||
12931 | PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X), | |||
12932 | DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), | |||
12933 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
12934 | DAG.getNode(ISD::FP_EXTEND, SL, VT, U), | |||
12935 | DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z)); | |||
12936 | }; | |||
12937 | if (N0.getOpcode() == ISD::FP_EXTEND) { | |||
12938 | SDValue N00 = N0.getOperand(0); | |||
12939 | if (N00.getOpcode() == PreferredFusedOpcode) { | |||
12940 | SDValue N002 = N00.getOperand(2); | |||
12941 | if (isContractableFMUL(N002) && | |||
12942 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12943 | N00.getValueType())) { | |||
12944 | return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), | |||
12945 | N002.getOperand(0), N002.getOperand(1), | |||
12946 | N1); | |||
12947 | } | |||
12948 | } | |||
12949 | } | |||
12950 | ||||
12951 | // fold (fadd x, (fma y, z, (fpext (fmul u, v))) | |||
12952 | // -> (fma y, z, (fma (fpext u), (fpext v), x)) | |||
12953 | if (N1.getOpcode() == PreferredFusedOpcode) { | |||
12954 | SDValue N12 = N1.getOperand(2); | |||
12955 | if (N12.getOpcode() == ISD::FP_EXTEND) { | |||
12956 | SDValue N120 = N12.getOperand(0); | |||
12957 | if (isContractableFMUL(N120) && | |||
12958 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12959 | N120.getValueType())) { | |||
12960 | return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), | |||
12961 | N120.getOperand(0), N120.getOperand(1), | |||
12962 | N0); | |||
12963 | } | |||
12964 | } | |||
12965 | } | |||
12966 | ||||
12967 | // fold (fadd x, (fpext (fma y, z, (fmul u, v))) | |||
12968 | // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) | |||
12969 | // FIXME: This turns two single-precision and one double-precision | |||
12970 | // operation into two double-precision operations, which might not be | |||
12971 | // interesting for all targets, especially GPUs. | |||
12972 | if (N1.getOpcode() == ISD::FP_EXTEND) { | |||
12973 | SDValue N10 = N1.getOperand(0); | |||
12974 | if (N10.getOpcode() == PreferredFusedOpcode) { | |||
12975 | SDValue N102 = N10.getOperand(2); | |||
12976 | if (isContractableFMUL(N102) && | |||
12977 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
12978 | N10.getValueType())) { | |||
12979 | return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), | |||
12980 | N102.getOperand(0), N102.getOperand(1), | |||
12981 | N0); | |||
12982 | } | |||
12983 | } | |||
12984 | } | |||
12985 | } | |||
12986 | ||||
12987 | return SDValue(); | |||
12988 | } | |||
12989 | ||||
12990 | /// Try to perform FMA combining on a given FSUB node. | |||
12991 | SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { | |||
12992 | SDValue N0 = N->getOperand(0); | |||
12993 | SDValue N1 = N->getOperand(1); | |||
12994 | EVT VT = N->getValueType(0); | |||
12995 | SDLoc SL(N); | |||
12996 | ||||
12997 | const TargetOptions &Options = DAG.getTarget().Options; | |||
12998 | // Floating-point multiply-add with intermediate rounding. | |||
12999 | bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); | |||
13000 | ||||
13001 | // Floating-point multiply-add without intermediate rounding. | |||
13002 | bool HasFMA = | |||
13003 | TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && | |||
13004 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); | |||
13005 | ||||
13006 | // No valid opcode, do not combine. | |||
13007 | if (!HasFMAD && !HasFMA) | |||
13008 | return SDValue(); | |||
13009 | ||||
13010 | const SDNodeFlags Flags = N->getFlags(); | |||
13011 | bool CanFuse = Options.UnsafeFPMath || isContractable(N); | |||
13012 | bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || | |||
13013 | CanFuse || HasFMAD); | |||
13014 | ||||
13015 | // If the subtraction is not contractable, do not combine. | |||
13016 | if (!AllowFusionGlobally && !isContractable(N)) | |||
13017 | return SDValue(); | |||
13018 | ||||
13019 | if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) | |||
13020 | return SDValue(); | |||
13021 | ||||
13022 | // Always prefer FMAD to FMA for precision. | |||
13023 | unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; | |||
13024 | bool Aggressive = TLI.enableAggressiveFMAFusion(VT); | |||
13025 | bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros(); | |||
13026 | ||||
13027 | // Is the node an FMUL and contractable either due to global flags or | |||
13028 | // SDNodeFlags. | |||
13029 | auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { | |||
13030 | if (N.getOpcode() != ISD::FMUL) | |||
13031 | return false; | |||
13032 | return AllowFusionGlobally || isContractable(N.getNode()); | |||
13033 | }; | |||
13034 | ||||
13035 | // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) | |||
13036 | auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) { | |||
13037 | if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) { | |||
13038 | return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0), | |||
13039 | XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z)); | |||
13040 | } | |||
13041 | return SDValue(); | |||
13042 | }; | |||
13043 | ||||
13044 | // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) | |||
13045 | // Note: Commutes FSUB operands. | |||
13046 | auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) { | |||
13047 | if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) { | |||
13048 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13049 | DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)), | |||
13050 | YZ.getOperand(1), X); | |||
13051 | } | |||
13052 | return SDValue(); | |||
13053 | }; | |||
13054 | ||||
13055 | // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)), | |||
13056 | // prefer to fold the multiply with fewer uses. | |||
13057 | if (isContractableFMUL(N0) && isContractableFMUL(N1) && | |||
13058 | (N0.getNode()->use_size() > N1.getNode()->use_size())) { | |||
13059 | // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b)) | |||
13060 | if (SDValue V = tryToFoldXSubYZ(N0, N1)) | |||
13061 | return V; | |||
13062 | // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d))) | |||
13063 | if (SDValue V = tryToFoldXYSubZ(N0, N1)) | |||
13064 | return V; | |||
13065 | } else { | |||
13066 | // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) | |||
13067 | if (SDValue V = tryToFoldXYSubZ(N0, N1)) | |||
13068 | return V; | |||
13069 | // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) | |||
13070 | if (SDValue V = tryToFoldXSubYZ(N0, N1)) | |||
13071 | return V; | |||
13072 | } | |||
13073 | ||||
13074 | // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) | |||
13075 | if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && | |||
13076 | (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { | |||
13077 | SDValue N00 = N0.getOperand(0).getOperand(0); | |||
13078 | SDValue N01 = N0.getOperand(0).getOperand(1); | |||
13079 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13080 | DAG.getNode(ISD::FNEG, SL, VT, N00), N01, | |||
13081 | DAG.getNode(ISD::FNEG, SL, VT, N1)); | |||
13082 | } | |||
13083 | ||||
13084 | // Look through FP_EXTEND nodes to do more combining. | |||
13085 | ||||
13086 | // fold (fsub (fpext (fmul x, y)), z) | |||
13087 | // -> (fma (fpext x), (fpext y), (fneg z)) | |||
13088 | if (N0.getOpcode() == ISD::FP_EXTEND) { | |||
13089 | SDValue N00 = N0.getOperand(0); | |||
13090 | if (isContractableFMUL(N00) && | |||
13091 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13092 | N00.getValueType())) { | |||
13093 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13094 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), | |||
13095 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), | |||
13096 | DAG.getNode(ISD::FNEG, SL, VT, N1)); | |||
13097 | } | |||
13098 | } | |||
13099 | ||||
13100 | // fold (fsub x, (fpext (fmul y, z))) | |||
13101 | // -> (fma (fneg (fpext y)), (fpext z), x) | |||
13102 | // Note: Commutes FSUB operands. | |||
13103 | if (N1.getOpcode() == ISD::FP_EXTEND) { | |||
13104 | SDValue N10 = N1.getOperand(0); | |||
13105 | if (isContractableFMUL(N10) && | |||
13106 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13107 | N10.getValueType())) { | |||
13108 | return DAG.getNode( | |||
13109 | PreferredFusedOpcode, SL, VT, | |||
13110 | DAG.getNode(ISD::FNEG, SL, VT, | |||
13111 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))), | |||
13112 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0); | |||
13113 | } | |||
13114 | } | |||
13115 | ||||
13116 | // fold (fsub (fpext (fneg (fmul, x, y))), z) | |||
13117 | // -> (fneg (fma (fpext x), (fpext y), z)) | |||
13118 | // Note: This could be removed with appropriate canonicalization of the | |||
13119 | // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the | |||
13120 | // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent | |||
13121 | // from implementing the canonicalization in visitFSUB. | |||
13122 | if (N0.getOpcode() == ISD::FP_EXTEND) { | |||
13123 | SDValue N00 = N0.getOperand(0); | |||
13124 | if (N00.getOpcode() == ISD::FNEG) { | |||
13125 | SDValue N000 = N00.getOperand(0); | |||
13126 | if (isContractableFMUL(N000) && | |||
13127 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13128 | N00.getValueType())) { | |||
13129 | return DAG.getNode( | |||
13130 | ISD::FNEG, SL, VT, | |||
13131 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13132 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), | |||
13133 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), | |||
13134 | N1)); | |||
13135 | } | |||
13136 | } | |||
13137 | } | |||
13138 | ||||
13139 | // fold (fsub (fneg (fpext (fmul, x, y))), z) | |||
13140 | // -> (fneg (fma (fpext x)), (fpext y), z) | |||
13141 | // Note: This could be removed with appropriate canonicalization of the | |||
13142 | // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the | |||
13143 | // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent | |||
13144 | // from implementing the canonicalization in visitFSUB. | |||
13145 | if (N0.getOpcode() == ISD::FNEG) { | |||
13146 | SDValue N00 = N0.getOperand(0); | |||
13147 | if (N00.getOpcode() == ISD::FP_EXTEND) { | |||
13148 | SDValue N000 = N00.getOperand(0); | |||
13149 | if (isContractableFMUL(N000) && | |||
13150 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13151 | N000.getValueType())) { | |||
13152 | return DAG.getNode( | |||
13153 | ISD::FNEG, SL, VT, | |||
13154 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13155 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), | |||
13156 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), | |||
13157 | N1)); | |||
13158 | } | |||
13159 | } | |||
13160 | } | |||
13161 | ||||
13162 | // More folding opportunities when target permits. | |||
13163 | if (Aggressive) { | |||
13164 | // fold (fsub (fma x, y, (fmul u, v)), z) | |||
13165 | // -> (fma x, y (fma u, v, (fneg z))) | |||
13166 | if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && | |||
13167 | isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && | |||
13168 | N0.getOperand(2)->hasOneUse()) { | |||
13169 | return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), | |||
13170 | N0.getOperand(1), | |||
13171 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13172 | N0.getOperand(2).getOperand(0), | |||
13173 | N0.getOperand(2).getOperand(1), | |||
13174 | DAG.getNode(ISD::FNEG, SL, VT, N1))); | |||
13175 | } | |||
13176 | ||||
13177 | // fold (fsub x, (fma y, z, (fmul u, v))) | |||
13178 | // -> (fma (fneg y), z, (fma (fneg u), v, x)) | |||
13179 | if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && | |||
13180 | isContractableFMUL(N1.getOperand(2)) && | |||
13181 | N1->hasOneUse() && NoSignedZero) { | |||
13182 | SDValue N20 = N1.getOperand(2).getOperand(0); | |||
13183 | SDValue N21 = N1.getOperand(2).getOperand(1); | |||
13184 | return DAG.getNode( | |||
13185 | PreferredFusedOpcode, SL, VT, | |||
13186 | DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), | |||
13187 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13188 | DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0)); | |||
13189 | } | |||
13190 | ||||
13191 | ||||
13192 | // fold (fsub (fma x, y, (fpext (fmul u, v))), z) | |||
13193 | // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) | |||
13194 | if (N0.getOpcode() == PreferredFusedOpcode && | |||
13195 | N0->hasOneUse()) { | |||
13196 | SDValue N02 = N0.getOperand(2); | |||
13197 | if (N02.getOpcode() == ISD::FP_EXTEND) { | |||
13198 | SDValue N020 = N02.getOperand(0); | |||
13199 | if (isContractableFMUL(N020) && | |||
13200 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13201 | N020.getValueType())) { | |||
13202 | return DAG.getNode( | |||
13203 | PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1), | |||
13204 | DAG.getNode( | |||
13205 | PreferredFusedOpcode, SL, VT, | |||
13206 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)), | |||
13207 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)), | |||
13208 | DAG.getNode(ISD::FNEG, SL, VT, N1))); | |||
13209 | } | |||
13210 | } | |||
13211 | } | |||
13212 | ||||
13213 | // fold (fsub (fpext (fma x, y, (fmul u, v))), z) | |||
13214 | // -> (fma (fpext x), (fpext y), | |||
13215 | // (fma (fpext u), (fpext v), (fneg z))) | |||
13216 | // FIXME: This turns two single-precision and one double-precision | |||
13217 | // operation into two double-precision operations, which might not be | |||
13218 | // interesting for all targets, especially GPUs. | |||
13219 | if (N0.getOpcode() == ISD::FP_EXTEND) { | |||
13220 | SDValue N00 = N0.getOperand(0); | |||
13221 | if (N00.getOpcode() == PreferredFusedOpcode) { | |||
13222 | SDValue N002 = N00.getOperand(2); | |||
13223 | if (isContractableFMUL(N002) && | |||
13224 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13225 | N00.getValueType())) { | |||
13226 | return DAG.getNode( | |||
13227 | PreferredFusedOpcode, SL, VT, | |||
13228 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), | |||
13229 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), | |||
13230 | DAG.getNode( | |||
13231 | PreferredFusedOpcode, SL, VT, | |||
13232 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)), | |||
13233 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)), | |||
13234 | DAG.getNode(ISD::FNEG, SL, VT, N1))); | |||
13235 | } | |||
13236 | } | |||
13237 | } | |||
13238 | ||||
13239 | // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) | |||
13240 | // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) | |||
13241 | if (N1.getOpcode() == PreferredFusedOpcode && | |||
13242 | N1.getOperand(2).getOpcode() == ISD::FP_EXTEND && | |||
13243 | N1->hasOneUse()) { | |||
13244 | SDValue N120 = N1.getOperand(2).getOperand(0); | |||
13245 | if (isContractableFMUL(N120) && | |||
13246 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13247 | N120.getValueType())) { | |||
13248 | SDValue N1200 = N120.getOperand(0); | |||
13249 | SDValue N1201 = N120.getOperand(1); | |||
13250 | return DAG.getNode( | |||
13251 | PreferredFusedOpcode, SL, VT, | |||
13252 | DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), | |||
13253 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13254 | DAG.getNode(ISD::FNEG, SL, VT, | |||
13255 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)), | |||
13256 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0)); | |||
13257 | } | |||
13258 | } | |||
13259 | ||||
13260 | // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) | |||
13261 | // -> (fma (fneg (fpext y)), (fpext z), | |||
13262 | // (fma (fneg (fpext u)), (fpext v), x)) | |||
13263 | // FIXME: This turns two single-precision and one double-precision | |||
13264 | // operation into two double-precision operations, which might not be | |||
13265 | // interesting for all targets, especially GPUs. | |||
13266 | if (N1.getOpcode() == ISD::FP_EXTEND && | |||
13267 | N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { | |||
13268 | SDValue CvtSrc = N1.getOperand(0); | |||
13269 | SDValue N100 = CvtSrc.getOperand(0); | |||
13270 | SDValue N101 = CvtSrc.getOperand(1); | |||
13271 | SDValue N102 = CvtSrc.getOperand(2); | |||
13272 | if (isContractableFMUL(N102) && | |||
13273 | TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, | |||
13274 | CvtSrc.getValueType())) { | |||
13275 | SDValue N1020 = N102.getOperand(0); | |||
13276 | SDValue N1021 = N102.getOperand(1); | |||
13277 | return DAG.getNode( | |||
13278 | PreferredFusedOpcode, SL, VT, | |||
13279 | DAG.getNode(ISD::FNEG, SL, VT, | |||
13280 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)), | |||
13281 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), | |||
13282 | DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13283 | DAG.getNode(ISD::FNEG, SL, VT, | |||
13284 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)), | |||
13285 | DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0)); | |||
13286 | } | |||
13287 | } | |||
13288 | } | |||
13289 | ||||
13290 | return SDValue(); | |||
13291 | } | |||
13292 | ||||
13293 | /// Try to perform FMA combining on a given FMUL node based on the distributive | |||
13294 | /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, | |||
13295 | /// subtraction instead of addition). | |||
13296 | SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { | |||
13297 | SDValue N0 = N->getOperand(0); | |||
13298 | SDValue N1 = N->getOperand(1); | |||
13299 | EVT VT = N->getValueType(0); | |||
13300 | SDLoc SL(N); | |||
13301 | ||||
13302 | assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation")((N->getOpcode() == ISD::FMUL && "Expected FMUL Operation" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::FMUL && \"Expected FMUL Operation\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 13302, __PRETTY_FUNCTION__)); | |||
13303 | ||||
13304 | const TargetOptions &Options = DAG.getTarget().Options; | |||
13305 | ||||
13306 | // The transforms below are incorrect when x == 0 and y == inf, because the | |||
13307 | // intermediate multiplication produces a nan. | |||
13308 | if (!Options.NoInfsFPMath) | |||
13309 | return SDValue(); | |||
13310 | ||||
13311 | // Floating-point multiply-add without intermediate rounding. | |||
13312 | bool HasFMA = | |||
13313 | (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && | |||
13314 | TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && | |||
13315 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); | |||
13316 | ||||
13317 | // Floating-point multiply-add with intermediate rounding. This can result | |||
13318 | // in a less precise result due to the changed rounding order. | |||
13319 | bool HasFMAD = Options.UnsafeFPMath && | |||
13320 | (LegalOperations && TLI.isFMADLegal(DAG, N)); | |||
13321 | ||||
13322 | // No valid opcode, do not combine. | |||
13323 | if (!HasFMAD && !HasFMA) | |||
13324 | return SDValue(); | |||
13325 | ||||
13326 | // Always prefer FMAD to FMA for precision. | |||
13327 | unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; | |||
13328 | bool Aggressive = TLI.enableAggressiveFMAFusion(VT); | |||
13329 | ||||
13330 | // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y) | |||
13331 | // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y)) | |||
13332 | auto FuseFADD = [&](SDValue X, SDValue Y) { | |||
13333 | if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { | |||
13334 | if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) { | |||
13335 | if (C->isExactlyValue(+1.0)) | |||
13336 | return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, | |||
13337 | Y); | |||
13338 | if (C->isExactlyValue(-1.0)) | |||
13339 | return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, | |||
13340 | DAG.getNode(ISD::FNEG, SL, VT, Y)); | |||
13341 | } | |||
13342 | } | |||
13343 | return SDValue(); | |||
13344 | }; | |||
13345 | ||||
13346 | if (SDValue FMA = FuseFADD(N0, N1)) | |||
13347 | return FMA; | |||
13348 | if (SDValue FMA = FuseFADD(N1, N0)) | |||
13349 | return FMA; | |||
13350 | ||||
13351 | // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y) | |||
13352 | // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y)) | |||
13353 | // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y)) | |||
13354 | // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y) | |||
13355 | auto FuseFSUB = [&](SDValue X, SDValue Y) { | |||
13356 | if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { | |||
13357 | if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) { | |||
13358 | if (C0->isExactlyValue(+1.0)) | |||
13359 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13360 | DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, | |||
13361 | Y); | |||
13362 | if (C0->isExactlyValue(-1.0)) | |||
13363 | return DAG.getNode(PreferredFusedOpcode, SL, VT, | |||
13364 | DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, | |||
13365 | DAG.getNode(ISD::FNEG, SL, VT, Y)); | |||
13366 | } | |||
13367 | if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) { | |||
13368 | if (C1->isExactlyValue(+1.0)) | |||
13369 | return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, | |||
13370 | DAG.getNode(ISD::FNEG, SL, VT, Y)); | |||
13371 | if (C1->isExactlyValue(-1.0)) | |||
13372 | return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, | |||
13373 | Y); | |||
13374 | } | |||
13375 | } | |||
13376 | return SDValue(); | |||
13377 | }; | |||
13378 | ||||
13379 | if (SDValue FMA = FuseFSUB(N0, N1)) | |||
13380 | return FMA; | |||
13381 | if (SDValue FMA = FuseFSUB(N1, N0)) | |||
13382 | return FMA; | |||
13383 | ||||
13384 | return SDValue(); | |||
13385 | } | |||
13386 | ||||
13387 | SDValue DAGCombiner::visitFADD(SDNode *N) { | |||
13388 | SDValue N0 = N->getOperand(0); | |||
13389 | SDValue N1 = N->getOperand(1); | |||
13390 | bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); | |||
13391 | bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); | |||
13392 | EVT VT = N->getValueType(0); | |||
13393 | SDLoc DL(N); | |||
13394 | const TargetOptions &Options = DAG.getTarget().Options; | |||
13395 | SDNodeFlags Flags = N->getFlags(); | |||
13396 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
13397 | ||||
13398 | if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) | |||
13399 | return R; | |||
13400 | ||||
13401 | // fold vector ops | |||
13402 | if (VT.isVector()) | |||
13403 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
13404 | return FoldedVOp; | |||
13405 | ||||
13406 | // fold (fadd c1, c2) -> c1 + c2 | |||
13407 | if (N0CFP && N1CFP) | |||
13408 | return DAG.getNode(ISD::FADD, DL, VT, N0, N1); | |||
13409 | ||||
13410 | // canonicalize constant to RHS | |||
13411 | if (N0CFP && !N1CFP) | |||
13412 | return DAG.getNode(ISD::FADD, DL, VT, N1, N0); | |||
13413 | ||||
13414 | // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) | |||
13415 | ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true); | |||
13416 | if (N1C && N1C->isZero()) | |||
13417 | if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) | |||
13418 | return N0; | |||
13419 | ||||
13420 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
13421 | return NewSel; | |||
13422 | ||||
13423 | // fold (fadd A, (fneg B)) -> (fsub A, B) | |||
13424 | if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) | |||
13425 | if (SDValue NegN1 = TLI.getCheaperNegatedExpression( | |||
13426 | N1, DAG, LegalOperations, ForCodeSize)) | |||
13427 | return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1); | |||
13428 | ||||
13429 | // fold (fadd (fneg A), B) -> (fsub B, A) | |||
13430 | if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) | |||
13431 | if (SDValue NegN0 = TLI.getCheaperNegatedExpression( | |||
13432 | N0, DAG, LegalOperations, ForCodeSize)) | |||
13433 | return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0); | |||
13434 | ||||
13435 | auto isFMulNegTwo = [](SDValue FMul) { | |||
13436 | if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL) | |||
13437 | return false; | |||
13438 | auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true); | |||
13439 | return C && C->isExactlyValue(-2.0); | |||
13440 | }; | |||
13441 | ||||
13442 | // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B) | |||
13443 | if (isFMulNegTwo(N0)) { | |||
13444 | SDValue B = N0.getOperand(0); | |||
13445 | SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); | |||
13446 | return DAG.getNode(ISD::FSUB, DL, VT, N1, Add); | |||
13447 | } | |||
13448 | // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B) | |||
13449 | if (isFMulNegTwo(N1)) { | |||
13450 | SDValue B = N1.getOperand(0); | |||
13451 | SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); | |||
13452 | return DAG.getNode(ISD::FSUB, DL, VT, N0, Add); | |||
13453 | } | |||
13454 | ||||
13455 | // No FP constant should be created after legalization as Instruction | |||
13456 | // Selection pass has a hard time dealing with FP constants. | |||
13457 | bool AllowNewConst = (Level < AfterLegalizeDAG); | |||
13458 | ||||
13459 | // If nnan is enabled, fold lots of things. | |||
13460 | if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) { | |||
13461 | // If allowed, fold (fadd (fneg x), x) -> 0.0 | |||
13462 | if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) | |||
13463 | return DAG.getConstantFP(0.0, DL, VT); | |||
13464 | ||||
13465 | // If allowed, fold (fadd x, (fneg x)) -> 0.0 | |||
13466 | if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) | |||
13467 | return DAG.getConstantFP(0.0, DL, VT); | |||
13468 | } | |||
13469 | ||||
13470 | // If 'unsafe math' or reassoc and nsz, fold lots of things. | |||
13471 | // TODO: break out portions of the transformations below for which Unsafe is | |||
13472 | // considered and which do not require both nsz and reassoc | |||
13473 | if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || | |||
13474 | (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && | |||
13475 | AllowNewConst) { | |||
13476 | // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 | |||
13477 | if (N1CFP && N0.getOpcode() == ISD::FADD && | |||
13478 | DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { | |||
13479 | SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1); | |||
13480 | return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC); | |||
13481 | } | |||
13482 | ||||
13483 | // We can fold chains of FADD's of the same value into multiplications. | |||
13484 | // This transform is not safe in general because we are reducing the number | |||
13485 | // of rounding steps. | |||
13486 | if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { | |||
13487 | if (N0.getOpcode() == ISD::FMUL) { | |||
13488 | bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); | |||
13489 | bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); | |||
13490 | ||||
13491 | // (fadd (fmul x, c), x) -> (fmul x, c+1) | |||
13492 | if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { | |||
13493 | SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), | |||
13494 | DAG.getConstantFP(1.0, DL, VT)); | |||
13495 | return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); | |||
13496 | } | |||
13497 | ||||
13498 | // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) | |||
13499 | if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && | |||
13500 | N1.getOperand(0) == N1.getOperand(1) && | |||
13501 | N0.getOperand(0) == N1.getOperand(0)) { | |||
13502 | SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), | |||
13503 | DAG.getConstantFP(2.0, DL, VT)); | |||
13504 | return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); | |||
13505 | } | |||
13506 | } | |||
13507 | ||||
13508 | if (N1.getOpcode() == ISD::FMUL) { | |||
13509 | bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); | |||
13510 | bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); | |||
13511 | ||||
13512 | // (fadd x, (fmul x, c)) -> (fmul x, c+1) | |||
13513 | if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { | |||
13514 | SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), | |||
13515 | DAG.getConstantFP(1.0, DL, VT)); | |||
13516 | return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); | |||
13517 | } | |||
13518 | ||||
13519 | // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) | |||
13520 | if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && | |||
13521 | N0.getOperand(0) == N0.getOperand(1) && | |||
13522 | N1.getOperand(0) == N0.getOperand(0)) { | |||
13523 | SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), | |||
13524 | DAG.getConstantFP(2.0, DL, VT)); | |||
13525 | return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); | |||
13526 | } | |||
13527 | } | |||
13528 | ||||
13529 | if (N0.getOpcode() == ISD::FADD) { | |||
13530 | bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); | |||
13531 | // (fadd (fadd x, x), x) -> (fmul x, 3.0) | |||
13532 | if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && | |||
13533 | (N0.getOperand(0) == N1)) { | |||
13534 | return DAG.getNode(ISD::FMUL, DL, VT, N1, | |||
13535 | DAG.getConstantFP(3.0, DL, VT)); | |||
13536 | } | |||
13537 | } | |||
13538 | ||||
13539 | if (N1.getOpcode() == ISD::FADD) { | |||
13540 | bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); | |||
13541 | // (fadd x, (fadd x, x)) -> (fmul x, 3.0) | |||
13542 | if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && | |||
13543 | N1.getOperand(0) == N0) { | |||
13544 | return DAG.getNode(ISD::FMUL, DL, VT, N0, | |||
13545 | DAG.getConstantFP(3.0, DL, VT)); | |||
13546 | } | |||
13547 | } | |||
13548 | ||||
13549 | // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) | |||
13550 | if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && | |||
13551 | N0.getOperand(0) == N0.getOperand(1) && | |||
13552 | N1.getOperand(0) == N1.getOperand(1) && | |||
13553 | N0.getOperand(0) == N1.getOperand(0)) { | |||
13554 | return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), | |||
13555 | DAG.getConstantFP(4.0, DL, VT)); | |||
13556 | } | |||
13557 | } | |||
13558 | } // enable-unsafe-fp-math | |||
13559 | ||||
13560 | // FADD -> FMA combines: | |||
13561 | if (SDValue Fused = visitFADDForFMACombine(N)) { | |||
13562 | AddToWorklist(Fused.getNode()); | |||
13563 | return Fused; | |||
13564 | } | |||
13565 | return SDValue(); | |||
13566 | } | |||
13567 | ||||
13568 | SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) { | |||
13569 | SDValue Chain = N->getOperand(0); | |||
13570 | SDValue N0 = N->getOperand(1); | |||
13571 | SDValue N1 = N->getOperand(2); | |||
13572 | EVT VT = N->getValueType(0); | |||
13573 | EVT ChainVT = N->getValueType(1); | |||
13574 | SDLoc DL(N); | |||
13575 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
13576 | ||||
13577 | // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B) | |||
13578 | if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) | |||
13579 | if (SDValue NegN1 = TLI.getCheaperNegatedExpression( | |||
13580 | N1, DAG, LegalOperations, ForCodeSize)) { | |||
13581 | return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), | |||
13582 | {Chain, N0, NegN1}); | |||
13583 | } | |||
13584 | ||||
13585 | // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A) | |||
13586 | if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) | |||
13587 | if (SDValue NegN0 = TLI.getCheaperNegatedExpression( | |||
13588 | N0, DAG, LegalOperations, ForCodeSize)) { | |||
13589 | return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), | |||
13590 | {Chain, N1, NegN0}); | |||
13591 | } | |||
13592 | return SDValue(); | |||
13593 | } | |||
13594 | ||||
13595 | SDValue DAGCombiner::visitFSUB(SDNode *N) { | |||
13596 | SDValue N0 = N->getOperand(0); | |||
13597 | SDValue N1 = N->getOperand(1); | |||
13598 | ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); | |||
13599 | ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); | |||
13600 | EVT VT = N->getValueType(0); | |||
13601 | SDLoc DL(N); | |||
13602 | const TargetOptions &Options = DAG.getTarget().Options; | |||
13603 | const SDNodeFlags Flags = N->getFlags(); | |||
13604 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
13605 | ||||
13606 | if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) | |||
13607 | return R; | |||
13608 | ||||
13609 | // fold vector ops | |||
13610 | if (VT.isVector()) | |||
13611 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
13612 | return FoldedVOp; | |||
13613 | ||||
13614 | // fold (fsub c1, c2) -> c1-c2 | |||
13615 | if (N0CFP && N1CFP) | |||
13616 | return DAG.getNode(ISD::FSUB, DL, VT, N0, N1); | |||
13617 | ||||
13618 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
13619 | return NewSel; | |||
13620 | ||||
13621 | // (fsub A, 0) -> A | |||
13622 | if (N1CFP && N1CFP->isZero()) { | |||
13623 | if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath || | |||
13624 | Flags.hasNoSignedZeros()) { | |||
13625 | return N0; | |||
13626 | } | |||
13627 | } | |||
13628 | ||||
13629 | if (N0 == N1) { | |||
13630 | // (fsub x, x) -> 0.0 | |||
13631 | if (Options.NoNaNsFPMath || Flags.hasNoNaNs()) | |||
13632 | return DAG.getConstantFP(0.0f, DL, VT); | |||
13633 | } | |||
13634 | ||||
13635 | // (fsub -0.0, N1) -> -N1 | |||
13636 | if (N0CFP && N0CFP->isZero()) { | |||
13637 | if (N0CFP->isNegative() || | |||
13638 | (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) { | |||
13639 | // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are | |||
13640 | // flushed to zero, unless all users treat denorms as zero (DAZ). | |||
13641 | // FIXME: This transform will change the sign of a NaN and the behavior | |||
13642 | // of a signaling NaN. It is only valid when a NoNaN flag is present. | |||
13643 | DenormalMode DenormMode = DAG.getDenormalMode(VT); | |||
13644 | if (DenormMode == DenormalMode::getIEEE()) { | |||
13645 | if (SDValue NegN1 = | |||
13646 | TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) | |||
13647 | return NegN1; | |||
13648 | if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) | |||
13649 | return DAG.getNode(ISD::FNEG, DL, VT, N1); | |||
13650 | } | |||
13651 | } | |||
13652 | } | |||
13653 | ||||
13654 | if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || | |||
13655 | (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && | |||
13656 | N1.getOpcode() == ISD::FADD) { | |||
13657 | // X - (X + Y) -> -Y | |||
13658 | if (N0 == N1->getOperand(0)) | |||
13659 | return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1)); | |||
13660 | // X - (Y + X) -> -Y | |||
13661 | if (N0 == N1->getOperand(1)) | |||
13662 | return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0)); | |||
13663 | } | |||
13664 | ||||
13665 | // fold (fsub A, (fneg B)) -> (fadd A, B) | |||
13666 | if (SDValue NegN1 = | |||
13667 | TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) | |||
13668 | return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1); | |||
13669 | ||||
13670 | // FSUB -> FMA combines: | |||
13671 | if (SDValue Fused = visitFSUBForFMACombine(N)) { | |||
13672 | AddToWorklist(Fused.getNode()); | |||
13673 | return Fused; | |||
13674 | } | |||
13675 | ||||
13676 | return SDValue(); | |||
13677 | } | |||
13678 | ||||
13679 | SDValue DAGCombiner::visitFMUL(SDNode *N) { | |||
13680 | SDValue N0 = N->getOperand(0); | |||
13681 | SDValue N1 = N->getOperand(1); | |||
13682 | ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); | |||
13683 | ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); | |||
13684 | EVT VT = N->getValueType(0); | |||
13685 | SDLoc DL(N); | |||
13686 | const TargetOptions &Options = DAG.getTarget().Options; | |||
13687 | const SDNodeFlags Flags = N->getFlags(); | |||
13688 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
13689 | ||||
13690 | if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) | |||
13691 | return R; | |||
13692 | ||||
13693 | // fold vector ops | |||
13694 | if (VT.isVector()) { | |||
13695 | // This just handles C1 * C2 for vectors. Other vector folds are below. | |||
13696 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
13697 | return FoldedVOp; | |||
13698 | } | |||
13699 | ||||
13700 | // fold (fmul c1, c2) -> c1*c2 | |||
13701 | if (N0CFP && N1CFP) | |||
13702 | return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); | |||
13703 | ||||
13704 | // canonicalize constant to RHS | |||
13705 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && | |||
13706 | !DAG.isConstantFPBuildVectorOrConstantFP(N1)) | |||
13707 | return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); | |||
13708 | ||||
13709 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
13710 | return NewSel; | |||
13711 | ||||
13712 | if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { | |||
13713 | // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 | |||
13714 | if (DAG.isConstantFPBuildVectorOrConstantFP(N1) && | |||
13715 | N0.getOpcode() == ISD::FMUL) { | |||
13716 | SDValue N00 = N0.getOperand(0); | |||
13717 | SDValue N01 = N0.getOperand(1); | |||
13718 | // Avoid an infinite loop by making sure that N00 is not a constant | |||
13719 | // (the inner multiply has not been constant folded yet). | |||
13720 | if (DAG.isConstantFPBuildVectorOrConstantFP(N01) && | |||
13721 | !DAG.isConstantFPBuildVectorOrConstantFP(N00)) { | |||
13722 | SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); | |||
13723 | return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); | |||
13724 | } | |||
13725 | } | |||
13726 | ||||
13727 | // Match a special-case: we convert X * 2.0 into fadd. | |||
13728 | // fmul (fadd X, X), C -> fmul X, 2.0 * C | |||
13729 | if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && | |||
13730 | N0.getOperand(0) == N0.getOperand(1)) { | |||
13731 | const SDValue Two = DAG.getConstantFP(2.0, DL, VT); | |||
13732 | SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); | |||
13733 | return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); | |||
13734 | } | |||
13735 | } | |||
13736 | ||||
13737 | // fold (fmul X, 2.0) -> (fadd X, X) | |||
13738 | if (N1CFP && N1CFP->isExactlyValue(+2.0)) | |||
13739 | return DAG.getNode(ISD::FADD, DL, VT, N0, N0); | |||
13740 | ||||
13741 | // fold (fmul X, -1.0) -> (fneg X) | |||
13742 | if (N1CFP && N1CFP->isExactlyValue(-1.0)) | |||
13743 | if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) | |||
13744 | return DAG.getNode(ISD::FNEG, DL, VT, N0); | |||
13745 | ||||
13746 | // -N0 * -N1 --> N0 * N1 | |||
13747 | TargetLowering::NegatibleCost CostN0 = | |||
13748 | TargetLowering::NegatibleCost::Expensive; | |||
13749 | TargetLowering::NegatibleCost CostN1 = | |||
13750 | TargetLowering::NegatibleCost::Expensive; | |||
13751 | SDValue NegN0 = | |||
13752 | TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); | |||
13753 | SDValue NegN1 = | |||
13754 | TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); | |||
13755 | if (NegN0 && NegN1 && | |||
13756 | (CostN0 == TargetLowering::NegatibleCost::Cheaper || | |||
13757 | CostN1 == TargetLowering::NegatibleCost::Cheaper)) | |||
13758 | return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1); | |||
13759 | ||||
13760 | // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) | |||
13761 | // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) | |||
13762 | if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && | |||
13763 | (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && | |||
13764 | TLI.isOperationLegal(ISD::FABS, VT)) { | |||
13765 | SDValue Select = N0, X = N1; | |||
13766 | if (Select.getOpcode() != ISD::SELECT) | |||
13767 | std::swap(Select, X); | |||
13768 | ||||
13769 | SDValue Cond = Select.getOperand(0); | |||
13770 | auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); | |||
13771 | auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); | |||
13772 | ||||
13773 | if (TrueOpnd && FalseOpnd && | |||
13774 | Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && | |||
13775 | isa<ConstantFPSDNode>(Cond.getOperand(1)) && | |||
13776 | cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { | |||
13777 | ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); | |||
13778 | switch (CC) { | |||
13779 | default: break; | |||
13780 | case ISD::SETOLT: | |||
13781 | case ISD::SETULT: | |||
13782 | case ISD::SETOLE: | |||
13783 | case ISD::SETULE: | |||
13784 | case ISD::SETLT: | |||
13785 | case ISD::SETLE: | |||
13786 | std::swap(TrueOpnd, FalseOpnd); | |||
13787 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
13788 | case ISD::SETOGT: | |||
13789 | case ISD::SETUGT: | |||
13790 | case ISD::SETOGE: | |||
13791 | case ISD::SETUGE: | |||
13792 | case ISD::SETGT: | |||
13793 | case ISD::SETGE: | |||
13794 | if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && | |||
13795 | TLI.isOperationLegal(ISD::FNEG, VT)) | |||
13796 | return DAG.getNode(ISD::FNEG, DL, VT, | |||
13797 | DAG.getNode(ISD::FABS, DL, VT, X)); | |||
13798 | if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) | |||
13799 | return DAG.getNode(ISD::FABS, DL, VT, X); | |||
13800 | ||||
13801 | break; | |||
13802 | } | |||
13803 | } | |||
13804 | } | |||
13805 | ||||
13806 | // FMUL -> FMA combines: | |||
13807 | if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { | |||
13808 | AddToWorklist(Fused.getNode()); | |||
13809 | return Fused; | |||
13810 | } | |||
13811 | ||||
13812 | return SDValue(); | |||
13813 | } | |||
13814 | ||||
13815 | SDValue DAGCombiner::visitFMA(SDNode *N) { | |||
13816 | SDValue N0 = N->getOperand(0); | |||
13817 | SDValue N1 = N->getOperand(1); | |||
13818 | SDValue N2 = N->getOperand(2); | |||
13819 | ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); | |||
13820 | ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); | |||
13821 | EVT VT = N->getValueType(0); | |||
13822 | SDLoc DL(N); | |||
13823 | const TargetOptions &Options = DAG.getTarget().Options; | |||
13824 | // FMA nodes have flags that propagate to the created nodes. | |||
13825 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
13826 | ||||
13827 | bool UnsafeFPMath = | |||
13828 | Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); | |||
13829 | ||||
13830 | // Constant fold FMA. | |||
13831 | if (isa<ConstantFPSDNode>(N0) && | |||
13832 | isa<ConstantFPSDNode>(N1) && | |||
13833 | isa<ConstantFPSDNode>(N2)) { | |||
13834 | return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); | |||
13835 | } | |||
13836 | ||||
13837 | // (-N0 * -N1) + N2 --> (N0 * N1) + N2 | |||
13838 | TargetLowering::NegatibleCost CostN0 = | |||
13839 | TargetLowering::NegatibleCost::Expensive; | |||
13840 | TargetLowering::NegatibleCost CostN1 = | |||
13841 | TargetLowering::NegatibleCost::Expensive; | |||
13842 | SDValue NegN0 = | |||
13843 | TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); | |||
13844 | SDValue NegN1 = | |||
13845 | TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); | |||
13846 | if (NegN0 && NegN1 && | |||
13847 | (CostN0 == TargetLowering::NegatibleCost::Cheaper || | |||
13848 | CostN1 == TargetLowering::NegatibleCost::Cheaper)) | |||
13849 | return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2); | |||
13850 | ||||
13851 | if (UnsafeFPMath) { | |||
13852 | if (N0CFP && N0CFP->isZero()) | |||
13853 | return N2; | |||
13854 | if (N1CFP && N1CFP->isZero()) | |||
13855 | return N2; | |||
13856 | } | |||
13857 | ||||
13858 | if (N0CFP && N0CFP->isExactlyValue(1.0)) | |||
13859 | return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); | |||
13860 | if (N1CFP && N1CFP->isExactlyValue(1.0)) | |||
13861 | return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); | |||
13862 | ||||
13863 | // Canonicalize (fma c, x, y) -> (fma x, c, y) | |||
13864 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && | |||
13865 | !DAG.isConstantFPBuildVectorOrConstantFP(N1)) | |||
13866 | return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); | |||
13867 | ||||
13868 | if (UnsafeFPMath) { | |||
13869 | // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) | |||
13870 | if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && | |||
13871 | DAG.isConstantFPBuildVectorOrConstantFP(N1) && | |||
13872 | DAG.isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { | |||
13873 | return DAG.getNode(ISD::FMUL, DL, VT, N0, | |||
13874 | DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1))); | |||
13875 | } | |||
13876 | ||||
13877 | // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) | |||
13878 | if (N0.getOpcode() == ISD::FMUL && | |||
13879 | DAG.isConstantFPBuildVectorOrConstantFP(N1) && | |||
13880 | DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { | |||
13881 | return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), | |||
13882 | DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)), | |||
13883 | N2); | |||
13884 | } | |||
13885 | } | |||
13886 | ||||
13887 | // (fma x, -1, y) -> (fadd (fneg x), y) | |||
13888 | if (N1CFP) { | |||
13889 | if (N1CFP->isExactlyValue(1.0)) | |||
13890 | return DAG.getNode(ISD::FADD, DL, VT, N0, N2); | |||
13891 | ||||
13892 | if (N1CFP->isExactlyValue(-1.0) && | |||
13893 | (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { | |||
13894 | SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); | |||
13895 | AddToWorklist(RHSNeg.getNode()); | |||
13896 | return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); | |||
13897 | } | |||
13898 | ||||
13899 | // fma (fneg x), K, y -> fma x -K, y | |||
13900 | if (N0.getOpcode() == ISD::FNEG && | |||
13901 | (TLI.isOperationLegal(ISD::ConstantFP, VT) || | |||
13902 | (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, | |||
13903 | ForCodeSize)))) { | |||
13904 | return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), | |||
13905 | DAG.getNode(ISD::FNEG, DL, VT, N1), N2); | |||
13906 | } | |||
13907 | } | |||
13908 | ||||
13909 | if (UnsafeFPMath) { | |||
13910 | // (fma x, c, x) -> (fmul x, (c+1)) | |||
13911 | if (N1CFP && N0 == N2) { | |||
13912 | return DAG.getNode( | |||
13913 | ISD::FMUL, DL, VT, N0, | |||
13914 | DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT))); | |||
13915 | } | |||
13916 | ||||
13917 | // (fma x, c, (fneg x)) -> (fmul x, (c-1)) | |||
13918 | if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { | |||
13919 | return DAG.getNode( | |||
13920 | ISD::FMUL, DL, VT, N0, | |||
13921 | DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT))); | |||
13922 | } | |||
13923 | } | |||
13924 | ||||
13925 | // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z)) | |||
13926 | // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z)) | |||
13927 | if (!TLI.isFNegFree(VT)) | |||
13928 | if (SDValue Neg = TLI.getCheaperNegatedExpression( | |||
13929 | SDValue(N, 0), DAG, LegalOperations, ForCodeSize)) | |||
13930 | return DAG.getNode(ISD::FNEG, DL, VT, Neg); | |||
13931 | return SDValue(); | |||
13932 | } | |||
13933 | ||||
13934 | // Combine multiple FDIVs with the same divisor into multiple FMULs by the | |||
13935 | // reciprocal. | |||
13936 | // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) | |||
13937 | // Notice that this is not always beneficial. One reason is different targets | |||
13938 | // may have different costs for FDIV and FMUL, so sometimes the cost of two | |||
13939 | // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason | |||
13940 | // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". | |||
13941 | SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { | |||
13942 | // TODO: Limit this transform based on optsize/minsize - it always creates at | |||
13943 | // least 1 extra instruction. But the perf win may be substantial enough | |||
13944 | // that only minsize should restrict this. | |||
13945 | bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; | |||
13946 | const SDNodeFlags Flags = N->getFlags(); | |||
13947 | if (LegalDAG || (!UnsafeMath && !Flags.hasAllowReciprocal())) | |||
13948 | return SDValue(); | |||
13949 | ||||
13950 | // Skip if current node is a reciprocal/fneg-reciprocal. | |||
13951 | SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); | |||
13952 | ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true); | |||
13953 | if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0))) | |||
13954 | return SDValue(); | |||
13955 | ||||
13956 | // Exit early if the target does not want this transform or if there can't | |||
13957 | // possibly be enough uses of the divisor to make the transform worthwhile. | |||
13958 | unsigned MinUses = TLI.combineRepeatedFPDivisors(); | |||
13959 | ||||
13960 | // For splat vectors, scale the number of uses by the splat factor. If we can | |||
13961 | // convert the division into a scalar op, that will likely be much faster. | |||
13962 | unsigned NumElts = 1; | |||
13963 | EVT VT = N->getValueType(0); | |||
13964 | if (VT.isVector() && DAG.isSplatValue(N1)) | |||
13965 | NumElts = VT.getVectorNumElements(); | |||
13966 | ||||
13967 | if (!MinUses || (N1->use_size() * NumElts) < MinUses) | |||
13968 | return SDValue(); | |||
13969 | ||||
13970 | // Find all FDIV users of the same divisor. | |||
13971 | // Use a set because duplicates may be present in the user list. | |||
13972 | SetVector<SDNode *> Users; | |||
13973 | for (auto *U : N1->uses()) { | |||
13974 | if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { | |||
13975 | // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet. | |||
13976 | if (U->getOperand(1).getOpcode() == ISD::FSQRT && | |||
13977 | U->getOperand(0) == U->getOperand(1).getOperand(0) && | |||
13978 | U->getFlags().hasAllowReassociation() && | |||
13979 | U->getFlags().hasNoSignedZeros()) | |||
13980 | continue; | |||
13981 | ||||
13982 | // This division is eligible for optimization only if global unsafe math | |||
13983 | // is enabled or if this division allows reciprocal formation. | |||
13984 | if (UnsafeMath || U->getFlags().hasAllowReciprocal()) | |||
13985 | Users.insert(U); | |||
13986 | } | |||
13987 | } | |||
13988 | ||||
13989 | // Now that we have the actual number of divisor uses, make sure it meets | |||
13990 | // the minimum threshold specified by the target. | |||
13991 | if ((Users.size() * NumElts) < MinUses) | |||
13992 | return SDValue(); | |||
13993 | ||||
13994 | SDLoc DL(N); | |||
13995 | SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); | |||
13996 | SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); | |||
13997 | ||||
13998 | // Dividend / Divisor -> Dividend * Reciprocal | |||
13999 | for (auto *U : Users) { | |||
14000 | SDValue Dividend = U->getOperand(0); | |||
14001 | if (Dividend != FPOne) { | |||
14002 | SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, | |||
14003 | Reciprocal, Flags); | |||
14004 | CombineTo(U, NewNode); | |||
14005 | } else if (U != Reciprocal.getNode()) { | |||
14006 | // In the absence of fast-math-flags, this user node is always the | |||
14007 | // same node as Reciprocal, but with FMF they may be different nodes. | |||
14008 | CombineTo(U, Reciprocal); | |||
14009 | } | |||
14010 | } | |||
14011 | return SDValue(N, 0); // N was replaced. | |||
14012 | } | |||
14013 | ||||
14014 | SDValue DAGCombiner::visitFDIV(SDNode *N) { | |||
14015 | SDValue N0 = N->getOperand(0); | |||
14016 | SDValue N1 = N->getOperand(1); | |||
14017 | ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); | |||
14018 | ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); | |||
14019 | EVT VT = N->getValueType(0); | |||
14020 | SDLoc DL(N); | |||
14021 | const TargetOptions &Options = DAG.getTarget().Options; | |||
14022 | SDNodeFlags Flags = N->getFlags(); | |||
14023 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
14024 | ||||
14025 | if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) | |||
14026 | return R; | |||
14027 | ||||
14028 | // fold vector ops | |||
14029 | if (VT.isVector()) | |||
14030 | if (SDValue FoldedVOp = SimplifyVBinOp(N)) | |||
14031 | return FoldedVOp; | |||
14032 | ||||
14033 | // fold (fdiv c1, c2) -> c1/c2 | |||
14034 | if (N0CFP && N1CFP) | |||
14035 | return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); | |||
14036 | ||||
14037 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
14038 | return NewSel; | |||
14039 | ||||
14040 | if (SDValue V = combineRepeatedFPDivisors(N)) | |||
14041 | return V; | |||
14042 | ||||
14043 | if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { | |||
14044 | // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. | |||
14045 | if (N1CFP) { | |||
14046 | // Compute the reciprocal 1.0 / c2. | |||
14047 | const APFloat &N1APF = N1CFP->getValueAPF(); | |||
14048 | APFloat Recip(N1APF.getSemantics(), 1); // 1.0 | |||
14049 | APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); | |||
14050 | // Only do the transform if the reciprocal is a legal fp immediate that | |||
14051 | // isn't too nasty (eg NaN, denormal, ...). | |||
14052 | if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty | |||
14053 | (!LegalOperations || | |||
14054 | // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM | |||
14055 | // backend)... we should handle this gracefully after Legalize. | |||
14056 | // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || | |||
14057 | TLI.isOperationLegal(ISD::ConstantFP, VT) || | |||
14058 | TLI.isFPImmLegal(Recip, VT, ForCodeSize))) | |||
14059 | return DAG.getNode(ISD::FMUL, DL, VT, N0, | |||
14060 | DAG.getConstantFP(Recip, DL, VT)); | |||
14061 | } | |||
14062 | ||||
14063 | // If this FDIV is part of a reciprocal square root, it may be folded | |||
14064 | // into a target-specific square root estimate instruction. | |||
14065 | if (N1.getOpcode() == ISD::FSQRT) { | |||
14066 | if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) | |||
14067 | return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); | |||
14068 | } else if (N1.getOpcode() == ISD::FP_EXTEND && | |||
14069 | N1.getOperand(0).getOpcode() == ISD::FSQRT) { | |||
14070 | if (SDValue RV = | |||
14071 | buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { | |||
14072 | RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); | |||
14073 | AddToWorklist(RV.getNode()); | |||
14074 | return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); | |||
14075 | } | |||
14076 | } else if (N1.getOpcode() == ISD::FP_ROUND && | |||
14077 | N1.getOperand(0).getOpcode() == ISD::FSQRT) { | |||
14078 | if (SDValue RV = | |||
14079 | buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { | |||
14080 | RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); | |||
14081 | AddToWorklist(RV.getNode()); | |||
14082 | return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); | |||
14083 | } | |||
14084 | } else if (N1.getOpcode() == ISD::FMUL) { | |||
14085 | // Look through an FMUL. Even though this won't remove the FDIV directly, | |||
14086 | // it's still worthwhile to get rid of the FSQRT if possible. | |||
14087 | SDValue Sqrt, Y; | |||
14088 | if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { | |||
14089 | Sqrt = N1.getOperand(0); | |||
14090 | Y = N1.getOperand(1); | |||
14091 | } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { | |||
14092 | Sqrt = N1.getOperand(1); | |||
14093 | Y = N1.getOperand(0); | |||
14094 | } | |||
14095 | if (Sqrt.getNode()) { | |||
14096 | // If the other multiply operand is known positive, pull it into the | |||
14097 | // sqrt. That will eliminate the division if we convert to an estimate. | |||
14098 | if (Flags.hasAllowReassociation() && N1.hasOneUse() && | |||
14099 | N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) { | |||
14100 | SDValue A; | |||
14101 | if (Y.getOpcode() == ISD::FABS && Y.hasOneUse()) | |||
14102 | A = Y.getOperand(0); | |||
14103 | else if (Y == Sqrt.getOperand(0)) | |||
14104 | A = Y; | |||
14105 | if (A) { | |||
14106 | // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z) | |||
14107 | // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A) | |||
14108 | SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A); | |||
14109 | SDValue AAZ = | |||
14110 | DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0)); | |||
14111 | if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Flags)) | |||
14112 | return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt); | |||
14113 | ||||
14114 | // Estimate creation failed. Clean up speculatively created nodes. | |||
14115 | recursivelyDeleteUnusedNodes(AAZ.getNode()); | |||
14116 | } | |||
14117 | } | |||
14118 | ||||
14119 | // We found a FSQRT, so try to make this fold: | |||
14120 | // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y) | |||
14121 | if (SDValue Rsqrt = buildRsqrtEstimate(Sqrt.getOperand(0), Flags)) { | |||
14122 | SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y); | |||
14123 | AddToWorklist(Div.getNode()); | |||
14124 | return DAG.getNode(ISD::FMUL, DL, VT, N0, Div); | |||
14125 | } | |||
14126 | } | |||
14127 | } | |||
14128 | ||||
14129 | // Fold into a reciprocal estimate and multiply instead of a real divide. | |||
14130 | if (Options.NoInfsFPMath || Flags.hasNoInfs()) | |||
14131 | if (SDValue RV = BuildDivEstimate(N0, N1, Flags)) | |||
14132 | return RV; | |||
14133 | } | |||
14134 | ||||
14135 | // Fold X/Sqrt(X) -> Sqrt(X) | |||
14136 | if ((Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) && | |||
14137 | (Options.UnsafeFPMath || Flags.hasAllowReassociation())) | |||
14138 | if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0)) | |||
14139 | return N1; | |||
14140 | ||||
14141 | // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) | |||
14142 | TargetLowering::NegatibleCost CostN0 = | |||
14143 | TargetLowering::NegatibleCost::Expensive; | |||
14144 | TargetLowering::NegatibleCost CostN1 = | |||
14145 | TargetLowering::NegatibleCost::Expensive; | |||
14146 | SDValue NegN0 = | |||
14147 | TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); | |||
14148 | SDValue NegN1 = | |||
14149 | TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); | |||
14150 | if (NegN0 && NegN1 && | |||
14151 | (CostN0 == TargetLowering::NegatibleCost::Cheaper || | |||
14152 | CostN1 == TargetLowering::NegatibleCost::Cheaper)) | |||
14153 | return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1); | |||
14154 | ||||
14155 | return SDValue(); | |||
14156 | } | |||
14157 | ||||
14158 | SDValue DAGCombiner::visitFREM(SDNode *N) { | |||
14159 | SDValue N0 = N->getOperand(0); | |||
14160 | SDValue N1 = N->getOperand(1); | |||
14161 | ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); | |||
14162 | ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); | |||
14163 | EVT VT = N->getValueType(0); | |||
14164 | SDNodeFlags Flags = N->getFlags(); | |||
14165 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
14166 | ||||
14167 | if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) | |||
14168 | return R; | |||
14169 | ||||
14170 | // fold (frem c1, c2) -> fmod(c1,c2) | |||
14171 | if (N0CFP && N1CFP) | |||
14172 | return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); | |||
14173 | ||||
14174 | if (SDValue NewSel = foldBinOpIntoSelect(N)) | |||
14175 | return NewSel; | |||
14176 | ||||
14177 | return SDValue(); | |||
14178 | } | |||
14179 | ||||
14180 | SDValue DAGCombiner::visitFSQRT(SDNode *N) { | |||
14181 | SDNodeFlags Flags = N->getFlags(); | |||
14182 | const TargetOptions &Options = DAG.getTarget().Options; | |||
14183 | ||||
14184 | // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as: | |||
14185 | // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN | |||
14186 | if (!Flags.hasApproximateFuncs() || | |||
14187 | (!Options.NoInfsFPMath && !Flags.hasNoInfs())) | |||
14188 | return SDValue(); | |||
14189 | ||||
14190 | SDValue N0 = N->getOperand(0); | |||
14191 | if (TLI.isFsqrtCheap(N0, DAG)) | |||
14192 | return SDValue(); | |||
14193 | ||||
14194 | // FSQRT nodes have flags that propagate to the created nodes. | |||
14195 | // TODO: If this is N0/sqrt(N0), and we reach this node before trying to | |||
14196 | // transform the fdiv, we may produce a sub-optimal estimate sequence | |||
14197 | // because the reciprocal calculation may not have to filter out a | |||
14198 | // 0.0 input. | |||
14199 | return buildSqrtEstimate(N0, Flags); | |||
14200 | } | |||
14201 | ||||
14202 | /// copysign(x, fp_extend(y)) -> copysign(x, y) | |||
14203 | /// copysign(x, fp_round(y)) -> copysign(x, y) | |||
14204 | static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { | |||
14205 | SDValue N1 = N->getOperand(1); | |||
14206 | if ((N1.getOpcode() == ISD::FP_EXTEND || | |||
14207 | N1.getOpcode() == ISD::FP_ROUND)) { | |||
14208 | EVT N1VT = N1->getValueType(0); | |||
14209 | EVT N1Op0VT = N1->getOperand(0).getValueType(); | |||
14210 | ||||
14211 | // Always fold no-op FP casts. | |||
14212 | if (N1VT == N1Op0VT) | |||
14213 | return true; | |||
14214 | ||||
14215 | // Do not optimize out type conversion of f128 type yet. | |||
14216 | // For some targets like x86_64, configuration is changed to keep one f128 | |||
14217 | // value in one SSE register, but instruction selection cannot handle | |||
14218 | // FCOPYSIGN on SSE registers yet. | |||
14219 | if (N1Op0VT == MVT::f128) | |||
14220 | return false; | |||
14221 | ||||
14222 | // Avoid mismatched vector operand types, for better instruction selection. | |||
14223 | if (N1Op0VT.isVector()) | |||
14224 | return false; | |||
14225 | ||||
14226 | return true; | |||
14227 | } | |||
14228 | return false; | |||
14229 | } | |||
14230 | ||||
14231 | SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { | |||
14232 | SDValue N0 = N->getOperand(0); | |||
14233 | SDValue N1 = N->getOperand(1); | |||
14234 | bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); | |||
14235 | bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); | |||
14236 | EVT VT = N->getValueType(0); | |||
14237 | ||||
14238 | if (N0CFP && N1CFP) // Constant fold | |||
14239 | return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); | |||
14240 | ||||
14241 | if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) { | |||
14242 | const APFloat &V = N1C->getValueAPF(); | |||
14243 | // copysign(x, c1) -> fabs(x) iff ispos(c1) | |||
14244 | // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) | |||
14245 | if (!V.isNegative()) { | |||
14246 | if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) | |||
14247 | return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); | |||
14248 | } else { | |||
14249 | if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) | |||
14250 | return DAG.getNode(ISD::FNEG, SDLoc(N), VT, | |||
14251 | DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); | |||
14252 | } | |||
14253 | } | |||
14254 | ||||
14255 | // copysign(fabs(x), y) -> copysign(x, y) | |||
14256 | // copysign(fneg(x), y) -> copysign(x, y) | |||
14257 | // copysign(copysign(x,z), y) -> copysign(x, y) | |||
14258 | if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || | |||
14259 | N0.getOpcode() == ISD::FCOPYSIGN) | |||
14260 | return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); | |||
14261 | ||||
14262 | // copysign(x, abs(y)) -> abs(x) | |||
14263 | if (N1.getOpcode() == ISD::FABS) | |||
14264 | return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); | |||
14265 | ||||
14266 | // copysign(x, copysign(y,z)) -> copysign(x, z) | |||
14267 | if (N1.getOpcode() == ISD::FCOPYSIGN) | |||
14268 | return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); | |||
14269 | ||||
14270 | // copysign(x, fp_extend(y)) -> copysign(x, y) | |||
14271 | // copysign(x, fp_round(y)) -> copysign(x, y) | |||
14272 | if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) | |||
14273 | return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); | |||
14274 | ||||
14275 | return SDValue(); | |||
14276 | } | |||
14277 | ||||
14278 | SDValue DAGCombiner::visitFPOW(SDNode *N) { | |||
14279 | ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1)); | |||
14280 | if (!ExponentC) | |||
14281 | return SDValue(); | |||
14282 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
14283 | ||||
14284 | // Try to convert x ** (1/3) into cube root. | |||
14285 | // TODO: Handle the various flavors of long double. | |||
14286 | // TODO: Since we're approximating, we don't need an exact 1/3 exponent. | |||
14287 | // Some range near 1/3 should be fine. | |||
14288 | EVT VT = N->getValueType(0); | |||
14289 | if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) || | |||
14290 | (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) { | |||
14291 | // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0. | |||
14292 | // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf. | |||
14293 | // pow(-val, 1/3) = nan; cbrt(-val) = -num. | |||
14294 | // For regular numbers, rounding may cause the results to differ. | |||
14295 | // Therefore, we require { nsz ninf nnan afn } for this transform. | |||
14296 | // TODO: We could select out the special cases if we don't have nsz/ninf. | |||
14297 | SDNodeFlags Flags = N->getFlags(); | |||
14298 | if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() || | |||
14299 | !Flags.hasApproximateFuncs()) | |||
14300 | return SDValue(); | |||
14301 | ||||
14302 | // Do not create a cbrt() libcall if the target does not have it, and do not | |||
14303 | // turn a pow that has lowering support into a cbrt() libcall. | |||
14304 | if (!DAG.getLibInfo().has(LibFunc_cbrt) || | |||
14305 | (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) && | |||
14306 | DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT))) | |||
14307 | return SDValue(); | |||
14308 | ||||
14309 | return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0)); | |||
14310 | } | |||
14311 | ||||
14312 | // Try to convert x ** (1/4) and x ** (3/4) into square roots. | |||
14313 | // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case. | |||
14314 | // TODO: This could be extended (using a target hook) to handle smaller | |||
14315 | // power-of-2 fractional exponents. | |||
14316 | bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25); | |||
14317 | bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75); | |||
14318 | if (ExponentIs025 || ExponentIs075) { | |||
14319 | // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0. | |||
14320 | // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN. | |||
14321 | // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0. | |||
14322 | // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN. | |||
14323 | // For regular numbers, rounding may cause the results to differ. | |||
14324 | // Therefore, we require { nsz ninf afn } for this transform. | |||
14325 | // TODO: We could select out the special cases if we don't have nsz/ninf. | |||
14326 | SDNodeFlags Flags = N->getFlags(); | |||
14327 | ||||
14328 | // We only need no signed zeros for the 0.25 case. | |||
14329 | if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() || | |||
14330 | !Flags.hasApproximateFuncs()) | |||
14331 | return SDValue(); | |||
14332 | ||||
14333 | // Don't double the number of libcalls. We are trying to inline fast code. | |||
14334 | if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT)) | |||
14335 | return SDValue(); | |||
14336 | ||||
14337 | // Assume that libcalls are the smallest code. | |||
14338 | // TODO: This restriction should probably be lifted for vectors. | |||
14339 | if (ForCodeSize) | |||
14340 | return SDValue(); | |||
14341 | ||||
14342 | // pow(X, 0.25) --> sqrt(sqrt(X)) | |||
14343 | SDLoc DL(N); | |||
14344 | SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0)); | |||
14345 | SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt); | |||
14346 | if (ExponentIs025) | |||
14347 | return SqrtSqrt; | |||
14348 | // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X)) | |||
14349 | return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt); | |||
14350 | } | |||
14351 | ||||
14352 | return SDValue(); | |||
14353 | } | |||
14354 | ||||
14355 | static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, | |||
14356 | const TargetLowering &TLI) { | |||
14357 | // This optimization is guarded by a function attribute because it may produce | |||
14358 | // unexpected results. Ie, programs may be relying on the platform-specific | |||
14359 | // undefined behavior when the float-to-int conversion overflows. | |||
14360 | const Function &F = DAG.getMachineFunction().getFunction(); | |||
14361 | Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); | |||
14362 | if (StrictOverflow.getValueAsString().equals("false")) | |||
14363 | return SDValue(); | |||
14364 | ||||
14365 | // We only do this if the target has legal ftrunc. Otherwise, we'd likely be | |||
14366 | // replacing casts with a libcall. We also must be allowed to ignore -0.0 | |||
14367 | // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer | |||
14368 | // conversions would return +0.0. | |||
14369 | // FIXME: We should be able to use node-level FMF here. | |||
14370 | // TODO: If strict math, should we use FABS (+ range check for signed cast)? | |||
14371 | EVT VT = N->getValueType(0); | |||
14372 | if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || | |||
14373 | !DAG.getTarget().Options.NoSignedZerosFPMath) | |||
14374 | return SDValue(); | |||
14375 | ||||
14376 | // fptosi/fptoui round towards zero, so converting from FP to integer and | |||
14377 | // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X | |||
14378 | SDValue N0 = N->getOperand(0); | |||
14379 | if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && | |||
14380 | N0.getOperand(0).getValueType() == VT) | |||
14381 | return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); | |||
14382 | ||||
14383 | if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && | |||
14384 | N0.getOperand(0).getValueType() == VT) | |||
14385 | return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); | |||
14386 | ||||
14387 | return SDValue(); | |||
14388 | } | |||
14389 | ||||
14390 | SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { | |||
14391 | SDValue N0 = N->getOperand(0); | |||
14392 | EVT VT = N->getValueType(0); | |||
14393 | EVT OpVT = N0.getValueType(); | |||
14394 | ||||
14395 | // [us]itofp(undef) = 0, because the result value is bounded. | |||
14396 | if (N0.isUndef()) | |||
14397 | return DAG.getConstantFP(0.0, SDLoc(N), VT); | |||
14398 | ||||
14399 | // fold (sint_to_fp c1) -> c1fp | |||
14400 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
14401 | // ...but only if the target supports immediate floating-point values | |||
14402 | (!LegalOperations || | |||
14403 | TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) | |||
14404 | return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); | |||
14405 | ||||
14406 | // If the input is a legal type, and SINT_TO_FP is not legal on this target, | |||
14407 | // but UINT_TO_FP is legal on this target, try to convert. | |||
14408 | if (!hasOperation(ISD::SINT_TO_FP, OpVT) && | |||
14409 | hasOperation(ISD::UINT_TO_FP, OpVT)) { | |||
14410 | // If the sign bit is known to be zero, we can change this to UINT_TO_FP. | |||
14411 | if (DAG.SignBitIsZero(N0)) | |||
14412 | return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); | |||
14413 | } | |||
14414 | ||||
14415 | // The next optimizations are desirable only if SELECT_CC can be lowered. | |||
14416 | // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0) | |||
14417 | if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && | |||
14418 | !VT.isVector() && | |||
14419 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { | |||
14420 | SDLoc DL(N); | |||
14421 | return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT), | |||
14422 | DAG.getConstantFP(0.0, DL, VT)); | |||
14423 | } | |||
14424 | ||||
14425 | // fold (sint_to_fp (zext (setcc x, y, cc))) -> | |||
14426 | // (select (setcc x, y, cc), 1.0, 0.0) | |||
14427 | if (N0.getOpcode() == ISD::ZERO_EXTEND && | |||
14428 | N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() && | |||
14429 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { | |||
14430 | SDLoc DL(N); | |||
14431 | return DAG.getSelect(DL, VT, N0.getOperand(0), | |||
14432 | DAG.getConstantFP(1.0, DL, VT), | |||
14433 | DAG.getConstantFP(0.0, DL, VT)); | |||
14434 | } | |||
14435 | ||||
14436 | if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) | |||
14437 | return FTrunc; | |||
14438 | ||||
14439 | return SDValue(); | |||
14440 | } | |||
14441 | ||||
14442 | SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { | |||
14443 | SDValue N0 = N->getOperand(0); | |||
14444 | EVT VT = N->getValueType(0); | |||
14445 | EVT OpVT = N0.getValueType(); | |||
14446 | ||||
14447 | // [us]itofp(undef) = 0, because the result value is bounded. | |||
14448 | if (N0.isUndef()) | |||
14449 | return DAG.getConstantFP(0.0, SDLoc(N), VT); | |||
14450 | ||||
14451 | // fold (uint_to_fp c1) -> c1fp | |||
14452 | if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && | |||
14453 | // ...but only if the target supports immediate floating-point values | |||
14454 | (!LegalOperations || | |||
14455 | TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) | |||
14456 | return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); | |||
14457 | ||||
14458 | // If the input is a legal type, and UINT_TO_FP is not legal on this target, | |||
14459 | // but SINT_TO_FP is legal on this target, try to convert. | |||
14460 | if (!hasOperation(ISD::UINT_TO_FP, OpVT) && | |||
14461 | hasOperation(ISD::SINT_TO_FP, OpVT)) { | |||
14462 | // If the sign bit is known to be zero, we can change this to SINT_TO_FP. | |||
14463 | if (DAG.SignBitIsZero(N0)) | |||
14464 | return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); | |||
14465 | } | |||
14466 | ||||
14467 | // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0) | |||
14468 | if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && | |||
14469 | (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { | |||
14470 | SDLoc DL(N); | |||
14471 | return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT), | |||
14472 | DAG.getConstantFP(0.0, DL, VT)); | |||
14473 | } | |||
14474 | ||||
14475 | if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) | |||
14476 | return FTrunc; | |||
14477 | ||||
14478 | return SDValue(); | |||
14479 | } | |||
14480 | ||||
14481 | // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x | |||
14482 | static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { | |||
14483 | SDValue N0 = N->getOperand(0); | |||
14484 | EVT VT = N->getValueType(0); | |||
14485 | ||||
14486 | if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) | |||
14487 | return SDValue(); | |||
14488 | ||||
14489 | SDValue Src = N0.getOperand(0); | |||
14490 | EVT SrcVT = Src.getValueType(); | |||
14491 | bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; | |||
14492 | bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; | |||
14493 | ||||
14494 | // We can safely assume the conversion won't overflow the output range, | |||
14495 | // because (for example) (uint8_t)18293.f is undefined behavior. | |||
14496 | ||||
14497 | // Since we can assume the conversion won't overflow, our decision as to | |||
14498 | // whether the input will fit in the float should depend on the minimum | |||
14499 | // of the input range and output range. | |||
14500 | ||||
14501 | // This means this is also safe for a signed input and unsigned output, since | |||
14502 | // a negative input would lead to undefined behavior. | |||
14503 | unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; | |||
14504 | unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; | |||
14505 | unsigned ActualSize = std::min(InputSize, OutputSize); | |||
14506 | const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); | |||
14507 | ||||
14508 | // We can only fold away the float conversion if the input range can be | |||
14509 | // represented exactly in the float range. | |||
14510 | if (APFloat::semanticsPrecision(sem) >= ActualSize) { | |||
14511 | if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { | |||
14512 | unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND | |||
14513 | : ISD::ZERO_EXTEND; | |||
14514 | return DAG.getNode(ExtOp, SDLoc(N), VT, Src); | |||
14515 | } | |||
14516 | if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) | |||
14517 | return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); | |||
14518 | return DAG.getBitcast(VT, Src); | |||
14519 | } | |||
14520 | return SDValue(); | |||
14521 | } | |||
14522 | ||||
14523 | SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { | |||
14524 | SDValue N0 = N->getOperand(0); | |||
14525 | EVT VT = N->getValueType(0); | |||
14526 | ||||
14527 | // fold (fp_to_sint undef) -> undef | |||
14528 | if (N0.isUndef()) | |||
14529 | return DAG.getUNDEF(VT); | |||
14530 | ||||
14531 | // fold (fp_to_sint c1fp) -> c1 | |||
14532 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14533 | return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); | |||
14534 | ||||
14535 | return FoldIntToFPToInt(N, DAG); | |||
14536 | } | |||
14537 | ||||
14538 | SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { | |||
14539 | SDValue N0 = N->getOperand(0); | |||
14540 | EVT VT = N->getValueType(0); | |||
14541 | ||||
14542 | // fold (fp_to_uint undef) -> undef | |||
14543 | if (N0.isUndef()) | |||
14544 | return DAG.getUNDEF(VT); | |||
14545 | ||||
14546 | // fold (fp_to_uint c1fp) -> c1 | |||
14547 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14548 | return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); | |||
14549 | ||||
14550 | return FoldIntToFPToInt(N, DAG); | |||
14551 | } | |||
14552 | ||||
14553 | SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { | |||
14554 | SDValue N0 = N->getOperand(0); | |||
14555 | SDValue N1 = N->getOperand(1); | |||
14556 | ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); | |||
14557 | EVT VT = N->getValueType(0); | |||
14558 | ||||
14559 | // fold (fp_round c1fp) -> c1fp | |||
14560 | if (N0CFP) | |||
14561 | return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); | |||
14562 | ||||
14563 | // fold (fp_round (fp_extend x)) -> x | |||
14564 | if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) | |||
14565 | return N0.getOperand(0); | |||
14566 | ||||
14567 | // fold (fp_round (fp_round x)) -> (fp_round x) | |||
14568 | if (N0.getOpcode() == ISD::FP_ROUND) { | |||
14569 | const bool NIsTrunc = N->getConstantOperandVal(1) == 1; | |||
14570 | const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; | |||
14571 | ||||
14572 | // Skip this folding if it results in an fp_round from f80 to f16. | |||
14573 | // | |||
14574 | // f80 to f16 always generates an expensive (and as yet, unimplemented) | |||
14575 | // libcall to __truncxfhf2 instead of selecting native f16 conversion | |||
14576 | // instructions from f32 or f64. Moreover, the first (value-preserving) | |||
14577 | // fp_round from f80 to either f32 or f64 may become a NOP in platforms like | |||
14578 | // x86. | |||
14579 | if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) | |||
14580 | return SDValue(); | |||
14581 | ||||
14582 | // If the first fp_round isn't a value preserving truncation, it might | |||
14583 | // introduce a tie in the second fp_round, that wouldn't occur in the | |||
14584 | // single-step fp_round we want to fold to. | |||
14585 | // In other words, double rounding isn't the same as rounding. | |||
14586 | // Also, this is a value preserving truncation iff both fp_round's are. | |||
14587 | if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { | |||
14588 | SDLoc DL(N); | |||
14589 | return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), | |||
14590 | DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); | |||
14591 | } | |||
14592 | } | |||
14593 | ||||
14594 | // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) | |||
14595 | if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { | |||
14596 | SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, | |||
14597 | N0.getOperand(0), N1); | |||
14598 | AddToWorklist(Tmp.getNode()); | |||
14599 | return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, | |||
14600 | Tmp, N0.getOperand(1)); | |||
14601 | } | |||
14602 | ||||
14603 | if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) | |||
14604 | return NewVSel; | |||
14605 | ||||
14606 | return SDValue(); | |||
14607 | } | |||
14608 | ||||
14609 | SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { | |||
14610 | SDValue N0 = N->getOperand(0); | |||
14611 | EVT VT = N->getValueType(0); | |||
14612 | ||||
14613 | // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. | |||
14614 | if (N->hasOneUse() && | |||
14615 | N->use_begin()->getOpcode() == ISD::FP_ROUND) | |||
14616 | return SDValue(); | |||
14617 | ||||
14618 | // fold (fp_extend c1fp) -> c1fp | |||
14619 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14620 | return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); | |||
14621 | ||||
14622 | // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) | |||
14623 | if (N0.getOpcode() == ISD::FP16_TO_FP && | |||
14624 | TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) | |||
14625 | return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); | |||
14626 | ||||
14627 | // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the | |||
14628 | // value of X. | |||
14629 | if (N0.getOpcode() == ISD::FP_ROUND | |||
14630 | && N0.getConstantOperandVal(1) == 1) { | |||
14631 | SDValue In = N0.getOperand(0); | |||
14632 | if (In.getValueType() == VT) return In; | |||
14633 | if (VT.bitsLT(In.getValueType())) | |||
14634 | return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, | |||
14635 | In, N0.getOperand(1)); | |||
14636 | return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); | |||
14637 | } | |||
14638 | ||||
14639 | // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) | |||
14640 | if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && | |||
14641 | TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { | |||
14642 | LoadSDNode *LN0 = cast<LoadSDNode>(N0); | |||
14643 | SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, | |||
14644 | LN0->getChain(), | |||
14645 | LN0->getBasePtr(), N0.getValueType(), | |||
14646 | LN0->getMemOperand()); | |||
14647 | CombineTo(N, ExtLoad); | |||
14648 | CombineTo(N0.getNode(), | |||
14649 | DAG.getNode(ISD::FP_ROUND, SDLoc(N0), | |||
14650 | N0.getValueType(), ExtLoad, | |||
14651 | DAG.getIntPtrConstant(1, SDLoc(N0))), | |||
14652 | ExtLoad.getValue(1)); | |||
14653 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
14654 | } | |||
14655 | ||||
14656 | if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) | |||
14657 | return NewVSel; | |||
14658 | ||||
14659 | return SDValue(); | |||
14660 | } | |||
14661 | ||||
14662 | SDValue DAGCombiner::visitFCEIL(SDNode *N) { | |||
14663 | SDValue N0 = N->getOperand(0); | |||
14664 | EVT VT = N->getValueType(0); | |||
14665 | ||||
14666 | // fold (fceil c1) -> fceil(c1) | |||
14667 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14668 | return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); | |||
14669 | ||||
14670 | return SDValue(); | |||
14671 | } | |||
14672 | ||||
14673 | SDValue DAGCombiner::visitFTRUNC(SDNode *N) { | |||
14674 | SDValue N0 = N->getOperand(0); | |||
14675 | EVT VT = N->getValueType(0); | |||
14676 | ||||
14677 | // fold (ftrunc c1) -> ftrunc(c1) | |||
14678 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14679 | return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); | |||
14680 | ||||
14681 | // fold ftrunc (known rounded int x) -> x | |||
14682 | // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is | |||
14683 | // likely to be generated to extract integer from a rounded floating value. | |||
14684 | switch (N0.getOpcode()) { | |||
14685 | default: break; | |||
14686 | case ISD::FRINT: | |||
14687 | case ISD::FTRUNC: | |||
14688 | case ISD::FNEARBYINT: | |||
14689 | case ISD::FFLOOR: | |||
14690 | case ISD::FCEIL: | |||
14691 | return N0; | |||
14692 | } | |||
14693 | ||||
14694 | return SDValue(); | |||
14695 | } | |||
14696 | ||||
14697 | SDValue DAGCombiner::visitFFLOOR(SDNode *N) { | |||
14698 | SDValue N0 = N->getOperand(0); | |||
14699 | EVT VT = N->getValueType(0); | |||
14700 | ||||
14701 | // fold (ffloor c1) -> ffloor(c1) | |||
14702 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14703 | return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); | |||
14704 | ||||
14705 | return SDValue(); | |||
14706 | } | |||
14707 | ||||
14708 | SDValue DAGCombiner::visitFNEG(SDNode *N) { | |||
14709 | SDValue N0 = N->getOperand(0); | |||
14710 | EVT VT = N->getValueType(0); | |||
14711 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
14712 | ||||
14713 | // Constant fold FNEG. | |||
14714 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14715 | return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); | |||
14716 | ||||
14717 | if (SDValue NegN0 = | |||
14718 | TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize)) | |||
14719 | return NegN0; | |||
14720 | ||||
14721 | // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 | |||
14722 | // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't | |||
14723 | // know it was called from a context with a nsz flag if the input fsub does | |||
14724 | // not. | |||
14725 | if (N0.getOpcode() == ISD::FSUB && | |||
14726 | (DAG.getTarget().Options.NoSignedZerosFPMath || | |||
14727 | N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) { | |||
14728 | return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1), | |||
14729 | N0.getOperand(0)); | |||
14730 | } | |||
14731 | ||||
14732 | if (SDValue Cast = foldSignChangeInBitcast(N)) | |||
14733 | return Cast; | |||
14734 | ||||
14735 | return SDValue(); | |||
14736 | } | |||
14737 | ||||
14738 | static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, | |||
14739 | APFloat (*Op)(const APFloat &, const APFloat &)) { | |||
14740 | SDValue N0 = N->getOperand(0); | |||
14741 | SDValue N1 = N->getOperand(1); | |||
14742 | EVT VT = N->getValueType(0); | |||
14743 | const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); | |||
14744 | const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); | |||
14745 | const SDNodeFlags Flags = N->getFlags(); | |||
14746 | unsigned Opc = N->getOpcode(); | |||
14747 | bool PropagatesNaN = Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM; | |||
14748 | bool IsMin = Opc == ISD::FMINNUM || Opc == ISD::FMINIMUM; | |||
14749 | SelectionDAG::FlagInserter FlagsInserter(DAG, N); | |||
14750 | ||||
14751 | if (N0CFP && N1CFP) { | |||
14752 | const APFloat &C0 = N0CFP->getValueAPF(); | |||
14753 | const APFloat &C1 = N1CFP->getValueAPF(); | |||
14754 | return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT); | |||
14755 | } | |||
14756 | ||||
14757 | // Canonicalize to constant on RHS. | |||
14758 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && | |||
14759 | !DAG.isConstantFPBuildVectorOrConstantFP(N1)) | |||
14760 | return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); | |||
14761 | ||||
14762 | if (N1CFP) { | |||
14763 | const APFloat &AF = N1CFP->getValueAPF(); | |||
14764 | ||||
14765 | // minnum(X, nan) -> X | |||
14766 | // maxnum(X, nan) -> X | |||
14767 | // minimum(X, nan) -> nan | |||
14768 | // maximum(X, nan) -> nan | |||
14769 | if (AF.isNaN()) | |||
14770 | return PropagatesNaN ? N->getOperand(1) : N->getOperand(0); | |||
14771 | ||||
14772 | // In the following folds, inf can be replaced with the largest finite | |||
14773 | // float, if the ninf flag is set. | |||
14774 | if (AF.isInfinity() || (Flags.hasNoInfs() && AF.isLargest())) { | |||
14775 | // minnum(X, -inf) -> -inf | |||
14776 | // maxnum(X, +inf) -> +inf | |||
14777 | // minimum(X, -inf) -> -inf if nnan | |||
14778 | // maximum(X, +inf) -> +inf if nnan | |||
14779 | if (IsMin == AF.isNegative() && (!PropagatesNaN || Flags.hasNoNaNs())) | |||
14780 | return N->getOperand(1); | |||
14781 | ||||
14782 | // minnum(X, +inf) -> X if nnan | |||
14783 | // maxnum(X, -inf) -> X if nnan | |||
14784 | // minimum(X, +inf) -> X | |||
14785 | // maximum(X, -inf) -> X | |||
14786 | if (IsMin != AF.isNegative() && (PropagatesNaN || Flags.hasNoNaNs())) | |||
14787 | return N->getOperand(0); | |||
14788 | } | |||
14789 | } | |||
14790 | ||||
14791 | return SDValue(); | |||
14792 | } | |||
14793 | ||||
14794 | SDValue DAGCombiner::visitFMINNUM(SDNode *N) { | |||
14795 | return visitFMinMax(DAG, N, minnum); | |||
14796 | } | |||
14797 | ||||
14798 | SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { | |||
14799 | return visitFMinMax(DAG, N, maxnum); | |||
14800 | } | |||
14801 | ||||
14802 | SDValue DAGCombiner::visitFMINIMUM(SDNode *N) { | |||
14803 | return visitFMinMax(DAG, N, minimum); | |||
14804 | } | |||
14805 | ||||
14806 | SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) { | |||
14807 | return visitFMinMax(DAG, N, maximum); | |||
14808 | } | |||
14809 | ||||
14810 | SDValue DAGCombiner::visitFABS(SDNode *N) { | |||
14811 | SDValue N0 = N->getOperand(0); | |||
14812 | EVT VT = N->getValueType(0); | |||
14813 | ||||
14814 | // fold (fabs c1) -> fabs(c1) | |||
14815 | if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) | |||
14816 | return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); | |||
14817 | ||||
14818 | // fold (fabs (fabs x)) -> (fabs x) | |||
14819 | if (N0.getOpcode() == ISD::FABS) | |||
14820 | return N->getOperand(0); | |||
14821 | ||||
14822 | // fold (fabs (fneg x)) -> (fabs x) | |||
14823 | // fold (fabs (fcopysign x, y)) -> (fabs x) | |||
14824 | if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) | |||
14825 | return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); | |||
14826 | ||||
14827 | if (SDValue Cast = foldSignChangeInBitcast(N)) | |||
14828 | return Cast; | |||
14829 | ||||
14830 | return SDValue(); | |||
14831 | } | |||
14832 | ||||
14833 | SDValue DAGCombiner::visitBRCOND(SDNode *N) { | |||
14834 | SDValue Chain = N->getOperand(0); | |||
14835 | SDValue N1 = N->getOperand(1); | |||
14836 | SDValue N2 = N->getOperand(2); | |||
14837 | ||||
14838 | // BRCOND(FREEZE(cond)) is equivalent to BRCOND(cond) (both are | |||
14839 | // nondeterministic jumps). | |||
14840 | if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse()) { | |||
14841 | return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, | |||
14842 | N1->getOperand(0), N2); | |||
14843 | } | |||
14844 | ||||
14845 | // If N is a constant we could fold this into a fallthrough or unconditional | |||
14846 | // branch. However that doesn't happen very often in normal code, because | |||
14847 | // Instcombine/SimplifyCFG should have handled the available opportunities. | |||
14848 | // If we did this folding here, it would be necessary to update the | |||
14849 | // MachineBasicBlock CFG, which is awkward. | |||
14850 | ||||
14851 | // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal | |||
14852 | // on the target. | |||
14853 | if (N1.getOpcode() == ISD::SETCC && | |||
14854 | TLI.isOperationLegalOrCustom(ISD::BR_CC, | |||
14855 | N1.getOperand(0).getValueType())) { | |||
14856 | return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, | |||
14857 | Chain, N1.getOperand(2), | |||
14858 | N1.getOperand(0), N1.getOperand(1), N2); | |||
14859 | } | |||
14860 | ||||
14861 | if (N1.hasOneUse()) { | |||
14862 | // rebuildSetCC calls visitXor which may change the Chain when there is a | |||
14863 | // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes. | |||
14864 | HandleSDNode ChainHandle(Chain); | |||
14865 | if (SDValue NewN1 = rebuildSetCC(N1)) | |||
14866 | return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, | |||
14867 | ChainHandle.getValue(), NewN1, N2); | |||
14868 | } | |||
14869 | ||||
14870 | return SDValue(); | |||
14871 | } | |||
14872 | ||||
14873 | SDValue DAGCombiner::rebuildSetCC(SDValue N) { | |||
14874 | if (N.getOpcode() == ISD::SRL || | |||
14875 | (N.getOpcode() == ISD::TRUNCATE && | |||
14876 | (N.getOperand(0).hasOneUse() && | |||
14877 | N.getOperand(0).getOpcode() == ISD::SRL))) { | |||
14878 | // Look pass the truncate. | |||
14879 | if (N.getOpcode() == ISD::TRUNCATE) | |||
14880 | N = N.getOperand(0); | |||
14881 | ||||
14882 | // Match this pattern so that we can generate simpler code: | |||
14883 | // | |||
14884 | // %a = ... | |||
14885 | // %b = and i32 %a, 2 | |||
14886 | // %c = srl i32 %b, 1 | |||
14887 | // brcond i32 %c ... | |||
14888 | // | |||
14889 | // into | |||
14890 | // | |||
14891 | // %a = ... | |||
14892 | // %b = and i32 %a, 2 | |||
14893 | // %c = setcc eq %b, 0 | |||
14894 | // brcond %c ... | |||
14895 | // | |||
14896 | // This applies only when the AND constant value has one bit set and the | |||
14897 | // SRL constant is equal to the log2 of the AND constant. The back-end is | |||
14898 | // smart enough to convert the result into a TEST/JMP sequence. | |||
14899 | SDValue Op0 = N.getOperand(0); | |||
14900 | SDValue Op1 = N.getOperand(1); | |||
14901 | ||||
14902 | if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { | |||
14903 | SDValue AndOp1 = Op0.getOperand(1); | |||
14904 | ||||
14905 | if (AndOp1.getOpcode() == ISD::Constant) { | |||
14906 | const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); | |||
14907 | ||||
14908 | if (AndConst.isPowerOf2() && | |||
14909 | cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { | |||
14910 | SDLoc DL(N); | |||
14911 | return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), | |||
14912 | Op0, DAG.getConstant(0, DL, Op0.getValueType()), | |||
14913 | ISD::SETNE); | |||
14914 | } | |||
14915 | } | |||
14916 | } | |||
14917 | } | |||
14918 | ||||
14919 | // Transform (brcond (xor x, y)) -> (brcond (setcc, x, y, ne)) | |||
14920 | // Transform (brcond (xor (xor x, y), -1)) -> (brcond (setcc, x, y, eq)) | |||
14921 | if (N.getOpcode() == ISD::XOR) { | |||
14922 | // Because we may call this on a speculatively constructed | |||
14923 | // SimplifiedSetCC Node, we need to simplify this node first. | |||
14924 | // Ideally this should be folded into SimplifySetCC and not | |||
14925 | // here. For now, grab a handle to N so we don't lose it from | |||
14926 | // replacements interal to the visit. | |||
14927 | HandleSDNode XORHandle(N); | |||
14928 | while (N.getOpcode() == ISD::XOR) { | |||
14929 | SDValue Tmp = visitXOR(N.getNode()); | |||
14930 | // No simplification done. | |||
14931 | if (!Tmp.getNode()) | |||
14932 | break; | |||
14933 | // Returning N is form in-visit replacement that may invalidated | |||
14934 | // N. Grab value from Handle. | |||
14935 | if (Tmp.getNode() == N.getNode()) | |||
14936 | N = XORHandle.getValue(); | |||
14937 | else // Node simplified. Try simplifying again. | |||
14938 | N = Tmp; | |||
14939 | } | |||
14940 | ||||
14941 | if (N.getOpcode() != ISD::XOR) | |||
14942 | return N; | |||
14943 | ||||
14944 | SDValue Op0 = N->getOperand(0); | |||
14945 | SDValue Op1 = N->getOperand(1); | |||
14946 | ||||
14947 | if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { | |||
14948 | bool Equal = false; | |||
14949 | // (brcond (xor (xor x, y), -1)) -> (brcond (setcc x, y, eq)) | |||
14950 | if (isBitwiseNot(N) && Op0.hasOneUse() && Op0.getOpcode() == ISD::XOR && | |||
14951 | Op0.getValueType() == MVT::i1) { | |||
14952 | N = Op0; | |||
14953 | Op0 = N->getOperand(0); | |||
14954 | Op1 = N->getOperand(1); | |||
14955 | Equal = true; | |||
14956 | } | |||
14957 | ||||
14958 | EVT SetCCVT = N.getValueType(); | |||
14959 | if (LegalTypes) | |||
14960 | SetCCVT = getSetCCResultType(SetCCVT); | |||
14961 | // Replace the uses of XOR with SETCC | |||
14962 | return DAG.getSetCC(SDLoc(N), SetCCVT, Op0, Op1, | |||
14963 | Equal ? ISD::SETEQ : ISD::SETNE); | |||
14964 | } | |||
14965 | } | |||
14966 | ||||
14967 | return SDValue(); | |||
14968 | } | |||
14969 | ||||
14970 | // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. | |||
14971 | // | |||
14972 | SDValue DAGCombiner::visitBR_CC(SDNode *N) { | |||
14973 | CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); | |||
14974 | SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); | |||
14975 | ||||
14976 | // If N is a constant we could fold this into a fallthrough or unconditional | |||
14977 | // branch. However that doesn't happen very often in normal code, because | |||
14978 | // Instcombine/SimplifyCFG should have handled the available opportunities. | |||
14979 | // If we did this folding here, it would be necessary to update the | |||
14980 | // MachineBasicBlock CFG, which is awkward. | |||
14981 | ||||
14982 | // Use SimplifySetCC to simplify SETCC's. | |||
14983 | SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), | |||
14984 | CondLHS, CondRHS, CC->get(), SDLoc(N), | |||
14985 | false); | |||
14986 | if (Simp.getNode()) AddToWorklist(Simp.getNode()); | |||
14987 | ||||
14988 | // fold to a simpler setcc | |||
14989 | if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) | |||
14990 | return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, | |||
14991 | N->getOperand(0), Simp.getOperand(2), | |||
14992 | Simp.getOperand(0), Simp.getOperand(1), | |||
14993 | N->getOperand(4)); | |||
14994 | ||||
14995 | return SDValue(); | |||
14996 | } | |||
14997 | ||||
14998 | static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec, | |||
14999 | bool &IsLoad, bool &IsMasked, SDValue &Ptr, | |||
15000 | const TargetLowering &TLI) { | |||
15001 | if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { | |||
15002 | if (LD->isIndexed()) | |||
15003 | return false; | |||
15004 | EVT VT = LD->getMemoryVT(); | |||
15005 | if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT)) | |||
15006 | return false; | |||
15007 | Ptr = LD->getBasePtr(); | |||
15008 | } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { | |||
15009 | if (ST->isIndexed()) | |||
15010 | return false; | |||
15011 | EVT VT = ST->getMemoryVT(); | |||
15012 | if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT)) | |||
15013 | return false; | |||
15014 | Ptr = ST->getBasePtr(); | |||
15015 | IsLoad = false; | |||
15016 | } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { | |||
15017 | if (LD->isIndexed()) | |||
15018 | return false; | |||
15019 | EVT VT = LD->getMemoryVT(); | |||
15020 | if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) && | |||
15021 | !TLI.isIndexedMaskedLoadLegal(Dec, VT)) | |||
15022 | return false; | |||
15023 | Ptr = LD->getBasePtr(); | |||
15024 | IsMasked = true; | |||
15025 | } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { | |||
15026 | if (ST->isIndexed()) | |||
15027 | return false; | |||
15028 | EVT VT = ST->getMemoryVT(); | |||
15029 | if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) && | |||
15030 | !TLI.isIndexedMaskedStoreLegal(Dec, VT)) | |||
15031 | return false; | |||
15032 | Ptr = ST->getBasePtr(); | |||
15033 | IsLoad = false; | |||
15034 | IsMasked = true; | |||
15035 | } else { | |||
15036 | return false; | |||
15037 | } | |||
15038 | return true; | |||
15039 | } | |||
15040 | ||||
15041 | /// Try turning a load/store into a pre-indexed load/store when the base | |||
15042 | /// pointer is an add or subtract and it has other uses besides the load/store. | |||
15043 | /// After the transformation, the new indexed load/store has effectively folded | |||
15044 | /// the add/subtract in and all of its other uses are redirected to the | |||
15045 | /// new load/store. | |||
15046 | bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { | |||
15047 | if (Level < AfterLegalizeDAG) | |||
15048 | return false; | |||
15049 | ||||
15050 | bool IsLoad = true; | |||
15051 | bool IsMasked = false; | |||
15052 | SDValue Ptr; | |||
15053 | if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked, | |||
15054 | Ptr, TLI)) | |||
15055 | return false; | |||
15056 | ||||
15057 | // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail | |||
15058 | // out. There is no reason to make this a preinc/predec. | |||
15059 | if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || | |||
15060 | Ptr.getNode()->hasOneUse()) | |||
15061 | return false; | |||
15062 | ||||
15063 | // Ask the target to do addressing mode selection. | |||
15064 | SDValue BasePtr; | |||
15065 | SDValue Offset; | |||
15066 | ISD::MemIndexedMode AM = ISD::UNINDEXED; | |||
15067 | if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) | |||
15068 | return false; | |||
15069 | ||||
15070 | // Backends without true r+i pre-indexed forms may need to pass a | |||
15071 | // constant base with a variable offset so that constant coercion | |||
15072 | // will work with the patterns in canonical form. | |||
15073 | bool Swapped = false; | |||
15074 | if (isa<ConstantSDNode>(BasePtr)) { | |||
15075 | std::swap(BasePtr, Offset); | |||
15076 | Swapped = true; | |||
15077 | } | |||
15078 | ||||
15079 | // Don't create a indexed load / store with zero offset. | |||
15080 | if (isNullConstant(Offset)) | |||
15081 | return false; | |||
15082 | ||||
15083 | // Try turning it into a pre-indexed load / store except when: | |||
15084 | // 1) The new base ptr is a frame index. | |||
15085 | // 2) If N is a store and the new base ptr is either the same as or is a | |||
15086 | // predecessor of the value being stored. | |||
15087 | // 3) Another use of old base ptr is a predecessor of N. If ptr is folded | |||
15088 | // that would create a cycle. | |||
15089 | // 4) All uses are load / store ops that use it as old base ptr. | |||
15090 | ||||
15091 | // Check #1. Preinc'ing a frame index would require copying the stack pointer | |||
15092 | // (plus the implicit offset) to a register to preinc anyway. | |||
15093 | if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) | |||
15094 | return false; | |||
15095 | ||||
15096 | // Check #2. | |||
15097 | if (!IsLoad) { | |||
15098 | SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue() | |||
15099 | : cast<StoreSDNode>(N)->getValue(); | |||
15100 | ||||
15101 | // Would require a copy. | |||
15102 | if (Val == BasePtr) | |||
15103 | return false; | |||
15104 | ||||
15105 | // Would create a cycle. | |||
15106 | if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode())) | |||
15107 | return false; | |||
15108 | } | |||
15109 | ||||
15110 | // Caches for hasPredecessorHelper. | |||
15111 | SmallPtrSet<const SDNode *, 32> Visited; | |||
15112 | SmallVector<const SDNode *, 16> Worklist; | |||
15113 | Worklist.push_back(N); | |||
15114 | ||||
15115 | // If the offset is a constant, there may be other adds of constants that | |||
15116 | // can be folded with this one. We should do this to avoid having to keep | |||
15117 | // a copy of the original base pointer. | |||
15118 | SmallVector<SDNode *, 16> OtherUses; | |||
15119 | if (isa<ConstantSDNode>(Offset)) | |||
15120 | for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), | |||
15121 | UE = BasePtr.getNode()->use_end(); | |||
15122 | UI != UE; ++UI) { | |||
15123 | SDUse &Use = UI.getUse(); | |||
15124 | // Skip the use that is Ptr and uses of other results from BasePtr's | |||
15125 | // node (important for nodes that return multiple results). | |||
15126 | if (Use.getUser() == Ptr.getNode() || Use != BasePtr) | |||
15127 | continue; | |||
15128 | ||||
15129 | if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) | |||
15130 | continue; | |||
15131 | ||||
15132 | if (Use.getUser()->getOpcode() != ISD::ADD && | |||
15133 | Use.getUser()->getOpcode() != ISD::SUB) { | |||
15134 | OtherUses.clear(); | |||
15135 | break; | |||
15136 | } | |||
15137 | ||||
15138 | SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); | |||
15139 | if (!isa<ConstantSDNode>(Op1)) { | |||
15140 | OtherUses.clear(); | |||
15141 | break; | |||
15142 | } | |||
15143 | ||||
15144 | // FIXME: In some cases, we can be smarter about this. | |||
15145 | if (Op1.getValueType() != Offset.getValueType()) { | |||
15146 | OtherUses.clear(); | |||
15147 | break; | |||
15148 | } | |||
15149 | ||||
15150 | OtherUses.push_back(Use.getUser()); | |||
15151 | } | |||
15152 | ||||
15153 | if (Swapped) | |||
15154 | std::swap(BasePtr, Offset); | |||
15155 | ||||
15156 | // Now check for #3 and #4. | |||
15157 | bool RealUse = false; | |||
15158 | ||||
15159 | for (SDNode *Use : Ptr.getNode()->uses()) { | |||
15160 | if (Use == N) | |||
15161 | continue; | |||
15162 | if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) | |||
15163 | return false; | |||
15164 | ||||
15165 | // If Ptr may be folded in addressing mode of other use, then it's | |||
15166 | // not profitable to do this transformation. | |||
15167 | if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) | |||
15168 | RealUse = true; | |||
15169 | } | |||
15170 | ||||
15171 | if (!RealUse) | |||
15172 | return false; | |||
15173 | ||||
15174 | SDValue Result; | |||
15175 | if (!IsMasked) { | |||
15176 | if (IsLoad) | |||
15177 | Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); | |||
15178 | else | |||
15179 | Result = | |||
15180 | DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); | |||
15181 | } else { | |||
15182 | if (IsLoad) | |||
15183 | Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr, | |||
15184 | Offset, AM); | |||
15185 | else | |||
15186 | Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr, | |||
15187 | Offset, AM); | |||
15188 | } | |||
15189 | ++PreIndexedNodes; | |||
15190 | ++NodesCombined; | |||
15191 | LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump (&DAG); dbgs() << "\nWith: "; Result.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false) | |||
15192 | Result.getNode()->dump(&DAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump (&DAG); dbgs() << "\nWith: "; Result.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false); | |||
15193 | WorklistRemover DeadNodes(*this); | |||
15194 | if (IsLoad) { | |||
15195 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); | |||
15196 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); | |||
15197 | } else { | |||
15198 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); | |||
15199 | } | |||
15200 | ||||
15201 | // Finally, since the node is now dead, remove it from the graph. | |||
15202 | deleteAndRecombine(N); | |||
15203 | ||||
15204 | if (Swapped) | |||
15205 | std::swap(BasePtr, Offset); | |||
15206 | ||||
15207 | // Replace other uses of BasePtr that can be updated to use Ptr | |||
15208 | for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { | |||
15209 | unsigned OffsetIdx = 1; | |||
15210 | if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) | |||
15211 | OffsetIdx = 0; | |||
15212 | assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==((OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr .getNode() && "Expected BasePtr operand") ? static_cast <void> (0) : __assert_fail ("OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr.getNode() && \"Expected BasePtr operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15213, __PRETTY_FUNCTION__)) | |||
15213 | BasePtr.getNode() && "Expected BasePtr operand")((OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr .getNode() && "Expected BasePtr operand") ? static_cast <void> (0) : __assert_fail ("OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr.getNode() && \"Expected BasePtr operand\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15213, __PRETTY_FUNCTION__)); | |||
15214 | ||||
15215 | // We need to replace ptr0 in the following expression: | |||
15216 | // x0 * offset0 + y0 * ptr0 = t0 | |||
15217 | // knowing that | |||
15218 | // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) | |||
15219 | // | |||
15220 | // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the | |||
15221 | // indexed load/store and the expression that needs to be re-written. | |||
15222 | // | |||
15223 | // Therefore, we have: | |||
15224 | // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 | |||
15225 | ||||
15226 | auto *CN = cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); | |||
15227 | const APInt &Offset0 = CN->getAPIntValue(); | |||
15228 | const APInt &Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); | |||
15229 | int X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; | |||
15230 | int Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; | |||
15231 | int X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; | |||
15232 | int Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; | |||
15233 | ||||
15234 | unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; | |||
15235 | ||||
15236 | APInt CNV = Offset0; | |||
15237 | if (X0 < 0) CNV = -CNV; | |||
15238 | if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; | |||
15239 | else CNV = CNV - Offset1; | |||
15240 | ||||
15241 | SDLoc DL(OtherUses[i]); | |||
15242 | ||||
15243 | // We can now generate the new expression. | |||
15244 | SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); | |||
15245 | SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0); | |||
15246 | ||||
15247 | SDValue NewUse = DAG.getNode(Opcode, | |||
15248 | DL, | |||
15249 | OtherUses[i]->getValueType(0), NewOp1, NewOp2); | |||
15250 | DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); | |||
15251 | deleteAndRecombine(OtherUses[i]); | |||
15252 | } | |||
15253 | ||||
15254 | // Replace the uses of Ptr with uses of the updated base value. | |||
15255 | DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0)); | |||
15256 | deleteAndRecombine(Ptr.getNode()); | |||
15257 | AddToWorklist(Result.getNode()); | |||
15258 | ||||
15259 | return true; | |||
15260 | } | |||
15261 | ||||
15262 | static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse, | |||
15263 | SDValue &BasePtr, SDValue &Offset, | |||
15264 | ISD::MemIndexedMode &AM, | |||
15265 | SelectionDAG &DAG, | |||
15266 | const TargetLowering &TLI) { | |||
15267 | if (PtrUse == N || | |||
15268 | (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB)) | |||
15269 | return false; | |||
15270 | ||||
15271 | if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG)) | |||
15272 | return false; | |||
15273 | ||||
15274 | // Don't create a indexed load / store with zero offset. | |||
15275 | if (isNullConstant(Offset)) | |||
15276 | return false; | |||
15277 | ||||
15278 | if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) | |||
15279 | return false; | |||
15280 | ||||
15281 | SmallPtrSet<const SDNode *, 32> Visited; | |||
15282 | for (SDNode *Use : BasePtr.getNode()->uses()) { | |||
15283 | if (Use == Ptr.getNode()) | |||
15284 | continue; | |||
15285 | ||||
15286 | // No if there's a later user which could perform the index instead. | |||
15287 | if (isa<MemSDNode>(Use)) { | |||
15288 | bool IsLoad = true; | |||
15289 | bool IsMasked = false; | |||
15290 | SDValue OtherPtr; | |||
15291 | if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad, | |||
15292 | IsMasked, OtherPtr, TLI)) { | |||
15293 | SmallVector<const SDNode *, 2> Worklist; | |||
15294 | Worklist.push_back(Use); | |||
15295 | if (SDNode::hasPredecessorHelper(N, Visited, Worklist)) | |||
15296 | return false; | |||
15297 | } | |||
15298 | } | |||
15299 | ||||
15300 | // If all the uses are load / store addresses, then don't do the | |||
15301 | // transformation. | |||
15302 | if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) { | |||
15303 | for (SDNode *UseUse : Use->uses()) | |||
15304 | if (canFoldInAddressingMode(Use, UseUse, DAG, TLI)) | |||
15305 | return false; | |||
15306 | } | |||
15307 | } | |||
15308 | return true; | |||
15309 | } | |||
15310 | ||||
15311 | static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad, | |||
15312 | bool &IsMasked, SDValue &Ptr, | |||
15313 | SDValue &BasePtr, SDValue &Offset, | |||
15314 | ISD::MemIndexedMode &AM, | |||
15315 | SelectionDAG &DAG, | |||
15316 | const TargetLowering &TLI) { | |||
15317 | if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad, | |||
15318 | IsMasked, Ptr, TLI) || | |||
15319 | Ptr.getNode()->hasOneUse()) | |||
15320 | return nullptr; | |||
15321 | ||||
15322 | // Try turning it into a post-indexed load / store except when | |||
15323 | // 1) All uses are load / store ops that use it as base ptr (and | |||
15324 | // it may be folded as addressing mmode). | |||
15325 | // 2) Op must be independent of N, i.e. Op is neither a predecessor | |||
15326 | // nor a successor of N. Otherwise, if Op is folded that would | |||
15327 | // create a cycle. | |||
15328 | for (SDNode *Op : Ptr->uses()) { | |||
15329 | // Check for #1. | |||
15330 | if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI)) | |||
15331 | continue; | |||
15332 | ||||
15333 | // Check for #2. | |||
15334 | SmallPtrSet<const SDNode *, 32> Visited; | |||
15335 | SmallVector<const SDNode *, 8> Worklist; | |||
15336 | // Ptr is predecessor to both N and Op. | |||
15337 | Visited.insert(Ptr.getNode()); | |||
15338 | Worklist.push_back(N); | |||
15339 | Worklist.push_back(Op); | |||
15340 | if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) && | |||
15341 | !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) | |||
15342 | return Op; | |||
15343 | } | |||
15344 | return nullptr; | |||
15345 | } | |||
15346 | ||||
15347 | /// Try to combine a load/store with a add/sub of the base pointer node into a | |||
15348 | /// post-indexed load/store. The transformation folded the add/subtract into the | |||
15349 | /// new indexed load/store effectively and all of its uses are redirected to the | |||
15350 | /// new load/store. | |||
15351 | bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { | |||
15352 | if (Level < AfterLegalizeDAG) | |||
15353 | return false; | |||
15354 | ||||
15355 | bool IsLoad = true; | |||
15356 | bool IsMasked = false; | |||
15357 | SDValue Ptr; | |||
15358 | SDValue BasePtr; | |||
15359 | SDValue Offset; | |||
15360 | ISD::MemIndexedMode AM = ISD::UNINDEXED; | |||
15361 | SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr, | |||
15362 | Offset, AM, DAG, TLI); | |||
15363 | if (!Op) | |||
15364 | return false; | |||
15365 | ||||
15366 | SDValue Result; | |||
15367 | if (!IsMasked) | |||
15368 | Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, | |||
15369 | Offset, AM) | |||
15370 | : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), | |||
15371 | BasePtr, Offset, AM); | |||
15372 | else | |||
15373 | Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), | |||
15374 | BasePtr, Offset, AM) | |||
15375 | : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), | |||
15376 | BasePtr, Offset, AM); | |||
15377 | ++PostIndexedNodes; | |||
15378 | ++NodesCombined; | |||
15379 | LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump (&DAG); dbgs() << "\nWith: "; Result.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false) | |||
15380 | dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump (&DAG); dbgs() << "\nWith: "; Result.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false) | |||
15381 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump (&DAG); dbgs() << "\nWith: "; Result.getNode()-> dump(&DAG); dbgs() << '\n'; } } while (false); | |||
15382 | WorklistRemover DeadNodes(*this); | |||
15383 | if (IsLoad) { | |||
15384 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); | |||
15385 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); | |||
15386 | } else { | |||
15387 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); | |||
15388 | } | |||
15389 | ||||
15390 | // Finally, since the node is now dead, remove it from the graph. | |||
15391 | deleteAndRecombine(N); | |||
15392 | ||||
15393 | // Replace the uses of Use with uses of the updated base value. | |||
15394 | DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), | |||
15395 | Result.getValue(IsLoad ? 1 : 0)); | |||
15396 | deleteAndRecombine(Op); | |||
15397 | return true; | |||
15398 | } | |||
15399 | ||||
15400 | /// Return the base-pointer arithmetic from an indexed \p LD. | |||
15401 | SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { | |||
15402 | ISD::MemIndexedMode AM = LD->getAddressingMode(); | |||
15403 | assert(AM != ISD::UNINDEXED)((AM != ISD::UNINDEXED) ? static_cast<void> (0) : __assert_fail ("AM != ISD::UNINDEXED", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15403, __PRETTY_FUNCTION__)); | |||
15404 | SDValue BP = LD->getOperand(1); | |||
15405 | SDValue Inc = LD->getOperand(2); | |||
15406 | ||||
15407 | // Some backends use TargetConstants for load offsets, but don't expect | |||
15408 | // TargetConstants in general ADD nodes. We can convert these constants into | |||
15409 | // regular Constants (if the constant is not opaque). | |||
15410 | assert((Inc.getOpcode() != ISD::TargetConstant ||(((Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode >(Inc)->isOpaque()) && "Cannot split out indexing using opaque target constants" ) ? static_cast<void> (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15412, __PRETTY_FUNCTION__)) | |||
15411 | !cast<ConstantSDNode>(Inc)->isOpaque()) &&(((Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode >(Inc)->isOpaque()) && "Cannot split out indexing using opaque target constants" ) ? static_cast<void> (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15412, __PRETTY_FUNCTION__)) | |||
15412 | "Cannot split out indexing using opaque target constants")(((Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode >(Inc)->isOpaque()) && "Cannot split out indexing using opaque target constants" ) ? static_cast<void> (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15412, __PRETTY_FUNCTION__)); | |||
15413 | if (Inc.getOpcode() == ISD::TargetConstant) { | |||
15414 | ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); | |||
15415 | Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), | |||
15416 | ConstInc->getValueType(0)); | |||
15417 | } | |||
15418 | ||||
15419 | unsigned Opc = | |||
15420 | (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); | |||
15421 | return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); | |||
15422 | } | |||
15423 | ||||
15424 | static inline ElementCount numVectorEltsOrZero(EVT T) { | |||
15425 | return T.isVector() ? T.getVectorElementCount() : ElementCount::getFixed(0); | |||
15426 | } | |||
15427 | ||||
15428 | bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) { | |||
15429 | Val = ST->getValue(); | |||
15430 | EVT STType = Val.getValueType(); | |||
15431 | EVT STMemType = ST->getMemoryVT(); | |||
15432 | if (STType == STMemType) | |||
15433 | return true; | |||
15434 | if (isTypeLegal(STMemType)) | |||
15435 | return false; // fail. | |||
15436 | if (STType.isFloatingPoint() && STMemType.isFloatingPoint() && | |||
15437 | TLI.isOperationLegal(ISD::FTRUNC, STMemType)) { | |||
15438 | Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val); | |||
15439 | return true; | |||
15440 | } | |||
15441 | if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) && | |||
15442 | STType.isInteger() && STMemType.isInteger()) { | |||
15443 | Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val); | |||
15444 | return true; | |||
15445 | } | |||
15446 | if (STType.getSizeInBits() == STMemType.getSizeInBits()) { | |||
15447 | Val = DAG.getBitcast(STMemType, Val); | |||
15448 | return true; | |||
15449 | } | |||
15450 | return false; // fail. | |||
15451 | } | |||
15452 | ||||
15453 | bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) { | |||
15454 | EVT LDMemType = LD->getMemoryVT(); | |||
15455 | EVT LDType = LD->getValueType(0); | |||
15456 | assert(Val.getValueType() == LDMemType &&((Val.getValueType() == LDMemType && "Attempting to extend value of non-matching type" ) ? static_cast<void> (0) : __assert_fail ("Val.getValueType() == LDMemType && \"Attempting to extend value of non-matching type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15457, __PRETTY_FUNCTION__)) | |||
15457 | "Attempting to extend value of non-matching type")((Val.getValueType() == LDMemType && "Attempting to extend value of non-matching type" ) ? static_cast<void> (0) : __assert_fail ("Val.getValueType() == LDMemType && \"Attempting to extend value of non-matching type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15457, __PRETTY_FUNCTION__)); | |||
15458 | if (LDType == LDMemType) | |||
15459 | return true; | |||
15460 | if (LDMemType.isInteger() && LDType.isInteger()) { | |||
15461 | switch (LD->getExtensionType()) { | |||
15462 | case ISD::NON_EXTLOAD: | |||
15463 | Val = DAG.getBitcast(LDType, Val); | |||
15464 | return true; | |||
15465 | case ISD::EXTLOAD: | |||
15466 | Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val); | |||
15467 | return true; | |||
15468 | case ISD::SEXTLOAD: | |||
15469 | Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val); | |||
15470 | return true; | |||
15471 | case ISD::ZEXTLOAD: | |||
15472 | Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val); | |||
15473 | return true; | |||
15474 | } | |||
15475 | } | |||
15476 | return false; | |||
15477 | } | |||
15478 | ||||
15479 | SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) { | |||
15480 | if (OptLevel == CodeGenOpt::None || !LD->isSimple()) | |||
15481 | return SDValue(); | |||
15482 | SDValue Chain = LD->getOperand(0); | |||
15483 | StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode()); | |||
15484 | // TODO: Relax this restriction for unordered atomics (see D66309) | |||
15485 | if (!ST || !ST->isSimple()) | |||
15486 | return SDValue(); | |||
15487 | ||||
15488 | EVT LDType = LD->getValueType(0); | |||
15489 | EVT LDMemType = LD->getMemoryVT(); | |||
15490 | EVT STMemType = ST->getMemoryVT(); | |||
15491 | EVT STType = ST->getValue().getValueType(); | |||
15492 | ||||
15493 | // There are two cases to consider here: | |||
15494 | // 1. The store is fixed width and the load is scalable. In this case we | |||
15495 | // don't know at compile time if the store completely envelops the load | |||
15496 | // so we abandon the optimisation. | |||
15497 | // 2. The store is scalable and the load is fixed width. We could | |||
15498 | // potentially support a limited number of cases here, but there has been | |||
15499 | // no cost-benefit analysis to prove it's worth it. | |||
15500 | bool LdStScalable = LDMemType.isScalableVector(); | |||
15501 | if (LdStScalable != STMemType.isScalableVector()) | |||
15502 | return SDValue(); | |||
15503 | ||||
15504 | // If we are dealing with scalable vectors on a big endian platform the | |||
15505 | // calculation of offsets below becomes trickier, since we do not know at | |||
15506 | // compile time the absolute size of the vector. Until we've done more | |||
15507 | // analysis on big-endian platforms it seems better to bail out for now. | |||
15508 | if (LdStScalable && DAG.getDataLayout().isBigEndian()) | |||
15509 | return SDValue(); | |||
15510 | ||||
15511 | BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG); | |||
15512 | BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG); | |||
15513 | int64_t Offset; | |||
15514 | if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset)) | |||
15515 | return SDValue(); | |||
15516 | ||||
15517 | // Normalize for Endianness. After this Offset=0 will denote that the least | |||
15518 | // significant bit in the loaded value maps to the least significant bit in | |||
15519 | // the stored value). With Offset=n (for n > 0) the loaded value starts at the | |||
15520 | // n:th least significant byte of the stored value. | |||
15521 | if (DAG.getDataLayout().isBigEndian()) | |||
15522 | Offset = ((int64_t)STMemType.getStoreSizeInBits().getFixedSize() - | |||
15523 | (int64_t)LDMemType.getStoreSizeInBits().getFixedSize()) / | |||
15524 | 8 - | |||
15525 | Offset; | |||
15526 | ||||
15527 | // Check that the stored value cover all bits that are loaded. | |||
15528 | bool STCoversLD; | |||
15529 | ||||
15530 | TypeSize LdMemSize = LDMemType.getSizeInBits(); | |||
15531 | TypeSize StMemSize = STMemType.getSizeInBits(); | |||
15532 | if (LdStScalable) | |||
15533 | STCoversLD = (Offset == 0) && LdMemSize == StMemSize; | |||
15534 | else | |||
15535 | STCoversLD = (Offset >= 0) && (Offset * 8 + LdMemSize.getFixedSize() <= | |||
15536 | StMemSize.getFixedSize()); | |||
15537 | ||||
15538 | auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue { | |||
15539 | if (LD->isIndexed()) { | |||
15540 | // Cannot handle opaque target constants and we must respect the user's | |||
15541 | // request not to split indexes from loads. | |||
15542 | if (!canSplitIdx(LD)) | |||
15543 | return SDValue(); | |||
15544 | SDValue Idx = SplitIndexingFromLoad(LD); | |||
15545 | SDValue Ops[] = {Val, Idx, Chain}; | |||
15546 | return CombineTo(LD, Ops, 3); | |||
15547 | } | |||
15548 | return CombineTo(LD, Val, Chain); | |||
15549 | }; | |||
15550 | ||||
15551 | if (!STCoversLD) | |||
15552 | return SDValue(); | |||
15553 | ||||
15554 | // Memory as copy space (potentially masked). | |||
15555 | if (Offset == 0 && LDType == STType && STMemType == LDMemType) { | |||
15556 | // Simple case: Direct non-truncating forwarding | |||
15557 | if (LDType.getSizeInBits() == LdMemSize) | |||
15558 | return ReplaceLd(LD, ST->getValue(), Chain); | |||
15559 | // Can we model the truncate and extension with an and mask? | |||
15560 | if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() && | |||
15561 | !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) { | |||
15562 | // Mask to size of LDMemType | |||
15563 | auto Mask = | |||
15564 | DAG.getConstant(APInt::getLowBitsSet(STType.getFixedSizeInBits(), | |||
15565 | StMemSize.getFixedSize()), | |||
15566 | SDLoc(ST), STType); | |||
15567 | auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask); | |||
15568 | return ReplaceLd(LD, Val, Chain); | |||
15569 | } | |||
15570 | } | |||
15571 | ||||
15572 | // TODO: Deal with nonzero offset. | |||
15573 | if (LD->getBasePtr().isUndef() || Offset != 0) | |||
15574 | return SDValue(); | |||
15575 | // Model necessary truncations / extenstions. | |||
15576 | SDValue Val; | |||
15577 | // Truncate Value To Stored Memory Size. | |||
15578 | do { | |||
15579 | if (!getTruncatedStoreValue(ST, Val)) | |||
15580 | continue; | |||
15581 | if (!isTypeLegal(LDMemType)) | |||
15582 | continue; | |||
15583 | if (STMemType != LDMemType) { | |||
15584 | // TODO: Support vectors? This requires extract_subvector/bitcast. | |||
15585 | if (!STMemType.isVector() && !LDMemType.isVector() && | |||
15586 | STMemType.isInteger() && LDMemType.isInteger()) | |||
15587 | Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val); | |||
15588 | else | |||
15589 | continue; | |||
15590 | } | |||
15591 | if (!extendLoadedValueToExtension(LD, Val)) | |||
15592 | continue; | |||
15593 | return ReplaceLd(LD, Val, Chain); | |||
15594 | } while (false); | |||
15595 | ||||
15596 | // On failure, cleanup dead nodes we may have created. | |||
15597 | if (Val->use_empty()) | |||
15598 | deleteAndRecombine(Val.getNode()); | |||
15599 | return SDValue(); | |||
15600 | } | |||
15601 | ||||
15602 | SDValue DAGCombiner::visitLOAD(SDNode *N) { | |||
15603 | LoadSDNode *LD = cast<LoadSDNode>(N); | |||
15604 | SDValue Chain = LD->getChain(); | |||
15605 | SDValue Ptr = LD->getBasePtr(); | |||
15606 | ||||
15607 | // If load is not volatile and there are no uses of the loaded value (and | |||
15608 | // the updated indexed value in case of indexed loads), change uses of the | |||
15609 | // chain value into uses of the chain input (i.e. delete the dead load). | |||
15610 | // TODO: Allow this for unordered atomics (see D66309) | |||
15611 | if (LD->isSimple()) { | |||
15612 | if (N->getValueType(1) == MVT::Other) { | |||
15613 | // Unindexed loads. | |||
15614 | if (!N->hasAnyUseOfValue(0)) { | |||
15615 | // It's not safe to use the two value CombineTo variant here. e.g. | |||
15616 | // v1, chain2 = load chain1, loc | |||
15617 | // v2, chain3 = load chain2, loc | |||
15618 | // v3 = add v2, c | |||
15619 | // Now we replace use of chain2 with chain1. This makes the second load | |||
15620 | // isomorphic to the one we are deleting, and thus makes this load live. | |||
15621 | LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump (&DAG); dbgs() << "\nWith chain: "; Chain.getNode() ->dump(&DAG); dbgs() << "\n"; } } while (false) | |||
15622 | dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump (&DAG); dbgs() << "\nWith chain: "; Chain.getNode() ->dump(&DAG); dbgs() << "\n"; } } while (false) | |||
15623 | dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump (&DAG); dbgs() << "\nWith chain: "; Chain.getNode() ->dump(&DAG); dbgs() << "\n"; } } while (false); | |||
15624 | WorklistRemover DeadNodes(*this); | |||
15625 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); | |||
15626 | AddUsersToWorklist(Chain.getNode()); | |||
15627 | if (N->use_empty()) | |||
15628 | deleteAndRecombine(N); | |||
15629 | ||||
15630 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
15631 | } | |||
15632 | } else { | |||
15633 | // Indexed loads. | |||
15634 | assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?")((N->getValueType(2) == MVT::Other && "Malformed indexed loads?" ) ? static_cast<void> (0) : __assert_fail ("N->getValueType(2) == MVT::Other && \"Malformed indexed loads?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15634, __PRETTY_FUNCTION__)); | |||
15635 | ||||
15636 | // If this load has an opaque TargetConstant offset, then we cannot split | |||
15637 | // the indexing into an add/sub directly (that TargetConstant may not be | |||
15638 | // valid for a different type of node, and we cannot convert an opaque | |||
15639 | // target constant into a regular constant). | |||
15640 | bool CanSplitIdx = canSplitIdx(LD); | |||
15641 | ||||
15642 | if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) { | |||
15643 | SDValue Undef = DAG.getUNDEF(N->getValueType(0)); | |||
15644 | SDValue Index; | |||
15645 | if (N->hasAnyUseOfValue(1) && CanSplitIdx) { | |||
15646 | Index = SplitIndexingFromLoad(LD); | |||
15647 | // Try to fold the base pointer arithmetic into subsequent loads and | |||
15648 | // stores. | |||
15649 | AddUsersToWorklist(N); | |||
15650 | } else | |||
15651 | Index = DAG.getUNDEF(N->getValueType(1)); | |||
15652 | LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump (&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump (&DAG); dbgs() << " and 2 other values\n"; } } while (false) | |||
15653 | dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump (&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump (&DAG); dbgs() << " and 2 other values\n"; } } while (false) | |||
15654 | dbgs() << " and 2 other values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump (&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump (&DAG); dbgs() << " and 2 other values\n"; } } while (false); | |||
15655 | WorklistRemover DeadNodes(*this); | |||
15656 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); | |||
15657 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); | |||
15658 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); | |||
15659 | deleteAndRecombine(N); | |||
15660 | return SDValue(N, 0); // Return N so it doesn't get rechecked! | |||
15661 | } | |||
15662 | } | |||
15663 | } | |||
15664 | ||||
15665 | // If this load is directly stored, replace the load value with the stored | |||
15666 | // value. | |||
15667 | if (auto V = ForwardStoreValueToDirectLoad(LD)) | |||
15668 | return V; | |||
15669 | ||||
15670 | // Try to infer better alignment information than the load already has. | |||
15671 | if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) { | |||
15672 | if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { | |||
15673 | if (*Alignment > LD->getAlign() && | |||
15674 | isAligned(*Alignment, LD->getSrcValueOffset())) { | |||
15675 | SDValue NewLoad = DAG.getExtLoad( | |||
15676 | LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, | |||
15677 | LD->getPointerInfo(), LD->getMemoryVT(), *Alignment, | |||
15678 | LD->getMemOperand()->getFlags(), LD->getAAInfo()); | |||
15679 | // NewLoad will always be N as we are only refining the alignment | |||
15680 | assert(NewLoad.getNode() == N)((NewLoad.getNode() == N) ? static_cast<void> (0) : __assert_fail ("NewLoad.getNode() == N", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15680, __PRETTY_FUNCTION__)); | |||
15681 | (void)NewLoad; | |||
15682 | } | |||
15683 | } | |||
15684 | } | |||
15685 | ||||
15686 | if (LD->isUnindexed()) { | |||
15687 | // Walk up chain skipping non-aliasing memory nodes. | |||
15688 | SDValue BetterChain = FindBetterChain(LD, Chain); | |||
15689 | ||||
15690 | // If there is a better chain. | |||
15691 | if (Chain != BetterChain) { | |||
15692 | SDValue ReplLoad; | |||
15693 | ||||
15694 | // Replace the chain to void dependency. | |||
15695 | if (LD->getExtensionType() == ISD::NON_EXTLOAD) { | |||
15696 | ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), | |||
15697 | BetterChain, Ptr, LD->getMemOperand()); | |||
15698 | } else { | |||
15699 | ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), | |||
15700 | LD->getValueType(0), | |||
15701 | BetterChain, Ptr, LD->getMemoryVT(), | |||
15702 | LD->getMemOperand()); | |||
15703 | } | |||
15704 | ||||
15705 | // Create token factor to keep old chain connected. | |||
15706 | SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), | |||
15707 | MVT::Other, Chain, ReplLoad.getValue(1)); | |||
15708 | ||||
15709 | // Replace uses with load result and token factor | |||
15710 | return CombineTo(N, ReplLoad.getValue(0), Token); | |||
15711 | } | |||
15712 | } | |||
15713 | ||||
15714 | // Try transforming N to an indexed load. | |||
15715 | if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) | |||
15716 | return SDValue(N, 0); | |||
15717 | ||||
15718 | // Try to slice up N to more direct loads if the slices are mapped to | |||
15719 | // different register banks or pairing can take place. | |||
15720 | if (SliceUpLoad(N)) | |||
15721 | return SDValue(N, 0); | |||
15722 | ||||
15723 | return SDValue(); | |||
15724 | } | |||
15725 | ||||
15726 | namespace { | |||
15727 | ||||
15728 | /// Helper structure used to slice a load in smaller loads. | |||
15729 | /// Basically a slice is obtained from the following sequence: | |||
15730 | /// Origin = load Ty1, Base | |||
15731 | /// Shift = srl Ty1 Origin, CstTy Amount | |||
15732 | /// Inst = trunc Shift to Ty2 | |||
15733 | /// | |||
15734 | /// Then, it will be rewritten into: | |||
15735 | /// Slice = load SliceTy, Base + SliceOffset | |||
15736 | /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 | |||
15737 | /// | |||
15738 | /// SliceTy is deduced from the number of bits that are actually used to | |||
15739 | /// build Inst. | |||
15740 | struct LoadedSlice { | |||
15741 | /// Helper structure used to compute the cost of a slice. | |||
15742 | struct Cost { | |||
15743 | /// Are we optimizing for code size. | |||
15744 | bool ForCodeSize = false; | |||
15745 | ||||
15746 | /// Various cost. | |||
15747 | unsigned Loads = 0; | |||
15748 | unsigned Truncates = 0; | |||
15749 | unsigned CrossRegisterBanksCopies = 0; | |||
15750 | unsigned ZExts = 0; | |||
15751 | unsigned Shift = 0; | |||
15752 | ||||
15753 | explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {} | |||
15754 | ||||
15755 | /// Get the cost of one isolated slice. | |||
15756 | Cost(const LoadedSlice &LS, bool ForCodeSize) | |||
15757 | : ForCodeSize(ForCodeSize), Loads(1) { | |||
15758 | EVT TruncType = LS.Inst->getValueType(0); | |||
15759 | EVT LoadedType = LS.getLoadedType(); | |||
15760 | if (TruncType != LoadedType && | |||
15761 | !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) | |||
15762 | ZExts = 1; | |||
15763 | } | |||
15764 | ||||
15765 | /// Account for slicing gain in the current cost. | |||
15766 | /// Slicing provide a few gains like removing a shift or a | |||
15767 | /// truncate. This method allows to grow the cost of the original | |||
15768 | /// load with the gain from this slice. | |||
15769 | void addSliceGain(const LoadedSlice &LS) { | |||
15770 | // Each slice saves a truncate. | |||
15771 | const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); | |||
15772 | if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), | |||
15773 | LS.Inst->getValueType(0))) | |||
15774 | ++Truncates; | |||
15775 | // If there is a shift amount, this slice gets rid of it. | |||
15776 | if (LS.Shift) | |||
15777 | ++Shift; | |||
15778 | // If this slice can merge a cross register bank copy, account for it. | |||
15779 | if (LS.canMergeExpensiveCrossRegisterBankCopy()) | |||
15780 | ++CrossRegisterBanksCopies; | |||
15781 | } | |||
15782 | ||||
15783 | Cost &operator+=(const Cost &RHS) { | |||
15784 | Loads += RHS.Loads; | |||
15785 | Truncates += RHS.Truncates; | |||
15786 | CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; | |||
15787 | ZExts += RHS.ZExts; | |||
15788 | Shift += RHS.Shift; | |||
15789 | return *this; | |||
15790 | } | |||
15791 | ||||
15792 | bool operator==(const Cost &RHS) const { | |||
15793 | return Loads == RHS.Loads && Truncates == RHS.Truncates && | |||
15794 | CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && | |||
15795 | ZExts == RHS.ZExts && Shift == RHS.Shift; | |||
15796 | } | |||
15797 | ||||
15798 | bool operator!=(const Cost &RHS) const { return !(*this == RHS); } | |||
15799 | ||||
15800 | bool operator<(const Cost &RHS) const { | |||
15801 | // Assume cross register banks copies are as expensive as loads. | |||
15802 | // FIXME: Do we want some more target hooks? | |||
15803 | unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; | |||
15804 | unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; | |||
15805 | // Unless we are optimizing for code size, consider the | |||
15806 | // expensive operation first. | |||
15807 | if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) | |||
15808 | return ExpensiveOpsLHS < ExpensiveOpsRHS; | |||
15809 | return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < | |||
15810 | (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); | |||
15811 | } | |||
15812 | ||||
15813 | bool operator>(const Cost &RHS) const { return RHS < *this; } | |||
15814 | ||||
15815 | bool operator<=(const Cost &RHS) const { return !(RHS < *this); } | |||
15816 | ||||
15817 | bool operator>=(const Cost &RHS) const { return !(*this < RHS); } | |||
15818 | }; | |||
15819 | ||||
15820 | // The last instruction that represent the slice. This should be a | |||
15821 | // truncate instruction. | |||
15822 | SDNode *Inst; | |||
15823 | ||||
15824 | // The original load instruction. | |||
15825 | LoadSDNode *Origin; | |||
15826 | ||||
15827 | // The right shift amount in bits from the original load. | |||
15828 | unsigned Shift; | |||
15829 | ||||
15830 | // The DAG from which Origin came from. | |||
15831 | // This is used to get some contextual information about legal types, etc. | |||
15832 | SelectionDAG *DAG; | |||
15833 | ||||
15834 | LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, | |||
15835 | unsigned Shift = 0, SelectionDAG *DAG = nullptr) | |||
15836 | : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} | |||
15837 | ||||
15838 | /// Get the bits used in a chunk of bits \p BitWidth large. | |||
15839 | /// \return Result is \p BitWidth and has used bits set to 1 and | |||
15840 | /// not used bits set to 0. | |||
15841 | APInt getUsedBits() const { | |||
15842 | // Reproduce the trunc(lshr) sequence: | |||
15843 | // - Start from the truncated value. | |||
15844 | // - Zero extend to the desired bit width. | |||
15845 | // - Shift left. | |||
15846 | assert(Origin && "No original load to compare against.")((Origin && "No original load to compare against.") ? static_cast<void> (0) : __assert_fail ("Origin && \"No original load to compare against.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15846, __PRETTY_FUNCTION__)); | |||
15847 | unsigned BitWidth = Origin->getValueSizeInBits(0); | |||
15848 | assert(Inst && "This slice is not bound to an instruction")((Inst && "This slice is not bound to an instruction" ) ? static_cast<void> (0) : __assert_fail ("Inst && \"This slice is not bound to an instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15848, __PRETTY_FUNCTION__)); | |||
15849 | assert(Inst->getValueSizeInBits(0) <= BitWidth &&((Inst->getValueSizeInBits(0) <= BitWidth && "Extracted slice is bigger than the whole type!" ) ? static_cast<void> (0) : __assert_fail ("Inst->getValueSizeInBits(0) <= BitWidth && \"Extracted slice is bigger than the whole type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15850, __PRETTY_FUNCTION__)) | |||
15850 | "Extracted slice is bigger than the whole type!")((Inst->getValueSizeInBits(0) <= BitWidth && "Extracted slice is bigger than the whole type!" ) ? static_cast<void> (0) : __assert_fail ("Inst->getValueSizeInBits(0) <= BitWidth && \"Extracted slice is bigger than the whole type!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15850, __PRETTY_FUNCTION__)); | |||
15851 | APInt UsedBits(Inst->getValueSizeInBits(0), 0); | |||
15852 | UsedBits.setAllBits(); | |||
15853 | UsedBits = UsedBits.zext(BitWidth); | |||
15854 | UsedBits <<= Shift; | |||
15855 | return UsedBits; | |||
15856 | } | |||
15857 | ||||
15858 | /// Get the size of the slice to be loaded in bytes. | |||
15859 | unsigned getLoadedSize() const { | |||
15860 | unsigned SliceSize = getUsedBits().countPopulation(); | |||
15861 | assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.")((!(SliceSize & 0x7) && "Size is not a multiple of a byte." ) ? static_cast<void> (0) : __assert_fail ("!(SliceSize & 0x7) && \"Size is not a multiple of a byte.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15861, __PRETTY_FUNCTION__)); | |||
15862 | return SliceSize / 8; | |||
15863 | } | |||
15864 | ||||
15865 | /// Get the type that will be loaded for this slice. | |||
15866 | /// Note: This may not be the final type for the slice. | |||
15867 | EVT getLoadedType() const { | |||
15868 | assert(DAG && "Missing context")((DAG && "Missing context") ? static_cast<void> (0) : __assert_fail ("DAG && \"Missing context\"", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15868, __PRETTY_FUNCTION__)); | |||
15869 | LLVMContext &Ctxt = *DAG->getContext(); | |||
15870 | return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); | |||
15871 | } | |||
15872 | ||||
15873 | /// Get the alignment of the load used for this slice. | |||
15874 | Align getAlign() const { | |||
15875 | Align Alignment = Origin->getAlign(); | |||
15876 | uint64_t Offset = getOffsetFromBase(); | |||
15877 | if (Offset != 0) | |||
15878 | Alignment = commonAlignment(Alignment, Alignment.value() + Offset); | |||
15879 | return Alignment; | |||
15880 | } | |||
15881 | ||||
15882 | /// Check if this slice can be rewritten with legal operations. | |||
15883 | bool isLegal() const { | |||
15884 | // An invalid slice is not legal. | |||
15885 | if (!Origin || !Inst || !DAG) | |||
15886 | return false; | |||
15887 | ||||
15888 | // Offsets are for indexed load only, we do not handle that. | |||
15889 | if (!Origin->getOffset().isUndef()) | |||
15890 | return false; | |||
15891 | ||||
15892 | const TargetLowering &TLI = DAG->getTargetLoweringInfo(); | |||
15893 | ||||
15894 | // Check that the type is legal. | |||
15895 | EVT SliceType = getLoadedType(); | |||
15896 | if (!TLI.isTypeLegal(SliceType)) | |||
15897 | return false; | |||
15898 | ||||
15899 | // Check that the load is legal for this type. | |||
15900 | if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) | |||
15901 | return false; | |||
15902 | ||||
15903 | // Check that the offset can be computed. | |||
15904 | // 1. Check its type. | |||
15905 | EVT PtrType = Origin->getBasePtr().getValueType(); | |||
15906 | if (PtrType == MVT::Untyped || PtrType.isExtended()) | |||
15907 | return false; | |||
15908 | ||||
15909 | // 2. Check that it fits in the immediate. | |||
15910 | if (!TLI.isLegalAddImmediate(getOffsetFromBase())) | |||
15911 | return false; | |||
15912 | ||||
15913 | // 3. Check that the computation is legal. | |||
15914 | if (!TLI.isOperationLegal(ISD::ADD, PtrType)) | |||
15915 | return false; | |||
15916 | ||||
15917 | // Check that the zext is legal if it needs one. | |||
15918 | EVT TruncateType = Inst->getValueType(0); | |||
15919 | if (TruncateType != SliceType && | |||
15920 | !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) | |||
15921 | return false; | |||
15922 | ||||
15923 | return true; | |||
15924 | } | |||
15925 | ||||
15926 | /// Get the offset in bytes of this slice in the original chunk of | |||
15927 | /// bits. | |||
15928 | /// \pre DAG != nullptr. | |||
15929 | uint64_t getOffsetFromBase() const { | |||
15930 | assert(DAG && "Missing context.")((DAG && "Missing context.") ? static_cast<void> (0) : __assert_fail ("DAG && \"Missing context.\"", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15930, __PRETTY_FUNCTION__)); | |||
15931 | bool IsBigEndian = DAG->getDataLayout().isBigEndian(); | |||
15932 | assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.")((!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported." ) ? static_cast<void> (0) : __assert_fail ("!(Shift & 0x7) && \"Shifts not aligned on Bytes are not supported.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15932, __PRETTY_FUNCTION__)); | |||
15933 | uint64_t Offset = Shift / 8; | |||
15934 | unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; | |||
15935 | assert(!(Origin->getValueSizeInBits(0) & 0x7) &&((!(Origin->getValueSizeInBits(0) & 0x7) && "The size of the original loaded type is not a multiple of a" " byte.") ? static_cast<void> (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15937, __PRETTY_FUNCTION__)) | |||
15936 | "The size of the original loaded type is not a multiple of a"((!(Origin->getValueSizeInBits(0) & 0x7) && "The size of the original loaded type is not a multiple of a" " byte.") ? static_cast<void> (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15937, __PRETTY_FUNCTION__)) | |||
15937 | " byte.")((!(Origin->getValueSizeInBits(0) & 0x7) && "The size of the original loaded type is not a multiple of a" " byte.") ? static_cast<void> (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15937, __PRETTY_FUNCTION__)); | |||
15938 | // If Offset is bigger than TySizeInBytes, it means we are loading all | |||
15939 | // zeros. This should have been optimized before in the process. | |||
15940 | assert(TySizeInBytes > Offset &&((TySizeInBytes > Offset && "Invalid shift amount for given loaded size" ) ? static_cast<void> (0) : __assert_fail ("TySizeInBytes > Offset && \"Invalid shift amount for given loaded size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15941, __PRETTY_FUNCTION__)) | |||
15941 | "Invalid shift amount for given loaded size")((TySizeInBytes > Offset && "Invalid shift amount for given loaded size" ) ? static_cast<void> (0) : __assert_fail ("TySizeInBytes > Offset && \"Invalid shift amount for given loaded size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15941, __PRETTY_FUNCTION__)); | |||
15942 | if (IsBigEndian) | |||
15943 | Offset = TySizeInBytes - Offset - getLoadedSize(); | |||
15944 | return Offset; | |||
15945 | } | |||
15946 | ||||
15947 | /// Generate the sequence of instructions to load the slice | |||
15948 | /// represented by this object and redirect the uses of this slice to | |||
15949 | /// this new sequence of instructions. | |||
15950 | /// \pre this->Inst && this->Origin are valid Instructions and this | |||
15951 | /// object passed the legal check: LoadedSlice::isLegal returned true. | |||
15952 | /// \return The last instruction of the sequence used to load the slice. | |||
15953 | SDValue loadSlice() const { | |||
15954 | assert(Inst && Origin && "Unable to replace a non-existing slice.")((Inst && Origin && "Unable to replace a non-existing slice." ) ? static_cast<void> (0) : __assert_fail ("Inst && Origin && \"Unable to replace a non-existing slice.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15954, __PRETTY_FUNCTION__)); | |||
15955 | const SDValue &OldBaseAddr = Origin->getBasePtr(); | |||
15956 | SDValue BaseAddr = OldBaseAddr; | |||
15957 | // Get the offset in that chunk of bytes w.r.t. the endianness. | |||
15958 | int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); | |||
15959 | assert(Offset >= 0 && "Offset too big to fit in int64_t!")((Offset >= 0 && "Offset too big to fit in int64_t!" ) ? static_cast<void> (0) : __assert_fail ("Offset >= 0 && \"Offset too big to fit in int64_t!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15959, __PRETTY_FUNCTION__)); | |||
15960 | if (Offset) { | |||
15961 | // BaseAddr = BaseAddr + Offset. | |||
15962 | EVT ArithType = BaseAddr.getValueType(); | |||
15963 | SDLoc DL(Origin); | |||
15964 | BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, | |||
15965 | DAG->getConstant(Offset, DL, ArithType)); | |||
15966 | } | |||
15967 | ||||
15968 | // Create the type of the loaded slice according to its size. | |||
15969 | EVT SliceType = getLoadedType(); | |||
15970 | ||||
15971 | // Create the load for the slice. | |||
15972 | SDValue LastInst = | |||
15973 | DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, | |||
15974 | Origin->getPointerInfo().getWithOffset(Offset), getAlign(), | |||
15975 | Origin->getMemOperand()->getFlags()); | |||
15976 | // If the final type is not the same as the loaded type, this means that | |||
15977 | // we have to pad with zero. Create a zero extend for that. | |||
15978 | EVT FinalType = Inst->getValueType(0); | |||
15979 | if (SliceType != FinalType) | |||
15980 | LastInst = | |||
15981 | DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); | |||
15982 | return LastInst; | |||
15983 | } | |||
15984 | ||||
15985 | /// Check if this slice can be merged with an expensive cross register | |||
15986 | /// bank copy. E.g., | |||
15987 | /// i = load i32 | |||
15988 | /// f = bitcast i32 i to float | |||
15989 | bool canMergeExpensiveCrossRegisterBankCopy() const { | |||
15990 | if (!Inst || !Inst->hasOneUse()) | |||
15991 | return false; | |||
15992 | SDNode *Use = *Inst->use_begin(); | |||
15993 | if (Use->getOpcode() != ISD::BITCAST) | |||
15994 | return false; | |||
15995 | assert(DAG && "Missing context")((DAG && "Missing context") ? static_cast<void> (0) : __assert_fail ("DAG && \"Missing context\"", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 15995, __PRETTY_FUNCTION__)); | |||
15996 | const TargetLowering &TLI = DAG->getTargetLoweringInfo(); | |||
15997 | EVT ResVT = Use->getValueType(0); | |||
15998 | const TargetRegisterClass *ResRC = | |||
15999 | TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent()); | |||
16000 | const TargetRegisterClass *ArgRC = | |||
16001 | TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(), | |||
16002 | Use->getOperand(0)->isDivergent()); | |||
16003 | if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) | |||
16004 | return false; | |||
16005 | ||||
16006 | // At this point, we know that we perform a cross-register-bank copy. | |||
16007 | // Check if it is expensive. | |||
16008 | const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); | |||
16009 | // Assume bitcasts are cheap, unless both register classes do not | |||
16010 | // explicitly share a common sub class. | |||
16011 | if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) | |||
16012 | return false; | |||
16013 | ||||
16014 | // Check if it will be merged with the load. | |||
16015 | // 1. Check the alignment constraint. | |||
16016 | Align RequiredAlignment = DAG->getDataLayout().getABITypeAlign( | |||
16017 | ResVT.getTypeForEVT(*DAG->getContext())); | |||
16018 | ||||
16019 | if (RequiredAlignment > getAlign()) | |||
16020 | return false; | |||
16021 | ||||
16022 | // 2. Check that the load is a legal operation for that type. | |||
16023 | if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) | |||
16024 | return false; | |||
16025 | ||||
16026 | // 3. Check that we do not have a zext in the way. | |||
16027 | if (Inst->getValueType(0) != getLoadedType()) | |||
16028 | return false; | |||
16029 | ||||
16030 | return true; | |||
16031 | } | |||
16032 | }; | |||
16033 | ||||
16034 | } // end anonymous namespace | |||
16035 | ||||
16036 | /// Check that all bits set in \p UsedBits form a dense region, i.e., | |||
16037 | /// \p UsedBits looks like 0..0 1..1 0..0. | |||
16038 | static bool areUsedBitsDense(const APInt &UsedBits) { | |||
16039 | // If all the bits are one, this is dense! | |||
16040 | if (UsedBits.isAllOnesValue()) | |||
16041 | return true; | |||
16042 | ||||
16043 | // Get rid of the unused bits on the right. | |||
16044 | APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); | |||
16045 | // Get rid of the unused bits on the left. | |||
16046 | if (NarrowedUsedBits.countLeadingZeros()) | |||
16047 | NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); | |||
16048 | // Check that the chunk of bits is completely used. | |||
16049 | return NarrowedUsedBits.isAllOnesValue(); | |||
16050 | } | |||
16051 | ||||
16052 | /// Check whether or not \p First and \p Second are next to each other | |||
16053 | /// in memory. This means that there is no hole between the bits loaded | |||
16054 | /// by \p First and the bits loaded by \p Second. | |||
16055 | static bool areSlicesNextToEachOther(const LoadedSlice &First, | |||
16056 | const LoadedSlice &Second) { | |||
16057 | assert(First.Origin == Second.Origin && First.Origin &&((First.Origin == Second.Origin && First.Origin && "Unable to match different memory origins.") ? static_cast< void> (0) : __assert_fail ("First.Origin == Second.Origin && First.Origin && \"Unable to match different memory origins.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16058, __PRETTY_FUNCTION__)) | |||
16058 | "Unable to match different memory origins.")((First.Origin == Second.Origin && First.Origin && "Unable to match different memory origins.") ? static_cast< void> (0) : __assert_fail ("First.Origin == Second.Origin && First.Origin && \"Unable to match different memory origins.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16058, __PRETTY_FUNCTION__)); | |||
16059 | APInt UsedBits = First.getUsedBits(); | |||
16060 | assert((UsedBits & Second.getUsedBits()) == 0 &&(((UsedBits & Second.getUsedBits()) == 0 && "Slices are not supposed to overlap." ) ? static_cast<void> (0) : __assert_fail ("(UsedBits & Second.getUsedBits()) == 0 && \"Slices are not supposed to overlap.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16061, __PRETTY_FUNCTION__)) | |||
16061 | "Slices are not supposed to overlap.")(((UsedBits & Second.getUsedBits()) == 0 && "Slices are not supposed to overlap." ) ? static_cast<void> (0) : __assert_fail ("(UsedBits & Second.getUsedBits()) == 0 && \"Slices are not supposed to overlap.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16061, __PRETTY_FUNCTION__)); | |||
16062 | UsedBits |= Second.getUsedBits(); | |||
16063 | return areUsedBitsDense(UsedBits); | |||
16064 | } | |||
16065 | ||||
16066 | /// Adjust the \p GlobalLSCost according to the target | |||
16067 | /// paring capabilities and the layout of the slices. | |||
16068 | /// \pre \p GlobalLSCost should account for at least as many loads as | |||
16069 | /// there is in the slices in \p LoadedSlices. | |||
16070 | static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, | |||
16071 | LoadedSlice::Cost &GlobalLSCost) { | |||
16072 | unsigned NumberOfSlices = LoadedSlices.size(); | |||
16073 | // If there is less than 2 elements, no pairing is possible. | |||
16074 | if (NumberOfSlices < 2) | |||
16075 | return; | |||
16076 | ||||
16077 | // Sort the slices so that elements that are likely to be next to each | |||
16078 | // other in memory are next to each other in the list. | |||
16079 | llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) { | |||
16080 | assert(LHS.Origin == RHS.Origin && "Different bases not implemented.")((LHS.Origin == RHS.Origin && "Different bases not implemented." ) ? static_cast<void> (0) : __assert_fail ("LHS.Origin == RHS.Origin && \"Different bases not implemented.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16080, __PRETTY_FUNCTION__)); | |||
16081 | return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); | |||
16082 | }); | |||
16083 | const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); | |||
16084 | // First (resp. Second) is the first (resp. Second) potentially candidate | |||
16085 | // to be placed in a paired load. | |||
16086 | const LoadedSlice *First = nullptr; | |||
16087 | const LoadedSlice *Second = nullptr; | |||
16088 | for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, | |||
16089 | // Set the beginning of the pair. | |||
16090 | First = Second) { | |||
16091 | Second = &LoadedSlices[CurrSlice]; | |||
16092 | ||||
16093 | // If First is NULL, it means we start a new pair. | |||
16094 | // Get to the next slice. | |||
16095 | if (!First) | |||
16096 | continue; | |||
16097 | ||||
16098 | EVT LoadedType = First->getLoadedType(); | |||
16099 | ||||
16100 | // If the types of the slices are different, we cannot pair them. | |||
16101 | if (LoadedType != Second->getLoadedType()) | |||
16102 | continue; | |||
16103 | ||||
16104 | // Check if the target supplies paired loads for this type. | |||
16105 | Align RequiredAlignment; | |||
16106 | if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { | |||
16107 | // move to the next pair, this type is hopeless. | |||
16108 | Second = nullptr; | |||
16109 | continue; | |||
16110 | } | |||
16111 | // Check if we meet the alignment requirement. | |||
16112 | if (First->getAlign() < RequiredAlignment) | |||
16113 | continue; | |||
16114 | ||||
16115 | // Check that both loads are next to each other in memory. | |||
16116 | if (!areSlicesNextToEachOther(*First, *Second)) | |||
16117 | continue; | |||
16118 | ||||
16119 | assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!")((GlobalLSCost.Loads > 0 && "We save more loads than we created!" ) ? static_cast<void> (0) : __assert_fail ("GlobalLSCost.Loads > 0 && \"We save more loads than we created!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16119, __PRETTY_FUNCTION__)); | |||
16120 | --GlobalLSCost.Loads; | |||
16121 | // Move to the next pair. | |||
16122 | Second = nullptr; | |||
16123 | } | |||
16124 | } | |||
16125 | ||||
16126 | /// Check the profitability of all involved LoadedSlice. | |||
16127 | /// Currently, it is considered profitable if there is exactly two | |||
16128 | /// involved slices (1) which are (2) next to each other in memory, and | |||
16129 | /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). | |||
16130 | /// | |||
16131 | /// Note: The order of the elements in \p LoadedSlices may be modified, but not | |||
16132 | /// the elements themselves. | |||
16133 | /// | |||
16134 | /// FIXME: When the cost model will be mature enough, we can relax | |||
16135 | /// constraints (1) and (2). | |||
16136 | static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, | |||
16137 | const APInt &UsedBits, bool ForCodeSize) { | |||
16138 | unsigned NumberOfSlices = LoadedSlices.size(); | |||
16139 | if (StressLoadSlicing) | |||
16140 | return NumberOfSlices > 1; | |||
16141 | ||||
16142 | // Check (1). | |||
16143 | if (NumberOfSlices != 2) | |||
16144 | return false; | |||
16145 | ||||
16146 | // Check (2). | |||
16147 | if (!areUsedBitsDense(UsedBits)) | |||
16148 | return false; | |||
16149 | ||||
16150 | // Check (3). | |||
16151 | LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); | |||
16152 | // The original code has one big load. | |||
16153 | OrigCost.Loads = 1; | |||
16154 | for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { | |||
16155 | const LoadedSlice &LS = LoadedSlices[CurrSlice]; | |||
16156 | // Accumulate the cost of all the slices. | |||
16157 | LoadedSlice::Cost SliceCost(LS, ForCodeSize); | |||
16158 | GlobalSlicingCost += SliceCost; | |||
16159 | ||||
16160 | // Account as cost in the original configuration the gain obtained | |||
16161 | // with the current slices. | |||
16162 | OrigCost.addSliceGain(LS); | |||
16163 | } | |||
16164 | ||||
16165 | // If the target supports paired load, adjust the cost accordingly. | |||
16166 | adjustCostForPairing(LoadedSlices, GlobalSlicingCost); | |||
16167 | return OrigCost > GlobalSlicingCost; | |||
16168 | } | |||
16169 | ||||
16170 | /// If the given load, \p LI, is used only by trunc or trunc(lshr) | |||
16171 | /// operations, split it in the various pieces being extracted. | |||
16172 | /// | |||
16173 | /// This sort of thing is introduced by SROA. | |||
16174 | /// This slicing takes care not to insert overlapping loads. | |||
16175 | /// \pre LI is a simple load (i.e., not an atomic or volatile load). | |||
16176 | bool DAGCombiner::SliceUpLoad(SDNode *N) { | |||
16177 | if (Level < AfterLegalizeDAG) | |||
16178 | return false; | |||
16179 | ||||
16180 | LoadSDNode *LD = cast<LoadSDNode>(N); | |||
16181 | if (!LD->isSimple() || !ISD::isNormalLoad(LD) || | |||
16182 | !LD->getValueType(0).isInteger()) | |||
16183 | return false; | |||
16184 | ||||
16185 | // The algorithm to split up a load of a scalable vector into individual | |||
16186 | // elements currently requires knowing the length of the loaded type, | |||
16187 | // so will need adjusting to work on scalable vectors. | |||
16188 | if (LD->getValueType(0).isScalableVector()) | |||
16189 | return false; | |||
16190 | ||||
16191 | // Keep track of already used bits to detect overlapping values. | |||
16192 | // In that case, we will just abort the transformation. | |||
16193 | APInt UsedBits(LD->getValueSizeInBits(0), 0); | |||
16194 | ||||
16195 | SmallVector<LoadedSlice, 4> LoadedSlices; | |||
16196 | ||||
16197 | // Check if this load is used as several smaller chunks of bits. | |||
16198 | // Basically, look for uses in trunc or trunc(lshr) and record a new chain | |||
16199 | // of computation for each trunc. | |||
16200 | for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); | |||
16201 | UI != UIEnd; ++UI) { | |||
16202 | // Skip the uses of the chain. | |||
16203 | if (UI.getUse().getResNo() != 0) | |||
16204 | continue; | |||
16205 | ||||
16206 | SDNode *User = *UI; | |||
16207 | unsigned Shift = 0; | |||
16208 | ||||
16209 | // Check if this is a trunc(lshr). | |||
16210 | if (User->getOpcode() == ISD::SRL && User->hasOneUse() && | |||
16211 | isa<ConstantSDNode>(User->getOperand(1))) { | |||
16212 | Shift = User->getConstantOperandVal(1); | |||
16213 | User = *User->use_begin(); | |||
16214 | } | |||
16215 | ||||
16216 | // At this point, User is a Truncate, iff we encountered, trunc or | |||
16217 | // trunc(lshr). | |||
16218 | if (User->getOpcode() != ISD::TRUNCATE) | |||
16219 | return false; | |||
16220 | ||||
16221 | // The width of the type must be a power of 2 and greater than 8-bits. | |||
16222 | // Otherwise the load cannot be represented in LLVM IR. | |||
16223 | // Moreover, if we shifted with a non-8-bits multiple, the slice | |||
16224 | // will be across several bytes. We do not support that. | |||
16225 | unsigned Width = User->getValueSizeInBits(0); | |||
16226 | if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) | |||
16227 | return false; | |||
16228 | ||||
16229 | // Build the slice for this chain of computations. | |||
16230 | LoadedSlice LS(User, LD, Shift, &DAG); | |||
16231 | APInt CurrentUsedBits = LS.getUsedBits(); | |||
16232 | ||||
16233 | // Check if this slice overlaps with another. | |||
16234 | if ((CurrentUsedBits & UsedBits) != 0) | |||
16235 | return false; | |||
16236 | // Update the bits used globally. | |||
16237 | UsedBits |= CurrentUsedBits; | |||
16238 | ||||
16239 | // Check if the new slice would be legal. | |||
16240 | if (!LS.isLegal()) | |||
16241 | return false; | |||
16242 | ||||
16243 | // Record the slice. | |||
16244 | LoadedSlices.push_back(LS); | |||
16245 | } | |||
16246 | ||||
16247 | // Abort slicing if it does not seem to be profitable. | |||
16248 | if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) | |||
16249 | return false; | |||
16250 | ||||
16251 | ++SlicedLoads; | |||
16252 | ||||
16253 | // Rewrite each chain to use an independent load. | |||
16254 | // By construction, each chain can be represented by a unique load. | |||
16255 | ||||
16256 | // Prepare the argument for the new token factor for all the slices. | |||
16257 | SmallVector<SDValue, 8> ArgChains; | |||
16258 | for (const LoadedSlice &LS : LoadedSlices) { | |||
16259 | SDValue SliceInst = LS.loadSlice(); | |||
16260 | CombineTo(LS.Inst, SliceInst, true); | |||
16261 | if (SliceInst.getOpcode() != ISD::LOAD) | |||
16262 | SliceInst = SliceInst.getOperand(0); | |||
16263 | assert(SliceInst->getOpcode() == ISD::LOAD &&((SliceInst->getOpcode() == ISD::LOAD && "It takes more than a zext to get to the loaded slice!!" ) ? static_cast<void> (0) : __assert_fail ("SliceInst->getOpcode() == ISD::LOAD && \"It takes more than a zext to get to the loaded slice!!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16264, __PRETTY_FUNCTION__)) | |||
16264 | "It takes more than a zext to get to the loaded slice!!")((SliceInst->getOpcode() == ISD::LOAD && "It takes more than a zext to get to the loaded slice!!" ) ? static_cast<void> (0) : __assert_fail ("SliceInst->getOpcode() == ISD::LOAD && \"It takes more than a zext to get to the loaded slice!!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16264, __PRETTY_FUNCTION__)); | |||
16265 | ArgChains.push_back(SliceInst.getValue(1)); | |||
16266 | } | |||
16267 | ||||
16268 | SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, | |||
16269 | ArgChains); | |||
16270 | DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); | |||
16271 | AddToWorklist(Chain.getNode()); | |||
16272 | return true; | |||
16273 | } | |||
16274 | ||||
16275 | /// Check to see if V is (and load (ptr), imm), where the load is having | |||
16276 | /// specific bytes cleared out. If so, return the byte size being masked out | |||
16277 | /// and the shift amount. | |||
16278 | static std::pair<unsigned, unsigned> | |||
16279 | CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { | |||
16280 | std::pair<unsigned, unsigned> Result(0, 0); | |||
16281 | ||||
16282 | // Check for the structure we're looking for. | |||
16283 | if (V->getOpcode() != ISD::AND || | |||
16284 | !isa<ConstantSDNode>(V->getOperand(1)) || | |||
16285 | !ISD::isNormalLoad(V->getOperand(0).getNode())) | |||
16286 | return Result; | |||
16287 | ||||
16288 | // Check the chain and pointer. | |||
16289 | LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); | |||
16290 | if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. | |||
16291 | ||||
16292 | // This only handles simple types. | |||
16293 | if (V.getValueType() != MVT::i16 && | |||
16294 | V.getValueType() != MVT::i32 && | |||
16295 | V.getValueType() != MVT::i64) | |||
16296 | return Result; | |||
16297 | ||||
16298 | // Check the constant mask. Invert it so that the bits being masked out are | |||
16299 | // 0 and the bits being kept are 1. Use getSExtValue so that leading bits | |||
16300 | // follow the sign bit for uniformity. | |||
16301 | uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); | |||
16302 | unsigned NotMaskLZ = countLeadingZeros(NotMask); | |||
16303 | if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. | |||
16304 | unsigned NotMaskTZ = countTrailingZeros(NotMask); | |||
16305 | if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. | |||
16306 | if (NotMaskLZ == 64) return Result; // All zero mask. | |||
16307 | ||||
16308 | // See if we have a continuous run of bits. If so, we have 0*1+0* | |||
16309 | if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) | |||
16310 | return Result; | |||
16311 | ||||
16312 | // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. | |||
16313 | if (V.getValueType() != MVT::i64 && NotMaskLZ) | |||
16314 | NotMaskLZ -= 64-V.getValueSizeInBits(); | |||
16315 | ||||
16316 | unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; | |||
16317 | switch (MaskedBytes) { | |||
16318 | case 1: | |||
16319 | case 2: | |||
16320 | case 4: break; | |||
16321 | default: return Result; // All one mask, or 5-byte mask. | |||
16322 | } | |||
16323 | ||||
16324 | // Verify that the first bit starts at a multiple of mask so that the access | |||
16325 | // is aligned the same as the access width. | |||
16326 | if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; | |||
16327 | ||||
16328 | // For narrowing to be valid, it must be the case that the load the | |||
16329 | // immediately preceding memory operation before the store. | |||
16330 | if (LD == Chain.getNode()) | |||
16331 | ; // ok. | |||
16332 | else if (Chain->getOpcode() == ISD::TokenFactor && | |||
16333 | SDValue(LD, 1).hasOneUse()) { | |||
16334 | // LD has only 1 chain use so they are no indirect dependencies. | |||
16335 | if (!LD->isOperandOf(Chain.getNode())) | |||
16336 | return Result; | |||
16337 | } else | |||
16338 | return Result; // Fail. | |||
16339 | ||||
16340 | Result.first = MaskedBytes; | |||
16341 | Result.second = NotMaskTZ/8; | |||
16342 | return Result; | |||
16343 | } | |||
16344 | ||||
16345 | /// Check to see if IVal is something that provides a value as specified by | |||
16346 | /// MaskInfo. If so, replace the specified store with a narrower store of | |||
16347 | /// truncated IVal. | |||
16348 | static SDValue | |||
16349 | ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, | |||
16350 | SDValue IVal, StoreSDNode *St, | |||
16351 | DAGCombiner *DC) { | |||
16352 | unsigned NumBytes = MaskInfo.first; | |||
16353 | unsigned ByteShift = MaskInfo.second; | |||
16354 | SelectionDAG &DAG = DC->getDAG(); | |||
16355 | ||||
16356 | // Check to see if IVal is all zeros in the part being masked in by the 'or' | |||
16357 | // that uses this. If not, this is not a replacement. | |||
16358 | APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), | |||
16359 | ByteShift*8, (ByteShift+NumBytes)*8); | |||
16360 | if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue(); | |||
16361 | ||||
16362 | // Check that it is legal on the target to do this. It is legal if the new | |||
16363 | // VT we're shrinking to (i8/i16/i32) is legal or we're still before type | |||
16364 | // legalization (and the target doesn't explicitly think this is a bad idea). | |||
16365 | MVT VT = MVT::getIntegerVT(NumBytes * 8); | |||
16366 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
16367 | if (!DC->isTypeLegal(VT)) | |||
16368 | return SDValue(); | |||
16369 | if (St->getMemOperand() && | |||
16370 | !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, | |||
16371 | *St->getMemOperand())) | |||
16372 | return SDValue(); | |||
16373 | ||||
16374 | // Okay, we can do this! Replace the 'St' store with a store of IVal that is | |||
16375 | // shifted by ByteShift and truncated down to NumBytes. | |||
16376 | if (ByteShift) { | |||
16377 | SDLoc DL(IVal); | |||
16378 | IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, | |||
16379 | DAG.getConstant(ByteShift*8, DL, | |||
16380 | DC->getShiftAmountTy(IVal.getValueType()))); | |||
16381 | } | |||
16382 | ||||
16383 | // Figure out the offset for the store and the alignment of the access. | |||
16384 | unsigned StOffset; | |||
16385 | if (DAG.getDataLayout().isLittleEndian()) | |||
16386 | StOffset = ByteShift; | |||
16387 | else | |||
16388 | StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; | |||
16389 | ||||
16390 | SDValue Ptr = St->getBasePtr(); | |||
16391 | if (StOffset) { | |||
16392 | SDLoc DL(IVal); | |||
16393 | Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(StOffset), DL); | |||
16394 | } | |||
16395 | ||||
16396 | // Truncate down to the new size. | |||
16397 | IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); | |||
16398 | ||||
16399 | ++OpsNarrowed; | |||
16400 | return DAG | |||
16401 | .getStore(St->getChain(), SDLoc(St), IVal, Ptr, | |||
16402 | St->getPointerInfo().getWithOffset(StOffset), | |||
16403 | St->getOriginalAlign()); | |||
16404 | } | |||
16405 | ||||
16406 | /// Look for sequence of load / op / store where op is one of 'or', 'xor', and | |||
16407 | /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try | |||
16408 | /// narrowing the load and store if it would end up being a win for performance | |||
16409 | /// or code size. | |||
16410 | SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { | |||
16411 | StoreSDNode *ST = cast<StoreSDNode>(N); | |||
16412 | if (!ST->isSimple()) | |||
16413 | return SDValue(); | |||
16414 | ||||
16415 | SDValue Chain = ST->getChain(); | |||
16416 | SDValue Value = ST->getValue(); | |||
16417 | SDValue Ptr = ST->getBasePtr(); | |||
16418 | EVT VT = Value.getValueType(); | |||
16419 | ||||
16420 | if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) | |||
16421 | return SDValue(); | |||
16422 | ||||
16423 | unsigned Opc = Value.getOpcode(); | |||
16424 | ||||
16425 | // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst | |||
16426 | // is a byte mask indicating a consecutive number of bytes, check to see if | |||
16427 | // Y is known to provide just those bytes. If so, we try to replace the | |||
16428 | // load + replace + store sequence with a single (narrower) store, which makes | |||
16429 | // the load dead. | |||
16430 | if (Opc == ISD::OR && EnableShrinkLoadReplaceStoreWithStore) { | |||
16431 | std::pair<unsigned, unsigned> MaskedLoad; | |||
16432 | MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); | |||
16433 | if (MaskedLoad.first) | |||
16434 | if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, | |||
16435 | Value.getOperand(1), ST,this)) | |||
16436 | return NewST; | |||
16437 | ||||
16438 | // Or is commutative, so try swapping X and Y. | |||
16439 | MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); | |||
16440 | if (MaskedLoad.first) | |||
16441 | if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, | |||
16442 | Value.getOperand(0), ST,this)) | |||
16443 | return NewST; | |||
16444 | } | |||
16445 | ||||
16446 | if (!EnableReduceLoadOpStoreWidth) | |||
16447 | return SDValue(); | |||
16448 | ||||
16449 | if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || | |||
16450 | Value.getOperand(1).getOpcode() != ISD::Constant) | |||
16451 | return SDValue(); | |||
16452 | ||||
16453 | SDValue N0 = Value.getOperand(0); | |||
16454 | if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && | |||
16455 | Chain == SDValue(N0.getNode(), 1)) { | |||
16456 | LoadSDNode *LD = cast<LoadSDNode>(N0); | |||
16457 | if (LD->getBasePtr() != Ptr || | |||
16458 | LD->getPointerInfo().getAddrSpace() != | |||
16459 | ST->getPointerInfo().getAddrSpace()) | |||
16460 | return SDValue(); | |||
16461 | ||||
16462 | // Find the type to narrow it the load / op / store to. | |||
16463 | SDValue N1 = Value.getOperand(1); | |||
16464 | unsigned BitWidth = N1.getValueSizeInBits(); | |||
16465 | APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); | |||
16466 | if (Opc == ISD::AND) | |||
16467 | Imm ^= APInt::getAllOnesValue(BitWidth); | |||
16468 | if (Imm == 0 || Imm.isAllOnesValue()) | |||
16469 | return SDValue(); | |||
16470 | unsigned ShAmt = Imm.countTrailingZeros(); | |||
16471 | unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; | |||
16472 | unsigned NewBW = NextPowerOf2(MSB - ShAmt); | |||
16473 | EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); | |||
16474 | // The narrowing should be profitable, the load/store operation should be | |||
16475 | // legal (or custom) and the store size should be equal to the NewVT width. | |||
16476 | while (NewBW < BitWidth && | |||
16477 | (NewVT.getStoreSizeInBits() != NewBW || | |||
16478 | !TLI.isOperationLegalOrCustom(Opc, NewVT) || | |||
16479 | !TLI.isNarrowingProfitable(VT, NewVT))) { | |||
16480 | NewBW = NextPowerOf2(NewBW); | |||
16481 | NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); | |||
16482 | } | |||
16483 | if (NewBW >= BitWidth) | |||
16484 | return SDValue(); | |||
16485 | ||||
16486 | // If the lsb changed does not start at the type bitwidth boundary, | |||
16487 | // start at the previous one. | |||
16488 | if (ShAmt % NewBW) | |||
16489 | ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; | |||
16490 | APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, | |||
16491 | std::min(BitWidth, ShAmt + NewBW)); | |||
16492 | if ((Imm & Mask) == Imm) { | |||
16493 | APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); | |||
16494 | if (Opc == ISD::AND) | |||
16495 | NewImm ^= APInt::getAllOnesValue(NewBW); | |||
16496 | uint64_t PtrOff = ShAmt / 8; | |||
16497 | // For big endian targets, we need to adjust the offset to the pointer to | |||
16498 | // load the correct bytes. | |||
16499 | if (DAG.getDataLayout().isBigEndian()) | |||
16500 | PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; | |||
16501 | ||||
16502 | Align NewAlign = commonAlignment(LD->getAlign(), PtrOff); | |||
16503 | Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); | |||
16504 | if (NewAlign < DAG.getDataLayout().getABITypeAlign(NewVTTy)) | |||
16505 | return SDValue(); | |||
16506 | ||||
16507 | SDValue NewPtr = | |||
16508 | DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(PtrOff), SDLoc(LD)); | |||
16509 | SDValue NewLD = | |||
16510 | DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, | |||
16511 | LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, | |||
16512 | LD->getMemOperand()->getFlags(), LD->getAAInfo()); | |||
16513 | SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, | |||
16514 | DAG.getConstant(NewImm, SDLoc(Value), | |||
16515 | NewVT)); | |||
16516 | SDValue NewST = | |||
16517 | DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, | |||
16518 | ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); | |||
16519 | ||||
16520 | AddToWorklist(NewPtr.getNode()); | |||
16521 | AddToWorklist(NewLD.getNode()); | |||
16522 | AddToWorklist(NewVal.getNode()); | |||
16523 | WorklistRemover DeadNodes(*this); | |||
16524 | DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); | |||
16525 | ++OpsNarrowed; | |||
16526 | return NewST; | |||
16527 | } | |||
16528 | } | |||
16529 | ||||
16530 | return SDValue(); | |||
16531 | } | |||
16532 | ||||
16533 | /// For a given floating point load / store pair, if the load value isn't used | |||
16534 | /// by any other operations, then consider transforming the pair to integer | |||
16535 | /// load / store operations if the target deems the transformation profitable. | |||
16536 | SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { | |||
16537 | StoreSDNode *ST = cast<StoreSDNode>(N); | |||
16538 | SDValue Value = ST->getValue(); | |||
16539 | if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && | |||
16540 | Value.hasOneUse()) { | |||
16541 | LoadSDNode *LD = cast<LoadSDNode>(Value); | |||
16542 | EVT VT = LD->getMemoryVT(); | |||
16543 | if (!VT.isFloatingPoint() || | |||
16544 | VT != ST->getMemoryVT() || | |||
16545 | LD->isNonTemporal() || | |||
16546 | ST->isNonTemporal() || | |||
16547 | LD->getPointerInfo().getAddrSpace() != 0 || | |||
16548 | ST->getPointerInfo().getAddrSpace() != 0) | |||
16549 | return SDValue(); | |||
16550 | ||||
16551 | TypeSize VTSize = VT.getSizeInBits(); | |||
16552 | ||||
16553 | // We don't know the size of scalable types at compile time so we cannot | |||
16554 | // create an integer of the equivalent size. | |||
16555 | if (VTSize.isScalable()) | |||
16556 | return SDValue(); | |||
16557 | ||||
16558 | EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VTSize.getFixedSize()); | |||
16559 | if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || | |||
16560 | !TLI.isOperationLegal(ISD::STORE, IntVT) || | |||
16561 | !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || | |||
16562 | !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) | |||
16563 | return SDValue(); | |||
16564 | ||||
16565 | Align LDAlign = LD->getAlign(); | |||
16566 | Align STAlign = ST->getAlign(); | |||
16567 | Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); | |||
16568 | Align ABIAlign = DAG.getDataLayout().getABITypeAlign(IntVTTy); | |||
16569 | if (LDAlign < ABIAlign || STAlign < ABIAlign) | |||
16570 | return SDValue(); | |||
16571 | ||||
16572 | SDValue NewLD = | |||
16573 | DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), | |||
16574 | LD->getPointerInfo(), LDAlign); | |||
16575 | ||||
16576 | SDValue NewST = | |||
16577 | DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(), | |||
16578 | ST->getPointerInfo(), STAlign); | |||
16579 | ||||
16580 | AddToWorklist(NewLD.getNode()); | |||
16581 | AddToWorklist(NewST.getNode()); | |||
16582 | WorklistRemover DeadNodes(*this); | |||
16583 | DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); | |||
16584 | ++LdStFP2Int; | |||
16585 | return NewST; | |||
16586 | } | |||
16587 | ||||
16588 | return SDValue(); | |||
16589 | } | |||
16590 | ||||
16591 | // This is a helper function for visitMUL to check the profitability | |||
16592 | // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). | |||
16593 | // MulNode is the original multiply, AddNode is (add x, c1), | |||
16594 | // and ConstNode is c2. | |||
16595 | // | |||
16596 | // If the (add x, c1) has multiple uses, we could increase | |||
16597 | // the number of adds if we make this transformation. | |||
16598 | // It would only be worth doing this if we can remove a | |||
16599 | // multiply in the process. Check for that here. | |||
16600 | // To illustrate: | |||
16601 | // (A + c1) * c3 | |||
16602 | // (A + c2) * c3 | |||
16603 | // We're checking for cases where we have common "c3 * A" expressions. | |||
16604 | bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, | |||
16605 | SDValue &AddNode, | |||
16606 | SDValue &ConstNode) { | |||
16607 | APInt Val; | |||
16608 | ||||
16609 | // If the add only has one use, this would be OK to do. | |||
16610 | if (AddNode.getNode()->hasOneUse()) | |||
16611 | return true; | |||
16612 | ||||
16613 | // Walk all the users of the constant with which we're multiplying. | |||
16614 | for (SDNode *Use : ConstNode->uses()) { | |||
16615 | if (Use == MulNode) // This use is the one we're on right now. Skip it. | |||
16616 | continue; | |||
16617 | ||||
16618 | if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. | |||
16619 | SDNode *OtherOp; | |||
16620 | SDNode *MulVar = AddNode.getOperand(0).getNode(); | |||
16621 | ||||
16622 | // OtherOp is what we're multiplying against the constant. | |||
16623 | if (Use->getOperand(0) == ConstNode) | |||
16624 | OtherOp = Use->getOperand(1).getNode(); | |||
16625 | else | |||
16626 | OtherOp = Use->getOperand(0).getNode(); | |||
16627 | ||||
16628 | // Check to see if multiply is with the same operand of our "add". | |||
16629 | // | |||
16630 | // ConstNode = CONST | |||
16631 | // Use = ConstNode * A <-- visiting Use. OtherOp is A. | |||
16632 | // ... | |||
16633 | // AddNode = (A + c1) <-- MulVar is A. | |||
16634 | // = AddNode * ConstNode <-- current visiting instruction. | |||
16635 | // | |||
16636 | // If we make this transformation, we will have a common | |||
16637 | // multiply (ConstNode * A) that we can save. | |||
16638 | if (OtherOp == MulVar) | |||
16639 | return true; | |||
16640 | ||||
16641 | // Now check to see if a future expansion will give us a common | |||
16642 | // multiply. | |||
16643 | // | |||
16644 | // ConstNode = CONST | |||
16645 | // AddNode = (A + c1) | |||
16646 | // ... = AddNode * ConstNode <-- current visiting instruction. | |||
16647 | // ... | |||
16648 | // OtherOp = (A + c2) | |||
16649 | // Use = OtherOp * ConstNode <-- visiting Use. | |||
16650 | // | |||
16651 | // If we make this transformation, we will have a common | |||
16652 | // multiply (CONST * A) after we also do the same transformation | |||
16653 | // to the "t2" instruction. | |||
16654 | if (OtherOp->getOpcode() == ISD::ADD && | |||
16655 | DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && | |||
16656 | OtherOp->getOperand(0).getNode() == MulVar) | |||
16657 | return true; | |||
16658 | } | |||
16659 | } | |||
16660 | ||||
16661 | // Didn't find a case where this would be profitable. | |||
16662 | return false; | |||
16663 | } | |||
16664 | ||||
16665 | SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
16666 | unsigned NumStores) { | |||
16667 | SmallVector<SDValue, 8> Chains; | |||
16668 | SmallPtrSet<const SDNode *, 8> Visited; | |||
16669 | SDLoc StoreDL(StoreNodes[0].MemNode); | |||
16670 | ||||
16671 | for (unsigned i = 0; i < NumStores; ++i) { | |||
16672 | Visited.insert(StoreNodes[i].MemNode); | |||
16673 | } | |||
16674 | ||||
16675 | // don't include nodes that are children or repeated nodes. | |||
16676 | for (unsigned i = 0; i < NumStores; ++i) { | |||
16677 | if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second) | |||
16678 | Chains.push_back(StoreNodes[i].MemNode->getChain()); | |||
16679 | } | |||
16680 | ||||
16681 | assert(Chains.size() > 0 && "Chain should have generated a chain")((Chains.size() > 0 && "Chain should have generated a chain" ) ? static_cast<void> (0) : __assert_fail ("Chains.size() > 0 && \"Chain should have generated a chain\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16681, __PRETTY_FUNCTION__)); | |||
16682 | return DAG.getTokenFactor(StoreDL, Chains); | |||
16683 | } | |||
16684 | ||||
16685 | bool DAGCombiner::mergeStoresOfConstantsOrVecElts( | |||
16686 | SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, | |||
16687 | bool IsConstantSrc, bool UseVector, bool UseTrunc) { | |||
16688 | // Make sure we have something to merge. | |||
16689 | if (NumStores < 2) | |||
16690 | return false; | |||
16691 | ||||
16692 | // The latest Node in the DAG. | |||
16693 | SDLoc DL(StoreNodes[0].MemNode); | |||
16694 | ||||
16695 | TypeSize ElementSizeBits = MemVT.getStoreSizeInBits(); | |||
16696 | unsigned SizeInBits = NumStores * ElementSizeBits; | |||
16697 | unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; | |||
16698 | ||||
16699 | EVT StoreTy; | |||
16700 | if (UseVector) { | |||
16701 | unsigned Elts = NumStores * NumMemElts; | |||
16702 | // Get the type for the merged vector store. | |||
16703 | StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); | |||
16704 | } else | |||
16705 | StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); | |||
16706 | ||||
16707 | SDValue StoredVal; | |||
16708 | if (UseVector) { | |||
16709 | if (IsConstantSrc) { | |||
16710 | SmallVector<SDValue, 8> BuildVector; | |||
16711 | for (unsigned I = 0; I != NumStores; ++I) { | |||
16712 | StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); | |||
16713 | SDValue Val = St->getValue(); | |||
16714 | // If constant is of the wrong type, convert it now. | |||
16715 | if (MemVT != Val.getValueType()) { | |||
16716 | Val = peekThroughBitcasts(Val); | |||
16717 | // Deal with constants of wrong size. | |||
16718 | if (ElementSizeBits != Val.getValueSizeInBits()) { | |||
16719 | EVT IntMemVT = | |||
16720 | EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); | |||
16721 | if (isa<ConstantFPSDNode>(Val)) { | |||
16722 | // Not clear how to truncate FP values. | |||
16723 | return false; | |||
16724 | } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) | |||
16725 | Val = DAG.getConstant(C->getAPIntValue() | |||
16726 | .zextOrTrunc(Val.getValueSizeInBits()) | |||
16727 | .zextOrTrunc(ElementSizeBits), | |||
16728 | SDLoc(C), IntMemVT); | |||
16729 | } | |||
16730 | // Make sure correctly size type is the correct type. | |||
16731 | Val = DAG.getBitcast(MemVT, Val); | |||
16732 | } | |||
16733 | BuildVector.push_back(Val); | |||
16734 | } | |||
16735 | StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS | |||
16736 | : ISD::BUILD_VECTOR, | |||
16737 | DL, StoreTy, BuildVector); | |||
16738 | } else { | |||
16739 | SmallVector<SDValue, 8> Ops; | |||
16740 | for (unsigned i = 0; i < NumStores; ++i) { | |||
16741 | StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); | |||
16742 | SDValue Val = peekThroughBitcasts(St->getValue()); | |||
16743 | // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of | |||
16744 | // type MemVT. If the underlying value is not the correct | |||
16745 | // type, but it is an extraction of an appropriate vector we | |||
16746 | // can recast Val to be of the correct type. This may require | |||
16747 | // converting between EXTRACT_VECTOR_ELT and | |||
16748 | // EXTRACT_SUBVECTOR. | |||
16749 | if ((MemVT != Val.getValueType()) && | |||
16750 | (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || | |||
16751 | Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { | |||
16752 | EVT MemVTScalarTy = MemVT.getScalarType(); | |||
16753 | // We may need to add a bitcast here to get types to line up. | |||
16754 | if (MemVTScalarTy != Val.getValueType().getScalarType()) { | |||
16755 | Val = DAG.getBitcast(MemVT, Val); | |||
16756 | } else { | |||
16757 | unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR | |||
16758 | : ISD::EXTRACT_VECTOR_ELT; | |||
16759 | SDValue Vec = Val.getOperand(0); | |||
16760 | SDValue Idx = Val.getOperand(1); | |||
16761 | Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); | |||
16762 | } | |||
16763 | } | |||
16764 | Ops.push_back(Val); | |||
16765 | } | |||
16766 | ||||
16767 | // Build the extracted vector elements back into a vector. | |||
16768 | StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS | |||
16769 | : ISD::BUILD_VECTOR, | |||
16770 | DL, StoreTy, Ops); | |||
16771 | } | |||
16772 | } else { | |||
16773 | // We should always use a vector store when merging extracted vector | |||
16774 | // elements, so this path implies a store of constants. | |||
16775 | assert(IsConstantSrc && "Merged vector elements should use vector store")((IsConstantSrc && "Merged vector elements should use vector store" ) ? static_cast<void> (0) : __assert_fail ("IsConstantSrc && \"Merged vector elements should use vector store\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16775, __PRETTY_FUNCTION__)); | |||
16776 | ||||
16777 | APInt StoreInt(SizeInBits, 0); | |||
16778 | ||||
16779 | // Construct a single integer constant which is made of the smaller | |||
16780 | // constant inputs. | |||
16781 | bool IsLE = DAG.getDataLayout().isLittleEndian(); | |||
16782 | for (unsigned i = 0; i < NumStores; ++i) { | |||
16783 | unsigned Idx = IsLE ? (NumStores - 1 - i) : i; | |||
16784 | StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); | |||
16785 | ||||
16786 | SDValue Val = St->getValue(); | |||
16787 | Val = peekThroughBitcasts(Val); | |||
16788 | StoreInt <<= ElementSizeBits; | |||
16789 | if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { | |||
16790 | StoreInt |= C->getAPIntValue() | |||
16791 | .zextOrTrunc(ElementSizeBits) | |||
16792 | .zextOrTrunc(SizeInBits); | |||
16793 | } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { | |||
16794 | StoreInt |= C->getValueAPF() | |||
16795 | .bitcastToAPInt() | |||
16796 | .zextOrTrunc(ElementSizeBits) | |||
16797 | .zextOrTrunc(SizeInBits); | |||
16798 | // If fp truncation is necessary give up for now. | |||
16799 | if (MemVT.getSizeInBits() != ElementSizeBits) | |||
16800 | return false; | |||
16801 | } else { | |||
16802 | llvm_unreachable("Invalid constant element type")::llvm::llvm_unreachable_internal("Invalid constant element type" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16802); | |||
16803 | } | |||
16804 | } | |||
16805 | ||||
16806 | // Create the new Load and Store operations. | |||
16807 | StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); | |||
16808 | } | |||
16809 | ||||
16810 | LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; | |||
16811 | SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); | |||
16812 | ||||
16813 | // make sure we use trunc store if it's necessary to be legal. | |||
16814 | SDValue NewStore; | |||
16815 | if (!UseTrunc) { | |||
16816 | NewStore = | |||
16817 | DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), | |||
16818 | FirstInChain->getPointerInfo(), FirstInChain->getAlign()); | |||
16819 | } else { // Must be realized as a trunc store | |||
16820 | EVT LegalizedStoredValTy = | |||
16821 | TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); | |||
16822 | unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); | |||
16823 | ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); | |||
16824 | SDValue ExtendedStoreVal = | |||
16825 | DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, | |||
16826 | LegalizedStoredValTy); | |||
16827 | NewStore = DAG.getTruncStore( | |||
16828 | NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), | |||
16829 | FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, | |||
16830 | FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags()); | |||
16831 | } | |||
16832 | ||||
16833 | // Replace all merged stores with the new store. | |||
16834 | for (unsigned i = 0; i < NumStores; ++i) | |||
16835 | CombineTo(StoreNodes[i].MemNode, NewStore); | |||
16836 | ||||
16837 | AddToWorklist(NewChain.getNode()); | |||
16838 | return true; | |||
16839 | } | |||
16840 | ||||
16841 | void DAGCombiner::getStoreMergeCandidates( | |||
16842 | StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, | |||
16843 | SDNode *&RootNode) { | |||
16844 | // This holds the base pointer, index, and the offset in bytes from the base | |||
16845 | // pointer. We must have a base and an offset. Do not handle stores to undef | |||
16846 | // base pointers. | |||
16847 | BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); | |||
16848 | if (!BasePtr.getBase().getNode() || BasePtr.getBase().isUndef()) | |||
16849 | return; | |||
16850 | ||||
16851 | SDValue Val = peekThroughBitcasts(St->getValue()); | |||
16852 | StoreSource StoreSrc = getStoreSource(Val); | |||
16853 | assert(StoreSrc != StoreSource::Unknown && "Expected known source for store")((StoreSrc != StoreSource::Unknown && "Expected known source for store" ) ? static_cast<void> (0) : __assert_fail ("StoreSrc != StoreSource::Unknown && \"Expected known source for store\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16853, __PRETTY_FUNCTION__)); | |||
16854 | ||||
16855 | // Match on loadbaseptr if relevant. | |||
16856 | EVT MemVT = St->getMemoryVT(); | |||
16857 | BaseIndexOffset LBasePtr; | |||
16858 | EVT LoadVT; | |||
16859 | if (StoreSrc == StoreSource::Load) { | |||
16860 | auto *Ld = cast<LoadSDNode>(Val); | |||
16861 | LBasePtr = BaseIndexOffset::match(Ld, DAG); | |||
16862 | LoadVT = Ld->getMemoryVT(); | |||
16863 | // Load and store should be the same type. | |||
16864 | if (MemVT != LoadVT) | |||
16865 | return; | |||
16866 | // Loads must only have one use. | |||
16867 | if (!Ld->hasNUsesOfValue(1, 0)) | |||
16868 | return; | |||
16869 | // The memory operands must not be volatile/indexed/atomic. | |||
16870 | // TODO: May be able to relax for unordered atomics (see D66309) | |||
16871 | if (!Ld->isSimple() || Ld->isIndexed()) | |||
16872 | return; | |||
16873 | } | |||
16874 | auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, | |||
16875 | int64_t &Offset) -> bool { | |||
16876 | // The memory operands must not be volatile/indexed/atomic. | |||
16877 | // TODO: May be able to relax for unordered atomics (see D66309) | |||
16878 | if (!Other->isSimple() || Other->isIndexed()) | |||
16879 | return false; | |||
16880 | // Don't mix temporal stores with non-temporal stores. | |||
16881 | if (St->isNonTemporal() != Other->isNonTemporal()) | |||
16882 | return false; | |||
16883 | SDValue OtherBC = peekThroughBitcasts(Other->getValue()); | |||
16884 | // Allow merging constants of different types as integers. | |||
16885 | bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) | |||
16886 | : Other->getMemoryVT() != MemVT; | |||
16887 | switch (StoreSrc) { | |||
16888 | case StoreSource::Load: { | |||
16889 | if (NoTypeMatch) | |||
16890 | return false; | |||
16891 | // The Load's Base Ptr must also match. | |||
16892 | auto *OtherLd = dyn_cast<LoadSDNode>(OtherBC); | |||
16893 | if (!OtherLd) | |||
16894 | return false; | |||
16895 | BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG); | |||
16896 | if (LoadVT != OtherLd->getMemoryVT()) | |||
16897 | return false; | |||
16898 | // Loads must only have one use. | |||
16899 | if (!OtherLd->hasNUsesOfValue(1, 0)) | |||
16900 | return false; | |||
16901 | // The memory operands must not be volatile/indexed/atomic. | |||
16902 | // TODO: May be able to relax for unordered atomics (see D66309) | |||
16903 | if (!OtherLd->isSimple() || OtherLd->isIndexed()) | |||
16904 | return false; | |||
16905 | // Don't mix temporal loads with non-temporal loads. | |||
16906 | if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal()) | |||
16907 | return false; | |||
16908 | if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) | |||
16909 | return false; | |||
16910 | break; | |||
16911 | } | |||
16912 | case StoreSource::Constant: | |||
16913 | if (NoTypeMatch) | |||
16914 | return false; | |||
16915 | if (!isIntOrFPConstant(OtherBC)) | |||
16916 | return false; | |||
16917 | break; | |||
16918 | case StoreSource::Extract: | |||
16919 | // Do not merge truncated stores here. | |||
16920 | if (Other->isTruncatingStore()) | |||
16921 | return false; | |||
16922 | if (!MemVT.bitsEq(OtherBC.getValueType())) | |||
16923 | return false; | |||
16924 | if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT && | |||
16925 | OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR) | |||
16926 | return false; | |||
16927 | break; | |||
16928 | default: | |||
16929 | llvm_unreachable("Unhandled store source for merging")::llvm::llvm_unreachable_internal("Unhandled store source for merging" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 16929); | |||
16930 | } | |||
16931 | Ptr = BaseIndexOffset::match(Other, DAG); | |||
16932 | return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); | |||
16933 | }; | |||
16934 | ||||
16935 | // Check if the pair of StoreNode and the RootNode already bail out many | |||
16936 | // times which is over the limit in dependence check. | |||
16937 | auto OverLimitInDependenceCheck = [&](SDNode *StoreNode, | |||
16938 | SDNode *RootNode) -> bool { | |||
16939 | auto RootCount = StoreRootCountMap.find(StoreNode); | |||
16940 | return RootCount != StoreRootCountMap.end() && | |||
16941 | RootCount->second.first == RootNode && | |||
16942 | RootCount->second.second > StoreMergeDependenceLimit; | |||
16943 | }; | |||
16944 | ||||
16945 | auto TryToAddCandidate = [&](SDNode::use_iterator UseIter) { | |||
16946 | // This must be a chain use. | |||
16947 | if (UseIter.getOperandNo() != 0) | |||
16948 | return; | |||
16949 | if (auto *OtherStore = dyn_cast<StoreSDNode>(*UseIter)) { | |||
16950 | BaseIndexOffset Ptr; | |||
16951 | int64_t PtrDiff; | |||
16952 | if (CandidateMatch(OtherStore, Ptr, PtrDiff) && | |||
16953 | !OverLimitInDependenceCheck(OtherStore, RootNode)) | |||
16954 | StoreNodes.push_back(MemOpLink(OtherStore, PtrDiff)); | |||
16955 | } | |||
16956 | }; | |||
16957 | ||||
16958 | // We looking for a root node which is an ancestor to all mergable | |||
16959 | // stores. We search up through a load, to our root and then down | |||
16960 | // through all children. For instance we will find Store{1,2,3} if | |||
16961 | // St is Store1, Store2. or Store3 where the root is not a load | |||
16962 | // which always true for nonvolatile ops. TODO: Expand | |||
16963 | // the search to find all valid candidates through multiple layers of loads. | |||
16964 | // | |||
16965 | // Root | |||
16966 | // |-------|-------| | |||
16967 | // Load Load Store3 | |||
16968 | // | | | |||
16969 | // Store1 Store2 | |||
16970 | // | |||
16971 | // FIXME: We should be able to climb and | |||
16972 | // descend TokenFactors to find candidates as well. | |||
16973 | ||||
16974 | RootNode = St->getChain().getNode(); | |||
16975 | ||||
16976 | unsigned NumNodesExplored = 0; | |||
16977 | const unsigned MaxSearchNodes = 1024; | |||
16978 | if (auto *Ldn = dyn_cast<LoadSDNode>(RootNode)) { | |||
16979 | RootNode = Ldn->getChain().getNode(); | |||
16980 | for (auto I = RootNode->use_begin(), E = RootNode->use_end(); | |||
16981 | I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) { | |||
16982 | if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) { // walk down chain | |||
16983 | for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) | |||
16984 | TryToAddCandidate(I2); | |||
16985 | } | |||
16986 | } | |||
16987 | } else { | |||
16988 | for (auto I = RootNode->use_begin(), E = RootNode->use_end(); | |||
16989 | I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) | |||
16990 | TryToAddCandidate(I); | |||
16991 | } | |||
16992 | } | |||
16993 | ||||
16994 | // We need to check that merging these stores does not cause a loop in | |||
16995 | // the DAG. Any store candidate may depend on another candidate | |||
16996 | // indirectly through its operand (we already consider dependencies | |||
16997 | // through the chain). Check in parallel by searching up from | |||
16998 | // non-chain operands of candidates. | |||
16999 | bool DAGCombiner::checkMergeStoreCandidatesForDependencies( | |||
17000 | SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, | |||
17001 | SDNode *RootNode) { | |||
17002 | // FIXME: We should be able to truncate a full search of | |||
17003 | // predecessors by doing a BFS and keeping tabs the originating | |||
17004 | // stores from which worklist nodes come from in a similar way to | |||
17005 | // TokenFactor simplfication. | |||
17006 | ||||
17007 | SmallPtrSet<const SDNode *, 32> Visited; | |||
17008 | SmallVector<const SDNode *, 8> Worklist; | |||
17009 | ||||
17010 | // RootNode is a predecessor to all candidates so we need not search | |||
17011 | // past it. Add RootNode (peeking through TokenFactors). Do not count | |||
17012 | // these towards size check. | |||
17013 | ||||
17014 | Worklist.push_back(RootNode); | |||
17015 | while (!Worklist.empty()) { | |||
17016 | auto N = Worklist.pop_back_val(); | |||
17017 | if (!Visited.insert(N).second) | |||
17018 | continue; // Already present in Visited. | |||
17019 | if (N->getOpcode() == ISD::TokenFactor) { | |||
17020 | for (SDValue Op : N->ops()) | |||
17021 | Worklist.push_back(Op.getNode()); | |||
17022 | } | |||
17023 | } | |||
17024 | ||||
17025 | // Don't count pruning nodes towards max. | |||
17026 | unsigned int Max = 1024 + Visited.size(); | |||
17027 | // Search Ops of store candidates. | |||
17028 | for (unsigned i = 0; i < NumStores; ++i) { | |||
17029 | SDNode *N = StoreNodes[i].MemNode; | |||
17030 | // Of the 4 Store Operands: | |||
17031 | // * Chain (Op 0) -> We have already considered these | |||
17032 | // in candidate selection and can be | |||
17033 | // safely ignored | |||
17034 | // * Value (Op 1) -> Cycles may happen (e.g. through load chains) | |||
17035 | // * Address (Op 2) -> Merged addresses may only vary by a fixed constant, | |||
17036 | // but aren't necessarily fromt the same base node, so | |||
17037 | // cycles possible (e.g. via indexed store). | |||
17038 | // * (Op 3) -> Represents the pre or post-indexing offset (or undef for | |||
17039 | // non-indexed stores). Not constant on all targets (e.g. ARM) | |||
17040 | // and so can participate in a cycle. | |||
17041 | for (unsigned j = 1; j < N->getNumOperands(); ++j) | |||
17042 | Worklist.push_back(N->getOperand(j).getNode()); | |||
17043 | } | |||
17044 | // Search through DAG. We can stop early if we find a store node. | |||
17045 | for (unsigned i = 0; i < NumStores; ++i) | |||
17046 | if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, | |||
17047 | Max)) { | |||
17048 | // If the searching bail out, record the StoreNode and RootNode in the | |||
17049 | // StoreRootCountMap. If we have seen the pair many times over a limit, | |||
17050 | // we won't add the StoreNode into StoreNodes set again. | |||
17051 | if (Visited.size() >= Max) { | |||
17052 | auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode]; | |||
17053 | if (RootCount.first == RootNode) | |||
17054 | RootCount.second++; | |||
17055 | else | |||
17056 | RootCount = {RootNode, 1}; | |||
17057 | } | |||
17058 | return false; | |||
17059 | } | |||
17060 | return true; | |||
17061 | } | |||
17062 | ||||
17063 | unsigned | |||
17064 | DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
17065 | int64_t ElementSizeBytes) const { | |||
17066 | while (true) { | |||
17067 | // Find a store past the width of the first store. | |||
17068 | size_t StartIdx = 0; | |||
17069 | while ((StartIdx + 1 < StoreNodes.size()) && | |||
17070 | StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != | |||
17071 | StoreNodes[StartIdx + 1].OffsetFromBase) | |||
17072 | ++StartIdx; | |||
17073 | ||||
17074 | // Bail if we don't have enough candidates to merge. | |||
17075 | if (StartIdx + 1 >= StoreNodes.size()) | |||
17076 | return 0; | |||
17077 | ||||
17078 | // Trim stores that overlapped with the first store. | |||
17079 | if (StartIdx) | |||
17080 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); | |||
17081 | ||||
17082 | // Scan the memory operations on the chain and find the first | |||
17083 | // non-consecutive store memory address. | |||
17084 | unsigned NumConsecutiveStores = 1; | |||
17085 | int64_t StartAddress = StoreNodes[0].OffsetFromBase; | |||
17086 | // Check that the addresses are consecutive starting from the second | |||
17087 | // element in the list of stores. | |||
17088 | for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { | |||
17089 | int64_t CurrAddress = StoreNodes[i].OffsetFromBase; | |||
17090 | if (CurrAddress - StartAddress != (ElementSizeBytes * i)) | |||
17091 | break; | |||
17092 | NumConsecutiveStores = i + 1; | |||
17093 | } | |||
17094 | if (NumConsecutiveStores > 1) | |||
17095 | return NumConsecutiveStores; | |||
17096 | ||||
17097 | // There are no consecutive stores at the start of the list. | |||
17098 | // Remove the first store and try again. | |||
17099 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); | |||
17100 | } | |||
17101 | } | |||
17102 | ||||
17103 | bool DAGCombiner::tryStoreMergeOfConstants( | |||
17104 | SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, | |||
17105 | EVT MemVT, SDNode *RootNode, bool AllowVectors) { | |||
17106 | LLVMContext &Context = *DAG.getContext(); | |||
17107 | const DataLayout &DL = DAG.getDataLayout(); | |||
17108 | int64_t ElementSizeBytes = MemVT.getStoreSize(); | |||
17109 | unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; | |||
17110 | bool MadeChange = false; | |||
17111 | ||||
17112 | // Store the constants into memory as one consecutive store. | |||
17113 | while (NumConsecutiveStores >= 2) { | |||
17114 | LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; | |||
17115 | unsigned FirstStoreAS = FirstInChain->getAddressSpace(); | |||
17116 | unsigned FirstStoreAlign = FirstInChain->getAlignment(); | |||
17117 | unsigned LastLegalType = 1; | |||
17118 | unsigned LastLegalVectorType = 1; | |||
17119 | bool LastIntegerTrunc = false; | |||
17120 | bool NonZero = false; | |||
17121 | unsigned FirstZeroAfterNonZero = NumConsecutiveStores; | |||
17122 | for (unsigned i = 0; i < NumConsecutiveStores; ++i) { | |||
17123 | StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); | |||
17124 | SDValue StoredVal = ST->getValue(); | |||
17125 | bool IsElementZero = false; | |||
17126 | if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) | |||
17127 | IsElementZero = C->isNullValue(); | |||
17128 | else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) | |||
17129 | IsElementZero = C->getConstantFPValue()->isNullValue(); | |||
17130 | if (IsElementZero) { | |||
17131 | if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) | |||
17132 | FirstZeroAfterNonZero = i; | |||
17133 | } | |||
17134 | NonZero |= !IsElementZero; | |||
17135 | ||||
17136 | // Find a legal type for the constant store. | |||
17137 | unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; | |||
17138 | EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); | |||
17139 | bool IsFast = false; | |||
17140 | ||||
17141 | // Break early when size is too large to be legal. | |||
17142 | if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) | |||
17143 | break; | |||
17144 | ||||
17145 | if (TLI.isTypeLegal(StoreTy) && | |||
17146 | TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && | |||
17147 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17148 | *FirstInChain->getMemOperand(), &IsFast) && | |||
17149 | IsFast) { | |||
17150 | LastIntegerTrunc = false; | |||
17151 | LastLegalType = i + 1; | |||
17152 | // Or check whether a truncstore is legal. | |||
17153 | } else if (TLI.getTypeAction(Context, StoreTy) == | |||
17154 | TargetLowering::TypePromoteInteger) { | |||
17155 | EVT LegalizedStoredValTy = | |||
17156 | TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); | |||
17157 | if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && | |||
17158 | TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && | |||
17159 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17160 | *FirstInChain->getMemOperand(), &IsFast) && | |||
17161 | IsFast) { | |||
17162 | LastIntegerTrunc = true; | |||
17163 | LastLegalType = i + 1; | |||
17164 | } | |||
17165 | } | |||
17166 | ||||
17167 | // We only use vectors if the constant is known to be zero or the | |||
17168 | // target allows it and the function is not marked with the | |||
17169 | // noimplicitfloat attribute. | |||
17170 | if ((!NonZero || | |||
17171 | TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && | |||
17172 | AllowVectors) { | |||
17173 | // Find a legal type for the vector store. | |||
17174 | unsigned Elts = (i + 1) * NumMemElts; | |||
17175 | EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); | |||
17176 | if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && | |||
17177 | TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && | |||
17178 | TLI.allowsMemoryAccess(Context, DL, Ty, | |||
17179 | *FirstInChain->getMemOperand(), &IsFast) && | |||
17180 | IsFast) | |||
17181 | LastLegalVectorType = i + 1; | |||
17182 | } | |||
17183 | } | |||
17184 | ||||
17185 | bool UseVector = (LastLegalVectorType > LastLegalType) && AllowVectors; | |||
17186 | unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; | |||
17187 | ||||
17188 | // Check if we found a legal integer type that creates a meaningful | |||
17189 | // merge. | |||
17190 | if (NumElem < 2) { | |||
17191 | // We know that candidate stores are in order and of correct | |||
17192 | // shape. While there is no mergeable sequence from the | |||
17193 | // beginning one may start later in the sequence. The only | |||
17194 | // reason a merge of size N could have failed where another of | |||
17195 | // the same size would not have, is if the alignment has | |||
17196 | // improved or we've dropped a non-zero value. Drop as many | |||
17197 | // candidates as we can here. | |||
17198 | unsigned NumSkip = 1; | |||
17199 | while ((NumSkip < NumConsecutiveStores) && | |||
17200 | (NumSkip < FirstZeroAfterNonZero) && | |||
17201 | (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) | |||
17202 | NumSkip++; | |||
17203 | ||||
17204 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); | |||
17205 | NumConsecutiveStores -= NumSkip; | |||
17206 | continue; | |||
17207 | } | |||
17208 | ||||
17209 | // Check that we can merge these candidates without causing a cycle. | |||
17210 | if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, | |||
17211 | RootNode)) { | |||
17212 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); | |||
17213 | NumConsecutiveStores -= NumElem; | |||
17214 | continue; | |||
17215 | } | |||
17216 | ||||
17217 | MadeChange |= mergeStoresOfConstantsOrVecElts( | |||
17218 | StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); | |||
17219 | ||||
17220 | // Remove merged stores for next iteration. | |||
17221 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); | |||
17222 | NumConsecutiveStores -= NumElem; | |||
17223 | } | |||
17224 | return MadeChange; | |||
17225 | } | |||
17226 | ||||
17227 | bool DAGCombiner::tryStoreMergeOfExtracts( | |||
17228 | SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, | |||
17229 | EVT MemVT, SDNode *RootNode) { | |||
17230 | LLVMContext &Context = *DAG.getContext(); | |||
17231 | const DataLayout &DL = DAG.getDataLayout(); | |||
17232 | unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; | |||
17233 | bool MadeChange = false; | |||
17234 | ||||
17235 | // Loop on Consecutive Stores on success. | |||
17236 | while (NumConsecutiveStores >= 2) { | |||
17237 | LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; | |||
17238 | unsigned FirstStoreAS = FirstInChain->getAddressSpace(); | |||
17239 | unsigned FirstStoreAlign = FirstInChain->getAlignment(); | |||
17240 | unsigned NumStoresToMerge = 1; | |||
17241 | for (unsigned i = 0; i < NumConsecutiveStores; ++i) { | |||
17242 | // Find a legal type for the vector store. | |||
17243 | unsigned Elts = (i + 1) * NumMemElts; | |||
17244 | EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); | |||
17245 | bool IsFast = false; | |||
17246 | ||||
17247 | // Break early when size is too large to be legal. | |||
17248 | if (Ty.getSizeInBits() > MaximumLegalStoreInBits) | |||
17249 | break; | |||
17250 | ||||
17251 | if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && | |||
17252 | TLI.allowsMemoryAccess(Context, DL, Ty, | |||
17253 | *FirstInChain->getMemOperand(), &IsFast) && | |||
17254 | IsFast) | |||
17255 | NumStoresToMerge = i + 1; | |||
17256 | } | |||
17257 | ||||
17258 | // Check if we found a legal integer type creating a meaningful | |||
17259 | // merge. | |||
17260 | if (NumStoresToMerge < 2) { | |||
17261 | // We know that candidate stores are in order and of correct | |||
17262 | // shape. While there is no mergeable sequence from the | |||
17263 | // beginning one may start later in the sequence. The only | |||
17264 | // reason a merge of size N could have failed where another of | |||
17265 | // the same size would not have, is if the alignment has | |||
17266 | // improved. Drop as many candidates as we can here. | |||
17267 | unsigned NumSkip = 1; | |||
17268 | while ((NumSkip < NumConsecutiveStores) && | |||
17269 | (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) | |||
17270 | NumSkip++; | |||
17271 | ||||
17272 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); | |||
17273 | NumConsecutiveStores -= NumSkip; | |||
17274 | continue; | |||
17275 | } | |||
17276 | ||||
17277 | // Check that we can merge these candidates without causing a cycle. | |||
17278 | if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumStoresToMerge, | |||
17279 | RootNode)) { | |||
17280 | StoreNodes.erase(StoreNodes.begin(), | |||
17281 | StoreNodes.begin() + NumStoresToMerge); | |||
17282 | NumConsecutiveStores -= NumStoresToMerge; | |||
17283 | continue; | |||
17284 | } | |||
17285 | ||||
17286 | MadeChange |= mergeStoresOfConstantsOrVecElts( | |||
17287 | StoreNodes, MemVT, NumStoresToMerge, false, true, false); | |||
17288 | ||||
17289 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumStoresToMerge); | |||
17290 | NumConsecutiveStores -= NumStoresToMerge; | |||
17291 | } | |||
17292 | return MadeChange; | |||
17293 | } | |||
17294 | ||||
17295 | bool DAGCombiner::tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, | |||
17296 | unsigned NumConsecutiveStores, EVT MemVT, | |||
17297 | SDNode *RootNode, bool AllowVectors, | |||
17298 | bool IsNonTemporalStore, | |||
17299 | bool IsNonTemporalLoad) { | |||
17300 | LLVMContext &Context = *DAG.getContext(); | |||
17301 | const DataLayout &DL = DAG.getDataLayout(); | |||
17302 | int64_t ElementSizeBytes = MemVT.getStoreSize(); | |||
17303 | unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; | |||
17304 | bool MadeChange = false; | |||
17305 | ||||
17306 | // Look for load nodes which are used by the stored values. | |||
17307 | SmallVector<MemOpLink, 8> LoadNodes; | |||
17308 | ||||
17309 | // Find acceptable loads. Loads need to have the same chain (token factor), | |||
17310 | // must not be zext, volatile, indexed, and they must be consecutive. | |||
17311 | BaseIndexOffset LdBasePtr; | |||
17312 | ||||
17313 | for (unsigned i = 0; i < NumConsecutiveStores; ++i) { | |||
17314 | StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); | |||
17315 | SDValue Val = peekThroughBitcasts(St->getValue()); | |||
17316 | LoadSDNode *Ld = cast<LoadSDNode>(Val); | |||
17317 | ||||
17318 | BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); | |||
17319 | // If this is not the first ptr that we check. | |||
17320 | int64_t LdOffset = 0; | |||
17321 | if (LdBasePtr.getBase().getNode()) { | |||
17322 | // The base ptr must be the same. | |||
17323 | if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) | |||
17324 | break; | |||
17325 | } else { | |||
17326 | // Check that all other base pointers are the same as this one. | |||
17327 | LdBasePtr = LdPtr; | |||
17328 | } | |||
17329 | ||||
17330 | // We found a potential memory operand to merge. | |||
17331 | LoadNodes.push_back(MemOpLink(Ld, LdOffset)); | |||
17332 | } | |||
17333 | ||||
17334 | while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { | |||
17335 | Align RequiredAlignment; | |||
17336 | bool NeedRotate = false; | |||
17337 | if (LoadNodes.size() == 2) { | |||
17338 | // If we have load/store pair instructions and we only have two values, | |||
17339 | // don't bother merging. | |||
17340 | if (TLI.hasPairedLoad(MemVT, RequiredAlignment) && | |||
17341 | StoreNodes[0].MemNode->getAlign() >= RequiredAlignment) { | |||
17342 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); | |||
17343 | LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); | |||
17344 | break; | |||
17345 | } | |||
17346 | // If the loads are reversed, see if we can rotate the halves into place. | |||
17347 | int64_t Offset0 = LoadNodes[0].OffsetFromBase; | |||
17348 | int64_t Offset1 = LoadNodes[1].OffsetFromBase; | |||
17349 | EVT PairVT = EVT::getIntegerVT(Context, ElementSizeBytes * 8 * 2); | |||
17350 | if (Offset0 - Offset1 == ElementSizeBytes && | |||
17351 | (hasOperation(ISD::ROTL, PairVT) || | |||
17352 | hasOperation(ISD::ROTR, PairVT))) { | |||
17353 | std::swap(LoadNodes[0], LoadNodes[1]); | |||
17354 | NeedRotate = true; | |||
17355 | } | |||
17356 | } | |||
17357 | LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; | |||
17358 | unsigned FirstStoreAS = FirstInChain->getAddressSpace(); | |||
17359 | Align FirstStoreAlign = FirstInChain->getAlign(); | |||
17360 | LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); | |||
17361 | ||||
17362 | // Scan the memory operations on the chain and find the first | |||
17363 | // non-consecutive load memory address. These variables hold the index in | |||
17364 | // the store node array. | |||
17365 | ||||
17366 | unsigned LastConsecutiveLoad = 1; | |||
17367 | ||||
17368 | // This variable refers to the size and not index in the array. | |||
17369 | unsigned LastLegalVectorType = 1; | |||
17370 | unsigned LastLegalIntegerType = 1; | |||
17371 | bool isDereferenceable = true; | |||
17372 | bool DoIntegerTruncate = false; | |||
17373 | int64_t StartAddress = LoadNodes[0].OffsetFromBase; | |||
17374 | SDValue LoadChain = FirstLoad->getChain(); | |||
17375 | for (unsigned i = 1; i < LoadNodes.size(); ++i) { | |||
17376 | // All loads must share the same chain. | |||
17377 | if (LoadNodes[i].MemNode->getChain() != LoadChain) | |||
17378 | break; | |||
17379 | ||||
17380 | int64_t CurrAddress = LoadNodes[i].OffsetFromBase; | |||
17381 | if (CurrAddress - StartAddress != (ElementSizeBytes * i)) | |||
17382 | break; | |||
17383 | LastConsecutiveLoad = i; | |||
17384 | ||||
17385 | if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) | |||
17386 | isDereferenceable = false; | |||
17387 | ||||
17388 | // Find a legal type for the vector store. | |||
17389 | unsigned Elts = (i + 1) * NumMemElts; | |||
17390 | EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); | |||
17391 | ||||
17392 | // Break early when size is too large to be legal. | |||
17393 | if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) | |||
17394 | break; | |||
17395 | ||||
17396 | bool IsFastSt = false; | |||
17397 | bool IsFastLd = false; | |||
17398 | if (TLI.isTypeLegal(StoreTy) && | |||
17399 | TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && | |||
17400 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17401 | *FirstInChain->getMemOperand(), &IsFastSt) && | |||
17402 | IsFastSt && | |||
17403 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17404 | *FirstLoad->getMemOperand(), &IsFastLd) && | |||
17405 | IsFastLd) { | |||
17406 | LastLegalVectorType = i + 1; | |||
17407 | } | |||
17408 | ||||
17409 | // Find a legal type for the integer store. | |||
17410 | unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; | |||
17411 | StoreTy = EVT::getIntegerVT(Context, SizeInBits); | |||
17412 | if (TLI.isTypeLegal(StoreTy) && | |||
17413 | TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && | |||
17414 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17415 | *FirstInChain->getMemOperand(), &IsFastSt) && | |||
17416 | IsFastSt && | |||
17417 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17418 | *FirstLoad->getMemOperand(), &IsFastLd) && | |||
17419 | IsFastLd) { | |||
17420 | LastLegalIntegerType = i + 1; | |||
17421 | DoIntegerTruncate = false; | |||
17422 | // Or check whether a truncstore and extload is legal. | |||
17423 | } else if (TLI.getTypeAction(Context, StoreTy) == | |||
17424 | TargetLowering::TypePromoteInteger) { | |||
17425 | EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); | |||
17426 | if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && | |||
17427 | TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && | |||
17428 | TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, StoreTy) && | |||
17429 | TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, StoreTy) && | |||
17430 | TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && | |||
17431 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17432 | *FirstInChain->getMemOperand(), &IsFastSt) && | |||
17433 | IsFastSt && | |||
17434 | TLI.allowsMemoryAccess(Context, DL, StoreTy, | |||
17435 | *FirstLoad->getMemOperand(), &IsFastLd) && | |||
17436 | IsFastLd) { | |||
17437 | LastLegalIntegerType = i + 1; | |||
17438 | DoIntegerTruncate = true; | |||
17439 | } | |||
17440 | } | |||
17441 | } | |||
17442 | ||||
17443 | // Only use vector types if the vector type is larger than the integer | |||
17444 | // type. If they are the same, use integers. | |||
17445 | bool UseVectorTy = | |||
17446 | LastLegalVectorType > LastLegalIntegerType && AllowVectors; | |||
17447 | unsigned LastLegalType = | |||
17448 | std::max(LastLegalVectorType, LastLegalIntegerType); | |||
17449 | ||||
17450 | // We add +1 here because the LastXXX variables refer to location while | |||
17451 | // the NumElem refers to array/index size. | |||
17452 | unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); | |||
17453 | NumElem = std::min(LastLegalType, NumElem); | |||
17454 | Align FirstLoadAlign = FirstLoad->getAlign(); | |||
17455 | ||||
17456 | if (NumElem < 2) { | |||
17457 | // We know that candidate stores are in order and of correct | |||
17458 | // shape. While there is no mergeable sequence from the | |||
17459 | // beginning one may start later in the sequence. The only | |||
17460 | // reason a merge of size N could have failed where another of | |||
17461 | // the same size would not have is if the alignment or either | |||
17462 | // the load or store has improved. Drop as many candidates as we | |||
17463 | // can here. | |||
17464 | unsigned NumSkip = 1; | |||
17465 | while ((NumSkip < LoadNodes.size()) && | |||
17466 | (LoadNodes[NumSkip].MemNode->getAlign() <= FirstLoadAlign) && | |||
17467 | (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign)) | |||
17468 | NumSkip++; | |||
17469 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); | |||
17470 | LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); | |||
17471 | NumConsecutiveStores -= NumSkip; | |||
17472 | continue; | |||
17473 | } | |||
17474 | ||||
17475 | // Check that we can merge these candidates without causing a cycle. | |||
17476 | if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, | |||
17477 | RootNode)) { | |||
17478 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); | |||
17479 | LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); | |||
17480 | NumConsecutiveStores -= NumElem; | |||
17481 | continue; | |||
17482 | } | |||
17483 | ||||
17484 | // Find if it is better to use vectors or integers to load and store | |||
17485 | // to memory. | |||
17486 | EVT JointMemOpVT; | |||
17487 | if (UseVectorTy) { | |||
17488 | // Find a legal type for the vector store. | |||
17489 | unsigned Elts = NumElem * NumMemElts; | |||
17490 | JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); | |||
17491 | } else { | |||
17492 | unsigned SizeInBits = NumElem * ElementSizeBytes * 8; | |||
17493 | JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); | |||
17494 | } | |||
17495 | ||||
17496 | SDLoc LoadDL(LoadNodes[0].MemNode); | |||
17497 | SDLoc StoreDL(StoreNodes[0].MemNode); | |||
17498 | ||||
17499 | // The merged loads are required to have the same incoming chain, so | |||
17500 | // using the first's chain is acceptable. | |||
17501 | ||||
17502 | SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); | |||
17503 | AddToWorklist(NewStoreChain.getNode()); | |||
17504 | ||||
17505 | MachineMemOperand::Flags LdMMOFlags = | |||
17506 | isDereferenceable ? MachineMemOperand::MODereferenceable | |||
17507 | : MachineMemOperand::MONone; | |||
17508 | if (IsNonTemporalLoad) | |||
17509 | LdMMOFlags |= MachineMemOperand::MONonTemporal; | |||
17510 | ||||
17511 | MachineMemOperand::Flags StMMOFlags = IsNonTemporalStore | |||
17512 | ? MachineMemOperand::MONonTemporal | |||
17513 | : MachineMemOperand::MONone; | |||
17514 | ||||
17515 | SDValue NewLoad, NewStore; | |||
17516 | if (UseVectorTy || !DoIntegerTruncate) { | |||
17517 | NewLoad = DAG.getLoad( | |||
17518 | JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), | |||
17519 | FirstLoad->getPointerInfo(), FirstLoadAlign, LdMMOFlags); | |||
17520 | SDValue StoreOp = NewLoad; | |||
17521 | if (NeedRotate) { | |||
17522 | unsigned LoadWidth = ElementSizeBytes * 8 * 2; | |||
17523 | assert(JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) &&((JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && "Unexpected type for rotate-able load pair") ? static_cast< void> (0) : __assert_fail ("JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && \"Unexpected type for rotate-able load pair\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17524, __PRETTY_FUNCTION__)) | |||
17524 | "Unexpected type for rotate-able load pair")((JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && "Unexpected type for rotate-able load pair") ? static_cast< void> (0) : __assert_fail ("JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && \"Unexpected type for rotate-able load pair\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17524, __PRETTY_FUNCTION__)); | |||
17525 | SDValue RotAmt = | |||
17526 | DAG.getShiftAmountConstant(LoadWidth / 2, JointMemOpVT, LoadDL); | |||
17527 | // Target can convert to the identical ROTR if it does not have ROTL. | |||
17528 | StoreOp = DAG.getNode(ISD::ROTL, LoadDL, JointMemOpVT, NewLoad, RotAmt); | |||
17529 | } | |||
17530 | NewStore = DAG.getStore( | |||
17531 | NewStoreChain, StoreDL, StoreOp, FirstInChain->getBasePtr(), | |||
17532 | FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags); | |||
17533 | } else { // This must be the truncstore/extload case | |||
17534 | EVT ExtendedTy = | |||
17535 | TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); | |||
17536 | NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, | |||
17537 | FirstLoad->getChain(), FirstLoad->getBasePtr(), | |||
17538 | FirstLoad->getPointerInfo(), JointMemOpVT, | |||
17539 | FirstLoadAlign, LdMMOFlags); | |||
17540 | NewStore = DAG.getTruncStore( | |||
17541 | NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), | |||
17542 | FirstInChain->getPointerInfo(), JointMemOpVT, | |||
17543 | FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags()); | |||
17544 | } | |||
17545 | ||||
17546 | // Transfer chain users from old loads to the new load. | |||
17547 | for (unsigned i = 0; i < NumElem; ++i) { | |||
17548 | LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); | |||
17549 | DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), | |||
17550 | SDValue(NewLoad.getNode(), 1)); | |||
17551 | } | |||
17552 | ||||
17553 | // Replace all stores with the new store. Recursively remove corresponding | |||
17554 | // values if they are no longer used. | |||
17555 | for (unsigned i = 0; i < NumElem; ++i) { | |||
17556 | SDValue Val = StoreNodes[i].MemNode->getOperand(1); | |||
17557 | CombineTo(StoreNodes[i].MemNode, NewStore); | |||
17558 | if (Val.getNode()->use_empty()) | |||
17559 | recursivelyDeleteUnusedNodes(Val.getNode()); | |||
17560 | } | |||
17561 | ||||
17562 | MadeChange = true; | |||
17563 | StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); | |||
17564 | LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); | |||
17565 | NumConsecutiveStores -= NumElem; | |||
17566 | } | |||
17567 | return MadeChange; | |||
17568 | } | |||
17569 | ||||
17570 | bool DAGCombiner::mergeConsecutiveStores(StoreSDNode *St) { | |||
17571 | if (OptLevel == CodeGenOpt::None || !EnableStoreMerging) | |||
17572 | return false; | |||
17573 | ||||
17574 | // TODO: Extend this function to merge stores of scalable vectors. | |||
17575 | // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8> | |||
17576 | // store since we know <vscale x 16 x i8> is exactly twice as large as | |||
17577 | // <vscale x 8 x i8>). Until then, bail out for scalable vectors. | |||
17578 | EVT MemVT = St->getMemoryVT(); | |||
17579 | if (MemVT.isScalableVector()) | |||
17580 | return false; | |||
17581 | if (!MemVT.isSimple() || MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) | |||
17582 | return false; | |||
17583 | ||||
17584 | // This function cannot currently deal with non-byte-sized memory sizes. | |||
17585 | int64_t ElementSizeBytes = MemVT.getStoreSize(); | |||
17586 | if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits()) | |||
17587 | return false; | |||
17588 | ||||
17589 | // Do not bother looking at stored values that are not constants, loads, or | |||
17590 | // extracted vector elements. | |||
17591 | SDValue StoredVal = peekThroughBitcasts(St->getValue()); | |||
17592 | const StoreSource StoreSrc = getStoreSource(StoredVal); | |||
17593 | if (StoreSrc == StoreSource::Unknown) | |||
17594 | return false; | |||
17595 | ||||
17596 | SmallVector<MemOpLink, 8> StoreNodes; | |||
17597 | SDNode *RootNode; | |||
17598 | // Find potential store merge candidates by searching through chain sub-DAG | |||
17599 | getStoreMergeCandidates(St, StoreNodes, RootNode); | |||
17600 | ||||
17601 | // Check if there is anything to merge. | |||
17602 | if (StoreNodes.size() < 2) | |||
17603 | return false; | |||
17604 | ||||
17605 | // Sort the memory operands according to their distance from the | |||
17606 | // base pointer. | |||
17607 | llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) { | |||
17608 | return LHS.OffsetFromBase < RHS.OffsetFromBase; | |||
17609 | }); | |||
17610 | ||||
17611 | bool AllowVectors = !DAG.getMachineFunction().getFunction().hasFnAttribute( | |||
17612 | Attribute::NoImplicitFloat); | |||
17613 | bool IsNonTemporalStore = St->isNonTemporal(); | |||
17614 | bool IsNonTemporalLoad = StoreSrc == StoreSource::Load && | |||
17615 | cast<LoadSDNode>(StoredVal)->isNonTemporal(); | |||
17616 | ||||
17617 | // Store Merge attempts to merge the lowest stores. This generally | |||
17618 | // works out as if successful, as the remaining stores are checked | |||
17619 | // after the first collection of stores is merged. However, in the | |||
17620 | // case that a non-mergeable store is found first, e.g., {p[-2], | |||
17621 | // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent | |||
17622 | // mergeable cases. To prevent this, we prune such stores from the | |||
17623 | // front of StoreNodes here. | |||
17624 | bool MadeChange = false; | |||
17625 | while (StoreNodes.size() > 1) { | |||
17626 | unsigned NumConsecutiveStores = | |||
17627 | getConsecutiveStores(StoreNodes, ElementSizeBytes); | |||
17628 | // There are no more stores in the list to examine. | |||
17629 | if (NumConsecutiveStores == 0) | |||
17630 | return MadeChange; | |||
17631 | ||||
17632 | // We have at least 2 consecutive stores. Try to merge them. | |||
17633 | assert(NumConsecutiveStores >= 2 && "Expected at least 2 stores")((NumConsecutiveStores >= 2 && "Expected at least 2 stores" ) ? static_cast<void> (0) : __assert_fail ("NumConsecutiveStores >= 2 && \"Expected at least 2 stores\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17633, __PRETTY_FUNCTION__)); | |||
17634 | switch (StoreSrc) { | |||
17635 | case StoreSource::Constant: | |||
17636 | MadeChange |= tryStoreMergeOfConstants(StoreNodes, NumConsecutiveStores, | |||
17637 | MemVT, RootNode, AllowVectors); | |||
17638 | break; | |||
17639 | ||||
17640 | case StoreSource::Extract: | |||
17641 | MadeChange |= tryStoreMergeOfExtracts(StoreNodes, NumConsecutiveStores, | |||
17642 | MemVT, RootNode); | |||
17643 | break; | |||
17644 | ||||
17645 | case StoreSource::Load: | |||
17646 | MadeChange |= tryStoreMergeOfLoads(StoreNodes, NumConsecutiveStores, | |||
17647 | MemVT, RootNode, AllowVectors, | |||
17648 | IsNonTemporalStore, IsNonTemporalLoad); | |||
17649 | break; | |||
17650 | ||||
17651 | default: | |||
17652 | llvm_unreachable("Unhandled store source type")::llvm::llvm_unreachable_internal("Unhandled store source type" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17652); | |||
17653 | } | |||
17654 | } | |||
17655 | return MadeChange; | |||
17656 | } | |||
17657 | ||||
17658 | SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { | |||
17659 | SDLoc SL(ST); | |||
17660 | SDValue ReplStore; | |||
17661 | ||||
17662 | // Replace the chain to avoid dependency. | |||
17663 | if (ST->isTruncatingStore()) { | |||
17664 | ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), | |||
17665 | ST->getBasePtr(), ST->getMemoryVT(), | |||
17666 | ST->getMemOperand()); | |||
17667 | } else { | |||
17668 | ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), | |||
17669 | ST->getMemOperand()); | |||
17670 | } | |||
17671 | ||||
17672 | // Create token to keep both nodes around. | |||
17673 | SDValue Token = DAG.getNode(ISD::TokenFactor, SL, | |||
17674 | MVT::Other, ST->getChain(), ReplStore); | |||
17675 | ||||
17676 | // Make sure the new and old chains are cleaned up. | |||
17677 | AddToWorklist(Token.getNode()); | |||
17678 | ||||
17679 | // Don't add users to work list. | |||
17680 | return CombineTo(ST, Token, false); | |||
17681 | } | |||
17682 | ||||
17683 | SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { | |||
17684 | SDValue Value = ST->getValue(); | |||
17685 | if (Value.getOpcode() == ISD::TargetConstantFP) | |||
17686 | return SDValue(); | |||
17687 | ||||
17688 | if (!ISD::isNormalStore(ST)) | |||
17689 | return SDValue(); | |||
17690 | ||||
17691 | SDLoc DL(ST); | |||
17692 | ||||
17693 | SDValue Chain = ST->getChain(); | |||
17694 | SDValue Ptr = ST->getBasePtr(); | |||
17695 | ||||
17696 | const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); | |||
17697 | ||||
17698 | // NOTE: If the original store is volatile, this transform must not increase | |||
17699 | // the number of stores. For example, on x86-32 an f64 can be stored in one | |||
17700 | // processor operation but an i64 (which is not legal) requires two. So the | |||
17701 | // transform should not be done in this case. | |||
17702 | ||||
17703 | SDValue Tmp; | |||
17704 | switch (CFP->getSimpleValueType(0).SimpleTy) { | |||
17705 | default: | |||
17706 | llvm_unreachable("Unknown FP type")::llvm::llvm_unreachable_internal("Unknown FP type", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17706); | |||
17707 | case MVT::f16: // We don't do this for these yet. | |||
17708 | case MVT::f80: | |||
17709 | case MVT::f128: | |||
17710 | case MVT::ppcf128: | |||
17711 | return SDValue(); | |||
17712 | case MVT::f32: | |||
17713 | if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) || | |||
17714 | TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { | |||
17715 | ; | |||
17716 | Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). | |||
17717 | bitcastToAPInt().getZExtValue(), SDLoc(CFP), | |||
17718 | MVT::i32); | |||
17719 | return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); | |||
17720 | } | |||
17721 | ||||
17722 | return SDValue(); | |||
17723 | case MVT::f64: | |||
17724 | if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && | |||
17725 | ST->isSimple()) || | |||
17726 | TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { | |||
17727 | ; | |||
17728 | Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). | |||
17729 | getZExtValue(), SDLoc(CFP), MVT::i64); | |||
17730 | return DAG.getStore(Chain, DL, Tmp, | |||
17731 | Ptr, ST->getMemOperand()); | |||
17732 | } | |||
17733 | ||||
17734 | if (ST->isSimple() && | |||
17735 | TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { | |||
17736 | // Many FP stores are not made apparent until after legalize, e.g. for | |||
17737 | // argument passing. Since this is so common, custom legalize the | |||
17738 | // 64-bit integer store into two 32-bit stores. | |||
17739 | uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); | |||
17740 | SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); | |||
17741 | SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); | |||
17742 | if (DAG.getDataLayout().isBigEndian()) | |||
17743 | std::swap(Lo, Hi); | |||
17744 | ||||
17745 | MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); | |||
17746 | AAMDNodes AAInfo = ST->getAAInfo(); | |||
17747 | ||||
17748 | SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), | |||
17749 | ST->getOriginalAlign(), MMOFlags, AAInfo); | |||
17750 | Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), DL); | |||
17751 | SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, | |||
17752 | ST->getPointerInfo().getWithOffset(4), | |||
17753 | ST->getOriginalAlign(), MMOFlags, AAInfo); | |||
17754 | return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, | |||
17755 | St0, St1); | |||
17756 | } | |||
17757 | ||||
17758 | return SDValue(); | |||
17759 | } | |||
17760 | } | |||
17761 | ||||
17762 | SDValue DAGCombiner::visitSTORE(SDNode *N) { | |||
17763 | StoreSDNode *ST = cast<StoreSDNode>(N); | |||
17764 | SDValue Chain = ST->getChain(); | |||
17765 | SDValue Value = ST->getValue(); | |||
17766 | SDValue Ptr = ST->getBasePtr(); | |||
17767 | ||||
17768 | // If this is a store of a bit convert, store the input value if the | |||
17769 | // resultant store does not need a higher alignment than the original. | |||
17770 | if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && | |||
17771 | ST->isUnindexed()) { | |||
17772 | EVT SVT = Value.getOperand(0).getValueType(); | |||
17773 | // If the store is volatile, we only want to change the store type if the | |||
17774 | // resulting store is legal. Otherwise we might increase the number of | |||
17775 | // memory accesses. We don't care if the original type was legal or not | |||
17776 | // as we assume software couldn't rely on the number of accesses of an | |||
17777 | // illegal type. | |||
17778 | // TODO: May be able to relax for unordered atomics (see D66309) | |||
17779 | if (((!LegalOperations && ST->isSimple()) || | |||
17780 | TLI.isOperationLegal(ISD::STORE, SVT)) && | |||
17781 | TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT, | |||
17782 | DAG, *ST->getMemOperand())) { | |||
17783 | return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, | |||
17784 | ST->getMemOperand()); | |||
17785 | } | |||
17786 | } | |||
17787 | ||||
17788 | // Turn 'store undef, Ptr' -> nothing. | |||
17789 | if (Value.isUndef() && ST->isUnindexed()) | |||
17790 | return Chain; | |||
17791 | ||||
17792 | // Try to infer better alignment information than the store already has. | |||
17793 | if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) { | |||
17794 | if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { | |||
17795 | if (*Alignment > ST->getAlign() && | |||
17796 | isAligned(*Alignment, ST->getSrcValueOffset())) { | |||
17797 | SDValue NewStore = | |||
17798 | DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), | |||
17799 | ST->getMemoryVT(), *Alignment, | |||
17800 | ST->getMemOperand()->getFlags(), ST->getAAInfo()); | |||
17801 | // NewStore will always be N as we are only refining the alignment | |||
17802 | assert(NewStore.getNode() == N)((NewStore.getNode() == N) ? static_cast<void> (0) : __assert_fail ("NewStore.getNode() == N", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 17802, __PRETTY_FUNCTION__)); | |||
17803 | (void)NewStore; | |||
17804 | } | |||
17805 | } | |||
17806 | } | |||
17807 | ||||
17808 | // Try transforming a pair floating point load / store ops to integer | |||
17809 | // load / store ops. | |||
17810 | if (SDValue NewST = TransformFPLoadStorePair(N)) | |||
17811 | return NewST; | |||
17812 | ||||
17813 | // Try transforming several stores into STORE (BSWAP). | |||
17814 | if (SDValue Store = mergeTruncStores(ST)) | |||
17815 | return Store; | |||
17816 | ||||
17817 | if (ST->isUnindexed()) { | |||
17818 | // Walk up chain skipping non-aliasing memory nodes, on this store and any | |||
17819 | // adjacent stores. | |||
17820 | if (findBetterNeighborChains(ST)) { | |||
17821 | // replaceStoreChain uses CombineTo, which handled all of the worklist | |||
17822 | // manipulation. Return the original node to not do anything else. | |||
17823 | return SDValue(ST, 0); | |||
17824 | } | |||
17825 | Chain = ST->getChain(); | |||
17826 | } | |||
17827 | ||||
17828 | // FIXME: is there such a thing as a truncating indexed store? | |||
17829 | if (ST->isTruncatingStore() && ST->isUnindexed() && | |||
17830 | Value.getValueType().isInteger() && | |||
17831 | (!isa<ConstantSDNode>(Value) || | |||
17832 | !cast<ConstantSDNode>(Value)->isOpaque())) { | |||
17833 | APInt TruncDemandedBits = | |||
17834 | APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), | |||
17835 | ST->getMemoryVT().getScalarSizeInBits()); | |||
17836 | ||||
17837 | // See if we can simplify the input to this truncstore with knowledge that | |||
17838 | // only the low bits are being used. For example: | |||
17839 | // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" | |||
17840 | AddToWorklist(Value.getNode()); | |||
17841 | if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits)) | |||
17842 | return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(), | |||
17843 | ST->getMemOperand()); | |||
17844 | ||||
17845 | // Otherwise, see if we can simplify the operation with | |||
17846 | // SimplifyDemandedBits, which only works if the value has a single use. | |||
17847 | if (SimplifyDemandedBits(Value, TruncDemandedBits)) { | |||
17848 | // Re-visit the store if anything changed and the store hasn't been merged | |||
17849 | // with another node (N is deleted) SimplifyDemandedBits will add Value's | |||
17850 | // node back to the worklist if necessary, but we also need to re-visit | |||
17851 | // the Store node itself. | |||
17852 | if (N->getOpcode() != ISD::DELETED_NODE) | |||
17853 | AddToWorklist(N); | |||
17854 | return SDValue(N, 0); | |||
17855 | } | |||
17856 | } | |||
17857 | ||||
17858 | // If this is a load followed by a store to the same location, then the store | |||
17859 | // is dead/noop. | |||
17860 | // TODO: Can relax for unordered atomics (see D66309) | |||
17861 | if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { | |||
17862 | if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && | |||
17863 | ST->isUnindexed() && ST->isSimple() && | |||
17864 | // There can't be any side effects between the load and store, such as | |||
17865 | // a call or store. | |||
17866 | Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { | |||
17867 | // The store is dead, remove it. | |||
17868 | return Chain; | |||
17869 | } | |||
17870 | } | |||
17871 | ||||
17872 | // TODO: Can relax for unordered atomics (see D66309) | |||
17873 | if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { | |||
17874 | if (ST->isUnindexed() && ST->isSimple() && | |||
17875 | ST1->isUnindexed() && ST1->isSimple()) { | |||
17876 | if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value && | |||
17877 | ST->getMemoryVT() == ST1->getMemoryVT()) { | |||
17878 | // If this is a store followed by a store with the same value to the | |||
17879 | // same location, then the store is dead/noop. | |||
17880 | return Chain; | |||
17881 | } | |||
17882 | ||||
17883 | if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && | |||
17884 | !ST1->getBasePtr().isUndef() && | |||
17885 | // BaseIndexOffset and the code below requires knowing the size | |||
17886 | // of a vector, so bail out if MemoryVT is scalable. | |||
17887 | !ST->getMemoryVT().isScalableVector() && | |||
17888 | !ST1->getMemoryVT().isScalableVector()) { | |||
17889 | const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG); | |||
17890 | const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG); | |||
17891 | unsigned STBitSize = ST->getMemoryVT().getFixedSizeInBits(); | |||
17892 | unsigned ChainBitSize = ST1->getMemoryVT().getFixedSizeInBits(); | |||
17893 | // If this is a store who's preceding store to a subset of the current | |||
17894 | // location and no one other node is chained to that store we can | |||
17895 | // effectively drop the store. Do not remove stores to undef as they may | |||
17896 | // be used as data sinks. | |||
17897 | if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) { | |||
17898 | CombineTo(ST1, ST1->getChain()); | |||
17899 | return SDValue(); | |||
17900 | } | |||
17901 | } | |||
17902 | } | |||
17903 | } | |||
17904 | ||||
17905 | // If this is an FP_ROUND or TRUNC followed by a store, fold this into a | |||
17906 | // truncating store. We can do this even if this is already a truncstore. | |||
17907 | if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) | |||
17908 | && Value.getNode()->hasOneUse() && ST->isUnindexed() && | |||
17909 | TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), | |||
17910 | ST->getMemoryVT())) { | |||
17911 | return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), | |||
17912 | Ptr, ST->getMemoryVT(), ST->getMemOperand()); | |||
17913 | } | |||
17914 | ||||
17915 | // Always perform this optimization before types are legal. If the target | |||
17916 | // prefers, also try this after legalization to catch stores that were created | |||
17917 | // by intrinsics or other nodes. | |||
17918 | if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) { | |||
17919 | while (true) { | |||
17920 | // There can be multiple store sequences on the same chain. | |||
17921 | // Keep trying to merge store sequences until we are unable to do so | |||
17922 | // or until we merge the last store on the chain. | |||
17923 | bool Changed = mergeConsecutiveStores(ST); | |||
17924 | if (!Changed) break; | |||
17925 | // Return N as merge only uses CombineTo and no worklist clean | |||
17926 | // up is necessary. | |||
17927 | if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) | |||
17928 | return SDValue(N, 0); | |||
17929 | } | |||
17930 | } | |||
17931 | ||||
17932 | // Try transforming N to an indexed store. | |||
17933 | if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) | |||
17934 | return SDValue(N, 0); | |||
17935 | ||||
17936 | // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' | |||
17937 | // | |||
17938 | // Make sure to do this only after attempting to merge stores in order to | |||
17939 | // avoid changing the types of some subset of stores due to visit order, | |||
17940 | // preventing their merging. | |||
17941 | if (isa<ConstantFPSDNode>(ST->getValue())) { | |||
17942 | if (SDValue NewSt = replaceStoreOfFPConstant(ST)) | |||
17943 | return NewSt; | |||
17944 | } | |||
17945 | ||||
17946 | if (SDValue NewSt = splitMergedValStore(ST)) | |||
17947 | return NewSt; | |||
17948 | ||||
17949 | return ReduceLoadOpStoreWidth(N); | |||
17950 | } | |||
17951 | ||||
17952 | SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) { | |||
17953 | const auto *LifetimeEnd = cast<LifetimeSDNode>(N); | |||
17954 | if (!LifetimeEnd->hasOffset()) | |||
17955 | return SDValue(); | |||
17956 | ||||
17957 | const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(), | |||
17958 | LifetimeEnd->getOffset(), false); | |||
17959 | ||||
17960 | // We walk up the chains to find stores. | |||
17961 | SmallVector<SDValue, 8> Chains = {N->getOperand(0)}; | |||
17962 | while (!Chains.empty()) { | |||
17963 | SDValue Chain = Chains.pop_back_val(); | |||
17964 | if (!Chain.hasOneUse()) | |||
17965 | continue; | |||
17966 | switch (Chain.getOpcode()) { | |||
17967 | case ISD::TokenFactor: | |||
17968 | for (unsigned Nops = Chain.getNumOperands(); Nops;) | |||
17969 | Chains.push_back(Chain.getOperand(--Nops)); | |||
17970 | break; | |||
17971 | case ISD::LIFETIME_START: | |||
17972 | case ISD::LIFETIME_END: | |||
17973 | // We can forward past any lifetime start/end that can be proven not to | |||
17974 | // alias the node. | |||
17975 | if (!isAlias(Chain.getNode(), N)) | |||
17976 | Chains.push_back(Chain.getOperand(0)); | |||
17977 | break; | |||
17978 | case ISD::STORE: { | |||
17979 | StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain); | |||
17980 | // TODO: Can relax for unordered atomics (see D66309) | |||
17981 | if (!ST->isSimple() || ST->isIndexed()) | |||
17982 | continue; | |||
17983 | const TypeSize StoreSize = ST->getMemoryVT().getStoreSize(); | |||
17984 | // The bounds of a scalable store are not known until runtime, so this | |||
17985 | // store cannot be elided. | |||
17986 | if (StoreSize.isScalable()) | |||
17987 | continue; | |||
17988 | const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG); | |||
17989 | // If we store purely within object bounds just before its lifetime ends, | |||
17990 | // we can remove the store. | |||
17991 | if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase, | |||
17992 | StoreSize.getFixedSize() * 8)) { | |||
17993 | LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nRemoving store:"; StoreBase .dump(); dbgs() << "\nwithin LIFETIME_END of : "; LifetimeEndBase .dump(); dbgs() << "\n"; } } while (false) | |||
17994 | dbgs() << "\nwithin LIFETIME_END of : ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nRemoving store:"; StoreBase .dump(); dbgs() << "\nwithin LIFETIME_END of : "; LifetimeEndBase .dump(); dbgs() << "\n"; } } while (false) | |||
17995 | LifetimeEndBase.dump(); dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("dagcombine")) { dbgs() << "\nRemoving store:"; StoreBase .dump(); dbgs() << "\nwithin LIFETIME_END of : "; LifetimeEndBase .dump(); dbgs() << "\n"; } } while (false); | |||
17996 | CombineTo(ST, ST->getChain()); | |||
17997 | return SDValue(N, 0); | |||
17998 | } | |||
17999 | } | |||
18000 | } | |||
18001 | } | |||
18002 | return SDValue(); | |||
18003 | } | |||
18004 | ||||
18005 | /// For the instruction sequence of store below, F and I values | |||
18006 | /// are bundled together as an i64 value before being stored into memory. | |||
18007 | /// Sometimes it is more efficent to generate separate stores for F and I, | |||
18008 | /// which can remove the bitwise instructions or sink them to colder places. | |||
18009 | /// | |||
18010 | /// (store (or (zext (bitcast F to i32) to i64), | |||
18011 | /// (shl (zext I to i64), 32)), addr) --> | |||
18012 | /// (store F, addr) and (store I, addr+4) | |||
18013 | /// | |||
18014 | /// Similarly, splitting for other merged store can also be beneficial, like: | |||
18015 | /// For pair of {i32, i32}, i64 store --> two i32 stores. | |||
18016 | /// For pair of {i32, i16}, i64 store --> two i32 stores. | |||
18017 | /// For pair of {i16, i16}, i32 store --> two i16 stores. | |||
18018 | /// For pair of {i16, i8}, i32 store --> two i16 stores. | |||
18019 | /// For pair of {i8, i8}, i16 store --> two i8 stores. | |||
18020 | /// | |||
18021 | /// We allow each target to determine specifically which kind of splitting is | |||
18022 | /// supported. | |||
18023 | /// | |||
18024 | /// The store patterns are commonly seen from the simple code snippet below | |||
18025 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. | |||
18026 | /// void goo(const std::pair<int, float> &); | |||
18027 | /// hoo() { | |||
18028 | /// ... | |||
18029 | /// goo(std::make_pair(tmp, ftmp)); | |||
18030 | /// ... | |||
18031 | /// } | |||
18032 | /// | |||
18033 | SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { | |||
18034 | if (OptLevel == CodeGenOpt::None) | |||
18035 | return SDValue(); | |||
18036 | ||||
18037 | // Can't change the number of memory accesses for a volatile store or break | |||
18038 | // atomicity for an atomic one. | |||
18039 | if (!ST->isSimple()) | |||
18040 | return SDValue(); | |||
18041 | ||||
18042 | SDValue Val = ST->getValue(); | |||
18043 | SDLoc DL(ST); | |||
18044 | ||||
18045 | // Match OR operand. | |||
18046 | if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) | |||
18047 | return SDValue(); | |||
18048 | ||||
18049 | // Match SHL operand and get Lower and Higher parts of Val. | |||
18050 | SDValue Op1 = Val.getOperand(0); | |||
18051 | SDValue Op2 = Val.getOperand(1); | |||
18052 | SDValue Lo, Hi; | |||
18053 | if (Op1.getOpcode() != ISD::SHL) { | |||
18054 | std::swap(Op1, Op2); | |||
18055 | if (Op1.getOpcode() != ISD::SHL) | |||
18056 | return SDValue(); | |||
18057 | } | |||
18058 | Lo = Op2; | |||
18059 | Hi = Op1.getOperand(0); | |||
18060 | if (!Op1.hasOneUse()) | |||
18061 | return SDValue(); | |||
18062 | ||||
18063 | // Match shift amount to HalfValBitSize. | |||
18064 | unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; | |||
18065 | ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); | |||
18066 | if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) | |||
18067 | return SDValue(); | |||
18068 | ||||
18069 | // Lo and Hi are zero-extended from int with size less equal than 32 | |||
18070 | // to i64. | |||
18071 | if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || | |||
18072 | !Lo.getOperand(0).getValueType().isScalarInteger() || | |||
18073 | Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || | |||
18074 | Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || | |||
18075 | !Hi.getOperand(0).getValueType().isScalarInteger() || | |||
18076 | Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) | |||
18077 | return SDValue(); | |||
18078 | ||||
18079 | // Use the EVT of low and high parts before bitcast as the input | |||
18080 | // of target query. | |||
18081 | EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) | |||
18082 | ? Lo.getOperand(0).getValueType() | |||
18083 | : Lo.getValueType(); | |||
18084 | EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) | |||
18085 | ? Hi.getOperand(0).getValueType() | |||
18086 | : Hi.getValueType(); | |||
18087 | if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) | |||
18088 | return SDValue(); | |||
18089 | ||||
18090 | // Start to split store. | |||
18091 | MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); | |||
18092 | AAMDNodes AAInfo = ST->getAAInfo(); | |||
18093 | ||||
18094 | // Change the sizes of Lo and Hi's value types to HalfValBitSize. | |||
18095 | EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); | |||
18096 | Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); | |||
18097 | Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); | |||
18098 | ||||
18099 | SDValue Chain = ST->getChain(); | |||
18100 | SDValue Ptr = ST->getBasePtr(); | |||
18101 | // Lower value store. | |||
18102 | SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), | |||
18103 | ST->getOriginalAlign(), MMOFlags, AAInfo); | |||
18104 | Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(HalfValBitSize / 8), DL); | |||
18105 | // Higher value store. | |||
18106 | SDValue St1 = DAG.getStore( | |||
18107 | St0, DL, Hi, Ptr, ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), | |||
18108 | ST->getOriginalAlign(), MMOFlags, AAInfo); | |||
18109 | return St1; | |||
18110 | } | |||
18111 | ||||
18112 | /// Convert a disguised subvector insertion into a shuffle: | |||
18113 | SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { | |||
18114 | assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT &&((N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Expected extract_vector_elt" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::INSERT_VECTOR_ELT && \"Expected extract_vector_elt\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18115, __PRETTY_FUNCTION__)) | |||
18115 | "Expected extract_vector_elt")((N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Expected extract_vector_elt" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::INSERT_VECTOR_ELT && \"Expected extract_vector_elt\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18115, __PRETTY_FUNCTION__)); | |||
18116 | SDValue InsertVal = N->getOperand(1); | |||
18117 | SDValue Vec = N->getOperand(0); | |||
18118 | ||||
18119 | // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N), | |||
18120 | // InsIndex) | |||
18121 | // --> (vector_shuffle X, Y) and variations where shuffle operands may be | |||
18122 | // CONCAT_VECTORS. | |||
18123 | if (Vec.getOpcode() == ISD::VECTOR_SHUFFLE && Vec.hasOneUse() && | |||
18124 | InsertVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
18125 | isa<ConstantSDNode>(InsertVal.getOperand(1))) { | |||
18126 | ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Vec.getNode()); | |||
18127 | ArrayRef<int> Mask = SVN->getMask(); | |||
18128 | ||||
18129 | SDValue X = Vec.getOperand(0); | |||
18130 | SDValue Y = Vec.getOperand(1); | |||
18131 | ||||
18132 | // Vec's operand 0 is using indices from 0 to N-1 and | |||
18133 | // operand 1 from N to 2N - 1, where N is the number of | |||
18134 | // elements in the vectors. | |||
18135 | SDValue InsertVal0 = InsertVal.getOperand(0); | |||
18136 | int ElementOffset = -1; | |||
18137 | ||||
18138 | // We explore the inputs of the shuffle in order to see if we find the | |||
18139 | // source of the extract_vector_elt. If so, we can use it to modify the | |||
18140 | // shuffle rather than perform an insert_vector_elt. | |||
18141 | SmallVector<std::pair<int, SDValue>, 8> ArgWorkList; | |||
18142 | ArgWorkList.emplace_back(Mask.size(), Y); | |||
18143 | ArgWorkList.emplace_back(0, X); | |||
18144 | ||||
18145 | while (!ArgWorkList.empty()) { | |||
18146 | int ArgOffset; | |||
18147 | SDValue ArgVal; | |||
18148 | std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val(); | |||
18149 | ||||
18150 | if (ArgVal == InsertVal0) { | |||
18151 | ElementOffset = ArgOffset; | |||
18152 | break; | |||
18153 | } | |||
18154 | ||||
18155 | // Peek through concat_vector. | |||
18156 | if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) { | |||
18157 | int CurrentArgOffset = | |||
18158 | ArgOffset + ArgVal.getValueType().getVectorNumElements(); | |||
18159 | int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements(); | |||
18160 | for (SDValue Op : reverse(ArgVal->ops())) { | |||
18161 | CurrentArgOffset -= Step; | |||
18162 | ArgWorkList.emplace_back(CurrentArgOffset, Op); | |||
18163 | } | |||
18164 | ||||
18165 | // Make sure we went through all the elements and did not screw up index | |||
18166 | // computation. | |||
18167 | assert(CurrentArgOffset == ArgOffset)((CurrentArgOffset == ArgOffset) ? static_cast<void> (0 ) : __assert_fail ("CurrentArgOffset == ArgOffset", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18167, __PRETTY_FUNCTION__)); | |||
18168 | } | |||
18169 | } | |||
18170 | ||||
18171 | if (ElementOffset != -1) { | |||
18172 | SmallVector<int, 16> NewMask(Mask.begin(), Mask.end()); | |||
18173 | ||||
18174 | auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1)); | |||
18175 | NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue(); | |||
18176 | assert(NewMask[InsIndex] <((NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements ()) && NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound" ) ? static_cast<void> (0) : __assert_fail ("NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements()) && NewMask[InsIndex] >= 0 && \"NewMask[InsIndex] is out of bound\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18178, __PRETTY_FUNCTION__)) | |||
18177 | (int)(2 * Vec.getValueType().getVectorNumElements()) &&((NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements ()) && NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound" ) ? static_cast<void> (0) : __assert_fail ("NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements()) && NewMask[InsIndex] >= 0 && \"NewMask[InsIndex] is out of bound\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18178, __PRETTY_FUNCTION__)) | |||
18178 | NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound")((NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements ()) && NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound" ) ? static_cast<void> (0) : __assert_fail ("NewMask[InsIndex] < (int)(2 * Vec.getValueType().getVectorNumElements()) && NewMask[InsIndex] >= 0 && \"NewMask[InsIndex] is out of bound\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18178, __PRETTY_FUNCTION__)); | |||
18179 | ||||
18180 | SDValue LegalShuffle = | |||
18181 | TLI.buildLegalVectorShuffle(Vec.getValueType(), SDLoc(N), X, | |||
18182 | Y, NewMask, DAG); | |||
18183 | if (LegalShuffle) | |||
18184 | return LegalShuffle; | |||
18185 | } | |||
18186 | } | |||
18187 | ||||
18188 | // insert_vector_elt V, (bitcast X from vector type), IdxC --> | |||
18189 | // bitcast(shuffle (bitcast V), (extended X), Mask) | |||
18190 | // Note: We do not use an insert_subvector node because that requires a | |||
18191 | // legal subvector type. | |||
18192 | if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || | |||
18193 | !InsertVal.getOperand(0).getValueType().isVector()) | |||
18194 | return SDValue(); | |||
18195 | ||||
18196 | SDValue SubVec = InsertVal.getOperand(0); | |||
18197 | SDValue DestVec = N->getOperand(0); | |||
18198 | EVT SubVecVT = SubVec.getValueType(); | |||
18199 | EVT VT = DestVec.getValueType(); | |||
18200 | unsigned NumSrcElts = SubVecVT.getVectorNumElements(); | |||
18201 | // If the source only has a single vector element, the cost of creating adding | |||
18202 | // it to a vector is likely to exceed the cost of a insert_vector_elt. | |||
18203 | if (NumSrcElts == 1) | |||
18204 | return SDValue(); | |||
18205 | unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); | |||
18206 | unsigned NumMaskVals = ExtendRatio * NumSrcElts; | |||
18207 | ||||
18208 | // Step 1: Create a shuffle mask that implements this insert operation. The | |||
18209 | // vector that we are inserting into will be operand 0 of the shuffle, so | |||
18210 | // those elements are just 'i'. The inserted subvector is in the first | |||
18211 | // positions of operand 1 of the shuffle. Example: | |||
18212 | // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} | |||
18213 | SmallVector<int, 16> Mask(NumMaskVals); | |||
18214 | for (unsigned i = 0; i != NumMaskVals; ++i) { | |||
18215 | if (i / NumSrcElts == InsIndex) | |||
18216 | Mask[i] = (i % NumSrcElts) + NumMaskVals; | |||
18217 | else | |||
18218 | Mask[i] = i; | |||
18219 | } | |||
18220 | ||||
18221 | // Bail out if the target can not handle the shuffle we want to create. | |||
18222 | EVT SubVecEltVT = SubVecVT.getVectorElementType(); | |||
18223 | EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); | |||
18224 | if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) | |||
18225 | return SDValue(); | |||
18226 | ||||
18227 | // Step 2: Create a wide vector from the inserted source vector by appending | |||
18228 | // undefined elements. This is the same size as our destination vector. | |||
18229 | SDLoc DL(N); | |||
18230 | SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); | |||
18231 | ConcatOps[0] = SubVec; | |||
18232 | SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); | |||
18233 | ||||
18234 | // Step 3: Shuffle in the padded subvector. | |||
18235 | SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); | |||
18236 | SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); | |||
18237 | AddToWorklist(PaddedSubV.getNode()); | |||
18238 | AddToWorklist(DestVecBC.getNode()); | |||
18239 | AddToWorklist(Shuf.getNode()); | |||
18240 | return DAG.getBitcast(VT, Shuf); | |||
18241 | } | |||
18242 | ||||
18243 | SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { | |||
18244 | SDValue InVec = N->getOperand(0); | |||
18245 | SDValue InVal = N->getOperand(1); | |||
18246 | SDValue EltNo = N->getOperand(2); | |||
18247 | SDLoc DL(N); | |||
18248 | ||||
18249 | EVT VT = InVec.getValueType(); | |||
18250 | auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); | |||
18251 | ||||
18252 | // Insert into out-of-bounds element is undefined. | |||
18253 | if (IndexC && VT.isFixedLengthVector() && | |||
18254 | IndexC->getZExtValue() >= VT.getVectorNumElements()) | |||
18255 | return DAG.getUNDEF(VT); | |||
18256 | ||||
18257 | // Remove redundant insertions: | |||
18258 | // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x | |||
18259 | if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
18260 | InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) | |||
18261 | return InVec; | |||
18262 | ||||
18263 | if (!IndexC) { | |||
18264 | // If this is variable insert to undef vector, it might be better to splat: | |||
18265 | // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > | |||
18266 | if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { | |||
18267 | if (VT.isScalableVector()) | |||
18268 | return DAG.getSplatVector(VT, DL, InVal); | |||
18269 | else { | |||
18270 | SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal); | |||
18271 | return DAG.getBuildVector(VT, DL, Ops); | |||
18272 | } | |||
18273 | } | |||
18274 | return SDValue(); | |||
18275 | } | |||
18276 | ||||
18277 | if (VT.isScalableVector()) | |||
18278 | return SDValue(); | |||
18279 | ||||
18280 | unsigned NumElts = VT.getVectorNumElements(); | |||
18281 | ||||
18282 | // We must know which element is being inserted for folds below here. | |||
18283 | unsigned Elt = IndexC->getZExtValue(); | |||
18284 | if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) | |||
18285 | return Shuf; | |||
18286 | ||||
18287 | // Canonicalize insert_vector_elt dag nodes. | |||
18288 | // Example: | |||
18289 | // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) | |||
18290 | // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) | |||
18291 | // | |||
18292 | // Do this only if the child insert_vector node has one use; also | |||
18293 | // do this only if indices are both constants and Idx1 < Idx0. | |||
18294 | if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() | |||
18295 | && isa<ConstantSDNode>(InVec.getOperand(2))) { | |||
18296 | unsigned OtherElt = InVec.getConstantOperandVal(2); | |||
18297 | if (Elt < OtherElt) { | |||
18298 | // Swap nodes. | |||
18299 | SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, | |||
18300 | InVec.getOperand(0), InVal, EltNo); | |||
18301 | AddToWorklist(NewOp.getNode()); | |||
18302 | return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), | |||
18303 | VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); | |||
18304 | } | |||
18305 | } | |||
18306 | ||||
18307 | // If we can't generate a legal BUILD_VECTOR, exit | |||
18308 | if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) | |||
18309 | return SDValue(); | |||
18310 | ||||
18311 | // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially | |||
18312 | // be converted to a BUILD_VECTOR). Fill in the Ops vector with the | |||
18313 | // vector elements. | |||
18314 | SmallVector<SDValue, 8> Ops; | |||
18315 | // Do not combine these two vectors if the output vector will not replace | |||
18316 | // the input vector. | |||
18317 | if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { | |||
18318 | Ops.append(InVec.getNode()->op_begin(), | |||
18319 | InVec.getNode()->op_end()); | |||
18320 | } else if (InVec.isUndef()) { | |||
18321 | Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType())); | |||
18322 | } else { | |||
18323 | return SDValue(); | |||
18324 | } | |||
18325 | assert(Ops.size() == NumElts && "Unexpected vector size")((Ops.size() == NumElts && "Unexpected vector size") ? static_cast<void> (0) : __assert_fail ("Ops.size() == NumElts && \"Unexpected vector size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18325, __PRETTY_FUNCTION__)); | |||
18326 | ||||
18327 | // Insert the element | |||
18328 | if (Elt < Ops.size()) { | |||
18329 | // All the operands of BUILD_VECTOR must have the same type; | |||
18330 | // we enforce that here. | |||
18331 | EVT OpVT = Ops[0].getValueType(); | |||
18332 | Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; | |||
18333 | } | |||
18334 | ||||
18335 | // Return the new vector | |||
18336 | return DAG.getBuildVector(VT, DL, Ops); | |||
18337 | } | |||
18338 | ||||
18339 | SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, | |||
18340 | SDValue EltNo, | |||
18341 | LoadSDNode *OriginalLoad) { | |||
18342 | assert(OriginalLoad->isSimple())((OriginalLoad->isSimple()) ? static_cast<void> (0) : __assert_fail ("OriginalLoad->isSimple()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18342, __PRETTY_FUNCTION__)); | |||
18343 | ||||
18344 | EVT ResultVT = EVE->getValueType(0); | |||
18345 | EVT VecEltVT = InVecVT.getVectorElementType(); | |||
18346 | ||||
18347 | // If the vector element type is not a multiple of a byte then we are unable | |||
18348 | // to correctly compute an address to load only the extracted element as a | |||
18349 | // scalar. | |||
18350 | if (!VecEltVT.isByteSized()) | |||
18351 | return SDValue(); | |||
18352 | ||||
18353 | Align Alignment = OriginalLoad->getAlign(); | |||
18354 | Align NewAlign = DAG.getDataLayout().getABITypeAlign( | |||
18355 | VecEltVT.getTypeForEVT(*DAG.getContext())); | |||
18356 | ||||
18357 | if (NewAlign > Alignment || | |||
18358 | !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) | |||
18359 | return SDValue(); | |||
18360 | ||||
18361 | ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? | |||
18362 | ISD::NON_EXTLOAD : ISD::EXTLOAD; | |||
18363 | if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) | |||
18364 | return SDValue(); | |||
18365 | ||||
18366 | Alignment = NewAlign; | |||
18367 | ||||
18368 | SDValue NewPtr = OriginalLoad->getBasePtr(); | |||
18369 | SDValue Offset; | |||
18370 | EVT PtrType = NewPtr.getValueType(); | |||
18371 | MachinePointerInfo MPI; | |||
18372 | SDLoc DL(EVE); | |||
18373 | if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { | |||
18374 | int Elt = ConstEltNo->getZExtValue(); | |||
18375 | unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; | |||
18376 | Offset = DAG.getConstant(PtrOff, DL, PtrType); | |||
18377 | MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); | |||
18378 | } else { | |||
18379 | Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); | |||
18380 | Offset = DAG.getNode( | |||
18381 | ISD::MUL, DL, PtrType, Offset, | |||
18382 | DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); | |||
18383 | // Discard the pointer info except the address space because the memory | |||
18384 | // operand can't represent this new access since the offset is variable. | |||
18385 | MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace()); | |||
18386 | } | |||
18387 | NewPtr = DAG.getMemBasePlusOffset(NewPtr, Offset, DL); | |||
18388 | ||||
18389 | // The replacement we need to do here is a little tricky: we need to | |||
18390 | // replace an extractelement of a load with a load. | |||
18391 | // Use ReplaceAllUsesOfValuesWith to do the replacement. | |||
18392 | // Note that this replacement assumes that the extractvalue is the only | |||
18393 | // use of the load; that's okay because we don't want to perform this | |||
18394 | // transformation in other cases anyway. | |||
18395 | SDValue Load; | |||
18396 | SDValue Chain; | |||
18397 | if (ResultVT.bitsGT(VecEltVT)) { | |||
18398 | // If the result type of vextract is wider than the load, then issue an | |||
18399 | // extending load instead. | |||
18400 | ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, | |||
18401 | VecEltVT) | |||
18402 | ? ISD::ZEXTLOAD | |||
18403 | : ISD::EXTLOAD; | |||
18404 | Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, | |||
18405 | OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, | |||
18406 | Alignment, OriginalLoad->getMemOperand()->getFlags(), | |||
18407 | OriginalLoad->getAAInfo()); | |||
18408 | Chain = Load.getValue(1); | |||
18409 | } else { | |||
18410 | Load = DAG.getLoad( | |||
18411 | VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, Alignment, | |||
18412 | OriginalLoad->getMemOperand()->getFlags(), OriginalLoad->getAAInfo()); | |||
18413 | Chain = Load.getValue(1); | |||
18414 | if (ResultVT.bitsLT(VecEltVT)) | |||
18415 | Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); | |||
18416 | else | |||
18417 | Load = DAG.getBitcast(ResultVT, Load); | |||
18418 | } | |||
18419 | WorklistRemover DeadNodes(*this); | |||
18420 | SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; | |||
18421 | SDValue To[] = { Load, Chain }; | |||
18422 | DAG.ReplaceAllUsesOfValuesWith(From, To, 2); | |||
18423 | // Make sure to revisit this node to clean it up; it will usually be dead. | |||
18424 | AddToWorklist(EVE); | |||
18425 | // Since we're explicitly calling ReplaceAllUses, add the new node to the | |||
18426 | // worklist explicitly as well. | |||
18427 | AddToWorklistWithUsers(Load.getNode()); | |||
18428 | ++OpsNarrowed; | |||
18429 | return SDValue(EVE, 0); | |||
18430 | } | |||
18431 | ||||
18432 | /// Transform a vector binary operation into a scalar binary operation by moving | |||
18433 | /// the math/logic after an extract element of a vector. | |||
18434 | static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG, | |||
18435 | bool LegalOperations) { | |||
18436 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
18437 | SDValue Vec = ExtElt->getOperand(0); | |||
18438 | SDValue Index = ExtElt->getOperand(1); | |||
18439 | auto *IndexC = dyn_cast<ConstantSDNode>(Index); | |||
18440 | if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() || | |||
18441 | Vec.getNode()->getNumValues() != 1) | |||
18442 | return SDValue(); | |||
18443 | ||||
18444 | // Targets may want to avoid this to prevent an expensive register transfer. | |||
18445 | if (!TLI.shouldScalarizeBinop(Vec)) | |||
18446 | return SDValue(); | |||
18447 | ||||
18448 | // Extracting an element of a vector constant is constant-folded, so this | |||
18449 | // transform is just replacing a vector op with a scalar op while moving the | |||
18450 | // extract. | |||
18451 | SDValue Op0 = Vec.getOperand(0); | |||
18452 | SDValue Op1 = Vec.getOperand(1); | |||
18453 | if (isAnyConstantBuildVector(Op0, true) || | |||
18454 | isAnyConstantBuildVector(Op1, true)) { | |||
18455 | // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C' | |||
18456 | // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC) | |||
18457 | SDLoc DL(ExtElt); | |||
18458 | EVT VT = ExtElt->getValueType(0); | |||
18459 | SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index); | |||
18460 | SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index); | |||
18461 | return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1); | |||
18462 | } | |||
18463 | ||||
18464 | return SDValue(); | |||
18465 | } | |||
18466 | ||||
18467 | SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { | |||
18468 | SDValue VecOp = N->getOperand(0); | |||
18469 | SDValue Index = N->getOperand(1); | |||
18470 | EVT ScalarVT = N->getValueType(0); | |||
18471 | EVT VecVT = VecOp.getValueType(); | |||
18472 | if (VecOp.isUndef()) | |||
18473 | return DAG.getUNDEF(ScalarVT); | |||
18474 | ||||
18475 | // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val | |||
18476 | // | |||
18477 | // This only really matters if the index is non-constant since other combines | |||
18478 | // on the constant elements already work. | |||
18479 | SDLoc DL(N); | |||
18480 | if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT && | |||
18481 | Index == VecOp.getOperand(2)) { | |||
18482 | SDValue Elt = VecOp.getOperand(1); | |||
18483 | return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt; | |||
18484 | } | |||
18485 | ||||
18486 | // (vextract (scalar_to_vector val, 0) -> val | |||
18487 | if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) { | |||
18488 | // Only 0'th element of SCALAR_TO_VECTOR is defined. | |||
18489 | if (DAG.isKnownNeverZero(Index)) | |||
18490 | return DAG.getUNDEF(ScalarVT); | |||
18491 | ||||
18492 | // Check if the result type doesn't match the inserted element type. A | |||
18493 | // SCALAR_TO_VECTOR may truncate the inserted element and the | |||
18494 | // EXTRACT_VECTOR_ELT may widen the extracted vector. | |||
18495 | SDValue InOp = VecOp.getOperand(0); | |||
18496 | if (InOp.getValueType() != ScalarVT) { | |||
18497 | assert(InOp.getValueType().isInteger() && ScalarVT.isInteger())((InOp.getValueType().isInteger() && ScalarVT.isInteger ()) ? static_cast<void> (0) : __assert_fail ("InOp.getValueType().isInteger() && ScalarVT.isInteger()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18497, __PRETTY_FUNCTION__)); | |||
18498 | return DAG.getSExtOrTrunc(InOp, DL, ScalarVT); | |||
18499 | } | |||
18500 | return InOp; | |||
18501 | } | |||
18502 | ||||
18503 | // extract_vector_elt of out-of-bounds element -> UNDEF | |||
18504 | auto *IndexC = dyn_cast<ConstantSDNode>(Index); | |||
18505 | if (IndexC && VecVT.isFixedLengthVector() && | |||
18506 | IndexC->getAPIntValue().uge(VecVT.getVectorNumElements())) | |||
18507 | return DAG.getUNDEF(ScalarVT); | |||
18508 | ||||
18509 | // extract_vector_elt (build_vector x, y), 1 -> y | |||
18510 | if (((IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR) || | |||
18511 | VecOp.getOpcode() == ISD::SPLAT_VECTOR) && | |||
18512 | TLI.isTypeLegal(VecVT) && | |||
18513 | (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) { | |||
18514 | assert((VecOp.getOpcode() != ISD::BUILD_VECTOR ||(((VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector ()) && "BUILD_VECTOR used for scalable vectors") ? static_cast <void> (0) : __assert_fail ("(VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector()) && \"BUILD_VECTOR used for scalable vectors\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18516, __PRETTY_FUNCTION__)) | |||
18515 | VecVT.isFixedLengthVector()) &&(((VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector ()) && "BUILD_VECTOR used for scalable vectors") ? static_cast <void> (0) : __assert_fail ("(VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector()) && \"BUILD_VECTOR used for scalable vectors\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18516, __PRETTY_FUNCTION__)) | |||
18516 | "BUILD_VECTOR used for scalable vectors")(((VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector ()) && "BUILD_VECTOR used for scalable vectors") ? static_cast <void> (0) : __assert_fail ("(VecOp.getOpcode() != ISD::BUILD_VECTOR || VecVT.isFixedLengthVector()) && \"BUILD_VECTOR used for scalable vectors\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18516, __PRETTY_FUNCTION__)); | |||
18517 | unsigned IndexVal = | |||
18518 | VecOp.getOpcode() == ISD::BUILD_VECTOR ? IndexC->getZExtValue() : 0; | |||
18519 | SDValue Elt = VecOp.getOperand(IndexVal); | |||
18520 | EVT InEltVT = Elt.getValueType(); | |||
18521 | ||||
18522 | // Sometimes build_vector's scalar input types do not match result type. | |||
18523 | if (ScalarVT == InEltVT) | |||
18524 | return Elt; | |||
18525 | ||||
18526 | // TODO: It may be useful to truncate if free if the build_vector implicitly | |||
18527 | // converts. | |||
18528 | } | |||
18529 | ||||
18530 | if (VecVT.isScalableVector()) | |||
18531 | return SDValue(); | |||
18532 | ||||
18533 | // All the code from this point onwards assumes fixed width vectors, but it's | |||
18534 | // possible that some of the combinations could be made to work for scalable | |||
18535 | // vectors too. | |||
18536 | unsigned NumElts = VecVT.getVectorNumElements(); | |||
18537 | unsigned VecEltBitWidth = VecVT.getScalarSizeInBits(); | |||
18538 | ||||
18539 | // TODO: These transforms should not require the 'hasOneUse' restriction, but | |||
18540 | // there are regressions on multiple targets without it. We can end up with a | |||
18541 | // mess of scalar and vector code if we reduce only part of the DAG to scalar. | |||
18542 | if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() && | |||
18543 | VecOp.hasOneUse()) { | |||
18544 | // The vector index of the LSBs of the source depend on the endian-ness. | |||
18545 | bool IsLE = DAG.getDataLayout().isLittleEndian(); | |||
18546 | unsigned ExtractIndex = IndexC->getZExtValue(); | |||
18547 | // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x) | |||
18548 | unsigned BCTruncElt = IsLE ? 0 : NumElts - 1; | |||
18549 | SDValue BCSrc = VecOp.getOperand(0); | |||
18550 | if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger()) | |||
18551 | return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc); | |||
18552 | ||||
18553 | if (LegalTypes && BCSrc.getValueType().isInteger() && | |||
18554 | BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) { | |||
18555 | // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt --> | |||
18556 | // trunc i64 X to i32 | |||
18557 | SDValue X = BCSrc.getOperand(0); | |||
18558 | assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() &&((X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger () && "Extract element and scalar to vector can't change element type " "from FP to integer.") ? static_cast<void> (0) : __assert_fail ("X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && \"Extract element and scalar to vector can't change element type \" \"from FP to integer.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18560, __PRETTY_FUNCTION__)) | |||
18559 | "Extract element and scalar to vector can't change element type "((X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger () && "Extract element and scalar to vector can't change element type " "from FP to integer.") ? static_cast<void> (0) : __assert_fail ("X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && \"Extract element and scalar to vector can't change element type \" \"from FP to integer.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18560, __PRETTY_FUNCTION__)) | |||
18560 | "from FP to integer.")((X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger () && "Extract element and scalar to vector can't change element type " "from FP to integer.") ? static_cast<void> (0) : __assert_fail ("X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && \"Extract element and scalar to vector can't change element type \" \"from FP to integer.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18560, __PRETTY_FUNCTION__)); | |||
18561 | unsigned XBitWidth = X.getValueSizeInBits(); | |||
18562 | BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1; | |||
18563 | ||||
18564 | // An extract element return value type can be wider than its vector | |||
18565 | // operand element type. In that case, the high bits are undefined, so | |||
18566 | // it's possible that we may need to extend rather than truncate. | |||
18567 | if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) { | |||
18568 | assert(XBitWidth % VecEltBitWidth == 0 &&((XBitWidth % VecEltBitWidth == 0 && "Scalar bitwidth must be a multiple of vector element bitwidth" ) ? static_cast<void> (0) : __assert_fail ("XBitWidth % VecEltBitWidth == 0 && \"Scalar bitwidth must be a multiple of vector element bitwidth\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18569, __PRETTY_FUNCTION__)) | |||
18569 | "Scalar bitwidth must be a multiple of vector element bitwidth")((XBitWidth % VecEltBitWidth == 0 && "Scalar bitwidth must be a multiple of vector element bitwidth" ) ? static_cast<void> (0) : __assert_fail ("XBitWidth % VecEltBitWidth == 0 && \"Scalar bitwidth must be a multiple of vector element bitwidth\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18569, __PRETTY_FUNCTION__)); | |||
18570 | return DAG.getAnyExtOrTrunc(X, DL, ScalarVT); | |||
18571 | } | |||
18572 | } | |||
18573 | } | |||
18574 | ||||
18575 | if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations)) | |||
18576 | return BO; | |||
18577 | ||||
18578 | // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. | |||
18579 | // We only perform this optimization before the op legalization phase because | |||
18580 | // we may introduce new vector instructions which are not backed by TD | |||
18581 | // patterns. For example on AVX, extracting elements from a wide vector | |||
18582 | // without using extract_subvector. However, if we can find an underlying | |||
18583 | // scalar value, then we can always use that. | |||
18584 | if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) { | |||
18585 | auto *Shuf = cast<ShuffleVectorSDNode>(VecOp); | |||
18586 | // Find the new index to extract from. | |||
18587 | int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue()); | |||
18588 | ||||
18589 | // Extracting an undef index is undef. | |||
18590 | if (OrigElt == -1) | |||
18591 | return DAG.getUNDEF(ScalarVT); | |||
18592 | ||||
18593 | // Select the right vector half to extract from. | |||
18594 | SDValue SVInVec; | |||
18595 | if (OrigElt < (int)NumElts) { | |||
18596 | SVInVec = VecOp.getOperand(0); | |||
18597 | } else { | |||
18598 | SVInVec = VecOp.getOperand(1); | |||
18599 | OrigElt -= NumElts; | |||
18600 | } | |||
18601 | ||||
18602 | if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { | |||
18603 | SDValue InOp = SVInVec.getOperand(OrigElt); | |||
18604 | if (InOp.getValueType() != ScalarVT) { | |||
18605 | assert(InOp.getValueType().isInteger() && ScalarVT.isInteger())((InOp.getValueType().isInteger() && ScalarVT.isInteger ()) ? static_cast<void> (0) : __assert_fail ("InOp.getValueType().isInteger() && ScalarVT.isInteger()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18605, __PRETTY_FUNCTION__)); | |||
18606 | InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT); | |||
18607 | } | |||
18608 | ||||
18609 | return InOp; | |||
18610 | } | |||
18611 | ||||
18612 | // FIXME: We should handle recursing on other vector shuffles and | |||
18613 | // scalar_to_vector here as well. | |||
18614 | ||||
18615 | if (!LegalOperations || | |||
18616 | // FIXME: Should really be just isOperationLegalOrCustom. | |||
18617 | TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) || | |||
18618 | TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) { | |||
18619 | return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec, | |||
18620 | DAG.getVectorIdxConstant(OrigElt, DL)); | |||
18621 | } | |||
18622 | } | |||
18623 | ||||
18624 | // If only EXTRACT_VECTOR_ELT nodes use the source vector we can | |||
18625 | // simplify it based on the (valid) extraction indices. | |||
18626 | if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) { | |||
18627 | return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
18628 | Use->getOperand(0) == VecOp && | |||
18629 | isa<ConstantSDNode>(Use->getOperand(1)); | |||
18630 | })) { | |||
18631 | APInt DemandedElts = APInt::getNullValue(NumElts); | |||
18632 | for (SDNode *Use : VecOp->uses()) { | |||
18633 | auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); | |||
18634 | if (CstElt->getAPIntValue().ult(NumElts)) | |||
18635 | DemandedElts.setBit(CstElt->getZExtValue()); | |||
18636 | } | |||
18637 | if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) { | |||
18638 | // We simplified the vector operand of this extract element. If this | |||
18639 | // extract is not dead, visit it again so it is folded properly. | |||
18640 | if (N->getOpcode() != ISD::DELETED_NODE) | |||
18641 | AddToWorklist(N); | |||
18642 | return SDValue(N, 0); | |||
18643 | } | |||
18644 | APInt DemandedBits = APInt::getAllOnesValue(VecEltBitWidth); | |||
18645 | if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) { | |||
18646 | // We simplified the vector operand of this extract element. If this | |||
18647 | // extract is not dead, visit it again so it is folded properly. | |||
18648 | if (N->getOpcode() != ISD::DELETED_NODE) | |||
18649 | AddToWorklist(N); | |||
18650 | return SDValue(N, 0); | |||
18651 | } | |||
18652 | } | |||
18653 | ||||
18654 | // Everything under here is trying to match an extract of a loaded value. | |||
18655 | // If the result of load has to be truncated, then it's not necessarily | |||
18656 | // profitable. | |||
18657 | bool BCNumEltsChanged = false; | |||
18658 | EVT ExtVT = VecVT.getVectorElementType(); | |||
18659 | EVT LVT = ExtVT; | |||
18660 | if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT)) | |||
18661 | return SDValue(); | |||
18662 | ||||
18663 | if (VecOp.getOpcode() == ISD::BITCAST) { | |||
18664 | // Don't duplicate a load with other uses. | |||
18665 | if (!VecOp.hasOneUse()) | |||
18666 | return SDValue(); | |||
18667 | ||||
18668 | EVT BCVT = VecOp.getOperand(0).getValueType(); | |||
18669 | if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) | |||
18670 | return SDValue(); | |||
18671 | if (NumElts != BCVT.getVectorNumElements()) | |||
18672 | BCNumEltsChanged = true; | |||
18673 | VecOp = VecOp.getOperand(0); | |||
18674 | ExtVT = BCVT.getVectorElementType(); | |||
18675 | } | |||
18676 | ||||
18677 | // extract (vector load $addr), i --> load $addr + i * size | |||
18678 | if (!LegalOperations && !IndexC && VecOp.hasOneUse() && | |||
18679 | ISD::isNormalLoad(VecOp.getNode()) && | |||
18680 | !Index->hasPredecessor(VecOp.getNode())) { | |||
18681 | auto *VecLoad = dyn_cast<LoadSDNode>(VecOp); | |||
18682 | if (VecLoad && VecLoad->isSimple()) | |||
18683 | return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad); | |||
18684 | } | |||
18685 | ||||
18686 | // Perform only after legalization to ensure build_vector / vector_shuffle | |||
18687 | // optimizations have already been done. | |||
18688 | if (!LegalOperations || !IndexC) | |||
18689 | return SDValue(); | |||
18690 | ||||
18691 | // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) | |||
18692 | // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) | |||
18693 | // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) | |||
18694 | int Elt = IndexC->getZExtValue(); | |||
18695 | LoadSDNode *LN0 = nullptr; | |||
18696 | if (ISD::isNormalLoad(VecOp.getNode())) { | |||
18697 | LN0 = cast<LoadSDNode>(VecOp); | |||
18698 | } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR && | |||
18699 | VecOp.getOperand(0).getValueType() == ExtVT && | |||
18700 | ISD::isNormalLoad(VecOp.getOperand(0).getNode())) { | |||
18701 | // Don't duplicate a load with other uses. | |||
18702 | if (!VecOp.hasOneUse()) | |||
18703 | return SDValue(); | |||
18704 | ||||
18705 | LN0 = cast<LoadSDNode>(VecOp.getOperand(0)); | |||
18706 | } | |||
18707 | if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) { | |||
18708 | // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) | |||
18709 | // => | |||
18710 | // (load $addr+1*size) | |||
18711 | ||||
18712 | // Don't duplicate a load with other uses. | |||
18713 | if (!VecOp.hasOneUse()) | |||
18714 | return SDValue(); | |||
18715 | ||||
18716 | // If the bit convert changed the number of elements, it is unsafe | |||
18717 | // to examine the mask. | |||
18718 | if (BCNumEltsChanged) | |||
18719 | return SDValue(); | |||
18720 | ||||
18721 | // Select the input vector, guarding against out of range extract vector. | |||
18722 | int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt); | |||
18723 | VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1); | |||
18724 | ||||
18725 | if (VecOp.getOpcode() == ISD::BITCAST) { | |||
18726 | // Don't duplicate a load with other uses. | |||
18727 | if (!VecOp.hasOneUse()) | |||
18728 | return SDValue(); | |||
18729 | ||||
18730 | VecOp = VecOp.getOperand(0); | |||
18731 | } | |||
18732 | if (ISD::isNormalLoad(VecOp.getNode())) { | |||
18733 | LN0 = cast<LoadSDNode>(VecOp); | |||
18734 | Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts; | |||
18735 | Index = DAG.getConstant(Elt, DL, Index.getValueType()); | |||
18736 | } | |||
18737 | } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS && !BCNumEltsChanged && | |||
18738 | VecVT.getVectorElementType() == ScalarVT && | |||
18739 | (!LegalTypes || | |||
18740 | TLI.isTypeLegal( | |||
18741 | VecOp.getOperand(0).getValueType().getVectorElementType()))) { | |||
18742 | // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0 | |||
18743 | // -> extract_vector_elt a, 0 | |||
18744 | // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1 | |||
18745 | // -> extract_vector_elt a, 1 | |||
18746 | // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2 | |||
18747 | // -> extract_vector_elt b, 0 | |||
18748 | // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3 | |||
18749 | // -> extract_vector_elt b, 1 | |||
18750 | SDLoc SL(N); | |||
18751 | EVT ConcatVT = VecOp.getOperand(0).getValueType(); | |||
18752 | unsigned ConcatNumElts = ConcatVT.getVectorNumElements(); | |||
18753 | SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL, | |||
18754 | Index.getValueType()); | |||
18755 | ||||
18756 | SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts); | |||
18757 | SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, | |||
18758 | ConcatVT.getVectorElementType(), | |||
18759 | ConcatOp, NewIdx); | |||
18760 | return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt); | |||
18761 | } | |||
18762 | ||||
18763 | // Make sure we found a non-volatile load and the extractelement is | |||
18764 | // the only use. | |||
18765 | if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple()) | |||
18766 | return SDValue(); | |||
18767 | ||||
18768 | // If Idx was -1 above, Elt is going to be -1, so just return undef. | |||
18769 | if (Elt == -1) | |||
18770 | return DAG.getUNDEF(LVT); | |||
18771 | ||||
18772 | return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0); | |||
18773 | } | |||
18774 | ||||
18775 | // Simplify (build_vec (ext )) to (bitcast (build_vec )) | |||
18776 | SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { | |||
18777 | // We perform this optimization post type-legalization because | |||
18778 | // the type-legalizer often scalarizes integer-promoted vectors. | |||
18779 | // Performing this optimization before may create bit-casts which | |||
18780 | // will be type-legalized to complex code sequences. | |||
18781 | // We perform this optimization only before the operation legalizer because we | |||
18782 | // may introduce illegal operations. | |||
18783 | if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) | |||
18784 | return SDValue(); | |||
18785 | ||||
18786 | unsigned NumInScalars = N->getNumOperands(); | |||
18787 | SDLoc DL(N); | |||
18788 | EVT VT = N->getValueType(0); | |||
18789 | ||||
18790 | // Check to see if this is a BUILD_VECTOR of a bunch of values | |||
18791 | // which come from any_extend or zero_extend nodes. If so, we can create | |||
18792 | // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR | |||
18793 | // optimizations. We do not handle sign-extend because we can't fill the sign | |||
18794 | // using shuffles. | |||
18795 | EVT SourceType = MVT::Other; | |||
18796 | bool AllAnyExt = true; | |||
18797 | ||||
18798 | for (unsigned i = 0; i != NumInScalars; ++i) { | |||
18799 | SDValue In = N->getOperand(i); | |||
18800 | // Ignore undef inputs. | |||
18801 | if (In.isUndef()) continue; | |||
18802 | ||||
18803 | bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; | |||
18804 | bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; | |||
18805 | ||||
18806 | // Abort if the element is not an extension. | |||
18807 | if (!ZeroExt && !AnyExt) { | |||
18808 | SourceType = MVT::Other; | |||
18809 | break; | |||
18810 | } | |||
18811 | ||||
18812 | // The input is a ZeroExt or AnyExt. Check the original type. | |||
18813 | EVT InTy = In.getOperand(0).getValueType(); | |||
18814 | ||||
18815 | // Check that all of the widened source types are the same. | |||
18816 | if (SourceType == MVT::Other) | |||
18817 | // First time. | |||
18818 | SourceType = InTy; | |||
18819 | else if (InTy != SourceType) { | |||
18820 | // Multiple income types. Abort. | |||
18821 | SourceType = MVT::Other; | |||
18822 | break; | |||
18823 | } | |||
18824 | ||||
18825 | // Check if all of the extends are ANY_EXTENDs. | |||
18826 | AllAnyExt &= AnyExt; | |||
18827 | } | |||
18828 | ||||
18829 | // In order to have valid types, all of the inputs must be extended from the | |||
18830 | // same source type and all of the inputs must be any or zero extend. | |||
18831 | // Scalar sizes must be a power of two. | |||
18832 | EVT OutScalarTy = VT.getScalarType(); | |||
18833 | bool ValidTypes = SourceType != MVT::Other && | |||
18834 | isPowerOf2_32(OutScalarTy.getSizeInBits()) && | |||
18835 | isPowerOf2_32(SourceType.getSizeInBits()); | |||
18836 | ||||
18837 | // Create a new simpler BUILD_VECTOR sequence which other optimizations can | |||
18838 | // turn into a single shuffle instruction. | |||
18839 | if (!ValidTypes) | |||
18840 | return SDValue(); | |||
18841 | ||||
18842 | // If we already have a splat buildvector, then don't fold it if it means | |||
18843 | // introducing zeros. | |||
18844 | if (!AllAnyExt && DAG.isSplatValue(SDValue(N, 0), /*AllowUndefs*/ true)) | |||
18845 | return SDValue(); | |||
18846 | ||||
18847 | bool isLE = DAG.getDataLayout().isLittleEndian(); | |||
18848 | unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); | |||
18849 | assert(ElemRatio > 1 && "Invalid element size ratio")((ElemRatio > 1 && "Invalid element size ratio") ? static_cast<void> (0) : __assert_fail ("ElemRatio > 1 && \"Invalid element size ratio\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18849, __PRETTY_FUNCTION__)); | |||
18850 | SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): | |||
18851 | DAG.getConstant(0, DL, SourceType); | |||
18852 | ||||
18853 | unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); | |||
18854 | SmallVector<SDValue, 8> Ops(NewBVElems, Filler); | |||
18855 | ||||
18856 | // Populate the new build_vector | |||
18857 | for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { | |||
18858 | SDValue Cast = N->getOperand(i); | |||
18859 | assert((Cast.getOpcode() == ISD::ANY_EXTEND ||(((Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && "Invalid cast opcode" ) ? static_cast<void> (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18861, __PRETTY_FUNCTION__)) | |||
18860 | Cast.getOpcode() == ISD::ZERO_EXTEND ||(((Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && "Invalid cast opcode" ) ? static_cast<void> (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18861, __PRETTY_FUNCTION__)) | |||
18861 | Cast.isUndef()) && "Invalid cast opcode")(((Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && "Invalid cast opcode" ) ? static_cast<void> (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18861, __PRETTY_FUNCTION__)); | |||
18862 | SDValue In; | |||
18863 | if (Cast.isUndef()) | |||
18864 | In = DAG.getUNDEF(SourceType); | |||
18865 | else | |||
18866 | In = Cast->getOperand(0); | |||
18867 | unsigned Index = isLE ? (i * ElemRatio) : | |||
18868 | (i * ElemRatio + (ElemRatio - 1)); | |||
18869 | ||||
18870 | assert(Index < Ops.size() && "Invalid index")((Index < Ops.size() && "Invalid index") ? static_cast <void> (0) : __assert_fail ("Index < Ops.size() && \"Invalid index\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18870, __PRETTY_FUNCTION__)); | |||
18871 | Ops[Index] = In; | |||
18872 | } | |||
18873 | ||||
18874 | // The type of the new BUILD_VECTOR node. | |||
18875 | EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); | |||
18876 | assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&((VecVT.getSizeInBits() == VT.getSizeInBits() && "Invalid vector size" ) ? static_cast<void> (0) : __assert_fail ("VecVT.getSizeInBits() == VT.getSizeInBits() && \"Invalid vector size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18877, __PRETTY_FUNCTION__)) | |||
18877 | "Invalid vector size")((VecVT.getSizeInBits() == VT.getSizeInBits() && "Invalid vector size" ) ? static_cast<void> (0) : __assert_fail ("VecVT.getSizeInBits() == VT.getSizeInBits() && \"Invalid vector size\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18877, __PRETTY_FUNCTION__)); | |||
18878 | // Check if the new vector type is legal. | |||
18879 | if (!isTypeLegal(VecVT) || | |||
18880 | (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && | |||
18881 | TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) | |||
18882 | return SDValue(); | |||
18883 | ||||
18884 | // Make the new BUILD_VECTOR. | |||
18885 | SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); | |||
18886 | ||||
18887 | // The new BUILD_VECTOR node has the potential to be further optimized. | |||
18888 | AddToWorklist(BV.getNode()); | |||
18889 | // Bitcast to the desired type. | |||
18890 | return DAG.getBitcast(VT, BV); | |||
18891 | } | |||
18892 | ||||
18893 | // Simplify (build_vec (trunc $1) | |||
18894 | // (trunc (srl $1 half-width)) | |||
18895 | // (trunc (srl $1 (2 * half-width))) …) | |||
18896 | // to (bitcast $1) | |||
18897 | SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) { | |||
18898 | assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector")((N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Expected build vector\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18898, __PRETTY_FUNCTION__)); | |||
18899 | ||||
18900 | // Only for little endian | |||
18901 | if (!DAG.getDataLayout().isLittleEndian()) | |||
18902 | return SDValue(); | |||
18903 | ||||
18904 | SDLoc DL(N); | |||
18905 | EVT VT = N->getValueType(0); | |||
18906 | EVT OutScalarTy = VT.getScalarType(); | |||
18907 | uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits(); | |||
18908 | ||||
18909 | // Only for power of two types to be sure that bitcast works well | |||
18910 | if (!isPowerOf2_64(ScalarTypeBitsize)) | |||
18911 | return SDValue(); | |||
18912 | ||||
18913 | unsigned NumInScalars = N->getNumOperands(); | |||
18914 | ||||
18915 | // Look through bitcasts | |||
18916 | auto PeekThroughBitcast = [](SDValue Op) { | |||
18917 | if (Op.getOpcode() == ISD::BITCAST) | |||
18918 | return Op.getOperand(0); | |||
18919 | return Op; | |||
18920 | }; | |||
18921 | ||||
18922 | // The source value where all the parts are extracted. | |||
18923 | SDValue Src; | |||
18924 | for (unsigned i = 0; i != NumInScalars; ++i) { | |||
18925 | SDValue In = PeekThroughBitcast(N->getOperand(i)); | |||
18926 | // Ignore undef inputs. | |||
18927 | if (In.isUndef()) continue; | |||
18928 | ||||
18929 | if (In.getOpcode() != ISD::TRUNCATE) | |||
18930 | return SDValue(); | |||
18931 | ||||
18932 | In = PeekThroughBitcast(In.getOperand(0)); | |||
18933 | ||||
18934 | if (In.getOpcode() != ISD::SRL) { | |||
18935 | // For now only build_vec without shuffling, handle shifts here in the | |||
18936 | // future. | |||
18937 | if (i != 0) | |||
18938 | return SDValue(); | |||
18939 | ||||
18940 | Src = In; | |||
18941 | } else { | |||
18942 | // In is SRL | |||
18943 | SDValue part = PeekThroughBitcast(In.getOperand(0)); | |||
18944 | ||||
18945 | if (!Src) { | |||
18946 | Src = part; | |||
18947 | } else if (Src != part) { | |||
18948 | // Vector parts do not stem from the same variable | |||
18949 | return SDValue(); | |||
18950 | } | |||
18951 | ||||
18952 | SDValue ShiftAmtVal = In.getOperand(1); | |||
18953 | if (!isa<ConstantSDNode>(ShiftAmtVal)) | |||
18954 | return SDValue(); | |||
18955 | ||||
18956 | uint64_t ShiftAmt = In.getNode()->getConstantOperandVal(1); | |||
18957 | ||||
18958 | // The extracted value is not extracted at the right position | |||
18959 | if (ShiftAmt != i * ScalarTypeBitsize) | |||
18960 | return SDValue(); | |||
18961 | } | |||
18962 | } | |||
18963 | ||||
18964 | // Only cast if the size is the same | |||
18965 | if (Src.getValueType().getSizeInBits() != VT.getSizeInBits()) | |||
18966 | return SDValue(); | |||
18967 | ||||
18968 | return DAG.getBitcast(VT, Src); | |||
18969 | } | |||
18970 | ||||
18971 | SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, | |||
18972 | ArrayRef<int> VectorMask, | |||
18973 | SDValue VecIn1, SDValue VecIn2, | |||
18974 | unsigned LeftIdx, bool DidSplitVec) { | |||
18975 | SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL); | |||
18976 | ||||
18977 | EVT VT = N->getValueType(0); | |||
18978 | EVT InVT1 = VecIn1.getValueType(); | |||
18979 | EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; | |||
18980 | ||||
18981 | unsigned NumElems = VT.getVectorNumElements(); | |||
18982 | unsigned ShuffleNumElems = NumElems; | |||
18983 | ||||
18984 | // If we artificially split a vector in two already, then the offsets in the | |||
18985 | // operands will all be based off of VecIn1, even those in VecIn2. | |||
18986 | unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements(); | |||
18987 | ||||
18988 | uint64_t VTSize = VT.getFixedSizeInBits(); | |||
18989 | uint64_t InVT1Size = InVT1.getFixedSizeInBits(); | |||
18990 | uint64_t InVT2Size = InVT2.getFixedSizeInBits(); | |||
18991 | ||||
18992 | // We can't generate a shuffle node with mismatched input and output types. | |||
18993 | // Try to make the types match the type of the output. | |||
18994 | if (InVT1 != VT || InVT2 != VT) { | |||
18995 | if ((VTSize % InVT1Size == 0) && InVT1 == InVT2) { | |||
18996 | // If the output vector length is a multiple of both input lengths, | |||
18997 | // we can concatenate them and pad the rest with undefs. | |||
18998 | unsigned NumConcats = VTSize / InVT1Size; | |||
18999 | assert(NumConcats >= 2 && "Concat needs at least two inputs!")((NumConcats >= 2 && "Concat needs at least two inputs!" ) ? static_cast<void> (0) : __assert_fail ("NumConcats >= 2 && \"Concat needs at least two inputs!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 18999, __PRETTY_FUNCTION__)); | |||
19000 | SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); | |||
19001 | ConcatOps[0] = VecIn1; | |||
19002 | ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); | |||
19003 | VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); | |||
19004 | VecIn2 = SDValue(); | |||
19005 | } else if (InVT1Size == VTSize * 2) { | |||
19006 | if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) | |||
19007 | return SDValue(); | |||
19008 | ||||
19009 | if (!VecIn2.getNode()) { | |||
19010 | // If we only have one input vector, and it's twice the size of the | |||
19011 | // output, split it in two. | |||
19012 | VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, | |||
19013 | DAG.getVectorIdxConstant(NumElems, DL)); | |||
19014 | VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); | |||
19015 | // Since we now have shorter input vectors, adjust the offset of the | |||
19016 | // second vector's start. | |||
19017 | Vec2Offset = NumElems; | |||
19018 | } else if (InVT2Size <= InVT1Size) { | |||
19019 | // VecIn1 is wider than the output, and we have another, possibly | |||
19020 | // smaller input. Pad the smaller input with undefs, shuffle at the | |||
19021 | // input vector width, and extract the output. | |||
19022 | // The shuffle type is different than VT, so check legality again. | |||
19023 | if (LegalOperations && | |||
19024 | !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) | |||
19025 | return SDValue(); | |||
19026 | ||||
19027 | // Legalizing INSERT_SUBVECTOR is tricky - you basically have to | |||
19028 | // lower it back into a BUILD_VECTOR. So if the inserted type is | |||
19029 | // illegal, don't even try. | |||
19030 | if (InVT1 != InVT2) { | |||
19031 | if (!TLI.isTypeLegal(InVT2)) | |||
19032 | return SDValue(); | |||
19033 | VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, | |||
19034 | DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); | |||
19035 | } | |||
19036 | ShuffleNumElems = NumElems * 2; | |||
19037 | } else { | |||
19038 | // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider | |||
19039 | // than VecIn1. We can't handle this for now - this case will disappear | |||
19040 | // when we start sorting the vectors by type. | |||
19041 | return SDValue(); | |||
19042 | } | |||
19043 | } else if (InVT2Size * 2 == VTSize && InVT1Size == VTSize) { | |||
19044 | SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); | |||
19045 | ConcatOps[0] = VecIn2; | |||
19046 | VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); | |||
19047 | } else { | |||
19048 | // TODO: Support cases where the length mismatch isn't exactly by a | |||
19049 | // factor of 2. | |||
19050 | // TODO: Move this check upwards, so that if we have bad type | |||
19051 | // mismatches, we don't create any DAG nodes. | |||
19052 | return SDValue(); | |||
19053 | } | |||
19054 | } | |||
19055 | ||||
19056 | // Initialize mask to undef. | |||
19057 | SmallVector<int, 8> Mask(ShuffleNumElems, -1); | |||
19058 | ||||
19059 | // Only need to run up to the number of elements actually used, not the | |||
19060 | // total number of elements in the shuffle - if we are shuffling a wider | |||
19061 | // vector, the high lanes should be set to undef. | |||
19062 | for (unsigned i = 0; i != NumElems; ++i) { | |||
19063 | if (VectorMask[i] <= 0) | |||
19064 | continue; | |||
19065 | ||||
19066 | unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); | |||
19067 | if (VectorMask[i] == (int)LeftIdx) { | |||
19068 | Mask[i] = ExtIndex; | |||
19069 | } else if (VectorMask[i] == (int)LeftIdx + 1) { | |||
19070 | Mask[i] = Vec2Offset + ExtIndex; | |||
19071 | } | |||
19072 | } | |||
19073 | ||||
19074 | // The type the input vectors may have changed above. | |||
19075 | InVT1 = VecIn1.getValueType(); | |||
19076 | ||||
19077 | // If we already have a VecIn2, it should have the same type as VecIn1. | |||
19078 | // If we don't, get an undef/zero vector of the appropriate type. | |||
19079 | VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); | |||
19080 | assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.")((InVT1 == VecIn2.getValueType() && "Unexpected second input type." ) ? static_cast<void> (0) : __assert_fail ("InVT1 == VecIn2.getValueType() && \"Unexpected second input type.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19080, __PRETTY_FUNCTION__)); | |||
19081 | ||||
19082 | SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); | |||
19083 | if (ShuffleNumElems > NumElems) | |||
19084 | Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); | |||
19085 | ||||
19086 | return Shuffle; | |||
19087 | } | |||
19088 | ||||
19089 | static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) { | |||
19090 | assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector")((BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector" ) ? static_cast<void> (0) : __assert_fail ("BV->getOpcode() == ISD::BUILD_VECTOR && \"Expected build vector\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19090, __PRETTY_FUNCTION__)); | |||
19091 | ||||
19092 | // First, determine where the build vector is not undef. | |||
19093 | // TODO: We could extend this to handle zero elements as well as undefs. | |||
19094 | int NumBVOps = BV->getNumOperands(); | |||
19095 | int ZextElt = -1; | |||
19096 | for (int i = 0; i != NumBVOps; ++i) { | |||
19097 | SDValue Op = BV->getOperand(i); | |||
19098 | if (Op.isUndef()) | |||
19099 | continue; | |||
19100 | if (ZextElt == -1) | |||
19101 | ZextElt = i; | |||
19102 | else | |||
19103 | return SDValue(); | |||
19104 | } | |||
19105 | // Bail out if there's no non-undef element. | |||
19106 | if (ZextElt == -1) | |||
19107 | return SDValue(); | |||
19108 | ||||
19109 | // The build vector contains some number of undef elements and exactly | |||
19110 | // one other element. That other element must be a zero-extended scalar | |||
19111 | // extracted from a vector at a constant index to turn this into a shuffle. | |||
19112 | // Also, require that the build vector does not implicitly truncate/extend | |||
19113 | // its elements. | |||
19114 | // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND. | |||
19115 | EVT VT = BV->getValueType(0); | |||
19116 | SDValue Zext = BV->getOperand(ZextElt); | |||
19117 | if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() || | |||
19118 | Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || | |||
19119 | !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) || | |||
19120 | Zext.getValueSizeInBits() != VT.getScalarSizeInBits()) | |||
19121 | return SDValue(); | |||
19122 | ||||
19123 | // The zero-extend must be a multiple of the source size, and we must be | |||
19124 | // building a vector of the same size as the source of the extract element. | |||
19125 | SDValue Extract = Zext.getOperand(0); | |||
19126 | unsigned DestSize = Zext.getValueSizeInBits(); | |||
19127 | unsigned SrcSize = Extract.getValueSizeInBits(); | |||
19128 | if (DestSize % SrcSize != 0 || | |||
19129 | Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits()) | |||
19130 | return SDValue(); | |||
19131 | ||||
19132 | // Create a shuffle mask that will combine the extracted element with zeros | |||
19133 | // and undefs. | |||
19134 | int ZextRatio = DestSize / SrcSize; | |||
19135 | int NumMaskElts = NumBVOps * ZextRatio; | |||
19136 | SmallVector<int, 32> ShufMask(NumMaskElts, -1); | |||
19137 | for (int i = 0; i != NumMaskElts; ++i) { | |||
19138 | if (i / ZextRatio == ZextElt) { | |||
19139 | // The low bits of the (potentially translated) extracted element map to | |||
19140 | // the source vector. The high bits map to zero. We will use a zero vector | |||
19141 | // as the 2nd source operand of the shuffle, so use the 1st element of | |||
19142 | // that vector (mask value is number-of-elements) for the high bits. | |||
19143 | if (i % ZextRatio == 0) | |||
19144 | ShufMask[i] = Extract.getConstantOperandVal(1); | |||
19145 | else | |||
19146 | ShufMask[i] = NumMaskElts; | |||
19147 | } | |||
19148 | ||||
19149 | // Undef elements of the build vector remain undef because we initialize | |||
19150 | // the shuffle mask with -1. | |||
19151 | } | |||
19152 | ||||
19153 | // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... --> | |||
19154 | // bitcast (shuffle V, ZeroVec, VectorMask) | |||
19155 | SDLoc DL(BV); | |||
19156 | EVT VecVT = Extract.getOperand(0).getValueType(); | |||
19157 | SDValue ZeroVec = DAG.getConstant(0, DL, VecVT); | |||
19158 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19159 | SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0), | |||
19160 | ZeroVec, ShufMask, DAG); | |||
19161 | if (!Shuf) | |||
19162 | return SDValue(); | |||
19163 | return DAG.getBitcast(VT, Shuf); | |||
19164 | } | |||
19165 | ||||
19166 | // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT | |||
19167 | // operations. If the types of the vectors we're extracting from allow it, | |||
19168 | // turn this into a vector_shuffle node. | |||
19169 | SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { | |||
19170 | SDLoc DL(N); | |||
19171 | EVT VT = N->getValueType(0); | |||
19172 | ||||
19173 | // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. | |||
19174 | if (!isTypeLegal(VT)) | |||
19175 | return SDValue(); | |||
19176 | ||||
19177 | if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG)) | |||
19178 | return V; | |||
19179 | ||||
19180 | // May only combine to shuffle after legalize if shuffle is legal. | |||
19181 | if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) | |||
19182 | return SDValue(); | |||
19183 | ||||
19184 | bool UsesZeroVector = false; | |||
19185 | unsigned NumElems = N->getNumOperands(); | |||
19186 | ||||
19187 | // Record, for each element of the newly built vector, which input vector | |||
19188 | // that element comes from. -1 stands for undef, 0 for the zero vector, | |||
19189 | // and positive values for the input vectors. | |||
19190 | // VectorMask maps each element to its vector number, and VecIn maps vector | |||
19191 | // numbers to their initial SDValues. | |||
19192 | ||||
19193 | SmallVector<int, 8> VectorMask(NumElems, -1); | |||
19194 | SmallVector<SDValue, 8> VecIn; | |||
19195 | VecIn.push_back(SDValue()); | |||
19196 | ||||
19197 | for (unsigned i = 0; i != NumElems; ++i) { | |||
19198 | SDValue Op = N->getOperand(i); | |||
19199 | ||||
19200 | if (Op.isUndef()) | |||
19201 | continue; | |||
19202 | ||||
19203 | // See if we can use a blend with a zero vector. | |||
19204 | // TODO: Should we generalize this to a blend with an arbitrary constant | |||
19205 | // vector? | |||
19206 | if (isNullConstant(Op) || isNullFPConstant(Op)) { | |||
19207 | UsesZeroVector = true; | |||
19208 | VectorMask[i] = 0; | |||
19209 | continue; | |||
19210 | } | |||
19211 | ||||
19212 | // Not an undef or zero. If the input is something other than an | |||
19213 | // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. | |||
19214 | if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || | |||
19215 | !isa<ConstantSDNode>(Op.getOperand(1))) | |||
19216 | return SDValue(); | |||
19217 | SDValue ExtractedFromVec = Op.getOperand(0); | |||
19218 | ||||
19219 | if (ExtractedFromVec.getValueType().isScalableVector()) | |||
19220 | return SDValue(); | |||
19221 | ||||
19222 | const APInt &ExtractIdx = Op.getConstantOperandAPInt(1); | |||
19223 | if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) | |||
19224 | return SDValue(); | |||
19225 | ||||
19226 | // All inputs must have the same element type as the output. | |||
19227 | if (VT.getVectorElementType() != | |||
19228 | ExtractedFromVec.getValueType().getVectorElementType()) | |||
19229 | return SDValue(); | |||
19230 | ||||
19231 | // Have we seen this input vector before? | |||
19232 | // The vectors are expected to be tiny (usually 1 or 2 elements), so using | |||
19233 | // a map back from SDValues to numbers isn't worth it. | |||
19234 | unsigned Idx = std::distance(VecIn.begin(), find(VecIn, ExtractedFromVec)); | |||
19235 | if (Idx == VecIn.size()) | |||
19236 | VecIn.push_back(ExtractedFromVec); | |||
19237 | ||||
19238 | VectorMask[i] = Idx; | |||
19239 | } | |||
19240 | ||||
19241 | // If we didn't find at least one input vector, bail out. | |||
19242 | if (VecIn.size() < 2) | |||
19243 | return SDValue(); | |||
19244 | ||||
19245 | // If all the Operands of BUILD_VECTOR extract from same | |||
19246 | // vector, then split the vector efficiently based on the maximum | |||
19247 | // vector access index and adjust the VectorMask and | |||
19248 | // VecIn accordingly. | |||
19249 | bool DidSplitVec = false; | |||
19250 | if (VecIn.size() == 2) { | |||
19251 | unsigned MaxIndex = 0; | |||
19252 | unsigned NearestPow2 = 0; | |||
19253 | SDValue Vec = VecIn.back(); | |||
19254 | EVT InVT = Vec.getValueType(); | |||
19255 | SmallVector<unsigned, 8> IndexVec(NumElems, 0); | |||
19256 | ||||
19257 | for (unsigned i = 0; i < NumElems; i++) { | |||
19258 | if (VectorMask[i] <= 0) | |||
19259 | continue; | |||
19260 | unsigned Index = N->getOperand(i).getConstantOperandVal(1); | |||
19261 | IndexVec[i] = Index; | |||
19262 | MaxIndex = std::max(MaxIndex, Index); | |||
19263 | } | |||
19264 | ||||
19265 | NearestPow2 = PowerOf2Ceil(MaxIndex); | |||
19266 | if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && | |||
19267 | NumElems * 2 < NearestPow2) { | |||
19268 | unsigned SplitSize = NearestPow2 / 2; | |||
19269 | EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), | |||
19270 | InVT.getVectorElementType(), SplitSize); | |||
19271 | if (TLI.isTypeLegal(SplitVT)) { | |||
19272 | SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, | |||
19273 | DAG.getVectorIdxConstant(SplitSize, DL)); | |||
19274 | SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, | |||
19275 | DAG.getVectorIdxConstant(0, DL)); | |||
19276 | VecIn.pop_back(); | |||
19277 | VecIn.push_back(VecIn1); | |||
19278 | VecIn.push_back(VecIn2); | |||
19279 | DidSplitVec = true; | |||
19280 | ||||
19281 | for (unsigned i = 0; i < NumElems; i++) { | |||
19282 | if (VectorMask[i] <= 0) | |||
19283 | continue; | |||
19284 | VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; | |||
19285 | } | |||
19286 | } | |||
19287 | } | |||
19288 | } | |||
19289 | ||||
19290 | // TODO: We want to sort the vectors by descending length, so that adjacent | |||
19291 | // pairs have similar length, and the longer vector is always first in the | |||
19292 | // pair. | |||
19293 | ||||
19294 | // TODO: Should this fire if some of the input vectors has illegal type (like | |||
19295 | // it does now), or should we let legalization run its course first? | |||
19296 | ||||
19297 | // Shuffle phase: | |||
19298 | // Take pairs of vectors, and shuffle them so that the result has elements | |||
19299 | // from these vectors in the correct places. | |||
19300 | // For example, given: | |||
19301 | // t10: i32 = extract_vector_elt t1, Constant:i64<0> | |||
19302 | // t11: i32 = extract_vector_elt t2, Constant:i64<0> | |||
19303 | // t12: i32 = extract_vector_elt t3, Constant:i64<0> | |||
19304 | // t13: i32 = extract_vector_elt t1, Constant:i64<1> | |||
19305 | // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 | |||
19306 | // We will generate: | |||
19307 | // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 | |||
19308 | // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef | |||
19309 | SmallVector<SDValue, 4> Shuffles; | |||
19310 | for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { | |||
19311 | unsigned LeftIdx = 2 * In + 1; | |||
19312 | SDValue VecLeft = VecIn[LeftIdx]; | |||
19313 | SDValue VecRight = | |||
19314 | (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); | |||
19315 | ||||
19316 | if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, | |||
19317 | VecRight, LeftIdx, DidSplitVec)) | |||
19318 | Shuffles.push_back(Shuffle); | |||
19319 | else | |||
19320 | return SDValue(); | |||
19321 | } | |||
19322 | ||||
19323 | // If we need the zero vector as an "ingredient" in the blend tree, add it | |||
19324 | // to the list of shuffles. | |||
19325 | if (UsesZeroVector) | |||
19326 | Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) | |||
19327 | : DAG.getConstantFP(0.0, DL, VT)); | |||
19328 | ||||
19329 | // If we only have one shuffle, we're done. | |||
19330 | if (Shuffles.size() == 1) | |||
19331 | return Shuffles[0]; | |||
19332 | ||||
19333 | // Update the vector mask to point to the post-shuffle vectors. | |||
19334 | for (int &Vec : VectorMask) | |||
19335 | if (Vec == 0) | |||
19336 | Vec = Shuffles.size() - 1; | |||
19337 | else | |||
19338 | Vec = (Vec - 1) / 2; | |||
19339 | ||||
19340 | // More than one shuffle. Generate a binary tree of blends, e.g. if from | |||
19341 | // the previous step we got the set of shuffles t10, t11, t12, t13, we will | |||
19342 | // generate: | |||
19343 | // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 | |||
19344 | // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 | |||
19345 | // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 | |||
19346 | // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 | |||
19347 | // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 | |||
19348 | // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 | |||
19349 | // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 | |||
19350 | ||||
19351 | // Make sure the initial size of the shuffle list is even. | |||
19352 | if (Shuffles.size() % 2) | |||
19353 | Shuffles.push_back(DAG.getUNDEF(VT)); | |||
19354 | ||||
19355 | for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { | |||
19356 | if (CurSize % 2) { | |||
19357 | Shuffles[CurSize] = DAG.getUNDEF(VT); | |||
19358 | CurSize++; | |||
19359 | } | |||
19360 | for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { | |||
19361 | int Left = 2 * In; | |||
19362 | int Right = 2 * In + 1; | |||
19363 | SmallVector<int, 8> Mask(NumElems, -1); | |||
19364 | for (unsigned i = 0; i != NumElems; ++i) { | |||
19365 | if (VectorMask[i] == Left) { | |||
19366 | Mask[i] = i; | |||
19367 | VectorMask[i] = In; | |||
19368 | } else if (VectorMask[i] == Right) { | |||
19369 | Mask[i] = i + NumElems; | |||
19370 | VectorMask[i] = In; | |||
19371 | } | |||
19372 | } | |||
19373 | ||||
19374 | Shuffles[In] = | |||
19375 | DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); | |||
19376 | } | |||
19377 | } | |||
19378 | return Shuffles[0]; | |||
19379 | } | |||
19380 | ||||
19381 | // Try to turn a build vector of zero extends of extract vector elts into a | |||
19382 | // a vector zero extend and possibly an extract subvector. | |||
19383 | // TODO: Support sign extend? | |||
19384 | // TODO: Allow undef elements? | |||
19385 | SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { | |||
19386 | if (LegalOperations) | |||
19387 | return SDValue(); | |||
19388 | ||||
19389 | EVT VT = N->getValueType(0); | |||
19390 | ||||
19391 | bool FoundZeroExtend = false; | |||
19392 | SDValue Op0 = N->getOperand(0); | |||
19393 | auto checkElem = [&](SDValue Op) -> int64_t { | |||
19394 | unsigned Opc = Op.getOpcode(); | |||
19395 | FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND); | |||
19396 | if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) && | |||
19397 | Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
19398 | Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) | |||
19399 | if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) | |||
19400 | return C->getZExtValue(); | |||
19401 | return -1; | |||
19402 | }; | |||
19403 | ||||
19404 | // Make sure the first element matches | |||
19405 | // (zext (extract_vector_elt X, C)) | |||
19406 | int64_t Offset = checkElem(Op0); | |||
19407 | if (Offset < 0) | |||
19408 | return SDValue(); | |||
19409 | ||||
19410 | unsigned NumElems = N->getNumOperands(); | |||
19411 | SDValue In = Op0.getOperand(0).getOperand(0); | |||
19412 | EVT InSVT = In.getValueType().getScalarType(); | |||
19413 | EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); | |||
19414 | ||||
19415 | // Don't create an illegal input type after type legalization. | |||
19416 | if (LegalTypes && !TLI.isTypeLegal(InVT)) | |||
19417 | return SDValue(); | |||
19418 | ||||
19419 | // Ensure all the elements come from the same vector and are adjacent. | |||
19420 | for (unsigned i = 1; i != NumElems; ++i) { | |||
19421 | if ((Offset + i) != checkElem(N->getOperand(i))) | |||
19422 | return SDValue(); | |||
19423 | } | |||
19424 | ||||
19425 | SDLoc DL(N); | |||
19426 | In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, | |||
19427 | Op0.getOperand(0).getOperand(1)); | |||
19428 | return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL, | |||
19429 | VT, In); | |||
19430 | } | |||
19431 | ||||
19432 | SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { | |||
19433 | EVT VT = N->getValueType(0); | |||
19434 | ||||
19435 | // A vector built entirely of undefs is undef. | |||
19436 | if (ISD::allOperandsUndef(N)) | |||
19437 | return DAG.getUNDEF(VT); | |||
19438 | ||||
19439 | // If this is a splat of a bitcast from another vector, change to a | |||
19440 | // concat_vector. | |||
19441 | // For example: | |||
19442 | // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> | |||
19443 | // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) | |||
19444 | // | |||
19445 | // If X is a build_vector itself, the concat can become a larger build_vector. | |||
19446 | // TODO: Maybe this is useful for non-splat too? | |||
19447 | if (!LegalOperations) { | |||
19448 | if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { | |||
19449 | Splat = peekThroughBitcasts(Splat); | |||
19450 | EVT SrcVT = Splat.getValueType(); | |||
19451 | if (SrcVT.isVector()) { | |||
19452 | unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); | |||
19453 | EVT NewVT = EVT::getVectorVT(*DAG.getContext(), | |||
19454 | SrcVT.getVectorElementType(), NumElts); | |||
19455 | if (!LegalTypes || TLI.isTypeLegal(NewVT)) { | |||
19456 | SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); | |||
19457 | SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), | |||
19458 | NewVT, Ops); | |||
19459 | return DAG.getBitcast(VT, Concat); | |||
19460 | } | |||
19461 | } | |||
19462 | } | |||
19463 | } | |||
19464 | ||||
19465 | // A splat of a single element is a SPLAT_VECTOR if supported on the target. | |||
19466 | if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand) | |||
19467 | if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) { | |||
19468 | assert(!V.isUndef() && "Splat of undef should have been handled earlier")((!V.isUndef() && "Splat of undef should have been handled earlier" ) ? static_cast<void> (0) : __assert_fail ("!V.isUndef() && \"Splat of undef should have been handled earlier\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19468, __PRETTY_FUNCTION__)); | |||
19469 | return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V); | |||
19470 | } | |||
19471 | ||||
19472 | // Check if we can express BUILD VECTOR via subvector extract. | |||
19473 | if (!LegalTypes && (N->getNumOperands() > 1)) { | |||
19474 | SDValue Op0 = N->getOperand(0); | |||
19475 | auto checkElem = [&](SDValue Op) -> uint64_t { | |||
19476 | if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && | |||
19477 | (Op0.getOperand(0) == Op.getOperand(0))) | |||
19478 | if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) | |||
19479 | return CNode->getZExtValue(); | |||
19480 | return -1; | |||
19481 | }; | |||
19482 | ||||
19483 | int Offset = checkElem(Op0); | |||
19484 | for (unsigned i = 0; i < N->getNumOperands(); ++i) { | |||
19485 | if (Offset + i != checkElem(N->getOperand(i))) { | |||
19486 | Offset = -1; | |||
19487 | break; | |||
19488 | } | |||
19489 | } | |||
19490 | ||||
19491 | if ((Offset == 0) && | |||
19492 | (Op0.getOperand(0).getValueType() == N->getValueType(0))) | |||
19493 | return Op0.getOperand(0); | |||
19494 | if ((Offset != -1) && | |||
19495 | ((Offset % N->getValueType(0).getVectorNumElements()) == | |||
19496 | 0)) // IDX must be multiple of output size. | |||
19497 | return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), | |||
19498 | Op0.getOperand(0), Op0.getOperand(1)); | |||
19499 | } | |||
19500 | ||||
19501 | if (SDValue V = convertBuildVecZextToZext(N)) | |||
19502 | return V; | |||
19503 | ||||
19504 | if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) | |||
19505 | return V; | |||
19506 | ||||
19507 | if (SDValue V = reduceBuildVecTruncToBitCast(N)) | |||
19508 | return V; | |||
19509 | ||||
19510 | if (SDValue V = reduceBuildVecToShuffle(N)) | |||
19511 | return V; | |||
19512 | ||||
19513 | return SDValue(); | |||
19514 | } | |||
19515 | ||||
19516 | static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { | |||
19517 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19518 | EVT OpVT = N->getOperand(0).getValueType(); | |||
19519 | ||||
19520 | // If the operands are legal vectors, leave them alone. | |||
19521 | if (TLI.isTypeLegal(OpVT)) | |||
19522 | return SDValue(); | |||
19523 | ||||
19524 | SDLoc DL(N); | |||
19525 | EVT VT = N->getValueType(0); | |||
19526 | SmallVector<SDValue, 8> Ops; | |||
19527 | ||||
19528 | EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); | |||
19529 | SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); | |||
19530 | ||||
19531 | // Keep track of what we encounter. | |||
19532 | bool AnyInteger = false; | |||
19533 | bool AnyFP = false; | |||
19534 | for (const SDValue &Op : N->ops()) { | |||
19535 | if (ISD::BITCAST == Op.getOpcode() && | |||
19536 | !Op.getOperand(0).getValueType().isVector()) | |||
19537 | Ops.push_back(Op.getOperand(0)); | |||
19538 | else if (ISD::UNDEF == Op.getOpcode()) | |||
19539 | Ops.push_back(ScalarUndef); | |||
19540 | else | |||
19541 | return SDValue(); | |||
19542 | ||||
19543 | // Note whether we encounter an integer or floating point scalar. | |||
19544 | // If it's neither, bail out, it could be something weird like x86mmx. | |||
19545 | EVT LastOpVT = Ops.back().getValueType(); | |||
19546 | if (LastOpVT.isFloatingPoint()) | |||
19547 | AnyFP = true; | |||
19548 | else if (LastOpVT.isInteger()) | |||
19549 | AnyInteger = true; | |||
19550 | else | |||
19551 | return SDValue(); | |||
19552 | } | |||
19553 | ||||
19554 | // If any of the operands is a floating point scalar bitcast to a vector, | |||
19555 | // use floating point types throughout, and bitcast everything. | |||
19556 | // Replace UNDEFs by another scalar UNDEF node, of the final desired type. | |||
19557 | if (AnyFP) { | |||
19558 | SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); | |||
19559 | ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); | |||
19560 | if (AnyInteger) { | |||
19561 | for (SDValue &Op : Ops) { | |||
19562 | if (Op.getValueType() == SVT) | |||
19563 | continue; | |||
19564 | if (Op.isUndef()) | |||
19565 | Op = ScalarUndef; | |||
19566 | else | |||
19567 | Op = DAG.getBitcast(SVT, Op); | |||
19568 | } | |||
19569 | } | |||
19570 | } | |||
19571 | ||||
19572 | EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, | |||
19573 | VT.getSizeInBits() / SVT.getSizeInBits()); | |||
19574 | return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); | |||
19575 | } | |||
19576 | ||||
19577 | // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR | |||
19578 | // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at | |||
19579 | // most two distinct vectors the same size as the result, attempt to turn this | |||
19580 | // into a legal shuffle. | |||
19581 | static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { | |||
19582 | EVT VT = N->getValueType(0); | |||
19583 | EVT OpVT = N->getOperand(0).getValueType(); | |||
19584 | ||||
19585 | // We currently can't generate an appropriate shuffle for a scalable vector. | |||
19586 | if (VT.isScalableVector()) | |||
19587 | return SDValue(); | |||
19588 | ||||
19589 | int NumElts = VT.getVectorNumElements(); | |||
19590 | int NumOpElts = OpVT.getVectorNumElements(); | |||
19591 | ||||
19592 | SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); | |||
19593 | SmallVector<int, 8> Mask; | |||
19594 | ||||
19595 | for (SDValue Op : N->ops()) { | |||
19596 | Op = peekThroughBitcasts(Op); | |||
19597 | ||||
19598 | // UNDEF nodes convert to UNDEF shuffle mask values. | |||
19599 | if (Op.isUndef()) { | |||
19600 | Mask.append((unsigned)NumOpElts, -1); | |||
19601 | continue; | |||
19602 | } | |||
19603 | ||||
19604 | if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) | |||
19605 | return SDValue(); | |||
19606 | ||||
19607 | // What vector are we extracting the subvector from and at what index? | |||
19608 | SDValue ExtVec = Op.getOperand(0); | |||
19609 | int ExtIdx = Op.getConstantOperandVal(1); | |||
19610 | ||||
19611 | // We want the EVT of the original extraction to correctly scale the | |||
19612 | // extraction index. | |||
19613 | EVT ExtVT = ExtVec.getValueType(); | |||
19614 | ExtVec = peekThroughBitcasts(ExtVec); | |||
19615 | ||||
19616 | // UNDEF nodes convert to UNDEF shuffle mask values. | |||
19617 | if (ExtVec.isUndef()) { | |||
19618 | Mask.append((unsigned)NumOpElts, -1); | |||
19619 | continue; | |||
19620 | } | |||
19621 | ||||
19622 | // Ensure that we are extracting a subvector from a vector the same | |||
19623 | // size as the result. | |||
19624 | if (ExtVT.getSizeInBits() != VT.getSizeInBits()) | |||
19625 | return SDValue(); | |||
19626 | ||||
19627 | // Scale the subvector index to account for any bitcast. | |||
19628 | int NumExtElts = ExtVT.getVectorNumElements(); | |||
19629 | if (0 == (NumExtElts % NumElts)) | |||
19630 | ExtIdx /= (NumExtElts / NumElts); | |||
19631 | else if (0 == (NumElts % NumExtElts)) | |||
19632 | ExtIdx *= (NumElts / NumExtElts); | |||
19633 | else | |||
19634 | return SDValue(); | |||
19635 | ||||
19636 | // At most we can reference 2 inputs in the final shuffle. | |||
19637 | if (SV0.isUndef() || SV0 == ExtVec) { | |||
19638 | SV0 = ExtVec; | |||
19639 | for (int i = 0; i != NumOpElts; ++i) | |||
19640 | Mask.push_back(i + ExtIdx); | |||
19641 | } else if (SV1.isUndef() || SV1 == ExtVec) { | |||
19642 | SV1 = ExtVec; | |||
19643 | for (int i = 0; i != NumOpElts; ++i) | |||
19644 | Mask.push_back(i + ExtIdx + NumElts); | |||
19645 | } else { | |||
19646 | return SDValue(); | |||
19647 | } | |||
19648 | } | |||
19649 | ||||
19650 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19651 | return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), | |||
19652 | DAG.getBitcast(VT, SV1), Mask, DAG); | |||
19653 | } | |||
19654 | ||||
19655 | static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) { | |||
19656 | unsigned CastOpcode = N->getOperand(0).getOpcode(); | |||
19657 | switch (CastOpcode) { | |||
19658 | case ISD::SINT_TO_FP: | |||
19659 | case ISD::UINT_TO_FP: | |||
19660 | case ISD::FP_TO_SINT: | |||
19661 | case ISD::FP_TO_UINT: | |||
19662 | // TODO: Allow more opcodes? | |||
19663 | // case ISD::BITCAST: | |||
19664 | // case ISD::TRUNCATE: | |||
19665 | // case ISD::ZERO_EXTEND: | |||
19666 | // case ISD::SIGN_EXTEND: | |||
19667 | // case ISD::FP_EXTEND: | |||
19668 | break; | |||
19669 | default: | |||
19670 | return SDValue(); | |||
19671 | } | |||
19672 | ||||
19673 | EVT SrcVT = N->getOperand(0).getOperand(0).getValueType(); | |||
19674 | if (!SrcVT.isVector()) | |||
19675 | return SDValue(); | |||
19676 | ||||
19677 | // All operands of the concat must be the same kind of cast from the same | |||
19678 | // source type. | |||
19679 | SmallVector<SDValue, 4> SrcOps; | |||
19680 | for (SDValue Op : N->ops()) { | |||
19681 | if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() || | |||
19682 | Op.getOperand(0).getValueType() != SrcVT) | |||
19683 | return SDValue(); | |||
19684 | SrcOps.push_back(Op.getOperand(0)); | |||
19685 | } | |||
19686 | ||||
19687 | // The wider cast must be supported by the target. This is unusual because | |||
19688 | // the operation support type parameter depends on the opcode. In addition, | |||
19689 | // check the other type in the cast to make sure this is really legal. | |||
19690 | EVT VT = N->getValueType(0); | |||
19691 | EVT SrcEltVT = SrcVT.getVectorElementType(); | |||
19692 | ElementCount NumElts = SrcVT.getVectorElementCount() * N->getNumOperands(); | |||
19693 | EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts); | |||
19694 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19695 | switch (CastOpcode) { | |||
19696 | case ISD::SINT_TO_FP: | |||
19697 | case ISD::UINT_TO_FP: | |||
19698 | if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) || | |||
19699 | !TLI.isTypeLegal(VT)) | |||
19700 | return SDValue(); | |||
19701 | break; | |||
19702 | case ISD::FP_TO_SINT: | |||
19703 | case ISD::FP_TO_UINT: | |||
19704 | if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) || | |||
19705 | !TLI.isTypeLegal(ConcatSrcVT)) | |||
19706 | return SDValue(); | |||
19707 | break; | |||
19708 | default: | |||
19709 | llvm_unreachable("Unexpected cast opcode")::llvm::llvm_unreachable_internal("Unexpected cast opcode", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19709); | |||
19710 | } | |||
19711 | ||||
19712 | // concat (cast X), (cast Y)... -> cast (concat X, Y...) | |||
19713 | SDLoc DL(N); | |||
19714 | SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps); | |||
19715 | return DAG.getNode(CastOpcode, DL, VT, NewConcat); | |||
19716 | } | |||
19717 | ||||
19718 | SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { | |||
19719 | // If we only have one input vector, we don't need to do any concatenation. | |||
19720 | if (N->getNumOperands() == 1) | |||
19721 | return N->getOperand(0); | |||
19722 | ||||
19723 | // Check if all of the operands are undefs. | |||
19724 | EVT VT = N->getValueType(0); | |||
19725 | if (ISD::allOperandsUndef(N)) | |||
19726 | return DAG.getUNDEF(VT); | |||
19727 | ||||
19728 | // Optimize concat_vectors where all but the first of the vectors are undef. | |||
19729 | if (all_of(drop_begin(N->ops()), | |||
19730 | [](const SDValue &Op) { return Op.isUndef(); })) { | |||
19731 | SDValue In = N->getOperand(0); | |||
19732 | assert(In.getValueType().isVector() && "Must concat vectors")((In.getValueType().isVector() && "Must concat vectors" ) ? static_cast<void> (0) : __assert_fail ("In.getValueType().isVector() && \"Must concat vectors\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19732, __PRETTY_FUNCTION__)); | |||
19733 | ||||
19734 | // If the input is a concat_vectors, just make a larger concat by padding | |||
19735 | // with smaller undefs. | |||
19736 | if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) { | |||
19737 | unsigned NumOps = N->getNumOperands() * In.getNumOperands(); | |||
19738 | SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end()); | |||
19739 | Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType())); | |||
19740 | return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); | |||
19741 | } | |||
19742 | ||||
19743 | SDValue Scalar = peekThroughOneUseBitcasts(In); | |||
19744 | ||||
19745 | // concat_vectors(scalar_to_vector(scalar), undef) -> | |||
19746 | // scalar_to_vector(scalar) | |||
19747 | if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR && | |||
19748 | Scalar.hasOneUse()) { | |||
19749 | EVT SVT = Scalar.getValueType().getVectorElementType(); | |||
19750 | if (SVT == Scalar.getOperand(0).getValueType()) | |||
19751 | Scalar = Scalar.getOperand(0); | |||
19752 | } | |||
19753 | ||||
19754 | // concat_vectors(scalar, undef) -> scalar_to_vector(scalar) | |||
19755 | if (!Scalar.getValueType().isVector()) { | |||
19756 | // If the bitcast type isn't legal, it might be a trunc of a legal type; | |||
19757 | // look through the trunc so we can still do the transform: | |||
19758 | // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) | |||
19759 | if (Scalar->getOpcode() == ISD::TRUNCATE && | |||
19760 | !TLI.isTypeLegal(Scalar.getValueType()) && | |||
19761 | TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) | |||
19762 | Scalar = Scalar->getOperand(0); | |||
19763 | ||||
19764 | EVT SclTy = Scalar.getValueType(); | |||
19765 | ||||
19766 | if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) | |||
19767 | return SDValue(); | |||
19768 | ||||
19769 | // Bail out if the vector size is not a multiple of the scalar size. | |||
19770 | if (VT.getSizeInBits() % SclTy.getSizeInBits()) | |||
19771 | return SDValue(); | |||
19772 | ||||
19773 | unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); | |||
19774 | if (VNTNumElms < 2) | |||
19775 | return SDValue(); | |||
19776 | ||||
19777 | EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); | |||
19778 | if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) | |||
19779 | return SDValue(); | |||
19780 | ||||
19781 | SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); | |||
19782 | return DAG.getBitcast(VT, Res); | |||
19783 | } | |||
19784 | } | |||
19785 | ||||
19786 | // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. | |||
19787 | // We have already tested above for an UNDEF only concatenation. | |||
19788 | // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) | |||
19789 | // -> (BUILD_VECTOR A, B, ..., C, D, ...) | |||
19790 | auto IsBuildVectorOrUndef = [](const SDValue &Op) { | |||
19791 | return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); | |||
19792 | }; | |||
19793 | if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { | |||
19794 | SmallVector<SDValue, 8> Opnds; | |||
19795 | EVT SVT = VT.getScalarType(); | |||
19796 | ||||
19797 | EVT MinVT = SVT; | |||
19798 | if (!SVT.isFloatingPoint()) { | |||
19799 | // If BUILD_VECTOR are from built from integer, they may have different | |||
19800 | // operand types. Get the smallest type and truncate all operands to it. | |||
19801 | bool FoundMinVT = false; | |||
19802 | for (const SDValue &Op : N->ops()) | |||
19803 | if (ISD::BUILD_VECTOR == Op.getOpcode()) { | |||
19804 | EVT OpSVT = Op.getOperand(0).getValueType(); | |||
19805 | MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; | |||
19806 | FoundMinVT = true; | |||
19807 | } | |||
19808 | assert(FoundMinVT && "Concat vector type mismatch")((FoundMinVT && "Concat vector type mismatch") ? static_cast <void> (0) : __assert_fail ("FoundMinVT && \"Concat vector type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19808, __PRETTY_FUNCTION__)); | |||
19809 | } | |||
19810 | ||||
19811 | for (const SDValue &Op : N->ops()) { | |||
19812 | EVT OpVT = Op.getValueType(); | |||
19813 | unsigned NumElts = OpVT.getVectorNumElements(); | |||
19814 | ||||
19815 | if (ISD::UNDEF == Op.getOpcode()) | |||
19816 | Opnds.append(NumElts, DAG.getUNDEF(MinVT)); | |||
19817 | ||||
19818 | if (ISD::BUILD_VECTOR == Op.getOpcode()) { | |||
19819 | if (SVT.isFloatingPoint()) { | |||
19820 | assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch")((SVT == OpVT.getScalarType() && "Concat vector type mismatch" ) ? static_cast<void> (0) : __assert_fail ("SVT == OpVT.getScalarType() && \"Concat vector type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19820, __PRETTY_FUNCTION__)); | |||
19821 | Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); | |||
19822 | } else { | |||
19823 | for (unsigned i = 0; i != NumElts; ++i) | |||
19824 | Opnds.push_back( | |||
19825 | DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); | |||
19826 | } | |||
19827 | } | |||
19828 | } | |||
19829 | ||||
19830 | assert(VT.getVectorNumElements() == Opnds.size() &&((VT.getVectorNumElements() == Opnds.size() && "Concat vector type mismatch" ) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == Opnds.size() && \"Concat vector type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19831, __PRETTY_FUNCTION__)) | |||
19831 | "Concat vector type mismatch")((VT.getVectorNumElements() == Opnds.size() && "Concat vector type mismatch" ) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == Opnds.size() && \"Concat vector type mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19831, __PRETTY_FUNCTION__)); | |||
19832 | return DAG.getBuildVector(VT, SDLoc(N), Opnds); | |||
19833 | } | |||
19834 | ||||
19835 | // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. | |||
19836 | if (SDValue V = combineConcatVectorOfScalars(N, DAG)) | |||
19837 | return V; | |||
19838 | ||||
19839 | // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. | |||
19840 | if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) | |||
19841 | if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) | |||
19842 | return V; | |||
19843 | ||||
19844 | if (SDValue V = combineConcatVectorOfCasts(N, DAG)) | |||
19845 | return V; | |||
19846 | ||||
19847 | // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR | |||
19848 | // nodes often generate nop CONCAT_VECTOR nodes. Scan the CONCAT_VECTOR | |||
19849 | // operands and look for a CONCAT operations that place the incoming vectors | |||
19850 | // at the exact same location. | |||
19851 | // | |||
19852 | // For scalable vectors, EXTRACT_SUBVECTOR indexes are implicitly scaled. | |||
19853 | SDValue SingleSource = SDValue(); | |||
19854 | unsigned PartNumElem = | |||
19855 | N->getOperand(0).getValueType().getVectorMinNumElements(); | |||
19856 | ||||
19857 | for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { | |||
19858 | SDValue Op = N->getOperand(i); | |||
19859 | ||||
19860 | if (Op.isUndef()) | |||
19861 | continue; | |||
19862 | ||||
19863 | // Check if this is the identity extract: | |||
19864 | if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) | |||
19865 | return SDValue(); | |||
19866 | ||||
19867 | // Find the single incoming vector for the extract_subvector. | |||
19868 | if (SingleSource.getNode()) { | |||
19869 | if (Op.getOperand(0) != SingleSource) | |||
19870 | return SDValue(); | |||
19871 | } else { | |||
19872 | SingleSource = Op.getOperand(0); | |||
19873 | ||||
19874 | // Check the source type is the same as the type of the result. | |||
19875 | // If not, this concat may extend the vector, so we can not | |||
19876 | // optimize it away. | |||
19877 | if (SingleSource.getValueType() != N->getValueType(0)) | |||
19878 | return SDValue(); | |||
19879 | } | |||
19880 | ||||
19881 | // Check that we are reading from the identity index. | |||
19882 | unsigned IdentityIndex = i * PartNumElem; | |||
19883 | if (Op.getConstantOperandAPInt(1) != IdentityIndex) | |||
19884 | return SDValue(); | |||
19885 | } | |||
19886 | ||||
19887 | if (SingleSource.getNode()) | |||
19888 | return SingleSource; | |||
19889 | ||||
19890 | return SDValue(); | |||
19891 | } | |||
19892 | ||||
19893 | // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find | |||
19894 | // if the subvector can be sourced for free. | |||
19895 | static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) { | |||
19896 | if (V.getOpcode() == ISD::INSERT_SUBVECTOR && | |||
19897 | V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) { | |||
19898 | return V.getOperand(1); | |||
19899 | } | |||
19900 | auto *IndexC = dyn_cast<ConstantSDNode>(Index); | |||
19901 | if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS && | |||
19902 | V.getOperand(0).getValueType() == SubVT && | |||
19903 | (IndexC->getZExtValue() % SubVT.getVectorMinNumElements()) == 0) { | |||
19904 | uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorMinNumElements(); | |||
19905 | return V.getOperand(SubIdx); | |||
19906 | } | |||
19907 | return SDValue(); | |||
19908 | } | |||
19909 | ||||
19910 | static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract, | |||
19911 | SelectionDAG &DAG, | |||
19912 | bool LegalOperations) { | |||
19913 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19914 | SDValue BinOp = Extract->getOperand(0); | |||
19915 | unsigned BinOpcode = BinOp.getOpcode(); | |||
19916 | if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1) | |||
19917 | return SDValue(); | |||
19918 | ||||
19919 | EVT VecVT = BinOp.getValueType(); | |||
19920 | SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1); | |||
19921 | if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType()) | |||
19922 | return SDValue(); | |||
19923 | ||||
19924 | SDValue Index = Extract->getOperand(1); | |||
19925 | EVT SubVT = Extract->getValueType(0); | |||
19926 | if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT, LegalOperations)) | |||
19927 | return SDValue(); | |||
19928 | ||||
19929 | SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT); | |||
19930 | SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT); | |||
19931 | ||||
19932 | // TODO: We could handle the case where only 1 operand is being inserted by | |||
19933 | // creating an extract of the other operand, but that requires checking | |||
19934 | // number of uses and/or costs. | |||
19935 | if (!Sub0 || !Sub1) | |||
19936 | return SDValue(); | |||
19937 | ||||
19938 | // We are inserting both operands of the wide binop only to extract back | |||
19939 | // to the narrow vector size. Eliminate all of the insert/extract: | |||
19940 | // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y | |||
19941 | return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1, | |||
19942 | BinOp->getFlags()); | |||
19943 | } | |||
19944 | ||||
19945 | /// If we are extracting a subvector produced by a wide binary operator try | |||
19946 | /// to use a narrow binary operator and/or avoid concatenation and extraction. | |||
19947 | static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG, | |||
19948 | bool LegalOperations) { | |||
19949 | // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share | |||
19950 | // some of these bailouts with other transforms. | |||
19951 | ||||
19952 | if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG, LegalOperations)) | |||
19953 | return V; | |||
19954 | ||||
19955 | // The extract index must be a constant, so we can map it to a concat operand. | |||
19956 | auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); | |||
19957 | if (!ExtractIndexC) | |||
19958 | return SDValue(); | |||
19959 | ||||
19960 | // We are looking for an optionally bitcasted wide vector binary operator | |||
19961 | // feeding an extract subvector. | |||
19962 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
19963 | SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0)); | |||
19964 | unsigned BOpcode = BinOp.getOpcode(); | |||
19965 | if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1) | |||
19966 | return SDValue(); | |||
19967 | ||||
19968 | // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be | |||
19969 | // reduced to the unary fneg when it is visited, and we probably want to deal | |||
19970 | // with fneg in a target-specific way. | |||
19971 | if (BOpcode == ISD::FSUB) { | |||
19972 | auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true); | |||
19973 | if (C && C->getValueAPF().isNegZero()) | |||
19974 | return SDValue(); | |||
19975 | } | |||
19976 | ||||
19977 | // The binop must be a vector type, so we can extract some fraction of it. | |||
19978 | EVT WideBVT = BinOp.getValueType(); | |||
19979 | // The optimisations below currently assume we are dealing with fixed length | |||
19980 | // vectors. It is possible to add support for scalable vectors, but at the | |||
19981 | // moment we've done no analysis to prove whether they are profitable or not. | |||
19982 | if (!WideBVT.isFixedLengthVector()) | |||
19983 | return SDValue(); | |||
19984 | ||||
19985 | EVT VT = Extract->getValueType(0); | |||
19986 | unsigned ExtractIndex = ExtractIndexC->getZExtValue(); | |||
19987 | assert(ExtractIndex % VT.getVectorNumElements() == 0 &&((ExtractIndex % VT.getVectorNumElements() == 0 && "Extract index is not a multiple of the vector length." ) ? static_cast<void> (0) : __assert_fail ("ExtractIndex % VT.getVectorNumElements() == 0 && \"Extract index is not a multiple of the vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19988, __PRETTY_FUNCTION__)) | |||
19988 | "Extract index is not a multiple of the vector length.")((ExtractIndex % VT.getVectorNumElements() == 0 && "Extract index is not a multiple of the vector length." ) ? static_cast<void> (0) : __assert_fail ("ExtractIndex % VT.getVectorNumElements() == 0 && \"Extract index is not a multiple of the vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 19988, __PRETTY_FUNCTION__)); | |||
19989 | ||||
19990 | // Bail out if this is not a proper multiple width extraction. | |||
19991 | unsigned WideWidth = WideBVT.getSizeInBits(); | |||
19992 | unsigned NarrowWidth = VT.getSizeInBits(); | |||
19993 | if (WideWidth % NarrowWidth != 0) | |||
19994 | return SDValue(); | |||
19995 | ||||
19996 | // Bail out if we are extracting a fraction of a single operation. This can | |||
19997 | // occur because we potentially looked through a bitcast of the binop. | |||
19998 | unsigned NarrowingRatio = WideWidth / NarrowWidth; | |||
19999 | unsigned WideNumElts = WideBVT.getVectorNumElements(); | |||
20000 | if (WideNumElts % NarrowingRatio != 0) | |||
20001 | return SDValue(); | |||
20002 | ||||
20003 | // Bail out if the target does not support a narrower version of the binop. | |||
20004 | EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), | |||
20005 | WideNumElts / NarrowingRatio); | |||
20006 | if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) | |||
20007 | return SDValue(); | |||
20008 | ||||
20009 | // If extraction is cheap, we don't need to look at the binop operands | |||
20010 | // for concat ops. The narrow binop alone makes this transform profitable. | |||
20011 | // We can't just reuse the original extract index operand because we may have | |||
20012 | // bitcasted. | |||
20013 | unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements(); | |||
20014 | unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); | |||
20015 | if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) && | |||
20016 | BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) { | |||
20017 | // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N) | |||
20018 | SDLoc DL(Extract); | |||
20019 | SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL); | |||
20020 | SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, | |||
20021 | BinOp.getOperand(0), NewExtIndex); | |||
20022 | SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, | |||
20023 | BinOp.getOperand(1), NewExtIndex); | |||
20024 | SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y, | |||
20025 | BinOp.getNode()->getFlags()); | |||
20026 | return DAG.getBitcast(VT, NarrowBinOp); | |||
20027 | } | |||
20028 | ||||
20029 | // Only handle the case where we are doubling and then halving. A larger ratio | |||
20030 | // may require more than two narrow binops to replace the wide binop. | |||
20031 | if (NarrowingRatio != 2) | |||
20032 | return SDValue(); | |||
20033 | ||||
20034 | // TODO: The motivating case for this transform is an x86 AVX1 target. That | |||
20035 | // target has temptingly almost legal versions of bitwise logic ops in 256-bit | |||
20036 | // flavors, but no other 256-bit integer support. This could be extended to | |||
20037 | // handle any binop, but that may require fixing/adding other folds to avoid | |||
20038 | // codegen regressions. | |||
20039 | if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) | |||
20040 | return SDValue(); | |||
20041 | ||||
20042 | // We need at least one concatenation operation of a binop operand to make | |||
20043 | // this transform worthwhile. The concat must double the input vector sizes. | |||
20044 | auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue { | |||
20045 | if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2) | |||
20046 | return V.getOperand(ConcatOpNum); | |||
20047 | return SDValue(); | |||
20048 | }; | |||
20049 | SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0))); | |||
20050 | SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1))); | |||
20051 | ||||
20052 | if (SubVecL || SubVecR) { | |||
20053 | // If a binop operand was not the result of a concat, we must extract a | |||
20054 | // half-sized operand for our new narrow binop: | |||
20055 | // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN | |||
20056 | // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC) | |||
20057 | // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN | |||
20058 | SDLoc DL(Extract); | |||
20059 | SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL); | |||
20060 | SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL) | |||
20061 | : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, | |||
20062 | BinOp.getOperand(0), IndexC); | |||
20063 | ||||
20064 | SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR) | |||
20065 | : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, | |||
20066 | BinOp.getOperand(1), IndexC); | |||
20067 | ||||
20068 | SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); | |||
20069 | return DAG.getBitcast(VT, NarrowBinOp); | |||
20070 | } | |||
20071 | ||||
20072 | return SDValue(); | |||
20073 | } | |||
20074 | ||||
20075 | /// If we are extracting a subvector from a wide vector load, convert to a | |||
20076 | /// narrow load to eliminate the extraction: | |||
20077 | /// (extract_subvector (load wide vector)) --> (load narrow vector) | |||
20078 | static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { | |||
20079 | // TODO: Add support for big-endian. The offset calculation must be adjusted. | |||
20080 | if (DAG.getDataLayout().isBigEndian()) | |||
20081 | return SDValue(); | |||
20082 | ||||
20083 | auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); | |||
20084 | auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); | |||
20085 | if (!Ld || Ld->getExtensionType() || !Ld->isSimple() || | |||
20086 | !ExtIdx) | |||
20087 | return SDValue(); | |||
20088 | ||||
20089 | // Allow targets to opt-out. | |||
20090 | EVT VT = Extract->getValueType(0); | |||
20091 | ||||
20092 | // We can only create byte sized loads. | |||
20093 | if (!VT.isByteSized()) | |||
20094 | return SDValue(); | |||
20095 | ||||
20096 | unsigned Index = ExtIdx->getZExtValue(); | |||
20097 | unsigned NumElts = VT.getVectorMinNumElements(); | |||
20098 | ||||
20099 | // The definition of EXTRACT_SUBVECTOR states that the index must be a | |||
20100 | // multiple of the minimum number of elements in the result type. | |||
20101 | assert(Index % NumElts == 0 && "The extract subvector index is not a "((Index % NumElts == 0 && "The extract subvector index is not a " "multiple of the result's element count") ? static_cast<void > (0) : __assert_fail ("Index % NumElts == 0 && \"The extract subvector index is not a \" \"multiple of the result's element count\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20102, __PRETTY_FUNCTION__)) | |||
20102 | "multiple of the result's element count")((Index % NumElts == 0 && "The extract subvector index is not a " "multiple of the result's element count") ? static_cast<void > (0) : __assert_fail ("Index % NumElts == 0 && \"The extract subvector index is not a \" \"multiple of the result's element count\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20102, __PRETTY_FUNCTION__)); | |||
20103 | ||||
20104 | // It's fine to use TypeSize here as we know the offset will not be negative. | |||
20105 | TypeSize Offset = VT.getStoreSize() * (Index / NumElts); | |||
20106 | ||||
20107 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
20108 | if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT)) | |||
20109 | return SDValue(); | |||
20110 | ||||
20111 | // The narrow load will be offset from the base address of the old load if | |||
20112 | // we are extracting from something besides index 0 (little-endian). | |||
20113 | SDLoc DL(Extract); | |||
20114 | ||||
20115 | // TODO: Use "BaseIndexOffset" to make this more effective. | |||
20116 | SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), Offset, DL); | |||
20117 | ||||
20118 | uint64_t StoreSize = MemoryLocation::getSizeOrUnknown(VT.getStoreSize()); | |||
20119 | MachineFunction &MF = DAG.getMachineFunction(); | |||
20120 | MachineMemOperand *MMO; | |||
20121 | if (Offset.isScalable()) { | |||
20122 | MachinePointerInfo MPI = | |||
20123 | MachinePointerInfo(Ld->getPointerInfo().getAddrSpace()); | |||
20124 | MMO = MF.getMachineMemOperand(Ld->getMemOperand(), MPI, StoreSize); | |||
20125 | } else | |||
20126 | MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset.getFixedSize(), | |||
20127 | StoreSize); | |||
20128 | ||||
20129 | SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); | |||
20130 | DAG.makeEquivalentMemoryOrdering(Ld, NewLd); | |||
20131 | return NewLd; | |||
20132 | } | |||
20133 | ||||
20134 | SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) { | |||
20135 | EVT NVT = N->getValueType(0); | |||
20136 | SDValue V = N->getOperand(0); | |||
20137 | uint64_t ExtIdx = N->getConstantOperandVal(1); | |||
20138 | ||||
20139 | // Extract from UNDEF is UNDEF. | |||
20140 | if (V.isUndef()) | |||
20141 | return DAG.getUNDEF(NVT); | |||
20142 | ||||
20143 | if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) | |||
20144 | if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) | |||
20145 | return NarrowLoad; | |||
20146 | ||||
20147 | // Combine an extract of an extract into a single extract_subvector. | |||
20148 | // ext (ext X, C), 0 --> ext X, C | |||
20149 | if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) { | |||
20150 | if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(), | |||
20151 | V.getConstantOperandVal(1)) && | |||
20152 | TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) { | |||
20153 | return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0), | |||
20154 | V.getOperand(1)); | |||
20155 | } | |||
20156 | } | |||
20157 | ||||
20158 | // Try to move vector bitcast after extract_subv by scaling extraction index: | |||
20159 | // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index') | |||
20160 | if (V.getOpcode() == ISD::BITCAST && | |||
20161 | V.getOperand(0).getValueType().isVector()) { | |||
20162 | SDValue SrcOp = V.getOperand(0); | |||
20163 | EVT SrcVT = SrcOp.getValueType(); | |||
20164 | unsigned SrcNumElts = SrcVT.getVectorMinNumElements(); | |||
20165 | unsigned DestNumElts = V.getValueType().getVectorMinNumElements(); | |||
20166 | if ((SrcNumElts % DestNumElts) == 0) { | |||
20167 | unsigned SrcDestRatio = SrcNumElts / DestNumElts; | |||
20168 | ElementCount NewExtEC = NVT.getVectorElementCount() * SrcDestRatio; | |||
20169 | EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(), | |||
20170 | NewExtEC); | |||
20171 | if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { | |||
20172 | SDLoc DL(N); | |||
20173 | SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL); | |||
20174 | SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, | |||
20175 | V.getOperand(0), NewIndex); | |||
20176 | return DAG.getBitcast(NVT, NewExtract); | |||
20177 | } | |||
20178 | } | |||
20179 | if ((DestNumElts % SrcNumElts) == 0) { | |||
20180 | unsigned DestSrcRatio = DestNumElts / SrcNumElts; | |||
20181 | if (NVT.getVectorElementCount().isKnownMultipleOf(DestSrcRatio)) { | |||
20182 | ElementCount NewExtEC = | |||
20183 | NVT.getVectorElementCount().divideCoefficientBy(DestSrcRatio); | |||
20184 | EVT ScalarVT = SrcVT.getScalarType(); | |||
20185 | if ((ExtIdx % DestSrcRatio) == 0) { | |||
20186 | SDLoc DL(N); | |||
20187 | unsigned IndexValScaled = ExtIdx / DestSrcRatio; | |||
20188 | EVT NewExtVT = | |||
20189 | EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtEC); | |||
20190 | if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { | |||
20191 | SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); | |||
20192 | SDValue NewExtract = | |||
20193 | DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, | |||
20194 | V.getOperand(0), NewIndex); | |||
20195 | return DAG.getBitcast(NVT, NewExtract); | |||
20196 | } | |||
20197 | if (NewExtEC.isScalar() && | |||
20198 | TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) { | |||
20199 | SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); | |||
20200 | SDValue NewExtract = | |||
20201 | DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, | |||
20202 | V.getOperand(0), NewIndex); | |||
20203 | return DAG.getBitcast(NVT, NewExtract); | |||
20204 | } | |||
20205 | } | |||
20206 | } | |||
20207 | } | |||
20208 | } | |||
20209 | ||||
20210 | if (V.getOpcode() == ISD::CONCAT_VECTORS) { | |||
20211 | unsigned ExtNumElts = NVT.getVectorMinNumElements(); | |||
20212 | EVT ConcatSrcVT = V.getOperand(0).getValueType(); | |||
20213 | assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() &&((ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType () && "Concat and extract subvector do not change element type" ) ? static_cast<void> (0) : __assert_fail ("ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() && \"Concat and extract subvector do not change element type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20214, __PRETTY_FUNCTION__)) | |||
20214 | "Concat and extract subvector do not change element type")((ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType () && "Concat and extract subvector do not change element type" ) ? static_cast<void> (0) : __assert_fail ("ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() && \"Concat and extract subvector do not change element type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20214, __PRETTY_FUNCTION__)); | |||
20215 | assert((ExtIdx % ExtNumElts) == 0 &&(((ExtIdx % ExtNumElts) == 0 && "Extract index is not a multiple of the input vector length." ) ? static_cast<void> (0) : __assert_fail ("(ExtIdx % ExtNumElts) == 0 && \"Extract index is not a multiple of the input vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20216, __PRETTY_FUNCTION__)) | |||
20216 | "Extract index is not a multiple of the input vector length.")(((ExtIdx % ExtNumElts) == 0 && "Extract index is not a multiple of the input vector length." ) ? static_cast<void> (0) : __assert_fail ("(ExtIdx % ExtNumElts) == 0 && \"Extract index is not a multiple of the input vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20216, __PRETTY_FUNCTION__)); | |||
20217 | ||||
20218 | unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorMinNumElements(); | |||
20219 | unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts; | |||
20220 | ||||
20221 | // If the concatenated source types match this extract, it's a direct | |||
20222 | // simplification: | |||
20223 | // extract_subvec (concat V1, V2, ...), i --> Vi | |||
20224 | if (ConcatSrcNumElts == ExtNumElts) | |||
20225 | return V.getOperand(ConcatOpIdx); | |||
20226 | ||||
20227 | // If the concatenated source vectors are a multiple length of this extract, | |||
20228 | // then extract a fraction of one of those source vectors directly from a | |||
20229 | // concat operand. Example: | |||
20230 | // v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 --> | |||
20231 | // v2i8 extract_subvec v8i8 Y, 6 | |||
20232 | if (NVT.isFixedLengthVector() && ConcatSrcNumElts % ExtNumElts == 0) { | |||
20233 | SDLoc DL(N); | |||
20234 | unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts; | |||
20235 | assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts &&((NewExtIdx + ExtNumElts <= ConcatSrcNumElts && "Trying to extract from >1 concat operand?" ) ? static_cast<void> (0) : __assert_fail ("NewExtIdx + ExtNumElts <= ConcatSrcNumElts && \"Trying to extract from >1 concat operand?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20236, __PRETTY_FUNCTION__)) | |||
20236 | "Trying to extract from >1 concat operand?")((NewExtIdx + ExtNumElts <= ConcatSrcNumElts && "Trying to extract from >1 concat operand?" ) ? static_cast<void> (0) : __assert_fail ("NewExtIdx + ExtNumElts <= ConcatSrcNumElts && \"Trying to extract from >1 concat operand?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20236, __PRETTY_FUNCTION__)); | |||
20237 | assert(NewExtIdx % ExtNumElts == 0 &&((NewExtIdx % ExtNumElts == 0 && "Extract index is not a multiple of the input vector length." ) ? static_cast<void> (0) : __assert_fail ("NewExtIdx % ExtNumElts == 0 && \"Extract index is not a multiple of the input vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20238, __PRETTY_FUNCTION__)) | |||
20238 | "Extract index is not a multiple of the input vector length.")((NewExtIdx % ExtNumElts == 0 && "Extract index is not a multiple of the input vector length." ) ? static_cast<void> (0) : __assert_fail ("NewExtIdx % ExtNumElts == 0 && \"Extract index is not a multiple of the input vector length.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20238, __PRETTY_FUNCTION__)); | |||
20239 | SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL); | |||
20240 | return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT, | |||
20241 | V.getOperand(ConcatOpIdx), NewIndexC); | |||
20242 | } | |||
20243 | } | |||
20244 | ||||
20245 | V = peekThroughBitcasts(V); | |||
20246 | ||||
20247 | // If the input is a build vector. Try to make a smaller build vector. | |||
20248 | if (V.getOpcode() == ISD::BUILD_VECTOR) { | |||
20249 | EVT InVT = V.getValueType(); | |||
20250 | unsigned ExtractSize = NVT.getSizeInBits(); | |||
20251 | unsigned EltSize = InVT.getScalarSizeInBits(); | |||
20252 | // Only do this if we won't split any elements. | |||
20253 | if (ExtractSize % EltSize == 0) { | |||
20254 | unsigned NumElems = ExtractSize / EltSize; | |||
20255 | EVT EltVT = InVT.getVectorElementType(); | |||
20256 | EVT ExtractVT = | |||
20257 | NumElems == 1 ? EltVT | |||
20258 | : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); | |||
20259 | if ((Level < AfterLegalizeDAG || | |||
20260 | (NumElems == 1 || | |||
20261 | TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && | |||
20262 | (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { | |||
20263 | unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize; | |||
20264 | ||||
20265 | if (NumElems == 1) { | |||
20266 | SDValue Src = V->getOperand(IdxVal); | |||
20267 | if (EltVT != Src.getValueType()) | |||
20268 | Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); | |||
20269 | return DAG.getBitcast(NVT, Src); | |||
20270 | } | |||
20271 | ||||
20272 | // Extract the pieces from the original build_vector. | |||
20273 | SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), | |||
20274 | V->ops().slice(IdxVal, NumElems)); | |||
20275 | return DAG.getBitcast(NVT, BuildVec); | |||
20276 | } | |||
20277 | } | |||
20278 | } | |||
20279 | ||||
20280 | if (V.getOpcode() == ISD::INSERT_SUBVECTOR) { | |||
20281 | // Handle only simple case where vector being inserted and vector | |||
20282 | // being extracted are of same size. | |||
20283 | EVT SmallVT = V.getOperand(1).getValueType(); | |||
20284 | if (!NVT.bitsEq(SmallVT)) | |||
20285 | return SDValue(); | |||
20286 | ||||
20287 | // Combine: | |||
20288 | // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) | |||
20289 | // Into: | |||
20290 | // indices are equal or bit offsets are equal => V1 | |||
20291 | // otherwise => (extract_subvec V1, ExtIdx) | |||
20292 | uint64_t InsIdx = V.getConstantOperandVal(2); | |||
20293 | if (InsIdx * SmallVT.getScalarSizeInBits() == | |||
20294 | ExtIdx * NVT.getScalarSizeInBits()) | |||
20295 | return DAG.getBitcast(NVT, V.getOperand(1)); | |||
20296 | return DAG.getNode( | |||
20297 | ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, | |||
20298 | DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)), | |||
20299 | N->getOperand(1)); | |||
20300 | } | |||
20301 | ||||
20302 | if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG, LegalOperations)) | |||
20303 | return NarrowBOp; | |||
20304 | ||||
20305 | if (SimplifyDemandedVectorElts(SDValue(N, 0))) | |||
20306 | return SDValue(N, 0); | |||
20307 | ||||
20308 | return SDValue(); | |||
20309 | } | |||
20310 | ||||
20311 | /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles | |||
20312 | /// followed by concatenation. Narrow vector ops may have better performance | |||
20313 | /// than wide ops, and this can unlock further narrowing of other vector ops. | |||
20314 | /// Targets can invert this transform later if it is not profitable. | |||
20315 | static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf, | |||
20316 | SelectionDAG &DAG) { | |||
20317 | SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1); | |||
20318 | if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 || | |||
20319 | N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 || | |||
20320 | !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef()) | |||
20321 | return SDValue(); | |||
20322 | ||||
20323 | // Split the wide shuffle mask into halves. Any mask element that is accessing | |||
20324 | // operand 1 is offset down to account for narrowing of the vectors. | |||
20325 | ArrayRef<int> Mask = Shuf->getMask(); | |||
20326 | EVT VT = Shuf->getValueType(0); | |||
20327 | unsigned NumElts = VT.getVectorNumElements(); | |||
20328 | unsigned HalfNumElts = NumElts / 2; | |||
20329 | SmallVector<int, 16> Mask0(HalfNumElts, -1); | |||
20330 | SmallVector<int, 16> Mask1(HalfNumElts, -1); | |||
20331 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20332 | if (Mask[i] == -1) | |||
20333 | continue; | |||
20334 | int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts; | |||
20335 | if (i < HalfNumElts) | |||
20336 | Mask0[i] = M; | |||
20337 | else | |||
20338 | Mask1[i - HalfNumElts] = M; | |||
20339 | } | |||
20340 | ||||
20341 | // Ask the target if this is a valid transform. | |||
20342 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
20343 | EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), | |||
20344 | HalfNumElts); | |||
20345 | if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) || | |||
20346 | !TLI.isShuffleMaskLegal(Mask1, HalfVT)) | |||
20347 | return SDValue(); | |||
20348 | ||||
20349 | // shuffle (concat X, undef), (concat Y, undef), Mask --> | |||
20350 | // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1) | |||
20351 | SDValue X = N0.getOperand(0), Y = N1.getOperand(0); | |||
20352 | SDLoc DL(Shuf); | |||
20353 | SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0); | |||
20354 | SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1); | |||
20355 | return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1); | |||
20356 | } | |||
20357 | ||||
20358 | // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, | |||
20359 | // or turn a shuffle of a single concat into simpler shuffle then concat. | |||
20360 | static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { | |||
20361 | EVT VT = N->getValueType(0); | |||
20362 | unsigned NumElts = VT.getVectorNumElements(); | |||
20363 | ||||
20364 | SDValue N0 = N->getOperand(0); | |||
20365 | SDValue N1 = N->getOperand(1); | |||
20366 | ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); | |||
20367 | ArrayRef<int> Mask = SVN->getMask(); | |||
20368 | ||||
20369 | SmallVector<SDValue, 4> Ops; | |||
20370 | EVT ConcatVT = N0.getOperand(0).getValueType(); | |||
20371 | unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); | |||
20372 | unsigned NumConcats = NumElts / NumElemsPerConcat; | |||
20373 | ||||
20374 | auto IsUndefMaskElt = [](int i) { return i == -1; }; | |||
20375 | ||||
20376 | // Special case: shuffle(concat(A,B)) can be more efficiently represented | |||
20377 | // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high | |||
20378 | // half vector elements. | |||
20379 | if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && | |||
20380 | llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat), | |||
20381 | IsUndefMaskElt)) { | |||
20382 | N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), | |||
20383 | N0.getOperand(1), | |||
20384 | Mask.slice(0, NumElemsPerConcat)); | |||
20385 | N1 = DAG.getUNDEF(ConcatVT); | |||
20386 | return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); | |||
20387 | } | |||
20388 | ||||
20389 | // Look at every vector that's inserted. We're looking for exact | |||
20390 | // subvector-sized copies from a concatenated vector | |||
20391 | for (unsigned I = 0; I != NumConcats; ++I) { | |||
20392 | unsigned Begin = I * NumElemsPerConcat; | |||
20393 | ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat); | |||
20394 | ||||
20395 | // Make sure we're dealing with a copy. | |||
20396 | if (llvm::all_of(SubMask, IsUndefMaskElt)) { | |||
20397 | Ops.push_back(DAG.getUNDEF(ConcatVT)); | |||
20398 | continue; | |||
20399 | } | |||
20400 | ||||
20401 | int OpIdx = -1; | |||
20402 | for (int i = 0; i != (int)NumElemsPerConcat; ++i) { | |||
20403 | if (IsUndefMaskElt(SubMask[i])) | |||
20404 | continue; | |||
20405 | if ((SubMask[i] % (int)NumElemsPerConcat) != i) | |||
20406 | return SDValue(); | |||
20407 | int EltOpIdx = SubMask[i] / NumElemsPerConcat; | |||
20408 | if (0 <= OpIdx && EltOpIdx != OpIdx) | |||
20409 | return SDValue(); | |||
20410 | OpIdx = EltOpIdx; | |||
20411 | } | |||
20412 | assert(0 <= OpIdx && "Unknown concat_vectors op")((0 <= OpIdx && "Unknown concat_vectors op") ? static_cast <void> (0) : __assert_fail ("0 <= OpIdx && \"Unknown concat_vectors op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20412, __PRETTY_FUNCTION__)); | |||
20413 | ||||
20414 | if (OpIdx < (int)N0.getNumOperands()) | |||
20415 | Ops.push_back(N0.getOperand(OpIdx)); | |||
20416 | else | |||
20417 | Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands())); | |||
20418 | } | |||
20419 | ||||
20420 | return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); | |||
20421 | } | |||
20422 | ||||
20423 | // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - | |||
20424 | // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. | |||
20425 | // | |||
20426 | // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always | |||
20427 | // a simplification in some sense, but it isn't appropriate in general: some | |||
20428 | // BUILD_VECTORs are substantially cheaper than others. The general case | |||
20429 | // of a BUILD_VECTOR requires inserting each element individually (or | |||
20430 | // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of | |||
20431 | // all constants is a single constant pool load. A BUILD_VECTOR where each | |||
20432 | // element is identical is a splat. A BUILD_VECTOR where most of the operands | |||
20433 | // are undef lowers to a small number of element insertions. | |||
20434 | // | |||
20435 | // To deal with this, we currently use a bunch of mostly arbitrary heuristics. | |||
20436 | // We don't fold shuffles where one side is a non-zero constant, and we don't | |||
20437 | // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate | |||
20438 | // non-constant operands. This seems to work out reasonably well in practice. | |||
20439 | static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, | |||
20440 | SelectionDAG &DAG, | |||
20441 | const TargetLowering &TLI) { | |||
20442 | EVT VT = SVN->getValueType(0); | |||
20443 | unsigned NumElts = VT.getVectorNumElements(); | |||
20444 | SDValue N0 = SVN->getOperand(0); | |||
20445 | SDValue N1 = SVN->getOperand(1); | |||
20446 | ||||
20447 | if (!N0->hasOneUse()) | |||
20448 | return SDValue(); | |||
20449 | ||||
20450 | // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as | |||
20451 | // discussed above. | |||
20452 | if (!N1.isUndef()) { | |||
20453 | if (!N1->hasOneUse()) | |||
20454 | return SDValue(); | |||
20455 | ||||
20456 | bool N0AnyConst = isAnyConstantBuildVector(N0); | |||
20457 | bool N1AnyConst = isAnyConstantBuildVector(N1); | |||
20458 | if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) | |||
20459 | return SDValue(); | |||
20460 | if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) | |||
20461 | return SDValue(); | |||
20462 | } | |||
20463 | ||||
20464 | // If both inputs are splats of the same value then we can safely merge this | |||
20465 | // to a single BUILD_VECTOR with undef elements based on the shuffle mask. | |||
20466 | bool IsSplat = false; | |||
20467 | auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); | |||
20468 | auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); | |||
20469 | if (BV0 && BV1) | |||
20470 | if (SDValue Splat0 = BV0->getSplatValue()) | |||
20471 | IsSplat = (Splat0 == BV1->getSplatValue()); | |||
20472 | ||||
20473 | SmallVector<SDValue, 8> Ops; | |||
20474 | SmallSet<SDValue, 16> DuplicateOps; | |||
20475 | for (int M : SVN->getMask()) { | |||
20476 | SDValue Op = DAG.getUNDEF(VT.getScalarType()); | |||
20477 | if (M >= 0) { | |||
20478 | int Idx = M < (int)NumElts ? M : M - NumElts; | |||
20479 | SDValue &S = (M < (int)NumElts ? N0 : N1); | |||
20480 | if (S.getOpcode() == ISD::BUILD_VECTOR) { | |||
20481 | Op = S.getOperand(Idx); | |||
20482 | } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { | |||
20483 | SDValue Op0 = S.getOperand(0); | |||
20484 | Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType()); | |||
20485 | } else { | |||
20486 | // Operand can't be combined - bail out. | |||
20487 | return SDValue(); | |||
20488 | } | |||
20489 | } | |||
20490 | ||||
20491 | // Don't duplicate a non-constant BUILD_VECTOR operand unless we're | |||
20492 | // generating a splat; semantically, this is fine, but it's likely to | |||
20493 | // generate low-quality code if the target can't reconstruct an appropriate | |||
20494 | // shuffle. | |||
20495 | if (!Op.isUndef() && !isIntOrFPConstant(Op)) | |||
20496 | if (!IsSplat && !DuplicateOps.insert(Op).second) | |||
20497 | return SDValue(); | |||
20498 | ||||
20499 | Ops.push_back(Op); | |||
20500 | } | |||
20501 | ||||
20502 | // BUILD_VECTOR requires all inputs to be of the same type, find the | |||
20503 | // maximum type and extend them all. | |||
20504 | EVT SVT = VT.getScalarType(); | |||
20505 | if (SVT.isInteger()) | |||
20506 | for (SDValue &Op : Ops) | |||
20507 | SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); | |||
20508 | if (SVT != VT.getScalarType()) | |||
20509 | for (SDValue &Op : Ops) | |||
20510 | Op = TLI.isZExtFree(Op.getValueType(), SVT) | |||
20511 | ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) | |||
20512 | : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); | |||
20513 | return DAG.getBuildVector(VT, SDLoc(SVN), Ops); | |||
20514 | } | |||
20515 | ||||
20516 | // Match shuffles that can be converted to any_vector_extend_in_reg. | |||
20517 | // This is often generated during legalization. | |||
20518 | // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) | |||
20519 | // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. | |||
20520 | static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, | |||
20521 | SelectionDAG &DAG, | |||
20522 | const TargetLowering &TLI, | |||
20523 | bool LegalOperations) { | |||
20524 | EVT VT = SVN->getValueType(0); | |||
20525 | bool IsBigEndian = DAG.getDataLayout().isBigEndian(); | |||
20526 | ||||
20527 | // TODO Add support for big-endian when we have a test case. | |||
20528 | if (!VT.isInteger() || IsBigEndian) | |||
20529 | return SDValue(); | |||
20530 | ||||
20531 | unsigned NumElts = VT.getVectorNumElements(); | |||
20532 | unsigned EltSizeInBits = VT.getScalarSizeInBits(); | |||
20533 | ArrayRef<int> Mask = SVN->getMask(); | |||
20534 | SDValue N0 = SVN->getOperand(0); | |||
20535 | ||||
20536 | // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) | |||
20537 | auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { | |||
20538 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20539 | if (Mask[i] < 0) | |||
20540 | continue; | |||
20541 | if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) | |||
20542 | continue; | |||
20543 | return false; | |||
20544 | } | |||
20545 | return true; | |||
20546 | }; | |||
20547 | ||||
20548 | // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for | |||
20549 | // power-of-2 extensions as they are the most likely. | |||
20550 | for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { | |||
20551 | // Check for non power of 2 vector sizes | |||
20552 | if (NumElts % Scale != 0) | |||
20553 | continue; | |||
20554 | if (!isAnyExtend(Scale)) | |||
20555 | continue; | |||
20556 | ||||
20557 | EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); | |||
20558 | EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); | |||
20559 | // Never create an illegal type. Only create unsupported operations if we | |||
20560 | // are pre-legalization. | |||
20561 | if (TLI.isTypeLegal(OutVT)) | |||
20562 | if (!LegalOperations || | |||
20563 | TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) | |||
20564 | return DAG.getBitcast(VT, | |||
20565 | DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, | |||
20566 | SDLoc(SVN), OutVT, N0)); | |||
20567 | } | |||
20568 | ||||
20569 | return SDValue(); | |||
20570 | } | |||
20571 | ||||
20572 | // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of | |||
20573 | // each source element of a large type into the lowest elements of a smaller | |||
20574 | // destination type. This is often generated during legalization. | |||
20575 | // If the source node itself was a '*_extend_vector_inreg' node then we should | |||
20576 | // then be able to remove it. | |||
20577 | static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, | |||
20578 | SelectionDAG &DAG) { | |||
20579 | EVT VT = SVN->getValueType(0); | |||
20580 | bool IsBigEndian = DAG.getDataLayout().isBigEndian(); | |||
20581 | ||||
20582 | // TODO Add support for big-endian when we have a test case. | |||
20583 | if (!VT.isInteger() || IsBigEndian) | |||
20584 | return SDValue(); | |||
20585 | ||||
20586 | SDValue N0 = peekThroughBitcasts(SVN->getOperand(0)); | |||
20587 | ||||
20588 | unsigned Opcode = N0.getOpcode(); | |||
20589 | if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && | |||
20590 | Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && | |||
20591 | Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) | |||
20592 | return SDValue(); | |||
20593 | ||||
20594 | SDValue N00 = N0.getOperand(0); | |||
20595 | ArrayRef<int> Mask = SVN->getMask(); | |||
20596 | unsigned NumElts = VT.getVectorNumElements(); | |||
20597 | unsigned EltSizeInBits = VT.getScalarSizeInBits(); | |||
20598 | unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); | |||
20599 | unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); | |||
20600 | ||||
20601 | if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) | |||
20602 | return SDValue(); | |||
20603 | unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; | |||
20604 | ||||
20605 | // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> | |||
20606 | // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> | |||
20607 | // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> | |||
20608 | auto isTruncate = [&Mask, &NumElts](unsigned Scale) { | |||
20609 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20610 | if (Mask[i] < 0) | |||
20611 | continue; | |||
20612 | if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) | |||
20613 | continue; | |||
20614 | return false; | |||
20615 | } | |||
20616 | return true; | |||
20617 | }; | |||
20618 | ||||
20619 | // At the moment we just handle the case where we've truncated back to the | |||
20620 | // same size as before the extension. | |||
20621 | // TODO: handle more extension/truncation cases as cases arise. | |||
20622 | if (EltSizeInBits != ExtSrcSizeInBits) | |||
20623 | return SDValue(); | |||
20624 | ||||
20625 | // We can remove *extend_vector_inreg only if the truncation happens at | |||
20626 | // the same scale as the extension. | |||
20627 | if (isTruncate(ExtScale)) | |||
20628 | return DAG.getBitcast(VT, N00); | |||
20629 | ||||
20630 | return SDValue(); | |||
20631 | } | |||
20632 | ||||
20633 | // Combine shuffles of splat-shuffles of the form: | |||
20634 | // shuffle (shuffle V, undef, splat-mask), undef, M | |||
20635 | // If splat-mask contains undef elements, we need to be careful about | |||
20636 | // introducing undef's in the folded mask which are not the result of composing | |||
20637 | // the masks of the shuffles. | |||
20638 | static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf, | |||
20639 | SelectionDAG &DAG) { | |||
20640 | if (!Shuf->getOperand(1).isUndef()) | |||
20641 | return SDValue(); | |||
20642 | auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); | |||
20643 | if (!Splat || !Splat->isSplat()) | |||
20644 | return SDValue(); | |||
20645 | ||||
20646 | ArrayRef<int> ShufMask = Shuf->getMask(); | |||
20647 | ArrayRef<int> SplatMask = Splat->getMask(); | |||
20648 | assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch")((ShufMask.size() == SplatMask.size() && "Mask length mismatch" ) ? static_cast<void> (0) : __assert_fail ("ShufMask.size() == SplatMask.size() && \"Mask length mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20648, __PRETTY_FUNCTION__)); | |||
20649 | ||||
20650 | // Prefer simplifying to the splat-shuffle, if possible. This is legal if | |||
20651 | // every undef mask element in the splat-shuffle has a corresponding undef | |||
20652 | // element in the user-shuffle's mask or if the composition of mask elements | |||
20653 | // would result in undef. | |||
20654 | // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): | |||
20655 | // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] | |||
20656 | // In this case it is not legal to simplify to the splat-shuffle because we | |||
20657 | // may be exposing the users of the shuffle an undef element at index 1 | |||
20658 | // which was not there before the combine. | |||
20659 | // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] | |||
20660 | // In this case the composition of masks yields SplatMask, so it's ok to | |||
20661 | // simplify to the splat-shuffle. | |||
20662 | // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] | |||
20663 | // In this case the composed mask includes all undef elements of SplatMask | |||
20664 | // and in addition sets element zero to undef. It is safe to simplify to | |||
20665 | // the splat-shuffle. | |||
20666 | auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, | |||
20667 | ArrayRef<int> SplatMask) { | |||
20668 | for (unsigned i = 0, e = UserMask.size(); i != e; ++i) | |||
20669 | if (UserMask[i] != -1 && SplatMask[i] == -1 && | |||
20670 | SplatMask[UserMask[i]] != -1) | |||
20671 | return false; | |||
20672 | return true; | |||
20673 | }; | |||
20674 | if (CanSimplifyToExistingSplat(ShufMask, SplatMask)) | |||
20675 | return Shuf->getOperand(0); | |||
20676 | ||||
20677 | // Create a new shuffle with a mask that is composed of the two shuffles' | |||
20678 | // masks. | |||
20679 | SmallVector<int, 32> NewMask; | |||
20680 | for (int Idx : ShufMask) | |||
20681 | NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); | |||
20682 | ||||
20683 | return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), | |||
20684 | Splat->getOperand(0), Splat->getOperand(1), | |||
20685 | NewMask); | |||
20686 | } | |||
20687 | ||||
20688 | /// Combine shuffle of shuffle of the form: | |||
20689 | /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X | |||
20690 | static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf, | |||
20691 | SelectionDAG &DAG) { | |||
20692 | if (!OuterShuf->getOperand(1).isUndef()) | |||
20693 | return SDValue(); | |||
20694 | auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0)); | |||
20695 | if (!InnerShuf || !InnerShuf->getOperand(1).isUndef()) | |||
20696 | return SDValue(); | |||
20697 | ||||
20698 | ArrayRef<int> OuterMask = OuterShuf->getMask(); | |||
20699 | ArrayRef<int> InnerMask = InnerShuf->getMask(); | |||
20700 | unsigned NumElts = OuterMask.size(); | |||
20701 | assert(NumElts == InnerMask.size() && "Mask length mismatch")((NumElts == InnerMask.size() && "Mask length mismatch" ) ? static_cast<void> (0) : __assert_fail ("NumElts == InnerMask.size() && \"Mask length mismatch\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20701, __PRETTY_FUNCTION__)); | |||
20702 | SmallVector<int, 32> CombinedMask(NumElts, -1); | |||
20703 | int SplatIndex = -1; | |||
20704 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20705 | // Undef lanes remain undef. | |||
20706 | int OuterMaskElt = OuterMask[i]; | |||
20707 | if (OuterMaskElt == -1) | |||
20708 | continue; | |||
20709 | ||||
20710 | // Peek through the shuffle masks to get the underlying source element. | |||
20711 | int InnerMaskElt = InnerMask[OuterMaskElt]; | |||
20712 | if (InnerMaskElt == -1) | |||
20713 | continue; | |||
20714 | ||||
20715 | // Initialize the splatted element. | |||
20716 | if (SplatIndex == -1) | |||
20717 | SplatIndex = InnerMaskElt; | |||
20718 | ||||
20719 | // Non-matching index - this is not a splat. | |||
20720 | if (SplatIndex != InnerMaskElt) | |||
20721 | return SDValue(); | |||
20722 | ||||
20723 | CombinedMask[i] = InnerMaskElt; | |||
20724 | } | |||
20725 | assert((all_of(CombinedMask, [](int M) { return M == -1; }) ||(((all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex (CombinedMask) != -1) && "Expected a splat mask") ? static_cast <void> (0) : __assert_fail ("(all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex(CombinedMask) != -1) && \"Expected a splat mask\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20727, __PRETTY_FUNCTION__)) | |||
20726 | getSplatIndex(CombinedMask) != -1) &&(((all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex (CombinedMask) != -1) && "Expected a splat mask") ? static_cast <void> (0) : __assert_fail ("(all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex(CombinedMask) != -1) && \"Expected a splat mask\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20727, __PRETTY_FUNCTION__)) | |||
20727 | "Expected a splat mask")(((all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex (CombinedMask) != -1) && "Expected a splat mask") ? static_cast <void> (0) : __assert_fail ("(all_of(CombinedMask, [](int M) { return M == -1; }) || getSplatIndex(CombinedMask) != -1) && \"Expected a splat mask\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20727, __PRETTY_FUNCTION__)); | |||
20728 | ||||
20729 | // TODO: The transform may be a win even if the mask is not legal. | |||
20730 | EVT VT = OuterShuf->getValueType(0); | |||
20731 | assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types")((VT == InnerShuf->getValueType(0) && "Expected matching shuffle types" ) ? static_cast<void> (0) : __assert_fail ("VT == InnerShuf->getValueType(0) && \"Expected matching shuffle types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20731, __PRETTY_FUNCTION__)); | |||
20732 | if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT)) | |||
20733 | return SDValue(); | |||
20734 | ||||
20735 | return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0), | |||
20736 | InnerShuf->getOperand(1), CombinedMask); | |||
20737 | } | |||
20738 | ||||
20739 | /// If the shuffle mask is taking exactly one element from the first vector | |||
20740 | /// operand and passing through all other elements from the second vector | |||
20741 | /// operand, return the index of the mask element that is choosing an element | |||
20742 | /// from the first operand. Otherwise, return -1. | |||
20743 | static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { | |||
20744 | int MaskSize = Mask.size(); | |||
20745 | int EltFromOp0 = -1; | |||
20746 | // TODO: This does not match if there are undef elements in the shuffle mask. | |||
20747 | // Should we ignore undefs in the shuffle mask instead? The trade-off is | |||
20748 | // removing an instruction (a shuffle), but losing the knowledge that some | |||
20749 | // vector lanes are not needed. | |||
20750 | for (int i = 0; i != MaskSize; ++i) { | |||
20751 | if (Mask[i] >= 0 && Mask[i] < MaskSize) { | |||
20752 | // We're looking for a shuffle of exactly one element from operand 0. | |||
20753 | if (EltFromOp0 != -1) | |||
20754 | return -1; | |||
20755 | EltFromOp0 = i; | |||
20756 | } else if (Mask[i] != i + MaskSize) { | |||
20757 | // Nothing from operand 1 can change lanes. | |||
20758 | return -1; | |||
20759 | } | |||
20760 | } | |||
20761 | return EltFromOp0; | |||
20762 | } | |||
20763 | ||||
20764 | /// If a shuffle inserts exactly one element from a source vector operand into | |||
20765 | /// another vector operand and we can access the specified element as a scalar, | |||
20766 | /// then we can eliminate the shuffle. | |||
20767 | static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, | |||
20768 | SelectionDAG &DAG) { | |||
20769 | // First, check if we are taking one element of a vector and shuffling that | |||
20770 | // element into another vector. | |||
20771 | ArrayRef<int> Mask = Shuf->getMask(); | |||
20772 | SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); | |||
20773 | SDValue Op0 = Shuf->getOperand(0); | |||
20774 | SDValue Op1 = Shuf->getOperand(1); | |||
20775 | int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); | |||
20776 | if (ShufOp0Index == -1) { | |||
20777 | // Commute mask and check again. | |||
20778 | ShuffleVectorSDNode::commuteMask(CommutedMask); | |||
20779 | ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); | |||
20780 | if (ShufOp0Index == -1) | |||
20781 | return SDValue(); | |||
20782 | // Commute operands to match the commuted shuffle mask. | |||
20783 | std::swap(Op0, Op1); | |||
20784 | Mask = CommutedMask; | |||
20785 | } | |||
20786 | ||||
20787 | // The shuffle inserts exactly one element from operand 0 into operand 1. | |||
20788 | // Now see if we can access that element as a scalar via a real insert element | |||
20789 | // instruction. | |||
20790 | // TODO: We can try harder to locate the element as a scalar. Examples: it | |||
20791 | // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. | |||
20792 | assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&((Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && "Shuffle mask value must be from operand 0" ) ? static_cast<void> (0) : __assert_fail ("Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && \"Shuffle mask value must be from operand 0\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20793, __PRETTY_FUNCTION__)) | |||
20793 | "Shuffle mask value must be from operand 0")((Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && "Shuffle mask value must be from operand 0" ) ? static_cast<void> (0) : __assert_fail ("Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && \"Shuffle mask value must be from operand 0\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20793, __PRETTY_FUNCTION__)); | |||
20794 | if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) | |||
20795 | return SDValue(); | |||
20796 | ||||
20797 | auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); | |||
20798 | if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) | |||
20799 | return SDValue(); | |||
20800 | ||||
20801 | // There's an existing insertelement with constant insertion index, so we | |||
20802 | // don't need to check the legality/profitability of a replacement operation | |||
20803 | // that differs at most in the constant value. The target should be able to | |||
20804 | // lower any of those in a similar way. If not, legalization will expand this | |||
20805 | // to a scalar-to-vector plus shuffle. | |||
20806 | // | |||
20807 | // Note that the shuffle may move the scalar from the position that the insert | |||
20808 | // element used. Therefore, our new insert element occurs at the shuffle's | |||
20809 | // mask index value, not the insert's index value. | |||
20810 | // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' | |||
20811 | SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf)); | |||
20812 | return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), | |||
20813 | Op1, Op0.getOperand(1), NewInsIndex); | |||
20814 | } | |||
20815 | ||||
20816 | /// If we have a unary shuffle of a shuffle, see if it can be folded away | |||
20817 | /// completely. This has the potential to lose undef knowledge because the first | |||
20818 | /// shuffle may not have an undef mask element where the second one does. So | |||
20819 | /// only call this after doing simplifications based on demanded elements. | |||
20820 | static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) { | |||
20821 | // shuf (shuf0 X, Y, Mask0), undef, Mask | |||
20822 | auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); | |||
20823 | if (!Shuf0 || !Shuf->getOperand(1).isUndef()) | |||
20824 | return SDValue(); | |||
20825 | ||||
20826 | ArrayRef<int> Mask = Shuf->getMask(); | |||
20827 | ArrayRef<int> Mask0 = Shuf0->getMask(); | |||
20828 | for (int i = 0, e = (int)Mask.size(); i != e; ++i) { | |||
20829 | // Ignore undef elements. | |||
20830 | if (Mask[i] == -1) | |||
20831 | continue; | |||
20832 | assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value")((Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value" ) ? static_cast<void> (0) : __assert_fail ("Mask[i] >= 0 && Mask[i] < e && \"Unexpected shuffle mask value\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20832, __PRETTY_FUNCTION__)); | |||
20833 | ||||
20834 | // Is the element of the shuffle operand chosen by this shuffle the same as | |||
20835 | // the element chosen by the shuffle operand itself? | |||
20836 | if (Mask0[Mask[i]] != Mask0[i]) | |||
20837 | return SDValue(); | |||
20838 | } | |||
20839 | // Every element of this shuffle is identical to the result of the previous | |||
20840 | // shuffle, so we can replace this value. | |||
20841 | return Shuf->getOperand(0); | |||
20842 | } | |||
20843 | ||||
20844 | SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { | |||
20845 | EVT VT = N->getValueType(0); | |||
20846 | unsigned NumElts = VT.getVectorNumElements(); | |||
20847 | ||||
20848 | SDValue N0 = N->getOperand(0); | |||
20849 | SDValue N1 = N->getOperand(1); | |||
20850 | ||||
20851 | assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG")((N0.getValueType() == VT && "Vector shuffle must be normalized in DAG" ) ? static_cast<void> (0) : __assert_fail ("N0.getValueType() == VT && \"Vector shuffle must be normalized in DAG\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20851, __PRETTY_FUNCTION__)); | |||
20852 | ||||
20853 | // Canonicalize shuffle undef, undef -> undef | |||
20854 | if (N0.isUndef() && N1.isUndef()) | |||
20855 | return DAG.getUNDEF(VT); | |||
20856 | ||||
20857 | ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); | |||
20858 | ||||
20859 | // Canonicalize shuffle v, v -> v, undef | |||
20860 | if (N0 == N1) { | |||
20861 | SmallVector<int, 8> NewMask; | |||
20862 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20863 | int Idx = SVN->getMaskElt(i); | |||
20864 | if (Idx >= (int)NumElts) Idx -= NumElts; | |||
20865 | NewMask.push_back(Idx); | |||
20866 | } | |||
20867 | return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); | |||
20868 | } | |||
20869 | ||||
20870 | // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. | |||
20871 | if (N0.isUndef()) | |||
20872 | return DAG.getCommutedVectorShuffle(*SVN); | |||
20873 | ||||
20874 | // Remove references to rhs if it is undef | |||
20875 | if (N1.isUndef()) { | |||
20876 | bool Changed = false; | |||
20877 | SmallVector<int, 8> NewMask; | |||
20878 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20879 | int Idx = SVN->getMaskElt(i); | |||
20880 | if (Idx >= (int)NumElts) { | |||
20881 | Idx = -1; | |||
20882 | Changed = true; | |||
20883 | } | |||
20884 | NewMask.push_back(Idx); | |||
20885 | } | |||
20886 | if (Changed) | |||
20887 | return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); | |||
20888 | } | |||
20889 | ||||
20890 | if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) | |||
20891 | return InsElt; | |||
20892 | ||||
20893 | // A shuffle of a single vector that is a splatted value can always be folded. | |||
20894 | if (SDValue V = combineShuffleOfSplatVal(SVN, DAG)) | |||
20895 | return V; | |||
20896 | ||||
20897 | if (SDValue V = formSplatFromShuffles(SVN, DAG)) | |||
20898 | return V; | |||
20899 | ||||
20900 | // If it is a splat, check if the argument vector is another splat or a | |||
20901 | // build_vector. | |||
20902 | if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { | |||
20903 | int SplatIndex = SVN->getSplatIndex(); | |||
20904 | if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) && | |||
20905 | TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) { | |||
20906 | // splat (vector_bo L, R), Index --> | |||
20907 | // splat (scalar_bo (extelt L, Index), (extelt R, Index)) | |||
20908 | SDValue L = N0.getOperand(0), R = N0.getOperand(1); | |||
20909 | SDLoc DL(N); | |||
20910 | EVT EltVT = VT.getScalarType(); | |||
20911 | SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL); | |||
20912 | SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index); | |||
20913 | SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index); | |||
20914 | SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR, | |||
20915 | N0.getNode()->getFlags()); | |||
20916 | SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO); | |||
20917 | SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0); | |||
20918 | return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask); | |||
20919 | } | |||
20920 | ||||
20921 | // If this is a bit convert that changes the element type of the vector but | |||
20922 | // not the number of vector elements, look through it. Be careful not to | |||
20923 | // look though conversions that change things like v4f32 to v2f64. | |||
20924 | SDNode *V = N0.getNode(); | |||
20925 | if (V->getOpcode() == ISD::BITCAST) { | |||
20926 | SDValue ConvInput = V->getOperand(0); | |||
20927 | if (ConvInput.getValueType().isVector() && | |||
20928 | ConvInput.getValueType().getVectorNumElements() == NumElts) | |||
20929 | V = ConvInput.getNode(); | |||
20930 | } | |||
20931 | ||||
20932 | if (V->getOpcode() == ISD::BUILD_VECTOR) { | |||
20933 | assert(V->getNumOperands() == NumElts &&((V->getNumOperands() == NumElts && "BUILD_VECTOR has wrong number of operands" ) ? static_cast<void> (0) : __assert_fail ("V->getNumOperands() == NumElts && \"BUILD_VECTOR has wrong number of operands\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20934, __PRETTY_FUNCTION__)) | |||
20934 | "BUILD_VECTOR has wrong number of operands")((V->getNumOperands() == NumElts && "BUILD_VECTOR has wrong number of operands" ) ? static_cast<void> (0) : __assert_fail ("V->getNumOperands() == NumElts && \"BUILD_VECTOR has wrong number of operands\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 20934, __PRETTY_FUNCTION__)); | |||
20935 | SDValue Base; | |||
20936 | bool AllSame = true; | |||
20937 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20938 | if (!V->getOperand(i).isUndef()) { | |||
20939 | Base = V->getOperand(i); | |||
20940 | break; | |||
20941 | } | |||
20942 | } | |||
20943 | // Splat of <u, u, u, u>, return <u, u, u, u> | |||
20944 | if (!Base.getNode()) | |||
20945 | return N0; | |||
20946 | for (unsigned i = 0; i != NumElts; ++i) { | |||
20947 | if (V->getOperand(i) != Base) { | |||
20948 | AllSame = false; | |||
20949 | break; | |||
20950 | } | |||
20951 | } | |||
20952 | // Splat of <x, x, x, x>, return <x, x, x, x> | |||
20953 | if (AllSame) | |||
20954 | return N0; | |||
20955 | ||||
20956 | // Canonicalize any other splat as a build_vector. | |||
20957 | SDValue Splatted = V->getOperand(SplatIndex); | |||
20958 | SmallVector<SDValue, 8> Ops(NumElts, Splatted); | |||
20959 | SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); | |||
20960 | ||||
20961 | // We may have jumped through bitcasts, so the type of the | |||
20962 | // BUILD_VECTOR may not match the type of the shuffle. | |||
20963 | if (V->getValueType(0) != VT) | |||
20964 | NewBV = DAG.getBitcast(VT, NewBV); | |||
20965 | return NewBV; | |||
20966 | } | |||
20967 | } | |||
20968 | ||||
20969 | // Simplify source operands based on shuffle mask. | |||
20970 | if (SimplifyDemandedVectorElts(SDValue(N, 0))) | |||
20971 | return SDValue(N, 0); | |||
20972 | ||||
20973 | // This is intentionally placed after demanded elements simplification because | |||
20974 | // it could eliminate knowledge of undef elements created by this shuffle. | |||
20975 | if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN)) | |||
20976 | return ShufOp; | |||
20977 | ||||
20978 | // Match shuffles that can be converted to any_vector_extend_in_reg. | |||
20979 | if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) | |||
20980 | return V; | |||
20981 | ||||
20982 | // Combine "truncate_vector_in_reg" style shuffles. | |||
20983 | if (SDValue V = combineTruncationShuffle(SVN, DAG)) | |||
20984 | return V; | |||
20985 | ||||
20986 | if (N0.getOpcode() == ISD::CONCAT_VECTORS && | |||
20987 | Level < AfterLegalizeVectorOps && | |||
20988 | (N1.isUndef() || | |||
20989 | (N1.getOpcode() == ISD::CONCAT_VECTORS && | |||
20990 | N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { | |||
20991 | if (SDValue V = partitionShuffleOfConcats(N, DAG)) | |||
20992 | return V; | |||
20993 | } | |||
20994 | ||||
20995 | // A shuffle of a concat of the same narrow vector can be reduced to use | |||
20996 | // only low-half elements of a concat with undef: | |||
20997 | // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask' | |||
20998 | if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() && | |||
20999 | N0.getNumOperands() == 2 && | |||
21000 | N0.getOperand(0) == N0.getOperand(1)) { | |||
21001 | int HalfNumElts = (int)NumElts / 2; | |||
21002 | SmallVector<int, 8> NewMask; | |||
21003 | for (unsigned i = 0; i != NumElts; ++i) { | |||
21004 | int Idx = SVN->getMaskElt(i); | |||
21005 | if (Idx >= HalfNumElts) { | |||
21006 | assert(Idx < (int)NumElts && "Shuffle mask chooses undef op")((Idx < (int)NumElts && "Shuffle mask chooses undef op" ) ? static_cast<void> (0) : __assert_fail ("Idx < (int)NumElts && \"Shuffle mask chooses undef op\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21006, __PRETTY_FUNCTION__)); | |||
21007 | Idx -= HalfNumElts; | |||
21008 | } | |||
21009 | NewMask.push_back(Idx); | |||
21010 | } | |||
21011 | if (TLI.isShuffleMaskLegal(NewMask, VT)) { | |||
21012 | SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType()); | |||
21013 | SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, | |||
21014 | N0.getOperand(0), UndefVec); | |||
21015 | return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask); | |||
21016 | } | |||
21017 | } | |||
21018 | ||||
21019 | // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - | |||
21020 | // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. | |||
21021 | if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) | |||
21022 | if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) | |||
21023 | return Res; | |||
21024 | ||||
21025 | // If this shuffle only has a single input that is a bitcasted shuffle, | |||
21026 | // attempt to merge the 2 shuffles and suitably bitcast the inputs/output | |||
21027 | // back to their original types. | |||
21028 | if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && | |||
21029 | N1.isUndef() && Level < AfterLegalizeVectorOps && | |||
21030 | TLI.isTypeLegal(VT)) { | |||
21031 | ||||
21032 | SDValue BC0 = peekThroughOneUseBitcasts(N0); | |||
21033 | if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { | |||
21034 | EVT SVT = VT.getScalarType(); | |||
21035 | EVT InnerVT = BC0->getValueType(0); | |||
21036 | EVT InnerSVT = InnerVT.getScalarType(); | |||
21037 | ||||
21038 | // Determine which shuffle works with the smaller scalar type. | |||
21039 | EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; | |||
21040 | EVT ScaleSVT = ScaleVT.getScalarType(); | |||
21041 | ||||
21042 | if (TLI.isTypeLegal(ScaleVT) && | |||
21043 | 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && | |||
21044 | 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { | |||
21045 | int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); | |||
21046 | int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); | |||
21047 | ||||
21048 | // Scale the shuffle masks to the smaller scalar type. | |||
21049 | ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); | |||
21050 | SmallVector<int, 8> InnerMask; | |||
21051 | SmallVector<int, 8> OuterMask; | |||
21052 | narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask); | |||
21053 | narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask); | |||
21054 | ||||
21055 | // Merge the shuffle masks. | |||
21056 | SmallVector<int, 8> NewMask; | |||
21057 | for (int M : OuterMask) | |||
21058 | NewMask.push_back(M < 0 ? -1 : InnerMask[M]); | |||
21059 | ||||
21060 | // Test for shuffle mask legality over both commutations. | |||
21061 | SDValue SV0 = BC0->getOperand(0); | |||
21062 | SDValue SV1 = BC0->getOperand(1); | |||
21063 | bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); | |||
21064 | if (!LegalMask) { | |||
21065 | std::swap(SV0, SV1); | |||
21066 | ShuffleVectorSDNode::commuteMask(NewMask); | |||
21067 | LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); | |||
21068 | } | |||
21069 | ||||
21070 | if (LegalMask) { | |||
21071 | SV0 = DAG.getBitcast(ScaleVT, SV0); | |||
21072 | SV1 = DAG.getBitcast(ScaleVT, SV1); | |||
21073 | return DAG.getBitcast( | |||
21074 | VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); | |||
21075 | } | |||
21076 | } | |||
21077 | } | |||
21078 | } | |||
21079 | ||||
21080 | // Compute the combined shuffle mask for a shuffle with SV0 as the first | |||
21081 | // operand, and SV1 as the second operand. | |||
21082 | // i.e. Merge SVN(OtherSVN, N1) -> shuffle(SV0, SV1, Mask) iff Commute = false | |||
21083 | // Merge SVN(N1, OtherSVN) -> shuffle(SV0, SV1, Mask') iff Commute = true | |||
21084 | auto MergeInnerShuffle = | |||
21085 | [NumElts, &VT](bool Commute, ShuffleVectorSDNode *SVN, | |||
21086 | ShuffleVectorSDNode *OtherSVN, SDValue N1, | |||
21087 | const TargetLowering &TLI, SDValue &SV0, SDValue &SV1, | |||
21088 | SmallVectorImpl<int> &Mask) -> bool { | |||
21089 | // Don't try to fold splats; they're likely to simplify somehow, or they | |||
21090 | // might be free. | |||
21091 | if (OtherSVN->isSplat()) | |||
21092 | return false; | |||
21093 | ||||
21094 | SV0 = SV1 = SDValue(); | |||
21095 | Mask.clear(); | |||
21096 | ||||
21097 | for (unsigned i = 0; i != NumElts; ++i) { | |||
21098 | int Idx = SVN->getMaskElt(i); | |||
21099 | if (Idx < 0) { | |||
21100 | // Propagate Undef. | |||
21101 | Mask.push_back(Idx); | |||
21102 | continue; | |||
21103 | } | |||
21104 | ||||
21105 | if (Commute) | |||
21106 | Idx = (Idx < (int)NumElts) ? (Idx + NumElts) : (Idx - NumElts); | |||
21107 | ||||
21108 | SDValue CurrentVec; | |||
21109 | if (Idx < (int)NumElts) { | |||
21110 | // This shuffle index refers to the inner shuffle N0. Lookup the inner | |||
21111 | // shuffle mask to identify which vector is actually referenced. | |||
21112 | Idx = OtherSVN->getMaskElt(Idx); | |||
21113 | if (Idx < 0) { | |||
21114 | // Propagate Undef. | |||
21115 | Mask.push_back(Idx); | |||
21116 | continue; | |||
21117 | } | |||
21118 | CurrentVec = (Idx < (int)NumElts) ? OtherSVN->getOperand(0) | |||
21119 | : OtherSVN->getOperand(1); | |||
21120 | } else { | |||
21121 | // This shuffle index references an element within N1. | |||
21122 | CurrentVec = N1; | |||
21123 | } | |||
21124 | ||||
21125 | // Simple case where 'CurrentVec' is UNDEF. | |||
21126 | if (CurrentVec.isUndef()) { | |||
21127 | Mask.push_back(-1); | |||
21128 | continue; | |||
21129 | } | |||
21130 | ||||
21131 | // Canonicalize the shuffle index. We don't know yet if CurrentVec | |||
21132 | // will be the first or second operand of the combined shuffle. | |||
21133 | Idx = Idx % NumElts; | |||
21134 | if (!SV0.getNode() || SV0 == CurrentVec) { | |||
21135 | // Ok. CurrentVec is the left hand side. | |||
21136 | // Update the mask accordingly. | |||
21137 | SV0 = CurrentVec; | |||
21138 | Mask.push_back(Idx); | |||
21139 | continue; | |||
21140 | } | |||
21141 | if (!SV1.getNode() || SV1 == CurrentVec) { | |||
21142 | // Ok. CurrentVec is the right hand side. | |||
21143 | // Update the mask accordingly. | |||
21144 | SV1 = CurrentVec; | |||
21145 | Mask.push_back(Idx + NumElts); | |||
21146 | continue; | |||
21147 | } | |||
21148 | ||||
21149 | // Last chance - see if the vector is another shuffle and if it | |||
21150 | // uses one of the existing candidate shuffle ops. | |||
21151 | if (auto *CurrentSVN = dyn_cast<ShuffleVectorSDNode>(CurrentVec)) { | |||
21152 | int InnerIdx = CurrentSVN->getMaskElt(Idx); | |||
21153 | if (InnerIdx < 0) { | |||
21154 | Mask.push_back(-1); | |||
21155 | continue; | |||
21156 | } | |||
21157 | SDValue InnerVec = (InnerIdx < (int)NumElts) | |||
21158 | ? CurrentSVN->getOperand(0) | |||
21159 | : CurrentSVN->getOperand(1); | |||
21160 | if (InnerVec.isUndef()) { | |||
21161 | Mask.push_back(-1); | |||
21162 | continue; | |||
21163 | } | |||
21164 | InnerIdx %= NumElts; | |||
21165 | if (InnerVec == SV0) { | |||
21166 | Mask.push_back(InnerIdx); | |||
21167 | continue; | |||
21168 | } | |||
21169 | if (InnerVec == SV1) { | |||
21170 | Mask.push_back(InnerIdx + NumElts); | |||
21171 | continue; | |||
21172 | } | |||
21173 | } | |||
21174 | ||||
21175 | // Bail out if we cannot convert the shuffle pair into a single shuffle. | |||
21176 | return false; | |||
21177 | } | |||
21178 | ||||
21179 | if (llvm::all_of(Mask, [](int M) { return M < 0; })) | |||
21180 | return true; | |||
21181 | ||||
21182 | // Avoid introducing shuffles with illegal mask. | |||
21183 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) | |||
21184 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) | |||
21185 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) | |||
21186 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) | |||
21187 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) | |||
21188 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) | |||
21189 | if (TLI.isShuffleMaskLegal(Mask, VT)) | |||
21190 | return true; | |||
21191 | ||||
21192 | std::swap(SV0, SV1); | |||
21193 | ShuffleVectorSDNode::commuteMask(Mask); | |||
21194 | return TLI.isShuffleMaskLegal(Mask, VT); | |||
21195 | }; | |||
21196 | ||||
21197 | if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { | |||
21198 | // Canonicalize shuffles according to rules: | |||
21199 | // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) | |||
21200 | // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) | |||
21201 | // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) | |||
21202 | if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && | |||
21203 | N0.getOpcode() != ISD::VECTOR_SHUFFLE) { | |||
21204 | // The incoming shuffle must be of the same type as the result of the | |||
21205 | // current shuffle. | |||
21206 | assert(N1->getOperand(0).getValueType() == VT &&((N1->getOperand(0).getValueType() == VT && "Shuffle types don't match" ) ? static_cast<void> (0) : __assert_fail ("N1->getOperand(0).getValueType() == VT && \"Shuffle types don't match\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21207, __PRETTY_FUNCTION__)) | |||
21207 | "Shuffle types don't match")((N1->getOperand(0).getValueType() == VT && "Shuffle types don't match" ) ? static_cast<void> (0) : __assert_fail ("N1->getOperand(0).getValueType() == VT && \"Shuffle types don't match\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21207, __PRETTY_FUNCTION__)); | |||
21208 | ||||
21209 | SDValue SV0 = N1->getOperand(0); | |||
21210 | SDValue SV1 = N1->getOperand(1); | |||
21211 | bool HasSameOp0 = N0 == SV0; | |||
21212 | bool IsSV1Undef = SV1.isUndef(); | |||
21213 | if (HasSameOp0 || IsSV1Undef || N0 == SV1) | |||
21214 | // Commute the operands of this shuffle so merging below will trigger. | |||
21215 | return DAG.getCommutedVectorShuffle(*SVN); | |||
21216 | } | |||
21217 | ||||
21218 | // Canonicalize splat shuffles to the RHS to improve merging below. | |||
21219 | // shuffle(splat(A,u), shuffle(C,D)) -> shuffle'(shuffle(C,D), splat(A,u)) | |||
21220 | if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && | |||
21221 | N1.getOpcode() == ISD::VECTOR_SHUFFLE && | |||
21222 | cast<ShuffleVectorSDNode>(N0)->isSplat() && | |||
21223 | !cast<ShuffleVectorSDNode>(N1)->isSplat()) { | |||
21224 | return DAG.getCommutedVectorShuffle(*SVN); | |||
21225 | } | |||
21226 | ||||
21227 | // Try to fold according to rules: | |||
21228 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) | |||
21229 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) | |||
21230 | // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) | |||
21231 | // Don't try to fold shuffles with illegal type. | |||
21232 | // Only fold if this shuffle is the only user of the other shuffle. | |||
21233 | // Try matching shuffle(C,shuffle(A,B)) commutted patterns as well. | |||
21234 | for (int i = 0; i != 2; ++i) { | |||
21235 | if (N->getOperand(i).getOpcode() == ISD::VECTOR_SHUFFLE && | |||
21236 | N->isOnlyUserOf(N->getOperand(i).getNode())) { | |||
21237 | // The incoming shuffle must be of the same type as the result of the | |||
21238 | // current shuffle. | |||
21239 | auto *OtherSV = cast<ShuffleVectorSDNode>(N->getOperand(i)); | |||
21240 | assert(OtherSV->getOperand(0).getValueType() == VT &&((OtherSV->getOperand(0).getValueType() == VT && "Shuffle types don't match" ) ? static_cast<void> (0) : __assert_fail ("OtherSV->getOperand(0).getValueType() == VT && \"Shuffle types don't match\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21241, __PRETTY_FUNCTION__)) | |||
21241 | "Shuffle types don't match")((OtherSV->getOperand(0).getValueType() == VT && "Shuffle types don't match" ) ? static_cast<void> (0) : __assert_fail ("OtherSV->getOperand(0).getValueType() == VT && \"Shuffle types don't match\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21241, __PRETTY_FUNCTION__)); | |||
21242 | ||||
21243 | SDValue SV0, SV1; | |||
21244 | SmallVector<int, 4> Mask; | |||
21245 | if (MergeInnerShuffle(i != 0, SVN, OtherSV, N->getOperand(1 - i), TLI, | |||
21246 | SV0, SV1, Mask)) { | |||
21247 | // Check if all indices in Mask are Undef. In case, propagate Undef. | |||
21248 | if (llvm::all_of(Mask, [](int M) { return M < 0; })) | |||
21249 | return DAG.getUNDEF(VT); | |||
21250 | ||||
21251 | return DAG.getVectorShuffle(VT, SDLoc(N), | |||
21252 | SV0 ? SV0 : DAG.getUNDEF(VT), | |||
21253 | SV1 ? SV1 : DAG.getUNDEF(VT), Mask); | |||
21254 | } | |||
21255 | } | |||
21256 | } | |||
21257 | ||||
21258 | // Merge shuffles through binops if we are able to merge it with at least | |||
21259 | // one other shuffles. | |||
21260 | // shuffle(bop(shuffle(x,y),shuffle(z,w)),undef) | |||
21261 | // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d))) | |||
21262 | unsigned SrcOpcode = N0.getOpcode(); | |||
21263 | if (TLI.isBinOp(SrcOpcode) && N->isOnlyUserOf(N0.getNode()) && | |||
21264 | (N1.isUndef() || | |||
21265 | (SrcOpcode == N1.getOpcode() && N->isOnlyUserOf(N1.getNode())))) { | |||
21266 | // Get binop source ops, or just pass on the undef. | |||
21267 | SDValue Op00 = N0.getOperand(0); | |||
21268 | SDValue Op01 = N0.getOperand(1); | |||
21269 | SDValue Op10 = N1.isUndef() ? N1 : N1.getOperand(0); | |||
21270 | SDValue Op11 = N1.isUndef() ? N1 : N1.getOperand(1); | |||
21271 | // TODO: We might be able to relax the VT check but we don't currently | |||
21272 | // have any isBinOp() that has different result/ops VTs so play safe until | |||
21273 | // we have test coverage. | |||
21274 | if (Op00.getValueType() == VT && Op10.getValueType() == VT && | |||
21275 | Op01.getValueType() == VT && Op11.getValueType() == VT && | |||
21276 | (Op00.getOpcode() == ISD::VECTOR_SHUFFLE || | |||
21277 | Op10.getOpcode() == ISD::VECTOR_SHUFFLE || | |||
21278 | Op01.getOpcode() == ISD::VECTOR_SHUFFLE || | |||
21279 | Op11.getOpcode() == ISD::VECTOR_SHUFFLE)) { | |||
21280 | auto CanMergeInnerShuffle = [&](SDValue &SV0, SDValue &SV1, | |||
21281 | SmallVectorImpl<int> &Mask, bool LeftOp, | |||
21282 | bool Commute) { | |||
21283 | SDValue InnerN = Commute ? N1 : N0; | |||
21284 | SDValue Op0 = LeftOp ? Op00 : Op01; | |||
21285 | SDValue Op1 = LeftOp ? Op10 : Op11; | |||
21286 | if (Commute) | |||
21287 | std::swap(Op0, Op1); | |||
21288 | // Only accept the merged shuffle if we don't introduce undef elements, | |||
21289 | // or the inner shuffle already contained undef elements. | |||
21290 | auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(Op0); | |||
21291 | return SVN0 && InnerN->isOnlyUserOf(SVN0) && | |||
21292 | MergeInnerShuffle(Commute, SVN, SVN0, Op1, TLI, SV0, SV1, | |||
21293 | Mask) && | |||
21294 | (llvm::any_of(SVN0->getMask(), [](int M) { return M < 0; }) || | |||
21295 | llvm::none_of(Mask, [](int M) { return M < 0; })); | |||
21296 | }; | |||
21297 | ||||
21298 | // Ensure we don't increase the number of shuffles - we must merge a | |||
21299 | // shuffle from at least one of the LHS and RHS ops. | |||
21300 | bool MergedLeft = false; | |||
21301 | SDValue LeftSV0, LeftSV1; | |||
21302 | SmallVector<int, 4> LeftMask; | |||
21303 | if (CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, false) || | |||
21304 | CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, true)) { | |||
21305 | MergedLeft = true; | |||
21306 | } else { | |||
21307 | LeftMask.assign(SVN->getMask().begin(), SVN->getMask().end()); | |||
21308 | LeftSV0 = Op00, LeftSV1 = Op10; | |||
21309 | } | |||
21310 | ||||
21311 | bool MergedRight = false; | |||
21312 | SDValue RightSV0, RightSV1; | |||
21313 | SmallVector<int, 4> RightMask; | |||
21314 | if (CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, false) || | |||
21315 | CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, true)) { | |||
21316 | MergedRight = true; | |||
21317 | } else { | |||
21318 | RightMask.assign(SVN->getMask().begin(), SVN->getMask().end()); | |||
21319 | RightSV0 = Op01, RightSV1 = Op11; | |||
21320 | } | |||
21321 | ||||
21322 | if (MergedLeft || MergedRight) { | |||
21323 | SDLoc DL(N); | |||
21324 | SDValue LHS = DAG.getVectorShuffle( | |||
21325 | VT, DL, LeftSV0 ? LeftSV0 : DAG.getUNDEF(VT), | |||
21326 | LeftSV1 ? LeftSV1 : DAG.getUNDEF(VT), LeftMask); | |||
21327 | SDValue RHS = DAG.getVectorShuffle( | |||
21328 | VT, DL, RightSV0 ? RightSV0 : DAG.getUNDEF(VT), | |||
21329 | RightSV1 ? RightSV1 : DAG.getUNDEF(VT), RightMask); | |||
21330 | return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS); | |||
21331 | } | |||
21332 | } | |||
21333 | } | |||
21334 | } | |||
21335 | ||||
21336 | if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG)) | |||
21337 | return V; | |||
21338 | ||||
21339 | return SDValue(); | |||
21340 | } | |||
21341 | ||||
21342 | SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { | |||
21343 | SDValue InVal = N->getOperand(0); | |||
21344 | EVT VT = N->getValueType(0); | |||
21345 | ||||
21346 | // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern | |||
21347 | // with a VECTOR_SHUFFLE and possible truncate. | |||
21348 | if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && | |||
21349 | VT.isFixedLengthVector() && | |||
21350 | InVal->getOperand(0).getValueType().isFixedLengthVector()) { | |||
21351 | SDValue InVec = InVal->getOperand(0); | |||
21352 | SDValue EltNo = InVal->getOperand(1); | |||
21353 | auto InVecT = InVec.getValueType(); | |||
21354 | if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { | |||
21355 | SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); | |||
21356 | int Elt = C0->getZExtValue(); | |||
21357 | NewMask[0] = Elt; | |||
21358 | // If we have an implict truncate do truncate here as long as it's legal. | |||
21359 | // if it's not legal, this should | |||
21360 | if (VT.getScalarType() != InVal.getValueType() && | |||
21361 | InVal.getValueType().isScalarInteger() && | |||
21362 | isTypeLegal(VT.getScalarType())) { | |||
21363 | SDValue Val = | |||
21364 | DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); | |||
21365 | return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); | |||
21366 | } | |||
21367 | if (VT.getScalarType() == InVecT.getScalarType() && | |||
21368 | VT.getVectorNumElements() <= InVecT.getVectorNumElements()) { | |||
21369 | SDValue LegalShuffle = | |||
21370 | TLI.buildLegalVectorShuffle(InVecT, SDLoc(N), InVec, | |||
21371 | DAG.getUNDEF(InVecT), NewMask, DAG); | |||
21372 | if (LegalShuffle) { | |||
21373 | // If the initial vector is the correct size this shuffle is a | |||
21374 | // valid result. | |||
21375 | if (VT == InVecT) | |||
21376 | return LegalShuffle; | |||
21377 | // If not we must truncate the vector. | |||
21378 | if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { | |||
21379 | SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N)); | |||
21380 | EVT SubVT = EVT::getVectorVT(*DAG.getContext(), | |||
21381 | InVecT.getVectorElementType(), | |||
21382 | VT.getVectorNumElements()); | |||
21383 | return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, | |||
21384 | LegalShuffle, ZeroIdx); | |||
21385 | } | |||
21386 | } | |||
21387 | } | |||
21388 | } | |||
21389 | } | |||
21390 | ||||
21391 | return SDValue(); | |||
21392 | } | |||
21393 | ||||
21394 | SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { | |||
21395 | EVT VT = N->getValueType(0); | |||
21396 | SDValue N0 = N->getOperand(0); | |||
21397 | SDValue N1 = N->getOperand(1); | |||
21398 | SDValue N2 = N->getOperand(2); | |||
21399 | uint64_t InsIdx = N->getConstantOperandVal(2); | |||
21400 | ||||
21401 | // If inserting an UNDEF, just return the original vector. | |||
21402 | if (N1.isUndef()) | |||
21403 | return N0; | |||
21404 | ||||
21405 | // If this is an insert of an extracted vector into an undef vector, we can | |||
21406 | // just use the input to the extract. | |||
21407 | if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && | |||
21408 | N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) | |||
21409 | return N1.getOperand(0); | |||
21410 | ||||
21411 | // If we are inserting a bitcast value into an undef, with the same | |||
21412 | // number of elements, just use the bitcast input of the extract. | |||
21413 | // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> | |||
21414 | // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) | |||
21415 | if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && | |||
21416 | N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && | |||
21417 | N1.getOperand(0).getOperand(1) == N2 && | |||
21418 | N1.getOperand(0).getOperand(0).getValueType().getVectorElementCount() == | |||
21419 | VT.getVectorElementCount() && | |||
21420 | N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == | |||
21421 | VT.getSizeInBits()) { | |||
21422 | return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); | |||
21423 | } | |||
21424 | ||||
21425 | // If both N1 and N2 are bitcast values on which insert_subvector | |||
21426 | // would makes sense, pull the bitcast through. | |||
21427 | // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> | |||
21428 | // BITCAST (INSERT_SUBVECTOR N0 N1 N2) | |||
21429 | if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { | |||
21430 | SDValue CN0 = N0.getOperand(0); | |||
21431 | SDValue CN1 = N1.getOperand(0); | |||
21432 | EVT CN0VT = CN0.getValueType(); | |||
21433 | EVT CN1VT = CN1.getValueType(); | |||
21434 | if (CN0VT.isVector() && CN1VT.isVector() && | |||
21435 | CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && | |||
21436 | CN0VT.getVectorElementCount() == VT.getVectorElementCount()) { | |||
21437 | SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), | |||
21438 | CN0.getValueType(), CN0, CN1, N2); | |||
21439 | return DAG.getBitcast(VT, NewINSERT); | |||
21440 | } | |||
21441 | } | |||
21442 | ||||
21443 | // Combine INSERT_SUBVECTORs where we are inserting to the same index. | |||
21444 | // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) | |||
21445 | // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) | |||
21446 | if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && | |||
21447 | N0.getOperand(1).getValueType() == N1.getValueType() && | |||
21448 | N0.getOperand(2) == N2) | |||
21449 | return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), | |||
21450 | N1, N2); | |||
21451 | ||||
21452 | // Eliminate an intermediate insert into an undef vector: | |||
21453 | // insert_subvector undef, (insert_subvector undef, X, 0), N2 --> | |||
21454 | // insert_subvector undef, X, N2 | |||
21455 | if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR && | |||
21456 | N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2))) | |||
21457 | return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0, | |||
21458 | N1.getOperand(1), N2); | |||
21459 | ||||
21460 | // Push subvector bitcasts to the output, adjusting the index as we go. | |||
21461 | // insert_subvector(bitcast(v), bitcast(s), c1) | |||
21462 | // -> bitcast(insert_subvector(v, s, c2)) | |||
21463 | if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) && | |||
21464 | N1.getOpcode() == ISD::BITCAST) { | |||
21465 | SDValue N0Src = peekThroughBitcasts(N0); | |||
21466 | SDValue N1Src = peekThroughBitcasts(N1); | |||
21467 | EVT N0SrcSVT = N0Src.getValueType().getScalarType(); | |||
21468 | EVT N1SrcSVT = N1Src.getValueType().getScalarType(); | |||
21469 | if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) && | |||
21470 | N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) { | |||
21471 | EVT NewVT; | |||
21472 | SDLoc DL(N); | |||
21473 | SDValue NewIdx; | |||
21474 | LLVMContext &Ctx = *DAG.getContext(); | |||
21475 | ElementCount NumElts = VT.getVectorElementCount(); | |||
21476 | unsigned EltSizeInBits = VT.getScalarSizeInBits(); | |||
21477 | if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) { | |||
21478 | unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits(); | |||
21479 | NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale); | |||
21480 | NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL); | |||
21481 | } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) { | |||
21482 | unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits; | |||
21483 | if (NumElts.isKnownMultipleOf(Scale) && (InsIdx % Scale) == 0) { | |||
21484 | NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, | |||
21485 | NumElts.divideCoefficientBy(Scale)); | |||
21486 | NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL); | |||
21487 | } | |||
21488 | } | |||
21489 | if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) { | |||
21490 | SDValue Res = DAG.getBitcast(NewVT, N0Src); | |||
21491 | Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx); | |||
21492 | return DAG.getBitcast(VT, Res); | |||
21493 | } | |||
21494 | } | |||
21495 | } | |||
21496 | ||||
21497 | // Canonicalize insert_subvector dag nodes. | |||
21498 | // Example: | |||
21499 | // (insert_subvector (insert_subvector A, Idx0), Idx1) | |||
21500 | // -> (insert_subvector (insert_subvector A, Idx1), Idx0) | |||
21501 | if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && | |||
21502 | N1.getValueType() == N0.getOperand(1).getValueType()) { | |||
21503 | unsigned OtherIdx = N0.getConstantOperandVal(2); | |||
21504 | if (InsIdx < OtherIdx) { | |||
21505 | // Swap nodes. | |||
21506 | SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, | |||
21507 | N0.getOperand(0), N1, N2); | |||
21508 | AddToWorklist(NewOp.getNode()); | |||
21509 | return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), | |||
21510 | VT, NewOp, N0.getOperand(1), N0.getOperand(2)); | |||
21511 | } | |||
21512 | } | |||
21513 | ||||
21514 | // If the input vector is a concatenation, and the insert replaces | |||
21515 | // one of the pieces, we can optimize into a single concat_vectors. | |||
21516 | if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && | |||
21517 | N0.getOperand(0).getValueType() == N1.getValueType() && | |||
21518 | N0.getOperand(0).getValueType().isScalableVector() == | |||
21519 | N1.getValueType().isScalableVector()) { | |||
21520 | unsigned Factor = N1.getValueType().getVectorMinNumElements(); | |||
21521 | SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); | |||
21522 | Ops[InsIdx / Factor] = N1; | |||
21523 | return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); | |||
21524 | } | |||
21525 | ||||
21526 | // Simplify source operands based on insertion. | |||
21527 | if (SimplifyDemandedVectorElts(SDValue(N, 0))) | |||
21528 | return SDValue(N, 0); | |||
21529 | ||||
21530 | return SDValue(); | |||
21531 | } | |||
21532 | ||||
21533 | SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { | |||
21534 | SDValue N0 = N->getOperand(0); | |||
21535 | ||||
21536 | // fold (fp_to_fp16 (fp16_to_fp op)) -> op | |||
21537 | if (N0->getOpcode() == ISD::FP16_TO_FP) | |||
21538 | return N0->getOperand(0); | |||
21539 | ||||
21540 | return SDValue(); | |||
21541 | } | |||
21542 | ||||
21543 | SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { | |||
21544 | SDValue N0 = N->getOperand(0); | |||
21545 | ||||
21546 | // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) | |||
21547 | if (!TLI.shouldKeepZExtForFP16Conv() && N0->getOpcode() == ISD::AND) { | |||
21548 | ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); | |||
21549 | if (AndConst && AndConst->getAPIntValue() == 0xffff) { | |||
21550 | return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), | |||
21551 | N0.getOperand(0)); | |||
21552 | } | |||
21553 | } | |||
21554 | ||||
21555 | return SDValue(); | |||
21556 | } | |||
21557 | ||||
21558 | SDValue DAGCombiner::visitVECREDUCE(SDNode *N) { | |||
21559 | SDValue N0 = N->getOperand(0); | |||
21560 | EVT VT = N0.getValueType(); | |||
21561 | unsigned Opcode = N->getOpcode(); | |||
21562 | ||||
21563 | // VECREDUCE over 1-element vector is just an extract. | |||
21564 | if (VT.getVectorElementCount().isScalar()) { | |||
21565 | SDLoc dl(N); | |||
21566 | SDValue Res = | |||
21567 | DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0, | |||
21568 | DAG.getVectorIdxConstant(0, dl)); | |||
21569 | if (Res.getValueType() != N->getValueType(0)) | |||
21570 | Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res); | |||
21571 | return Res; | |||
21572 | } | |||
21573 | ||||
21574 | // On an boolean vector an and/or reduction is the same as a umin/umax | |||
21575 | // reduction. Convert them if the latter is legal while the former isn't. | |||
21576 | if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) { | |||
21577 | unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND | |||
21578 | ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX; | |||
21579 | if (!TLI.isOperationLegalOrCustom(Opcode, VT) && | |||
21580 | TLI.isOperationLegalOrCustom(NewOpcode, VT) && | |||
21581 | DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits()) | |||
21582 | return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0); | |||
21583 | } | |||
21584 | ||||
21585 | return SDValue(); | |||
21586 | } | |||
21587 | ||||
21588 | /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle | |||
21589 | /// with the destination vector and a zero vector. | |||
21590 | /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> | |||
21591 | /// vector_shuffle V, Zero, <0, 4, 2, 4> | |||
21592 | SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { | |||
21593 | assert(N->getOpcode() == ISD::AND && "Unexpected opcode!")((N->getOpcode() == ISD::AND && "Unexpected opcode!" ) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::AND && \"Unexpected opcode!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21593, __PRETTY_FUNCTION__)); | |||
21594 | ||||
21595 | EVT VT = N->getValueType(0); | |||
21596 | SDValue LHS = N->getOperand(0); | |||
21597 | SDValue RHS = peekThroughBitcasts(N->getOperand(1)); | |||
21598 | SDLoc DL(N); | |||
21599 | ||||
21600 | // Make sure we're not running after operation legalization where it | |||
21601 | // may have custom lowered the vector shuffles. | |||
21602 | if (LegalOperations) | |||
21603 | return SDValue(); | |||
21604 | ||||
21605 | if (RHS.getOpcode() != ISD::BUILD_VECTOR) | |||
21606 | return SDValue(); | |||
21607 | ||||
21608 | EVT RVT = RHS.getValueType(); | |||
21609 | unsigned NumElts = RHS.getNumOperands(); | |||
21610 | ||||
21611 | // Attempt to create a valid clear mask, splitting the mask into | |||
21612 | // sub elements and checking to see if each is | |||
21613 | // all zeros or all ones - suitable for shuffle masking. | |||
21614 | auto BuildClearMask = [&](int Split) { | |||
21615 | int NumSubElts = NumElts * Split; | |||
21616 | int NumSubBits = RVT.getScalarSizeInBits() / Split; | |||
21617 | ||||
21618 | SmallVector<int, 8> Indices; | |||
21619 | for (int i = 0; i != NumSubElts; ++i) { | |||
21620 | int EltIdx = i / Split; | |||
21621 | int SubIdx = i % Split; | |||
21622 | SDValue Elt = RHS.getOperand(EltIdx); | |||
21623 | // X & undef --> 0 (not undef). So this lane must be converted to choose | |||
21624 | // from the zero constant vector (same as if the element had all 0-bits). | |||
21625 | if (Elt.isUndef()) { | |||
21626 | Indices.push_back(i + NumSubElts); | |||
21627 | continue; | |||
21628 | } | |||
21629 | ||||
21630 | APInt Bits; | |||
21631 | if (isa<ConstantSDNode>(Elt)) | |||
21632 | Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); | |||
21633 | else if (isa<ConstantFPSDNode>(Elt)) | |||
21634 | Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); | |||
21635 | else | |||
21636 | return SDValue(); | |||
21637 | ||||
21638 | // Extract the sub element from the constant bit mask. | |||
21639 | if (DAG.getDataLayout().isBigEndian()) | |||
21640 | Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits); | |||
21641 | else | |||
21642 | Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits); | |||
21643 | ||||
21644 | if (Bits.isAllOnesValue()) | |||
21645 | Indices.push_back(i); | |||
21646 | else if (Bits == 0) | |||
21647 | Indices.push_back(i + NumSubElts); | |||
21648 | else | |||
21649 | return SDValue(); | |||
21650 | } | |||
21651 | ||||
21652 | // Let's see if the target supports this vector_shuffle. | |||
21653 | EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); | |||
21654 | EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); | |||
21655 | if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) | |||
21656 | return SDValue(); | |||
21657 | ||||
21658 | SDValue Zero = DAG.getConstant(0, DL, ClearVT); | |||
21659 | return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, | |||
21660 | DAG.getBitcast(ClearVT, LHS), | |||
21661 | Zero, Indices)); | |||
21662 | }; | |||
21663 | ||||
21664 | // Determine maximum split level (byte level masking). | |||
21665 | int MaxSplit = 1; | |||
21666 | if (RVT.getScalarSizeInBits() % 8 == 0) | |||
21667 | MaxSplit = RVT.getScalarSizeInBits() / 8; | |||
21668 | ||||
21669 | for (int Split = 1; Split <= MaxSplit; ++Split) | |||
21670 | if (RVT.getScalarSizeInBits() % Split == 0) | |||
21671 | if (SDValue S = BuildClearMask(Split)) | |||
21672 | return S; | |||
21673 | ||||
21674 | return SDValue(); | |||
21675 | } | |||
21676 | ||||
21677 | /// If a vector binop is performed on splat values, it may be profitable to | |||
21678 | /// extract, scalarize, and insert/splat. | |||
21679 | static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG) { | |||
21680 | SDValue N0 = N->getOperand(0); | |||
21681 | SDValue N1 = N->getOperand(1); | |||
21682 | unsigned Opcode = N->getOpcode(); | |||
21683 | EVT VT = N->getValueType(0); | |||
21684 | EVT EltVT = VT.getVectorElementType(); | |||
21685 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); | |||
21686 | ||||
21687 | // TODO: Remove/replace the extract cost check? If the elements are available | |||
21688 | // as scalars, then there may be no extract cost. Should we ask if | |||
21689 | // inserting a scalar back into a vector is cheap instead? | |||
21690 | int Index0, Index1; | |||
21691 | SDValue Src0 = DAG.getSplatSourceVector(N0, Index0); | |||
21692 | SDValue Src1 = DAG.getSplatSourceVector(N1, Index1); | |||
21693 | if (!Src0 || !Src1 || Index0 != Index1 || | |||
21694 | Src0.getValueType().getVectorElementType() != EltVT || | |||
21695 | Src1.getValueType().getVectorElementType() != EltVT || | |||
21696 | !TLI.isExtractVecEltCheap(VT, Index0) || | |||
21697 | !TLI.isOperationLegalOrCustom(Opcode, EltVT)) | |||
21698 | return SDValue(); | |||
21699 | ||||
21700 | SDLoc DL(N); | |||
21701 | SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL); | |||
21702 | SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src0, IndexC); | |||
21703 | SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src1, IndexC); | |||
21704 | SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags()); | |||
21705 | ||||
21706 | // If all lanes but 1 are undefined, no need to splat the scalar result. | |||
21707 | // TODO: Keep track of undefs and use that info in the general case. | |||
21708 | if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() && | |||
21709 | count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 && | |||
21710 | count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) { | |||
21711 | // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) --> | |||
21712 | // build_vec ..undef, (bo X, Y), undef... | |||
21713 | SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT)); | |||
21714 | Ops[Index0] = ScalarBO; | |||
21715 | return DAG.getBuildVector(VT, DL, Ops); | |||
21716 | } | |||
21717 | ||||
21718 | // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index | |||
21719 | SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO); | |||
21720 | return DAG.getBuildVector(VT, DL, Ops); | |||
21721 | } | |||
21722 | ||||
21723 | /// Visit a binary vector operation, like ADD. | |||
21724 | SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { | |||
21725 | assert(N->getValueType(0).isVector() &&((N->getValueType(0).isVector() && "SimplifyVBinOp only works on vectors!" ) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0).isVector() && \"SimplifyVBinOp only works on vectors!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21726, __PRETTY_FUNCTION__)) | |||
21726 | "SimplifyVBinOp only works on vectors!")((N->getValueType(0).isVector() && "SimplifyVBinOp only works on vectors!" ) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0).isVector() && \"SimplifyVBinOp only works on vectors!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21726, __PRETTY_FUNCTION__)); | |||
21727 | ||||
21728 | SDValue LHS = N->getOperand(0); | |||
21729 | SDValue RHS = N->getOperand(1); | |||
21730 | SDValue Ops[] = {LHS, RHS}; | |||
21731 | EVT VT = N->getValueType(0); | |||
21732 | unsigned Opcode = N->getOpcode(); | |||
21733 | SDNodeFlags Flags = N->getFlags(); | |||
21734 | ||||
21735 | // See if we can constant fold the vector operation. | |||
21736 | if (SDValue Fold = DAG.FoldConstantVectorArithmetic( | |||
21737 | Opcode, SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) | |||
21738 | return Fold; | |||
21739 | ||||
21740 | // Move unary shuffles with identical masks after a vector binop: | |||
21741 | // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask)) | |||
21742 | // --> shuffle (VBinOp A, B), Undef, Mask | |||
21743 | // This does not require type legality checks because we are creating the | |||
21744 | // same types of operations that are in the original sequence. We do have to | |||
21745 | // restrict ops like integer div that have immediate UB (eg, div-by-zero) | |||
21746 | // though. This code is adapted from the identical transform in instcombine. | |||
21747 | if (Opcode != ISD::UDIV && Opcode != ISD::SDIV && | |||
21748 | Opcode != ISD::UREM && Opcode != ISD::SREM && | |||
21749 | Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) { | |||
21750 | auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS); | |||
21751 | auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS); | |||
21752 | if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) && | |||
21753 | LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() && | |||
21754 | (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) { | |||
21755 | SDLoc DL(N); | |||
21756 | SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0), | |||
21757 | RHS.getOperand(0), Flags); | |||
21758 | SDValue UndefV = LHS.getOperand(1); | |||
21759 | return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask()); | |||
21760 | } | |||
21761 | ||||
21762 | // Try to sink a splat shuffle after a binop with a uniform constant. | |||
21763 | // This is limited to cases where neither the shuffle nor the constant have | |||
21764 | // undefined elements because that could be poison-unsafe or inhibit | |||
21765 | // demanded elements analysis. It is further limited to not change a splat | |||
21766 | // of an inserted scalar because that may be optimized better by | |||
21767 | // load-folding or other target-specific behaviors. | |||
21768 | if (isConstOrConstSplat(RHS) && Shuf0 && is_splat(Shuf0->getMask()) && | |||
21769 | Shuf0->hasOneUse() && Shuf0->getOperand(1).isUndef() && | |||
21770 | Shuf0->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { | |||
21771 | // binop (splat X), (splat C) --> splat (binop X, C) | |||
21772 | SDLoc DL(N); | |||
21773 | SDValue X = Shuf0->getOperand(0); | |||
21774 | SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, X, RHS, Flags); | |||
21775 | return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), | |||
21776 | Shuf0->getMask()); | |||
21777 | } | |||
21778 | if (isConstOrConstSplat(LHS) && Shuf1 && is_splat(Shuf1->getMask()) && | |||
21779 | Shuf1->hasOneUse() && Shuf1->getOperand(1).isUndef() && | |||
21780 | Shuf1->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { | |||
21781 | // binop (splat C), (splat X) --> splat (binop C, X) | |||
21782 | SDLoc DL(N); | |||
21783 | SDValue X = Shuf1->getOperand(0); | |||
21784 | SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS, X, Flags); | |||
21785 | return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), | |||
21786 | Shuf1->getMask()); | |||
21787 | } | |||
21788 | } | |||
21789 | ||||
21790 | // The following pattern is likely to emerge with vector reduction ops. Moving | |||
21791 | // the binary operation ahead of insertion may allow using a narrower vector | |||
21792 | // instruction that has better performance than the wide version of the op: | |||
21793 | // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z | |||
21794 | if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() && | |||
21795 | RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() && | |||
21796 | LHS.getOperand(2) == RHS.getOperand(2) && | |||
21797 | (LHS.hasOneUse() || RHS.hasOneUse())) { | |||
21798 | SDValue X = LHS.getOperand(1); | |||
21799 | SDValue Y = RHS.getOperand(1); | |||
21800 | SDValue Z = LHS.getOperand(2); | |||
21801 | EVT NarrowVT = X.getValueType(); | |||
21802 | if (NarrowVT == Y.getValueType() && | |||
21803 | TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT, | |||
21804 | LegalOperations)) { | |||
21805 | // (binop undef, undef) may not return undef, so compute that result. | |||
21806 | SDLoc DL(N); | |||
21807 | SDValue VecC = | |||
21808 | DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT)); | |||
21809 | SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y); | |||
21810 | return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z); | |||
21811 | } | |||
21812 | } | |||
21813 | ||||
21814 | // Make sure all but the first op are undef or constant. | |||
21815 | auto ConcatWithConstantOrUndef = [](SDValue Concat) { | |||
21816 | return Concat.getOpcode() == ISD::CONCAT_VECTORS && | |||
21817 | all_of(drop_begin(Concat->ops()), [](const SDValue &Op) { | |||
21818 | return Op.isUndef() || | |||
21819 | ISD::isBuildVectorOfConstantSDNodes(Op.getNode()); | |||
21820 | }); | |||
21821 | }; | |||
21822 | ||||
21823 | // The following pattern is likely to emerge with vector reduction ops. Moving | |||
21824 | // the binary operation ahead of the concat may allow using a narrower vector | |||
21825 | // instruction that has better performance than the wide version of the op: | |||
21826 | // VBinOp (concat X, undef/constant), (concat Y, undef/constant) --> | |||
21827 | // concat (VBinOp X, Y), VecC | |||
21828 | if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) && | |||
21829 | (LHS.hasOneUse() || RHS.hasOneUse())) { | |||
21830 | EVT NarrowVT = LHS.getOperand(0).getValueType(); | |||
21831 | if (NarrowVT == RHS.getOperand(0).getValueType() && | |||
21832 | TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) { | |||
21833 | SDLoc DL(N); | |||
21834 | unsigned NumOperands = LHS.getNumOperands(); | |||
21835 | SmallVector<SDValue, 4> ConcatOps; | |||
21836 | for (unsigned i = 0; i != NumOperands; ++i) { | |||
21837 | // This constant fold for operands 1 and up. | |||
21838 | ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i), | |||
21839 | RHS.getOperand(i))); | |||
21840 | } | |||
21841 | ||||
21842 | return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); | |||
21843 | } | |||
21844 | } | |||
21845 | ||||
21846 | if (SDValue V = scalarizeBinOpOfSplats(N, DAG)) | |||
21847 | return V; | |||
21848 | ||||
21849 | return SDValue(); | |||
21850 | } | |||
21851 | ||||
21852 | SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, | |||
21853 | SDValue N2) { | |||
21854 | assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!")((N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!" ) ? static_cast<void> (0) : __assert_fail ("N0.getOpcode() ==ISD::SETCC && \"First argument must be a SetCC node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 21854, __PRETTY_FUNCTION__)); | |||
21855 | ||||
21856 | SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, | |||
21857 | cast<CondCodeSDNode>(N0.getOperand(2))->get()); | |||
21858 | ||||
21859 | // If we got a simplified select_cc node back from SimplifySelectCC, then | |||
21860 | // break it down into a new SETCC node, and a new SELECT node, and then return | |||
21861 | // the SELECT node, since we were called with a SELECT node. | |||
21862 | if (SCC.getNode()) { | |||
21863 | // Check to see if we got a select_cc back (to turn into setcc/select). | |||
21864 | // Otherwise, just return whatever node we got back, like fabs. | |||
21865 | if (SCC.getOpcode() == ISD::SELECT_CC) { | |||
21866 | const SDNodeFlags Flags = N0.getNode()->getFlags(); | |||
21867 | SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), | |||
21868 | N0.getValueType(), | |||
21869 | SCC.getOperand(0), SCC.getOperand(1), | |||
21870 | SCC.getOperand(4), Flags); | |||
21871 | AddToWorklist(SETCC.getNode()); | |||
21872 | SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, | |||
21873 | SCC.getOperand(2), SCC.getOperand(3)); | |||
21874 | SelectNode->setFlags(Flags); | |||
21875 | return SelectNode; | |||
21876 | } | |||
21877 | ||||
21878 | return SCC; | |||
21879 | } | |||
21880 | return SDValue(); | |||
21881 | } | |||
21882 | ||||
21883 | /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values | |||
21884 | /// being selected between, see if we can simplify the select. Callers of this | |||
21885 | /// should assume that TheSelect is deleted if this returns true. As such, they | |||
21886 | /// should return the appropriate thing (e.g. the node) back to the top-level of | |||
21887 | /// the DAG combiner loop to avoid it being looked at. | |||
21888 | bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, | |||
21889 | SDValue RHS) { | |||
21890 | // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) | |||
21891 | // The select + setcc is redundant, because fsqrt returns NaN for X < 0. | |||
21892 | if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { | |||
21893 | if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { | |||
21894 | // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) | |||
21895 | SDValue Sqrt = RHS; | |||
21896 | ISD::CondCode CC; | |||
21897 | SDValue CmpLHS; | |||
21898 | const ConstantFPSDNode *Zero = nullptr; | |||
21899 | ||||
21900 | if (TheSelect->getOpcode() == ISD::SELECT_CC) { | |||
21901 | CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); | |||
21902 | CmpLHS = TheSelect->getOperand(0); | |||
21903 | Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); | |||
21904 | } else { | |||
21905 | // SELECT or VSELECT | |||
21906 | SDValue Cmp = TheSelect->getOperand(0); | |||
21907 | if (Cmp.getOpcode() == ISD::SETCC) { | |||
21908 | CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); | |||
21909 | CmpLHS = Cmp.getOperand(0); | |||
21910 | Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); | |||
21911 | } | |||
21912 | } | |||
21913 | if (Zero && Zero->isZero() && | |||
21914 | Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || | |||
21915 | CC == ISD::SETULT || CC == ISD::SETLT)) { | |||
21916 | // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) | |||
21917 | CombineTo(TheSelect, Sqrt); | |||
21918 | return true; | |||
21919 | } | |||
21920 | } | |||
21921 | } | |||
21922 | // Cannot simplify select with vector condition | |||
21923 | if (TheSelect->getOperand(0).getValueType().isVector()) return false; | |||
21924 | ||||
21925 | // If this is a select from two identical things, try to pull the operation | |||
21926 | // through the select. | |||
21927 | if (LHS.getOpcode() != RHS.getOpcode() || | |||
21928 | !LHS.hasOneUse() || !RHS.hasOneUse()) | |||
21929 | return false; | |||
21930 | ||||
21931 | // If this is a load and the token chain is identical, replace the select | |||
21932 | // of two loads with a load through a select of the address to load from. | |||
21933 | // This triggers in things like "select bool X, 10.0, 123.0" after the FP | |||
21934 | // constants have been dropped into the constant pool. | |||
21935 | if (LHS.getOpcode() == ISD::LOAD) { | |||
21936 | LoadSDNode *LLD = cast<LoadSDNode>(LHS); | |||
21937 | LoadSDNode *RLD = cast<LoadSDNode>(RHS); | |||
21938 | ||||
21939 | // Token chains must be identical. | |||
21940 | if (LHS.getOperand(0) != RHS.getOperand(0) || | |||
21941 | // Do not let this transformation reduce the number of volatile loads. | |||
21942 | // Be conservative for atomics for the moment | |||
21943 | // TODO: This does appear to be legal for unordered atomics (see D66309) | |||
21944 | !LLD->isSimple() || !RLD->isSimple() || | |||
21945 | // FIXME: If either is a pre/post inc/dec load, | |||
21946 | // we'd need to split out the address adjustment. | |||
21947 | LLD->isIndexed() || RLD->isIndexed() || | |||
21948 | // If this is an EXTLOAD, the VT's must match. | |||
21949 | LLD->getMemoryVT() != RLD->getMemoryVT() || | |||
21950 | // If this is an EXTLOAD, the kind of extension must match. | |||
21951 | (LLD->getExtensionType() != RLD->getExtensionType() && | |||
21952 | // The only exception is if one of the extensions is anyext. | |||
21953 | LLD->getExtensionType() != ISD::EXTLOAD && | |||
21954 | RLD->getExtensionType() != ISD::EXTLOAD) || | |||
21955 | // FIXME: this discards src value information. This is | |||
21956 | // over-conservative. It would be beneficial to be able to remember | |||
21957 | // both potential memory locations. Since we are discarding | |||
21958 | // src value info, don't do the transformation if the memory | |||
21959 | // locations are not in the default address space. | |||
21960 | LLD->getPointerInfo().getAddrSpace() != 0 || | |||
21961 | RLD->getPointerInfo().getAddrSpace() != 0 || | |||
21962 | // We can't produce a CMOV of a TargetFrameIndex since we won't | |||
21963 | // generate the address generation required. | |||
21964 | LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || | |||
21965 | RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || | |||
21966 | !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), | |||
21967 | LLD->getBasePtr().getValueType())) | |||
21968 | return false; | |||
21969 | ||||
21970 | // The loads must not depend on one another. | |||
21971 | if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD)) | |||
21972 | return false; | |||
21973 | ||||
21974 | // Check that the select condition doesn't reach either load. If so, | |||
21975 | // folding this will induce a cycle into the DAG. If not, this is safe to | |||
21976 | // xform, so create a select of the addresses. | |||
21977 | ||||
21978 | SmallPtrSet<const SDNode *, 32> Visited; | |||
21979 | SmallVector<const SDNode *, 16> Worklist; | |||
21980 | ||||
21981 | // Always fail if LLD and RLD are not independent. TheSelect is a | |||
21982 | // predecessor to all Nodes in question so we need not search past it. | |||
21983 | ||||
21984 | Visited.insert(TheSelect); | |||
21985 | Worklist.push_back(LLD); | |||
21986 | Worklist.push_back(RLD); | |||
21987 | ||||
21988 | if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) || | |||
21989 | SDNode::hasPredecessorHelper(RLD, Visited, Worklist)) | |||
21990 | return false; | |||
21991 | ||||
21992 | SDValue Addr; | |||
21993 | if (TheSelect->getOpcode() == ISD::SELECT) { | |||
21994 | // We cannot do this optimization if any pair of {RLD, LLD} is a | |||
21995 | // predecessor to {RLD, LLD, CondNode}. As we've already compared the | |||
21996 | // Loads, we only need to check if CondNode is a successor to one of the | |||
21997 | // loads. We can further avoid this if there's no use of their chain | |||
21998 | // value. | |||
21999 | SDNode *CondNode = TheSelect->getOperand(0).getNode(); | |||
22000 | Worklist.push_back(CondNode); | |||
22001 | ||||
22002 | if ((LLD->hasAnyUseOfValue(1) && | |||
22003 | SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || | |||
22004 | (RLD->hasAnyUseOfValue(1) && | |||
22005 | SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) | |||
22006 | return false; | |||
22007 | ||||
22008 | Addr = DAG.getSelect(SDLoc(TheSelect), | |||
22009 | LLD->getBasePtr().getValueType(), | |||
22010 | TheSelect->getOperand(0), LLD->getBasePtr(), | |||
22011 | RLD->getBasePtr()); | |||
22012 | } else { // Otherwise SELECT_CC | |||
22013 | // We cannot do this optimization if any pair of {RLD, LLD} is a | |||
22014 | // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared | |||
22015 | // the Loads, we only need to check if CondLHS/CondRHS is a successor to | |||
22016 | // one of the loads. We can further avoid this if there's no use of their | |||
22017 | // chain value. | |||
22018 | ||||
22019 | SDNode *CondLHS = TheSelect->getOperand(0).getNode(); | |||
22020 | SDNode *CondRHS = TheSelect->getOperand(1).getNode(); | |||
22021 | Worklist.push_back(CondLHS); | |||
22022 | Worklist.push_back(CondRHS); | |||
22023 | ||||
22024 | if ((LLD->hasAnyUseOfValue(1) && | |||
22025 | SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || | |||
22026 | (RLD->hasAnyUseOfValue(1) && | |||
22027 | SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) | |||
22028 | return false; | |||
22029 | ||||
22030 | Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), | |||
22031 | LLD->getBasePtr().getValueType(), | |||
22032 | TheSelect->getOperand(0), | |||
22033 | TheSelect->getOperand(1), | |||
22034 | LLD->getBasePtr(), RLD->getBasePtr(), | |||
22035 | TheSelect->getOperand(4)); | |||
22036 | } | |||
22037 | ||||
22038 | SDValue Load; | |||
22039 | // It is safe to replace the two loads if they have different alignments, | |||
22040 | // but the new load must be the minimum (most restrictive) alignment of the | |||
22041 | // inputs. | |||
22042 | Align Alignment = std::min(LLD->getAlign(), RLD->getAlign()); | |||
22043 | MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); | |||
22044 | if (!RLD->isInvariant()) | |||
22045 | MMOFlags &= ~MachineMemOperand::MOInvariant; | |||
22046 | if (!RLD->isDereferenceable()) | |||
22047 | MMOFlags &= ~MachineMemOperand::MODereferenceable; | |||
22048 | if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { | |||
22049 | // FIXME: Discards pointer and AA info. | |||
22050 | Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), | |||
22051 | LLD->getChain(), Addr, MachinePointerInfo(), Alignment, | |||
22052 | MMOFlags); | |||
22053 | } else { | |||
22054 | // FIXME: Discards pointer and AA info. | |||
22055 | Load = DAG.getExtLoad( | |||
22056 | LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() | |||
22057 | : LLD->getExtensionType(), | |||
22058 | SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, | |||
22059 | MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); | |||
22060 | } | |||
22061 | ||||
22062 | // Users of the select now use the result of the load. | |||
22063 | CombineTo(TheSelect, Load); | |||
22064 | ||||
22065 | // Users of the old loads now use the new load's chain. We know the | |||
22066 | // old-load value is dead now. | |||
22067 | CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); | |||
22068 | CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); | |||
22069 | return true; | |||
22070 | } | |||
22071 | ||||
22072 | return false; | |||
22073 | } | |||
22074 | ||||
22075 | /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and | |||
22076 | /// bitwise 'and'. | |||
22077 | SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, | |||
22078 | SDValue N1, SDValue N2, SDValue N3, | |||
22079 | ISD::CondCode CC) { | |||
22080 | // If this is a select where the false operand is zero and the compare is a | |||
22081 | // check of the sign bit, see if we can perform the "gzip trick": | |||
22082 | // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A | |||
22083 | // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A | |||
22084 | EVT XType = N0.getValueType(); | |||
22085 | EVT AType = N2.getValueType(); | |||
22086 | if (!isNullConstant(N3) || !XType.bitsGE(AType)) | |||
22087 | return SDValue(); | |||
22088 | ||||
22089 | // If the comparison is testing for a positive value, we have to invert | |||
22090 | // the sign bit mask, so only do that transform if the target has a bitwise | |||
22091 | // 'and not' instruction (the invert is free). | |||
22092 | if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { | |||
22093 | // (X > -1) ? A : 0 | |||
22094 | // (X > 0) ? X : 0 <-- This is canonical signed max. | |||
22095 | if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) | |||
22096 | return SDValue(); | |||
22097 | } else if (CC == ISD::SETLT) { | |||
22098 | // (X < 0) ? A : 0 | |||
22099 | // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. | |||
22100 | if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) | |||
22101 | return SDValue(); | |||
22102 | } else { | |||
22103 | return SDValue(); | |||
22104 | } | |||
22105 | ||||
22106 | // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit | |||
22107 | // constant. | |||
22108 | EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); | |||
22109 | auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); | |||
22110 | if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { | |||
22111 | unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; | |||
22112 | if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) { | |||
22113 | SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); | |||
22114 | SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); | |||
22115 | AddToWorklist(Shift.getNode()); | |||
22116 | ||||
22117 | if (XType.bitsGT(AType)) { | |||
22118 | Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); | |||
22119 | AddToWorklist(Shift.getNode()); | |||
22120 | } | |||
22121 | ||||
22122 | if (CC == ISD::SETGT) | |||
22123 | Shift = DAG.getNOT(DL, Shift, AType); | |||
22124 | ||||
22125 | return DAG.getNode(ISD::AND, DL, AType, Shift, N2); | |||
22126 | } | |||
22127 | } | |||
22128 | ||||
22129 | unsigned ShCt = XType.getSizeInBits() - 1; | |||
22130 | if (TLI.shouldAvoidTransformToShift(XType, ShCt)) | |||
22131 | return SDValue(); | |||
22132 | ||||
22133 | SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); | |||
22134 | SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); | |||
22135 | AddToWorklist(Shift.getNode()); | |||
22136 | ||||
22137 | if (XType.bitsGT(AType)) { | |||
22138 | Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); | |||
22139 | AddToWorklist(Shift.getNode()); | |||
22140 | } | |||
22141 | ||||
22142 | if (CC == ISD::SETGT) | |||
22143 | Shift = DAG.getNOT(DL, Shift, AType); | |||
22144 | ||||
22145 | return DAG.getNode(ISD::AND, DL, AType, Shift, N2); | |||
22146 | } | |||
22147 | ||||
22148 | // Transform (fneg/fabs (bitconvert x)) to avoid loading constant pool values. | |||
22149 | SDValue DAGCombiner::foldSignChangeInBitcast(SDNode *N) { | |||
22150 | SDValue N0 = N->getOperand(0); | |||
22151 | EVT VT = N->getValueType(0); | |||
22152 | bool IsFabs = N->getOpcode() == ISD::FABS; | |||
22153 | bool IsFree = IsFabs ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT); | |||
22154 | ||||
22155 | if (IsFree || N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse()) | |||
22156 | return SDValue(); | |||
22157 | ||||
22158 | SDValue Int = N0.getOperand(0); | |||
22159 | EVT IntVT = Int.getValueType(); | |||
22160 | ||||
22161 | // The operand to cast should be integer. | |||
22162 | if (!IntVT.isInteger() || IntVT.isVector()) | |||
22163 | return SDValue(); | |||
22164 | ||||
22165 | // (fneg (bitconvert x)) -> (bitconvert (xor x sign)) | |||
22166 | // (fabs (bitconvert x)) -> (bitconvert (and x ~sign)) | |||
22167 | APInt SignMask; | |||
22168 | if (N0.getValueType().isVector()) { | |||
22169 | // For vector, create a sign mask (0x80...) or its inverse (for fabs, | |||
22170 | // 0x7f...) per element and splat it. | |||
22171 | SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); | |||
22172 | if (IsFabs) | |||
22173 | SignMask = ~SignMask; | |||
22174 | SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); | |||
22175 | } else { | |||
22176 | // For scalar, just use the sign mask (0x80... or the inverse, 0x7f...) | |||
22177 | SignMask = APInt::getSignMask(IntVT.getSizeInBits()); | |||
22178 | if (IsFabs) | |||
22179 | SignMask = ~SignMask; | |||
22180 | } | |||
22181 | SDLoc DL(N0); | |||
22182 | Int = DAG.getNode(IsFabs ? ISD::AND : ISD::XOR, DL, IntVT, Int, | |||
22183 | DAG.getConstant(SignMask, DL, IntVT)); | |||
22184 | AddToWorklist(Int.getNode()); | |||
22185 | return DAG.getBitcast(VT, Int); | |||
22186 | } | |||
22187 | ||||
22188 | /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" | |||
22189 | /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 | |||
22190 | /// in it. This may be a win when the constant is not otherwise available | |||
22191 | /// because it replaces two constant pool loads with one. | |||
22192 | SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset( | |||
22193 | const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, | |||
22194 | ISD::CondCode CC) { | |||
22195 | if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType())) | |||
22196 | return SDValue(); | |||
22197 | ||||
22198 | // If we are before legalize types, we want the other legalization to happen | |||
22199 | // first (for example, to avoid messing with soft float). | |||
22200 | auto *TV = dyn_cast<ConstantFPSDNode>(N2); | |||
22201 | auto *FV = dyn_cast<ConstantFPSDNode>(N3); | |||
22202 | EVT VT = N2.getValueType(); | |||
22203 | if (!TV || !FV || !TLI.isTypeLegal(VT)) | |||
22204 | return SDValue(); | |||
22205 | ||||
22206 | // If a constant can be materialized without loads, this does not make sense. | |||
22207 | if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal || | |||
22208 | TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) || | |||
22209 | TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize)) | |||
22210 | return SDValue(); | |||
22211 | ||||
22212 | // If both constants have multiple uses, then we won't need to do an extra | |||
22213 | // load. The values are likely around in registers for other users. | |||
22214 | if (!TV->hasOneUse() && !FV->hasOneUse()) | |||
22215 | return SDValue(); | |||
22216 | ||||
22217 | Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()), | |||
22218 | const_cast<ConstantFP*>(TV->getConstantFPValue()) }; | |||
22219 | Type *FPTy = Elts[0]->getType(); | |||
22220 | const DataLayout &TD = DAG.getDataLayout(); | |||
22221 | ||||
22222 | // Create a ConstantArray of the two constants. | |||
22223 | Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); | |||
22224 | SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), | |||
22225 | TD.getPrefTypeAlign(FPTy)); | |||
22226 | Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); | |||
22227 | ||||
22228 | // Get offsets to the 0 and 1 elements of the array, so we can select between | |||
22229 | // them. | |||
22230 | SDValue Zero = DAG.getIntPtrConstant(0, DL); | |||
22231 | unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); | |||
22232 | SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); | |||
22233 | SDValue Cond = | |||
22234 | DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC); | |||
22235 | AddToWorklist(Cond.getNode()); | |||
22236 | SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero); | |||
22237 | AddToWorklist(CstOffset.getNode()); | |||
22238 | CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset); | |||
22239 | AddToWorklist(CPIdx.getNode()); | |||
22240 | return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, | |||
22241 | MachinePointerInfo::getConstantPool( | |||
22242 | DAG.getMachineFunction()), Alignment); | |||
22243 | } | |||
22244 | ||||
22245 | /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 | |||
22246 | /// where 'cond' is the comparison specified by CC. | |||
22247 | SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, | |||
22248 | SDValue N2, SDValue N3, ISD::CondCode CC, | |||
22249 | bool NotExtCompare) { | |||
22250 | // (x ? y : y) -> y. | |||
22251 | if (N2 == N3) return N2; | |||
22252 | ||||
22253 | EVT CmpOpVT = N0.getValueType(); | |||
22254 | EVT CmpResVT = getSetCCResultType(CmpOpVT); | |||
22255 | EVT VT = N2.getValueType(); | |||
22256 | auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); | |||
22257 | auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); | |||
22258 | auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); | |||
22259 | ||||
22260 | // Determine if the condition we're dealing with is constant. | |||
22261 | if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) { | |||
22262 | AddToWorklist(SCC.getNode()); | |||
22263 | if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) { | |||
22264 | // fold select_cc true, x, y -> x | |||
22265 | // fold select_cc false, x, y -> y | |||
22266 | return !(SCCC->isNullValue()) ? N2 : N3; | |||
22267 | } | |||
22268 | } | |||
22269 | ||||
22270 | if (SDValue V = | |||
22271 | convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC)) | |||
22272 | return V; | |||
22273 | ||||
22274 | if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) | |||
22275 | return V; | |||
22276 | ||||
22277 | // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) | |||
22278 | // where y is has a single bit set. | |||
22279 | // A plaintext description would be, we can turn the SELECT_CC into an AND | |||
22280 | // when the condition can be materialized as an all-ones register. Any | |||
22281 | // single bit-test can be materialized as an all-ones register with | |||
22282 | // shift-left and shift-right-arith. | |||
22283 | if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && | |||
22284 | N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { | |||
22285 | SDValue AndLHS = N0->getOperand(0); | |||
22286 | auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); | |||
22287 | if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { | |||
22288 | // Shift the tested bit over the sign bit. | |||
22289 | const APInt &AndMask = ConstAndRHS->getAPIntValue(); | |||
22290 | unsigned ShCt = AndMask.getBitWidth() - 1; | |||
22291 | if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { | |||
22292 | SDValue ShlAmt = | |||
22293 | DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), | |||
22294 | getShiftAmountTy(AndLHS.getValueType())); | |||
22295 | SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); | |||
22296 | ||||
22297 | // Now arithmetic right shift it all the way over, so the result is | |||
22298 | // either all-ones, or zero. | |||
22299 | SDValue ShrAmt = | |||
22300 | DAG.getConstant(ShCt, SDLoc(Shl), | |||
22301 | getShiftAmountTy(Shl.getValueType())); | |||
22302 | SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); | |||
22303 | ||||
22304 | return DAG.getNode(ISD::AND, DL, VT, Shr, N3); | |||
22305 | } | |||
22306 | } | |||
22307 | } | |||
22308 | ||||
22309 | // fold select C, 16, 0 -> shl C, 4 | |||
22310 | bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2(); | |||
22311 | bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2(); | |||
22312 | ||||
22313 | if ((Fold || Swap) && | |||
22314 | TLI.getBooleanContents(CmpOpVT) == | |||
22315 | TargetLowering::ZeroOrOneBooleanContent && | |||
22316 | (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) { | |||
22317 | ||||
22318 | if (Swap) { | |||
22319 | CC = ISD::getSetCCInverse(CC, CmpOpVT); | |||
22320 | std::swap(N2C, N3C); | |||
22321 | } | |||
22322 | ||||
22323 | // If the caller doesn't want us to simplify this into a zext of a compare, | |||
22324 | // don't do it. | |||
22325 | if (NotExtCompare && N2C->isOne()) | |||
22326 | return SDValue(); | |||
22327 | ||||
22328 | SDValue Temp, SCC; | |||
22329 | // zext (setcc n0, n1) | |||
22330 | if (LegalTypes) { | |||
22331 | SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC); | |||
22332 | if (VT.bitsLT(SCC.getValueType())) | |||
22333 | Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT); | |||
22334 | else | |||
22335 | Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); | |||
22336 | } else { | |||
22337 | SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); | |||
22338 | Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); | |||
22339 | } | |||
22340 | ||||
22341 | AddToWorklist(SCC.getNode()); | |||
22342 | AddToWorklist(Temp.getNode()); | |||
22343 | ||||
22344 | if (N2C->isOne()) | |||
22345 | return Temp; | |||
22346 | ||||
22347 | unsigned ShCt = N2C->getAPIntValue().logBase2(); | |||
22348 | if (TLI.shouldAvoidTransformToShift(VT, ShCt)) | |||
22349 | return SDValue(); | |||
22350 | ||||
22351 | // shl setcc result by log2 n2c | |||
22352 | return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, | |||
22353 | DAG.getConstant(ShCt, SDLoc(Temp), | |||
22354 | getShiftAmountTy(Temp.getValueType()))); | |||
22355 | } | |||
22356 | ||||
22357 | // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) | |||
22358 | // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) | |||
22359 | // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) | |||
22360 | // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) | |||
22361 | // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) | |||
22362 | // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) | |||
22363 | // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) | |||
22364 | // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) | |||
22365 | if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { | |||
22366 | SDValue ValueOnZero = N2; | |||
22367 | SDValue Count = N3; | |||
22368 | // If the condition is NE instead of E, swap the operands. | |||
22369 | if (CC == ISD::SETNE) | |||
22370 | std::swap(ValueOnZero, Count); | |||
22371 | // Check if the value on zero is a constant equal to the bits in the type. | |||
22372 | if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { | |||
22373 | if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { | |||
22374 | // If the other operand is cttz/cttz_zero_undef of N0, and cttz is | |||
22375 | // legal, combine to just cttz. | |||
22376 | if ((Count.getOpcode() == ISD::CTTZ || | |||
22377 | Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && | |||
22378 | N0 == Count.getOperand(0) && | |||
22379 | (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) | |||
22380 | return DAG.getNode(ISD::CTTZ, DL, VT, N0); | |||
22381 | // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is | |||
22382 | // legal, combine to just ctlz. | |||
22383 | if ((Count.getOpcode() == ISD::CTLZ || | |||
22384 | Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && | |||
22385 | N0 == Count.getOperand(0) && | |||
22386 | (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) | |||
22387 | return DAG.getNode(ISD::CTLZ, DL, VT, N0); | |||
22388 | } | |||
22389 | } | |||
22390 | } | |||
22391 | ||||
22392 | return SDValue(); | |||
22393 | } | |||
22394 | ||||
22395 | /// This is a stub for TargetLowering::SimplifySetCC. | |||
22396 | SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, | |||
22397 | ISD::CondCode Cond, const SDLoc &DL, | |||
22398 | bool foldBooleans) { | |||
22399 | TargetLowering::DAGCombinerInfo | |||
22400 | DagCombineInfo(DAG, Level, false, this); | |||
22401 | return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); | |||
22402 | } | |||
22403 | ||||
22404 | /// Given an ISD::SDIV node expressing a divide by constant, return | |||
22405 | /// a DAG expression to select that will generate the same value by multiplying | |||
22406 | /// by a magic number. | |||
22407 | /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". | |||
22408 | SDValue DAGCombiner::BuildSDIV(SDNode *N) { | |||
22409 | // when optimising for minimum size, we don't want to expand a div to a mul | |||
22410 | // and a shift. | |||
22411 | if (DAG.getMachineFunction().getFunction().hasMinSize()) | |||
22412 | return SDValue(); | |||
22413 | ||||
22414 | SmallVector<SDNode *, 8> Built; | |||
22415 | if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { | |||
22416 | for (SDNode *N : Built) | |||
22417 | AddToWorklist(N); | |||
22418 | return S; | |||
22419 | } | |||
22420 | ||||
22421 | return SDValue(); | |||
22422 | } | |||
22423 | ||||
22424 | /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a | |||
22425 | /// DAG expression that will generate the same value by right shifting. | |||
22426 | SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { | |||
22427 | ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); | |||
22428 | if (!C) | |||
22429 | return SDValue(); | |||
22430 | ||||
22431 | // Avoid division by zero. | |||
22432 | if (C->isNullValue()) | |||
22433 | return SDValue(); | |||
22434 | ||||
22435 | SmallVector<SDNode *, 8> Built; | |||
22436 | if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { | |||
22437 | for (SDNode *N : Built) | |||
22438 | AddToWorklist(N); | |||
22439 | return S; | |||
22440 | } | |||
22441 | ||||
22442 | return SDValue(); | |||
22443 | } | |||
22444 | ||||
22445 | /// Given an ISD::UDIV node expressing a divide by constant, return a DAG | |||
22446 | /// expression that will generate the same value by multiplying by a magic | |||
22447 | /// number. | |||
22448 | /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". | |||
22449 | SDValue DAGCombiner::BuildUDIV(SDNode *N) { | |||
22450 | // when optimising for minimum size, we don't want to expand a div to a mul | |||
22451 | // and a shift. | |||
22452 | if (DAG.getMachineFunction().getFunction().hasMinSize()) | |||
22453 | return SDValue(); | |||
22454 | ||||
22455 | SmallVector<SDNode *, 8> Built; | |||
22456 | if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { | |||
22457 | for (SDNode *N : Built) | |||
22458 | AddToWorklist(N); | |||
22459 | return S; | |||
22460 | } | |||
22461 | ||||
22462 | return SDValue(); | |||
22463 | } | |||
22464 | ||||
22465 | /// Determines the LogBase2 value for a non-null input value using the | |||
22466 | /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). | |||
22467 | SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { | |||
22468 | EVT VT = V.getValueType(); | |||
22469 | SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); | |||
22470 | SDValue Base = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); | |||
22471 | SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); | |||
22472 | return LogBase2; | |||
22473 | } | |||
22474 | ||||
22475 | /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) | |||
22476 | /// For the reciprocal, we need to find the zero of the function: | |||
22477 | /// F(X) = A X - 1 [which has a zero at X = 1/A] | |||
22478 | /// => | |||
22479 | /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form | |||
22480 | /// does not require additional intermediate precision] | |||
22481 | /// For the last iteration, put numerator N into it to gain more precision: | |||
22482 | /// Result = N X_i + X_i (N - N A X_i) | |||
22483 | SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op, | |||
22484 | SDNodeFlags Flags) { | |||
22485 | if (LegalDAG) | |||
22486 | return SDValue(); | |||
22487 | ||||
22488 | // TODO: Handle half and/or extended types? | |||
22489 | EVT VT = Op.getValueType(); | |||
22490 | if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) | |||
22491 | return SDValue(); | |||
22492 | ||||
22493 | // If estimates are explicitly disabled for this function, we're done. | |||
22494 | MachineFunction &MF = DAG.getMachineFunction(); | |||
22495 | int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); | |||
22496 | if (Enabled == TLI.ReciprocalEstimate::Disabled) | |||
22497 | return SDValue(); | |||
22498 | ||||
22499 | // Estimates may be explicitly enabled for this type with a custom number of | |||
22500 | // refinement steps. | |||
22501 | int Iterations = TLI.getDivRefinementSteps(VT, MF); | |||
22502 | if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { | |||
22503 | AddToWorklist(Est.getNode()); | |||
22504 | ||||
22505 | SDLoc DL(Op); | |||
22506 | if (Iterations) { | |||
22507 | SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); | |||
22508 | ||||
22509 | // Newton iterations: Est = Est + Est (N - Arg * Est) | |||
22510 | // If this is the last iteration, also multiply by the numerator. | |||
22511 | for (int i = 0; i < Iterations; ++i) { | |||
22512 | SDValue MulEst = Est; | |||
22513 | ||||
22514 | if (i == Iterations - 1) { | |||
22515 | MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags); | |||
22516 | AddToWorklist(MulEst.getNode()); | |||
22517 | } | |||
22518 | ||||
22519 | SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags); | |||
22520 | AddToWorklist(NewEst.getNode()); | |||
22521 | ||||
22522 | NewEst = DAG.getNode(ISD::FSUB, DL, VT, | |||
22523 | (i == Iterations - 1 ? N : FPOne), NewEst, Flags); | |||
22524 | AddToWorklist(NewEst.getNode()); | |||
22525 | ||||
22526 | NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); | |||
22527 | AddToWorklist(NewEst.getNode()); | |||
22528 | ||||
22529 | Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags); | |||
22530 | AddToWorklist(Est.getNode()); | |||
22531 | } | |||
22532 | } else { | |||
22533 | // If no iterations are available, multiply with N. | |||
22534 | Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags); | |||
22535 | AddToWorklist(Est.getNode()); | |||
22536 | } | |||
22537 | ||||
22538 | return Est; | |||
22539 | } | |||
22540 | ||||
22541 | return SDValue(); | |||
22542 | } | |||
22543 | ||||
22544 | /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) | |||
22545 | /// For the reciprocal sqrt, we need to find the zero of the function: | |||
22546 | /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] | |||
22547 | /// => | |||
22548 | /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) | |||
22549 | /// As a result, we precompute A/2 prior to the iteration loop. | |||
22550 | SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, | |||
22551 | unsigned Iterations, | |||
22552 | SDNodeFlags Flags, bool Reciprocal) { | |||
22553 | EVT VT = Arg.getValueType(); | |||
22554 | SDLoc DL(Arg); | |||
22555 | SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); | |||
22556 | ||||
22557 | // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that | |||
22558 | // this entire sequence requires only one FP constant. | |||
22559 | SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); | |||
22560 | HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); | |||
22561 | ||||
22562 | // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) | |||
22563 | for (unsigned i = 0; i < Iterations; ++i) { | |||
22564 | SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); | |||
22565 | NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); | |||
22566 | NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); | |||
22567 | Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); | |||
22568 | } | |||
22569 | ||||
22570 | // If non-reciprocal square root is requested, multiply the result by Arg. | |||
22571 | if (!Reciprocal) | |||
22572 | Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); | |||
22573 | ||||
22574 | return Est; | |||
22575 | } | |||
22576 | ||||
22577 | /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) | |||
22578 | /// For the reciprocal sqrt, we need to find the zero of the function: | |||
22579 | /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] | |||
22580 | /// => | |||
22581 | /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) | |||
22582 | SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, | |||
22583 | unsigned Iterations, | |||
22584 | SDNodeFlags Flags, bool Reciprocal) { | |||
22585 | EVT VT = Arg.getValueType(); | |||
22586 | SDLoc DL(Arg); | |||
22587 | SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); | |||
22588 | SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); | |||
22589 | ||||
22590 | // This routine must enter the loop below to work correctly | |||
22591 | // when (Reciprocal == false). | |||
22592 | assert(Iterations > 0)((Iterations > 0) ? static_cast<void> (0) : __assert_fail ("Iterations > 0", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp" , 22592, __PRETTY_FUNCTION__)); | |||
22593 | ||||
22594 | // Newton iterations for reciprocal square root: | |||
22595 | // E = (E * -0.5) * ((A * E) * E + -3.0) | |||
22596 | for (unsigned i = 0; i < Iterations; ++i) { | |||
22597 | SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); | |||
22598 | SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); | |||
22599 | SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); | |||
22600 | ||||
22601 | // When calculating a square root at the last iteration build: | |||
22602 | // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) | |||
22603 | // (notice a common subexpression) | |||
22604 | SDValue LHS; | |||
22605 | if (Reciprocal || (i + 1) < Iterations) { | |||
22606 | // RSQRT: LHS = (E * -0.5) | |||
22607 | LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); | |||
22608 | } else { | |||
22609 | // SQRT: LHS = (A * E) * -0.5 | |||
22610 | LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); | |||
22611 | } | |||
22612 | ||||
22613 | Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); | |||
22614 | } | |||
22615 | ||||
22616 | return Est; | |||
22617 | } | |||
22618 | ||||
22619 | /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case | |||
22620 | /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if | |||
22621 | /// Op can be zero. | |||
22622 | SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, | |||
22623 | bool Reciprocal) { | |||
22624 | if (LegalDAG) | |||
22625 | return SDValue(); | |||
22626 | ||||
22627 | // TODO: Handle half and/or extended types? | |||
22628 | EVT VT = Op.getValueType(); | |||
22629 | if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) | |||
22630 | return SDValue(); | |||
22631 | ||||
22632 | // If estimates are explicitly disabled for this function, we're done. | |||
22633 | MachineFunction &MF = DAG.getMachineFunction(); | |||
22634 | int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); | |||
22635 | if (Enabled == TLI.ReciprocalEstimate::Disabled) | |||
22636 | return SDValue(); | |||
22637 | ||||
22638 | // Estimates may be explicitly enabled for this type with a custom number of | |||
22639 | // refinement steps. | |||
22640 | int Iterations = TLI.getSqrtRefinementSteps(VT, MF); | |||
22641 | ||||
22642 | bool UseOneConstNR = false; | |||
22643 | if (SDValue Est = | |||
22644 | TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, | |||
22645 | Reciprocal)) { | |||
22646 | AddToWorklist(Est.getNode()); | |||
22647 | ||||
22648 | if (Iterations) | |||
22649 | Est = UseOneConstNR | |||
22650 | ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) | |||
22651 | : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); | |||
22652 | if (!Reciprocal) { | |||
22653 | SDLoc DL(Op); | |||
22654 | // Try the target specific test first. | |||
22655 | SDValue Test = TLI.getSqrtInputTest(Op, DAG, DAG.getDenormalMode(VT)); | |||
22656 | ||||
22657 | // The estimate is now completely wrong if the input was exactly 0.0 or | |||
22658 | // possibly a denormal. Force the answer to 0.0 or value provided by | |||
22659 | // target for those cases. | |||
22660 | Est = DAG.getNode( | |||
22661 | Test.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, | |||
22662 | Test, TLI.getSqrtResultForDenormInput(Op, DAG), Est); | |||
22663 | } | |||
22664 | return Est; | |||
22665 | } | |||
22666 | ||||
22667 | return SDValue(); | |||
22668 | } | |||
22669 | ||||
22670 | SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { | |||
22671 | return buildSqrtEstimateImpl(Op, Flags, true); | |||
22672 | } | |||
22673 | ||||
22674 | SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { | |||
22675 | return buildSqrtEstimateImpl(Op, Flags, false); | |||
22676 | } | |||
22677 | ||||
22678 | /// Return true if there is any possibility that the two addresses overlap. | |||
22679 | bool DAGCombiner::isAlias(SDNode *Op0, SDNode *Op1) const { | |||
22680 | ||||
22681 | struct MemUseCharacteristics { | |||
22682 | bool IsVolatile; | |||
22683 | bool IsAtomic; | |||
22684 | SDValue BasePtr; | |||
22685 | int64_t Offset; | |||
22686 | Optional<int64_t> NumBytes; | |||
22687 | MachineMemOperand *MMO; | |||
22688 | }; | |||
22689 | ||||
22690 | auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics { | |||
22691 | if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) { | |||
22692 | int64_t Offset = 0; | |||
22693 | if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset())) | |||
22694 | Offset = (LSN->getAddressingMode() == ISD::PRE_INC) | |||
22695 | ? C->getSExtValue() | |||
22696 | : (LSN->getAddressingMode() == ISD::PRE_DEC) | |||
22697 | ? -1 * C->getSExtValue() | |||
22698 | : 0; | |||
22699 | uint64_t Size = | |||
22700 | MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize()); | |||
22701 | return {LSN->isVolatile(), LSN->isAtomic(), LSN->getBasePtr(), | |||
22702 | Offset /*base offset*/, | |||
22703 | Optional<int64_t>(Size), | |||
22704 | LSN->getMemOperand()}; | |||
22705 | } | |||
22706 | if (const auto *LN = cast<LifetimeSDNode>(N)) | |||
22707 | return {false /*isVolatile*/, /*isAtomic*/ false, LN->getOperand(1), | |||
22708 | (LN->hasOffset()) ? LN->getOffset() : 0, | |||
22709 | (LN->hasOffset()) ? Optional<int64_t>(LN->getSize()) | |||
22710 | : Optional<int64_t>(), | |||
22711 | (MachineMemOperand *)nullptr}; | |||
22712 | // Default. | |||
22713 | return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(), | |||
22714 | (int64_t)0 /*offset*/, | |||
22715 | Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr}; | |||
22716 | }; | |||
22717 | ||||
22718 | MemUseCharacteristics MUC0 = getCharacteristics(Op0), | |||
22719 | MUC1 = getCharacteristics(Op1); | |||
22720 | ||||
22721 | // If they are to the same address, then they must be aliases. | |||
22722 | if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr && | |||
22723 | MUC0.Offset == MUC1.Offset) | |||
22724 | return true; | |||
22725 | ||||
22726 | // If they are both volatile then they cannot be reordered. | |||
22727 | if (MUC0.IsVolatile && MUC1.IsVolatile) | |||
22728 | return true; | |||
22729 | ||||
22730 | // Be conservative about atomics for the moment | |||
22731 | // TODO: This is way overconservative for unordered atomics (see D66309) | |||
22732 | if (MUC0.IsAtomic && MUC1.IsAtomic) | |||
22733 | return true; | |||
22734 | ||||
22735 | if (MUC0.MMO && MUC1.MMO) { | |||
22736 | if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || | |||
22737 | (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) | |||
22738 | return false; | |||
22739 | } | |||
22740 | ||||
22741 | // Try to prove that there is aliasing, or that there is no aliasing. Either | |||
22742 | // way, we can return now. If nothing can be proved, proceed with more tests. | |||
22743 | bool IsAlias; | |||
22744 | if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes, | |||
22745 | DAG, IsAlias)) | |||
22746 | return IsAlias; | |||
22747 | ||||
22748 | // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if | |||
22749 | // either are not known. | |||
22750 | if (!MUC0.MMO || !MUC1.MMO) | |||
22751 | return true; | |||
22752 | ||||
22753 | // If one operation reads from invariant memory, and the other may store, they | |||
22754 | // cannot alias. These should really be checking the equivalent of mayWrite, | |||
22755 | // but it only matters for memory nodes other than load /store. | |||
22756 | if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || | |||
22757 | (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) | |||
22758 | return false; | |||
22759 | ||||
22760 | // If we know required SrcValue1 and SrcValue2 have relatively large | |||
22761 | // alignment compared to the size and offset of the access, we may be able | |||
22762 | // to prove they do not alias. This check is conservative for now to catch | |||
22763 | // cases created by splitting vector types, it only works when the offsets are | |||
22764 | // multiples of the size of the data. | |||
22765 | int64_t SrcValOffset0 = MUC0.MMO->getOffset(); | |||
22766 | int64_t SrcValOffset1 = MUC1.MMO->getOffset(); | |||
22767 | Align OrigAlignment0 = MUC0.MMO->getBaseAlign(); | |||
22768 | Align OrigAlignment1 = MUC1.MMO->getBaseAlign(); | |||
22769 | auto &Size0 = MUC0.NumBytes; | |||
22770 | auto &Size1 = MUC1.NumBytes; | |||
22771 | if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && | |||
22772 | Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 && | |||
22773 | OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 && | |||
22774 | SrcValOffset1 % *Size1 == 0) { | |||
22775 | int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value(); | |||
22776 | int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value(); | |||
22777 | ||||
22778 | // There is no overlap between these relatively aligned accesses of | |||
22779 | // similar size. Return no alias. | |||
22780 | if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0) | |||
22781 | return false; | |||
22782 | } | |||
22783 | ||||
22784 | bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 | |||
22785 | ? CombinerGlobalAA | |||
22786 | : DAG.getSubtarget().useAA(); | |||
22787 | #ifndef NDEBUG | |||
22788 | if (CombinerAAOnlyFunc.getNumOccurrences() && | |||
22789 | CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) | |||
22790 | UseAA = false; | |||
22791 | #endif | |||
22792 | ||||
22793 | if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && | |||
22794 | Size0.hasValue() && Size1.hasValue()) { | |||
22795 | // Use alias analysis information. | |||
22796 | int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); | |||
22797 | int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset; | |||
22798 | int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset; | |||
22799 | if (AA->isNoAlias( | |||
22800 | MemoryLocation(MUC0.MMO->getValue(), Overlap0, | |||
22801 | UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()), | |||
22802 | MemoryLocation(MUC1.MMO->getValue(), Overlap1, | |||
22803 | UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes()))) | |||
22804 | return false; | |||
22805 | } | |||
22806 | ||||
22807 | // Otherwise we have to assume they alias. | |||
22808 | return true; | |||
22809 | } | |||
22810 | ||||
22811 | /// Walk up chain skipping non-aliasing memory nodes, | |||
22812 | /// looking for aliasing nodes and adding them to the Aliases vector. | |||
22813 | void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, | |||
22814 | SmallVectorImpl<SDValue> &Aliases) { | |||
22815 | SmallVector<SDValue, 8> Chains; // List of chains to visit. | |||
22816 | SmallPtrSet<SDNode *, 16> Visited; // Visited node set. | |||
22817 | ||||
22818 | // Get alias information for node. | |||
22819 | // TODO: relax aliasing for unordered atomics (see D66309) | |||
22820 | const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple(); | |||
22821 | ||||
22822 | // Starting off. | |||
22823 | Chains.push_back(OriginalChain); | |||
22824 | unsigned Depth = 0; | |||
22825 | ||||
22826 | // Attempt to improve chain by a single step | |||
22827 | std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool { | |||
22828 | switch (C.getOpcode()) { | |||
22829 | case ISD::EntryToken: | |||
22830 | // No need to mark EntryToken. | |||
22831 | C = SDValue(); | |||
22832 | return true; | |||
22833 | case ISD::LOAD: | |||
22834 | case ISD::STORE: { | |||
22835 | // Get alias information for C. | |||
22836 | // TODO: Relax aliasing for unordered atomics (see D66309) | |||
22837 | bool IsOpLoad = isa<LoadSDNode>(C.getNode()) && | |||
22838 | cast<LSBaseSDNode>(C.getNode())->isSimple(); | |||
22839 | if ((IsLoad && IsOpLoad) || !isAlias(N, C.getNode())) { | |||
22840 | // Look further up the chain. | |||
22841 | C = C.getOperand(0); | |||
22842 | return true; | |||
22843 | } | |||
22844 | // Alias, so stop here. | |||
22845 | return false; | |||
22846 | } | |||
22847 | ||||
22848 | case ISD::CopyFromReg: | |||
22849 | // Always forward past past CopyFromReg. | |||
22850 | C = C.getOperand(0); | |||
22851 | return true; | |||
22852 | ||||
22853 | case ISD::LIFETIME_START: | |||
22854 | case ISD::LIFETIME_END: { | |||
22855 | // We can forward past any lifetime start/end that can be proven not to | |||
22856 | // alias the memory access. | |||
22857 | if (!isAlias(N, C.getNode())) { | |||
22858 | // Look further up the chain. | |||
22859 | C = C.getOperand(0); | |||
22860 | return true; | |||
22861 | } | |||
22862 | return false; | |||
22863 | } | |||
22864 | default: | |||
22865 | return false; | |||
22866 | } | |||
22867 | }; | |||
22868 | ||||
22869 | // Look at each chain and determine if it is an alias. If so, add it to the | |||
22870 | // aliases list. If not, then continue up the chain looking for the next | |||
22871 | // candidate. | |||
22872 | while (!Chains.empty()) { | |||
22873 | SDValue Chain = Chains.pop_back_val(); | |||
22874 | ||||
22875 | // Don't bother if we've seen Chain before. | |||
22876 | if (!Visited.insert(Chain.getNode()).second) | |||
22877 | continue; | |||
22878 | ||||
22879 | // For TokenFactor nodes, look at each operand and only continue up the | |||
22880 | // chain until we reach the depth limit. | |||
22881 | // | |||
22882 | // FIXME: The depth check could be made to return the last non-aliasing | |||
22883 | // chain we found before we hit a tokenfactor rather than the original | |||
22884 | // chain. | |||
22885 | if (Depth > TLI.getGatherAllAliasesMaxDepth()) { | |||
22886 | Aliases.clear(); | |||
22887 | Aliases.push_back(OriginalChain); | |||
22888 | return; | |||
22889 | } | |||
22890 | ||||
22891 | if (Chain.getOpcode() == ISD::TokenFactor) { | |||
22892 | // We have to check each of the operands of the token factor for "small" | |||
22893 | // token factors, so we queue them up. Adding the operands to the queue | |||
22894 | // (stack) in reverse order maintains the original order and increases the | |||
22895 | // likelihood that getNode will find a matching token factor (CSE.) | |||
22896 | if (Chain.getNumOperands() > 16) { | |||
22897 | Aliases.push_back(Chain); | |||
22898 | continue; | |||
22899 | } | |||
22900 | for (unsigned n = Chain.getNumOperands(); n;) | |||
22901 | Chains.push_back(Chain.getOperand(--n)); | |||
22902 | ++Depth; | |||
22903 | continue; | |||
22904 | } | |||
22905 | // Everything else | |||
22906 | if (ImproveChain(Chain)) { | |||
22907 | // Updated Chain Found, Consider new chain if one exists. | |||
22908 | if (Chain.getNode()) | |||
22909 | Chains.push_back(Chain); | |||
22910 | ++Depth; | |||
22911 | continue; | |||
22912 | } | |||
22913 | // No Improved Chain Possible, treat as Alias. | |||
22914 | Aliases.push_back(Chain); | |||
22915 | } | |||
22916 | } | |||
22917 | ||||
22918 | /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain | |||
22919 | /// (aliasing node.) | |||
22920 | SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { | |||
22921 | if (OptLevel == CodeGenOpt::None) | |||
22922 | return OldChain; | |||
22923 | ||||
22924 | // Ops for replacing token factor. | |||
22925 | SmallVector<SDValue, 8> Aliases; | |||
22926 | ||||
22927 | // Accumulate all the aliases to this node. | |||
22928 | GatherAllAliases(N, OldChain, Aliases); | |||
22929 | ||||
22930 | // If no operands then chain to entry token. | |||
22931 | if (Aliases.size() == 0) | |||
22932 | return DAG.getEntryNode(); | |||
22933 | ||||
22934 | // If a single operand then chain to it. We don't need to revisit it. | |||
22935 | if (Aliases.size() == 1) | |||
22936 | return Aliases[0]; | |||
22937 | ||||
22938 | // Construct a custom tailored token factor. | |||
22939 | return DAG.getTokenFactor(SDLoc(N), Aliases); | |||
22940 | } | |||
22941 | ||||
22942 | namespace { | |||
22943 | // TODO: Replace with with std::monostate when we move to C++17. | |||
22944 | struct UnitT { } Unit; | |||
22945 | bool operator==(const UnitT &, const UnitT &) { return true; } | |||
22946 | bool operator!=(const UnitT &, const UnitT &) { return false; } | |||
22947 | } // namespace | |||
22948 | ||||
22949 | // This function tries to collect a bunch of potentially interesting | |||
22950 | // nodes to improve the chains of, all at once. This might seem | |||
22951 | // redundant, as this function gets called when visiting every store | |||
22952 | // node, so why not let the work be done on each store as it's visited? | |||
22953 | // | |||
22954 | // I believe this is mainly important because mergeConsecutiveStores | |||
22955 | // is unable to deal with merging stores of different sizes, so unless | |||
22956 | // we improve the chains of all the potential candidates up-front | |||
22957 | // before running mergeConsecutiveStores, it might only see some of | |||
22958 | // the nodes that will eventually be candidates, and then not be able | |||
22959 | // to go from a partially-merged state to the desired final | |||
22960 | // fully-merged state. | |||
22961 | ||||
22962 | bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) { | |||
22963 | SmallVector<StoreSDNode *, 8> ChainedStores; | |||
22964 | StoreSDNode *STChain = St; | |||
22965 | // Intervals records which offsets from BaseIndex have been covered. In | |||
22966 | // the common case, every store writes to the immediately previous address | |||
22967 | // space and thus merged with the previous interval at insertion time. | |||
22968 | ||||
22969 | using IMap = | |||
22970 | llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>; | |||
22971 | IMap::Allocator A; | |||
22972 | IMap Intervals(A); | |||
22973 | ||||
22974 | // This holds the base pointer, index, and the offset in bytes from the base | |||
22975 | // pointer. | |||
22976 | const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); | |||
22977 | ||||
22978 | // We must have a base and an offset. | |||
22979 | if (!BasePtr.getBase().getNode()) | |||
22980 | return false; | |||
22981 | ||||
22982 | // Do not handle stores to undef base pointers. | |||
22983 | if (BasePtr.getBase().isUndef()) | |||
22984 | return false; | |||
22985 | ||||
22986 | // BaseIndexOffset assumes that offsets are fixed-size, which | |||
22987 | // is not valid for scalable vectors where the offsets are | |||
22988 | // scaled by `vscale`, so bail out early. | |||
22989 | if (St->getMemoryVT().isScalableVector()) | |||
22990 | return false; | |||
22991 | ||||
22992 | // Add ST's interval. | |||
22993 | Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit); | |||
22994 | ||||
22995 | while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) { | |||
22996 | // If the chain has more than one use, then we can't reorder the mem ops. | |||
22997 | if (!SDValue(Chain, 0)->hasOneUse()) | |||
22998 | break; | |||
22999 | // TODO: Relax for unordered atomics (see D66309) | |||
23000 | if (!Chain->isSimple() || Chain->isIndexed()) | |||
23001 | break; | |||
23002 | ||||
23003 | // Find the base pointer and offset for this memory node. | |||
23004 | const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG); | |||
23005 | // Check that the base pointer is the same as the original one. | |||
23006 | int64_t Offset; | |||
23007 | if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset)) | |||
23008 | break; | |||
23009 | int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8; | |||
23010 | // Make sure we don't overlap with other intervals by checking the ones to | |||
23011 | // the left or right before inserting. | |||
23012 | auto I = Intervals.find(Offset); | |||
23013 | // If there's a next interval, we should end before it. | |||
23014 | if (I != Intervals.end() && I.start() < (Offset + Length)) | |||
23015 | break; | |||
23016 | // If there's a previous interval, we should start after it. | |||
23017 | if (I != Intervals.begin() && (--I).stop() <= Offset) | |||
23018 | break; | |||
23019 | Intervals.insert(Offset, Offset + Length, Unit); | |||
23020 | ||||
23021 | ChainedStores.push_back(Chain); | |||
23022 | STChain = Chain; | |||
23023 | } | |||
23024 | ||||
23025 | // If we didn't find a chained store, exit. | |||
23026 | if (ChainedStores.size() == 0) | |||
23027 | return false; | |||
23028 | ||||
23029 | // Improve all chained stores (St and ChainedStores members) starting from | |||
23030 | // where the store chain ended and return single TokenFactor. | |||
23031 | SDValue NewChain = STChain->getChain(); | |||
23032 | SmallVector<SDValue, 8> TFOps; | |||
23033 | for (unsigned I = ChainedStores.size(); I;) { | |||
23034 | StoreSDNode *S = ChainedStores[--I]; | |||
23035 | SDValue BetterChain = FindBetterChain(S, NewChain); | |||
23036 | S = cast<StoreSDNode>(DAG.UpdateNodeOperands( | |||
23037 | S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3))); | |||
23038 | TFOps.push_back(SDValue(S, 0)); | |||
23039 | ChainedStores[I] = S; | |||
23040 | } | |||
23041 | ||||
23042 | // Improve St's chain. Use a new node to avoid creating a loop from CombineTo. | |||
23043 | SDValue BetterChain = FindBetterChain(St, NewChain); | |||
23044 | SDValue NewST; | |||
23045 | if (St->isTruncatingStore()) | |||
23046 | NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(), | |||
23047 | St->getBasePtr(), St->getMemoryVT(), | |||
23048 | St->getMemOperand()); | |||
23049 | else | |||
23050 | NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(), | |||
23051 | St->getBasePtr(), St->getMemOperand()); | |||
23052 | ||||
23053 | TFOps.push_back(NewST); | |||
23054 | ||||
23055 | // If we improved every element of TFOps, then we've lost the dependence on | |||
23056 | // NewChain to successors of St and we need to add it back to TFOps. Do so at | |||
23057 | // the beginning to keep relative order consistent with FindBetterChains. | |||
23058 | auto hasImprovedChain = [&](SDValue ST) -> bool { | |||
23059 | return ST->getOperand(0) != NewChain; | |||
23060 | }; | |||
23061 | bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain); | |||
23062 | if (AddNewChain) | |||
23063 | TFOps.insert(TFOps.begin(), NewChain); | |||
23064 | ||||
23065 | SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps); | |||
23066 | CombineTo(St, TF); | |||
23067 | ||||
23068 | // Add TF and its operands to the worklist. | |||
23069 | AddToWorklist(TF.getNode()); | |||
23070 | for (const SDValue &Op : TF->ops()) | |||
23071 | AddToWorklist(Op.getNode()); | |||
23072 | AddToWorklist(STChain); | |||
23073 | return true; | |||
23074 | } | |||
23075 | ||||
23076 | bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { | |||
23077 | if (OptLevel == CodeGenOpt::None) | |||
23078 | return false; | |||
23079 | ||||
23080 | const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); | |||
23081 | ||||
23082 | // We must have a base and an offset. | |||
23083 | if (!BasePtr.getBase().getNode()) | |||
23084 | return false; | |||
23085 | ||||
23086 | // Do not handle stores to undef base pointers. | |||
23087 | if (BasePtr.getBase().isUndef()) | |||
23088 | return false; | |||
23089 | ||||
23090 | // Directly improve a chain of disjoint stores starting at St. | |||
23091 | if (parallelizeChainedStores(St)) | |||
23092 | return true; | |||
23093 | ||||
23094 | // Improve St's Chain.. | |||
23095 | SDValue BetterChain = FindBetterChain(St, St->getChain()); | |||
23096 | if (St->getChain() != BetterChain) { | |||
23097 | replaceStoreChain(St, BetterChain); | |||
23098 | return true; | |||
23099 | } | |||
23100 | return false; | |||
23101 | } | |||
23102 | ||||
23103 | /// This is the entry point for the file. | |||
23104 | void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, | |||
23105 | CodeGenOpt::Level OptLevel) { | |||
23106 | /// This is the main entry point to this class. | |||
23107 | DAGCombiner(*this, AA, OptLevel).Run(Level); | |||
23108 | } |
1 | //===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- C++ -*-===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file declares the SDNode class and derived classes, which are used to | |||
10 | // represent the nodes and operations present in a SelectionDAG. These nodes | |||
11 | // and operations are machine code level operations, with some similarities to | |||
12 | // the GCC RTL representation. | |||
13 | // | |||
14 | // Clients should include the SelectionDAG.h file instead of this file directly. | |||
15 | // | |||
16 | //===----------------------------------------------------------------------===// | |||
17 | ||||
18 | #ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H | |||
19 | #define LLVM_CODEGEN_SELECTIONDAGNODES_H | |||
20 | ||||
21 | #include "llvm/ADT/APFloat.h" | |||
22 | #include "llvm/ADT/ArrayRef.h" | |||
23 | #include "llvm/ADT/BitVector.h" | |||
24 | #include "llvm/ADT/FoldingSet.h" | |||
25 | #include "llvm/ADT/GraphTraits.h" | |||
26 | #include "llvm/ADT/SmallPtrSet.h" | |||
27 | #include "llvm/ADT/SmallVector.h" | |||
28 | #include "llvm/ADT/ilist_node.h" | |||
29 | #include "llvm/ADT/iterator.h" | |||
30 | #include "llvm/ADT/iterator_range.h" | |||
31 | #include "llvm/CodeGen/ISDOpcodes.h" | |||
32 | #include "llvm/CodeGen/MachineMemOperand.h" | |||
33 | #include "llvm/CodeGen/Register.h" | |||
34 | #include "llvm/CodeGen/ValueTypes.h" | |||
35 | #include "llvm/IR/Constants.h" | |||
36 | #include "llvm/IR/DebugLoc.h" | |||
37 | #include "llvm/IR/Instruction.h" | |||
38 | #include "llvm/IR/Instructions.h" | |||
39 | #include "llvm/IR/Metadata.h" | |||
40 | #include "llvm/IR/Operator.h" | |||
41 | #include "llvm/Support/AlignOf.h" | |||
42 | #include "llvm/Support/AtomicOrdering.h" | |||
43 | #include "llvm/Support/Casting.h" | |||
44 | #include "llvm/Support/ErrorHandling.h" | |||
45 | #include "llvm/Support/MachineValueType.h" | |||
46 | #include "llvm/Support/TypeSize.h" | |||
47 | #include <algorithm> | |||
48 | #include <cassert> | |||
49 | #include <climits> | |||
50 | #include <cstddef> | |||
51 | #include <cstdint> | |||
52 | #include <cstring> | |||
53 | #include <iterator> | |||
54 | #include <string> | |||
55 | #include <tuple> | |||
56 | ||||
57 | namespace llvm { | |||
58 | ||||
59 | class APInt; | |||
60 | class Constant; | |||
61 | template <typename T> struct DenseMapInfo; | |||
62 | class GlobalValue; | |||
63 | class MachineBasicBlock; | |||
64 | class MachineConstantPoolValue; | |||
65 | class MCSymbol; | |||
66 | class raw_ostream; | |||
67 | class SDNode; | |||
68 | class SelectionDAG; | |||
69 | class Type; | |||
70 | class Value; | |||
71 | ||||
72 | void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr, | |||
73 | bool force = false); | |||
74 | ||||
75 | /// This represents a list of ValueType's that has been intern'd by | |||
76 | /// a SelectionDAG. Instances of this simple value class are returned by | |||
77 | /// SelectionDAG::getVTList(...). | |||
78 | /// | |||
79 | struct SDVTList { | |||
80 | const EVT *VTs; | |||
81 | unsigned int NumVTs; | |||
82 | }; | |||
83 | ||||
84 | namespace ISD { | |||
85 | ||||
86 | /// Node predicates | |||
87 | ||||
88 | /// If N is a BUILD_VECTOR or SPLAT_VECTOR node whose elements are all the | |||
89 | /// same constant or undefined, return true and return the constant value in | |||
90 | /// \p SplatValue. | |||
91 | bool isConstantSplatVector(const SDNode *N, APInt &SplatValue); | |||
92 | ||||
93 | /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where | |||
94 | /// all of the elements are ~0 or undef. If \p BuildVectorOnly is set to | |||
95 | /// true, it only checks BUILD_VECTOR. | |||
96 | bool isConstantSplatVectorAllOnes(const SDNode *N, | |||
97 | bool BuildVectorOnly = false); | |||
98 | ||||
99 | /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where | |||
100 | /// all of the elements are 0 or undef. If \p BuildVectorOnly is set to true, it | |||
101 | /// only checks BUILD_VECTOR. | |||
102 | bool isConstantSplatVectorAllZeros(const SDNode *N, | |||
103 | bool BuildVectorOnly = false); | |||
104 | ||||
105 | /// Return true if the specified node is a BUILD_VECTOR where all of the | |||
106 | /// elements are ~0 or undef. | |||
107 | bool isBuildVectorAllOnes(const SDNode *N); | |||
108 | ||||
109 | /// Return true if the specified node is a BUILD_VECTOR where all of the | |||
110 | /// elements are 0 or undef. | |||
111 | bool isBuildVectorAllZeros(const SDNode *N); | |||
112 | ||||
113 | /// Return true if the specified node is a BUILD_VECTOR node of all | |||
114 | /// ConstantSDNode or undef. | |||
115 | bool isBuildVectorOfConstantSDNodes(const SDNode *N); | |||
116 | ||||
117 | /// Return true if the specified node is a BUILD_VECTOR node of all | |||
118 | /// ConstantFPSDNode or undef. | |||
119 | bool isBuildVectorOfConstantFPSDNodes(const SDNode *N); | |||
120 | ||||
121 | /// Return true if the node has at least one operand and all operands of the | |||
122 | /// specified node are ISD::UNDEF. | |||
123 | bool allOperandsUndef(const SDNode *N); | |||
124 | ||||
125 | } // end namespace ISD | |||
126 | ||||
127 | //===----------------------------------------------------------------------===// | |||
128 | /// Unlike LLVM values, Selection DAG nodes may return multiple | |||
129 | /// values as the result of a computation. Many nodes return multiple values, | |||
130 | /// from loads (which define a token and a return value) to ADDC (which returns | |||
131 | /// a result and a carry value), to calls (which may return an arbitrary number | |||
132 | /// of values). | |||
133 | /// | |||
134 | /// As such, each use of a SelectionDAG computation must indicate the node that | |||
135 | /// computes it as well as which return value to use from that node. This pair | |||
136 | /// of information is represented with the SDValue value type. | |||
137 | /// | |||
138 | class SDValue { | |||
139 | friend struct DenseMapInfo<SDValue>; | |||
140 | ||||
141 | SDNode *Node = nullptr; // The node defining the value we are using. | |||
142 | unsigned ResNo = 0; // Which return value of the node we are using. | |||
143 | ||||
144 | public: | |||
145 | SDValue() = default; | |||
146 | SDValue(SDNode *node, unsigned resno); | |||
147 | ||||
148 | /// get the index which selects a specific result in the SDNode | |||
149 | unsigned getResNo() const { return ResNo; } | |||
150 | ||||
151 | /// get the SDNode which holds the desired result | |||
152 | SDNode *getNode() const { return Node; } | |||
153 | ||||
154 | /// set the SDNode | |||
155 | void setNode(SDNode *N) { Node = N; } | |||
156 | ||||
157 | inline SDNode *operator->() const { return Node; } | |||
158 | ||||
159 | bool operator==(const SDValue &O) const { | |||
160 | return Node == O.Node && ResNo == O.ResNo; | |||
161 | } | |||
162 | bool operator!=(const SDValue &O) const { | |||
163 | return !operator==(O); | |||
164 | } | |||
165 | bool operator<(const SDValue &O) const { | |||
166 | return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo); | |||
167 | } | |||
168 | explicit operator bool() const { | |||
169 | return Node != nullptr; | |||
170 | } | |||
171 | ||||
172 | SDValue getValue(unsigned R) const { | |||
173 | return SDValue(Node, R); | |||
174 | } | |||
175 | ||||
176 | /// Return true if this node is an operand of N. | |||
177 | bool isOperandOf(const SDNode *N) const; | |||
178 | ||||
179 | /// Return the ValueType of the referenced return value. | |||
180 | inline EVT getValueType() const; | |||
181 | ||||
182 | /// Return the simple ValueType of the referenced return value. | |||
183 | MVT getSimpleValueType() const { | |||
184 | return getValueType().getSimpleVT(); | |||
185 | } | |||
186 | ||||
187 | /// Returns the size of the value in bits. | |||
188 | /// | |||
189 | /// If the value type is a scalable vector type, the scalable property will | |||
190 | /// be set and the runtime size will be a positive integer multiple of the | |||
191 | /// base size. | |||
192 | TypeSize getValueSizeInBits() const { | |||
193 | return getValueType().getSizeInBits(); | |||
194 | } | |||
195 | ||||
196 | uint64_t getScalarValueSizeInBits() const { | |||
197 | return getValueType().getScalarType().getFixedSizeInBits(); | |||
198 | } | |||
199 | ||||
200 | // Forwarding methods - These forward to the corresponding methods in SDNode. | |||
201 | inline unsigned getOpcode() const; | |||
202 | inline unsigned getNumOperands() const; | |||
203 | inline const SDValue &getOperand(unsigned i) const; | |||
204 | inline uint64_t getConstantOperandVal(unsigned i) const; | |||
205 | inline const APInt &getConstantOperandAPInt(unsigned i) const; | |||
206 | inline bool isTargetMemoryOpcode() const; | |||
207 | inline bool isTargetOpcode() const; | |||
208 | inline bool isMachineOpcode() const; | |||
209 | inline bool isUndef() const; | |||
210 | inline unsigned getMachineOpcode() const; | |||
211 | inline const DebugLoc &getDebugLoc() const; | |||
212 | inline void dump() const; | |||
213 | inline void dump(const SelectionDAG *G) const; | |||
214 | inline void dumpr() const; | |||
215 | inline void dumpr(const SelectionDAG *G) const; | |||
216 | ||||
217 | /// Return true if this operand (which must be a chain) reaches the | |||
218 | /// specified operand without crossing any side-effecting instructions. | |||
219 | /// In practice, this looks through token factors and non-volatile loads. | |||
220 | /// In order to remain efficient, this only | |||
221 | /// looks a couple of nodes in, it does not do an exhaustive search. | |||
222 | bool reachesChainWithoutSideEffects(SDValue Dest, | |||
223 | unsigned Depth = 2) const; | |||
224 | ||||
225 | /// Return true if there are no nodes using value ResNo of Node. | |||
226 | inline bool use_empty() const; | |||
227 | ||||
228 | /// Return true if there is exactly one node using value ResNo of Node. | |||
229 | inline bool hasOneUse() const; | |||
230 | }; | |||
231 | ||||
232 | template<> struct DenseMapInfo<SDValue> { | |||
233 | static inline SDValue getEmptyKey() { | |||
234 | SDValue V; | |||
235 | V.ResNo = -1U; | |||
236 | return V; | |||
237 | } | |||
238 | ||||
239 | static inline SDValue getTombstoneKey() { | |||
240 | SDValue V; | |||
241 | V.ResNo = -2U; | |||
242 | return V; | |||
243 | } | |||
244 | ||||
245 | static unsigned getHashValue(const SDValue &Val) { | |||
246 | return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^ | |||
247 | (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo(); | |||
248 | } | |||
249 | ||||
250 | static bool isEqual(const SDValue &LHS, const SDValue &RHS) { | |||
251 | return LHS == RHS; | |||
252 | } | |||
253 | }; | |||
254 | ||||
255 | /// Allow casting operators to work directly on | |||
256 | /// SDValues as if they were SDNode*'s. | |||
257 | template<> struct simplify_type<SDValue> { | |||
258 | using SimpleType = SDNode *; | |||
259 | ||||
260 | static SimpleType getSimplifiedValue(SDValue &Val) { | |||
261 | return Val.getNode(); | |||
262 | } | |||
263 | }; | |||
264 | template<> struct simplify_type<const SDValue> { | |||
265 | using SimpleType = /*const*/ SDNode *; | |||
266 | ||||
267 | static SimpleType getSimplifiedValue(const SDValue &Val) { | |||
268 | return Val.getNode(); | |||
269 | } | |||
270 | }; | |||
271 | ||||
272 | /// Represents a use of a SDNode. This class holds an SDValue, | |||
273 | /// which records the SDNode being used and the result number, a | |||
274 | /// pointer to the SDNode using the value, and Next and Prev pointers, | |||
275 | /// which link together all the uses of an SDNode. | |||
276 | /// | |||
277 | class SDUse { | |||
278 | /// Val - The value being used. | |||
279 | SDValue Val; | |||
280 | /// User - The user of this value. | |||
281 | SDNode *User = nullptr; | |||
282 | /// Prev, Next - Pointers to the uses list of the SDNode referred by | |||
283 | /// this operand. | |||
284 | SDUse **Prev = nullptr; | |||
285 | SDUse *Next = nullptr; | |||
286 | ||||
287 | public: | |||
288 | SDUse() = default; | |||
289 | SDUse(const SDUse &U) = delete; | |||
290 | SDUse &operator=(const SDUse &) = delete; | |||
291 | ||||
292 | /// Normally SDUse will just implicitly convert to an SDValue that it holds. | |||
293 | operator const SDValue&() const { return Val; } | |||
294 | ||||
295 | /// If implicit conversion to SDValue doesn't work, the get() method returns | |||
296 | /// the SDValue. | |||
297 | const SDValue &get() const { return Val; } | |||
298 | ||||
299 | /// This returns the SDNode that contains this Use. | |||
300 | SDNode *getUser() { return User; } | |||
301 | ||||
302 | /// Get the next SDUse in the use list. | |||
303 | SDUse *getNext() const { return Next; } | |||
304 | ||||
305 | /// Convenience function for get().getNode(). | |||
306 | SDNode *getNode() const { return Val.getNode(); } | |||
307 | /// Convenience function for get().getResNo(). | |||
308 | unsigned getResNo() const { return Val.getResNo(); } | |||
309 | /// Convenience function for get().getValueType(). | |||
310 | EVT getValueType() const { return Val.getValueType(); } | |||
311 | ||||
312 | /// Convenience function for get().operator== | |||
313 | bool operator==(const SDValue &V) const { | |||
314 | return Val == V; | |||
315 | } | |||
316 | ||||
317 | /// Convenience function for get().operator!= | |||
318 | bool operator!=(const SDValue &V) const { | |||
319 | return Val != V; | |||
320 | } | |||
321 | ||||
322 | /// Convenience function for get().operator< | |||
323 | bool operator<(const SDValue &V) const { | |||
324 | return Val < V; | |||
325 | } | |||
326 | ||||
327 | private: | |||
328 | friend class SelectionDAG; | |||
329 | friend class SDNode; | |||
330 | // TODO: unfriend HandleSDNode once we fix its operand handling. | |||
331 | friend class HandleSDNode; | |||
332 | ||||
333 | void setUser(SDNode *p) { User = p; } | |||
334 | ||||
335 | /// Remove this use from its existing use list, assign it the | |||
336 | /// given value, and add it to the new value's node's use list. | |||
337 | inline void set(const SDValue &V); | |||
338 | /// Like set, but only supports initializing a newly-allocated | |||
339 | /// SDUse with a non-null value. | |||
340 | inline void setInitial(const SDValue &V); | |||
341 | /// Like set, but only sets the Node portion of the value, | |||
342 | /// leaving the ResNo portion unmodified. | |||
343 | inline void setNode(SDNode *N); | |||
344 | ||||
345 | void addToList(SDUse **List) { | |||
346 | Next = *List; | |||
347 | if (Next) Next->Prev = &Next; | |||
348 | Prev = List; | |||
349 | *List = this; | |||
350 | } | |||
351 | ||||
352 | void removeFromList() { | |||
353 | *Prev = Next; | |||
354 | if (Next) Next->Prev = Prev; | |||
355 | } | |||
356 | }; | |||
357 | ||||
358 | /// simplify_type specializations - Allow casting operators to work directly on | |||
359 | /// SDValues as if they were SDNode*'s. | |||
360 | template<> struct simplify_type<SDUse> { | |||
361 | using SimpleType = SDNode *; | |||
362 | ||||
363 | static SimpleType getSimplifiedValue(SDUse &Val) { | |||
364 | return Val.getNode(); | |||
365 | } | |||
366 | }; | |||
367 | ||||
368 | /// These are IR-level optimization flags that may be propagated to SDNodes. | |||
369 | /// TODO: This data structure should be shared by the IR optimizer and the | |||
370 | /// the backend. | |||
371 | struct SDNodeFlags { | |||
372 | private: | |||
373 | bool NoUnsignedWrap : 1; | |||
374 | bool NoSignedWrap : 1; | |||
375 | bool Exact : 1; | |||
376 | bool NoNaNs : 1; | |||
377 | bool NoInfs : 1; | |||
378 | bool NoSignedZeros : 1; | |||
379 | bool AllowReciprocal : 1; | |||
380 | bool AllowContract : 1; | |||
381 | bool ApproximateFuncs : 1; | |||
382 | bool AllowReassociation : 1; | |||
383 | ||||
384 | // We assume instructions do not raise floating-point exceptions by default, | |||
385 | // and only those marked explicitly may do so. We could choose to represent | |||
386 | // this via a positive "FPExcept" flags like on the MI level, but having a | |||
387 | // negative "NoFPExcept" flag here (that defaults to true) makes the flag | |||
388 | // intersection logic more straightforward. | |||
389 | bool NoFPExcept : 1; | |||
390 | ||||
391 | public: | |||
392 | /// Default constructor turns off all optimization flags. | |||
393 | SDNodeFlags() | |||
394 | : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false), | |||
395 | NoInfs(false), NoSignedZeros(false), AllowReciprocal(false), | |||
396 | AllowContract(false), ApproximateFuncs(false), | |||
397 | AllowReassociation(false), NoFPExcept(false) {} | |||
398 | ||||
399 | /// Propagate the fast-math-flags from an IR FPMathOperator. | |||
400 | void copyFMF(const FPMathOperator &FPMO) { | |||
401 | setNoNaNs(FPMO.hasNoNaNs()); | |||
402 | setNoInfs(FPMO.hasNoInfs()); | |||
403 | setNoSignedZeros(FPMO.hasNoSignedZeros()); | |||
404 | setAllowReciprocal(FPMO.hasAllowReciprocal()); | |||
405 | setAllowContract(FPMO.hasAllowContract()); | |||
406 | setApproximateFuncs(FPMO.hasApproxFunc()); | |||
407 | setAllowReassociation(FPMO.hasAllowReassoc()); | |||
408 | } | |||
409 | ||||
410 | // These are mutators for each flag. | |||
411 | void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; } | |||
412 | void setNoSignedWrap(bool b) { NoSignedWrap = b; } | |||
413 | void setExact(bool b) { Exact = b; } | |||
414 | void setNoNaNs(bool b) { NoNaNs = b; } | |||
415 | void setNoInfs(bool b) { NoInfs = b; } | |||
416 | void setNoSignedZeros(bool b) { NoSignedZeros = b; } | |||
417 | void setAllowReciprocal(bool b) { AllowReciprocal = b; } | |||
418 | void setAllowContract(bool b) { AllowContract = b; } | |||
419 | void setApproximateFuncs(bool b) { ApproximateFuncs = b; } | |||
420 | void setAllowReassociation(bool b) { AllowReassociation = b; } | |||
421 | void setNoFPExcept(bool b) { NoFPExcept = b; } | |||
422 | ||||
423 | // These are accessors for each flag. | |||
424 | bool hasNoUnsignedWrap() const { return NoUnsignedWrap; } | |||
425 | bool hasNoSignedWrap() const { return NoSignedWrap; } | |||
426 | bool hasExact() const { return Exact; } | |||
427 | bool hasNoNaNs() const { return NoNaNs; } | |||
428 | bool hasNoInfs() const { return NoInfs; } | |||
429 | bool hasNoSignedZeros() const { return NoSignedZeros; } | |||
430 | bool hasAllowReciprocal() const { return AllowReciprocal; } | |||
431 | bool hasAllowContract() const { return AllowContract; } | |||
432 | bool hasApproximateFuncs() const { return ApproximateFuncs; } | |||
433 | bool hasAllowReassociation() const { return AllowReassociation; } | |||
434 | bool hasNoFPExcept() const { return NoFPExcept; } | |||
435 | ||||
436 | /// Clear any flags in this flag set that aren't also set in Flags. All | |||
437 | /// flags will be cleared if Flags are undefined. | |||
438 | void intersectWith(const SDNodeFlags Flags) { | |||
439 | NoUnsignedWrap &= Flags.NoUnsignedWrap; | |||
440 | NoSignedWrap &= Flags.NoSignedWrap; | |||
441 | Exact &= Flags.Exact; | |||
442 | NoNaNs &= Flags.NoNaNs; | |||
443 | NoInfs &= Flags.NoInfs; | |||
444 | NoSignedZeros &= Flags.NoSignedZeros; | |||
445 | AllowReciprocal &= Flags.AllowReciprocal; | |||
446 | AllowContract &= Flags.AllowContract; | |||
447 | ApproximateFuncs &= Flags.ApproximateFuncs; | |||
448 | AllowReassociation &= Flags.AllowReassociation; | |||
449 | NoFPExcept &= Flags.NoFPExcept; | |||
450 | } | |||
451 | }; | |||
452 | ||||
453 | /// Represents one node in the SelectionDAG. | |||
454 | /// | |||
455 | class SDNode : public FoldingSetNode, public ilist_node<SDNode> { | |||
456 | private: | |||
457 | /// The operation that this node performs. | |||
458 | int16_t NodeType; | |||
459 | ||||
460 | protected: | |||
461 | // We define a set of mini-helper classes to help us interpret the bits in our | |||
462 | // SubclassData. These are designed to fit within a uint16_t so they pack | |||
463 | // with NodeType. | |||
464 | ||||
465 | #if defined(_AIX) && (!defined(__GNUC__4) || defined(__ibmxl__)) | |||
466 | // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words | |||
467 | // and give the `pack` pragma push semantics. | |||
468 | #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2) | |||
469 | #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop) | |||
470 | #else | |||
471 | #define BEGIN_TWO_BYTE_PACK() | |||
472 | #define END_TWO_BYTE_PACK() | |||
473 | #endif | |||
474 | ||||
475 | BEGIN_TWO_BYTE_PACK() | |||
476 | class SDNodeBitfields { | |||
477 | friend class SDNode; | |||
478 | friend class MemIntrinsicSDNode; | |||
479 | friend class MemSDNode; | |||
480 | friend class SelectionDAG; | |||
481 | ||||
482 | uint16_t HasDebugValue : 1; | |||
483 | uint16_t IsMemIntrinsic : 1; | |||
484 | uint16_t IsDivergent : 1; | |||
485 | }; | |||
486 | enum { NumSDNodeBits = 3 }; | |||
487 | ||||
488 | class ConstantSDNodeBitfields { | |||
489 | friend class ConstantSDNode; | |||
490 | ||||
491 | uint16_t : NumSDNodeBits; | |||
492 | ||||
493 | uint16_t IsOpaque : 1; | |||
494 | }; | |||
495 | ||||
496 | class MemSDNodeBitfields { | |||
497 | friend class MemSDNode; | |||
498 | friend class MemIntrinsicSDNode; | |||
499 | friend class AtomicSDNode; | |||
500 | ||||
501 | uint16_t : NumSDNodeBits; | |||
502 | ||||
503 | uint16_t IsVolatile : 1; | |||
504 | uint16_t IsNonTemporal : 1; | |||
505 | uint16_t IsDereferenceable : 1; | |||
506 | uint16_t IsInvariant : 1; | |||
507 | }; | |||
508 | enum { NumMemSDNodeBits = NumSDNodeBits + 4 }; | |||
509 | ||||
510 | class LSBaseSDNodeBitfields { | |||
511 | friend class LSBaseSDNode; | |||
512 | friend class MaskedLoadStoreSDNode; | |||
513 | friend class MaskedGatherScatterSDNode; | |||
514 | ||||
515 | uint16_t : NumMemSDNodeBits; | |||
516 | ||||
517 | // This storage is shared between disparate class hierarchies to hold an | |||
518 | // enumeration specific to the class hierarchy in use. | |||
519 | // LSBaseSDNode => enum ISD::MemIndexedMode | |||
520 | // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode | |||
521 | // MaskedGatherScatterSDNode => enum ISD::MemIndexType | |||
522 | uint16_t AddressingMode : 3; | |||
523 | }; | |||
524 | enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 }; | |||
525 | ||||
526 | class LoadSDNodeBitfields { | |||
527 | friend class LoadSDNode; | |||
528 | friend class MaskedLoadSDNode; | |||
529 | friend class MaskedGatherSDNode; | |||
530 | ||||
531 | uint16_t : NumLSBaseSDNodeBits; | |||
532 | ||||
533 | uint16_t ExtTy : 2; // enum ISD::LoadExtType | |||
534 | uint16_t IsExpanding : 1; | |||
535 | }; | |||
536 | ||||
537 | class StoreSDNodeBitfields { | |||
538 | friend class StoreSDNode; | |||
539 | friend class MaskedStoreSDNode; | |||
540 | friend class MaskedScatterSDNode; | |||
541 | ||||
542 | uint16_t : NumLSBaseSDNodeBits; | |||
543 | ||||
544 | uint16_t IsTruncating : 1; | |||
545 | uint16_t IsCompressing : 1; | |||
546 | }; | |||
547 | ||||
548 | union { | |||
549 | char RawSDNodeBits[sizeof(uint16_t)]; | |||
550 | SDNodeBitfields SDNodeBits; | |||
551 | ConstantSDNodeBitfields ConstantSDNodeBits; | |||
552 | MemSDNodeBitfields MemSDNodeBits; | |||
553 | LSBaseSDNodeBitfields LSBaseSDNodeBits; | |||
554 | LoadSDNodeBitfields LoadSDNodeBits; | |||
555 | StoreSDNodeBitfields StoreSDNodeBits; | |||
556 | }; | |||
557 | END_TWO_BYTE_PACK() | |||
558 | #undef BEGIN_TWO_BYTE_PACK | |||
559 | #undef END_TWO_BYTE_PACK | |||
560 | ||||
561 | // RawSDNodeBits must cover the entirety of the union. This means that all of | |||
562 | // the union's members must have size <= RawSDNodeBits. We write the RHS as | |||
563 | // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter. | |||
564 | static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide"); | |||
565 | static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide"); | |||
566 | static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide"); | |||
567 | static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide"); | |||
568 | static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide"); | |||
569 | static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide"); | |||
570 | ||||
571 | private: | |||
572 | friend class SelectionDAG; | |||
573 | // TODO: unfriend HandleSDNode once we fix its operand handling. | |||
574 | friend class HandleSDNode; | |||
575 | ||||
576 | /// Unique id per SDNode in the DAG. | |||
577 | int NodeId = -1; | |||
578 | ||||
579 | /// The values that are used by this operation. | |||
580 | SDUse *OperandList = nullptr; | |||
581 | ||||
582 | /// The types of the values this node defines. SDNode's may | |||
583 | /// define multiple values simultaneously. | |||
584 | const EVT *ValueList; | |||
585 | ||||
586 | /// List of uses for this SDNode. | |||
587 | SDUse *UseList = nullptr; | |||
588 | ||||
589 | /// The number of entries in the Operand/Value list. | |||
590 | unsigned short NumOperands = 0; | |||
591 | unsigned short NumValues; | |||
592 | ||||
593 | // The ordering of the SDNodes. It roughly corresponds to the ordering of the | |||
594 | // original LLVM instructions. | |||
595 | // This is used for turning off scheduling, because we'll forgo | |||
596 | // the normal scheduling algorithms and output the instructions according to | |||
597 | // this ordering. | |||
598 | unsigned IROrder; | |||
599 | ||||
600 | /// Source line information. | |||
601 | DebugLoc debugLoc; | |||
602 | ||||
603 | /// Return a pointer to the specified value type. | |||
604 | static const EVT *getValueTypeList(EVT VT); | |||
605 | ||||
606 | SDNodeFlags Flags; | |||
607 | ||||
608 | public: | |||
609 | /// Unique and persistent id per SDNode in the DAG. | |||
610 | /// Used for debug printing. | |||
611 | uint16_t PersistentId; | |||
612 | ||||
613 | //===--------------------------------------------------------------------===// | |||
614 | // Accessors | |||
615 | // | |||
616 | ||||
617 | /// Return the SelectionDAG opcode value for this node. For | |||
618 | /// pre-isel nodes (those for which isMachineOpcode returns false), these | |||
619 | /// are the opcode values in the ISD and <target>ISD namespaces. For | |||
620 | /// post-isel opcodes, see getMachineOpcode. | |||
621 | unsigned getOpcode() const { return (unsigned short)NodeType; } | |||
622 | ||||
623 | /// Test if this node has a target-specific opcode (in the | |||
624 | /// \<target\>ISD namespace). | |||
625 | bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; } | |||
626 | ||||
627 | /// Test if this node has a target-specific opcode that may raise | |||
628 | /// FP exceptions (in the \<target\>ISD namespace and greater than | |||
629 | /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory | |||
630 | /// opcode are currently automatically considered to possibly raise | |||
631 | /// FP exceptions as well. | |||
632 | bool isTargetStrictFPOpcode() const { | |||
633 | return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE; | |||
634 | } | |||
635 | ||||
636 | /// Test if this node has a target-specific | |||
637 | /// memory-referencing opcode (in the \<target\>ISD namespace and | |||
638 | /// greater than FIRST_TARGET_MEMORY_OPCODE). | |||
639 | bool isTargetMemoryOpcode() const { | |||
640 | return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE; | |||
641 | } | |||
642 | ||||
643 | /// Return true if the type of the node type undefined. | |||
644 | bool isUndef() const { return NodeType == ISD::UNDEF; } | |||
645 | ||||
646 | /// Test if this node is a memory intrinsic (with valid pointer information). | |||
647 | /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for | |||
648 | /// non-memory intrinsics (with chains) that are not really instances of | |||
649 | /// MemSDNode. For such nodes, we need some extra state to determine the | |||
650 | /// proper classof relationship. | |||
651 | bool isMemIntrinsic() const { | |||
652 | return (NodeType == ISD::INTRINSIC_W_CHAIN || | |||
653 | NodeType == ISD::INTRINSIC_VOID) && | |||
654 | SDNodeBits.IsMemIntrinsic; | |||
655 | } | |||
656 | ||||
657 | /// Test if this node is a strict floating point pseudo-op. | |||
658 | bool isStrictFPOpcode() { | |||
659 | switch (NodeType) { | |||
660 | default: | |||
661 | return false; | |||
662 | case ISD::STRICT_FP16_TO_FP: | |||
663 | case ISD::STRICT_FP_TO_FP16: | |||
664 | #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ | |||
665 | case ISD::STRICT_##DAGN: | |||
666 | #include "llvm/IR/ConstrainedOps.def" | |||
667 | return true; | |||
668 | } | |||
669 | } | |||
670 | ||||
671 | /// Test if this node has a post-isel opcode, directly | |||
672 | /// corresponding to a MachineInstr opcode. | |||
673 | bool isMachineOpcode() const { return NodeType < 0; } | |||
674 | ||||
675 | /// This may only be called if isMachineOpcode returns | |||
676 | /// true. It returns the MachineInstr opcode value that the node's opcode | |||
677 | /// corresponds to. | |||
678 | unsigned getMachineOpcode() const { | |||
679 | assert(isMachineOpcode() && "Not a MachineInstr opcode!")((isMachineOpcode() && "Not a MachineInstr opcode!") ? static_cast<void> (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 679, __PRETTY_FUNCTION__)); | |||
680 | return ~NodeType; | |||
681 | } | |||
682 | ||||
683 | bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; } | |||
684 | void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; } | |||
685 | ||||
686 | bool isDivergent() const { return SDNodeBits.IsDivergent; } | |||
687 | ||||
688 | /// Return true if there are no uses of this node. | |||
689 | bool use_empty() const { return UseList == nullptr; } | |||
690 | ||||
691 | /// Return true if there is exactly one use of this node. | |||
692 | bool hasOneUse() const { return hasSingleElement(uses()); } | |||
693 | ||||
694 | /// Return the number of uses of this node. This method takes | |||
695 | /// time proportional to the number of uses. | |||
696 | size_t use_size() const { return std::distance(use_begin(), use_end()); } | |||
697 | ||||
698 | /// Return the unique node id. | |||
699 | int getNodeId() const { return NodeId; } | |||
700 | ||||
701 | /// Set unique node id. | |||
702 | void setNodeId(int Id) { NodeId = Id; } | |||
703 | ||||
704 | /// Return the node ordering. | |||
705 | unsigned getIROrder() const { return IROrder; } | |||
706 | ||||
707 | /// Set the node ordering. | |||
708 | void setIROrder(unsigned Order) { IROrder = Order; } | |||
709 | ||||
710 | /// Return the source location info. | |||
711 | const DebugLoc &getDebugLoc() const { return debugLoc; } | |||
712 | ||||
713 | /// Set source location info. Try to avoid this, putting | |||
714 | /// it in the constructor is preferable. | |||
715 | void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); } | |||
716 | ||||
717 | /// This class provides iterator support for SDUse | |||
718 | /// operands that use a specific SDNode. | |||
719 | class use_iterator { | |||
720 | friend class SDNode; | |||
721 | ||||
722 | SDUse *Op = nullptr; | |||
723 | ||||
724 | explicit use_iterator(SDUse *op) : Op(op) {} | |||
725 | ||||
726 | public: | |||
727 | using iterator_category = std::forward_iterator_tag; | |||
728 | using value_type = SDUse; | |||
729 | using difference_type = std::ptrdiff_t; | |||
730 | using pointer = value_type *; | |||
731 | using reference = value_type &; | |||
732 | ||||
733 | use_iterator() = default; | |||
734 | use_iterator(const use_iterator &I) : Op(I.Op) {} | |||
735 | ||||
736 | bool operator==(const use_iterator &x) const { | |||
737 | return Op == x.Op; | |||
738 | } | |||
739 | bool operator!=(const use_iterator &x) const { | |||
740 | return !operator==(x); | |||
741 | } | |||
742 | ||||
743 | /// Return true if this iterator is at the end of uses list. | |||
744 | bool atEnd() const { return Op == nullptr; } | |||
745 | ||||
746 | // Iterator traversal: forward iteration only. | |||
747 | use_iterator &operator++() { // Preincrement | |||
748 | assert(Op && "Cannot increment end iterator!")((Op && "Cannot increment end iterator!") ? static_cast <void> (0) : __assert_fail ("Op && \"Cannot increment end iterator!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 748, __PRETTY_FUNCTION__)); | |||
749 | Op = Op->getNext(); | |||
750 | return *this; | |||
751 | } | |||
752 | ||||
753 | use_iterator operator++(int) { // Postincrement | |||
754 | use_iterator tmp = *this; ++*this; return tmp; | |||
755 | } | |||
756 | ||||
757 | /// Retrieve a pointer to the current user node. | |||
758 | SDNode *operator*() const { | |||
759 | assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast <void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 759, __PRETTY_FUNCTION__)); | |||
760 | return Op->getUser(); | |||
761 | } | |||
762 | ||||
763 | SDNode *operator->() const { return operator*(); } | |||
764 | ||||
765 | SDUse &getUse() const { return *Op; } | |||
766 | ||||
767 | /// Retrieve the operand # of this use in its user. | |||
768 | unsigned getOperandNo() const { | |||
769 | assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast <void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 769, __PRETTY_FUNCTION__)); | |||
770 | return (unsigned)(Op - Op->getUser()->OperandList); | |||
771 | } | |||
772 | }; | |||
773 | ||||
774 | /// Provide iteration support to walk over all uses of an SDNode. | |||
775 | use_iterator use_begin() const { | |||
776 | return use_iterator(UseList); | |||
777 | } | |||
778 | ||||
779 | static use_iterator use_end() { return use_iterator(nullptr); } | |||
780 | ||||
781 | inline iterator_range<use_iterator> uses() { | |||
782 | return make_range(use_begin(), use_end()); | |||
783 | } | |||
784 | inline iterator_range<use_iterator> uses() const { | |||
785 | return make_range(use_begin(), use_end()); | |||
786 | } | |||
787 | ||||
788 | /// Return true if there are exactly NUSES uses of the indicated value. | |||
789 | /// This method ignores uses of other values defined by this operation. | |||
790 | bool hasNUsesOfValue(unsigned NUses, unsigned Value) const; | |||
791 | ||||
792 | /// Return true if there are any use of the indicated value. | |||
793 | /// This method ignores uses of other values defined by this operation. | |||
794 | bool hasAnyUseOfValue(unsigned Value) const; | |||
795 | ||||
796 | /// Return true if this node is the only use of N. | |||
797 | bool isOnlyUserOf(const SDNode *N) const; | |||
798 | ||||
799 | /// Return true if this node is an operand of N. | |||
800 | bool isOperandOf(const SDNode *N) const; | |||
801 | ||||
802 | /// Return true if this node is a predecessor of N. | |||
803 | /// NOTE: Implemented on top of hasPredecessor and every bit as | |||
804 | /// expensive. Use carefully. | |||
805 | bool isPredecessorOf(const SDNode *N) const { | |||
806 | return N->hasPredecessor(this); | |||
807 | } | |||
808 | ||||
809 | /// Return true if N is a predecessor of this node. | |||
810 | /// N is either an operand of this node, or can be reached by recursively | |||
811 | /// traversing up the operands. | |||
812 | /// NOTE: This is an expensive method. Use it carefully. | |||
813 | bool hasPredecessor(const SDNode *N) const; | |||
814 | ||||
815 | /// Returns true if N is a predecessor of any node in Worklist. This | |||
816 | /// helper keeps Visited and Worklist sets externally to allow unions | |||
817 | /// searches to be performed in parallel, caching of results across | |||
818 | /// queries and incremental addition to Worklist. Stops early if N is | |||
819 | /// found but will resume. Remember to clear Visited and Worklists | |||
820 | /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before | |||
821 | /// giving up. The TopologicalPrune flag signals that positive NodeIds are | |||
822 | /// topologically ordered (Operands have strictly smaller node id) and search | |||
823 | /// can be pruned leveraging this. | |||
824 | static bool hasPredecessorHelper(const SDNode *N, | |||
825 | SmallPtrSetImpl<const SDNode *> &Visited, | |||
826 | SmallVectorImpl<const SDNode *> &Worklist, | |||
827 | unsigned int MaxSteps = 0, | |||
828 | bool TopologicalPrune = false) { | |||
829 | SmallVector<const SDNode *, 8> DeferredNodes; | |||
830 | if (Visited.count(N)) | |||
831 | return true; | |||
832 | ||||
833 | // Node Id's are assigned in three places: As a topological | |||
834 | // ordering (> 0), during legalization (results in values set to | |||
835 | // 0), new nodes (set to -1). If N has a topolgical id then we | |||
836 | // know that all nodes with ids smaller than it cannot be | |||
837 | // successors and we need not check them. Filter out all node | |||
838 | // that can't be matches. We add them to the worklist before exit | |||
839 | // in case of multiple calls. Note that during selection the topological id | |||
840 | // may be violated if a node's predecessor is selected before it. We mark | |||
841 | // this at selection negating the id of unselected successors and | |||
842 | // restricting topological pruning to positive ids. | |||
843 | ||||
844 | int NId = N->getNodeId(); | |||
845 | // If we Invalidated the Id, reconstruct original NId. | |||
846 | if (NId < -1) | |||
847 | NId = -(NId + 1); | |||
848 | ||||
849 | bool Found = false; | |||
850 | while (!Worklist.empty()) { | |||
851 | const SDNode *M = Worklist.pop_back_val(); | |||
852 | int MId = M->getNodeId(); | |||
853 | if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) && | |||
854 | (MId > 0) && (MId < NId)) { | |||
855 | DeferredNodes.push_back(M); | |||
856 | continue; | |||
857 | } | |||
858 | for (const SDValue &OpV : M->op_values()) { | |||
859 | SDNode *Op = OpV.getNode(); | |||
860 | if (Visited.insert(Op).second) | |||
861 | Worklist.push_back(Op); | |||
862 | if (Op == N) | |||
863 | Found = true; | |||
864 | } | |||
865 | if (Found) | |||
866 | break; | |||
867 | if (MaxSteps != 0 && Visited.size() >= MaxSteps) | |||
868 | break; | |||
869 | } | |||
870 | // Push deferred nodes back on worklist. | |||
871 | Worklist.append(DeferredNodes.begin(), DeferredNodes.end()); | |||
872 | // If we bailed early, conservatively return found. | |||
873 | if (MaxSteps != 0 && Visited.size() >= MaxSteps) | |||
874 | return true; | |||
875 | return Found; | |||
876 | } | |||
877 | ||||
878 | /// Return true if all the users of N are contained in Nodes. | |||
879 | /// NOTE: Requires at least one match, but doesn't require them all. | |||
880 | static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N); | |||
881 | ||||
882 | /// Return the number of values used by this operation. | |||
883 | unsigned getNumOperands() const { return NumOperands; } | |||
884 | ||||
885 | /// Return the maximum number of operands that a SDNode can hold. | |||
886 | static constexpr size_t getMaxNumOperands() { | |||
887 | return std::numeric_limits<decltype(SDNode::NumOperands)>::max(); | |||
888 | } | |||
889 | ||||
890 | /// Helper method returns the integer value of a ConstantSDNode operand. | |||
891 | inline uint64_t getConstantOperandVal(unsigned Num) const; | |||
892 | ||||
893 | /// Helper method returns the APInt of a ConstantSDNode operand. | |||
894 | inline const APInt &getConstantOperandAPInt(unsigned Num) const; | |||
895 | ||||
896 | const SDValue &getOperand(unsigned Num) const { | |||
897 | assert(Num < NumOperands && "Invalid child # of SDNode!")((Num < NumOperands && "Invalid child # of SDNode!" ) ? static_cast<void> (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 897, __PRETTY_FUNCTION__)); | |||
898 | return OperandList[Num]; | |||
899 | } | |||
900 | ||||
901 | using op_iterator = SDUse *; | |||
902 | ||||
903 | op_iterator op_begin() const { return OperandList; } | |||
904 | op_iterator op_end() const { return OperandList+NumOperands; } | |||
905 | ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); } | |||
906 | ||||
907 | /// Iterator for directly iterating over the operand SDValue's. | |||
908 | struct value_op_iterator | |||
909 | : iterator_adaptor_base<value_op_iterator, op_iterator, | |||
910 | std::random_access_iterator_tag, SDValue, | |||
911 | ptrdiff_t, value_op_iterator *, | |||
912 | value_op_iterator *> { | |||
913 | explicit value_op_iterator(SDUse *U = nullptr) | |||
914 | : iterator_adaptor_base(U) {} | |||
915 | ||||
916 | const SDValue &operator*() const { return I->get(); } | |||
917 | }; | |||
918 | ||||
919 | iterator_range<value_op_iterator> op_values() const { | |||
920 | return make_range(value_op_iterator(op_begin()), | |||
921 | value_op_iterator(op_end())); | |||
922 | } | |||
923 | ||||
924 | SDVTList getVTList() const { | |||
925 | SDVTList X = { ValueList, NumValues }; | |||
926 | return X; | |||
927 | } | |||
928 | ||||
929 | /// If this node has a glue operand, return the node | |||
930 | /// to which the glue operand points. Otherwise return NULL. | |||
931 | SDNode *getGluedNode() const { | |||
932 | if (getNumOperands() != 0 && | |||
933 | getOperand(getNumOperands()-1).getValueType() == MVT::Glue) | |||
934 | return getOperand(getNumOperands()-1).getNode(); | |||
935 | return nullptr; | |||
936 | } | |||
937 | ||||
938 | /// If this node has a glue value with a user, return | |||
939 | /// the user (there is at most one). Otherwise return NULL. | |||
940 | SDNode *getGluedUser() const { | |||
941 | for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI) | |||
942 | if (UI.getUse().get().getValueType() == MVT::Glue) | |||
943 | return *UI; | |||
944 | return nullptr; | |||
945 | } | |||
946 | ||||
947 | SDNodeFlags getFlags() const { return Flags; } | |||
948 | void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; } | |||
949 | ||||
950 | /// Clear any flags in this node that aren't also set in Flags. | |||
951 | /// If Flags is not in a defined state then this has no effect. | |||
952 | void intersectFlagsWith(const SDNodeFlags Flags); | |||
953 | ||||
954 | /// Return the number of values defined/returned by this operator. | |||
955 | unsigned getNumValues() const { return NumValues; } | |||
956 | ||||
957 | /// Return the type of a specified result. | |||
958 | EVT getValueType(unsigned ResNo) const { | |||
959 | assert(ResNo < NumValues && "Illegal result number!")((ResNo < NumValues && "Illegal result number!") ? static_cast<void> (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 959, __PRETTY_FUNCTION__)); | |||
960 | return ValueList[ResNo]; | |||
961 | } | |||
962 | ||||
963 | /// Return the type of a specified result as a simple type. | |||
964 | MVT getSimpleValueType(unsigned ResNo) const { | |||
965 | return getValueType(ResNo).getSimpleVT(); | |||
966 | } | |||
967 | ||||
968 | /// Returns MVT::getSizeInBits(getValueType(ResNo)). | |||
969 | /// | |||
970 | /// If the value type is a scalable vector type, the scalable property will | |||
971 | /// be set and the runtime size will be a positive integer multiple of the | |||
972 | /// base size. | |||
973 | TypeSize getValueSizeInBits(unsigned ResNo) const { | |||
974 | return getValueType(ResNo).getSizeInBits(); | |||
975 | } | |||
976 | ||||
977 | using value_iterator = const EVT *; | |||
978 | ||||
979 | value_iterator value_begin() const { return ValueList; } | |||
980 | value_iterator value_end() const { return ValueList+NumValues; } | |||
981 | iterator_range<value_iterator> values() const { | |||
982 | return llvm::make_range(value_begin(), value_end()); | |||
983 | } | |||
984 | ||||
985 | /// Return the opcode of this operation for printing. | |||
986 | std::string getOperationName(const SelectionDAG *G = nullptr) const; | |||
987 | static const char* getIndexedModeName(ISD::MemIndexedMode AM); | |||
988 | void print_types(raw_ostream &OS, const SelectionDAG *G) const; | |||
989 | void print_details(raw_ostream &OS, const SelectionDAG *G) const; | |||
990 | void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const; | |||
991 | void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const; | |||
992 | ||||
993 | /// Print a SelectionDAG node and all children down to | |||
994 | /// the leaves. The given SelectionDAG allows target-specific nodes | |||
995 | /// to be printed in human-readable form. Unlike printr, this will | |||
996 | /// print the whole DAG, including children that appear multiple | |||
997 | /// times. | |||
998 | /// | |||
999 | void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const; | |||
1000 | ||||
1001 | /// Print a SelectionDAG node and children up to | |||
1002 | /// depth "depth." The given SelectionDAG allows target-specific | |||
1003 | /// nodes to be printed in human-readable form. Unlike printr, this | |||
1004 | /// will print children that appear multiple times wherever they are | |||
1005 | /// used. | |||
1006 | /// | |||
1007 | void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr, | |||
1008 | unsigned depth = 100) const; | |||
1009 | ||||
1010 | /// Dump this node, for debugging. | |||
1011 | void dump() const; | |||
1012 | ||||
1013 | /// Dump (recursively) this node and its use-def subgraph. | |||
1014 | void dumpr() const; | |||
1015 | ||||
1016 | /// Dump this node, for debugging. | |||
1017 | /// The given SelectionDAG allows target-specific nodes to be printed | |||
1018 | /// in human-readable form. | |||
1019 | void dump(const SelectionDAG *G) const; | |||
1020 | ||||
1021 | /// Dump (recursively) this node and its use-def subgraph. | |||
1022 | /// The given SelectionDAG allows target-specific nodes to be printed | |||
1023 | /// in human-readable form. | |||
1024 | void dumpr(const SelectionDAG *G) const; | |||
1025 | ||||
1026 | /// printrFull to dbgs(). The given SelectionDAG allows | |||
1027 | /// target-specific nodes to be printed in human-readable form. | |||
1028 | /// Unlike dumpr, this will print the whole DAG, including children | |||
1029 | /// that appear multiple times. | |||
1030 | void dumprFull(const SelectionDAG *G = nullptr) const; | |||
1031 | ||||
1032 | /// printrWithDepth to dbgs(). The given | |||
1033 | /// SelectionDAG allows target-specific nodes to be printed in | |||
1034 | /// human-readable form. Unlike dumpr, this will print children | |||
1035 | /// that appear multiple times wherever they are used. | |||
1036 | /// | |||
1037 | void dumprWithDepth(const SelectionDAG *G = nullptr, | |||
1038 | unsigned depth = 100) const; | |||
1039 | ||||
1040 | /// Gather unique data for the node. | |||
1041 | void Profile(FoldingSetNodeID &ID) const; | |||
1042 | ||||
1043 | /// This method should only be used by the SDUse class. | |||
1044 | void addUse(SDUse &U) { U.addToList(&UseList); } | |||
1045 | ||||
1046 | protected: | |||
1047 | static SDVTList getSDVTList(EVT VT) { | |||
1048 | SDVTList Ret = { getValueTypeList(VT), 1 }; | |||
1049 | return Ret; | |||
1050 | } | |||
1051 | ||||
1052 | /// Create an SDNode. | |||
1053 | /// | |||
1054 | /// SDNodes are created without any operands, and never own the operand | |||
1055 | /// storage. To add operands, see SelectionDAG::createOperands. | |||
1056 | SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs) | |||
1057 | : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs), | |||
1058 | IROrder(Order), debugLoc(std::move(dl)) { | |||
1059 | memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits)); | |||
1060 | assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor" ) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1060, __PRETTY_FUNCTION__)); | |||
1061 | assert(NumValues == VTs.NumVTs &&((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!" ) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1062, __PRETTY_FUNCTION__)) | |||
1062 | "NumValues wasn't wide enough for its operands!")((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!" ) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1062, __PRETTY_FUNCTION__)); | |||
1063 | } | |||
1064 | ||||
1065 | /// Release the operands and set this node to have zero operands. | |||
1066 | void DropOperands(); | |||
1067 | }; | |||
1068 | ||||
1069 | /// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed | |||
1070 | /// into SDNode creation functions. | |||
1071 | /// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted | |||
1072 | /// from the original Instruction, and IROrder is the ordinal position of | |||
1073 | /// the instruction. | |||
1074 | /// When an SDNode is created after the DAG is being built, both DebugLoc and | |||
1075 | /// the IROrder are propagated from the original SDNode. | |||
1076 | /// So SDLoc class provides two constructors besides the default one, one to | |||
1077 | /// be used by the DAGBuilder, the other to be used by others. | |||
1078 | class SDLoc { | |||
1079 | private: | |||
1080 | DebugLoc DL; | |||
1081 | int IROrder = 0; | |||
1082 | ||||
1083 | public: | |||
1084 | SDLoc() = default; | |||
1085 | SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {} | |||
1086 | SDLoc(const SDValue V) : SDLoc(V.getNode()) {} | |||
1087 | SDLoc(const Instruction *I, int Order) : IROrder(Order) { | |||
1088 | assert(Order >= 0 && "bad IROrder")((Order >= 0 && "bad IROrder") ? static_cast<void > (0) : __assert_fail ("Order >= 0 && \"bad IROrder\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1088, __PRETTY_FUNCTION__)); | |||
1089 | if (I) | |||
1090 | DL = I->getDebugLoc(); | |||
1091 | } | |||
1092 | ||||
1093 | unsigned getIROrder() const { return IROrder; } | |||
1094 | const DebugLoc &getDebugLoc() const { return DL; } | |||
1095 | }; | |||
1096 | ||||
1097 | // Define inline functions from the SDValue class. | |||
1098 | ||||
1099 | inline SDValue::SDValue(SDNode *node, unsigned resno) | |||
1100 | : Node(node), ResNo(resno) { | |||
1101 | // Explicitly check for !ResNo to avoid use-after-free, because there are | |||
1102 | // callers that use SDValue(N, 0) with a deleted N to indicate successful | |||
1103 | // combines. | |||
1104 | assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(((!Node || !ResNo || ResNo < Node->getNumValues()) && "Invalid result number for the given node!") ? static_cast< void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1105, __PRETTY_FUNCTION__)) | |||
1105 | "Invalid result number for the given node!")(((!Node || !ResNo || ResNo < Node->getNumValues()) && "Invalid result number for the given node!") ? static_cast< void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1105, __PRETTY_FUNCTION__)); | |||
1106 | assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")((ResNo < -2U && "Cannot use result numbers reserved for DenseMaps." ) ? static_cast<void> (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1106, __PRETTY_FUNCTION__)); | |||
1107 | } | |||
1108 | ||||
1109 | inline unsigned SDValue::getOpcode() const { | |||
1110 | return Node->getOpcode(); | |||
| ||||
1111 | } | |||
1112 | ||||
1113 | inline EVT SDValue::getValueType() const { | |||
1114 | return Node->getValueType(ResNo); | |||
1115 | } | |||
1116 | ||||
1117 | inline unsigned SDValue::getNumOperands() const { | |||
1118 | return Node->getNumOperands(); | |||
1119 | } | |||
1120 | ||||
1121 | inline const SDValue &SDValue::getOperand(unsigned i) const { | |||
1122 | return Node->getOperand(i); | |||
1123 | } | |||
1124 | ||||
1125 | inline uint64_t SDValue::getConstantOperandVal(unsigned i) const { | |||
1126 | return Node->getConstantOperandVal(i); | |||
1127 | } | |||
1128 | ||||
1129 | inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const { | |||
1130 | return Node->getConstantOperandAPInt(i); | |||
1131 | } | |||
1132 | ||||
1133 | inline bool SDValue::isTargetOpcode() const { | |||
1134 | return Node->isTargetOpcode(); | |||
1135 | } | |||
1136 | ||||
1137 | inline bool SDValue::isTargetMemoryOpcode() const { | |||
1138 | return Node->isTargetMemoryOpcode(); | |||
1139 | } | |||
1140 | ||||
1141 | inline bool SDValue::isMachineOpcode() const { | |||
1142 | return Node->isMachineOpcode(); | |||
1143 | } | |||
1144 | ||||
1145 | inline unsigned SDValue::getMachineOpcode() const { | |||
1146 | return Node->getMachineOpcode(); | |||
1147 | } | |||
1148 | ||||
1149 | inline bool SDValue::isUndef() const { | |||
1150 | return Node->isUndef(); | |||
1151 | } | |||
1152 | ||||
1153 | inline bool SDValue::use_empty() const { | |||
1154 | return !Node->hasAnyUseOfValue(ResNo); | |||
1155 | } | |||
1156 | ||||
1157 | inline bool SDValue::hasOneUse() const { | |||
1158 | return Node->hasNUsesOfValue(1, ResNo); | |||
1159 | } | |||
1160 | ||||
1161 | inline const DebugLoc &SDValue::getDebugLoc() const { | |||
1162 | return Node->getDebugLoc(); | |||
1163 | } | |||
1164 | ||||
1165 | inline void SDValue::dump() const { | |||
1166 | return Node->dump(); | |||
1167 | } | |||
1168 | ||||
1169 | inline void SDValue::dump(const SelectionDAG *G) const { | |||
1170 | return Node->dump(G); | |||
1171 | } | |||
1172 | ||||
1173 | inline void SDValue::dumpr() const { | |||
1174 | return Node->dumpr(); | |||
1175 | } | |||
1176 | ||||
1177 | inline void SDValue::dumpr(const SelectionDAG *G) const { | |||
1178 | return Node->dumpr(G); | |||
1179 | } | |||
1180 | ||||
1181 | // Define inline functions from the SDUse class. | |||
1182 | ||||
1183 | inline void SDUse::set(const SDValue &V) { | |||
1184 | if (Val.getNode()) removeFromList(); | |||
1185 | Val = V; | |||
1186 | if (V.getNode()) V.getNode()->addUse(*this); | |||
1187 | } | |||
1188 | ||||
1189 | inline void SDUse::setInitial(const SDValue &V) { | |||
1190 | Val = V; | |||
1191 | V.getNode()->addUse(*this); | |||
1192 | } | |||
1193 | ||||
1194 | inline void SDUse::setNode(SDNode *N) { | |||
1195 | if (Val.getNode()) removeFromList(); | |||
1196 | Val.setNode(N); | |||
1197 | if (N) N->addUse(*this); | |||
1198 | } | |||
1199 | ||||
1200 | /// This class is used to form a handle around another node that | |||
1201 | /// is persistent and is updated across invocations of replaceAllUsesWith on its | |||
1202 | /// operand. This node should be directly created by end-users and not added to | |||
1203 | /// the AllNodes list. | |||
1204 | class HandleSDNode : public SDNode { | |||
1205 | SDUse Op; | |||
1206 | ||||
1207 | public: | |||
1208 | explicit HandleSDNode(SDValue X) | |||
1209 | : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) { | |||
1210 | // HandleSDNodes are never inserted into the DAG, so they won't be | |||
1211 | // auto-numbered. Use ID 65535 as a sentinel. | |||
1212 | PersistentId = 0xffff; | |||
1213 | ||||
1214 | // Manually set up the operand list. This node type is special in that it's | |||
1215 | // always stack allocated and SelectionDAG does not manage its operands. | |||
1216 | // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not | |||
1217 | // be so special. | |||
1218 | Op.setUser(this); | |||
1219 | Op.setInitial(X); | |||
1220 | NumOperands = 1; | |||
1221 | OperandList = &Op; | |||
1222 | } | |||
1223 | ~HandleSDNode(); | |||
1224 | ||||
1225 | const SDValue &getValue() const { return Op; } | |||
1226 | }; | |||
1227 | ||||
1228 | class AddrSpaceCastSDNode : public SDNode { | |||
1229 | private: | |||
1230 | unsigned SrcAddrSpace; | |||
1231 | unsigned DestAddrSpace; | |||
1232 | ||||
1233 | public: | |||
1234 | AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT, | |||
1235 | unsigned SrcAS, unsigned DestAS); | |||
1236 | ||||
1237 | unsigned getSrcAddressSpace() const { return SrcAddrSpace; } | |||
1238 | unsigned getDestAddressSpace() const { return DestAddrSpace; } | |||
1239 | ||||
1240 | static bool classof(const SDNode *N) { | |||
1241 | return N->getOpcode() == ISD::ADDRSPACECAST; | |||
1242 | } | |||
1243 | }; | |||
1244 | ||||
1245 | /// This is an abstract virtual class for memory operations. | |||
1246 | class MemSDNode : public SDNode { | |||
1247 | private: | |||
1248 | // VT of in-memory value. | |||
1249 | EVT MemoryVT; | |||
1250 | ||||
1251 | protected: | |||
1252 | /// Memory reference information. | |||
1253 | MachineMemOperand *MMO; | |||
1254 | ||||
1255 | public: | |||
1256 | MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
1257 | EVT memvt, MachineMemOperand *MMO); | |||
1258 | ||||
1259 | bool readMem() const { return MMO->isLoad(); } | |||
1260 | bool writeMem() const { return MMO->isStore(); } | |||
1261 | ||||
1262 | /// Returns alignment and volatility of the memory access | |||
1263 | Align getOriginalAlign() const { return MMO->getBaseAlign(); } | |||
1264 | Align getAlign() const { return MMO->getAlign(); } | |||
1265 | LLVM_ATTRIBUTE_DEPRECATED(unsigned getOriginalAlignment() const,[[deprecated("Use getOriginalAlign() instead")]] unsigned getOriginalAlignment () const | |||
1266 | "Use getOriginalAlign() instead")[[deprecated("Use getOriginalAlign() instead")]] unsigned getOriginalAlignment () const { | |||
1267 | return MMO->getBaseAlign().value(); | |||
1268 | } | |||
1269 | // FIXME: Remove once transition to getAlign is over. | |||
1270 | unsigned getAlignment() const { return MMO->getAlign().value(); } | |||
1271 | ||||
1272 | /// Return the SubclassData value, without HasDebugValue. This contains an | |||
1273 | /// encoding of the volatile flag, as well as bits used by subclasses. This | |||
1274 | /// function should only be used to compute a FoldingSetNodeID value. | |||
1275 | /// The HasDebugValue bit is masked out because CSE map needs to match | |||
1276 | /// nodes with debug info with nodes without debug info. Same is about | |||
1277 | /// isDivergent bit. | |||
1278 | unsigned getRawSubclassData() const { | |||
1279 | uint16_t Data; | |||
1280 | union { | |||
1281 | char RawSDNodeBits[sizeof(uint16_t)]; | |||
1282 | SDNodeBitfields SDNodeBits; | |||
1283 | }; | |||
1284 | memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits)); | |||
1285 | SDNodeBits.HasDebugValue = 0; | |||
1286 | SDNodeBits.IsDivergent = false; | |||
1287 | memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits)); | |||
1288 | return Data; | |||
1289 | } | |||
1290 | ||||
1291 | bool isVolatile() const { return MemSDNodeBits.IsVolatile; } | |||
1292 | bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; } | |||
1293 | bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; } | |||
1294 | bool isInvariant() const { return MemSDNodeBits.IsInvariant; } | |||
1295 | ||||
1296 | // Returns the offset from the location of the access. | |||
1297 | int64_t getSrcValueOffset() const { return MMO->getOffset(); } | |||
1298 | ||||
1299 | /// Returns the AA info that describes the dereference. | |||
1300 | AAMDNodes getAAInfo() const { return MMO->getAAInfo(); } | |||
1301 | ||||
1302 | /// Returns the Ranges that describes the dereference. | |||
1303 | const MDNode *getRanges() const { return MMO->getRanges(); } | |||
1304 | ||||
1305 | /// Returns the synchronization scope ID for this memory operation. | |||
1306 | SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); } | |||
1307 | ||||
1308 | /// Return the atomic ordering requirements for this memory operation. For | |||
1309 | /// cmpxchg atomic operations, return the atomic ordering requirements when | |||
1310 | /// store occurs. | |||
1311 | AtomicOrdering getOrdering() const { return MMO->getOrdering(); } | |||
1312 | ||||
1313 | /// Return true if the memory operation ordering is Unordered or higher. | |||
1314 | bool isAtomic() const { return MMO->isAtomic(); } | |||
1315 | ||||
1316 | /// Returns true if the memory operation doesn't imply any ordering | |||
1317 | /// constraints on surrounding memory operations beyond the normal memory | |||
1318 | /// aliasing rules. | |||
1319 | bool isUnordered() const { return MMO->isUnordered(); } | |||
1320 | ||||
1321 | /// Returns true if the memory operation is neither atomic or volatile. | |||
1322 | bool isSimple() const { return !isAtomic() && !isVolatile(); } | |||
1323 | ||||
1324 | /// Return the type of the in-memory value. | |||
1325 | EVT getMemoryVT() const { return MemoryVT; } | |||
1326 | ||||
1327 | /// Return a MachineMemOperand object describing the memory | |||
1328 | /// reference performed by operation. | |||
1329 | MachineMemOperand *getMemOperand() const { return MMO; } | |||
1330 | ||||
1331 | const MachinePointerInfo &getPointerInfo() const { | |||
1332 | return MMO->getPointerInfo(); | |||
1333 | } | |||
1334 | ||||
1335 | /// Return the address space for the associated pointer | |||
1336 | unsigned getAddressSpace() const { | |||
1337 | return getPointerInfo().getAddrSpace(); | |||
1338 | } | |||
1339 | ||||
1340 | /// Update this MemSDNode's MachineMemOperand information | |||
1341 | /// to reflect the alignment of NewMMO, if it has a greater alignment. | |||
1342 | /// This must only be used when the new alignment applies to all users of | |||
1343 | /// this MachineMemOperand. | |||
1344 | void refineAlignment(const MachineMemOperand *NewMMO) { | |||
1345 | MMO->refineAlignment(NewMMO); | |||
1346 | } | |||
1347 | ||||
1348 | const SDValue &getChain() const { return getOperand(0); } | |||
1349 | ||||
1350 | const SDValue &getBasePtr() const { | |||
1351 | switch (getOpcode()) { | |||
1352 | case ISD::STORE: | |||
1353 | case ISD::MSTORE: | |||
1354 | return getOperand(2); | |||
1355 | case ISD::MGATHER: | |||
1356 | case ISD::MSCATTER: | |||
1357 | return getOperand(3); | |||
1358 | default: | |||
1359 | return getOperand(1); | |||
1360 | } | |||
1361 | } | |||
1362 | ||||
1363 | // Methods to support isa and dyn_cast | |||
1364 | static bool classof(const SDNode *N) { | |||
1365 | // For some targets, we lower some target intrinsics to a MemIntrinsicNode | |||
1366 | // with either an intrinsic or a target opcode. | |||
1367 | return N->getOpcode() == ISD::LOAD || | |||
1368 | N->getOpcode() == ISD::STORE || | |||
1369 | N->getOpcode() == ISD::PREFETCH || | |||
1370 | N->getOpcode() == ISD::ATOMIC_CMP_SWAP || | |||
1371 | N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS || | |||
1372 | N->getOpcode() == ISD::ATOMIC_SWAP || | |||
1373 | N->getOpcode() == ISD::ATOMIC_LOAD_ADD || | |||
1374 | N->getOpcode() == ISD::ATOMIC_LOAD_SUB || | |||
1375 | N->getOpcode() == ISD::ATOMIC_LOAD_AND || | |||
1376 | N->getOpcode() == ISD::ATOMIC_LOAD_CLR || | |||
1377 | N->getOpcode() == ISD::ATOMIC_LOAD_OR || | |||
1378 | N->getOpcode() == ISD::ATOMIC_LOAD_XOR || | |||
1379 | N->getOpcode() == ISD::ATOMIC_LOAD_NAND || | |||
1380 | N->getOpcode() == ISD::ATOMIC_LOAD_MIN || | |||
1381 | N->getOpcode() == ISD::ATOMIC_LOAD_MAX || | |||
1382 | N->getOpcode() == ISD::ATOMIC_LOAD_UMIN || | |||
1383 | N->getOpcode() == ISD::ATOMIC_LOAD_UMAX || | |||
1384 | N->getOpcode() == ISD::ATOMIC_LOAD_FADD || | |||
1385 | N->getOpcode() == ISD::ATOMIC_LOAD_FSUB || | |||
1386 | N->getOpcode() == ISD::ATOMIC_LOAD || | |||
1387 | N->getOpcode() == ISD::ATOMIC_STORE || | |||
1388 | N->getOpcode() == ISD::MLOAD || | |||
1389 | N->getOpcode() == ISD::MSTORE || | |||
1390 | N->getOpcode() == ISD::MGATHER || | |||
1391 | N->getOpcode() == ISD::MSCATTER || | |||
1392 | N->isMemIntrinsic() || | |||
1393 | N->isTargetMemoryOpcode(); | |||
1394 | } | |||
1395 | }; | |||
1396 | ||||
1397 | /// This is an SDNode representing atomic operations. | |||
1398 | class AtomicSDNode : public MemSDNode { | |||
1399 | public: | |||
1400 | AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL, | |||
1401 | EVT MemVT, MachineMemOperand *MMO) | |||
1402 | : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) { | |||
1403 | assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE ) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?" ) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1404, __PRETTY_FUNCTION__)) | |||
1404 | MMO->isAtomic()) && "then why are we using an AtomicSDNode?")((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE ) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?" ) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1404, __PRETTY_FUNCTION__)); | |||
1405 | } | |||
1406 | ||||
1407 | const SDValue &getBasePtr() const { return getOperand(1); } | |||
1408 | const SDValue &getVal() const { return getOperand(2); } | |||
1409 | ||||
1410 | /// Returns true if this SDNode represents cmpxchg atomic operation, false | |||
1411 | /// otherwise. | |||
1412 | bool isCompareAndSwap() const { | |||
1413 | unsigned Op = getOpcode(); | |||
1414 | return Op == ISD::ATOMIC_CMP_SWAP || | |||
1415 | Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS; | |||
1416 | } | |||
1417 | ||||
1418 | /// For cmpxchg atomic operations, return the atomic ordering requirements | |||
1419 | /// when store does not occur. | |||
1420 | AtomicOrdering getFailureOrdering() const { | |||
1421 | assert(isCompareAndSwap() && "Must be cmpxchg operation")((isCompareAndSwap() && "Must be cmpxchg operation") ? static_cast<void> (0) : __assert_fail ("isCompareAndSwap() && \"Must be cmpxchg operation\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1421, __PRETTY_FUNCTION__)); | |||
1422 | return MMO->getFailureOrdering(); | |||
1423 | } | |||
1424 | ||||
1425 | // Methods to support isa and dyn_cast | |||
1426 | static bool classof(const SDNode *N) { | |||
1427 | return N->getOpcode() == ISD::ATOMIC_CMP_SWAP || | |||
1428 | N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS || | |||
1429 | N->getOpcode() == ISD::ATOMIC_SWAP || | |||
1430 | N->getOpcode() == ISD::ATOMIC_LOAD_ADD || | |||
1431 | N->getOpcode() == ISD::ATOMIC_LOAD_SUB || | |||
1432 | N->getOpcode() == ISD::ATOMIC_LOAD_AND || | |||
1433 | N->getOpcode() == ISD::ATOMIC_LOAD_CLR || | |||
1434 | N->getOpcode() == ISD::ATOMIC_LOAD_OR || | |||
1435 | N->getOpcode() == ISD::ATOMIC_LOAD_XOR || | |||
1436 | N->getOpcode() == ISD::ATOMIC_LOAD_NAND || | |||
1437 | N->getOpcode() == ISD::ATOMIC_LOAD_MIN || | |||
1438 | N->getOpcode() == ISD::ATOMIC_LOAD_MAX || | |||
1439 | N->getOpcode() == ISD::ATOMIC_LOAD_UMIN || | |||
1440 | N->getOpcode() == ISD::ATOMIC_LOAD_UMAX || | |||
1441 | N->getOpcode() == ISD::ATOMIC_LOAD_FADD || | |||
1442 | N->getOpcode() == ISD::ATOMIC_LOAD_FSUB || | |||
1443 | N->getOpcode() == ISD::ATOMIC_LOAD || | |||
1444 | N->getOpcode() == ISD::ATOMIC_STORE; | |||
1445 | } | |||
1446 | }; | |||
1447 | ||||
1448 | /// This SDNode is used for target intrinsics that touch | |||
1449 | /// memory and need an associated MachineMemOperand. Its opcode may be | |||
1450 | /// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode | |||
1451 | /// with a value not less than FIRST_TARGET_MEMORY_OPCODE. | |||
1452 | class MemIntrinsicSDNode : public MemSDNode { | |||
1453 | public: | |||
1454 | MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, | |||
1455 | SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO) | |||
1456 | : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) { | |||
1457 | SDNodeBits.IsMemIntrinsic = true; | |||
1458 | } | |||
1459 | ||||
1460 | // Methods to support isa and dyn_cast | |||
1461 | static bool classof(const SDNode *N) { | |||
1462 | // We lower some target intrinsics to their target opcode | |||
1463 | // early a node with a target opcode can be of this class | |||
1464 | return N->isMemIntrinsic() || | |||
1465 | N->getOpcode() == ISD::PREFETCH || | |||
1466 | N->isTargetMemoryOpcode(); | |||
1467 | } | |||
1468 | }; | |||
1469 | ||||
1470 | /// This SDNode is used to implement the code generator | |||
1471 | /// support for the llvm IR shufflevector instruction. It combines elements | |||
1472 | /// from two input vectors into a new input vector, with the selection and | |||
1473 | /// ordering of elements determined by an array of integers, referred to as | |||
1474 | /// the shuffle mask. For input vectors of width N, mask indices of 0..N-1 | |||
1475 | /// refer to elements from the LHS input, and indices from N to 2N-1 the RHS. | |||
1476 | /// An index of -1 is treated as undef, such that the code generator may put | |||
1477 | /// any value in the corresponding element of the result. | |||
1478 | class ShuffleVectorSDNode : public SDNode { | |||
1479 | // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and | |||
1480 | // is freed when the SelectionDAG object is destroyed. | |||
1481 | const int *Mask; | |||
1482 | ||||
1483 | protected: | |||
1484 | friend class SelectionDAG; | |||
1485 | ||||
1486 | ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M) | |||
1487 | : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {} | |||
1488 | ||||
1489 | public: | |||
1490 | ArrayRef<int> getMask() const { | |||
1491 | EVT VT = getValueType(0); | |||
1492 | return makeArrayRef(Mask, VT.getVectorNumElements()); | |||
1493 | } | |||
1494 | ||||
1495 | int getMaskElt(unsigned Idx) const { | |||
1496 | assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!")((Idx < getValueType(0).getVectorNumElements() && "Idx out of range!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getValueType(0).getVectorNumElements() && \"Idx out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1496, __PRETTY_FUNCTION__)); | |||
1497 | return Mask[Idx]; | |||
1498 | } | |||
1499 | ||||
1500 | bool isSplat() const { return isSplatMask(Mask, getValueType(0)); } | |||
1501 | ||||
1502 | int getSplatIndex() const { | |||
1503 | assert(isSplat() && "Cannot get splat index for non-splat!")((isSplat() && "Cannot get splat index for non-splat!" ) ? static_cast<void> (0) : __assert_fail ("isSplat() && \"Cannot get splat index for non-splat!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1503, __PRETTY_FUNCTION__)); | |||
1504 | EVT VT = getValueType(0); | |||
1505 | for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) | |||
1506 | if (Mask[i] >= 0) | |||
1507 | return Mask[i]; | |||
1508 | ||||
1509 | // We can choose any index value here and be correct because all elements | |||
1510 | // are undefined. Return 0 for better potential for callers to simplify. | |||
1511 | return 0; | |||
1512 | } | |||
1513 | ||||
1514 | static bool isSplatMask(const int *Mask, EVT VT); | |||
1515 | ||||
1516 | /// Change values in a shuffle permute mask assuming | |||
1517 | /// the two vector operands have swapped position. | |||
1518 | static void commuteMask(MutableArrayRef<int> Mask) { | |||
1519 | unsigned NumElems = Mask.size(); | |||
1520 | for (unsigned i = 0; i != NumElems; ++i) { | |||
1521 | int idx = Mask[i]; | |||
1522 | if (idx < 0) | |||
1523 | continue; | |||
1524 | else if (idx < (int)NumElems) | |||
1525 | Mask[i] = idx + NumElems; | |||
1526 | else | |||
1527 | Mask[i] = idx - NumElems; | |||
1528 | } | |||
1529 | } | |||
1530 | ||||
1531 | static bool classof(const SDNode *N) { | |||
1532 | return N->getOpcode() == ISD::VECTOR_SHUFFLE; | |||
1533 | } | |||
1534 | }; | |||
1535 | ||||
1536 | class ConstantSDNode : public SDNode { | |||
1537 | friend class SelectionDAG; | |||
1538 | ||||
1539 | const ConstantInt *Value; | |||
1540 | ||||
1541 | ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT) | |||
1542 | : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(), | |||
1543 | getSDVTList(VT)), | |||
1544 | Value(val) { | |||
1545 | ConstantSDNodeBits.IsOpaque = isOpaque; | |||
1546 | } | |||
1547 | ||||
1548 | public: | |||
1549 | const ConstantInt *getConstantIntValue() const { return Value; } | |||
1550 | const APInt &getAPIntValue() const { return Value->getValue(); } | |||
1551 | uint64_t getZExtValue() const { return Value->getZExtValue(); } | |||
1552 | int64_t getSExtValue() const { return Value->getSExtValue(); } | |||
1553 | uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) { | |||
1554 | return Value->getLimitedValue(Limit); | |||
1555 | } | |||
1556 | MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); } | |||
1557 | Align getAlignValue() const { return Value->getAlignValue(); } | |||
1558 | ||||
1559 | bool isOne() const { return Value->isOne(); } | |||
1560 | bool isNullValue() const { return Value->isZero(); } | |||
1561 | bool isAllOnesValue() const { return Value->isMinusOne(); } | |||
1562 | ||||
1563 | bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; } | |||
1564 | ||||
1565 | static bool classof(const SDNode *N) { | |||
1566 | return N->getOpcode() == ISD::Constant || | |||
1567 | N->getOpcode() == ISD::TargetConstant; | |||
1568 | } | |||
1569 | }; | |||
1570 | ||||
1571 | uint64_t SDNode::getConstantOperandVal(unsigned Num) const { | |||
1572 | return cast<ConstantSDNode>(getOperand(Num))->getZExtValue(); | |||
1573 | } | |||
1574 | ||||
1575 | const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const { | |||
1576 | return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue(); | |||
1577 | } | |||
1578 | ||||
1579 | class ConstantFPSDNode : public SDNode { | |||
1580 | friend class SelectionDAG; | |||
1581 | ||||
1582 | const ConstantFP *Value; | |||
1583 | ||||
1584 | ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT) | |||
1585 | : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0, | |||
1586 | DebugLoc(), getSDVTList(VT)), | |||
1587 | Value(val) {} | |||
1588 | ||||
1589 | public: | |||
1590 | const APFloat& getValueAPF() const { return Value->getValueAPF(); } | |||
1591 | const ConstantFP *getConstantFPValue() const { return Value; } | |||
1592 | ||||
1593 | /// Return true if the value is positive or negative zero. | |||
1594 | bool isZero() const { return Value->isZero(); } | |||
1595 | ||||
1596 | /// Return true if the value is a NaN. | |||
1597 | bool isNaN() const { return Value->isNaN(); } | |||
1598 | ||||
1599 | /// Return true if the value is an infinity | |||
1600 | bool isInfinity() const { return Value->isInfinity(); } | |||
1601 | ||||
1602 | /// Return true if the value is negative. | |||
1603 | bool isNegative() const { return Value->isNegative(); } | |||
1604 | ||||
1605 | /// We don't rely on operator== working on double values, as | |||
1606 | /// it returns true for things that are clearly not equal, like -0.0 and 0.0. | |||
1607 | /// As such, this method can be used to do an exact bit-for-bit comparison of | |||
1608 | /// two floating point values. | |||
1609 | ||||
1610 | /// We leave the version with the double argument here because it's just so | |||
1611 | /// convenient to write "2.0" and the like. Without this function we'd | |||
1612 | /// have to duplicate its logic everywhere it's called. | |||
1613 | bool isExactlyValue(double V) const { | |||
1614 | return Value->getValueAPF().isExactlyValue(V); | |||
1615 | } | |||
1616 | bool isExactlyValue(const APFloat& V) const; | |||
1617 | ||||
1618 | static bool isValueValidForType(EVT VT, const APFloat& Val); | |||
1619 | ||||
1620 | static bool classof(const SDNode *N) { | |||
1621 | return N->getOpcode() == ISD::ConstantFP || | |||
1622 | N->getOpcode() == ISD::TargetConstantFP; | |||
1623 | } | |||
1624 | }; | |||
1625 | ||||
1626 | /// Returns true if \p V is a constant integer zero. | |||
1627 | bool isNullConstant(SDValue V); | |||
1628 | ||||
1629 | /// Returns true if \p V is an FP constant with a value of positive zero. | |||
1630 | bool isNullFPConstant(SDValue V); | |||
1631 | ||||
1632 | /// Returns true if \p V is an integer constant with all bits set. | |||
1633 | bool isAllOnesConstant(SDValue V); | |||
1634 | ||||
1635 | /// Returns true if \p V is a constant integer one. | |||
1636 | bool isOneConstant(SDValue V); | |||
1637 | ||||
1638 | /// Return the non-bitcasted source operand of \p V if it exists. | |||
1639 | /// If \p V is not a bitcasted value, it is returned as-is. | |||
1640 | SDValue peekThroughBitcasts(SDValue V); | |||
1641 | ||||
1642 | /// Return the non-bitcasted and one-use source operand of \p V if it exists. | |||
1643 | /// If \p V is not a bitcasted one-use value, it is returned as-is. | |||
1644 | SDValue peekThroughOneUseBitcasts(SDValue V); | |||
1645 | ||||
1646 | /// Return the non-extracted vector source operand of \p V if it exists. | |||
1647 | /// If \p V is not an extracted subvector, it is returned as-is. | |||
1648 | SDValue peekThroughExtractSubvectors(SDValue V); | |||
1649 | ||||
1650 | /// Returns true if \p V is a bitwise not operation. Assumes that an all ones | |||
1651 | /// constant is canonicalized to be operand 1. | |||
1652 | bool isBitwiseNot(SDValue V, bool AllowUndefs = false); | |||
1653 | ||||
1654 | /// Returns the SDNode if it is a constant splat BuildVector or constant int. | |||
1655 | ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false, | |||
1656 | bool AllowTruncation = false); | |||
1657 | ||||
1658 | /// Returns the SDNode if it is a demanded constant splat BuildVector or | |||
1659 | /// constant int. | |||
1660 | ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts, | |||
1661 | bool AllowUndefs = false, | |||
1662 | bool AllowTruncation = false); | |||
1663 | ||||
1664 | /// Returns the SDNode if it is a constant splat BuildVector or constant float. | |||
1665 | ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false); | |||
1666 | ||||
1667 | /// Returns the SDNode if it is a demanded constant splat BuildVector or | |||
1668 | /// constant float. | |||
1669 | ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts, | |||
1670 | bool AllowUndefs = false); | |||
1671 | ||||
1672 | /// Return true if the value is a constant 0 integer or a splatted vector of | |||
1673 | /// a constant 0 integer (with no undefs by default). | |||
1674 | /// Build vector implicit truncation is not an issue for null values. | |||
1675 | bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false); | |||
1676 | ||||
1677 | /// Return true if the value is a constant 1 integer or a splatted vector of a | |||
1678 | /// constant 1 integer (with no undefs). | |||
1679 | /// Does not permit build vector implicit truncation. | |||
1680 | bool isOneOrOneSplat(SDValue V, bool AllowUndefs = false); | |||
1681 | ||||
1682 | /// Return true if the value is a constant -1 integer or a splatted vector of a | |||
1683 | /// constant -1 integer (with no undefs). | |||
1684 | /// Does not permit build vector implicit truncation. | |||
1685 | bool isAllOnesOrAllOnesSplat(SDValue V, bool AllowUndefs = false); | |||
1686 | ||||
1687 | /// Return true if \p V is either a integer or FP constant. | |||
1688 | inline bool isIntOrFPConstant(SDValue V) { | |||
1689 | return isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V); | |||
1690 | } | |||
1691 | ||||
1692 | class GlobalAddressSDNode : public SDNode { | |||
1693 | friend class SelectionDAG; | |||
1694 | ||||
1695 | const GlobalValue *TheGlobal; | |||
1696 | int64_t Offset; | |||
1697 | unsigned TargetFlags; | |||
1698 | ||||
1699 | GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, | |||
1700 | const GlobalValue *GA, EVT VT, int64_t o, | |||
1701 | unsigned TF); | |||
1702 | ||||
1703 | public: | |||
1704 | const GlobalValue *getGlobal() const { return TheGlobal; } | |||
1705 | int64_t getOffset() const { return Offset; } | |||
1706 | unsigned getTargetFlags() const { return TargetFlags; } | |||
1707 | // Return the address space this GlobalAddress belongs to. | |||
1708 | unsigned getAddressSpace() const; | |||
1709 | ||||
1710 | static bool classof(const SDNode *N) { | |||
1711 | return N->getOpcode() == ISD::GlobalAddress || | |||
1712 | N->getOpcode() == ISD::TargetGlobalAddress || | |||
1713 | N->getOpcode() == ISD::GlobalTLSAddress || | |||
1714 | N->getOpcode() == ISD::TargetGlobalTLSAddress; | |||
1715 | } | |||
1716 | }; | |||
1717 | ||||
1718 | class FrameIndexSDNode : public SDNode { | |||
1719 | friend class SelectionDAG; | |||
1720 | ||||
1721 | int FI; | |||
1722 | ||||
1723 | FrameIndexSDNode(int fi, EVT VT, bool isTarg) | |||
1724 | : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex, | |||
1725 | 0, DebugLoc(), getSDVTList(VT)), FI(fi) { | |||
1726 | } | |||
1727 | ||||
1728 | public: | |||
1729 | int getIndex() const { return FI; } | |||
1730 | ||||
1731 | static bool classof(const SDNode *N) { | |||
1732 | return N->getOpcode() == ISD::FrameIndex || | |||
1733 | N->getOpcode() == ISD::TargetFrameIndex; | |||
1734 | } | |||
1735 | }; | |||
1736 | ||||
1737 | /// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate | |||
1738 | /// the offet and size that are started/ended in the underlying FrameIndex. | |||
1739 | class LifetimeSDNode : public SDNode { | |||
1740 | friend class SelectionDAG; | |||
1741 | int64_t Size; | |||
1742 | int64_t Offset; // -1 if offset is unknown. | |||
1743 | ||||
1744 | LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, | |||
1745 | SDVTList VTs, int64_t Size, int64_t Offset) | |||
1746 | : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {} | |||
1747 | public: | |||
1748 | int64_t getFrameIndex() const { | |||
1749 | return cast<FrameIndexSDNode>(getOperand(1))->getIndex(); | |||
1750 | } | |||
1751 | ||||
1752 | bool hasOffset() const { return Offset >= 0; } | |||
1753 | int64_t getOffset() const { | |||
1754 | assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast< void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1754, __PRETTY_FUNCTION__)); | |||
1755 | return Offset; | |||
1756 | } | |||
1757 | int64_t getSize() const { | |||
1758 | assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast< void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1758, __PRETTY_FUNCTION__)); | |||
1759 | return Size; | |||
1760 | } | |||
1761 | ||||
1762 | // Methods to support isa and dyn_cast | |||
1763 | static bool classof(const SDNode *N) { | |||
1764 | return N->getOpcode() == ISD::LIFETIME_START || | |||
1765 | N->getOpcode() == ISD::LIFETIME_END; | |||
1766 | } | |||
1767 | }; | |||
1768 | ||||
1769 | /// This SDNode is used for PSEUDO_PROBE values, which are the function guid and | |||
1770 | /// the index of the basic block being probed. A pseudo probe serves as a place | |||
1771 | /// holder and will be removed at the end of compilation. It does not have any | |||
1772 | /// operand because we do not want the instruction selection to deal with any. | |||
1773 | class PseudoProbeSDNode : public SDNode { | |||
1774 | friend class SelectionDAG; | |||
1775 | uint64_t Guid; | |||
1776 | uint64_t Index; | |||
1777 | uint32_t Attributes; | |||
1778 | ||||
1779 | PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl, | |||
1780 | SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr) | |||
1781 | : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index), | |||
1782 | Attributes(Attr) {} | |||
1783 | ||||
1784 | public: | |||
1785 | uint64_t getGuid() const { return Guid; } | |||
1786 | uint64_t getIndex() const { return Index; } | |||
1787 | uint32_t getAttributes() const { return Attributes; } | |||
1788 | ||||
1789 | // Methods to support isa and dyn_cast | |||
1790 | static bool classof(const SDNode *N) { | |||
1791 | return N->getOpcode() == ISD::PSEUDO_PROBE; | |||
1792 | } | |||
1793 | }; | |||
1794 | ||||
1795 | class JumpTableSDNode : public SDNode { | |||
1796 | friend class SelectionDAG; | |||
1797 | ||||
1798 | int JTI; | |||
1799 | unsigned TargetFlags; | |||
1800 | ||||
1801 | JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF) | |||
1802 | : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable, | |||
1803 | 0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) { | |||
1804 | } | |||
1805 | ||||
1806 | public: | |||
1807 | int getIndex() const { return JTI; } | |||
1808 | unsigned getTargetFlags() const { return TargetFlags; } | |||
1809 | ||||
1810 | static bool classof(const SDNode *N) { | |||
1811 | return N->getOpcode() == ISD::JumpTable || | |||
1812 | N->getOpcode() == ISD::TargetJumpTable; | |||
1813 | } | |||
1814 | }; | |||
1815 | ||||
1816 | class ConstantPoolSDNode : public SDNode { | |||
1817 | friend class SelectionDAG; | |||
1818 | ||||
1819 | union { | |||
1820 | const Constant *ConstVal; | |||
1821 | MachineConstantPoolValue *MachineCPVal; | |||
1822 | } Val; | |||
1823 | int Offset; // It's a MachineConstantPoolValue if top bit is set. | |||
1824 | Align Alignment; // Minimum alignment requirement of CP. | |||
1825 | unsigned TargetFlags; | |||
1826 | ||||
1827 | ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o, | |||
1828 | Align Alignment, unsigned TF) | |||
1829 | : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0, | |||
1830 | DebugLoc(), getSDVTList(VT)), | |||
1831 | Offset(o), Alignment(Alignment), TargetFlags(TF) { | |||
1832 | assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast <void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1832, __PRETTY_FUNCTION__)); | |||
1833 | Val.ConstVal = c; | |||
1834 | } | |||
1835 | ||||
1836 | ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o, | |||
1837 | Align Alignment, unsigned TF) | |||
1838 | : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0, | |||
1839 | DebugLoc(), getSDVTList(VT)), | |||
1840 | Offset(o), Alignment(Alignment), TargetFlags(TF) { | |||
1841 | assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast <void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1841, __PRETTY_FUNCTION__)); | |||
1842 | Val.MachineCPVal = v; | |||
1843 | Offset |= 1 << (sizeof(unsigned)*CHAR_BIT8-1); | |||
1844 | } | |||
1845 | ||||
1846 | public: | |||
1847 | bool isMachineConstantPoolEntry() const { | |||
1848 | return Offset < 0; | |||
1849 | } | |||
1850 | ||||
1851 | const Constant *getConstVal() const { | |||
1852 | assert(!isMachineConstantPoolEntry() && "Wrong constantpool type")((!isMachineConstantPoolEntry() && "Wrong constantpool type" ) ? static_cast<void> (0) : __assert_fail ("!isMachineConstantPoolEntry() && \"Wrong constantpool type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1852, __PRETTY_FUNCTION__)); | |||
1853 | return Val.ConstVal; | |||
1854 | } | |||
1855 | ||||
1856 | MachineConstantPoolValue *getMachineCPVal() const { | |||
1857 | assert(isMachineConstantPoolEntry() && "Wrong constantpool type")((isMachineConstantPoolEntry() && "Wrong constantpool type" ) ? static_cast<void> (0) : __assert_fail ("isMachineConstantPoolEntry() && \"Wrong constantpool type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 1857, __PRETTY_FUNCTION__)); | |||
1858 | return Val.MachineCPVal; | |||
1859 | } | |||
1860 | ||||
1861 | int getOffset() const { | |||
1862 | return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT8-1)); | |||
1863 | } | |||
1864 | ||||
1865 | // Return the alignment of this constant pool object, which is either 0 (for | |||
1866 | // default alignment) or the desired value. | |||
1867 | Align getAlign() const { return Alignment; } | |||
1868 | unsigned getTargetFlags() const { return TargetFlags; } | |||
1869 | ||||
1870 | Type *getType() const; | |||
1871 | ||||
1872 | static bool classof(const SDNode *N) { | |||
1873 | return N->getOpcode() == ISD::ConstantPool || | |||
1874 | N->getOpcode() == ISD::TargetConstantPool; | |||
1875 | } | |||
1876 | }; | |||
1877 | ||||
1878 | /// Completely target-dependent object reference. | |||
1879 | class TargetIndexSDNode : public SDNode { | |||
1880 | friend class SelectionDAG; | |||
1881 | ||||
1882 | unsigned TargetFlags; | |||
1883 | int Index; | |||
1884 | int64_t Offset; | |||
1885 | ||||
1886 | public: | |||
1887 | TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF) | |||
1888 | : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)), | |||
1889 | TargetFlags(TF), Index(Idx), Offset(Ofs) {} | |||
1890 | ||||
1891 | unsigned getTargetFlags() const { return TargetFlags; } | |||
1892 | int getIndex() const { return Index; } | |||
1893 | int64_t getOffset() const { return Offset; } | |||
1894 | ||||
1895 | static bool classof(const SDNode *N) { | |||
1896 | return N->getOpcode() == ISD::TargetIndex; | |||
1897 | } | |||
1898 | }; | |||
1899 | ||||
1900 | class BasicBlockSDNode : public SDNode { | |||
1901 | friend class SelectionDAG; | |||
1902 | ||||
1903 | MachineBasicBlock *MBB; | |||
1904 | ||||
1905 | /// Debug info is meaningful and potentially useful here, but we create | |||
1906 | /// blocks out of order when they're jumped to, which makes it a bit | |||
1907 | /// harder. Let's see if we need it first. | |||
1908 | explicit BasicBlockSDNode(MachineBasicBlock *mbb) | |||
1909 | : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb) | |||
1910 | {} | |||
1911 | ||||
1912 | public: | |||
1913 | MachineBasicBlock *getBasicBlock() const { return MBB; } | |||
1914 | ||||
1915 | static bool classof(const SDNode *N) { | |||
1916 | return N->getOpcode() == ISD::BasicBlock; | |||
1917 | } | |||
1918 | }; | |||
1919 | ||||
1920 | /// A "pseudo-class" with methods for operating on BUILD_VECTORs. | |||
1921 | class BuildVectorSDNode : public SDNode { | |||
1922 | public: | |||
1923 | // These are constructed as SDNodes and then cast to BuildVectorSDNodes. | |||
1924 | explicit BuildVectorSDNode() = delete; | |||
1925 | ||||
1926 | /// Check if this is a constant splat, and if so, find the | |||
1927 | /// smallest element size that splats the vector. If MinSplatBits is | |||
1928 | /// nonzero, the element size must be at least that large. Note that the | |||
1929 | /// splat element may be the entire vector (i.e., a one element vector). | |||
1930 | /// Returns the splat element value in SplatValue. Any undefined bits in | |||
1931 | /// that value are zero, and the corresponding bits in the SplatUndef mask | |||
1932 | /// are set. The SplatBitSize value is set to the splat element size in | |||
1933 | /// bits. HasAnyUndefs is set to true if any bits in the vector are | |||
1934 | /// undefined. isBigEndian describes the endianness of the target. | |||
1935 | bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, | |||
1936 | unsigned &SplatBitSize, bool &HasAnyUndefs, | |||
1937 | unsigned MinSplatBits = 0, | |||
1938 | bool isBigEndian = false) const; | |||
1939 | ||||
1940 | /// Returns the demanded splatted value or a null value if this is not a | |||
1941 | /// splat. | |||
1942 | /// | |||
1943 | /// The DemandedElts mask indicates the elements that must be in the splat. | |||
1944 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
1945 | /// the vector width and set the bits where elements are undef. | |||
1946 | SDValue getSplatValue(const APInt &DemandedElts, | |||
1947 | BitVector *UndefElements = nullptr) const; | |||
1948 | ||||
1949 | /// Returns the splatted value or a null value if this is not a splat. | |||
1950 | /// | |||
1951 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
1952 | /// the vector width and set the bits where elements are undef. | |||
1953 | SDValue getSplatValue(BitVector *UndefElements = nullptr) const; | |||
1954 | ||||
1955 | /// Find the shortest repeating sequence of values in the build vector. | |||
1956 | /// | |||
1957 | /// e.g. { u, X, u, X, u, u, X, u } -> { X } | |||
1958 | /// { X, Y, u, Y, u, u, X, u } -> { X, Y } | |||
1959 | /// | |||
1960 | /// Currently this must be a power-of-2 build vector. | |||
1961 | /// The DemandedElts mask indicates the elements that must be present, | |||
1962 | /// undemanded elements in Sequence may be null (SDValue()). If passed a | |||
1963 | /// non-null UndefElements bitvector, it will resize it to match the original | |||
1964 | /// vector width and set the bits where elements are undef. If result is | |||
1965 | /// false, Sequence will be empty. | |||
1966 | bool getRepeatedSequence(const APInt &DemandedElts, | |||
1967 | SmallVectorImpl<SDValue> &Sequence, | |||
1968 | BitVector *UndefElements = nullptr) const; | |||
1969 | ||||
1970 | /// Find the shortest repeating sequence of values in the build vector. | |||
1971 | /// | |||
1972 | /// e.g. { u, X, u, X, u, u, X, u } -> { X } | |||
1973 | /// { X, Y, u, Y, u, u, X, u } -> { X, Y } | |||
1974 | /// | |||
1975 | /// Currently this must be a power-of-2 build vector. | |||
1976 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
1977 | /// the original vector width and set the bits where elements are undef. | |||
1978 | /// If result is false, Sequence will be empty. | |||
1979 | bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, | |||
1980 | BitVector *UndefElements = nullptr) const; | |||
1981 | ||||
1982 | /// Returns the demanded splatted constant or null if this is not a constant | |||
1983 | /// splat. | |||
1984 | /// | |||
1985 | /// The DemandedElts mask indicates the elements that must be in the splat. | |||
1986 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
1987 | /// the vector width and set the bits where elements are undef. | |||
1988 | ConstantSDNode * | |||
1989 | getConstantSplatNode(const APInt &DemandedElts, | |||
1990 | BitVector *UndefElements = nullptr) const; | |||
1991 | ||||
1992 | /// Returns the splatted constant or null if this is not a constant | |||
1993 | /// splat. | |||
1994 | /// | |||
1995 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
1996 | /// the vector width and set the bits where elements are undef. | |||
1997 | ConstantSDNode * | |||
1998 | getConstantSplatNode(BitVector *UndefElements = nullptr) const; | |||
1999 | ||||
2000 | /// Returns the demanded splatted constant FP or null if this is not a | |||
2001 | /// constant FP splat. | |||
2002 | /// | |||
2003 | /// The DemandedElts mask indicates the elements that must be in the splat. | |||
2004 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
2005 | /// the vector width and set the bits where elements are undef. | |||
2006 | ConstantFPSDNode * | |||
2007 | getConstantFPSplatNode(const APInt &DemandedElts, | |||
2008 | BitVector *UndefElements = nullptr) const; | |||
2009 | ||||
2010 | /// Returns the splatted constant FP or null if this is not a constant | |||
2011 | /// FP splat. | |||
2012 | /// | |||
2013 | /// If passed a non-null UndefElements bitvector, it will resize it to match | |||
2014 | /// the vector width and set the bits where elements are undef. | |||
2015 | ConstantFPSDNode * | |||
2016 | getConstantFPSplatNode(BitVector *UndefElements = nullptr) const; | |||
2017 | ||||
2018 | /// If this is a constant FP splat and the splatted constant FP is an | |||
2019 | /// exact power or 2, return the log base 2 integer value. Otherwise, | |||
2020 | /// return -1. | |||
2021 | /// | |||
2022 | /// The BitWidth specifies the necessary bit precision. | |||
2023 | int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, | |||
2024 | uint32_t BitWidth) const; | |||
2025 | ||||
2026 | bool isConstant() const; | |||
2027 | ||||
2028 | static bool classof(const SDNode *N) { | |||
2029 | return N->getOpcode() == ISD::BUILD_VECTOR; | |||
2030 | } | |||
2031 | }; | |||
2032 | ||||
2033 | /// An SDNode that holds an arbitrary LLVM IR Value. This is | |||
2034 | /// used when the SelectionDAG needs to make a simple reference to something | |||
2035 | /// in the LLVM IR representation. | |||
2036 | /// | |||
2037 | class SrcValueSDNode : public SDNode { | |||
2038 | friend class SelectionDAG; | |||
2039 | ||||
2040 | const Value *V; | |||
2041 | ||||
2042 | /// Create a SrcValue for a general value. | |||
2043 | explicit SrcValueSDNode(const Value *v) | |||
2044 | : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {} | |||
2045 | ||||
2046 | public: | |||
2047 | /// Return the contained Value. | |||
2048 | const Value *getValue() const { return V; } | |||
2049 | ||||
2050 | static bool classof(const SDNode *N) { | |||
2051 | return N->getOpcode() == ISD::SRCVALUE; | |||
2052 | } | |||
2053 | }; | |||
2054 | ||||
2055 | class MDNodeSDNode : public SDNode { | |||
2056 | friend class SelectionDAG; | |||
2057 | ||||
2058 | const MDNode *MD; | |||
2059 | ||||
2060 | explicit MDNodeSDNode(const MDNode *md) | |||
2061 | : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md) | |||
2062 | {} | |||
2063 | ||||
2064 | public: | |||
2065 | const MDNode *getMD() const { return MD; } | |||
2066 | ||||
2067 | static bool classof(const SDNode *N) { | |||
2068 | return N->getOpcode() == ISD::MDNODE_SDNODE; | |||
2069 | } | |||
2070 | }; | |||
2071 | ||||
2072 | class RegisterSDNode : public SDNode { | |||
2073 | friend class SelectionDAG; | |||
2074 | ||||
2075 | Register Reg; | |||
2076 | ||||
2077 | RegisterSDNode(Register reg, EVT VT) | |||
2078 | : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {} | |||
2079 | ||||
2080 | public: | |||
2081 | Register getReg() const { return Reg; } | |||
2082 | ||||
2083 | static bool classof(const SDNode *N) { | |||
2084 | return N->getOpcode() == ISD::Register; | |||
2085 | } | |||
2086 | }; | |||
2087 | ||||
2088 | class RegisterMaskSDNode : public SDNode { | |||
2089 | friend class SelectionDAG; | |||
2090 | ||||
2091 | // The memory for RegMask is not owned by the node. | |||
2092 | const uint32_t *RegMask; | |||
2093 | ||||
2094 | RegisterMaskSDNode(const uint32_t *mask) | |||
2095 | : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)), | |||
2096 | RegMask(mask) {} | |||
2097 | ||||
2098 | public: | |||
2099 | const uint32_t *getRegMask() const { return RegMask; } | |||
2100 | ||||
2101 | static bool classof(const SDNode *N) { | |||
2102 | return N->getOpcode() == ISD::RegisterMask; | |||
2103 | } | |||
2104 | }; | |||
2105 | ||||
2106 | class BlockAddressSDNode : public SDNode { | |||
2107 | friend class SelectionDAG; | |||
2108 | ||||
2109 | const BlockAddress *BA; | |||
2110 | int64_t Offset; | |||
2111 | unsigned TargetFlags; | |||
2112 | ||||
2113 | BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba, | |||
2114 | int64_t o, unsigned Flags) | |||
2115 | : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)), | |||
2116 | BA(ba), Offset(o), TargetFlags(Flags) {} | |||
2117 | ||||
2118 | public: | |||
2119 | const BlockAddress *getBlockAddress() const { return BA; } | |||
2120 | int64_t getOffset() const { return Offset; } | |||
2121 | unsigned getTargetFlags() const { return TargetFlags; } | |||
2122 | ||||
2123 | static bool classof(const SDNode *N) { | |||
2124 | return N->getOpcode() == ISD::BlockAddress || | |||
2125 | N->getOpcode() == ISD::TargetBlockAddress; | |||
2126 | } | |||
2127 | }; | |||
2128 | ||||
2129 | class LabelSDNode : public SDNode { | |||
2130 | friend class SelectionDAG; | |||
2131 | ||||
2132 | MCSymbol *Label; | |||
2133 | ||||
2134 | LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L) | |||
2135 | : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) { | |||
2136 | assert(LabelSDNode::classof(this) && "not a label opcode")((LabelSDNode::classof(this) && "not a label opcode") ? static_cast<void> (0) : __assert_fail ("LabelSDNode::classof(this) && \"not a label opcode\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2136, __PRETTY_FUNCTION__)); | |||
2137 | } | |||
2138 | ||||
2139 | public: | |||
2140 | MCSymbol *getLabel() const { return Label; } | |||
2141 | ||||
2142 | static bool classof(const SDNode *N) { | |||
2143 | return N->getOpcode() == ISD::EH_LABEL || | |||
2144 | N->getOpcode() == ISD::ANNOTATION_LABEL; | |||
2145 | } | |||
2146 | }; | |||
2147 | ||||
2148 | class ExternalSymbolSDNode : public SDNode { | |||
2149 | friend class SelectionDAG; | |||
2150 | ||||
2151 | const char *Symbol; | |||
2152 | unsigned TargetFlags; | |||
2153 | ||||
2154 | ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT) | |||
2155 | : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0, | |||
2156 | DebugLoc(), getSDVTList(VT)), | |||
2157 | Symbol(Sym), TargetFlags(TF) {} | |||
2158 | ||||
2159 | public: | |||
2160 | const char *getSymbol() const { return Symbol; } | |||
2161 | unsigned getTargetFlags() const { return TargetFlags; } | |||
2162 | ||||
2163 | static bool classof(const SDNode *N) { | |||
2164 | return N->getOpcode() == ISD::ExternalSymbol || | |||
2165 | N->getOpcode() == ISD::TargetExternalSymbol; | |||
2166 | } | |||
2167 | }; | |||
2168 | ||||
2169 | class MCSymbolSDNode : public SDNode { | |||
2170 | friend class SelectionDAG; | |||
2171 | ||||
2172 | MCSymbol *Symbol; | |||
2173 | ||||
2174 | MCSymbolSDNode(MCSymbol *Symbol, EVT VT) | |||
2175 | : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {} | |||
2176 | ||||
2177 | public: | |||
2178 | MCSymbol *getMCSymbol() const { return Symbol; } | |||
2179 | ||||
2180 | static bool classof(const SDNode *N) { | |||
2181 | return N->getOpcode() == ISD::MCSymbol; | |||
2182 | } | |||
2183 | }; | |||
2184 | ||||
2185 | class CondCodeSDNode : public SDNode { | |||
2186 | friend class SelectionDAG; | |||
2187 | ||||
2188 | ISD::CondCode Condition; | |||
2189 | ||||
2190 | explicit CondCodeSDNode(ISD::CondCode Cond) | |||
2191 | : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)), | |||
2192 | Condition(Cond) {} | |||
2193 | ||||
2194 | public: | |||
2195 | ISD::CondCode get() const { return Condition; } | |||
2196 | ||||
2197 | static bool classof(const SDNode *N) { | |||
2198 | return N->getOpcode() == ISD::CONDCODE; | |||
2199 | } | |||
2200 | }; | |||
2201 | ||||
2202 | /// This class is used to represent EVT's, which are used | |||
2203 | /// to parameterize some operations. | |||
2204 | class VTSDNode : public SDNode { | |||
2205 | friend class SelectionDAG; | |||
2206 | ||||
2207 | EVT ValueType; | |||
2208 | ||||
2209 | explicit VTSDNode(EVT VT) | |||
2210 | : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)), | |||
2211 | ValueType(VT) {} | |||
2212 | ||||
2213 | public: | |||
2214 | EVT getVT() const { return ValueType; } | |||
2215 | ||||
2216 | static bool classof(const SDNode *N) { | |||
2217 | return N->getOpcode() == ISD::VALUETYPE; | |||
2218 | } | |||
2219 | }; | |||
2220 | ||||
2221 | /// Base class for LoadSDNode and StoreSDNode | |||
2222 | class LSBaseSDNode : public MemSDNode { | |||
2223 | public: | |||
2224 | LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl, | |||
2225 | SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT, | |||
2226 | MachineMemOperand *MMO) | |||
2227 | : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) { | |||
2228 | LSBaseSDNodeBits.AddressingMode = AM; | |||
2229 | assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast <void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2229, __PRETTY_FUNCTION__)); | |||
2230 | } | |||
2231 | ||||
2232 | const SDValue &getOffset() const { | |||
2233 | return getOperand(getOpcode() == ISD::LOAD ? 2 : 3); | |||
2234 | } | |||
2235 | ||||
2236 | /// Return the addressing mode for this load or store: | |||
2237 | /// unindexed, pre-inc, pre-dec, post-inc, or post-dec. | |||
2238 | ISD::MemIndexedMode getAddressingMode() const { | |||
2239 | return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode); | |||
2240 | } | |||
2241 | ||||
2242 | /// Return true if this is a pre/post inc/dec load/store. | |||
2243 | bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; } | |||
2244 | ||||
2245 | /// Return true if this is NOT a pre/post inc/dec load/store. | |||
2246 | bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; } | |||
2247 | ||||
2248 | static bool classof(const SDNode *N) { | |||
2249 | return N->getOpcode() == ISD::LOAD || | |||
2250 | N->getOpcode() == ISD::STORE; | |||
2251 | } | |||
2252 | }; | |||
2253 | ||||
2254 | /// This class is used to represent ISD::LOAD nodes. | |||
2255 | class LoadSDNode : public LSBaseSDNode { | |||
2256 | friend class SelectionDAG; | |||
2257 | ||||
2258 | LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2259 | ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT, | |||
2260 | MachineMemOperand *MMO) | |||
2261 | : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) { | |||
2262 | LoadSDNodeBits.ExtTy = ETy; | |||
2263 | assert(readMem() && "Load MachineMemOperand is not a load!")((readMem() && "Load MachineMemOperand is not a load!" ) ? static_cast<void> (0) : __assert_fail ("readMem() && \"Load MachineMemOperand is not a load!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2263, __PRETTY_FUNCTION__)); | |||
2264 | assert(!writeMem() && "Load MachineMemOperand is a store!")((!writeMem() && "Load MachineMemOperand is a store!" ) ? static_cast<void> (0) : __assert_fail ("!writeMem() && \"Load MachineMemOperand is a store!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2264, __PRETTY_FUNCTION__)); | |||
2265 | } | |||
2266 | ||||
2267 | public: | |||
2268 | /// Return whether this is a plain node, | |||
2269 | /// or one of the varieties of value-extending loads. | |||
2270 | ISD::LoadExtType getExtensionType() const { | |||
2271 | return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy); | |||
2272 | } | |||
2273 | ||||
2274 | const SDValue &getBasePtr() const { return getOperand(1); } | |||
2275 | const SDValue &getOffset() const { return getOperand(2); } | |||
2276 | ||||
2277 | static bool classof(const SDNode *N) { | |||
2278 | return N->getOpcode() == ISD::LOAD; | |||
2279 | } | |||
2280 | }; | |||
2281 | ||||
2282 | /// This class is used to represent ISD::STORE nodes. | |||
2283 | class StoreSDNode : public LSBaseSDNode { | |||
2284 | friend class SelectionDAG; | |||
2285 | ||||
2286 | StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2287 | ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT, | |||
2288 | MachineMemOperand *MMO) | |||
2289 | : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) { | |||
2290 | StoreSDNodeBits.IsTruncating = isTrunc; | |||
2291 | assert(!readMem() && "Store MachineMemOperand is a load!")((!readMem() && "Store MachineMemOperand is a load!") ? static_cast<void> (0) : __assert_fail ("!readMem() && \"Store MachineMemOperand is a load!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2291, __PRETTY_FUNCTION__)); | |||
2292 | assert(writeMem() && "Store MachineMemOperand is not a store!")((writeMem() && "Store MachineMemOperand is not a store!" ) ? static_cast<void> (0) : __assert_fail ("writeMem() && \"Store MachineMemOperand is not a store!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2292, __PRETTY_FUNCTION__)); | |||
2293 | } | |||
2294 | ||||
2295 | public: | |||
2296 | /// Return true if the op does a truncation before store. | |||
2297 | /// For integers this is the same as doing a TRUNCATE and storing the result. | |||
2298 | /// For floats, it is the same as doing an FP_ROUND and storing the result. | |||
2299 | bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; } | |||
2300 | void setTruncatingStore(bool Truncating) { | |||
2301 | StoreSDNodeBits.IsTruncating = Truncating; | |||
2302 | } | |||
2303 | ||||
2304 | const SDValue &getValue() const { return getOperand(1); } | |||
2305 | const SDValue &getBasePtr() const { return getOperand(2); } | |||
2306 | const SDValue &getOffset() const { return getOperand(3); } | |||
2307 | ||||
2308 | static bool classof(const SDNode *N) { | |||
2309 | return N->getOpcode() == ISD::STORE; | |||
2310 | } | |||
2311 | }; | |||
2312 | ||||
2313 | /// This base class is used to represent MLOAD and MSTORE nodes | |||
2314 | class MaskedLoadStoreSDNode : public MemSDNode { | |||
2315 | public: | |||
2316 | friend class SelectionDAG; | |||
2317 | ||||
2318 | MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order, | |||
2319 | const DebugLoc &dl, SDVTList VTs, | |||
2320 | ISD::MemIndexedMode AM, EVT MemVT, | |||
2321 | MachineMemOperand *MMO) | |||
2322 | : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) { | |||
2323 | LSBaseSDNodeBits.AddressingMode = AM; | |||
2324 | assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast <void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2324, __PRETTY_FUNCTION__)); | |||
2325 | } | |||
2326 | ||||
2327 | // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru) | |||
2328 | // MaskedStoreSDNode (Chain, data, ptr, offset, mask) | |||
2329 | // Mask is a vector of i1 elements | |||
2330 | const SDValue &getOffset() const { | |||
2331 | return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3); | |||
2332 | } | |||
2333 | const SDValue &getMask() const { | |||
2334 | return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4); | |||
2335 | } | |||
2336 | ||||
2337 | /// Return the addressing mode for this load or store: | |||
2338 | /// unindexed, pre-inc, pre-dec, post-inc, or post-dec. | |||
2339 | ISD::MemIndexedMode getAddressingMode() const { | |||
2340 | return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode); | |||
2341 | } | |||
2342 | ||||
2343 | /// Return true if this is a pre/post inc/dec load/store. | |||
2344 | bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; } | |||
2345 | ||||
2346 | /// Return true if this is NOT a pre/post inc/dec load/store. | |||
2347 | bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; } | |||
2348 | ||||
2349 | static bool classof(const SDNode *N) { | |||
2350 | return N->getOpcode() == ISD::MLOAD || | |||
2351 | N->getOpcode() == ISD::MSTORE; | |||
2352 | } | |||
2353 | }; | |||
2354 | ||||
2355 | /// This class is used to represent an MLOAD node | |||
2356 | class MaskedLoadSDNode : public MaskedLoadStoreSDNode { | |||
2357 | public: | |||
2358 | friend class SelectionDAG; | |||
2359 | ||||
2360 | MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2361 | ISD::MemIndexedMode AM, ISD::LoadExtType ETy, | |||
2362 | bool IsExpanding, EVT MemVT, MachineMemOperand *MMO) | |||
2363 | : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) { | |||
2364 | LoadSDNodeBits.ExtTy = ETy; | |||
2365 | LoadSDNodeBits.IsExpanding = IsExpanding; | |||
2366 | } | |||
2367 | ||||
2368 | ISD::LoadExtType getExtensionType() const { | |||
2369 | return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy); | |||
2370 | } | |||
2371 | ||||
2372 | const SDValue &getBasePtr() const { return getOperand(1); } | |||
2373 | const SDValue &getOffset() const { return getOperand(2); } | |||
2374 | const SDValue &getMask() const { return getOperand(3); } | |||
2375 | const SDValue &getPassThru() const { return getOperand(4); } | |||
2376 | ||||
2377 | static bool classof(const SDNode *N) { | |||
2378 | return N->getOpcode() == ISD::MLOAD; | |||
2379 | } | |||
2380 | ||||
2381 | bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; } | |||
2382 | }; | |||
2383 | ||||
2384 | /// This class is used to represent an MSTORE node | |||
2385 | class MaskedStoreSDNode : public MaskedLoadStoreSDNode { | |||
2386 | public: | |||
2387 | friend class SelectionDAG; | |||
2388 | ||||
2389 | MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2390 | ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing, | |||
2391 | EVT MemVT, MachineMemOperand *MMO) | |||
2392 | : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) { | |||
2393 | StoreSDNodeBits.IsTruncating = isTrunc; | |||
2394 | StoreSDNodeBits.IsCompressing = isCompressing; | |||
2395 | } | |||
2396 | ||||
2397 | /// Return true if the op does a truncation before store. | |||
2398 | /// For integers this is the same as doing a TRUNCATE and storing the result. | |||
2399 | /// For floats, it is the same as doing an FP_ROUND and storing the result. | |||
2400 | bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; } | |||
2401 | ||||
2402 | /// Returns true if the op does a compression to the vector before storing. | |||
2403 | /// The node contiguously stores the active elements (integers or floats) | |||
2404 | /// in src (those with their respective bit set in writemask k) to unaligned | |||
2405 | /// memory at base_addr. | |||
2406 | bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; } | |||
2407 | ||||
2408 | const SDValue &getValue() const { return getOperand(1); } | |||
2409 | const SDValue &getBasePtr() const { return getOperand(2); } | |||
2410 | const SDValue &getOffset() const { return getOperand(3); } | |||
2411 | const SDValue &getMask() const { return getOperand(4); } | |||
2412 | ||||
2413 | static bool classof(const SDNode *N) { | |||
2414 | return N->getOpcode() == ISD::MSTORE; | |||
2415 | } | |||
2416 | }; | |||
2417 | ||||
2418 | /// This is a base class used to represent | |||
2419 | /// MGATHER and MSCATTER nodes | |||
2420 | /// | |||
2421 | class MaskedGatherScatterSDNode : public MemSDNode { | |||
2422 | public: | |||
2423 | friend class SelectionDAG; | |||
2424 | ||||
2425 | MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order, | |||
2426 | const DebugLoc &dl, SDVTList VTs, EVT MemVT, | |||
2427 | MachineMemOperand *MMO, ISD::MemIndexType IndexType) | |||
2428 | : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) { | |||
2429 | LSBaseSDNodeBits.AddressingMode = IndexType; | |||
2430 | assert(getIndexType() == IndexType && "Value truncated")((getIndexType() == IndexType && "Value truncated") ? static_cast<void> (0) : __assert_fail ("getIndexType() == IndexType && \"Value truncated\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2430, __PRETTY_FUNCTION__)); | |||
2431 | } | |||
2432 | ||||
2433 | /// How is Index applied to BasePtr when computing addresses. | |||
2434 | ISD::MemIndexType getIndexType() const { | |||
2435 | return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode); | |||
2436 | } | |||
2437 | void setIndexType(ISD::MemIndexType IndexType) { | |||
2438 | LSBaseSDNodeBits.AddressingMode = IndexType; | |||
2439 | } | |||
2440 | bool isIndexScaled() const { | |||
2441 | return (getIndexType() == ISD::SIGNED_SCALED) || | |||
2442 | (getIndexType() == ISD::UNSIGNED_SCALED); | |||
2443 | } | |||
2444 | bool isIndexSigned() const { | |||
2445 | return (getIndexType() == ISD::SIGNED_SCALED) || | |||
2446 | (getIndexType() == ISD::SIGNED_UNSCALED); | |||
2447 | } | |||
2448 | ||||
2449 | // In the both nodes address is Op1, mask is Op2: | |||
2450 | // MaskedGatherSDNode (Chain, passthru, mask, base, index, scale) | |||
2451 | // MaskedScatterSDNode (Chain, value, mask, base, index, scale) | |||
2452 | // Mask is a vector of i1 elements | |||
2453 | const SDValue &getBasePtr() const { return getOperand(3); } | |||
2454 | const SDValue &getIndex() const { return getOperand(4); } | |||
2455 | const SDValue &getMask() const { return getOperand(2); } | |||
2456 | const SDValue &getScale() const { return getOperand(5); } | |||
2457 | ||||
2458 | static bool classof(const SDNode *N) { | |||
2459 | return N->getOpcode() == ISD::MGATHER || | |||
2460 | N->getOpcode() == ISD::MSCATTER; | |||
2461 | } | |||
2462 | }; | |||
2463 | ||||
2464 | /// This class is used to represent an MGATHER node | |||
2465 | /// | |||
2466 | class MaskedGatherSDNode : public MaskedGatherScatterSDNode { | |||
2467 | public: | |||
2468 | friend class SelectionDAG; | |||
2469 | ||||
2470 | MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2471 | EVT MemVT, MachineMemOperand *MMO, | |||
2472 | ISD::MemIndexType IndexType, ISD::LoadExtType ETy) | |||
2473 | : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO, | |||
2474 | IndexType) { | |||
2475 | LoadSDNodeBits.ExtTy = ETy; | |||
2476 | } | |||
2477 | ||||
2478 | const SDValue &getPassThru() const { return getOperand(1); } | |||
2479 | ||||
2480 | ISD::LoadExtType getExtensionType() const { | |||
2481 | return ISD::LoadExtType(LoadSDNodeBits.ExtTy); | |||
2482 | } | |||
2483 | ||||
2484 | static bool classof(const SDNode *N) { | |||
2485 | return N->getOpcode() == ISD::MGATHER; | |||
2486 | } | |||
2487 | }; | |||
2488 | ||||
2489 | /// This class is used to represent an MSCATTER node | |||
2490 | /// | |||
2491 | class MaskedScatterSDNode : public MaskedGatherScatterSDNode { | |||
2492 | public: | |||
2493 | friend class SelectionDAG; | |||
2494 | ||||
2495 | MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, | |||
2496 | EVT MemVT, MachineMemOperand *MMO, | |||
2497 | ISD::MemIndexType IndexType, bool IsTrunc) | |||
2498 | : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO, | |||
2499 | IndexType) { | |||
2500 | StoreSDNodeBits.IsTruncating = IsTrunc; | |||
2501 | } | |||
2502 | ||||
2503 | /// Return true if the op does a truncation before store. | |||
2504 | /// For integers this is the same as doing a TRUNCATE and storing the result. | |||
2505 | /// For floats, it is the same as doing an FP_ROUND and storing the result. | |||
2506 | bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; } | |||
2507 | ||||
2508 | const SDValue &getValue() const { return getOperand(1); } | |||
2509 | ||||
2510 | static bool classof(const SDNode *N) { | |||
2511 | return N->getOpcode() == ISD::MSCATTER; | |||
2512 | } | |||
2513 | }; | |||
2514 | ||||
2515 | /// An SDNode that represents everything that will be needed | |||
2516 | /// to construct a MachineInstr. These nodes are created during the | |||
2517 | /// instruction selection proper phase. | |||
2518 | /// | |||
2519 | /// Note that the only supported way to set the `memoperands` is by calling the | |||
2520 | /// `SelectionDAG::setNodeMemRefs` function as the memory management happens | |||
2521 | /// inside the DAG rather than in the node. | |||
2522 | class MachineSDNode : public SDNode { | |||
2523 | private: | |||
2524 | friend class SelectionDAG; | |||
2525 | ||||
2526 | MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs) | |||
2527 | : SDNode(Opc, Order, DL, VTs) {} | |||
2528 | ||||
2529 | // We use a pointer union between a single `MachineMemOperand` pointer and | |||
2530 | // a pointer to an array of `MachineMemOperand` pointers. This is null when | |||
2531 | // the number of these is zero, the single pointer variant used when the | |||
2532 | // number is one, and the array is used for larger numbers. | |||
2533 | // | |||
2534 | // The array is allocated via the `SelectionDAG`'s allocator and so will | |||
2535 | // always live until the DAG is cleaned up and doesn't require ownership here. | |||
2536 | // | |||
2537 | // We can't use something simpler like `TinyPtrVector` here because `SDNode` | |||
2538 | // subclasses aren't managed in a conforming C++ manner. See the comments on | |||
2539 | // `SelectionDAG::MorphNodeTo` which details what all goes on, but the | |||
2540 | // constraint here is that these don't manage memory with their constructor or | |||
2541 | // destructor and can be initialized to a good state even if they start off | |||
2542 | // uninitialized. | |||
2543 | PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {}; | |||
2544 | ||||
2545 | // Note that this could be folded into the above `MemRefs` member if doing so | |||
2546 | // is advantageous at some point. We don't need to store this in most cases. | |||
2547 | // However, at the moment this doesn't appear to make the allocation any | |||
2548 | // smaller and makes the code somewhat simpler to read. | |||
2549 | int NumMemRefs = 0; | |||
2550 | ||||
2551 | public: | |||
2552 | using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator; | |||
2553 | ||||
2554 | ArrayRef<MachineMemOperand *> memoperands() const { | |||
2555 | // Special case the common cases. | |||
2556 | if (NumMemRefs == 0) | |||
2557 | return {}; | |||
2558 | if (NumMemRefs == 1) | |||
2559 | return makeArrayRef(MemRefs.getAddrOfPtr1(), 1); | |||
2560 | ||||
2561 | // Otherwise we have an actual array. | |||
2562 | return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs); | |||
2563 | } | |||
2564 | mmo_iterator memoperands_begin() const { return memoperands().begin(); } | |||
2565 | mmo_iterator memoperands_end() const { return memoperands().end(); } | |||
2566 | bool memoperands_empty() const { return memoperands().empty(); } | |||
2567 | ||||
2568 | /// Clear out the memory reference descriptor list. | |||
2569 | void clearMemRefs() { | |||
2570 | MemRefs = nullptr; | |||
2571 | NumMemRefs = 0; | |||
2572 | } | |||
2573 | ||||
2574 | static bool classof(const SDNode *N) { | |||
2575 | return N->isMachineOpcode(); | |||
2576 | } | |||
2577 | }; | |||
2578 | ||||
2579 | /// An SDNode that records if a register contains a value that is guaranteed to | |||
2580 | /// be aligned accordingly. | |||
2581 | class AssertAlignSDNode : public SDNode { | |||
2582 | Align Alignment; | |||
2583 | ||||
2584 | public: | |||
2585 | AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A) | |||
2586 | : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {} | |||
2587 | ||||
2588 | Align getAlign() const { return Alignment; } | |||
2589 | ||||
2590 | static bool classof(const SDNode *N) { | |||
2591 | return N->getOpcode() == ISD::AssertAlign; | |||
2592 | } | |||
2593 | }; | |||
2594 | ||||
2595 | class SDNodeIterator { | |||
2596 | const SDNode *Node; | |||
2597 | unsigned Operand; | |||
2598 | ||||
2599 | SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {} | |||
2600 | ||||
2601 | public: | |||
2602 | using iterator_category = std::forward_iterator_tag; | |||
2603 | using value_type = SDNode; | |||
2604 | using difference_type = std::ptrdiff_t; | |||
2605 | using pointer = value_type *; | |||
2606 | using reference = value_type &; | |||
2607 | ||||
2608 | bool operator==(const SDNodeIterator& x) const { | |||
2609 | return Operand == x.Operand; | |||
2610 | } | |||
2611 | bool operator!=(const SDNodeIterator& x) const { return !operator==(x); } | |||
2612 | ||||
2613 | pointer operator*() const { | |||
2614 | return Node->getOperand(Operand).getNode(); | |||
2615 | } | |||
2616 | pointer operator->() const { return operator*(); } | |||
2617 | ||||
2618 | SDNodeIterator& operator++() { // Preincrement | |||
2619 | ++Operand; | |||
2620 | return *this; | |||
2621 | } | |||
2622 | SDNodeIterator operator++(int) { // Postincrement | |||
2623 | SDNodeIterator tmp = *this; ++*this; return tmp; | |||
2624 | } | |||
2625 | size_t operator-(SDNodeIterator Other) const { | |||
2626 | assert(Node == Other.Node &&((Node == Other.Node && "Cannot compare iterators of two different nodes!" ) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2627, __PRETTY_FUNCTION__)) | |||
2627 | "Cannot compare iterators of two different nodes!")((Node == Other.Node && "Cannot compare iterators of two different nodes!" ) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/CodeGen/SelectionDAGNodes.h" , 2627, __PRETTY_FUNCTION__)); | |||
2628 | return Operand - Other.Operand; | |||
2629 | } | |||
2630 | ||||
2631 | static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); } | |||
2632 | static SDNodeIterator end (const SDNode *N) { | |||
2633 | return SDNodeIterator(N, N->getNumOperands()); | |||
2634 | } | |||
2635 | ||||
2636 | unsigned getOperand() const { return Operand; } | |||
2637 | const SDNode *getNode() const { return Node; } | |||
2638 | }; | |||
2639 | ||||
2640 | template <> struct GraphTraits<SDNode*> { | |||
2641 | using NodeRef = SDNode *; | |||
2642 | using ChildIteratorType = SDNodeIterator; | |||
2643 | ||||
2644 | static NodeRef getEntryNode(SDNode *N) { return N; } | |||
2645 | ||||
2646 | static ChildIteratorType child_begin(NodeRef N) { | |||
2647 | return SDNodeIterator::begin(N); | |||
2648 | } | |||
2649 | ||||
2650 | static ChildIteratorType child_end(NodeRef N) { | |||
2651 | return SDNodeIterator::end(N); | |||
2652 | } | |||
2653 | }; | |||
2654 | ||||
2655 | /// A representation of the largest SDNode, for use in sizeof(). | |||
2656 | /// | |||
2657 | /// This needs to be a union because the largest node differs on 32 bit systems | |||
2658 | /// with 4 and 8 byte pointer alignment, respectively. | |||
2659 | using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode, | |||
2660 | BlockAddressSDNode, | |||
2661 | GlobalAddressSDNode, | |||
2662 | PseudoProbeSDNode>; | |||
2663 | ||||
2664 | /// The SDNode class with the greatest alignment requirement. | |||
2665 | using MostAlignedSDNode = GlobalAddressSDNode; | |||
2666 | ||||
2667 | namespace ISD { | |||
2668 | ||||
2669 | /// Returns true if the specified node is a non-extending and unindexed load. | |||
2670 | inline bool isNormalLoad(const SDNode *N) { | |||
2671 | const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N); | |||
2672 | return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD && | |||
2673 | Ld->getAddressingMode() == ISD::UNINDEXED; | |||
2674 | } | |||
2675 | ||||
2676 | /// Returns true if the specified node is a non-extending load. | |||
2677 | inline bool isNON_EXTLoad(const SDNode *N) { | |||
2678 | return isa<LoadSDNode>(N) && | |||
2679 | cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD; | |||
2680 | } | |||
2681 | ||||
2682 | /// Returns true if the specified node is a EXTLOAD. | |||
2683 | inline bool isEXTLoad(const SDNode *N) { | |||
2684 | return isa<LoadSDNode>(N) && | |||
2685 | cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD; | |||
2686 | } | |||
2687 | ||||
2688 | /// Returns true if the specified node is a SEXTLOAD. | |||
2689 | inline bool isSEXTLoad(const SDNode *N) { | |||
2690 | return isa<LoadSDNode>(N) && | |||
2691 | cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD; | |||
2692 | } | |||
2693 | ||||
2694 | /// Returns true if the specified node is a ZEXTLOAD. | |||
2695 | inline bool isZEXTLoad(const SDNode *N) { | |||
2696 | return isa<LoadSDNode>(N) && | |||
2697 | cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD; | |||
2698 | } | |||
2699 | ||||
2700 | /// Returns true if the specified node is an unindexed load. | |||
2701 | inline bool isUNINDEXEDLoad(const SDNode *N) { | |||
2702 | return isa<LoadSDNode>(N) && | |||
2703 | cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED; | |||
2704 | } | |||
2705 | ||||
2706 | /// Returns true if the specified node is a non-truncating | |||
2707 | /// and unindexed store. | |||
2708 | inline bool isNormalStore(const SDNode *N) { | |||
2709 | const StoreSDNode *St = dyn_cast<StoreSDNode>(N); | |||
2710 | return St && !St->isTruncatingStore() && | |||
2711 | St->getAddressingMode() == ISD::UNINDEXED; | |||
2712 | } | |||
2713 | ||||
2714 | /// Returns true if the specified node is a non-truncating store. | |||
2715 | inline bool isNON_TRUNCStore(const SDNode *N) { | |||
2716 | return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore(); | |||
2717 | } | |||
2718 | ||||
2719 | /// Returns true if the specified node is a truncating store. | |||
2720 | inline bool isTRUNCStore(const SDNode *N) { | |||
2721 | return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore(); | |||
2722 | } | |||
2723 | ||||
2724 | /// Returns true if the specified node is an unindexed store. | |||
2725 | inline bool isUNINDEXEDStore(const SDNode *N) { | |||
2726 | return isa<StoreSDNode>(N) && | |||
2727 | cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED; | |||
2728 | } | |||
2729 | ||||
2730 | /// Attempt to match a unary predicate against a scalar/splat constant or | |||
2731 | /// every element of a constant BUILD_VECTOR. | |||
2732 | /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match. | |||
2733 | bool matchUnaryPredicate(SDValue Op, | |||
2734 | std::function<bool(ConstantSDNode *)> Match, | |||
2735 | bool AllowUndefs = false); | |||
2736 | ||||
2737 | /// Attempt to match a binary predicate against a pair of scalar/splat | |||
2738 | /// constants or every element of a pair of constant BUILD_VECTORs. | |||
2739 | /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match. | |||
2740 | /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match. | |||
2741 | bool matchBinaryPredicate( | |||
2742 | SDValue LHS, SDValue RHS, | |||
2743 | std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, | |||
2744 | bool AllowUndefs = false, bool AllowTypeMismatch = false); | |||
2745 | ||||
2746 | /// Returns true if the specified value is the overflow result from one | |||
2747 | /// of the overflow intrinsic nodes. | |||
2748 | inline bool isOverflowIntrOpRes(SDValue Op) { | |||
2749 | unsigned Opc = Op.getOpcode(); | |||
2750 | return (Op.getResNo() == 1 && | |||
2751 | (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || | |||
2752 | Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); | |||
2753 | } | |||
2754 | ||||
2755 | } // end namespace ISD | |||
2756 | ||||
2757 | } // end namespace llvm | |||
2758 | ||||
2759 | #endif // LLVM_CODEGEN_SELECTIONDAGNODES_H |