LLVM 24.0.0git
LoadStoreVectorizer.cpp
Go to the documentation of this file.
1//===- LoadStoreVectorizer.cpp - GPU Load & Store Vectorizer --------------===//
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 merges loads/stores to/from sequential memory addresses into vector
10// loads/stores. Although there's nothing GPU-specific in here, this pass is
11// motivated by the microarchitectural quirks of nVidia and AMD GPUs.
12//
13// (For simplicity below we talk about loads only, but everything also applies
14// to stores.)
15//
16// This pass is intended to be run late in the pipeline, after other
17// vectorization opportunities have been exploited. So the assumption here is
18// that immediately following our new vector load we'll need to extract out the
19// individual elements of the load, so we can operate on them individually.
20//
21// On CPUs this transformation is usually not beneficial, because extracting the
22// elements of a vector register is expensive on most architectures. It's
23// usually better just to load each element individually into its own scalar
24// register.
25//
26// However, nVidia and AMD GPUs don't have proper vector registers. Instead, a
27// "vector load" loads directly into a series of scalar registers. In effect,
28// extracting the elements of the vector is free. It's therefore always
29// beneficial to vectorize a sequence of loads on these architectures.
30//
31// Vectorizing (perhaps a better name might be "coalescing") loads can have
32// large performance impacts on GPU kernels, and opportunities for vectorizing
33// are common in GPU code. This pass tries very hard to find such
34// opportunities; its runtime is quadratic in the number of loads in a BB.
35//
36// Some CPU architectures, such as ARM, have instructions that load into
37// multiple scalar registers, similar to a GPU vectorized load. In theory ARM
38// could use this pass (with some modifications), but currently it implements
39// its own pass to do something similar to what we do here.
40//
41// Overview of the algorithm and terminology in this pass:
42//
43// - Break up each basic block into pseudo-BBs, composed of instructions which
44// are guaranteed to transfer control to their successors.
45// - Within a single pseudo-BB, find all loads, and group them into
46// "equivalence classes" according to getUnderlyingObject() and loaded
47// element size. Do the same for stores.
48// - For each equivalence class, greedily build "chains". Each chain has a
49// leader instruction, and every other member of the chain has a known
50// constant offset from the first instr in the chain.
51// - Break up chains so that they contain only contiguous accesses of legal
52// size with no intervening may-alias instrs.
53// - Convert each chain to vector instructions.
54//
55// The O(n^2) behavior of this pass comes from initially building the chains.
56// In the worst case we have to compare each new instruction to all of those
57// that came before. To limit this, we only calculate the offset to the leaders
58// of the N most recently-used chains.
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/MapVector.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/Sequence.h"
70#include "llvm/ADT/Statistic.h"
79#include "llvm/IR/Attributes.h"
80#include "llvm/IR/BasicBlock.h"
82#include "llvm/IR/Constants.h"
83#include "llvm/IR/DataLayout.h"
85#include "llvm/IR/Dominators.h"
86#include "llvm/IR/Function.h"
88#include "llvm/IR/IRBuilder.h"
89#include "llvm/IR/InstrTypes.h"
90#include "llvm/IR/Instruction.h"
92#include "llvm/IR/LLVMContext.h"
93#include "llvm/IR/Module.h"
94#include "llvm/IR/Type.h"
95#include "llvm/IR/Value.h"
97#include "llvm/Pass.h"
100#include "llvm/Support/Debug.h"
103#include "llvm/Support/ModRef.h"
107#include <algorithm>
108#include <cassert>
109#include <cstdint>
110#include <cstdlib>
111#include <iterator>
112#include <optional>
113#include <tuple>
114#include <type_traits>
115#include <utility>
116#include <vector>
117
118using namespace llvm;
119
120#define DEBUG_TYPE "load-store-vectorizer"
121
122STATISTIC(NumVectorInstructions, "Number of vector accesses generated");
123STATISTIC(NumScalarsVectorized, "Number of scalar accesses vectorized");
124
125namespace {
126
127// Equivalence class key, the initial tuple by which we group loads/stores.
128// Loads/stores with different EqClassKeys are never merged.
129//
130// (We could in theory remove element-size from the this tuple. We'd just need
131// to fix up the vector packing/unpacking code.)
132using EqClassKey =
133 std::tuple<const Value * /* result of getUnderlyingObject() */,
134 unsigned /* AddrSpace */,
135 unsigned /* Load/Store element size bits */,
136 char /* IsLoad; char b/c bool can't be a DenseMap key */
137 >;
139 const EqClassKey &K) {
140 const auto &[UnderlyingObject, AddrSpace, ElementSize, IsLoad] = K;
141 return OS << (IsLoad ? "load" : "store") << " of " << *UnderlyingObject
142 << " of element size " << ElementSize << " bits in addrspace "
143 << AddrSpace;
144}
145
146// A Chain is a set of instructions such that:
147// - All instructions have the same equivalence class, so in particular all are
148// loads, or all are stores.
149// - We know the address accessed by the i'th chain elem relative to the
150// chain's leader instruction, which is the first instr of the chain in BB
151// order.
152//
153// Chains have two canonical orderings:
154// - BB order, sorted by Instr->comesBefore.
155// - Offset order, sorted by OffsetFromLeader.
156// This pass switches back and forth between these orders.
157struct ChainElem {
158 Instruction *Inst;
159 APInt OffsetFromLeader;
160 ChainElem(Instruction *Inst, APInt OffsetFromLeader)
161 : Inst(std::move(Inst)), OffsetFromLeader(std::move(OffsetFromLeader)) {}
162};
163using Chain = SmallVector<ChainElem, 1>;
164
165void sortChainInBBOrder(Chain &C) {
166 sort(C, [](auto &A, auto &B) { return A.Inst->comesBefore(B.Inst); });
167}
168
169void sortChainInOffsetOrder(Chain &C) {
170 sort(C, [](const auto &A, const auto &B) {
171 if (A.OffsetFromLeader != B.OffsetFromLeader)
172 return A.OffsetFromLeader.slt(B.OffsetFromLeader);
173 return A.Inst->comesBefore(B.Inst); // stable tiebreaker
174 });
175}
176
177[[maybe_unused]] void dumpChain(ArrayRef<ChainElem> C) {
178 for (const auto &E : C) {
179 dbgs() << " " << *E.Inst << " (offset " << E.OffsetFromLeader << ")\n";
180 }
181}
182
183using EquivalenceClassMap =
185
186// FIXME: Assuming stack alignment of 4 is always good enough
187constexpr unsigned StackAdjustedAlignment = 4;
188
191 for (const ChainElem &E : C)
192 Values.emplace_back(E.Inst);
194}
195
196bool isInvariantLoad(const Instruction *I) {
197 const LoadInst *LI = dyn_cast<LoadInst>(I);
198 return LI != nullptr && LI->hasMetadata(LLVMContext::MD_invariant_load);
199}
200
201/// Reorders the instructions that I depends on (the instructions defining its
202/// operands), to ensure they dominate I.
203void reorder(Instruction *I) {
204 SmallPtrSet<Instruction *, 16> InstructionsToMove;
206
207 Worklist.emplace_back(I);
208 while (!Worklist.empty()) {
209 Instruction *IW = Worklist.pop_back_val();
210 int NumOperands = IW->getNumOperands();
211 for (int Idx = 0; Idx < NumOperands; Idx++) {
213 if (!IM || IM->getOpcode() == Instruction::PHI)
214 continue;
215
216 // If IM is in another BB, no need to move it, because this pass only
217 // vectorizes instructions within one BB.
218 if (IM->getParent() != I->getParent())
219 continue;
220
221 assert(IM != I && "Unexpected cycle while re-ordering instructions");
222
223 if (!IM->comesBefore(I)) {
224 InstructionsToMove.insert(IM);
225 Worklist.emplace_back(IM);
226 }
227 }
228 }
229
230 // All instructions to move should follow I. Start from I, not from begin().
231 for (auto BBI = I->getIterator(), E = I->getParent()->end(); BBI != E;) {
232 Instruction *IM = &*(BBI++);
233 if (!InstructionsToMove.contains(IM))
234 continue;
235 IM->moveBefore(I->getIterator());
236 }
237}
238
239class Vectorizer {
240 Function &F;
241 AliasAnalysis &AA;
242 AssumptionCache &AC;
243 DominatorTree &DT;
244 ScalarEvolution &SE;
245 TargetTransformInfo &TTI;
246 const DataLayout &DL;
247 IRBuilder<> Builder;
248
249 /// We could erase instrs right after vectorizing them, but that can mess up
250 /// our BB iterators, and also can make the equivalence class keys point to
251 /// freed memory. This is fixable, but it's simpler just to wait until we're
252 /// done with the BB and erase all at once.
254
255 /// We insert load/store instructions and GEPs to fill gaps and extend chains
256 /// to enable vectorization. Keep track and delete them later.
257 DenseSet<Instruction *> ExtraElements;
258
259public:
260 Vectorizer(Function &F, AliasAnalysis &AA, AssumptionCache &AC,
261 DominatorTree &DT, ScalarEvolution &SE, TargetTransformInfo &TTI)
262 : F(F), AA(AA), AC(AC), DT(DT), SE(SE), TTI(TTI), DL(F.getDataLayout()),
263 Builder(SE.getModule()) {}
264
265 bool run();
266
267private:
268 static const unsigned MaxDepth = 3;
269
270 /// Runs the vectorizer on a "pseudo basic block", which is a range of
271 /// instructions [Begin, End) within one BB all of which have
272 /// isGuaranteedToTransferExecutionToSuccessor(I) == true.
273 bool runOnPseudoBB(BasicBlock::iterator Begin, BasicBlock::iterator End);
274
275 /// Runs the vectorizer on one equivalence class, i.e. one set of loads/stores
276 /// in the same BB with the same value for getUnderlyingObject() etc.
277 bool runOnEquivalenceClass(const EqClassKey &EqClassKey,
278 ArrayRef<Instruction *> EqClass);
279
280 /// Runs the vectorizer on one chain, i.e. a subset of an equivalence class
281 /// where all instructions access a known, constant offset from the first
282 /// instruction.
283 bool runOnChain(Chain &C);
284
285 /// Splits the chain into subchains of instructions which read/write a
286 /// contiguous block of memory. Discards any length-1 subchains (because
287 /// there's nothing to vectorize in there). Also attempts to fill gaps with
288 /// "extra" elements to artificially make chains contiguous in some cases.
289 std::vector<Chain> splitChainByContiguity(Chain &C);
290
291 /// Splits the chain into subchains where it's safe to hoist loads up to the
292 /// beginning of the sub-chain and it's safe to sink loads up to the end of
293 /// the sub-chain. Discards any length-1 subchains. Also attempts to extend
294 /// non-power-of-two chains by adding "extra" elements in some cases.
295 std::vector<Chain> splitChainByMayAliasInstrs(Chain &C);
296
297 /// Splits the chain into subchains that make legal, aligned accesses.
298 /// Discards any length-1 subchains.
299 std::vector<Chain> splitChainByAlignment(Chain &C);
300
301 /// Converts the instrs in the chain into a single vectorized load or store.
302 /// Adds the old scalar loads/stores to ToErase.
303 bool vectorizeChain(Chain &C);
304
305 /// Tries to compute the offset in bytes PtrB - PtrA.
306 std::optional<APInt> getConstantOffset(Value *PtrA, Value *PtrB,
307 Instruction *ContextInst,
308 unsigned Depth = 0);
309 std::optional<APInt> getConstantOffsetComplexAddrs(Value *PtrA, Value *PtrB,
310 Instruction *ContextInst,
311 unsigned Depth);
312 std::optional<APInt> getConstantOffsetSelects(Value *PtrA, Value *PtrB,
313 Instruction *ContextInst,
314 unsigned Depth);
315
316 /// Gets the element type of the vector that the chain will load or store.
317 /// This is nontrivial because the chain may contain elements of different
318 /// types; e.g. it's legal to have a chain that contains both i32 and float.
319 Type *getChainElemTy(const Chain &C);
320
321 /// Determines whether ChainElem can be moved up (if IsLoad) or down (if
322 /// !IsLoad) to ChainBegin -- i.e. there are no intervening may-alias
323 /// instructions.
324 ///
325 /// The map ChainElemOffsets must contain all of the elements in
326 /// [ChainBegin, ChainElem] and their offsets from some arbitrary base
327 /// address. It's ok if it contains additional entries.
328 template <bool IsLoadChain>
329 bool isSafeToMove(
330 Instruction *ChainElem, Instruction *ChainBegin,
331 const DenseMap<Instruction *, APInt /*OffsetFromLeader*/> &ChainOffsets,
332 BatchAAResults &BatchAA);
333
334 /// Merges the equivalence classes if they have underlying objects that differ
335 /// by one level of indirection (i.e., one is a getelementptr and the other is
336 /// the base pointer in that getelementptr).
337 void mergeEquivalenceClasses(EquivalenceClassMap &EQClasses) const;
338
339 /// Collects loads and stores grouped by "equivalence class", where:
340 /// - all elements in an eq class are a load or all are a store,
341 /// - they all load/store the same element size (it's OK to have e.g. i8 and
342 /// <4 x i8> in the same class, but not i32 and <4 x i8>), and
343 /// - they all have the same value for getUnderlyingObject().
344 EquivalenceClassMap collectEquivalenceClasses(BasicBlock::iterator Begin,
346
347 /// Partitions Instrs into "chains" where every instruction has a known
348 /// constant offset from the first instr in the chain.
349 ///
350 /// Postcondition: For all i, ret[i][0].second == 0, because the first instr
351 /// in the chain is the leader, and an instr touches distance 0 from itself.
352 std::vector<Chain> gatherChains(ArrayRef<Instruction *> Instrs);
353
354 /// Checks if a potential vector load/store with a given alignment is allowed
355 /// and fast. Aligned accesses are always allowed and fast, while misaligned
356 /// accesses depend on TTI checks to determine whether they can and should be
357 /// vectorized or kept as element-wise accesses.
358 bool accessIsAllowedAndFast(unsigned SizeBytes, unsigned AS, Align Alignment,
359 unsigned VecElemBits) const;
360
361 /// Create a new GEP and a new Load/Store instruction such that the GEP
362 /// is pointing at PrevElem + Offset. In the case of stores, store poison.
363 /// Extra elements will either be combined into a masked load/store or
364 /// deleted before the end of the pass.
365 ChainElem createExtraElementAfter(const ChainElem &PrevElem, Type *Ty,
366 APInt Offset, StringRef Prefix,
367 Align Alignment = Align());
368
369 /// Create a mask that masks off the extra elements in the chain, to be used
370 /// for the creation of a masked load/store vector.
371 Value *createMaskForExtraElements(const ArrayRef<ChainElem> C,
372 FixedVectorType *VecTy);
373
374 /// Delete dead GEPs and extra Load/Store instructions created by
375 /// createExtraElementAfter
376 void deleteExtraElements();
377};
378
379class LoadStoreVectorizerLegacyPass : public FunctionPass {
380public:
381 static char ID;
382
383 LoadStoreVectorizerLegacyPass() : FunctionPass(ID) {}
384
385 bool runOnFunction(Function &F) override;
386
387 StringRef getPassName() const override {
388 return "GPU Load and Store Vectorizer";
389 }
390
391 void getAnalysisUsage(AnalysisUsage &AU) const override {
392 AU.addRequired<AAResultsWrapperPass>();
393 AU.addRequired<AssumptionCacheTracker>();
394 AU.addRequired<ScalarEvolutionWrapperPass>();
395 AU.addRequired<DominatorTreeWrapperPass>();
396 AU.addRequired<TargetTransformInfoWrapperPass>();
397 AU.setPreservesCFG();
398 }
399};
400
401} // end anonymous namespace
402
403char LoadStoreVectorizerLegacyPass::ID = 0;
404
405INITIALIZE_PASS_BEGIN(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
406 "Vectorize load and Store instructions", false, false)
413INITIALIZE_PASS_END(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
414 "Vectorize load and store instructions", false, false)
415
417 return new LoadStoreVectorizerLegacyPass();
418}
419
420bool LoadStoreVectorizerLegacyPass::runOnFunction(Function &F) {
421 // Don't vectorize when the attribute NoImplicitFloat is used.
422 if (skipFunction(F) || F.hasFnAttribute(Attribute::NoImplicitFloat))
423 return false;
424
425 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
426 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
427 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
428 TargetTransformInfo &TTI =
429 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
430
431 AssumptionCache &AC =
432 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
433
434 return Vectorizer(F, AA, AC, DT, SE, TTI).run();
435}
436
439 // Don't vectorize when the attribute NoImplicitFloat is used.
440 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
441 return PreservedAnalyses::all();
442
448
449 bool Changed = Vectorizer(F, AA, AC, DT, SE, TTI).run();
452 return Changed ? PA : PreservedAnalyses::all();
453}
454
455bool Vectorizer::run() {
456 bool Changed = false;
457 // Break up the BB if there are any instrs which aren't guaranteed to transfer
458 // execution to their successor.
459 //
460 // Consider, for example:
461 //
462 // def assert_arr_len(int n) { if (n < 2) exit(); }
463 //
464 // load arr[0]
465 // call assert_array_len(arr.length)
466 // load arr[1]
467 //
468 // Even though assert_arr_len does not read or write any memory, we can't
469 // speculate the second load before the call. More info at
470 // https://github.com/llvm/llvm-project/issues/52950.
471 for (BasicBlock *BB : post_order(&F)) {
472 // BB must at least have a terminator.
473 assert(!BB->empty());
474
476 Barriers.emplace_back(BB->begin());
477 for (Instruction &I : *BB)
479 Barriers.emplace_back(I.getIterator());
480 Barriers.emplace_back(BB->end());
481
482 for (auto It = Barriers.begin(), End = std::prev(Barriers.end()); It != End;
483 ++It)
484 Changed |= runOnPseudoBB(*It, *std::next(It));
485
486 for (Instruction *I : ToErase) {
487 // These will get deleted in deleteExtraElements.
488 // This is because ExtraElements will include both extra elements
489 // that *were* vectorized and extra elements that *were not*
490 // vectorized. ToErase will only include extra elements that *were*
491 // vectorized, so in order to avoid double deletion we skip them here and
492 // handle them in deleteExtraElements.
493 if (ExtraElements.contains(I))
494 continue;
495 auto *PtrOperand = getLoadStorePointerOperand(I);
496 if (I->use_empty())
497 I->eraseFromParent();
499 }
500 ToErase.clear();
501 deleteExtraElements();
502 }
503
504 return Changed;
505}
506
507bool Vectorizer::runOnPseudoBB(BasicBlock::iterator Begin,
509 LLVM_DEBUG({
510 dbgs() << "LSV: Running on pseudo-BB [" << *Begin << " ... ";
511 if (End != Begin->getParent()->end())
512 dbgs() << *End;
513 else
514 dbgs() << "<BB end>";
515 dbgs() << ")\n";
516 });
517
518 bool Changed = false;
519 for (const auto &[EqClassKey, EqClass] :
520 collectEquivalenceClasses(Begin, End))
521 Changed |= runOnEquivalenceClass(EqClassKey, EqClass);
522
523 return Changed;
524}
525
526bool Vectorizer::runOnEquivalenceClass(const EqClassKey &EqClassKey,
527 ArrayRef<Instruction *> EqClass) {
528 bool Changed = false;
529
530 LLVM_DEBUG({
531 dbgs() << "LSV: Running on equivalence class of size " << EqClass.size()
532 << " keyed on " << EqClassKey << ":\n";
533 for (Instruction *I : EqClass)
534 dbgs() << " " << *I << "\n";
535 });
536
537 std::vector<Chain> Chains = gatherChains(EqClass);
538 LLVM_DEBUG(dbgs() << "LSV: Got " << Chains.size()
539 << " nontrivial chains.\n";);
540 for (Chain &C : Chains)
541 Changed |= runOnChain(C);
542 return Changed;
543}
544
545bool Vectorizer::runOnChain(Chain &C) {
546 LLVM_DEBUG({
547 dbgs() << "LSV: Running on chain with " << C.size() << " instructions:\n";
548 dumpChain(C);
549 });
550
551 // Split up the chain into increasingly smaller chains, until we can finally
552 // vectorize the chains.
553 //
554 // (Don't be scared by the depth of the loop nest here. These operations are
555 // all at worst O(n lg n) in the number of instructions, and splitting chains
556 // doesn't change the number of instrs. So the whole loop nest is O(n lg n).)
557 bool Changed = false;
558 for (auto &C : splitChainByMayAliasInstrs(C))
559 for (auto &C : splitChainByContiguity(C))
560 for (auto &C : splitChainByAlignment(C))
561 Changed |= vectorizeChain(C);
562 return Changed;
563}
564
565std::vector<Chain> Vectorizer::splitChainByMayAliasInstrs(Chain &C) {
566 if (C.empty())
567 return {};
568
569 sortChainInBBOrder(C);
570
571 LLVM_DEBUG({
572 dbgs() << "LSV: splitChainByMayAliasInstrs considering chain:\n";
573 dumpChain(C);
574 });
575
576 // We know that elements in the chain with nonverlapping offsets can't
577 // alias, but AA may not be smart enough to figure this out. Use a
578 // hashtable.
579 DenseMap<Instruction *, APInt /*OffsetFromLeader*/> ChainOffsets;
580 for (const auto &E : C)
581 ChainOffsets.insert({&*E.Inst, E.OffsetFromLeader});
582
583 // Across a single invocation of this function the IR is not changing, so
584 // using a batched Alias Analysis is safe and can reduce compile time.
585 BatchAAResults BatchAA(AA);
586
587 // Loads get hoisted up to the first load in the chain. Stores get sunk
588 // down to the last store in the chain. Our algorithm for loads is:
589 //
590 // - Take the first element of the chain. This is the start of a new chain.
591 // - Take the next element of `Chain` and check for may-alias instructions
592 // up to the start of NewChain. If no may-alias instrs, add it to
593 // NewChain. Otherwise, start a new NewChain.
594 //
595 // For stores it's the same except in the reverse direction.
596 //
597 // We expect IsLoad to be an std::bool_constant.
598 auto Impl = [&](auto IsLoad) {
599 // MSVC is unhappy if IsLoad is a capture, so pass it as an arg.
600 auto [ChainBegin, ChainEnd] = [&](auto IsLoad) {
601 if constexpr (IsLoad())
602 return std::make_pair(C.begin(), C.end());
603 else
604 return std::make_pair(C.rbegin(), C.rend());
605 }(IsLoad);
606 assert(ChainBegin != ChainEnd);
607
608 std::vector<Chain> Chains;
610 NewChain.emplace_back(*ChainBegin);
611 for (auto ChainIt = std::next(ChainBegin); ChainIt != ChainEnd; ++ChainIt) {
612 if (isSafeToMove<IsLoad>(ChainIt->Inst, NewChain.front().Inst,
613 ChainOffsets, BatchAA)) {
614 LLVM_DEBUG(dbgs() << "LSV: No intervening may-alias instrs; can merge "
615 << *ChainIt->Inst << " into " << *ChainBegin->Inst
616 << "\n");
617 NewChain.emplace_back(*ChainIt);
618 } else {
620 dbgs() << "LSV: Found intervening may-alias instrs; cannot merge "
621 << *ChainIt->Inst << " into " << *ChainBegin->Inst << "\n");
622 if (NewChain.size() > 1) {
623 LLVM_DEBUG({
624 dbgs() << "LSV: got nontrivial chain without aliasing instrs:\n";
625 dumpChain(NewChain);
626 });
627 Chains.emplace_back(std::move(NewChain));
628 }
629
630 // Start a new chain.
631 NewChain = SmallVector<ChainElem, 1>({*ChainIt});
632 }
633 }
634 if (NewChain.size() > 1) {
635 LLVM_DEBUG({
636 dbgs() << "LSV: got nontrivial chain without aliasing instrs:\n";
637 dumpChain(NewChain);
638 });
639 Chains.emplace_back(std::move(NewChain));
640 }
641 return Chains;
642 };
643
644 if (isa<LoadInst>(C[0].Inst))
645 return Impl(/*IsLoad=*/std::bool_constant<true>());
646
647 assert(isa<StoreInst>(C[0].Inst));
648 return Impl(/*IsLoad=*/std::bool_constant<false>());
649}
650
651std::vector<Chain> Vectorizer::splitChainByContiguity(Chain &C) {
652 if (C.empty())
653 return {};
654
655 sortChainInOffsetOrder(C);
656
657 LLVM_DEBUG({
658 dbgs() << "LSV: splitChainByContiguity considering chain:\n";
659 dumpChain(C);
660 });
661
662 // If the chain is not contiguous, we try to fill the gap with "extra"
663 // elements to artificially make it contiguous, to try to enable
664 // vectorization. We only fill gaps if there is potential to end up with a
665 // legal masked load/store given the target, address space, and element type.
666 // At this point, when querying the TTI, optimistically assume max alignment
667 // and max vector size, as splitChainByAlignment will ensure the final vector
668 // shape passes the legalization check.
669 unsigned AS = getLoadStoreAddressSpace(C[0].Inst);
671 unsigned MaxVecRegBits = TTI.getLoadStoreVecRegBitWidth(AS);
672 Align OptimisticAlign = Align(MaxVecRegBits / 8);
673 unsigned int MaxVectorNumElems =
674 MaxVecRegBits / DL.getTypeSizeInBits(ElementType);
675 // Note: This check decides whether to try to fill gaps based on the masked
676 // legality of the target's maximum vector size (getLoadStoreVecRegBitWidth).
677 // If a target *does not* support a masked load/store with this max vector
678 // size, but *does* support a masked load/store with a *smaller* vector size,
679 // that optimization will be missed. This does not occur in any of the targets
680 // that currently support this API.
681 FixedVectorType *OptimisticVectorType =
682 FixedVectorType::get(ElementType, MaxVectorNumElems);
683 bool TryFillGaps =
684 isa<LoadInst>(C[0].Inst)
685 ? TTI.isLegalMaskedLoad(OptimisticVectorType, OptimisticAlign, AS,
687 : TTI.isLegalMaskedStore(OptimisticVectorType, OptimisticAlign, AS,
689
690 // Cache the best aligned element in the chain for use when creating extra
691 // elements.
692 Align BestAlignedElemAlign = getLoadStoreAlignment(C[0].Inst);
693 APInt OffsetOfBestAlignedElemFromLeader = C[0].OffsetFromLeader;
694 for (const auto &E : C) {
695 Align ElementAlignment = getLoadStoreAlignment(E.Inst);
696 if (ElementAlignment > BestAlignedElemAlign) {
697 BestAlignedElemAlign = ElementAlignment;
698 OffsetOfBestAlignedElemFromLeader = E.OffsetFromLeader;
699 }
700 }
701
702 auto DeriveAlignFromBestAlignedElem = [&](APInt NewElemOffsetFromLeader) {
703 return commonAlignment(
704 BestAlignedElemAlign,
705 (NewElemOffsetFromLeader - OffsetOfBestAlignedElemFromLeader)
706 .abs()
707 .getLimitedValue());
708 };
709
710 unsigned ASPtrBits = DL.getIndexSizeInBits(AS);
711
712 std::vector<Chain> Ret;
713 Ret.push_back({C.front()});
714
715 unsigned ChainElemTyBits = DL.getTypeSizeInBits(getChainElemTy(C));
716 ChainElem &Prev = C[0];
717 for (auto It = std::next(C.begin()), End = C.end(); It != End; ++It) {
718 auto &CurChain = Ret.back();
719
720 APInt PrevSzBytes =
721 APInt(ASPtrBits, DL.getTypeStoreSize(getLoadStoreType(Prev.Inst)));
722 APInt PrevReadEnd = Prev.OffsetFromLeader + PrevSzBytes;
723 unsigned SzBytes = DL.getTypeStoreSize(getLoadStoreType(It->Inst));
724
725 // Add this instruction to the end of the current chain, or start a new one.
726 assert(
727 8 * SzBytes % ChainElemTyBits == 0 &&
728 "Every chain-element size must be a multiple of the element size after "
729 "vectorization.");
730 APInt ReadEnd = It->OffsetFromLeader + SzBytes;
731 // Allow redundancy: partial or full overlap counts as contiguous.
732 bool AreContiguous = false;
733 if (It->OffsetFromLeader.sle(PrevReadEnd)) {
734 // Check overlap is a multiple of the element size after vectorization.
735 uint64_t Overlap = (PrevReadEnd - It->OffsetFromLeader).getZExtValue();
736 if (8 * Overlap % ChainElemTyBits == 0)
737 AreContiguous = true;
738 }
739
740 LLVM_DEBUG(dbgs() << "LSV: Instruction is "
741 << (AreContiguous ? "contiguous" : "chain-breaker")
742 << *It->Inst << " (starts at offset "
743 << It->OffsetFromLeader << ")\n");
744
745 // If the chain is not contiguous, try to fill in gaps between Prev and
746 // Curr. For now, we aren't filling gaps between load/stores of different
747 // sizes. Additionally, as a conservative heuristic, we only fill gaps of
748 // 1-2 elements. Generating loads/stores with too many unused bytes has a
749 // side effect of increasing register pressure (on NVIDIA targets at least),
750 // which could cancel out the benefits of reducing number of load/stores.
751 bool GapFilled = false;
752 if (!AreContiguous && TryFillGaps && PrevSzBytes == SzBytes) {
753 APInt GapSzBytes = It->OffsetFromLeader - PrevReadEnd;
754 if (GapSzBytes == PrevSzBytes) {
755 // There is a single gap between Prev and Curr, create one extra element
756 ChainElem NewElem = createExtraElementAfter(
757 Prev, getLoadStoreType(Prev.Inst), PrevSzBytes, "GapFill",
758 DeriveAlignFromBestAlignedElem(PrevReadEnd));
759 CurChain.push_back(NewElem);
760 GapFilled = true;
761 }
762 // There are two gaps between Prev and Curr, only create two extra
763 // elements if Prev is the first element in a sequence of four.
764 // This has the highest chance of resulting in a beneficial vectorization.
765 if ((GapSzBytes == 2 * PrevSzBytes) && (CurChain.size() % 4 == 1)) {
766 ChainElem NewElem1 = createExtraElementAfter(
767 Prev, getLoadStoreType(Prev.Inst), PrevSzBytes, "GapFill",
768 DeriveAlignFromBestAlignedElem(PrevReadEnd));
769 ChainElem NewElem2 = createExtraElementAfter(
770 NewElem1, getLoadStoreType(Prev.Inst), PrevSzBytes, "GapFill",
771 DeriveAlignFromBestAlignedElem(PrevReadEnd + PrevSzBytes));
772 CurChain.push_back(NewElem1);
773 CurChain.push_back(NewElem2);
774 GapFilled = true;
775 }
776 }
777
778 if (AreContiguous || GapFilled) {
779 CurChain.push_back(*It);
780 // In certain cases when handling redundant elements with partial
781 // overlaps, the previous element may still extend beyond the current
782 // element. Only update Prev if the current element is the new end of the
783 // chain.
784 if (ReadEnd.sge(PrevReadEnd))
785 Prev = *It;
786 } else {
787 Ret.push_back({*It});
788 Prev = *It;
789 }
790 }
791
792 // Filter out length-1 chains, these are uninteresting.
793 llvm::erase_if(Ret, [](const auto &Chain) { return Chain.size() <= 1; });
794 return Ret;
795}
796
797Type *Vectorizer::getChainElemTy(const Chain &C) {
798 assert(!C.empty());
799 // The rules are:
800 // - If there are any pointer types in the chain, use an integer type.
801 // - Prefer an integer type if it appears in the chain.
802 // - Otherwise, use the first type in the chain.
803 //
804 // The rule about pointer types is a simplification when we merge e.g. a load
805 // of a ptr and a double. There's no direct conversion from a ptr to a
806 // double; it requires a ptrtoint followed by a bitcast.
807 //
808 // It's unclear to me if the other rules have any practical effect, but we do
809 // it to match this pass's previous behavior.
810 if (any_of(C, [](const ChainElem &E) {
811 return getLoadStoreType(E.Inst)->getScalarType()->isPointerTy();
812 })) {
813 return Type::getIntNTy(
814 F.getContext(),
815 DL.getTypeSizeInBits(getLoadStoreType(C[0].Inst)->getScalarType()));
816 }
817
818 for (const ChainElem &E : C)
819 if (Type *T = getLoadStoreType(E.Inst)->getScalarType(); T->isIntegerTy())
820 return T;
821 return getLoadStoreType(C[0].Inst)->getScalarType();
822}
823
824std::vector<Chain> Vectorizer::splitChainByAlignment(Chain &C) {
825 // We use a simple greedy algorithm.
826 // - Given a chain of length N, find all prefixes that
827 // (a) are not longer than the max register length, and
828 // (b) are a power of 2.
829 // - Starting from the longest prefix, try to create a vector of that length.
830 // - If one of them works, great. Repeat the algorithm on any remaining
831 // elements in the chain.
832 // - If none of them work, discard the first element and repeat on a chain
833 // of length N-1.
834 if (C.empty())
835 return {};
836
837 sortChainInOffsetOrder(C);
838
839 LLVM_DEBUG({
840 dbgs() << "LSV: splitChainByAlignment considering chain:\n";
841 dumpChain(C);
842 });
843
844 bool IsLoadChain = isa<LoadInst>(C[0].Inst);
845 auto GetVectorFactor = [&](unsigned VF, unsigned LoadStoreSize,
846 unsigned ChainSizeBytes, VectorType *VecTy) {
847 return IsLoadChain ? TTI.getLoadVectorFactor(VF, LoadStoreSize,
848 ChainSizeBytes, VecTy)
849 : TTI.getStoreVectorFactor(VF, LoadStoreSize,
850 ChainSizeBytes, VecTy);
851 };
852
853#ifndef NDEBUG
854 for (const auto &E : C) {
855 Type *Ty = getLoadStoreType(E.Inst)->getScalarType();
856 assert(isPowerOf2_32(DL.getTypeSizeInBits(Ty)) &&
857 "Should have filtered out non-power-of-two elements in "
858 "collectEquivalenceClasses.");
859 }
860#endif
861
862 unsigned AS = getLoadStoreAddressSpace(C[0].Inst);
863 unsigned VecRegBytes = TTI.getLoadStoreVecRegBitWidth(AS) / 8;
864
865 // For compile time reasons, we cache whether or not the superset
866 // of all candidate chains contains any extra loads/stores from earlier gap
867 // filling.
868 bool CandidateChainsMayContainExtraLoadsStores = any_of(
869 C, [this](const ChainElem &E) { return ExtraElements.contains(E.Inst); });
870
871 std::vector<Chain> Ret;
872 for (unsigned CBegin = 0; CBegin < C.size(); ++CBegin) {
873 // Find candidate chains of size not greater than the largest vector reg.
874 // These chains are over the closed interval [CBegin, CEnd].
875 SmallVector<std::pair<unsigned /*CEnd*/, unsigned /*SizeBytes*/>, 8>
876 CandidateChains;
877 // Need to compute the size of every candidate chain from its beginning
878 // because of possible overlapping among chain elements.
879 unsigned Sz = DL.getTypeStoreSize(getLoadStoreType(C[CBegin].Inst));
880 APInt PrevReadEnd = C[CBegin].OffsetFromLeader + Sz;
881 for (unsigned CEnd = CBegin + 1, Size = C.size(); CEnd < Size; ++CEnd) {
882 APInt ReadEnd = C[CEnd].OffsetFromLeader +
883 DL.getTypeStoreSize(getLoadStoreType(C[CEnd].Inst));
884 unsigned BytesAdded =
885 PrevReadEnd.sle(ReadEnd) ? (ReadEnd - PrevReadEnd).getSExtValue() : 0;
886 Sz += BytesAdded;
887 if (Sz > VecRegBytes)
888 break;
889 CandidateChains.emplace_back(CEnd, Sz);
890 PrevReadEnd = APIntOps::smax(PrevReadEnd, ReadEnd);
891 }
892
893 // Consider the longest chain first.
894 for (auto It = CandidateChains.rbegin(), End = CandidateChains.rend();
895 It != End; ++It) {
896 auto [CEnd, SizeBytes] = *It;
898 dbgs() << "LSV: splitChainByAlignment considering candidate chain ["
899 << *C[CBegin].Inst << " ... " << *C[CEnd].Inst << "]\n");
900
901 Type *VecElemTy = getChainElemTy(C);
902 // Note, VecElemTy is a power of 2, but might be less than one byte. For
903 // example, we can vectorize 2 x <2 x i4> to <4 x i4>, and in this case
904 // VecElemTy would be i4.
905 unsigned VecElemBits = DL.getTypeSizeInBits(VecElemTy);
906
907 // SizeBytes and VecElemBits are powers of 2, so they divide evenly.
908 assert((8 * SizeBytes) % VecElemBits == 0);
909 unsigned NumVecElems = 8 * SizeBytes / VecElemBits;
910 FixedVectorType *VecTy = FixedVectorType::get(VecElemTy, NumVecElems);
911 unsigned VF = 8 * VecRegBytes / VecElemBits;
912
913 // Check that TTI is happy with this vectorization factor.
914 unsigned TargetVF = GetVectorFactor(VF, VecElemBits,
915 VecElemBits * NumVecElems / 8, VecTy);
916 if (TargetVF != VF && TargetVF < NumVecElems) {
918 dbgs() << "LSV: splitChainByAlignment discarding candidate chain "
919 "because TargetVF="
920 << TargetVF << " != VF=" << VF
921 << " and TargetVF < NumVecElems=" << NumVecElems << "\n");
922 continue;
923 }
924
925 // If we're loading/storing from an alloca, align it if possible.
926 //
927 // FIXME: We eagerly upgrade the alignment, regardless of whether TTI
928 // tells us this is beneficial. This feels a bit odd, but it matches
929 // existing tests. This isn't *so* bad, because at most we align to 4
930 // bytes (current value of StackAdjustedAlignment).
931 //
932 // FIXME: We will upgrade the alignment of the alloca even if it turns out
933 // we can't vectorize for some other reason.
934 Value *PtrOperand = getLoadStorePointerOperand(C[CBegin].Inst);
935 bool IsAllocaAccess = AS == DL.getAllocaAddrSpace() &&
936 isa<AllocaInst>(PtrOperand->stripPointerCasts());
937 Align Alignment = getLoadStoreAlignment(C[CBegin].Inst);
938 Align PrefAlign = Align(StackAdjustedAlignment);
939 if (IsAllocaAccess && Alignment.value() % SizeBytes != 0 &&
940 accessIsAllowedAndFast(SizeBytes, AS, PrefAlign, VecElemBits)) {
942 PtrOperand, PrefAlign, DL, C[CBegin].Inst, nullptr, &DT);
943 if (NewAlign >= Alignment) {
945 << "LSV: splitByChain upgrading alloca alignment from "
946 << Alignment.value() << " to " << NewAlign.value()
947 << "\n");
948 Alignment = NewAlign;
949 }
950 }
951
952 Chain ExtendingLoadsStores;
953 if (!accessIsAllowedAndFast(SizeBytes, AS, Alignment, VecElemBits)) {
954 // If we have a non-power-of-2 element count, attempt to extend the
955 // chain to the next power-of-2 if it makes the access allowed and
956 // fast.
957 bool AllowedAndFast = false;
958 if (NumVecElems < TargetVF && !isPowerOf2_32(NumVecElems) &&
959 VecElemBits >= 8) {
960 // TargetVF may be a lot higher than NumVecElems,
961 // so only extend to the next power of 2.
962 assert(VecElemBits % 8 == 0);
963 unsigned VecElemBytes = VecElemBits / 8;
964 unsigned NewNumVecElems = PowerOf2Ceil(NumVecElems);
965 unsigned NewSizeBytes = VecElemBytes * NewNumVecElems;
966
967 assert(isPowerOf2_32(TargetVF) &&
968 "TargetVF expected to be a power of 2");
969 assert(NewNumVecElems <= TargetVF &&
970 "Should not extend past TargetVF");
971
973 << "LSV: attempting to extend chain of " << NumVecElems
974 << " " << (IsLoadChain ? "loads" : "stores") << " to "
975 << NewNumVecElems << " elements\n");
976 bool IsLegalToExtend =
977 IsLoadChain ? TTI.isLegalMaskedLoad(
978 FixedVectorType::get(VecElemTy, NewNumVecElems),
979 Alignment, AS, TTI::MaskKind::ConstantMask)
981 FixedVectorType::get(VecElemTy, NewNumVecElems),
982 Alignment, AS, TTI::MaskKind::ConstantMask);
983 // Only artificially increase the chain if it would be AllowedAndFast
984 // and if the resulting masked load/store will be legal for the
985 // target.
986 if (IsLegalToExtend &&
987 accessIsAllowedAndFast(NewSizeBytes, AS, Alignment,
988 VecElemBits)) {
990 << "LSV: extending " << (IsLoadChain ? "load" : "store")
991 << " chain of " << NumVecElems << " "
992 << (IsLoadChain ? "loads" : "stores")
993 << " with total byte size of " << SizeBytes << " to "
994 << NewNumVecElems << " "
995 << (IsLoadChain ? "loads" : "stores")
996 << " with total byte size of " << NewSizeBytes
997 << ", TargetVF=" << TargetVF << " \n");
998
999 // Create (NewNumVecElems - NumVecElems) extra elements.
1000 // We are basing each extra element on CBegin, which means the
1001 // offsets should be based on SizeBytes, which represents the offset
1002 // from CBegin to the current end of the chain.
1003 unsigned ASPtrBits = DL.getIndexSizeInBits(AS);
1004 for (unsigned I = 0; I < (NewNumVecElems - NumVecElems); I++) {
1005 ChainElem NewElem = createExtraElementAfter(
1006 C[CBegin], VecElemTy,
1007 APInt(ASPtrBits, SizeBytes + I * VecElemBytes), "Extend");
1008 ExtendingLoadsStores.push_back(NewElem);
1009 }
1010
1011 // Update the size and number of elements for upcoming checks.
1012 SizeBytes = NewSizeBytes;
1013 NumVecElems = NewNumVecElems;
1014 AllowedAndFast = true;
1015 }
1016 }
1017 if (!AllowedAndFast) {
1018 // We were not able to achieve legality by extending the chain.
1020 << "LSV: splitChainByAlignment discarding candidate chain "
1021 "because its alignment is not AllowedAndFast: "
1022 << Alignment.value() << "\n");
1023 continue;
1024 }
1025 }
1026
1027 if ((IsLoadChain &&
1028 !TTI.isLegalToVectorizeLoadChain(SizeBytes, Alignment, AS)) ||
1029 (!IsLoadChain &&
1030 !TTI.isLegalToVectorizeStoreChain(SizeBytes, Alignment, AS))) {
1031 LLVM_DEBUG(
1032 dbgs() << "LSV: splitChainByAlignment discarding candidate chain "
1033 "because !isLegalToVectorizeLoad/StoreChain.");
1034 continue;
1035 }
1036
1037 if (CandidateChainsMayContainExtraLoadsStores) {
1038 // If the candidate chain contains extra loads/stores from an earlier
1039 // optimization, confirm legality now. This filter is essential because
1040 // when filling gaps in splitChainByContiguity, we queried the API to
1041 // check that (for a given element type and address space) there *may*
1042 // have been a legal masked load/store we could possibly create. Now, we
1043 // need to check if the actual chain we ended up with is legal to turn
1044 // into a masked load/store. This is relevant for NVPTX, for example,
1045 // where a masked store is only legal if we have ended up with a 256-bit
1046 // vector.
1047 bool CurrCandContainsExtraLoadsStores = llvm::any_of(
1048 ArrayRef<ChainElem>(C).slice(CBegin, CEnd - CBegin + 1),
1049 [this](const ChainElem &E) {
1050 return ExtraElements.contains(E.Inst);
1051 });
1052
1053 if (CurrCandContainsExtraLoadsStores &&
1054 (IsLoadChain ? !TTI.isLegalMaskedLoad(
1055 FixedVectorType::get(VecElemTy, NumVecElems),
1056 Alignment, AS, TTI::MaskKind::ConstantMask)
1058 FixedVectorType::get(VecElemTy, NumVecElems),
1059 Alignment, AS, TTI::MaskKind::ConstantMask))) {
1061 << "LSV: splitChainByAlignment discarding candidate chain "
1062 "because it contains extra loads/stores that we cannot "
1063 "legally vectorize into a masked load/store \n");
1064 continue;
1065 }
1066 }
1067
1068 // Hooray, we can vectorize this chain!
1069 Chain &NewChain = Ret.emplace_back();
1070 for (unsigned I = CBegin; I <= CEnd; ++I)
1071 NewChain.emplace_back(C[I]);
1072 for (ChainElem E : ExtendingLoadsStores)
1073 NewChain.emplace_back(E);
1074 CBegin = CEnd; // Skip over the instructions we've added to the chain.
1075 break;
1076 }
1077 }
1078 return Ret;
1079}
1080
1081bool Vectorizer::vectorizeChain(Chain &C) {
1082 if (C.size() < 2)
1083 return false;
1084
1085 bool ChainContainsExtraLoadsStores = llvm::any_of(
1086 C, [this](const ChainElem &E) { return ExtraElements.contains(E.Inst); });
1087
1088 // If we are left with a two-element chain, and one of the elements is an
1089 // extra element, we don't want to vectorize
1090 if (C.size() == 2 && ChainContainsExtraLoadsStores)
1091 return false;
1092
1093 sortChainInOffsetOrder(C);
1094
1095 LLVM_DEBUG({
1096 dbgs() << "LSV: Vectorizing chain of " << C.size() << " instructions:\n";
1097 dumpChain(C);
1098 });
1099
1100 Type *VecElemTy = getChainElemTy(C);
1101 bool IsLoadChain = isa<LoadInst>(C[0].Inst);
1102 unsigned AS = getLoadStoreAddressSpace(C[0].Inst);
1103 unsigned BytesAdded = DL.getTypeStoreSize(getLoadStoreType(&*C[0].Inst));
1104 APInt PrevReadEnd = C[0].OffsetFromLeader + BytesAdded;
1105 unsigned ChainBytes = BytesAdded;
1106 for (auto It = std::next(C.begin()), End = C.end(); It != End; ++It) {
1107 unsigned SzBytes = DL.getTypeStoreSize(getLoadStoreType(&*It->Inst));
1108 APInt ReadEnd = It->OffsetFromLeader + SzBytes;
1109 // Update ChainBytes considering possible overlap.
1110 BytesAdded =
1111 PrevReadEnd.sle(ReadEnd) ? (ReadEnd - PrevReadEnd).getSExtValue() : 0;
1112 ChainBytes += BytesAdded;
1113 PrevReadEnd = APIntOps::smax(PrevReadEnd, ReadEnd);
1114 }
1115
1116 assert(8 * ChainBytes % DL.getTypeSizeInBits(VecElemTy) == 0);
1117 // VecTy is a power of 2 and 1 byte at smallest, but VecElemTy may be smaller
1118 // than 1 byte (e.g. VecTy == <32 x i1>).
1119 unsigned NumElem = 8 * ChainBytes / DL.getTypeSizeInBits(VecElemTy);
1120 Type *VecTy = FixedVectorType::get(VecElemTy, NumElem);
1121
1123 // If this is a load/store of an alloca, we might have upgraded the alloca's
1124 // alignment earlier. Get the new alignment.
1125 if (AS == DL.getAllocaAddrSpace()) {
1126 Alignment = std::max(
1127 Alignment,
1129 MaybeAlign(), DL, C[0].Inst, nullptr, &DT));
1130 }
1131
1132 // All elements of the chain must have the same scalar-type size.
1133#ifndef NDEBUG
1134 for (const ChainElem &E : C)
1135 assert(DL.getTypeStoreSize(getLoadStoreType(E.Inst)->getScalarType()) ==
1136 DL.getTypeStoreSize(VecElemTy));
1137#endif
1138
1139 Instruction *VecInst;
1140 if (IsLoadChain) {
1141 // Loads get hoisted to the location of the first load in the chain. We may
1142 // also need to hoist the (transitive) operands of the loads.
1143 Builder.SetInsertPoint(
1144 llvm::min_element(C, [](const auto &A, const auto &B) {
1145 return A.Inst->comesBefore(B.Inst);
1146 })->Inst);
1147
1148 // If the chain contains extra loads, we need to vectorize into a
1149 // masked load.
1150 if (ChainContainsExtraLoadsStores) {
1151 assert(TTI.isLegalMaskedLoad(VecTy, Alignment, AS,
1153 Value *Mask = createMaskForExtraElements(C, cast<FixedVectorType>(VecTy));
1154 VecInst = Builder.CreateMaskedLoad(
1155 VecTy, getLoadStorePointerOperand(C[0].Inst), Alignment, Mask);
1156 } else {
1157 // This can happen due to a chain of redundant loads.
1158 // In this case, just use the element-type, and avoid ExtractElement.
1159 if (NumElem == 1)
1160 VecTy = VecElemTy;
1161 // Chain is in offset order, so C[0] is the instr with the lowest offset,
1162 // i.e. the root of the vector.
1163 VecInst = Builder.CreateAlignedLoad(
1164 VecTy, getLoadStorePointerOperand(C[0].Inst), Alignment);
1165 }
1166
1167 for (const ChainElem &E : C) {
1168 Instruction *I = E.Inst;
1169 Value *V;
1171 unsigned EOffset =
1172 (E.OffsetFromLeader - C[0].OffsetFromLeader).getZExtValue();
1173 unsigned VecIdx = 8 * EOffset / DL.getTypeSizeInBits(VecElemTy);
1174 if (!VecTy->isVectorTy()) {
1175 V = VecInst;
1176 } else if (auto *VT = dyn_cast<FixedVectorType>(T)) {
1177 auto Mask = llvm::to_vector<8>(
1178 llvm::seq<int>(VecIdx, VecIdx + VT->getNumElements()));
1179 V = Builder.CreateShuffleVector(VecInst, Mask, I->getName());
1180 } else {
1181 V = Builder.CreateExtractElement(VecInst, VecIdx, I->getName());
1182 }
1183 if (V->getType() != I->getType())
1184 V = Builder.CreateBitOrPointerCast(V, I->getType());
1186 }
1187
1188 // Finally, we need to reorder the instrs in the BB so that the (transitive)
1189 // operands of VecInst appear before it. To see why, suppose we have
1190 // vectorized the following code:
1191 //
1192 // ptr1 = gep a, 1
1193 // load1 = load i32 ptr1
1194 // ptr0 = gep a, 0
1195 // load0 = load i32 ptr0
1196 //
1197 // We will put the vectorized load at the location of the earliest load in
1198 // the BB, i.e. load1. We get:
1199 //
1200 // ptr1 = gep a, 1
1201 // loadv = load <2 x i32> ptr0
1202 // load0 = extractelement loadv, 0
1203 // load1 = extractelement loadv, 1
1204 // ptr0 = gep a, 0
1205 //
1206 // Notice that loadv uses ptr0, which is defined *after* it!
1207 reorder(VecInst);
1208 } else {
1209 // Stores get sunk to the location of the last store in the chain.
1210 Builder.SetInsertPoint(llvm::max_element(C, [](auto &A, auto &B) {
1211 return A.Inst->comesBefore(B.Inst);
1212 })->Inst);
1213
1214 // Build the vector to store.
1215 Value *Vec = PoisonValue::get(VecTy);
1216 auto InsertElem = [&](Value *V, unsigned VecIdx) {
1217 if (V->getType() != VecElemTy)
1218 V = Builder.CreateBitOrPointerCast(V, VecElemTy);
1219 Vec = Builder.CreateInsertElement(Vec, V, VecIdx);
1220 };
1221 for (const ChainElem &E : C) {
1222 auto *I = cast<StoreInst>(E.Inst);
1223 unsigned EOffset =
1224 (E.OffsetFromLeader - C[0].OffsetFromLeader).getZExtValue();
1225 unsigned VecIdx = 8 * EOffset / DL.getTypeSizeInBits(VecElemTy);
1226 if (FixedVectorType *VT =
1228 for (int J = 0, JE = VT->getNumElements(); J < JE; ++J) {
1229 InsertElem(Builder.CreateExtractElement(I->getValueOperand(), J),
1230 VecIdx++);
1231 }
1232 } else {
1233 InsertElem(I->getValueOperand(), VecIdx);
1234 }
1235 }
1236
1237 // If the chain originates from extra stores, we need to vectorize into a
1238 // masked store.
1239 if (ChainContainsExtraLoadsStores) {
1240 assert(TTI.isLegalMaskedStore(Vec->getType(), Alignment, AS,
1242 Value *Mask =
1243 createMaskForExtraElements(C, cast<FixedVectorType>(Vec->getType()));
1244 VecInst = Builder.CreateMaskedStore(
1245 Vec, getLoadStorePointerOperand(C[0].Inst), Alignment, Mask);
1246 } else {
1247 // Chain is in offset order, so C[0] is the instr with the lowest offset,
1248 // i.e. the root of the vector.
1249 VecInst = Builder.CreateAlignedStore(
1250 Vec, getLoadStorePointerOperand(C[0].Inst), Alignment);
1251 }
1252 }
1253
1255
1256 for (const ChainElem &E : C)
1257 ToErase.emplace_back(E.Inst);
1258
1259 ++NumVectorInstructions;
1260 NumScalarsVectorized += C.size();
1261 return true;
1262}
1263
1264template <bool IsLoadChain>
1265bool Vectorizer::isSafeToMove(
1266 Instruction *ChainElem, Instruction *ChainBegin,
1267 const DenseMap<Instruction *, APInt /*OffsetFromLeader*/> &ChainOffsets,
1268 BatchAAResults &BatchAA) {
1269 LLVM_DEBUG(dbgs() << "LSV: isSafeToMove(" << *ChainElem << " -> "
1270 << *ChainBegin << ")\n");
1271
1272 assert(isa<LoadInst>(ChainElem) == IsLoadChain);
1273 if (ChainElem == ChainBegin)
1274 return true;
1275
1276 // Invariant loads can always be reordered; by definition they are not
1277 // clobbered by stores.
1278 if (isInvariantLoad(ChainElem))
1279 return true;
1280
1281 auto BBIt = std::next([&] {
1282 if constexpr (IsLoadChain)
1283 return BasicBlock::reverse_iterator(ChainElem);
1284 else
1285 return BasicBlock::iterator(ChainElem);
1286 }());
1287 auto BBItEnd = std::next([&] {
1288 if constexpr (IsLoadChain)
1289 return BasicBlock::reverse_iterator(ChainBegin);
1290 else
1291 return BasicBlock::iterator(ChainBegin);
1292 }());
1293
1294 const APInt &ChainElemOffset = ChainOffsets.at(ChainElem);
1295 const unsigned ChainElemSize =
1296 DL.getTypeStoreSize(getLoadStoreType(ChainElem));
1297
1298 for (; BBIt != BBItEnd; ++BBIt) {
1299 Instruction *I = &*BBIt;
1300
1301 if (!I->mayReadOrWriteMemory())
1302 continue;
1303
1304 // Loads can be reordered with other unordered loads. Ordered atomics
1305 // act as reordering barriers, via getModRefInfo below.
1306 if (auto *LI = dyn_cast<LoadInst>(I);
1307 IsLoadChain && LI && LI->isUnordered())
1308 continue;
1309
1310 // Stores can be sunk below invariant loads.
1311 if (!IsLoadChain && isInvariantLoad(I))
1312 continue;
1313
1314 // If I is in the chain, we can tell whether it aliases ChainIt by checking
1315 // what offset ChainIt accesses. This may be better than AA is able to do.
1316 //
1317 // We should really only have duplicate offsets for stores (the duplicate
1318 // loads should be CSE'ed), but in case we have a duplicate load, we'll
1319 // split the chain so we don't have to handle this case specially.
1320 if (auto OffsetIt = ChainOffsets.find(I); OffsetIt != ChainOffsets.end()) {
1321 // I and ChainElem overlap if:
1322 // - I and ChainElem have the same offset, OR
1323 // - I's offset is less than ChainElem's, but I touches past the
1324 // beginning of ChainElem, OR
1325 // - ChainElem's offset is less than I's, but ChainElem touches past the
1326 // beginning of I.
1327 const APInt &IOffset = OffsetIt->second;
1328 unsigned IElemSize = DL.getTypeStoreSize(getLoadStoreType(I));
1329 if (IOffset == ChainElemOffset ||
1330 (IOffset.sle(ChainElemOffset) &&
1331 (IOffset + IElemSize).sgt(ChainElemOffset)) ||
1332 (ChainElemOffset.sle(IOffset) &&
1333 (ChainElemOffset + ChainElemSize).sgt(OffsetIt->second))) {
1334 LLVM_DEBUG({
1335 // Double check that AA also sees this alias. If not, we probably
1336 // have a bug.
1337 ModRefInfo MR =
1338 BatchAA.getModRefInfo(I, MemoryLocation::get(ChainElem));
1339 assert(IsLoadChain ? isModSet(MR) : isModOrRefSet(MR));
1340 dbgs() << "LSV: Found alias in chain: " << *I << "\n";
1341 });
1342 return false; // We found an aliasing instruction; bail.
1343 }
1344
1345 continue; // We're confident there's no alias.
1346 }
1347
1348 LLVM_DEBUG(dbgs() << "LSV: Querying AA for " << *I << "\n");
1349 ModRefInfo MR = BatchAA.getModRefInfo(I, MemoryLocation::get(ChainElem));
1350 if (IsLoadChain ? isModSet(MR) : isModOrRefSet(MR)) {
1351 LLVM_DEBUG(dbgs() << "LSV: Found alias in chain:\n"
1352 << " Aliasing instruction:\n"
1353 << " " << *I << '\n'
1354 << " Aliased instruction and pointer:\n"
1355 << " " << *ChainElem << '\n'
1356 << " " << *getLoadStorePointerOperand(ChainElem)
1357 << '\n');
1358
1359 return false;
1360 }
1361 }
1362 return true;
1363}
1364
1366 // or disjoint is equivalent to add nuw nsw, so it never wraps.
1367 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I); PDI && PDI->isDisjoint())
1368 return true;
1370 return (Signed && BinOpI->hasNoSignedWrap()) ||
1371 (!Signed && BinOpI->hasNoUnsignedWrap());
1372}
1373
1374/// Check if instruction is an add or an or-disjoint (which is semantically
1375/// equivalent to add nuw nsw).
1376static bool isAddLike(Instruction *I) {
1377 switch (I->getOpcode()) {
1378 default:
1379 break;
1380 case Instruction::Add:
1381 return true;
1382 case Instruction::Or:
1383 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
1384 return PDI->isDisjoint();
1385 break;
1386 }
1387 return false;
1388}
1389
1390static bool checkIfSafeAddSequence(const APInt &IdxDiff, Instruction *AddOpA,
1391 unsigned MatchingOpIdxA, Instruction *AddOpB,
1392 unsigned MatchingOpIdxB, bool Signed) {
1393 LLVM_DEBUG(dbgs() << "LSV: checkIfSafeAddSequence IdxDiff=" << IdxDiff
1394 << ", AddOpA=" << *AddOpA << ", MatchingOpIdxA="
1395 << MatchingOpIdxA << ", AddOpB=" << *AddOpB
1396 << ", MatchingOpIdxB=" << MatchingOpIdxB
1397 << ", Signed=" << Signed << "\n");
1398 // If both OpA and OpB are adds (or or-disjoint) with NSW/NUW and with one of
1399 // the operands being the same, we can guarantee that the transformation is
1400 // safe if we can prove that OpA won't overflow when Ret added to the other
1401 // operand of OpA.
1402 // For example:
1403 // %tmp7 = add nsw i32 %tmp2, %v0
1404 // %tmp8 = sext i32 %tmp7 to i64
1405 // ...
1406 // %tmp11 = add nsw i32 %v0, 1
1407 // %tmp12 = add nsw i32 %tmp2, %tmp11
1408 // %tmp13 = sext i32 %tmp12 to i64
1409 //
1410 // Both %tmp7 and %tmp12 have the nsw flag and the first operand is %tmp2.
1411 // It's guaranteed that adding 1 to %tmp7 won't overflow because %tmp11 adds
1412 // 1 to %v0 and both %tmp11 and %tmp12 have the nsw flag.
1413 assert(isAddLike(AddOpA) && isAddLike(AddOpB) &&
1414 checkNoWrapFlags(AddOpA, Signed) && checkNoWrapFlags(AddOpB, Signed));
1415 if (AddOpA->getOperand(MatchingOpIdxA) ==
1416 AddOpB->getOperand(MatchingOpIdxB)) {
1417 Value *OtherOperandA = AddOpA->getOperand(MatchingOpIdxA == 1 ? 0 : 1);
1418 Value *OtherOperandB = AddOpB->getOperand(MatchingOpIdxB == 1 ? 0 : 1);
1419 Instruction *OtherInstrA = dyn_cast<Instruction>(OtherOperandA);
1420 Instruction *OtherInstrB = dyn_cast<Instruction>(OtherOperandB);
1421
1422 // Compare in N+1 bits, which can represent the exact difference between
1423 // any two extended N-bit values. Constants use the same extension as the
1424 // GEP indices, while IdxDiff remains a signed distance.
1425 unsigned WideBitWidth = IdxDiff.getBitWidth() + 1;
1426 APInt WideIdxDiff = IdxDiff.sext(WideBitWidth);
1427 auto ExtendConstant = [Signed, WideBitWidth](const ConstantInt *C) {
1428 const APInt &Value = C->getValue();
1429 return Signed ? Value.sext(WideBitWidth) : Value.zext(WideBitWidth);
1430 };
1431
1432 // Match `x +nsw/nuw y` and `x +nsw/nuw (y +nsw/nuw IdxDiff)`.
1433 if (OtherInstrB && isAddLike(OtherInstrB) &&
1434 checkNoWrapFlags(OtherInstrB, Signed) &&
1435 isa<ConstantInt>(OtherInstrB->getOperand(1))) {
1436 APInt WideCstVal =
1437 ExtendConstant(cast<ConstantInt>(OtherInstrB->getOperand(1)));
1438 if (OtherInstrB->getOperand(0) == OtherOperandA &&
1439 WideIdxDiff == WideCstVal)
1440 return true;
1441 }
1442 // Match `x +nsw/nuw (y +nsw/nuw -Idx)` and `x +nsw/nuw (y +nsw/nuw x)`.
1443 if (OtherInstrA && isAddLike(OtherInstrA) &&
1444 checkNoWrapFlags(OtherInstrA, Signed) &&
1445 isa<ConstantInt>(OtherInstrA->getOperand(1))) {
1446 APInt WideCstVal =
1447 ExtendConstant(cast<ConstantInt>(OtherInstrA->getOperand(1)));
1448 if (OtherInstrA->getOperand(0) == OtherOperandB &&
1449 WideIdxDiff == -WideCstVal)
1450 return true;
1451 }
1452 // Match `x +nsw/nuw (y +nsw/nuw c)` and
1453 // `x +nsw/nuw (y +nsw/nuw (c + IdxDiff))`.
1454 if (OtherInstrA && OtherInstrB && isAddLike(OtherInstrA) &&
1455 isAddLike(OtherInstrB) && checkNoWrapFlags(OtherInstrA, Signed) &&
1456 checkNoWrapFlags(OtherInstrB, Signed) &&
1457 isa<ConstantInt>(OtherInstrA->getOperand(1)) &&
1458 isa<ConstantInt>(OtherInstrB->getOperand(1))) {
1459 APInt WideCstValA =
1460 ExtendConstant(cast<ConstantInt>(OtherInstrA->getOperand(1)));
1461 APInt WideCstValB =
1462 ExtendConstant(cast<ConstantInt>(OtherInstrB->getOperand(1)));
1463 if (OtherInstrA->getOperand(0) == OtherInstrB->getOperand(0) &&
1464 WideIdxDiff == WideCstValB - WideCstValA)
1465 return true;
1466 }
1467 }
1468 return false;
1469}
1470
1471std::optional<APInt> Vectorizer::getConstantOffsetComplexAddrs(
1472 Value *PtrA, Value *PtrB, Instruction *ContextInst, unsigned Depth) {
1473 LLVM_DEBUG(dbgs() << "LSV: getConstantOffsetComplexAddrs PtrA=" << *PtrA
1474 << " PtrB=" << *PtrB << " ContextInst=" << *ContextInst
1475 << " Depth=" << Depth << "\n");
1476 auto *GEPA = dyn_cast<GetElementPtrInst>(PtrA);
1477 auto *GEPB = dyn_cast<GetElementPtrInst>(PtrB);
1478 if (!GEPA || !GEPB)
1479 return getConstantOffsetSelects(PtrA, PtrB, ContextInst, Depth);
1480
1481 // Look through GEPs after checking they're the same except for the last
1482 // index.
1483 if (GEPA->getNumOperands() != GEPB->getNumOperands() ||
1484 GEPA->getPointerOperand() != GEPB->getPointerOperand() ||
1485 GEPA->getSourceElementType() != GEPB->getSourceElementType())
1486 return std::nullopt;
1487 gep_type_iterator GTIA = gep_type_begin(GEPA);
1488 gep_type_iterator GTIB = gep_type_begin(GEPB);
1489 for (unsigned I = 0, E = GEPA->getNumIndices() - 1; I < E; ++I) {
1490 if (GTIA.getOperand() != GTIB.getOperand())
1491 return std::nullopt;
1492 ++GTIA;
1493 ++GTIB;
1494 }
1495
1498 if (!OpA || !OpB || OpA->getOpcode() != OpB->getOpcode() ||
1499 OpA->getType() != OpB->getType())
1500 return std::nullopt;
1501
1502 uint64_t Stride = GTIA.getSequentialElementStride(DL);
1503
1504 // Only look through a ZExt/SExt.
1505 if (!isa<SExtInst>(OpA) && !isa<ZExtInst>(OpA))
1506 return std::nullopt;
1507
1508 bool Signed = isa<SExtInst>(OpA);
1509
1510 // At this point A could be a function parameter, i.e. not an instruction
1511 Value *ValA = OpA->getOperand(0);
1512 OpB = dyn_cast<Instruction>(OpB->getOperand(0));
1513 if (!OpB || ValA->getType() != OpB->getType())
1514 return std::nullopt;
1515
1516 const SCEV *OffsetSCEVA = SE.getSCEV(ValA);
1517 const SCEV *OffsetSCEVB = SE.getSCEV(OpB);
1518 const SCEV *IdxDiffSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1519 if (IdxDiffSCEV == SE.getCouldNotCompute())
1520 return std::nullopt;
1521
1522 ConstantRange IdxDiffRange = SE.getSignedRange(IdxDiffSCEV);
1523 if (!IdxDiffRange.isSingleElement())
1524 return std::nullopt;
1525 APInt IdxDiff = *IdxDiffRange.getSingleElement();
1526
1527 LLVM_DEBUG(dbgs() << "LSV: getConstantOffsetComplexAddrs IdxDiff=" << IdxDiff
1528 << "\n");
1529
1530 // Now we need to prove that adding IdxDiff to ValA won't overflow.
1531 bool Safe = false;
1532
1533 // First attempt: if OpB is X + C with NSW/NUW, adding IdxDiff to ValA cannot
1534 // wrap when IdxDiff lies between zero and C. Compare in one extra bit so C is
1535 // represented exactly for both extension kinds.
1536 if (isAddLike(OpB) && isa<ConstantInt>(OpB->getOperand(1)) &&
1537 checkNoWrapFlags(OpB, Signed)) {
1538 const APInt &C = cast<ConstantInt>(OpB->getOperand(1))->getValue();
1539 unsigned WideBitWidth = IdxDiff.getBitWidth() + 1;
1540 APInt WideIdxDiff = IdxDiff.sext(WideBitWidth);
1541 APInt WideC = Signed ? C.sext(WideBitWidth) : C.zext(WideBitWidth);
1542 if (WideC.isNegative())
1543 Safe = WideIdxDiff.sge(WideC) && WideIdxDiff.sle(0);
1544 else
1545 Safe = WideIdxDiff.sge(0) && WideIdxDiff.sle(WideC);
1546 }
1547
1548 // Second attempt: check if we have eligible add NSW/NUW instruction
1549 // sequences.
1550 OpA = dyn_cast<Instruction>(ValA);
1551 if (!Safe && OpA && isAddLike(OpA) && isAddLike(OpB) &&
1553 // In the checks below a matching operand in OpA and OpB is an operand which
1554 // is the same in those two instructions. Below we account for possible
1555 // orders of the operands of these add instructions.
1556 for (unsigned MatchingOpIdxA : {0, 1})
1557 for (unsigned MatchingOpIdxB : {0, 1})
1558 if (!Safe)
1559 Safe = checkIfSafeAddSequence(IdxDiff, OpA, MatchingOpIdxA, OpB,
1560 MatchingOpIdxB, Signed);
1561 }
1562
1563 unsigned BitWidth = ValA->getType()->getScalarSizeInBits();
1564
1565 // Third attempt:
1566 //
1567 // Assuming IdxDiff is positive: If all set bits of IdxDiff or any higher
1568 // order bit other than the sign bit are known to be zero in ValA, we can add
1569 // Diff to it while guaranteeing no overflow of any sort.
1570 //
1571 // If IdxDiff is negative, do the same, but swap ValA and ValB.
1572 if (!Safe) {
1573 // When computing known bits, use the GEPs as context instructions, since
1574 // they likely are in the same BB as the load/store.
1575 KnownBits Known(BitWidth);
1576 computeKnownBits((IdxDiff.sge(0) ? ValA : OpB), Known, DL, &AC, ContextInst,
1577 &DT);
1578 APInt BitsAllowedToBeSet = Known.Zero.zext(IdxDiff.getBitWidth());
1579 if (Signed)
1580 BitsAllowedToBeSet.clearBit(BitWidth - 1);
1581 Safe = BitsAllowedToBeSet.uge(IdxDiff.abs());
1582 }
1583
1584 // Fourth attempt: use SCEV unsigned range to prove that adding IdxDiff
1585 // to ValA won't cause unsigned overflow (which would make zext produce
1586 // a different difference). This handles cases where KnownBits analysis
1587 // can't determine safety but SCEV has tighter range information.
1588 if (!Safe && !Signed) {
1589 Value *CheckVal = IdxDiff.sge(0) ? ValA : OpB;
1590 ConstantRange CR = SE.getUnsignedRange(SE.getSCEV(CheckVal));
1591 APInt AbsDiff = IdxDiff.abs().zextOrTrunc(BitWidth);
1592 APInt Limit = APInt::getMaxValue(BitWidth) - AbsDiff;
1593 Safe = CR.getUnsignedMax().ule(Limit);
1594 }
1595
1596 if (Safe) {
1597 // IdxDiff has the pre-extension index width. Scale it at the pointer index
1598 // width so any wrapping matches GEP offset arithmetic.
1599 unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(GEPA->getType());
1600 return IdxDiff.sextOrTrunc(OffsetBitWidth) * Stride;
1601 }
1602 return std::nullopt;
1603}
1604
1605std::optional<APInt> Vectorizer::getConstantOffsetSelects(
1606 Value *PtrA, Value *PtrB, Instruction *ContextInst, unsigned Depth) {
1607 if (Depth++ == MaxDepth)
1608 return std::nullopt;
1609
1610 if (auto *SelectA = dyn_cast<SelectInst>(PtrA)) {
1611 if (auto *SelectB = dyn_cast<SelectInst>(PtrB)) {
1612 if (SelectA->getCondition() != SelectB->getCondition())
1613 return std::nullopt;
1614 LLVM_DEBUG(dbgs() << "LSV: getConstantOffsetSelects, PtrA=" << *PtrA
1615 << ", PtrB=" << *PtrB << ", ContextInst="
1616 << *ContextInst << ", Depth=" << Depth << "\n");
1617 std::optional<APInt> TrueDiff = getConstantOffset(
1618 SelectA->getTrueValue(), SelectB->getTrueValue(), ContextInst, Depth);
1619 if (!TrueDiff)
1620 return std::nullopt;
1621 std::optional<APInt> FalseDiff =
1622 getConstantOffset(SelectA->getFalseValue(), SelectB->getFalseValue(),
1623 ContextInst, Depth);
1624 if (TrueDiff == FalseDiff)
1625 return TrueDiff;
1626 }
1627 }
1628 return std::nullopt;
1629}
1630
1631void Vectorizer::mergeEquivalenceClasses(EquivalenceClassMap &EQClasses) const {
1632 if (EQClasses.size() < 2) // There is nothing to merge.
1633 return;
1634
1635 // The reduced key has all elements of the ECClassKey except the underlying
1636 // object. Check that EqClassKey has 4 elements and define the reduced key.
1637 static_assert(std::tuple_size_v<EqClassKey> == 4,
1638 "EqClassKey has changed - EqClassReducedKey needs changes too");
1639 using EqClassReducedKey =
1640 std::tuple<std::tuple_element_t<1, EqClassKey> /* AddrSpace */,
1641 std::tuple_element_t<2, EqClassKey> /* Element size */,
1642 std::tuple_element_t<3, EqClassKey> /* IsLoad; */>;
1643 using ECReducedKeyToUnderlyingObjectMap =
1644 MapVector<EqClassReducedKey,
1645 SmallPtrSet<std::tuple_element_t<0, EqClassKey>, 4>>;
1646
1647 // Form a map from the reduced key (without the underlying object) to the
1648 // underlying objects: 1 reduced key to many underlying objects, to form
1649 // groups of potentially merge-able equivalence classes.
1650 ECReducedKeyToUnderlyingObjectMap RedKeyToUOMap;
1651 bool FoundPotentiallyOptimizableEC = false;
1652 for (const auto &EC : EQClasses) {
1653 const auto &Key = EC.first;
1654 EqClassReducedKey RedKey{std::get<1>(Key), std::get<2>(Key),
1655 std::get<3>(Key)};
1656 auto &UOMap = RedKeyToUOMap[RedKey];
1657 UOMap.insert(std::get<0>(Key));
1658 if (UOMap.size() > 1)
1659 FoundPotentiallyOptimizableEC = true;
1660 }
1661 if (!FoundPotentiallyOptimizableEC)
1662 return;
1663
1664 LLVM_DEBUG({
1665 dbgs() << "LSV: mergeEquivalenceClasses: before merging:\n";
1666 for (const auto &EC : EQClasses) {
1667 dbgs() << " Key: {" << EC.first << "}\n";
1668 for (const auto &Inst : EC.second)
1669 dbgs() << " Inst: " << *Inst << '\n';
1670 }
1671 });
1672 LLVM_DEBUG({
1673 dbgs() << "LSV: mergeEquivalenceClasses: RedKeyToUOMap:\n";
1674 for (const auto &RedKeyToUO : RedKeyToUOMap) {
1675 dbgs() << " Reduced key: {" << std::get<0>(RedKeyToUO.first) << ", "
1676 << std::get<1>(RedKeyToUO.first) << ", "
1677 << static_cast<int>(std::get<2>(RedKeyToUO.first)) << "} --> "
1678 << RedKeyToUO.second.size() << " underlying objects:\n";
1679 for (auto UObject : RedKeyToUO.second)
1680 dbgs() << " " << *UObject << '\n';
1681 }
1682 });
1683
1684 using UObjectToUObjectMap = DenseMap<const Value *, const Value *>;
1685
1686 // Compute the ultimate targets for a set of underlying objects.
1687 auto GetUltimateTargets =
1688 [](SmallPtrSetImpl<const Value *> &UObjects) -> UObjectToUObjectMap {
1689 UObjectToUObjectMap IndirectionMap;
1690 for (const auto *UObject : UObjects) {
1691 const unsigned MaxLookupDepth = 1; // look for 1-level indirections only
1692 const auto *UltimateTarget = getUnderlyingObject(UObject, MaxLookupDepth);
1693 if (UltimateTarget != UObject)
1694 IndirectionMap[UObject] = UltimateTarget;
1695 }
1696 UObjectToUObjectMap UltimateTargetsMap;
1697 for (const auto *UObject : UObjects) {
1698 auto Target = UObject;
1699 auto It = IndirectionMap.find(Target);
1700 for (; It != IndirectionMap.end(); It = IndirectionMap.find(Target))
1701 Target = It->second;
1702 UltimateTargetsMap[UObject] = Target;
1703 }
1704 return UltimateTargetsMap;
1705 };
1706
1707 // For each item in RedKeyToUOMap, if it has more than one underlying object,
1708 // try to merge the equivalence classes.
1709 for (auto &[RedKey, UObjects] : RedKeyToUOMap) {
1710 if (UObjects.size() < 2)
1711 continue;
1712 auto UTMap = GetUltimateTargets(UObjects);
1713 for (const auto &[UObject, UltimateTarget] : UTMap) {
1714 if (UObject == UltimateTarget)
1715 continue;
1716
1717 EqClassKey KeyFrom{UObject, std::get<0>(RedKey), std::get<1>(RedKey),
1718 std::get<2>(RedKey)};
1719 EqClassKey KeyTo{UltimateTarget, std::get<0>(RedKey), std::get<1>(RedKey),
1720 std::get<2>(RedKey)};
1721 // The entry for KeyFrom is guarantted to exist, unlike KeyTo. Thus,
1722 // request the reference to the instructions vector for KeyTo first.
1723 const auto &VecTo = EQClasses[KeyTo];
1724 const auto &VecFrom = EQClasses[KeyFrom];
1725 SmallVector<Instruction *, 8> MergedVec;
1726 std::merge(VecFrom.begin(), VecFrom.end(), VecTo.begin(), VecTo.end(),
1727 std::back_inserter(MergedVec),
1728 [](Instruction *A, Instruction *B) {
1729 return A && B && A->comesBefore(B);
1730 });
1731 EQClasses[KeyTo] = std::move(MergedVec);
1732 EQClasses.erase(KeyFrom);
1733 }
1734 }
1735 LLVM_DEBUG({
1736 dbgs() << "LSV: mergeEquivalenceClasses: after merging:\n";
1737 for (const auto &EC : EQClasses) {
1738 dbgs() << " Key: {" << EC.first << "}\n";
1739 for (const auto &Inst : EC.second)
1740 dbgs() << " Inst: " << *Inst << '\n';
1741 }
1742 });
1743}
1744
1745EquivalenceClassMap
1746Vectorizer::collectEquivalenceClasses(BasicBlock::iterator Begin,
1748 EquivalenceClassMap Ret;
1749
1750 auto GetUnderlyingObject = [](const Value *Ptr) -> const Value * {
1751 const Value *ObjPtr = llvm::getUnderlyingObject(Ptr);
1752 if (const auto *Sel = dyn_cast<SelectInst>(ObjPtr)) {
1753 // The select's themselves are distinct instructions even if they share
1754 // the same condition and evaluate to consecutive pointers for true and
1755 // false values of the condition. Therefore using the select's themselves
1756 // for grouping instructions would put consecutive accesses into different
1757 // lists and they won't be even checked for being consecutive, and won't
1758 // be vectorized.
1759 return Sel->getCondition();
1760 }
1761 return ObjPtr;
1762 };
1763
1764 for (Instruction &I : make_range(Begin, End)) {
1765 auto *LI = dyn_cast<LoadInst>(&I);
1766 auto *SI = dyn_cast<StoreInst>(&I);
1767 if (!LI && !SI)
1768 continue;
1769
1770 if ((LI && !LI->isSimple()) || (SI && !SI->isSimple()))
1771 continue;
1772
1773 if ((LI && !TTI.isLegalToVectorizeLoad(LI)) ||
1774 (SI && !TTI.isLegalToVectorizeStore(SI)))
1775 continue;
1776
1777 Type *Ty = getLoadStoreType(&I);
1778 if (!VectorType::isValidElementType(Ty->getScalarType()))
1779 continue;
1780
1781 // Pointer loads and stores with external state must retain their pointer
1782 // memory type so the out-of-band state is transferred. Do not vectorize
1783 // these pointers.
1784 if (DL.hasExternalState(Ty))
1785 continue;
1786
1787 // Skip weird non-byte sizes. They probably aren't worth the effort of
1788 // handling correctly.
1789 unsigned TySize = DL.getTypeSizeInBits(Ty);
1790 if ((TySize % 8) != 0)
1791 continue;
1792
1793 // Skip vectors of pointers. The vectorizeLoadChain/vectorizeStoreChain
1794 // functions are currently using an integer type for the vectorized
1795 // load/store, and does not support casting between the integer type and a
1796 // vector of pointers (e.g. i64 to <2 x i16*>)
1797 if (Ty->isVectorTy() && Ty->isPtrOrPtrVectorTy())
1798 continue;
1799
1801 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1802 unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
1803
1804 unsigned VF = VecRegSize / TySize;
1805 VectorType *VecTy = dyn_cast<VectorType>(Ty);
1806
1807 // Only handle power-of-two sized elements.
1808 if ((!VecTy && !isPowerOf2_32(DL.getTypeSizeInBits(Ty))) ||
1809 (VecTy && !isPowerOf2_32(DL.getTypeSizeInBits(VecTy->getScalarType()))))
1810 continue;
1811
1812 // No point in looking at these if they're too big to vectorize.
1813 if (TySize > VecRegSize / 2 ||
1814 (VecTy && TTI.getLoadVectorFactor(VF, TySize, TySize / 8, VecTy) == 0))
1815 continue;
1816
1817 Ret[{GetUnderlyingObject(Ptr), AS,
1818 DL.getTypeSizeInBits(getLoadStoreType(&I)->getScalarType()),
1819 /*IsLoad=*/LI != nullptr}]
1820 .emplace_back(&I);
1821 }
1822
1823 mergeEquivalenceClasses(Ret);
1824 return Ret;
1825}
1826
1827std::vector<Chain> Vectorizer::gatherChains(ArrayRef<Instruction *> Instrs) {
1828 if (Instrs.empty())
1829 return {};
1830
1831 unsigned AS = getLoadStoreAddressSpace(Instrs[0]);
1832 unsigned ASPtrBits = DL.getIndexSizeInBits(AS);
1833
1834#ifndef NDEBUG
1835 // Check that Instrs is in BB order and all have the same addr space.
1836 for (size_t I = 1; I < Instrs.size(); ++I) {
1837 assert(Instrs[I - 1]->comesBefore(Instrs[I]));
1838 assert(getLoadStoreAddressSpace(Instrs[I]) == AS);
1839 }
1840#endif
1841
1842 // Machinery to build an MRU-hashtable of Chains.
1843 //
1844 // (Ideally this could be done with MapVector, but as currently implemented,
1845 // moving an element to the front of a MapVector is O(n).)
1846 struct InstrListElem : ilist_node<InstrListElem>,
1847 std::pair<Instruction *, Chain> {
1848 explicit InstrListElem(Instruction *I)
1849 : std::pair<Instruction *, Chain>(I, {}) {}
1850 };
1851 struct InstrListElemDenseMapInfo {
1852 using IInfo = DenseMapInfo<Instruction *>;
1853 static unsigned getHashValue(const InstrListElem *E) {
1854 return IInfo::getHashValue(E->first);
1855 }
1856 static bool isEqual(const InstrListElem *A, const InstrListElem *B) {
1857 return IInfo::isEqual(A->first, B->first);
1858 }
1859 };
1860 SpecificBumpPtrAllocator<InstrListElem> Allocator;
1861 simple_ilist<InstrListElem> MRU;
1862 DenseSet<InstrListElem *, InstrListElemDenseMapInfo> Chains;
1863
1864 // Compare each instruction in `instrs` to leader of the N most recently-used
1865 // chains. This limits the O(n^2) behavior of this pass while also allowing
1866 // us to build arbitrarily long chains.
1867 for (Instruction *I : Instrs) {
1868 constexpr int MaxChainsToTry = 64;
1869
1870 bool MatchFound = false;
1871 auto ChainIter = MRU.begin();
1872 for (size_t J = 0; J < MaxChainsToTry && ChainIter != MRU.end();
1873 ++J, ++ChainIter) {
1874 if (std::optional<APInt> Offset = getConstantOffset(
1875 getLoadStorePointerOperand(ChainIter->first),
1877 /*ContextInst=*/
1878 (ChainIter->first->comesBefore(I) ? I : ChainIter->first))) {
1879 // `Offset` might not have the expected number of bits, if e.g. AS has a
1880 // different number of bits than opaque pointers.
1881 ChainIter->second.emplace_back(I, Offset.value());
1882 // Move ChainIter to the front of the MRU list.
1883 MRU.remove(*ChainIter);
1884 MRU.push_front(*ChainIter);
1885 MatchFound = true;
1886 break;
1887 }
1888 }
1889
1890 if (!MatchFound) {
1891 APInt ZeroOffset(ASPtrBits, 0);
1892 InstrListElem *E = new (Allocator.Allocate()) InstrListElem(I);
1893 E->second.emplace_back(I, ZeroOffset);
1894 MRU.push_front(*E);
1895 Chains.insert(E);
1896 }
1897 }
1898
1899 std::vector<Chain> Ret;
1900 Ret.reserve(Chains.size());
1901 // Iterate over MRU rather than Chains so the order is deterministic.
1902 for (auto &E : MRU)
1903 if (E.second.size() > 1)
1904 Ret.emplace_back(std::move(E.second));
1905 return Ret;
1906}
1907
1908std::optional<APInt> Vectorizer::getConstantOffset(Value *PtrA, Value *PtrB,
1909 Instruction *ContextInst,
1910 unsigned Depth) {
1911 LLVM_DEBUG(dbgs() << "LSV: getConstantOffset, PtrA=" << *PtrA
1912 << ", PtrB=" << *PtrB << ", ContextInst= " << *ContextInst
1913 << ", Depth=" << Depth << "\n");
1914 // We'll ultimately return a value of this bit width, even if computations
1915 // happen in a different width.
1916 unsigned OrigBitWidth = DL.getIndexTypeSizeInBits(PtrA->getType());
1917 APInt OffsetA(OrigBitWidth, 0);
1918 APInt OffsetB(OrigBitWidth, 0);
1919 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1920 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1921 unsigned NewPtrBitWidth = DL.getTypeStoreSizeInBits(PtrA->getType());
1922 if (NewPtrBitWidth != DL.getTypeStoreSizeInBits(PtrB->getType()))
1923 return std::nullopt;
1924
1925 // If we have to shrink the pointer, stripAndAccumulateInBoundsConstantOffsets
1926 // should properly handle a possible overflow and the value should fit into
1927 // the smallest data type used in the cast/gep chain.
1928 assert(OffsetA.getSignificantBits() <= NewPtrBitWidth &&
1929 OffsetB.getSignificantBits() <= NewPtrBitWidth);
1930
1931 OffsetA = OffsetA.sextOrTrunc(NewPtrBitWidth);
1932 OffsetB = OffsetB.sextOrTrunc(NewPtrBitWidth);
1933 if (PtrA == PtrB)
1934 return (OffsetB - OffsetA).sextOrTrunc(OrigBitWidth);
1935
1936 // Try to compute B - A.
1937 const SCEV *DistScev = SE.getMinusSCEV(SE.getSCEV(PtrB), SE.getSCEV(PtrA));
1938 if (DistScev != SE.getCouldNotCompute()) {
1939 LLVM_DEBUG(dbgs() << "LSV: SCEV PtrB - PtrA =" << *DistScev << "\n");
1940 ConstantRange DistRange = SE.getSignedRange(DistScev);
1941 if (DistRange.isSingleElement()) {
1942 // Handle index width (the width of Dist) != pointer width (the width of
1943 // the Offset*s at this point).
1944 APInt Dist = DistRange.getSingleElement()->sextOrTrunc(NewPtrBitWidth);
1945 return (OffsetB - OffsetA + Dist).sextOrTrunc(OrigBitWidth);
1946 }
1947 }
1948 if (std::optional<APInt> Diff =
1949 getConstantOffsetComplexAddrs(PtrA, PtrB, ContextInst, Depth))
1950 return (OffsetB - OffsetA + Diff->sext(OffsetB.getBitWidth()))
1951 .sextOrTrunc(OrigBitWidth);
1952 return std::nullopt;
1953}
1954
1955bool Vectorizer::accessIsAllowedAndFast(unsigned SizeBytes, unsigned AS,
1956 Align Alignment,
1957 unsigned VecElemBits) const {
1958 // Aligned vector accesses are ALWAYS faster than element-wise accesses.
1959 if (Alignment.value() % SizeBytes == 0)
1960 return true;
1961
1962 // Ask TTI whether misaligned accesses are faster as vector or element-wise.
1963 unsigned VectorizedSpeed = 0;
1964 bool AllowsMisaligned = TTI.allowsMisalignedMemoryAccesses(
1965 F.getContext(), SizeBytes * 8, AS, Alignment, &VectorizedSpeed);
1966 if (!AllowsMisaligned) {
1967 LLVM_DEBUG(
1968 dbgs() << "LSV: Access of " << SizeBytes << "B in addrspace " << AS
1969 << " with alignment " << Alignment.value()
1970 << " is misaligned, and therefore can't be vectorized.\n");
1971 return false;
1972 }
1973
1974 unsigned ElementwiseSpeed = 0;
1975 (TTI).allowsMisalignedMemoryAccesses((F).getContext(), VecElemBits, AS,
1976 Alignment, &ElementwiseSpeed);
1977 if (VectorizedSpeed < ElementwiseSpeed) {
1978 LLVM_DEBUG(dbgs() << "LSV: Access of " << SizeBytes << "B in addrspace "
1979 << AS << " with alignment " << Alignment.value()
1980 << " has relative speed " << VectorizedSpeed
1981 << ", which is lower than the elementwise speed of "
1982 << ElementwiseSpeed
1983 << ". Therefore this access won't be vectorized.\n");
1984 return false;
1985 }
1986 return true;
1987}
1988
1989ChainElem Vectorizer::createExtraElementAfter(const ChainElem &Prev, Type *Ty,
1990 APInt Offset, StringRef Prefix,
1991 Align Alignment) {
1992 Instruction *NewElement = nullptr;
1993 Builder.SetInsertPoint(Prev.Inst->getNextNode());
1994 if (LoadInst *PrevLoad = dyn_cast<LoadInst>(Prev.Inst)) {
1995 Value *NewGep = Builder.CreatePtrAdd(
1996 PrevLoad->getPointerOperand(), Builder.getInt(Offset), Prefix + "GEP");
1997 LLVM_DEBUG(dbgs() << "LSV: Extra GEP Created: \n" << *NewGep << "\n");
1998 NewElement = Builder.CreateAlignedLoad(Ty, NewGep, Alignment, Prefix);
1999 } else {
2000 StoreInst *PrevStore = cast<StoreInst>(Prev.Inst);
2001
2002 Value *NewGep = Builder.CreatePtrAdd(
2003 PrevStore->getPointerOperand(), Builder.getInt(Offset), Prefix + "GEP");
2004 LLVM_DEBUG(dbgs() << "LSV: Extra GEP Created: \n" << *NewGep << "\n");
2005 NewElement =
2006 Builder.CreateAlignedStore(PoisonValue::get(Ty), NewGep, Alignment);
2007 }
2008
2009 // Attach all metadata to the new element.
2010 // propagateMetadataForVectorization will fold it into the final vector when
2011 // applicable.
2012 NewElement->copyMetadata(*Prev.Inst);
2013
2014 // Cache created elements for tracking and cleanup
2015 ExtraElements.insert(NewElement);
2016
2017 APInt NewOffsetFromLeader = Prev.OffsetFromLeader + Offset;
2018 LLVM_DEBUG(dbgs() << "LSV: Extra Element Created: \n"
2019 << *NewElement
2020 << " OffsetFromLeader: " << NewOffsetFromLeader << "\n");
2021 return ChainElem{NewElement, NewOffsetFromLeader};
2022}
2023
2024Value *Vectorizer::createMaskForExtraElements(const ArrayRef<ChainElem> C,
2025 FixedVectorType *VecTy) {
2026 // Start each mask element as false
2028 Builder.getInt1(false));
2029 // Iterate over the chain and set the corresponding mask element to true for
2030 // each element that is not an extra element.
2031 for (const ChainElem &E : C) {
2032 if (ExtraElements.contains(E.Inst))
2033 continue;
2034 unsigned EOffset =
2035 (E.OffsetFromLeader - C[0].OffsetFromLeader).getZExtValue();
2036 unsigned VecIdx =
2037 8 * EOffset / DL.getTypeSizeInBits(VecTy->getScalarType());
2038 if (FixedVectorType *VT =
2040 for (unsigned J = 0; J < VT->getNumElements(); ++J)
2041 MaskElts[VecIdx + J] = Builder.getInt1(true);
2042 else
2043 MaskElts[VecIdx] = Builder.getInt1(true);
2044 }
2045 return ConstantVector::get(MaskElts);
2046}
2047
2048void Vectorizer::deleteExtraElements() {
2049 for (auto *ExtraElement : ExtraElements) {
2050 if (isa<LoadInst>(ExtraElement)) {
2051 [[maybe_unused]] bool Deleted =
2053 assert(Deleted && "Extra Load should always be trivially dead");
2054 } else {
2055 // Unlike Extra Loads, Extra Stores won't be "dead", but should all be
2056 // deleted regardless. They will have either been combined into a masked
2057 // store, or will be left behind and need to be cleaned up.
2058 auto *PtrOperand = getLoadStorePointerOperand(ExtraElement);
2059 ExtraElement->eraseFromParent();
2061 }
2062 }
2063
2064 ExtraElements.clear();
2065}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(AttributeSet CallerAttrs, AttributeSet CalleeAttrs)
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
static bool checkNoWrapFlags(Instruction *I, bool Signed)
static bool checkIfSafeAddSequence(const APInt &IdxDiff, Instruction *AddOpA, unsigned MatchingOpIdxA, Instruction *AddOpB, unsigned MatchingOpIdxB, bool Signed)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
#define T
static bool isAddLike(const SDValue V)
static bool isInvariantLoad(const Instruction *I, const Value *Ptr, const bool IsKernelFn)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
Basic Register Allocator
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use, const MachineInstr *Insert, const WebAssemblyFunctionInfo &MFI, const MachineRegisterInfo &MRI, bool Optimize)
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition APInt.h:78
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:171
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
iterator end()
Definition DenseMap.h:686
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Legacy wrapper pass to provide the GlobalsAAResult object.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:446
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2408
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
An instruction for reading from memory.
bool isUnordered() const
bool isSimple() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Legacy wrapper pass to provide the SCEVAAResult object.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getCouldNotCompute()
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Value * getPointerOperand()
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isLegalToVectorizeLoad(LoadInst *LI) const
LLVM_ABI bool isLegalToVectorizeStore(StoreInst *SI) const
LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace, MaskKind MaskKind=VariableOrConstantMask) const
Return true if the target supports masked store.
LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace=0, Align Alignment=Align(1), unsigned *Fast=nullptr) const
Determine if the target supports unaligned memory accesses.
LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace, MaskKind MaskKind=VariableOrConstantMask) const
Return true if the target supports masked load.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
size_type size() const
Definition DenseSet.h:85
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
void push_front(reference Node)
Insert a node at the front; never copies.
void remove(reference N)
Remove a node by reference; never deletes.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto min_element(R &&Range)
Provide wrappers to std::min_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2094
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1608
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1769
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
LLVM_ABI Instruction * propagateMetadataForVectorization(Instruction *I, ArrayRef< Value * > VL)
Propagate metadata that can be preserved after vectorization from VL to I, retaining only information...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
TargetTransformInfo TTI
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82