LLVM 24.0.0git
SROA.cpp
Go to the documentation of this file.
1//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
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/// \file
9/// This transformation implements the well known scalar replacement of
10/// aggregates transformation. It tries to identify promotable elements of an
11/// aggregate alloca, and promote them to registers. It will also try to
12/// convert uses of an element (or set of elements) of an alloca into a vector
13/// or bitfield-style integer scalar if appropriate.
14///
15/// It works to do this with minimal slicing of the alloca so that regions
16/// which are merely transferred in and out of external memory remain unchanged
17/// and are not decomposed to scalar code.
18///
19/// Because this also performs alloca promotion, it can be thought of as also
20/// serving the purpose of SSA formation. The algorithm iterates on the
21/// function until all opportunities for promotion have been realized.
22///
23//===----------------------------------------------------------------------===//
24
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/MapVector.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SetVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringRef.h"
38#include "llvm/ADT/Twine.h"
39#include "llvm/ADT/iterator.h"
44#include "llvm/Analysis/Loads.h"
48#include "llvm/IR/BasicBlock.h"
49#include "llvm/IR/Constant.h"
51#include "llvm/IR/Constants.h"
52#include "llvm/IR/DIBuilder.h"
53#include "llvm/IR/DataLayout.h"
54#include "llvm/IR/DebugInfo.h"
57#include "llvm/IR/Dominators.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalAlias.h"
60#include "llvm/IR/IRBuilder.h"
61#include "llvm/IR/InstVisitor.h"
62#include "llvm/IR/Instruction.h"
65#include "llvm/IR/LLVMContext.h"
66#include "llvm/IR/Metadata.h"
67#include "llvm/IR/Module.h"
68#include "llvm/IR/Operator.h"
69#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
76#include "llvm/Pass.h"
80#include "llvm/Support/Debug.h"
88#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <cstring>
93#include <iterator>
94#include <string>
95#include <tuple>
96#include <utility>
97#include <variant>
98#include <vector>
99
100using namespace llvm;
101
102#define DEBUG_TYPE "sroa"
103
104STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
105STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
106STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
107STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
108STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
109STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
110STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
111STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
112STATISTIC(NumLoadsPredicated,
113 "Number of loads rewritten into predicated loads to allow promotion");
115 NumStoresPredicated,
116 "Number of stores rewritten into predicated loads to allow promotion");
117STATISTIC(NumDeleted, "Number of instructions deleted");
118STATISTIC(NumVectorized, "Number of vectorized aggregates");
119
120namespace llvm {
121/// Disable running mem2reg during SROA in order to test or debug SROA.
122static cl::opt<bool> SROASkipMem2Reg("sroa-skip-mem2reg", cl::init(false),
123 cl::Hidden);
125} // namespace llvm
126
127namespace {
128
129class AllocaSliceRewriter;
130class AllocaSlices;
131class Partition;
132
133class SelectHandSpeculativity {
134 unsigned char Storage = 0; // None are speculatable by default.
135 using TrueVal = Bitfield::Element<bool, 0, 1>; // Low 0'th bit.
136 using FalseVal = Bitfield::Element<bool, 1, 1>; // Low 1'th bit.
137public:
138 SelectHandSpeculativity() = default;
139 SelectHandSpeculativity &setAsSpeculatable(bool isTrueVal);
140 bool isSpeculatable(bool isTrueVal) const;
141 bool areAllSpeculatable() const;
142 bool areAnySpeculatable() const;
143 bool areNoneSpeculatable() const;
144 // For interop as int half of PointerIntPair.
145 explicit operator intptr_t() const { return static_cast<intptr_t>(Storage); }
146 explicit SelectHandSpeculativity(intptr_t Storage_) : Storage(Storage_) {}
147};
148static_assert(sizeof(SelectHandSpeculativity) == sizeof(unsigned char));
149
150using PossiblySpeculatableLoad =
152using UnspeculatableStore = StoreInst *;
153using RewriteableMemOp =
154 std::variant<PossiblySpeculatableLoad, UnspeculatableStore>;
155using RewriteableMemOps = SmallVector<RewriteableMemOp, 2>;
156
157/// An optimization pass providing Scalar Replacement of Aggregates.
158///
159/// This pass takes allocations which can be completely analyzed (that is, they
160/// don't escape) and tries to turn them into scalar SSA values. There are
161/// a few steps to this process.
162///
163/// 1) It takes allocations of aggregates and analyzes the ways in which they
164/// are used to try to split them into smaller allocations, ideally of
165/// a single scalar data type. It will split up memcpy and memset accesses
166/// as necessary and try to isolate individual scalar accesses.
167/// 2) It will transform accesses into forms which are suitable for SSA value
168/// promotion. This can be replacing a memset with a scalar store of an
169/// integer value, or it can involve speculating operations on a PHI or
170/// select to be a PHI or select of the results.
171/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
172/// onto insert and extract operations on a vector value, and convert them to
173/// this form. By doing so, it will enable promotion of vector aggregates to
174/// SSA vector values.
175class SROA {
176 LLVMContext *const C;
177 DomTreeUpdater *const DTU;
178 AssumptionCache *const AC;
179 const bool PreserveCFG;
180 const bool AggregateToVector;
181
182 /// Worklist of alloca instructions to simplify.
183 ///
184 /// Each alloca in the function is added to this. Each new alloca formed gets
185 /// added to it as well to recursively simplify unless that alloca can be
186 /// directly promoted. Finally, each time we rewrite a use of an alloca other
187 /// the one being actively rewritten, we add it back onto the list if not
188 /// already present to ensure it is re-visited.
189 SmallSetVector<AllocaInst *, 16> Worklist;
190
191 /// A collection of instructions to delete.
192 /// We try to batch deletions to simplify code and make things a bit more
193 /// efficient. We also make sure there is no dangling pointers.
194 SmallVector<WeakVH, 8> DeadInsts;
195
196 /// Post-promotion worklist.
197 ///
198 /// Sometimes we discover an alloca which has a high probability of becoming
199 /// viable for SROA after a round of promotion takes place. In those cases,
200 /// the alloca is enqueued here for re-processing.
201 ///
202 /// Note that we have to be very careful to clear allocas out of this list in
203 /// the event they are deleted.
204 SmallSetVector<AllocaInst *, 16> PostPromotionWorklist;
205
206 /// A collection of alloca instructions we can directly promote.
207 SetVector<AllocaInst *, SmallVector<AllocaInst *>,
208 SmallPtrSet<AllocaInst *, 16>, 16>
209 PromotableAllocas;
210
211 /// A worklist of PHIs to speculate prior to promoting allocas.
212 ///
213 /// All of these PHIs have been checked for the safety of speculation and by
214 /// being speculated will allow promoting allocas currently in the promotable
215 /// queue.
216 SmallSetVector<PHINode *, 8> SpeculatablePHIs;
217
218 /// A worklist of select instructions to rewrite prior to promoting
219 /// allocas.
220 SmallMapVector<SelectInst *, RewriteableMemOps, 8> SelectsToRewrite;
221
222 /// Select instructions that use an alloca and are subsequently loaded can be
223 /// rewritten to load both input pointers and then select between the result,
224 /// allowing the load of the alloca to be promoted.
225 /// From this:
226 /// %P2 = select i1 %cond, ptr %Alloca, ptr %Other
227 /// %V = load <type>, ptr %P2
228 /// to:
229 /// %V1 = load <type>, ptr %Alloca -> will be mem2reg'd
230 /// %V2 = load <type>, ptr %Other
231 /// %V = select i1 %cond, <type> %V1, <type> %V2
232 ///
233 /// We can do this to a select if its only uses are loads
234 /// and if either the operand to the select can be loaded unconditionally,
235 /// or if we are allowed to perform CFG modifications.
236 static std::optional<RewriteableMemOps>
237 isSafeSelectToSpeculate(SelectInst &SI, bool PreserveCFG);
238
239public:
240 SROA(LLVMContext *C, DomTreeUpdater *DTU, AssumptionCache *AC,
241 SROAOptions Options)
242 : C(C), DTU(DTU), AC(AC),
243 PreserveCFG(Options.CFG == SROAOptions::PreserveCFG),
244 AggregateToVector(Options.AggregateToVector) {}
245
246 /// Main run method used by both the SROAPass and by the legacy pass.
247 std::pair<bool /*Changed*/, bool /*CFGChanged*/> runSROA(Function &F);
248
249private:
250 friend class AllocaSliceRewriter;
251
252 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
253 std::pair<AllocaInst *, uint64_t>
254 rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &P);
255 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
256 bool propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS);
257 std::pair<bool /*Changed*/, bool /*CFGChanged*/> runOnAlloca(AllocaInst &AI);
258 void clobberUse(Use &U);
259 bool deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
260 bool promoteAllocas();
261};
262
263} // end anonymous namespace
264
265/// Calculate the fragment of a variable to use when slicing a store
266/// based on the slice dimensions, existing fragment, and base storage
267/// fragment.
268/// Results:
269/// UseFrag - Use Target as the new fragment.
270/// UseNoFrag - The new slice already covers the whole variable.
271/// Skip - The new alloca slice doesn't include this variable.
272/// FIXME: Can we use calculateFragmentIntersect instead?
273namespace {
274enum FragCalcResult { UseFrag, UseNoFrag, Skip };
275}
276static FragCalcResult
278 uint64_t NewStorageSliceOffsetInBits,
279 uint64_t NewStorageSliceSizeInBits,
280 std::optional<DIExpression::FragmentInfo> StorageFragment,
281 std::optional<DIExpression::FragmentInfo> CurrentFragment,
283 // If the base storage describes part of the variable apply the offset and
284 // the size constraint.
285 if (StorageFragment) {
286 Target.SizeInBits =
287 std::min(NewStorageSliceSizeInBits, StorageFragment->SizeInBits);
288 Target.OffsetInBits =
289 NewStorageSliceOffsetInBits + StorageFragment->OffsetInBits;
290 } else {
291 Target.SizeInBits = NewStorageSliceSizeInBits;
292 Target.OffsetInBits = NewStorageSliceOffsetInBits;
293 }
294
295 // If this slice extracts the entirety of an independent variable from a
296 // larger alloca, do not produce a fragment expression, as the variable is
297 // not fragmented.
298 if (!CurrentFragment) {
299 if (auto Size = Variable->getSizeInBits()) {
300 // Treat the current fragment as covering the whole variable.
301 CurrentFragment = DIExpression::FragmentInfo(*Size, 0);
302 if (Target == CurrentFragment)
303 return UseNoFrag;
304 }
305 }
306
307 // No additional work to do if there isn't a fragment already, or there is
308 // but it already exactly describes the new assignment.
309 if (!CurrentFragment || *CurrentFragment == Target)
310 return UseFrag;
311
312 // Reject the target fragment if it doesn't fit wholly within the current
313 // fragment. TODO: We could instead chop up the target to fit in the case of
314 // a partial overlap.
315 if (Target.startInBits() < CurrentFragment->startInBits() ||
316 Target.endInBits() > CurrentFragment->endInBits())
317 return Skip;
318
319 // Target fits within the current fragment, return it.
320 return UseFrag;
321}
322
324 return DebugVariable(DVR->getVariable(), std::nullopt,
325 DVR->getDebugLoc().getInlinedAt());
326}
327
328/// Find linked dbg.assign and generate a new one with the correct
329/// FragmentInfo. Link Inst to the new dbg.assign. If Value is nullptr the
330/// value component is copied from the old dbg.assign to the new.
331/// \param OldAlloca Alloca for the variable before splitting.
332/// \param IsSplit True if the store (not necessarily alloca)
333/// is being split.
334/// \param OldAllocaOffsetInBits Offset of the slice taken from OldAlloca.
335/// \param SliceSizeInBits New number of bits being written to.
336/// \param OldInst Instruction that is being split.
337/// \param Inst New instruction performing this part of the
338/// split store.
339/// \param Dest Store destination.
340/// \param Value Stored value.
341/// \param DL Datalayout.
342static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
343 uint64_t OldAllocaOffsetInBits,
344 uint64_t SliceSizeInBits, Instruction *OldInst,
345 Instruction *Inst, Value *Dest, Value *Value,
346 const DataLayout &DL) {
347 // If we want allocas to be migrated using this helper then we need to ensure
348 // that the BaseFragments map code still works. A simple solution would be
349 // to choose to always clone alloca dbg_assigns (rather than sometimes
350 // "stealing" them).
351 assert(!isa<AllocaInst>(Inst) && "Unexpected alloca");
352
353 auto DVRAssignMarkerRange = at::getDVRAssignmentMarkers(OldInst);
354 // Nothing to do if OldInst has no linked dbg.assign intrinsics.
355 if (DVRAssignMarkerRange.empty())
356 return;
357
358 LLVM_DEBUG(dbgs() << " migrateDebugInfo\n");
359 LLVM_DEBUG(dbgs() << " OldAlloca: " << *OldAlloca << "\n");
360 LLVM_DEBUG(dbgs() << " IsSplit: " << IsSplit << "\n");
361 LLVM_DEBUG(dbgs() << " OldAllocaOffsetInBits: " << OldAllocaOffsetInBits
362 << "\n");
363 LLVM_DEBUG(dbgs() << " SliceSizeInBits: " << SliceSizeInBits << "\n");
364 LLVM_DEBUG(dbgs() << " OldInst: " << *OldInst << "\n");
365 LLVM_DEBUG(dbgs() << " Inst: " << *Inst << "\n");
366 LLVM_DEBUG(dbgs() << " Dest: " << *Dest << "\n");
367 if (Value)
368 LLVM_DEBUG(dbgs() << " Value: " << *Value << "\n");
369
370 /// Map of aggregate variables to their fragment associated with OldAlloca.
372 BaseFragments;
373 for (auto *DVR : at::getDVRAssignmentMarkers(OldAlloca))
374 BaseFragments[getAggregateVariable(DVR)] =
375 DVR->getExpression()->getFragmentInfo();
376
377 // The new inst needs a DIAssignID unique metadata tag (if OldInst has
378 // one). It shouldn't already have one: assert this assumption.
379 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID));
380 DIAssignID *NewID = nullptr;
381 auto &Ctx = Inst->getContext();
382 DIBuilder DIB(*OldInst->getModule(), /*AllowUnresolved*/ false);
383 assert(OldAlloca->isStaticAlloca());
384
385 auto MigrateDbgAssign = [&](DbgVariableRecord *DbgAssign) {
386 LLVM_DEBUG(dbgs() << " existing dbg.assign is: " << *DbgAssign
387 << "\n");
388 auto *Expr = DbgAssign->getExpression();
389 bool SetKillLocation = false;
390
391 if (IsSplit) {
392 std::optional<DIExpression::FragmentInfo> BaseFragment;
393 {
394 auto R = BaseFragments.find(getAggregateVariable(DbgAssign));
395 if (R == BaseFragments.end())
396 return;
397 BaseFragment = R->second;
398 }
399 std::optional<DIExpression::FragmentInfo> CurrentFragment =
400 Expr->getFragmentInfo();
401 DIExpression::FragmentInfo NewFragment;
402 FragCalcResult Result = calculateFragment(
403 DbgAssign->getVariable(), OldAllocaOffsetInBits, SliceSizeInBits,
404 BaseFragment, CurrentFragment, NewFragment);
405
406 if (Result == Skip)
407 return;
408 if (Result == UseFrag && !(NewFragment == CurrentFragment)) {
409 if (CurrentFragment) {
410 // Rewrite NewFragment to be relative to the existing one (this is
411 // what createFragmentExpression wants). CalculateFragment has
412 // already resolved the size for us. FIXME: Should it return the
413 // relative fragment too?
414 NewFragment.OffsetInBits -= CurrentFragment->OffsetInBits;
415 }
416 // Add the new fragment info to the existing expression if possible.
418 Expr, NewFragment.OffsetInBits, NewFragment.SizeInBits)) {
419 Expr = *E;
420 } else {
421 // Otherwise, add the new fragment info to an empty expression and
422 // discard the value component of this dbg.assign as the value cannot
423 // be computed with the new fragment.
425 DIExpression::get(Expr->getContext(), {}),
426 NewFragment.OffsetInBits, NewFragment.SizeInBits);
427 SetKillLocation = true;
428 }
429 }
430 }
431
432 // If we haven't created a DIAssignID ID do that now and attach it to Inst.
433 if (!NewID) {
434 NewID = DIAssignID::getDistinct(Ctx);
435 Inst->setMetadata(LLVMContext::MD_DIAssignID, NewID);
436 }
437
438 DbgVariableRecord *NewAssign;
439 if (IsSplit) {
440 ::Value *NewValue = Value ? Value : DbgAssign->getValue();
442 Inst, NewValue, DbgAssign->getVariable(), Expr, Dest,
443 DIExpression::get(Expr->getContext(), {}), DbgAssign->getDebugLoc()));
444 } else {
445 // The store is not split, simply steal the existing dbg_assign.
446 NewAssign = DbgAssign;
447 NewAssign->setAssignId(NewID); // FIXME: Can we avoid generating new IDs?
448 NewAssign->setAddress(Dest);
449 if (Value)
450 NewAssign->replaceVariableLocationOp(0u, Value);
451 assert(Expr == NewAssign->getExpression());
452 }
453
454 // If we've updated the value but the original dbg.assign has an arglist
455 // then kill it now - we can't use the requested new value.
456 // We can't replace the DIArgList with the new value as it'd leave
457 // the DIExpression in an invalid state (DW_OP_LLVM_arg operands without
458 // an arglist). And we can't keep the DIArgList in case the linked store
459 // is being split - in which case the DIArgList + expression may no longer
460 // be computing the correct value.
461 // This should be a very rare situation as it requires the value being
462 // stored to differ from the dbg.assign (i.e., the value has been
463 // represented differently in the debug intrinsic for some reason).
464 SetKillLocation |=
465 Value && (DbgAssign->hasArgList() ||
466 !DbgAssign->getExpression()->isSingleLocationExpression());
467 if (SetKillLocation)
468 NewAssign->setKillLocation();
469
470 // We could use more precision here at the cost of some additional (code)
471 // complexity - if the original dbg.assign was adjacent to its store, we
472 // could position this new dbg.assign adjacent to its store rather than the
473 // old dbg.assgn. That would result in interleaved dbg.assigns rather than
474 // what we get now:
475 // split store !1
476 // split store !2
477 // dbg.assign !1
478 // dbg.assign !2
479 // This (current behaviour) results results in debug assignments being
480 // noted as slightly offset (in code) from the store. In practice this
481 // should have little effect on the debugging experience due to the fact
482 // that all the split stores should get the same line number.
483 if (NewAssign != DbgAssign) {
484 NewAssign->moveBefore(DbgAssign->getIterator());
485 NewAssign->setDebugLoc(DbgAssign->getDebugLoc());
486 }
487 LLVM_DEBUG(dbgs() << "Created new assign: " << *NewAssign << "\n");
488 };
489
490 for_each(DVRAssignMarkerRange, MigrateDbgAssign);
491}
492
493namespace {
494
495/// A custom IRBuilder inserter which prefixes all names, but only in
496/// Assert builds.
497class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter {
498 std::string Prefix;
499
500 Twine getNameWithPrefix(const Twine &Name) const {
501 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
502 }
503
504public:
505 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
506
507 void InsertHelper(Instruction *I, const Twine &Name,
508 BasicBlock::iterator InsertPt) const override {
509 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name),
510 InsertPt);
511 }
512};
513
514/// Provide a type for IRBuilder that drops names in release builds.
516
517/// A used slice of an alloca.
518///
519/// This structure represents a slice of an alloca used by some instruction. It
520/// stores both the begin and end offsets of this use, a pointer to the use
521/// itself, and a flag indicating whether we can classify the use as splittable
522/// or not when forming partitions of the alloca.
523class Slice {
524 /// The beginning offset of the range.
525 uint64_t BeginOffset = 0;
526
527 /// The ending offset, not included in the range.
528 uint64_t EndOffset = 0;
529
530 /// Storage for both the use of this slice and whether it can be
531 /// split.
532 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
533
534public:
535 Slice() = default;
536
537 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
538 : BeginOffset(BeginOffset), EndOffset(EndOffset),
539 UseAndIsSplittable(U, IsSplittable) {}
540
541 uint64_t beginOffset() const { return BeginOffset; }
542 uint64_t endOffset() const { return EndOffset; }
543
544 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
545 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
546
547 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
548
549 bool isDead() const { return getUse() == nullptr; }
550 void kill() { UseAndIsSplittable.setPointer(nullptr); }
551
552 /// Support for ordering ranges.
553 ///
554 /// This provides an ordering over ranges such that start offsets are
555 /// always increasing, and within equal start offsets, the end offsets are
556 /// decreasing. Thus the spanning range comes first in a cluster with the
557 /// same start position.
558 bool operator<(const Slice &RHS) const {
559 if (beginOffset() < RHS.beginOffset())
560 return true;
561 if (beginOffset() > RHS.beginOffset())
562 return false;
563 if (isSplittable() != RHS.isSplittable())
564 return !isSplittable();
565 if (endOffset() > RHS.endOffset())
566 return true;
567 return false;
568 }
569
570 /// Support comparison with a single offset to allow binary searches.
571 [[maybe_unused]] friend bool operator<(const Slice &LHS, uint64_t RHSOffset) {
572 return LHS.beginOffset() < RHSOffset;
573 }
574 [[maybe_unused]] friend bool operator<(uint64_t LHSOffset, const Slice &RHS) {
575 return LHSOffset < RHS.beginOffset();
576 }
577
578 bool operator==(const Slice &RHS) const {
579 return isSplittable() == RHS.isSplittable() &&
580 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
581 }
582 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
583};
584
585/// Representation of the alloca slices.
586///
587/// This class represents the slices of an alloca which are formed by its
588/// various uses. If a pointer escapes, we can't fully build a representation
589/// for the slices used and we reflect that in this structure. The uses are
590/// stored, sorted by increasing beginning offset and with unsplittable slices
591/// starting at a particular offset before splittable slices.
592class AllocaSlices {
593public:
594 /// Construct the slices of a particular alloca.
595 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
596
597 /// Test whether a pointer to the allocation escapes our analysis.
598 ///
599 /// If this is true, the slices are never fully built and should be
600 /// ignored.
601 bool isEscaped() const { return PointerEscapingInstr; }
602 bool isEscapedReadOnly() const { return PointerEscapingInstrReadOnly; }
603
604 /// Support for iterating over the slices.
605 /// @{
606 using iterator = SmallVectorImpl<Slice>::iterator;
607 using range = iterator_range<iterator>;
608
609 iterator begin() { return Slices.begin(); }
610 iterator end() { return Slices.end(); }
611
612 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
613 using const_range = iterator_range<const_iterator>;
614
615 const_iterator begin() const { return Slices.begin(); }
616 const_iterator end() const { return Slices.end(); }
617 /// @}
618
619 /// Erase a range of slices.
620 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
621
622 /// Insert new slices for this alloca.
623 ///
624 /// This moves the slices into the alloca's slices collection, and re-sorts
625 /// everything so that the usual ordering properties of the alloca's slices
626 /// hold.
627 void insert(ArrayRef<Slice> NewSlices) {
628 int OldSize = Slices.size();
629 Slices.append(NewSlices.begin(), NewSlices.end());
630 auto SliceI = Slices.begin() + OldSize;
631 std::stable_sort(SliceI, Slices.end());
632 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
633 }
634
635 // Forward declare the iterator and range accessor for walking the
636 // partitions.
637 class partition_iterator;
639
640 /// Access the dead users for this alloca.
641 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
642
643 /// Access Uses that should be dropped if the alloca is promotable.
644 ArrayRef<Use *> getDeadUsesIfPromotable() const {
645 return DeadUseIfPromotable;
646 }
647
648 /// Access the dead operands referring to this alloca.
649 ///
650 /// These are operands which have cannot actually be used to refer to the
651 /// alloca as they are outside its range and the user doesn't correct for
652 /// that. These mostly consist of PHI node inputs and the like which we just
653 /// need to replace with undef.
654 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
655
656#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
657 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
658 void printSlice(raw_ostream &OS, const_iterator I,
659 StringRef Indent = " ") const;
660 void printUse(raw_ostream &OS, const_iterator I,
661 StringRef Indent = " ") const;
662 void print(raw_ostream &OS) const;
663 void dump(const_iterator I) const;
664 void dump() const;
665#endif
666
667private:
668 template <typename DerivedT, typename RetT = void> class BuilderBase;
669 class SliceBuilder;
670
671 friend class AllocaSlices::SliceBuilder;
672
673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
674 /// Handle to alloca instruction to simplify method interfaces.
675 AllocaInst &AI;
676#endif
677
678 /// The instruction responsible for this alloca not having a known set
679 /// of slices.
680 ///
681 /// When an instruction (potentially) escapes the pointer to the alloca, we
682 /// store a pointer to that here and abort trying to form slices of the
683 /// alloca. This will be null if the alloca slices are analyzed successfully.
684 Instruction *PointerEscapingInstr;
685 Instruction *PointerEscapingInstrReadOnly;
686
687 /// The slices of the alloca.
688 ///
689 /// We store a vector of the slices formed by uses of the alloca here. This
690 /// vector is sorted by increasing begin offset, and then the unsplittable
691 /// slices before the splittable ones. See the Slice inner class for more
692 /// details.
694
695 /// Instructions which will become dead if we rewrite the alloca.
696 ///
697 /// Note that these are not separated by slice. This is because we expect an
698 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
699 /// all these instructions can simply be removed and replaced with poison as
700 /// they come from outside of the allocated space.
701 SmallVector<Instruction *, 8> DeadUsers;
702
703 /// Uses which will become dead if can promote the alloca.
704 SmallVector<Use *, 8> DeadUseIfPromotable;
705
706 /// Operands which will become dead if we rewrite the alloca.
707 ///
708 /// These are operands that in their particular use can be replaced with
709 /// poison when we rewrite the alloca. These show up in out-of-bounds inputs
710 /// to PHI nodes and the like. They aren't entirely dead (there might be
711 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
712 /// want to swap this particular input for poison to simplify the use lists of
713 /// the alloca.
714 SmallVector<Use *, 8> DeadOperands;
715};
716
717/// A partition of the slices.
718///
719/// An ephemeral representation for a range of slices which can be viewed as
720/// a partition of the alloca. This range represents a span of the alloca's
721/// memory which cannot be split, and provides access to all of the slices
722/// overlapping some part of the partition.
723///
724/// Objects of this type are produced by traversing the alloca's slices, but
725/// are only ephemeral and not persistent.
726class Partition {
727private:
728 friend class AllocaSlices;
729 friend class AllocaSlices::partition_iterator;
730
731 using iterator = AllocaSlices::iterator;
732
733 /// The beginning and ending offsets of the alloca for this
734 /// partition.
735 uint64_t BeginOffset = 0, EndOffset = 0;
736
737 /// The start and end iterators of this partition.
738 iterator SI, SJ;
739
740 /// A collection of split slice tails overlapping the partition.
741 SmallVector<Slice *, 4> SplitTails;
742
743 /// Raw constructor builds an empty partition starting and ending at
744 /// the given iterator.
745 Partition(iterator SI) : SI(SI), SJ(SI) {}
746
747public:
748 /// The start offset of this partition.
749 ///
750 /// All of the contained slices start at or after this offset.
751 uint64_t beginOffset() const { return BeginOffset; }
752
753 /// The end offset of this partition.
754 ///
755 /// All of the contained slices end at or before this offset.
756 uint64_t endOffset() const { return EndOffset; }
757
758 /// The size of the partition.
759 ///
760 /// Note that this can never be zero.
761 uint64_t size() const {
762 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
763 return EndOffset - BeginOffset;
764 }
765
766 /// Test whether this partition contains no slices, and merely spans
767 /// a region occupied by split slices.
768 bool empty() const { return SI == SJ; }
769
770 /// \name Iterate slices that start within the partition.
771 /// These may be splittable or unsplittable. They have a begin offset >= the
772 /// partition begin offset.
773 /// @{
774 // FIXME: We should probably define a "concat_iterator" helper and use that
775 // to stitch together pointee_iterators over the split tails and the
776 // contiguous iterators of the partition. That would give a much nicer
777 // interface here. We could then additionally expose filtered iterators for
778 // split, unsplit, and unsplittable splices based on the usage patterns.
779 iterator begin() const { return SI; }
780 iterator end() const { return SJ; }
781 /// @}
782
783 /// Get the sequence of split slice tails.
784 ///
785 /// These tails are of slices which start before this partition but are
786 /// split and overlap into the partition. We accumulate these while forming
787 /// partitions.
788 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
789};
790
791} // end anonymous namespace
792
793/// An iterator over partitions of the alloca's slices.
794///
795/// This iterator implements the core algorithm for partitioning the alloca's
796/// slices. It is a forward iterator as we don't support backtracking for
797/// efficiency reasons, and re-use a single storage area to maintain the
798/// current set of split slices.
799///
800/// It is templated on the slice iterator type to use so that it can operate
801/// with either const or non-const slice iterators.
803 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
804 Partition> {
805 friend class AllocaSlices;
806
807 /// Most of the state for walking the partitions is held in a class
808 /// with a nice interface for examining them.
809 Partition P;
810
811 /// We need to keep the end of the slices to know when to stop.
812 AllocaSlices::iterator SE;
813
814 /// We also need to keep track of the maximum split end offset seen.
815 /// FIXME: Do we really?
816 uint64_t MaxSplitSliceEndOffset = 0;
817
818 /// Sets the partition to be empty at given iterator, and sets the
819 /// end iterator.
820 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
821 : P(SI), SE(SE) {
822 // If not already at the end, advance our state to form the initial
823 // partition.
824 if (SI != SE)
825 advance();
826 }
827
828 /// Advance the iterator to the next partition.
829 ///
830 /// Requires that the iterator not be at the end of the slices.
831 void advance() {
832 assert((P.SI != SE || !P.SplitTails.empty()) &&
833 "Cannot advance past the end of the slices!");
834
835 // Clear out any split uses which have ended.
836 if (!P.SplitTails.empty()) {
837 if (P.EndOffset >= MaxSplitSliceEndOffset) {
838 // If we've finished all splits, this is easy.
839 P.SplitTails.clear();
840 MaxSplitSliceEndOffset = 0;
841 } else {
842 // Remove the uses which have ended in the prior partition. This
843 // cannot change the max split slice end because we just checked that
844 // the prior partition ended prior to that max.
845 llvm::erase_if(P.SplitTails,
846 [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
847 assert(llvm::any_of(P.SplitTails,
848 [&](Slice *S) {
849 return S->endOffset() == MaxSplitSliceEndOffset;
850 }) &&
851 "Could not find the current max split slice offset!");
852 assert(llvm::all_of(P.SplitTails,
853 [&](Slice *S) {
854 return S->endOffset() <= MaxSplitSliceEndOffset;
855 }) &&
856 "Max split slice end offset is not actually the max!");
857 }
858 }
859
860 // If P.SI is already at the end, then we've cleared the split tail and
861 // now have an end iterator.
862 if (P.SI == SE) {
863 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
864 return;
865 }
866
867 // If we had a non-empty partition previously, set up the state for
868 // subsequent partitions.
869 if (P.SI != P.SJ) {
870 // Accumulate all the splittable slices which started in the old
871 // partition into the split list.
872 for (Slice &S : P)
873 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
874 P.SplitTails.push_back(&S);
875 MaxSplitSliceEndOffset =
876 std::max(S.endOffset(), MaxSplitSliceEndOffset);
877 }
878
879 // Start from the end of the previous partition.
880 P.SI = P.SJ;
881
882 // If P.SI is now at the end, we at most have a tail of split slices.
883 if (P.SI == SE) {
884 P.BeginOffset = P.EndOffset;
885 P.EndOffset = MaxSplitSliceEndOffset;
886 return;
887 }
888
889 // If the we have split slices and the next slice is after a gap and is
890 // not splittable immediately form an empty partition for the split
891 // slices up until the next slice begins.
892 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
893 !P.SI->isSplittable()) {
894 P.BeginOffset = P.EndOffset;
895 P.EndOffset = P.SI->beginOffset();
896 return;
897 }
898 }
899
900 // OK, we need to consume new slices. Set the end offset based on the
901 // current slice, and step SJ past it. The beginning offset of the
902 // partition is the beginning offset of the next slice unless we have
903 // pre-existing split slices that are continuing, in which case we begin
904 // at the prior end offset.
905 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
906 P.EndOffset = P.SI->endOffset();
907 ++P.SJ;
908
909 // There are two strategies to form a partition based on whether the
910 // partition starts with an unsplittable slice or a splittable slice.
911 if (!P.SI->isSplittable()) {
912 // When we're forming an unsplittable region, it must always start at
913 // the first slice and will extend through its end.
914 assert(P.BeginOffset == P.SI->beginOffset());
915
916 // Form a partition including all of the overlapping slices with this
917 // unsplittable slice.
918 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
919 if (!P.SJ->isSplittable())
920 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
921 ++P.SJ;
922 }
923
924 // We have a partition across a set of overlapping unsplittable
925 // partitions.
926 return;
927 }
928
929 // If we're starting with a splittable slice, then we need to form
930 // a synthetic partition spanning it and any other overlapping splittable
931 // splices.
932 assert(P.SI->isSplittable() && "Forming a splittable partition!");
933
934 // Collect all of the overlapping splittable slices.
935 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
936 P.SJ->isSplittable()) {
937 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
938 ++P.SJ;
939 }
940
941 // Back upiP.EndOffset if we ended the span early when encountering an
942 // unsplittable slice. This synthesizes the early end offset of
943 // a partition spanning only splittable slices.
944 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
945 assert(!P.SJ->isSplittable());
946 P.EndOffset = P.SJ->beginOffset();
947 }
948 }
949
950public:
951 bool operator==(const partition_iterator &RHS) const {
952 assert(SE == RHS.SE &&
953 "End iterators don't match between compared partition iterators!");
954
955 // The observed positions of partitions is marked by the P.SI iterator and
956 // the emptiness of the split slices. The latter is only relevant when
957 // P.SI == SE, as the end iterator will additionally have an empty split
958 // slices list, but the prior may have the same P.SI and a tail of split
959 // slices.
960 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
961 assert(P.SJ == RHS.P.SJ &&
962 "Same set of slices formed two different sized partitions!");
963 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
964 "Same slice position with differently sized non-empty split "
965 "slice tails!");
966 return true;
967 }
968 return false;
969 }
970
971 partition_iterator &operator++() {
972 advance();
973 return *this;
974 }
975
976 Partition &operator*() { return P; }
977};
978
979/// A forward range over the partitions of the alloca's slices.
980///
981/// This accesses an iterator range over the partitions of the alloca's
982/// slices. It computes these partitions on the fly based on the overlapping
983/// offsets of the slices and the ability to split them. It will visit "empty"
984/// partitions to cover regions of the alloca only accessed via split
985/// slices.
986iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
987 return make_range(partition_iterator(begin(), end()),
988 partition_iterator(end(), end()));
989}
990
992 // If the condition being selected on is a constant or the same value is
993 // being selected between, fold the select. Yes this does (rarely) happen
994 // early on.
995 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
996 return SI.getOperand(1 + CI->isZero());
997 if (SI.getOperand(1) == SI.getOperand(2))
998 return SI.getOperand(1);
999
1000 return nullptr;
1001}
1002
1003/// A helper that folds a PHI node or a select.
1005 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1006 // If PN merges together the same value, return that value.
1007 return PN->hasConstantValue();
1008 }
1010}
1011
1012/// Builder for the alloca slices.
1013///
1014/// This class builds a set of alloca slices by recursively visiting the uses
1015/// of an alloca and making a slice for each load and store at each offset.
1016class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
1017 friend class PtrUseVisitor<SliceBuilder>;
1018 friend class InstVisitor<SliceBuilder>;
1019
1020 using Base = PtrUseVisitor<SliceBuilder>;
1021
1022 const uint64_t AllocSize;
1023 AllocaSlices &AS;
1024
1025 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
1027
1028 /// Set to de-duplicate dead instructions found in the use walk.
1029 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
1030
1031public:
1032 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
1034 AllocSize(AI.getAllocationSize(DL)->getFixedValue()), AS(AS) {}
1035
1036private:
1037 void markAsDead(Instruction &I) {
1038 if (VisitedDeadInsts.insert(&I).second)
1039 AS.DeadUsers.push_back(&I);
1040 }
1041
1042 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
1043 bool IsSplittable = false) {
1044 // Completely skip uses which have a zero size or start either before or
1045 // past the end of the allocation.
1046 if (Size == 0 || Offset.uge(AllocSize)) {
1047 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
1048 << Offset
1049 << " which has zero size or starts outside of the "
1050 << AllocSize << " byte alloca:\n"
1051 << " alloca: " << AS.AI << "\n"
1052 << " use: " << I << "\n");
1053 return markAsDead(I);
1054 }
1055
1056 uint64_t BeginOffset = Offset.getZExtValue();
1057 uint64_t EndOffset = BeginOffset + Size;
1058
1059 // Clamp the end offset to the end of the allocation. Note that this is
1060 // formulated to handle even the case where "BeginOffset + Size" overflows.
1061 // This may appear superficially to be something we could ignore entirely,
1062 // but that is not so! There may be widened loads or PHI-node uses where
1063 // some instructions are dead but not others. We can't completely ignore
1064 // them, and so have to record at least the information here.
1065 assert(AllocSize >= BeginOffset); // Established above.
1066 if (Size > AllocSize - BeginOffset) {
1067 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
1068 << Offset << " to remain within the " << AllocSize
1069 << " byte alloca:\n"
1070 << " alloca: " << AS.AI << "\n"
1071 << " use: " << I << "\n");
1072 EndOffset = AllocSize;
1073 }
1074
1075 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
1076 }
1077
1078 void visitBitCastInst(BitCastInst &BC) {
1079 if (BC.use_empty())
1080 return markAsDead(BC);
1081
1082 return Base::visitBitCastInst(BC);
1083 }
1084
1085 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
1086 if (ASC.use_empty())
1087 return markAsDead(ASC);
1088
1089 return Base::visitAddrSpaceCastInst(ASC);
1090 }
1091
1092 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1093 if (GEPI.use_empty())
1094 return markAsDead(GEPI);
1095
1096 return Base::visitGetElementPtrInst(GEPI);
1097 }
1098
1099 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
1100 uint64_t Size, bool IsVolatile) {
1101 // We allow splitting of non-volatile loads and stores where the type is an
1102 // integer type. These may be used to implement 'memcpy' or other "transfer
1103 // of bits" patterns.
1104 bool IsSplittable =
1105 Ty->isIntegerTy() && !IsVolatile && DL.typeSizeEqualsStoreSize(Ty);
1106
1107 insertUse(I, Offset, Size, IsSplittable);
1108 }
1109
1110 void visitLoadInst(LoadInst &LI) {
1111 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
1112 "All simple FCA loads should have been pre-split");
1113
1114 // If there is a load with an unknown offset, we can still perform store
1115 // to load forwarding for other known-offset loads.
1116 if (!IsOffsetKnown)
1117 return PI.setEscapedReadOnly(&LI);
1118
1119 TypeSize Size = DL.getTypeStoreSize(LI.getType());
1120 if (Size.isScalable()) {
1121 unsigned VScale = LI.getFunction()->getVScaleValue();
1122 if (!VScale)
1123 return PI.setAborted(&LI);
1124
1125 Size = TypeSize::getFixed(Size.getKnownMinValue() * VScale);
1126 }
1127
1128 return handleLoadOrStore(LI.getType(), LI, Offset, Size.getFixedValue(),
1129 LI.isVolatile());
1130 }
1131
1132 void visitStoreInst(StoreInst &SI) {
1133 Value *ValOp = SI.getValueOperand();
1134 if (ValOp == *U)
1135 return PI.setEscapedAndAborted(&SI);
1136 if (!IsOffsetKnown)
1137 return PI.setAborted(&SI);
1138
1139 TypeSize StoreSize = DL.getTypeStoreSize(ValOp->getType());
1140 if (StoreSize.isScalable()) {
1141 unsigned VScale = SI.getFunction()->getVScaleValue();
1142 if (!VScale)
1143 return PI.setAborted(&SI);
1144
1145 StoreSize = TypeSize::getFixed(StoreSize.getKnownMinValue() * VScale);
1146 }
1147
1148 uint64_t Size = StoreSize.getFixedValue();
1149
1150 // If this memory access can be shown to *statically* extend outside the
1151 // bounds of the allocation, it's behavior is undefined, so simply
1152 // ignore it. Note that this is more strict than the generic clamping
1153 // behavior of insertUse. We also try to handle cases which might run the
1154 // risk of overflow.
1155 // FIXME: We should instead consider the pointer to have escaped if this
1156 // function is being instrumented for addressing bugs or race conditions.
1157 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
1158 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
1159 << Offset << " which extends past the end of the "
1160 << AllocSize << " byte alloca:\n"
1161 << " alloca: " << AS.AI << "\n"
1162 << " use: " << SI << "\n");
1163 return markAsDead(SI);
1164 }
1165
1166 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
1167 "All simple FCA stores should have been pre-split");
1168 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
1169 }
1170
1171 void visitMemSetInst(MemSetInst &II) {
1172 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
1173 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
1174 if ((Length && Length->getValue() == 0) ||
1175 (IsOffsetKnown && Offset.uge(AllocSize)))
1176 // Zero-length mem transfer intrinsics can be ignored entirely.
1177 return markAsDead(II);
1178
1179 if (!IsOffsetKnown)
1180 return PI.setAborted(&II);
1181
1182 insertUse(II, Offset,
1183 Length ? Length->getLimitedValue()
1184 : AllocSize - Offset.getLimitedValue(),
1185 (bool)Length);
1186 }
1187
1188 void visitMemTransferInst(MemTransferInst &II) {
1189 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
1190 if (Length && Length->getValue() == 0)
1191 // Zero-length mem transfer intrinsics can be ignored entirely.
1192 return markAsDead(II);
1193
1194 // Because we can visit these intrinsics twice, also check to see if the
1195 // first time marked this instruction as dead. If so, skip it.
1196 if (VisitedDeadInsts.count(&II))
1197 return;
1198
1199 if (!IsOffsetKnown)
1200 return PI.setAborted(&II);
1201
1202 // This side of the transfer is completely out-of-bounds, and so we can
1203 // nuke the entire transfer. However, we also need to nuke the other side
1204 // if already added to our partitions.
1205 // FIXME: Yet another place we really should bypass this when
1206 // instrumenting for ASan.
1207 if (Offset.uge(AllocSize)) {
1208 auto MTPI = MemTransferSliceMap.find(&II);
1209 if (MTPI != MemTransferSliceMap.end())
1210 AS.Slices[MTPI->second].kill();
1211 return markAsDead(II);
1212 }
1213
1214 uint64_t RawOffset = Offset.getLimitedValue();
1215 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
1216
1217 // Check for the special case where the same exact value is used for both
1218 // source and dest.
1219 if (*U == II.getRawDest() && *U == II.getRawSource()) {
1220 // For non-volatile transfers this is a no-op.
1221 if (!II.isVolatile())
1222 return markAsDead(II);
1223
1224 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
1225 }
1226
1227 // If we have seen both source and destination for a mem transfer, then
1228 // they both point to the same alloca.
1229 bool Inserted;
1230 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
1231 std::tie(MTPI, Inserted) =
1232 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
1233 unsigned PrevIdx = MTPI->second;
1234 if (!Inserted) {
1235 Slice &PrevP = AS.Slices[PrevIdx];
1236
1237 // Check if the begin offsets match and this is a non-volatile transfer.
1238 // In that case, we can completely elide the transfer.
1239 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
1240 PrevP.kill();
1241 return markAsDead(II);
1242 }
1243
1244 // Otherwise we have an offset transfer within the same alloca. We can't
1245 // split those.
1246 PrevP.makeUnsplittable();
1247 }
1248
1249 // Insert the use now that we've fixed up the splittable nature.
1250 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
1251
1252 // Check that we ended up with a valid index in the map.
1253 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
1254 "Map index doesn't point back to a slice with this user.");
1255 }
1256
1257 // Disable SRoA for any intrinsics except for lifetime invariants.
1258 // FIXME: What about debug intrinsics? This matches old behavior, but
1259 // doesn't make sense.
1260 void visitIntrinsicInst(IntrinsicInst &II) {
1261 if (II.isDroppable()) {
1262 AS.DeadUseIfPromotable.push_back(U);
1263 return;
1264 }
1265
1266 if (!IsOffsetKnown)
1267 return PI.setAborted(&II);
1268
1269 if (II.isLifetimeStartOrEnd()) {
1270 insertUse(II, Offset, AllocSize, true);
1271 return;
1272 }
1273
1274 Base::visitIntrinsicInst(II);
1275 }
1276
1277 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
1278 // We consider any PHI or select that results in a direct load or store of
1279 // the same offset to be a viable use for slicing purposes. These uses
1280 // are considered unsplittable and the size is the maximum loaded or stored
1281 // size.
1282 SmallPtrSet<Instruction *, 4> Visited;
1284 Visited.insert(Root);
1285 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
1286 const DataLayout &DL = Root->getDataLayout();
1287 // If there are no loads or stores, the access is dead. We mark that as
1288 // a size zero access.
1289 Size = 0;
1290 do {
1291 Instruction *I, *UsedI;
1292 std::tie(UsedI, I) = Uses.pop_back_val();
1293
1294 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1295 TypeSize LoadSize = DL.getTypeStoreSize(LI->getType());
1296 if (LoadSize.isScalable()) {
1297 PI.setAborted(LI);
1298 return nullptr;
1299 }
1300 Size = std::max(Size, LoadSize.getFixedValue());
1301 continue;
1302 }
1303 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1304 Value *Op = SI->getOperand(0);
1305 if (Op == UsedI)
1306 return SI;
1307 TypeSize StoreSize = DL.getTypeStoreSize(Op->getType());
1308 if (StoreSize.isScalable()) {
1309 PI.setAborted(SI);
1310 return nullptr;
1311 }
1312 Size = std::max(Size, StoreSize.getFixedValue());
1313 continue;
1314 }
1315
1316 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
1317 if (!GEP->hasAllZeroIndices())
1318 return GEP;
1319 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
1321 return I;
1322 }
1323
1324 for (User *U : I->users())
1325 if (Visited.insert(cast<Instruction>(U)).second)
1326 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
1327 } while (!Uses.empty());
1328
1329 return nullptr;
1330 }
1331
1332 void visitPHINodeOrSelectInst(Instruction &I) {
1334 if (I.use_empty())
1335 return markAsDead(I);
1336
1337 // If this is a PHI node before a catchswitch, we cannot insert any non-PHI
1338 // instructions in this BB, which may be required during rewriting. Bail out
1339 // on these cases.
1340 if (isa<PHINode>(I) && !I.getParent()->hasInsertionPt())
1341 return PI.setAborted(&I);
1342
1343 // TODO: We could use simplifyInstruction here to fold PHINodes and
1344 // SelectInsts. However, doing so requires to change the current
1345 // dead-operand-tracking mechanism. For instance, suppose neither loading
1346 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
1347 // trap either. However, if we simply replace %U with undef using the
1348 // current dead-operand-tracking mechanism, "load (select undef, undef,
1349 // %other)" may trap because the select may return the first operand
1350 // "undef".
1351 if (Value *Result = foldPHINodeOrSelectInst(I)) {
1352 if (Result == *U)
1353 // If the result of the constant fold will be the pointer, recurse
1354 // through the PHI/select as if we had RAUW'ed it.
1355 enqueueUsers(I);
1356 else
1357 // Otherwise the operand to the PHI/select is dead, and we can replace
1358 // it with poison.
1359 AS.DeadOperands.push_back(U);
1360
1361 return;
1362 }
1363
1364 if (!IsOffsetKnown)
1365 return PI.setAborted(&I);
1366
1367 // See if we already have computed info on this node.
1368 uint64_t &Size = PHIOrSelectSizes[&I];
1369 if (!Size) {
1370 // This is a new PHI/Select, check for an unsafe use of it.
1371 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1372 return PI.setAborted(UnsafeI);
1373 }
1374
1375 // For PHI and select operands outside the alloca, we can't nuke the entire
1376 // phi or select -- the other side might still be relevant, so we special
1377 // case them here and use a separate structure to track the operands
1378 // themselves which should be replaced with poison.
1379 // FIXME: This should instead be escaped in the event we're instrumenting
1380 // for address sanitization.
1381 if (Offset.uge(AllocSize)) {
1382 AS.DeadOperands.push_back(U);
1383 return;
1384 }
1385
1386 insertUse(I, Offset, Size);
1387 }
1388
1389 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1390
1391 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1392
1393 /// Disable SROA entirely if there are unhandled users of the alloca.
1394 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1395
1396 void visitCallBase(CallBase &CB) {
1397 // If the call operand is read-only and only does a read-only or address
1398 // capture, then we mark it as EscapedReadOnly.
1399 if (CB.isDataOperand(U) &&
1400 !capturesFullProvenance(CB.getCaptureInfo(U->getOperandNo())) &&
1401 CB.onlyReadsMemory(U->getOperandNo())) {
1402 PI.setEscapedReadOnly(&CB);
1403 return;
1404 }
1405
1406 Base::visitCallBase(CB);
1407 }
1408};
1409
1410AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1411 :
1412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1413 AI(AI),
1414#endif
1415 PointerEscapingInstr(nullptr), PointerEscapingInstrReadOnly(nullptr) {
1416 SliceBuilder PB(DL, AI, *this);
1417 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1418 if (PtrI.isEscaped() || PtrI.isAborted()) {
1419 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1420 // possibly by just storing the PtrInfo in the AllocaSlices.
1421 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1422 : PtrI.getAbortingInst();
1423 assert(PointerEscapingInstr && "Did not track a bad instruction");
1424 return;
1425 }
1426 PointerEscapingInstrReadOnly = PtrI.getEscapedReadOnlyInst();
1427
1428 llvm::erase_if(Slices, [](const Slice &S) { return S.isDead(); });
1429
1430 // Sort the uses. This arranges for the offsets to be in ascending order,
1431 // and the sizes to be in descending order.
1432 llvm::stable_sort(Slices);
1433}
1434
1435#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1436
1437void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1438 StringRef Indent) const {
1439 printSlice(OS, I, Indent);
1440 OS << "\n";
1441 printUse(OS, I, Indent);
1442}
1443
1444void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1445 StringRef Indent) const {
1446 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1447 << " slice #" << (I - begin())
1448 << (I->isSplittable() ? " (splittable)" : "");
1449}
1450
1451void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1452 StringRef Indent) const {
1453 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1454}
1455
1456void AllocaSlices::print(raw_ostream &OS) const {
1457 if (PointerEscapingInstr) {
1458 OS << "Can't analyze slices for alloca: " << AI << "\n"
1459 << " A pointer to this alloca escaped by:\n"
1460 << " " << *PointerEscapingInstr << "\n";
1461 return;
1462 }
1463
1464 if (PointerEscapingInstrReadOnly)
1465 OS << "Escapes into ReadOnly: " << *PointerEscapingInstrReadOnly << "\n";
1466
1467 OS << "Slices of alloca: " << AI << "\n";
1468 for (const_iterator I = begin(), E = end(); I != E; ++I)
1469 print(OS, I);
1470}
1471
1472LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1473 print(dbgs(), I);
1474}
1475LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1476
1477#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1478
1479/// Find a common load/store type used through a pointer PHI or select.
1480///
1481/// Look through a PHI or select to see if all of its users are loads or stores
1482/// of one common type. Whether those accesses can be speculated does not affect
1483/// the type they use and is checked separately when attempting promotion.
1485 assert((isa<PHINode, SelectInst>(I)) && "expected a PHI or select");
1486 Type *Ty = nullptr;
1487
1488 for (User *U : I.users()) {
1489 Type *UserTy = nullptr;
1490 if (auto *LI = dyn_cast<LoadInst>(U))
1491 UserTy = LI->getType();
1492 else if (auto *Store = dyn_cast<StoreInst>(U))
1493 // Slice building rejects stores of the PHI-or-select-derived pointer, so
1494 // it must be the store's pointer operand here.
1495 UserTy = Store->getValueOperand()->getType();
1496
1497 if (!UserTy || (Ty && Ty != UserTy))
1498 return nullptr;
1499 Ty = UserTy;
1500 }
1501
1502 return Ty;
1503}
1504
1505/// Walk the range of a partitioning looking for a common type to cover this
1506/// sequence of slices.
1507static std::pair<Type *, IntegerType *>
1508findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
1509 uint64_t EndOffset) {
1510 Type *Ty = nullptr;
1511 bool TyIsCommon = true;
1512 IntegerType *ITy = nullptr;
1513
1514 // Note that we need to look at *every* alloca slice's Use to ensure we
1515 // always get consistent results regardless of the order of slices.
1516 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1517 Use *U = I->getUse();
1518 if (isa<IntrinsicInst>(*U->getUser()))
1519 continue;
1520 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1521 continue;
1522
1523 Type *UserTy = nullptr;
1524 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1525 UserTy = LI->getType();
1526 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1527 UserTy = SI->getValueOperand()->getType();
1528 } else if (isa<PHINode, SelectInst>(U->getUser())) {
1529 UserTy =
1531 }
1532
1533 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1534 // If the type is larger than the partition, skip it. We only encounter
1535 // this for split integer operations where we want to use the type of the
1536 // entity causing the split. Also skip if the type is not a byte width
1537 // multiple.
1538 if (UserITy->getBitWidth() % 8 != 0 ||
1539 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1540 continue;
1541
1542 // Track the largest bitwidth integer type used in this way in case there
1543 // is no common type.
1544 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1545 ITy = UserITy;
1546 }
1547
1548 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1549 // depend on types skipped above.
1550 if (!UserTy || (Ty && Ty != UserTy))
1551 TyIsCommon = false; // Give up on anything but an iN type.
1552 else
1553 Ty = UserTy;
1554 }
1555
1556 return {TyIsCommon ? Ty : nullptr, ITy};
1557}
1558
1559/// PHI instructions that use an alloca and are subsequently loaded can be
1560/// rewritten to load both input pointers in the pred blocks and then PHI the
1561/// results, allowing the load of the alloca to be promoted.
1562/// From this:
1563/// %P2 = phi [i32* %Alloca, i32* %Other]
1564/// %V = load i32* %P2
1565/// to:
1566/// %V1 = load i32* %Alloca -> will be mem2reg'd
1567/// ...
1568/// %V2 = load i32* %Other
1569/// ...
1570/// %V = phi [i32 %V1, i32 %V2]
1571///
1572/// We can do this to a select if its only uses are loads and if the operands
1573/// to the select can be loaded unconditionally.
1574///
1575/// FIXME: This should be hoisted into a generic utility, likely in
1576/// Transforms/Util/Local.h
1578 const DataLayout &DL = PN.getDataLayout();
1579
1580 // For now, we can only do this promotion if the load is in the same block
1581 // as the PHI, and if there are no stores between the phi and load.
1582 // TODO: Allow recursive phi users.
1583 // TODO: Allow stores.
1584 BasicBlock *BB = PN.getParent();
1585 Align MaxAlign;
1586 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1587 Type *LoadType = nullptr;
1588 for (User *U : PN.users()) {
1590 if (!LI || !LI->isSimple())
1591 return false;
1592
1593 // For now we only allow loads in the same block as the PHI. This is
1594 // a common case that happens when instcombine merges two loads through
1595 // a PHI.
1596 if (LI->getParent() != BB)
1597 return false;
1598
1599 if (LoadType) {
1600 if (LoadType != LI->getType())
1601 return false;
1602 } else {
1603 LoadType = LI->getType();
1604 }
1605
1606 // Ensure that there are no instructions between the PHI and the load that
1607 // could store.
1608 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1609 if (BBI->mayWriteToMemory())
1610 return false;
1611
1612 MaxAlign = std::max(MaxAlign, LI->getAlign());
1613 }
1614
1615 if (!LoadType)
1616 return false;
1617
1618 APInt LoadSize =
1619 APInt(APWidth, DL.getTypeStoreSize(LoadType).getFixedValue());
1620
1621 // We can only transform this if it is safe to push the loads into the
1622 // predecessor blocks. The only thing to watch out for is that we can't put
1623 // a possibly trapping load in the predecessor if it is a critical edge.
1624 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1626 Value *InVal = PN.getIncomingValue(Idx);
1627
1628 // If the value is produced by the terminator of the predecessor (an
1629 // invoke) or it has side-effects, there is no valid place to put a load
1630 // in the predecessor.
1631 if (TI == InVal || TI->mayHaveSideEffects())
1632 return false;
1633
1634 // If the predecessor has a single successor, then the edge isn't
1635 // critical.
1636 if (TI->getNumSuccessors() == 1)
1637 continue;
1638
1639 // If this pointer is always safe to load, or if we can prove that there
1640 // is already a load in the block, then we can move the load to the pred
1641 // block.
1642 if (isSafeToLoadUnconditionally(InVal, MaxAlign, LoadSize,
1643 SimplifyQuery(DL, TI)))
1644 continue;
1645
1646 return false;
1647 }
1648
1649 return true;
1650}
1651
1652static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN) {
1653 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
1654
1655 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1656 Type *LoadTy = SomeLoad->getType();
1657 IRB.SetInsertPoint(&PN);
1658 PHINode *NewPN = IRB.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1659 PN.getName() + ".sroa.speculated");
1660
1661 // Get the AA tags and alignment to use from one of the loads. It does not
1662 // matter which one we get and if any differ.
1663 AAMDNodes AATags = SomeLoad->getAAMetadata();
1664 Align Alignment = SomeLoad->getAlign();
1665
1666 // Rewrite all loads of the PN to use the new PHI.
1667 while (!PN.use_empty()) {
1668 LoadInst *LI = cast<LoadInst>(PN.user_back());
1669 LI->replaceAllUsesWith(NewPN);
1670 LI->eraseFromParent();
1671 }
1672
1673 // Inject loads into all of the pred blocks.
1674 DenseMap<BasicBlock *, Value *> InjectedLoads;
1675 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1676 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1677 Value *InVal = PN.getIncomingValue(Idx);
1678
1679 // A PHI node is allowed to have multiple (duplicated) entries for the same
1680 // basic block, as long as the value is the same. So if we already injected
1681 // a load in the predecessor, then we should reuse the same load for all
1682 // duplicated entries.
1683 if (Value *V = InjectedLoads.lookup(Pred)) {
1684 NewPN->addIncoming(V, Pred);
1685 continue;
1686 }
1687
1688 Instruction *TI = Pred->getTerminator();
1689 IRB.SetInsertPoint(TI);
1690
1691 LoadInst *Load = IRB.CreateAlignedLoad(
1692 LoadTy, InVal, Alignment,
1693 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1694 ++NumLoadsSpeculated;
1695 if (AATags)
1696 Load->setAAMetadata(AATags);
1697 NewPN->addIncoming(Load, Pred);
1698 InjectedLoads[Pred] = Load;
1699 }
1700
1701 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1702 PN.eraseFromParent();
1703}
1704
1705SelectHandSpeculativity &
1706SelectHandSpeculativity::setAsSpeculatable(bool isTrueVal) {
1707 if (isTrueVal)
1709 else
1711 return *this;
1712}
1713
1714bool SelectHandSpeculativity::isSpeculatable(bool isTrueVal) const {
1715 return isTrueVal ? Bitfield::get<SelectHandSpeculativity::TrueVal>(Storage)
1716 : Bitfield::get<SelectHandSpeculativity::FalseVal>(Storage);
1717}
1718
1719bool SelectHandSpeculativity::areAllSpeculatable() const {
1720 return isSpeculatable(/*isTrueVal=*/true) &&
1721 isSpeculatable(/*isTrueVal=*/false);
1722}
1723
1724bool SelectHandSpeculativity::areAnySpeculatable() const {
1725 return isSpeculatable(/*isTrueVal=*/true) ||
1726 isSpeculatable(/*isTrueVal=*/false);
1727}
1728bool SelectHandSpeculativity::areNoneSpeculatable() const {
1729 return !areAnySpeculatable();
1730}
1731
1732static SelectHandSpeculativity
1734 assert(LI.isSimple() && "Only for simple loads");
1735 SelectHandSpeculativity Spec;
1736
1737 const DataLayout &DL = SI.getDataLayout();
1738 for (Value *Value : {SI.getTrueValue(), SI.getFalseValue()})
1740 SimplifyQuery(DL, &LI)))
1741 Spec.setAsSpeculatable(/*isTrueVal=*/Value == SI.getTrueValue());
1742 else if (PreserveCFG)
1743 return Spec;
1744
1745 return Spec;
1746}
1747
1748std::optional<RewriteableMemOps>
1749SROA::isSafeSelectToSpeculate(SelectInst &SI, bool PreserveCFG) {
1750 RewriteableMemOps Ops;
1751
1752 for (User *U : SI.users()) {
1753 if (auto *Store = dyn_cast<StoreInst>(U)) {
1754 // Note that atomic stores can be transformed; atomic semantics do not
1755 // have any meaning for a local alloca. Stores are not speculatable,
1756 // however, so if we can't turn it into a predicated store, we are done.
1757 if (Store->isVolatile() || PreserveCFG)
1758 return {}; // Give up on this `select`.
1759 Ops.emplace_back(Store);
1760 continue;
1761 }
1762
1763 auto *LI = dyn_cast<LoadInst>(U);
1764
1765 // Note that atomic loads can be transformed;
1766 // atomic semantics do not have any meaning for a local alloca.
1767 if (!LI || LI->isVolatile())
1768 return {}; // Give up on this `select`.
1769
1770 PossiblySpeculatableLoad Load(LI);
1771 if (!LI->isSimple()) {
1772 // If the `load` is not simple, we can't speculatively execute it,
1773 // but we could handle this via a CFG modification. But can we?
1774 if (PreserveCFG)
1775 return {}; // Give up on this `select`.
1776 Ops.emplace_back(Load);
1777 continue;
1778 }
1779
1780 SelectHandSpeculativity Spec =
1781 isSafeLoadOfSelectToSpeculate(*LI, SI, PreserveCFG);
1782 if (PreserveCFG && !Spec.areAllSpeculatable())
1783 return {}; // Give up on this `select`.
1784
1785 Load.setInt(Spec);
1786 Ops.emplace_back(Load);
1787 }
1788
1789 return Ops;
1790}
1791
1793 IRBuilderTy &IRB) {
1794 LLVM_DEBUG(dbgs() << " original load: " << SI << "\n");
1795
1796 Value *TV = SI.getTrueValue();
1797 Value *FV = SI.getFalseValue();
1798 // Replace the given load of the select with a select of two loads.
1799
1800 assert(LI.isSimple() && "We only speculate simple loads");
1801
1802 IRB.SetInsertPoint(&LI);
1803
1804 LoadInst *TL =
1805 IRB.CreateAlignedLoad(LI.getType(), TV, LI.getAlign(),
1806 LI.getName() + ".sroa.speculate.load.true");
1807 LoadInst *FL =
1808 IRB.CreateAlignedLoad(LI.getType(), FV, LI.getAlign(),
1809 LI.getName() + ".sroa.speculate.load.false");
1810 NumLoadsSpeculated += 2;
1811
1812 // Transfer alignment and AA info if present.
1813 TL->setAlignment(LI.getAlign());
1814 FL->setAlignment(LI.getAlign());
1815
1816 AAMDNodes Tags = LI.getAAMetadata();
1817 if (Tags) {
1818 TL->setAAMetadata(Tags);
1819 FL->setAAMetadata(Tags);
1820 }
1821
1822 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1823 LI.getName() + ".sroa.speculated",
1824 ProfcheckDisableMetadataFixes ? nullptr : &SI);
1825
1826 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
1827 LI.replaceAllUsesWith(V);
1828}
1829
1830template <typename T>
1832 SelectHandSpeculativity Spec,
1833 DomTreeUpdater &DTU) {
1834 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Only for load and store!");
1835 LLVM_DEBUG(dbgs() << " original mem op: " << I << "\n");
1836 BasicBlock *Head = I.getParent();
1837 Instruction *ThenTerm = nullptr;
1838 Instruction *ElseTerm = nullptr;
1839 if (Spec.areNoneSpeculatable())
1840 SplitBlockAndInsertIfThenElse(SI.getCondition(), &I, &ThenTerm, &ElseTerm,
1841 SI.getMetadata(LLVMContext::MD_prof), &DTU);
1842 else {
1843 SplitBlockAndInsertIfThen(SI.getCondition(), &I, /*Unreachable=*/false,
1844 SI.getMetadata(LLVMContext::MD_prof), &DTU,
1845 /*LI=*/nullptr, /*ThenBlock=*/nullptr);
1846 if (Spec.isSpeculatable(/*isTrueVal=*/true))
1847 cast<CondBrInst>(Head->getTerminator())->swapSuccessors();
1848 }
1849 auto *HeadBI = cast<CondBrInst>(Head->getTerminator());
1850 Spec = {}; // Do not use `Spec` beyond this point.
1851 BasicBlock *Tail = I.getParent();
1852 Tail->setName(Head->getName() + ".cont");
1853 PHINode *PN;
1854 if (isa<LoadInst>(I))
1855 PN = PHINode::Create(I.getType(), 2, "", I.getIterator());
1856 for (BasicBlock *SuccBB : successors(Head)) {
1857 bool IsThen = SuccBB == HeadBI->getSuccessor(0);
1858 int SuccIdx = IsThen ? 0 : 1;
1859 auto *NewMemOpBB = SuccBB == Tail ? Head : SuccBB;
1860 auto &CondMemOp = cast<T>(*I.clone());
1861 if (NewMemOpBB != Head) {
1862 NewMemOpBB->setName(Head->getName() + (IsThen ? ".then" : ".else"));
1863 if (isa<LoadInst>(I))
1864 ++NumLoadsPredicated;
1865 else
1866 ++NumStoresPredicated;
1867 } else {
1868 CondMemOp.dropUBImplyingAttrsAndMetadata();
1869 ++NumLoadsSpeculated;
1870 }
1871 CondMemOp.insertBefore(NewMemOpBB->getTerminator()->getIterator());
1872 Value *Ptr = SI.getOperand(1 + SuccIdx);
1873 CondMemOp.setOperand(I.getPointerOperandIndex(), Ptr);
1874 if (isa<LoadInst>(I)) {
1875 CondMemOp.setName(I.getName() + (IsThen ? ".then" : ".else") + ".val");
1876 PN->addIncoming(&CondMemOp, NewMemOpBB);
1877 } else
1878 LLVM_DEBUG(dbgs() << " to: " << CondMemOp << "\n");
1879 }
1880 if (isa<LoadInst>(I)) {
1881 PN->takeName(&I);
1882 LLVM_DEBUG(dbgs() << " to: " << *PN << "\n");
1883 I.replaceAllUsesWith(PN);
1884 }
1885}
1886
1888 SelectHandSpeculativity Spec,
1889 DomTreeUpdater &DTU) {
1890 if (auto *LI = dyn_cast<LoadInst>(&I))
1891 rewriteMemOpOfSelect(SelInst, *LI, Spec, DTU);
1892 else if (auto *SI = dyn_cast<StoreInst>(&I))
1893 rewriteMemOpOfSelect(SelInst, *SI, Spec, DTU);
1894 else
1895 llvm_unreachable_internal("Only for load and store.");
1896}
1897
1899 const RewriteableMemOps &Ops,
1900 IRBuilderTy &IRB, DomTreeUpdater *DTU) {
1901 bool CFGChanged = false;
1902 LLVM_DEBUG(dbgs() << " original select: " << SI << "\n");
1903
1904 for (const RewriteableMemOp &Op : Ops) {
1905 SelectHandSpeculativity Spec;
1906 Instruction *I;
1907 if (auto *const *US = std::get_if<UnspeculatableStore>(&Op)) {
1908 I = *US;
1909 } else {
1910 auto PSL = std::get<PossiblySpeculatableLoad>(Op);
1911 I = PSL.getPointer();
1912 Spec = PSL.getInt();
1913 }
1914 if (Spec.areAllSpeculatable()) {
1916 } else {
1917 assert(DTU && "Should not get here when not allowed to modify the CFG!");
1918 rewriteMemOpOfSelect(SI, *I, Spec, *DTU);
1919 CFGChanged = true;
1920 }
1921 I->eraseFromParent();
1922 }
1923
1924 for (User *U : make_early_inc_range(SI.users()))
1925 cast<BitCastInst>(U)->eraseFromParent();
1926 SI.eraseFromParent();
1927 return CFGChanged;
1928}
1929
1930/// Compute an adjusted pointer from Ptr by Offset bytes where the
1931/// resulting pointer has PointerTy.
1932static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1934 const Twine &NamePrefix) {
1935 if (Offset != 0)
1936 Ptr = IRB.CreateInBoundsPtrAdd(Ptr, IRB.getInt(Offset),
1937 NamePrefix + "sroa_idx");
1938 return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, PointerTy,
1939 NamePrefix + "sroa_cast");
1940}
1941
1942/// Compute the adjusted alignment for a load or store from an offset.
1946
1947/// Test whether we can convert a value from the old to the new type.
1948///
1949/// This predicate should be used to guard calls to convertValue in order to
1950/// ensure that we only try to convert viable values. The strategy is that we
1951/// will peel off single element struct and array wrappings to get to an
1952/// underlying value, and convert that value.
1953static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy,
1954 unsigned VScale = 0) {
1955 if (OldTy == NewTy)
1956 return true;
1957
1958 // For integer types, we can't handle any bit-width differences. This would
1959 // break both vector conversions with extension and introduce endianness
1960 // issues when in conjunction with loads and stores.
1961 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1963 cast<IntegerType>(NewTy)->getBitWidth() &&
1964 "We can't have the same bitwidth for different int types");
1965 return false;
1966 }
1967
1968 TypeSize NewSize = DL.getTypeSizeInBits(NewTy);
1969 TypeSize OldSize = DL.getTypeSizeInBits(OldTy);
1970
1971 if ((isa<ScalableVectorType>(NewTy) && isa<FixedVectorType>(OldTy)) ||
1972 (isa<ScalableVectorType>(OldTy) && isa<FixedVectorType>(NewTy))) {
1973 // Conversion is only possible when the size of scalable vectors is known.
1974 if (!VScale)
1975 return false;
1976
1977 // For ptr-to-int and int-to-ptr casts, the pointer side is resolved within
1978 // a single domain (either fixed or scalable). Any additional conversion
1979 // between fixed and scalable types is handled through integer types.
1980 auto OldVTy = OldTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(OldTy) : OldTy;
1981 auto NewVTy = NewTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(NewTy) : NewTy;
1982
1983 if (isa<ScalableVectorType>(NewTy)) {
1985 return false;
1986
1987 NewSize = TypeSize::getFixed(NewSize.getKnownMinValue() * VScale);
1988 } else {
1990 return false;
1991
1992 OldSize = TypeSize::getFixed(OldSize.getKnownMinValue() * VScale);
1993 }
1994 }
1995
1996 if (NewSize != OldSize)
1997 return false;
1998 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1999 return false;
2000
2001 // We can convert pointers to integers and vice-versa. Same for vectors
2002 // of pointers and integers.
2003 OldTy = OldTy->getScalarType();
2004 NewTy = NewTy->getScalarType();
2005 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2006 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
2007 unsigned OldAS = OldTy->getPointerAddressSpace();
2008 unsigned NewAS = NewTy->getPointerAddressSpace();
2009 // Convert pointers if they are pointers from the same address space or
2010 // different integral (not non-integral) address spaces with the same
2011 // pointer size.
2012 return OldAS == NewAS ||
2013 (!DL.isNonIntegralAddressSpace(OldAS) &&
2014 !DL.isNonIntegralAddressSpace(NewAS) &&
2015 DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
2016 }
2017
2018 // We can convert integers to integral pointers, but not to non-integral
2019 // pointers.
2020 if (OldTy->isIntegerTy())
2021 return !DL.isNonIntegralPointerType(NewTy);
2022
2023 // We can convert integral pointers to integers, but non-integral pointers
2024 // need to remain pointers.
2025 if (!DL.isNonIntegralPointerType(OldTy))
2026 return NewTy->isIntegerTy();
2027
2028 return false;
2029 }
2030
2031 if (OldTy->isTargetExtTy() || NewTy->isTargetExtTy())
2032 return false;
2033
2034 return true;
2035}
2036
2037/// Test whether the given slice use can be promoted to a vector.
2038///
2039/// This function is called to test each entry in a partition which is slated
2040/// for a single slice.
2041static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
2042 VectorType *Ty,
2043 uint64_t ElementSize,
2044 const DataLayout &DL,
2045 unsigned VScale) {
2046 // First validate the slice offsets.
2047 uint64_t BeginOffset =
2048 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
2049 uint64_t BeginIndex = BeginOffset / ElementSize;
2050 if (BeginIndex * ElementSize != BeginOffset ||
2051 BeginIndex >= cast<FixedVectorType>(Ty)->getNumElements())
2052 return false;
2053 uint64_t EndOffset = std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
2054 uint64_t EndIndex = EndOffset / ElementSize;
2055 if (EndIndex * ElementSize != EndOffset ||
2056 EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
2057 return false;
2058
2059 assert(EndIndex > BeginIndex && "Empty vector!");
2060 uint64_t NumElements = EndIndex - BeginIndex;
2061 Type *SliceTy = (NumElements == 1)
2062 ? Ty->getElementType()
2063 : FixedVectorType::get(Ty->getElementType(), NumElements);
2064
2065 Type *SplitIntTy =
2066 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
2067
2068 Use *U = S.getUse();
2069
2070 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2071 if (MI->isVolatile())
2072 return false;
2073 if (!S.isSplittable())
2074 return false; // Skip any unsplittable intrinsics.
2075 if (isa<MemSetInst>(MI)) {
2076 Type *SplatTy = Type::getIntNTy(Ty->getContext(), ElementSize * 8);
2077 if (!canConvertValue(DL, SplatTy, Ty->getElementType(), VScale))
2078 return false;
2079 }
2080 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2081 if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
2082 return false;
2083 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2084 if (LI->isVolatile())
2085 return false;
2086 Type *LTy = LI->getType();
2087 // Disable vector promotion when there are loads or stores of an FCA.
2088 if (LTy->isStructTy())
2089 return false;
2090 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2091 assert(LTy->isIntegerTy());
2092 LTy = SplitIntTy;
2093 }
2094 if (!canConvertValue(DL, SliceTy, LTy, VScale))
2095 return false;
2096 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2097 if (SI->isVolatile())
2098 return false;
2099 Type *STy = SI->getValueOperand()->getType();
2100 // Disable vector promotion when there are loads or stores of an FCA.
2101 if (STy->isStructTy())
2102 return false;
2103 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
2104 assert(STy->isIntegerTy());
2105 STy = SplitIntTy;
2106 }
2107 if (!canConvertValue(DL, STy, SliceTy, VScale))
2108 return false;
2109 } else {
2110 return false;
2111 }
2112
2113 return true;
2114}
2115
2116/// Test whether any vector type in \p CandidateTys is viable for promotion.
2117///
2118/// This implements the necessary checking for \c isVectorPromotionViable over
2119/// all slices of the alloca for the given VectorType.
2120static VectorType *
2122 SmallVectorImpl<VectorType *> &CandidateTys,
2123 bool HaveCommonEltTy, Type *CommonEltTy,
2124 bool HaveVecPtrTy, bool HaveCommonVecPtrTy,
2125 VectorType *CommonVecPtrTy, unsigned VScale) {
2126 // If we didn't find a vector type, nothing to do here.
2127 if (CandidateTys.empty())
2128 return nullptr;
2129
2130 // Pointer-ness is sticky, if we had a vector-of-pointers candidate type,
2131 // then we should choose it, not some other alternative.
2132 // But, we can't perform a no-op pointer address space change via bitcast,
2133 // so if we didn't have a common pointer element type, bail.
2134 if (HaveVecPtrTy && !HaveCommonVecPtrTy)
2135 return nullptr;
2136
2137 // Try to pick the "best" element type out of the choices.
2138 if (!HaveCommonEltTy && HaveVecPtrTy) {
2139 // If there was a pointer element type, there's really only one choice.
2140 CandidateTys.clear();
2141 CandidateTys.push_back(CommonVecPtrTy);
2142 } else if (!HaveCommonEltTy && !HaveVecPtrTy) {
2143 // Integer-ify vector types.
2144 for (VectorType *&VTy : CandidateTys) {
2145 if (!VTy->getElementType()->isIntegerTy())
2146 VTy = cast<VectorType>(VTy->getWithNewType(IntegerType::getIntNTy(
2147 VTy->getContext(), VTy->getScalarSizeInBits())));
2148 }
2149
2150 // Rank the remaining candidate vector types. This is easy because we know
2151 // they're all integer vectors. We sort by ascending number of elements.
2152 auto RankVectorTypesComp = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2153 (void)DL;
2154 assert(DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2155 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2156 "Cannot have vector types of different sizes!");
2157 assert(RHSTy->getElementType()->isIntegerTy() &&
2158 "All non-integer types eliminated!");
2159 assert(LHSTy->getElementType()->isIntegerTy() &&
2160 "All non-integer types eliminated!");
2161 return cast<FixedVectorType>(RHSTy)->getNumElements() <
2162 cast<FixedVectorType>(LHSTy)->getNumElements();
2163 };
2164 auto RankVectorTypesEq = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2165 (void)DL;
2166 assert(DL.getTypeSizeInBits(RHSTy).getFixedValue() ==
2167 DL.getTypeSizeInBits(LHSTy).getFixedValue() &&
2168 "Cannot have vector types of different sizes!");
2169 assert(RHSTy->getElementType()->isIntegerTy() &&
2170 "All non-integer types eliminated!");
2171 assert(LHSTy->getElementType()->isIntegerTy() &&
2172 "All non-integer types eliminated!");
2173 return cast<FixedVectorType>(RHSTy)->getNumElements() ==
2174 cast<FixedVectorType>(LHSTy)->getNumElements();
2175 };
2176 llvm::sort(CandidateTys, RankVectorTypesComp);
2177 CandidateTys.erase(llvm::unique(CandidateTys, RankVectorTypesEq),
2178 CandidateTys.end());
2179 } else {
2180// The only way to have the same element type in every vector type is to
2181// have the same vector type. Check that and remove all but one.
2182#ifndef NDEBUG
2183 for (VectorType *VTy : CandidateTys) {
2184 assert(VTy->getElementType() == CommonEltTy &&
2185 "Unaccounted for element type!");
2186 assert(VTy == CandidateTys[0] &&
2187 "Different vector types with the same element type!");
2188 }
2189#endif
2190 CandidateTys.resize(1);
2191 }
2192
2193 // FIXME: hack. Do we have a named constant for this?
2194 // SDAG SDNode can't have more than 65535 operands.
2195 llvm::erase_if(CandidateTys, [](VectorType *VTy) {
2196 return cast<FixedVectorType>(VTy)->getNumElements() >
2197 std::numeric_limits<unsigned short>::max();
2198 });
2199
2200 // Find a vector type viable for promotion by iterating over all slices.
2201 auto *VTy = llvm::find_if(CandidateTys, [&](VectorType *VTy) -> bool {
2202 uint64_t ElementSize =
2203 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2204
2205 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2206 // that aren't byte sized.
2207 if (ElementSize % 8)
2208 return false;
2209 assert((DL.getTypeSizeInBits(VTy).getFixedValue() % 8) == 0 &&
2210 "vector size not a multiple of element size?");
2211 ElementSize /= 8;
2212
2213 for (const Slice &S : P)
2214 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL, VScale))
2215 return false;
2216
2217 for (const Slice *S : P.splitSliceTails())
2218 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL, VScale))
2219 return false;
2220
2221 return true;
2222 });
2223 return VTy != CandidateTys.end() ? *VTy : nullptr;
2224}
2225
2227 SetVector<Type *> &OtherTys, ArrayRef<VectorType *> CandidateTysCopy,
2228 function_ref<void(Type *)> CheckCandidateType, Partition &P,
2229 const DataLayout &DL, SmallVectorImpl<VectorType *> &CandidateTys,
2230 bool &HaveCommonEltTy, Type *&CommonEltTy, bool &HaveVecPtrTy,
2231 bool &HaveCommonVecPtrTy, VectorType *&CommonVecPtrTy, unsigned VScale) {
2232 [[maybe_unused]] VectorType *OriginalElt =
2233 CandidateTysCopy.size() ? CandidateTysCopy[0] : nullptr;
2234 // Consider additional vector types where the element type size is a
2235 // multiple of load/store element size.
2236 for (Type *Ty : OtherTys) {
2238 continue;
2239 unsigned TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
2240 // Make a copy of CandidateTys and iterate through it, because we
2241 // might append to CandidateTys in the loop.
2242 for (VectorType *const VTy : CandidateTysCopy) {
2243 // The elements in the copy should remain invariant throughout the loop
2244 assert(CandidateTysCopy[0] == OriginalElt && "Different Element");
2245 unsigned VectorSize = DL.getTypeSizeInBits(VTy).getFixedValue();
2246 unsigned ElementSize =
2247 DL.getTypeSizeInBits(VTy->getElementType()).getFixedValue();
2248 if (TypeSize != VectorSize && TypeSize != ElementSize &&
2249 VectorSize % TypeSize == 0) {
2250 VectorType *NewVTy = VectorType::get(Ty, VectorSize / TypeSize, false);
2251 CheckCandidateType(NewVTy);
2252 }
2253 }
2254 }
2255
2257 P, DL, CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2258 HaveCommonVecPtrTy, CommonVecPtrTy, VScale);
2259}
2260
2261/// Test whether the given alloca partitioning and range of slices can be
2262/// promoted to a vector.
2263///
2264/// This is a quick test to check whether we can rewrite a particular alloca
2265/// partition (and its newly formed alloca) into a vector alloca with only
2266/// whole-vector loads and stores such that it could be promoted to a vector
2267/// SSA value. We only can ensure this for a limited set of operations, and we
2268/// don't want to do the rewrites unless we are confident that the result will
2269/// be promotable, so we have an early test here.
2271 unsigned VScale) {
2272 // Collect the candidate types for vector-based promotion. Also track whether
2273 // we have different element types.
2274 SmallVector<VectorType *, 4> CandidateTys;
2275 SetVector<Type *> LoadStoreTys;
2276 SetVector<Type *> DeferredTys;
2277 Type *CommonEltTy = nullptr;
2278 VectorType *CommonVecPtrTy = nullptr;
2279 bool HaveVecPtrTy = false;
2280 bool HaveCommonEltTy = true;
2281 bool HaveCommonVecPtrTy = true;
2282 auto CheckCandidateType = [&](Type *Ty) {
2283 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
2284 // Return if bitcast to vectors is different for total size in bits.
2285 if (!CandidateTys.empty()) {
2286 VectorType *V = CandidateTys[0];
2287 if (DL.getTypeSizeInBits(VTy).getFixedValue() !=
2288 DL.getTypeSizeInBits(V).getFixedValue()) {
2289 CandidateTys.clear();
2290 return;
2291 }
2292 }
2293 CandidateTys.push_back(VTy);
2294 Type *EltTy = VTy->getElementType();
2295
2296 if (!CommonEltTy)
2297 CommonEltTy = EltTy;
2298 else if (CommonEltTy != EltTy)
2299 HaveCommonEltTy = false;
2300
2301 if (EltTy->isPointerTy()) {
2302 HaveVecPtrTy = true;
2303 if (!CommonVecPtrTy)
2304 CommonVecPtrTy = VTy;
2305 else if (CommonVecPtrTy != VTy)
2306 HaveCommonVecPtrTy = false;
2307 }
2308 }
2309 };
2310
2311 // Put load and store types into a set for de-duplication.
2312 for (const Slice &S : P) {
2313 Type *Ty;
2314 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2315 Ty = LI->getType();
2316 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2317 Ty = SI->getValueOperand()->getType();
2318 else
2319 continue;
2320
2321 auto CandTy = Ty->getScalarType();
2322 if (CandTy->isPointerTy() && (S.beginOffset() != P.beginOffset() ||
2323 S.endOffset() != P.endOffset())) {
2324 DeferredTys.insert(Ty);
2325 continue;
2326 }
2327
2328 LoadStoreTys.insert(Ty);
2329 // Consider any loads or stores that are the exact size of the slice.
2330 if (S.beginOffset() == P.beginOffset() && S.endOffset() == P.endOffset())
2331 CheckCandidateType(Ty);
2332 }
2333
2334 SmallVector<VectorType *, 4> CandidateTysCopy = CandidateTys;
2336 LoadStoreTys, CandidateTysCopy, CheckCandidateType, P, DL,
2337 CandidateTys, HaveCommonEltTy, CommonEltTy, HaveVecPtrTy,
2338 HaveCommonVecPtrTy, CommonVecPtrTy, VScale))
2339 return VTy;
2340
2341 CandidateTys.clear();
2343 DeferredTys, CandidateTysCopy, CheckCandidateType, P, DL, CandidateTys,
2344 HaveCommonEltTy, CommonEltTy, HaveVecPtrTy, HaveCommonVecPtrTy,
2345 CommonVecPtrTy, VScale);
2346}
2347
2348/// Test whether a slice of an alloca is valid for integer widening.
2349///
2350/// This implements the necessary checking for the \c isIntegerWideningViable
2351/// test below on a single slice of the alloca.
2352static bool isIntegerWideningViableForSlice(const Slice &S,
2353 uint64_t AllocBeginOffset,
2354 Type *AllocaTy,
2355 const DataLayout &DL,
2356 bool &WholeAllocaOp) {
2357 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedValue();
2358
2359 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2360 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2361
2362 Use *U = S.getUse();
2363
2364 // Lifetime intrinsics operate over the whole alloca whose sizes are usually
2365 // larger than other load/store slices (RelEnd > Size). But lifetime are
2366 // always promotable and should not impact other slices' promotability of the
2367 // partition.
2368 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2369 if (II->isLifetimeStartOrEnd() || II->isDroppable())
2370 return true;
2371 }
2372
2373 // We can't reasonably handle cases where the load or store extends past
2374 // the end of the alloca's type and into its padding.
2375 if (RelEnd > Size)
2376 return false;
2377
2378 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2379 if (LI->isVolatile())
2380 return false;
2381 // We can't handle loads that extend past the allocated memory.
2382 TypeSize LoadSize = DL.getTypeStoreSize(LI->getType());
2383 if (!LoadSize.isFixed() || LoadSize.getFixedValue() > Size)
2384 return false;
2385 // So far, AllocaSliceRewriter does not support widening split slice tails
2386 // in rewriteIntegerLoad.
2387 if (S.beginOffset() < AllocBeginOffset)
2388 return false;
2389 // Note that we don't count vector loads or stores as whole-alloca
2390 // operations which enable integer widening because we would prefer to use
2391 // vector widening instead.
2392 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2393 WholeAllocaOp = true;
2394 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2395 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2396 return false;
2397 } else if (RelBegin != 0 || RelEnd != Size ||
2398 !canConvertValue(DL, AllocaTy, LI->getType())) {
2399 // Non-integer loads need to be convertible from the alloca type so that
2400 // they are promotable.
2401 return false;
2402 }
2403 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2404 Type *ValueTy = SI->getValueOperand()->getType();
2405 if (SI->isVolatile())
2406 return false;
2407 // We can't handle stores that extend past the allocated memory.
2408 TypeSize StoreSize = DL.getTypeStoreSize(ValueTy);
2409 if (!StoreSize.isFixed() || StoreSize.getFixedValue() > Size)
2410 return false;
2411 // So far, AllocaSliceRewriter does not support widening split slice tails
2412 // in rewriteIntegerStore.
2413 if (S.beginOffset() < AllocBeginOffset)
2414 return false;
2415 // Note that we don't count vector loads or stores as whole-alloca
2416 // operations which enable integer widening because we would prefer to use
2417 // vector widening instead.
2418 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2419 WholeAllocaOp = true;
2420 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2421 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedValue())
2422 return false;
2423 } else if (RelBegin != 0 || RelEnd != Size ||
2424 !canConvertValue(DL, ValueTy, AllocaTy)) {
2425 // Non-integer stores need to be convertible to the alloca type so that
2426 // they are promotable.
2427 return false;
2428 }
2429 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2430 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2431 return false;
2432 if (!S.isSplittable())
2433 return false; // Skip any unsplittable intrinsics.
2434 } else {
2435 return false;
2436 }
2437
2438 return true;
2439}
2440
2441/// Test whether the given alloca partition's integer operations can be
2442/// widened to promotable ones.
2443///
2444/// This is a quick test to check whether we can rewrite the integer loads and
2445/// stores to a particular alloca into wider loads and stores and be able to
2446/// promote the resulting alloca.
2447static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2448 const DataLayout &DL) {
2449 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedValue();
2450 // Don't create integer types larger than the maximum bitwidth.
2451 if (SizeInBits > IntegerType::MAX_INT_BITS)
2452 return false;
2453
2454 // Don't try to handle allocas with bit-padding.
2455 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedValue())
2456 return false;
2457
2458 // We need to ensure that an integer type with the appropriate bitwidth can
2459 // be converted to the alloca type, whatever that is. We don't want to force
2460 // the alloca itself to have an integer type if there is a more suitable one.
2461 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2462 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2463 !canConvertValue(DL, IntTy, AllocaTy))
2464 return false;
2465
2466 // While examining uses, we ensure that the alloca has a covering load or
2467 // store. We don't want to widen the integer operations only to fail to
2468 // promote due to some other unsplittable entry (which we may make splittable
2469 // later). However, if there are only splittable uses, go ahead and assume
2470 // that we cover the alloca.
2471 // FIXME: We shouldn't consider split slices that happen to start in the
2472 // partition here...
2473 bool WholeAllocaOp = P.empty() && DL.isLegalInteger(SizeInBits);
2474
2475 for (const Slice &S : P)
2476 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2477 WholeAllocaOp))
2478 return false;
2479
2480 for (const Slice *S : P.splitSliceTails())
2481 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2482 WholeAllocaOp))
2483 return false;
2484
2485 return WholeAllocaOp;
2486}
2487
2488static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2490 const Twine &Name) {
2491 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2492 IntegerType *IntTy = cast<IntegerType>(V->getType());
2493 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2494 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2495 "Element extends past full value");
2496 uint64_t ShAmt = 8 * Offset;
2497 if (DL.isBigEndian())
2498 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2499 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2500 if (ShAmt) {
2501 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2502 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2503 }
2504 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2505 "Cannot extract to a larger integer!");
2506 if (Ty != IntTy) {
2507 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2508 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
2509 }
2510 return V;
2511}
2512
2513static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2514 Value *V, uint64_t Offset, const Twine &Name) {
2515 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2516 IntegerType *Ty = cast<IntegerType>(V->getType());
2517 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2518 "Cannot insert a larger integer!");
2519 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
2520 if (Ty != IntTy) {
2521 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2522 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
2523 }
2524 assert(DL.getTypeStoreSize(Ty).getFixedValue() + Offset <=
2525 DL.getTypeStoreSize(IntTy).getFixedValue() &&
2526 "Element store outside of alloca store");
2527 uint64_t ShAmt = 8 * Offset;
2528 if (DL.isBigEndian())
2529 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedValue() -
2530 DL.getTypeStoreSize(Ty).getFixedValue() - Offset);
2531 if (ShAmt) {
2532 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2533 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
2534 }
2535
2536 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2537 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2538 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2539 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
2540 V = IRB.CreateOr(Old, V, Name + ".insert");
2541 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
2542 }
2543 return V;
2544}
2545
2546static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2547 unsigned EndIndex, const Twine &Name) {
2548 auto *VecTy = cast<FixedVectorType>(V->getType());
2549 unsigned NumElements = EndIndex - BeginIndex;
2550 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2551
2552 if (NumElements == VecTy->getNumElements())
2553 return V;
2554
2555 if (NumElements == 1) {
2556 V = IRB.CreateExtractElement(V, BeginIndex, Name + ".extract");
2557 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
2558 return V;
2559 }
2560
2561 auto Mask = llvm::to_vector<8>(llvm::seq<int>(BeginIndex, EndIndex));
2562 V = IRB.CreateShuffleVector(V, Mask, Name + ".extract");
2563 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2564 return V;
2565}
2566
2567static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2568 unsigned BeginIndex, const Twine &Name) {
2569 VectorType *VecTy = cast<VectorType>(Old->getType());
2570 assert(VecTy && "Can only insert a vector into a vector");
2571
2572 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2573 if (!Ty) {
2574 // Single element to insert.
2575 V = IRB.CreateInsertElement(Old, V, BeginIndex, Name + ".insert");
2576 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
2577 return V;
2578 }
2579
2580 unsigned NumSubElements = cast<FixedVectorType>(Ty)->getNumElements();
2581 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2582
2583 assert(NumSubElements <= NumElements && "Too many elements!");
2584 if (NumSubElements == NumElements) {
2585 assert(V->getType() == VecTy && "Vector type mismatch");
2586 return V;
2587 }
2588 unsigned EndIndex = BeginIndex + NumSubElements;
2589
2590 // When inserting a smaller vector into the larger to store, we first
2591 // use a shuffle vector to widen it with undef elements, and then
2592 // a second shuffle vector to select between the loaded vector and the
2593 // incoming vector.
2595 Mask.reserve(NumElements);
2596 for (unsigned Idx = 0; Idx != NumElements; ++Idx)
2597 if (Idx >= BeginIndex && Idx < EndIndex)
2598 Mask.push_back(Idx - BeginIndex);
2599 else
2600 Mask.push_back(-1);
2601 V = IRB.CreateShuffleVector(V, Mask, Name + ".expand");
2602 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
2603
2604 Mask.clear();
2605 for (unsigned Idx = 0; Idx != NumElements; ++Idx)
2606 if (Idx >= BeginIndex && Idx < EndIndex)
2607 Mask.push_back(Idx);
2608 else
2609 Mask.push_back(Idx + NumElements);
2610 V = IRB.CreateShuffleVector(V, Old, Mask, Name + "blend");
2611 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
2612 return V;
2613}
2614
2615/// This function takes two vector values and combines them into a single vector
2616/// by concatenating their elements. The function handles:
2617///
2618/// 1. Element type mismatch: If either vector's element type differs from
2619/// NewAIEltType, the function bitcasts the vector to use NewAIEltType while
2620/// preserving the total bit width (adjusting the number of elements
2621/// accordingly).
2622///
2623/// 2. Size mismatch: After transforming the vectors to have the desired element
2624/// type, if the two vectors have different numbers of elements, the smaller
2625/// vector is extended with poison values to match the size of the larger
2626/// vector before concatenation.
2627///
2628/// 3. Concatenation: The vectors are merged using a shuffle operation that
2629/// places all elements of V0 first, followed by all elements of V1.
2630///
2631/// \param V0 The first vector to merge (must be a vector type)
2632/// \param V1 The second vector to merge (must be a vector type)
2633/// \param DL The data layout for size calculations
2634/// \param NewAIEltTy The desired element type for the result vector
2635/// \param Builder IRBuilder for creating new instructions
2636/// \return A new vector containing all elements from V0 followed by all
2637/// elements from V1
2639 Type *NewAIEltTy, IRBuilder<> &Builder) {
2640 // V0 and V1 are vectors
2641 // Create a new vector type with combined elements
2642 // Use ShuffleVector to concatenate the vectors
2643 auto *VecType0 = cast<FixedVectorType>(V0->getType());
2644 auto *VecType1 = cast<FixedVectorType>(V1->getType());
2645
2646 // If V0/V1 element types are different from NewAllocaElementType,
2647 // we need to introduce bitcasts before merging them
2648 auto BitcastIfNeeded = [&](Value *&V, FixedVectorType *&VecType,
2649 const char *DebugName) {
2650 Type *EltType = VecType->getElementType();
2651 if (EltType != NewAIEltTy) {
2652 // Calculate new number of elements to maintain same bit width
2653 unsigned TotalBits =
2654 VecType->getNumElements() * DL.getTypeSizeInBits(EltType);
2655 unsigned NewNumElts = TotalBits / DL.getTypeSizeInBits(NewAIEltTy);
2656
2657 auto *NewVecType = FixedVectorType::get(NewAIEltTy, NewNumElts);
2658 V = Builder.CreateBitCast(V, NewVecType);
2659 VecType = NewVecType;
2660 LLVM_DEBUG(dbgs() << " bitcast " << DebugName << ": " << *V << "\n");
2661 }
2662 };
2663
2664 BitcastIfNeeded(V0, VecType0, "V0");
2665 BitcastIfNeeded(V1, VecType1, "V1");
2666
2667 unsigned NumElts0 = VecType0->getNumElements();
2668 unsigned NumElts1 = VecType1->getNumElements();
2669
2670 SmallVector<int, 16> ShuffleMask;
2671
2672 if (NumElts0 == NumElts1) {
2673 for (unsigned i = 0; i < NumElts0 + NumElts1; ++i)
2674 ShuffleMask.push_back(i);
2675 } else {
2676 // If two vectors have different sizes, we need to extend
2677 // the smaller vector to the size of the larger vector.
2678 unsigned SmallSize = std::min(NumElts0, NumElts1);
2679 unsigned LargeSize = std::max(NumElts0, NumElts1);
2680 bool IsV0Smaller = NumElts0 < NumElts1;
2681 Value *&ExtendedVec = IsV0Smaller ? V0 : V1;
2682 SmallVector<int, 16> ExtendMask;
2683 for (unsigned i = 0; i < SmallSize; ++i)
2684 ExtendMask.push_back(i);
2685 for (unsigned i = SmallSize; i < LargeSize; ++i)
2686 ExtendMask.push_back(PoisonMaskElem);
2687 ExtendedVec = Builder.CreateShuffleVector(
2688 ExtendedVec, PoisonValue::get(ExtendedVec->getType()), ExtendMask);
2689 LLVM_DEBUG(dbgs() << " shufflevector: " << *ExtendedVec << "\n");
2690 for (unsigned i = 0; i < NumElts0; ++i)
2691 ShuffleMask.push_back(i);
2692 for (unsigned i = 0; i < NumElts1; ++i)
2693 ShuffleMask.push_back(LargeSize + i);
2694 }
2695
2696 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2697}
2698
2699namespace {
2700
2701/// Visitor to rewrite instructions using p particular slice of an alloca
2702/// to use a new alloca.
2703///
2704/// Also implements the rewriting to vector-based accesses when the partition
2705/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2706/// lives here.
2707class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2708 // Befriend the base class so it can delegate to private visit methods.
2709 friend class InstVisitor<AllocaSliceRewriter, bool>;
2710
2711 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2712
2713 const DataLayout &DL;
2714 AllocaSlices &AS;
2715 SROA &Pass;
2716 AllocaInst &OldAI, &NewAI;
2717 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2718 Type *NewAllocaTy;
2719
2720 // This is a convenience and flag variable that will be null unless the new
2721 // alloca's integer operations should be widened to this integer type due to
2722 // passing isIntegerWideningViable above. If it is non-null, the desired
2723 // integer type will be stored here for easy access during rewriting.
2724 IntegerType *IntTy;
2725
2726 // If we are rewriting an alloca partition which can be written as pure
2727 // vector operations, we stash extra information here. When VecTy is
2728 // non-null, we have some strict guarantees about the rewritten alloca:
2729 // - The new alloca is exactly the size of the vector type here.
2730 // - The accesses all either map to the entire vector or to a single
2731 // element.
2732 // - The set of accessing instructions is only one of those handled above
2733 // in isVectorPromotionViable. Generally these are the same access kinds
2734 // which are promotable via mem2reg.
2735 VectorType *VecTy;
2736 Type *ElementTy;
2737 uint64_t ElementSize;
2738
2739 // The original offset of the slice currently being rewritten relative to
2740 // the original alloca.
2741 uint64_t BeginOffset = 0;
2742 uint64_t EndOffset = 0;
2743
2744 // The new offsets of the slice currently being rewritten relative to the
2745 // original alloca.
2746 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2747
2748 uint64_t SliceSize = 0;
2749 bool IsSplittable = false;
2750 bool IsSplit = false;
2751 Use *OldUse = nullptr;
2752 Instruction *OldPtr = nullptr;
2753
2754 // Track post-rewrite users which are PHI nodes and Selects.
2755 SmallSetVector<PHINode *, 8> &PHIUsers;
2756 SmallSetVector<SelectInst *, 8> &SelectUsers;
2757
2758 // Utility IR builder, whose name prefix is setup for each visited use, and
2759 // the insertion point is set to point to the user.
2760 IRBuilderTy IRB;
2761
2762 // Return the new alloca, addrspacecasted if required to avoid changing the
2763 // addrspace of a volatile access.
2764 Value *getPtrToNewAI(unsigned AddrSpace, bool IsVolatile) {
2765 if (!IsVolatile || AddrSpace == NewAI.getType()->getPointerAddressSpace())
2766 return &NewAI;
2767
2768 Type *AccessTy = IRB.getPtrTy(AddrSpace);
2769 return IRB.CreateAddrSpaceCast(&NewAI, AccessTy);
2770 }
2771
2772public:
2773 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2774 AllocaInst &OldAI, AllocaInst &NewAI, Type *NewAllocaTy,
2775 uint64_t NewAllocaBeginOffset,
2776 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2777 VectorType *PromotableVecTy,
2778 SmallSetVector<PHINode *, 8> &PHIUsers,
2779 SmallSetVector<SelectInst *, 8> &SelectUsers)
2780 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2781 NewAllocaBeginOffset(NewAllocaBeginOffset),
2782 NewAllocaEndOffset(NewAllocaEndOffset), NewAllocaTy(NewAllocaTy),
2783 IntTy(IsIntegerPromotable
2784 ? Type::getIntNTy(
2785 NewAI.getContext(),
2786 DL.getTypeSizeInBits(NewAllocaTy).getFixedValue())
2787 : nullptr),
2788 VecTy(PromotableVecTy),
2789 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2790 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8
2791 : 0),
2792 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2793 IRB(NewAI.getContext(), ConstantFolder()) {
2794 if (VecTy) {
2795 assert((DL.getTypeSizeInBits(ElementTy).getFixedValue() % 8) == 0 &&
2796 "Only multiple-of-8 sized vector elements are viable");
2797 ++NumVectorized;
2798 }
2799 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2800 }
2801
2802 bool visit(AllocaSlices::const_iterator I) {
2803 bool CanSROA = true;
2804 BeginOffset = I->beginOffset();
2805 EndOffset = I->endOffset();
2806 IsSplittable = I->isSplittable();
2807 IsSplit =
2808 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2809 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2810 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2811 LLVM_DEBUG(dbgs() << "\n");
2812
2813 // Compute the intersecting offset range.
2814 assert(BeginOffset < NewAllocaEndOffset);
2815 assert(EndOffset > NewAllocaBeginOffset);
2816 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2817 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2818
2819 SliceSize = NewEndOffset - NewBeginOffset;
2820 LLVM_DEBUG(dbgs() << " Begin:(" << BeginOffset << ", " << EndOffset
2821 << ") NewBegin:(" << NewBeginOffset << ", "
2822 << NewEndOffset << ") NewAllocaBegin:("
2823 << NewAllocaBeginOffset << ", " << NewAllocaEndOffset
2824 << ")\n");
2825 assert(IsSplit || NewBeginOffset == BeginOffset);
2826 OldUse = I->getUse();
2827 OldPtr = cast<Instruction>(OldUse->get());
2828
2829 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2830 IRB.SetInsertPoint(OldUserI);
2831 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2832 // Avoid materializing the name prefix when it is discarded anyway.
2833 if (!IRB.getContext().shouldDiscardValueNames())
2834 IRB.getInserter().SetNamePrefix(Twine(NewAI.getName()) + "." +
2835 Twine(BeginOffset) + ".");
2836
2837 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2838 if (VecTy || IntTy)
2839 assert(CanSROA);
2840 return CanSROA;
2841 }
2842
2843 /// Attempts to rewrite a partition using tree-structured merge optimization.
2844 ///
2845 /// This function handles two patterns. Both produce an O(log n) tree of
2846 /// shufflevectors in place of the linear expand+blend chain that SROA would
2847 /// otherwise emit for each partial store.
2848 ///
2849 /// Pattern 1 (stores-only):
2850 /// Multiple non-overlapping partial stores completely fill the alloca
2851 /// and there is exactly one full-width load coming after the stores.
2852 /// The stores are tree-merged into a single vector and stored once.
2853 ///
2854 /// Example transformation:
2855 /// Before: (stores do not have to be in order)
2856 /// %alloca = alloca <8 x float>
2857 /// store <2 x float> %val0, ptr %alloca ; offset 0-1
2858 /// store <2 x float> %val2, ptr %alloca+16 ; offset 4-5
2859 /// store <2 x float> %val1, ptr %alloca+8 ; offset 2-3
2860 /// store <2 x float> %val3, ptr %alloca+24 ; offset 6-7
2861 /// %r = load <8 x float>, ptr %alloca
2862 ///
2863 /// After: tree of shufflevectors producing <8 x float> directly.
2864 ///
2865 /// Pattern 2 (init + RMW, possibly multi-round):
2866 /// A single full-width init store, followed by partial loads and
2867 /// partial stores that read-modify-write the alloca one or more
2868 /// times, optionally followed by a full-width load. The only
2869 /// structural requirement is that the distinct [begin, end) ranges
2870 /// touched by the partial loads and stores, taken together, tile
2871 /// the alloca disjointly.
2872 ///
2873 /// We keep a map from each slice range to the SSA value that
2874 /// currently lives there, `SliceValues[r] -> Value*`:
2875 /// - initialize each entry to the corresponding piece of the
2876 /// init store's value (via a shufflevector picking the
2877 /// range's elements out of the init value),
2878 /// - walk partial loads and stores in block order,
2879 /// - for a partial load at range r: RAUW with `SliceValues[r]`,
2880 /// - for a partial store at range r: update `SliceValues[r]` to
2881 /// the stored value and drop the store.
2882 /// At the end, the final `SliceValues[r]` entries are tree-merged
2883 /// (in range order) into a single store to the alloca, and the
2884 /// optional full-width load is replaced by a load of the alloca.
2885 ///
2886 /// Because the ranges are disjoint by construction, a store at one
2887 /// range cannot affect another range's tracked value, so a single
2888 /// block-order walk correctly tracks the memory state at each
2889 /// range. The algorithm handles multi-round RMW, partial loads
2890 /// and stores interleaved in any order, read-only slices (the
2891 /// tracked value stays at the init extract), and write-only
2892 /// slices (the tracked value never flows into a load).
2893 ///
2894 /// \param P The partition to analyze and potentially rewrite
2895 /// \return An optional vector of values that were deleted during the
2896 /// rewrite, or std::nullopt if the partition cannot be optimized.
2897 std::optional<SmallVector<Value *, 4>>
2898 rewriteTreeStructuredMerge(Partition &P) {
2899 // No tail slices that overlap with the partition
2900 if (P.splitSliceTails().size() > 0)
2901 return std::nullopt;
2902
2903 // Structure to hold store information
2904 struct StoreInfo {
2905 StoreInst *Store;
2906 uint64_t BeginOffset;
2907 uint64_t EndOffset;
2908 Value *StoredValue;
2909 StoreInfo(StoreInst *SI, uint64_t Begin, uint64_t End, Value *Val)
2910 : Store(SI), BeginOffset(Begin), EndOffset(End), StoredValue(Val) {}
2911 };
2912 struct LoadInfo {
2913 LoadInst *Load;
2914 uint64_t BeginOffset;
2915 uint64_t EndOffset;
2916 };
2917
2918 SmallVector<StoreInfo, 4> StoreInfos; // partial stores only
2919 SmallVector<LoadInfo, 4> LoadInfos; // partial loads only
2920 LoadInst *FullLoad = nullptr; // optional full-width load
2921 StoreInst *InitStore = nullptr; // optional full-width init store
2922
2923 // If the new alloca is a fixed vector type, we use its element type as the
2924 // allocated element type, otherwise we use i8 as the allocated element
2925 Type *AllocatedEltTy =
2926 isa<FixedVectorType>(NewAllocaTy)
2927 ? cast<FixedVectorType>(NewAllocaTy)->getElementType()
2928 : Type::getInt8Ty(NewAI.getContext());
2929 unsigned AllocatedEltTySize = DL.getTypeSizeInBits(AllocatedEltTy);
2930
2931 // Helper to check if a type is
2932 // 1. A fixed vector type
2933 // 2. The element type is not a pointer
2934 // 3. The element type size is byte-aligned
2935 // We only handle the cases that the ld/st meet these conditions
2936 auto IsTypeValidForTreeStructuredMerge = [&](Type *Ty) -> bool {
2937 auto *FixedVecTy = dyn_cast<FixedVectorType>(Ty);
2938 return FixedVecTy &&
2939 DL.getTypeSizeInBits(FixedVecTy->getElementType()) % 8 == 0 &&
2940 !FixedVecTy->getElementType()->isPointerTy();
2941 };
2942
2943 for (Slice &S : P) {
2944 auto *User = cast<Instruction>(S.getUse()->getUser());
2945 // A "full-width" slice spans the entire alloca; it's either the single
2946 // init store (Pattern 2) or the single final load (both patterns).
2947 bool IsFullWidth = (S.beginOffset() == NewAllocaBeginOffset &&
2948 S.endOffset() == NewAllocaEndOffset);
2949 if (auto *LI = dyn_cast<LoadInst>(User)) {
2950 // Only handle simple (non-volatile, non-atomic) loads.
2951 if (!LI->isSimple() ||
2952 !IsTypeValidForTreeStructuredMerge(LI->getType()))
2953 return std::nullopt;
2954 if (IsFullWidth) {
2955 // We accept at most one full-width load (the "final" load, after
2956 // all the partial stores).
2957 if (FullLoad)
2958 return std::nullopt;
2959 FullLoad = LI;
2960 } else {
2961 // Partial load (RMW pattern only).
2962 LoadInfos.push_back({LI, S.beginOffset(), S.endOffset()});
2963 }
2964 } else if (auto *SI = dyn_cast<StoreInst>(User)) {
2965 // Do not handle the case if
2966 // 1. The store does not meet the conditions in the helper function
2967 // 2. The store is not simple — we drop stores as part of the
2968 // rewrite, so volatile stores (which must be kept) and atomic
2969 // stores (which carry memory-ordering semantics) are unsound
2970 // to replace with SSA bookkeeping.
2971 // 3. The total store size is not a multiple of the allocated
2972 // element type size (required so the tree merge can produce a
2973 // vector whose element type matches the alloca).
2974 if (!SI->isSimple() || !IsTypeValidForTreeStructuredMerge(
2975 SI->getValueOperand()->getType()))
2976 return std::nullopt;
2977 auto *StVecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
2978 unsigned NumElts = StVecTy->getNumElements();
2979 unsigned EltSize = DL.getTypeSizeInBits(StVecTy->getElementType());
2980 if (NumElts * EltSize % AllocatedEltTySize != 0)
2981 return std::nullopt;
2982 if (IsFullWidth) {
2983 // At most one full-width store is allowed — it's the init store
2984 // for the RMW pattern.
2985 if (InitStore)
2986 return std::nullopt;
2987 InitStore = SI;
2988 } else {
2989 StoreInfos.emplace_back(SI, S.beginOffset(), S.endOffset(),
2990 SI->getValueOperand());
2991 }
2992 } else {
2993 // If we have instructions other than load and store, we cannot do
2994 // the tree structured merge.
2995 return std::nullopt;
2996 }
2997 }
2998
2999 // Need at least two partial stores to benefit from tree-merging; a
3000 // single store is already optimal as-is. This applies to both patterns
3001 // below, so check it before classifying.
3002 if (StoreInfos.size() < 2)
3003 return std::nullopt;
3004
3005 // Classify the pattern by looking at what we collected:
3006 // Pattern 1 (stores-only): only partial stores + exactly one full load.
3007 // Pattern 2 (RMW): one full init store + partial loads + partial stores
3008 // (+ optional full final load). RMW also needs VecTy to be set
3009 // because we use getIndex() to convert byte offsets to element
3010 // indices, which requires a promoted vector alloca.
3011 bool IsRMWPattern = InitStore && VecTy && !LoadInfos.empty();
3012 bool IsStoresOnlyPattern = !InitStore && FullLoad && LoadInfos.empty();
3013 if (!IsRMWPattern && !IsStoresOnlyPattern)
3014 return std::nullopt;
3015
3016 // All partial stores must live in the same basic block — the tree merge
3017 // is built in a single BB using block-order ordering (comesBefore).
3018 BasicBlock *StoreBB = StoreInfos[0].Store->getParent();
3019 for (auto &Info : StoreInfos)
3020 if (Info.Store->getParent() != StoreBB)
3021 return std::nullopt;
3022
3023 SmallVector<Value *, 4> DeletedValues;
3024
3025 // Helper: pairwise tree-merge a list of vectors into a single vector.
3026 // At each iteration we merge each adjacent pair via mergeTwoVectors,
3027 // collect the merged values into Next, and (if Vals had odd length)
3028 // carry the trailing element through unchanged. Loop until one value
3029 // remains — the fully-merged vector.
3030 auto TreeMerge = [&](SmallVectorImpl<Value *> &Vals,
3031 IRBuilder<> &B) -> Value * {
3032 LLVM_DEBUG(dbgs() << " Rewrite stores into shufflevectors:\n");
3033 while (Vals.size() > 1) {
3034 SmallVector<Value *, 8> Next;
3035 for (unsigned I = 0, E = Vals.size(); I + 1 < E; I += 2) {
3036 Value *M =
3037 mergeTwoVectors(Vals[I], Vals[I + 1], DL, AllocatedEltTy, B);
3038 LLVM_DEBUG(dbgs() << " shufflevector: " << *M << "\n");
3039 Next.push_back(M);
3040 }
3041 if (Vals.size() % 2 == 1)
3042 Next.push_back(Vals.back());
3043 Vals = std::move(Next);
3044 }
3045 return Vals[0];
3046 };
3047
3048 // Replace a full-width load with a load of the freshly-merged alloca.
3049 // The merge stored a value of type Merged->getType() into NewAI; we load
3050 // that same type back so every access to NewAI stays consistently typed
3051 // (otherwise the alloca is no longer promotable).
3052 auto ReplaceFullLoad = [&](LoadInst *LoadToReplace, Value *Merged) {
3053 IRBuilder<> LoadBuilder(LoadToReplace);
3054 Value *NewLoad = LoadBuilder.CreateAlignedLoad(
3055 Merged->getType(), &NewAI, getSliceAlign(),
3056 LoadToReplace->isVolatile(),
3057 LoadToReplace->getName() + ".sroa.new.load");
3058 if (NewLoad->getType() != LoadToReplace->getType())
3059 NewLoad = LoadBuilder.CreateBitCast(NewLoad, LoadToReplace->getType());
3060 LoadToReplace->replaceAllUsesWith(NewLoad);
3061 DeletedValues.push_back(LoadToReplace);
3062 };
3063
3064 if (IsStoresOnlyPattern) {
3065 // Stores should not overlap and should cover the whole alloca.
3066 // Sort by begin offset to verify this with a single linear scan.
3067 llvm::sort(StoreInfos, [](const StoreInfo &A, const StoreInfo &B) {
3068 return A.BeginOffset < B.BeginOffset;
3069 });
3070 // Check for gap or overlap: each begin offset must equal the previous
3071 // end offset, i.e. the store ranges must tile [NewAllocaBeginOffset,
3072 // NewAllocaEndOffset) exactly.
3073 uint64_t Expected = NewAllocaBeginOffset;
3074 for (auto &Info : StoreInfos) {
3075 if (Info.BeginOffset != Expected)
3076 return std::nullopt;
3077 Expected = Info.EndOffset;
3078 }
3079 // Stores cover the entire alloca (no trailing gap either).
3080 if (Expected != NewAllocaEndOffset)
3081 return std::nullopt;
3082
3083 // The load should not be in the middle of the stores.
3084 // Note:
3085 // If the load is in a different basic block from the stores, we can
3086 // still do the tree-structured merge. We don't have store->load
3087 // forwarding here — the merged vector is stored back to NewAI and
3088 // the new load loads from NewAI. The forwarding will be handled
3089 // later when NewAI is promoted.
3090 BasicBlock *LoadBB = FullLoad->getParent();
3091 if (LoadBB == StoreBB) {
3092 for (auto &Info : StoreInfos)
3093 if (!Info.Store->comesBefore(FullLoad))
3094 return std::nullopt;
3095 }
3096
3097 LLVM_DEBUG({
3098 dbgs() << "Tree structured merge rewrite (stores-only):\n";
3099 dbgs() << " Load: " << *FullLoad << "\n Ordered stores:\n";
3100 for (auto [I, Info] : enumerate(StoreInfos)) {
3101 dbgs() << " [" << I << "] Range[" << Info.BeginOffset << ", "
3102 << Info.EndOffset << ") \tStore: " << *Info.Store
3103 << "\tValue: " << *Info.StoredValue << "\n";
3104 }
3105 });
3106
3107 // StoreInfos is sorted by offset, not by block order. Anchoring to
3108 // StoreInfos.back().Store (last by offset) can place shuffles before
3109 // operands that appear later in the block (invalid SSA). Insert before
3110 // FullLoad when it shares the store block (after all stores, before
3111 // any later IR in that block). Otherwise insert before the store
3112 // block's terminator so the merge runs after every store and any
3113 // trailing instructions in that block.
3114 IRBuilder<> Builder(LoadBB == StoreBB ? cast<Instruction>(FullLoad)
3115 : StoreBB->getTerminator());
3116 SmallVector<Value *, 8> Vals;
3117 for (const auto &Info : StoreInfos) {
3118 DeletedValues.push_back(Info.Store);
3119 Vals.push_back(Info.StoredValue);
3120 }
3121 // Merge all stored values and store the merged value into the alloca.
3122 Value *Merged = TreeMerge(Vals, Builder);
3123 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3124
3125 // Replace the original load with a load of the newly-merged alloca.
3126 ReplaceFullLoad(FullLoad, Merged);
3127 return DeletedValues;
3128 }
3129
3130 // RMW pattern handling starts from here.
3131 // Like StoreBB above: keep the init store, all partial loads and all
3132 // partial stores in one basic block so we can reason about ordering
3133 // with comesBefore and build SSA without PHIs.
3134 if (InitStore->getParent() != StoreBB)
3135 return std::nullopt;
3136 if (any_of(LoadInfos, [&](const LoadInfo &I) {
3137 return I.Load->getParent() != StoreBB;
3138 }))
3139 return std::nullopt;
3140 // FullLoad (if any) is allowed to live in a different basic block. See
3141 // the note on the stores-only path: we don't do store->load forwarding
3142 // directly — the merged vector is stored to NewAI and the new load
3143 // loads from NewAI, so cross-BB ordering is resolved later when NewAI
3144 // is promoted.
3145
3146 // Collect the combined partial-load/partial-store accesses sorted
3147 // by block order. Used both for ordering checks and for the rewrite
3148 // walk below.
3149 struct Access {
3150 Instruction *Inst;
3151 uint64_t BeginOffset, EndOffset;
3152 bool IsStore;
3153 };
3155 Accesses.reserve(LoadInfos.size() + StoreInfos.size());
3156 for (const auto &L : LoadInfos)
3157 Accesses.push_back({L.Load, L.BeginOffset, L.EndOffset, false});
3158 for (const auto &S : StoreInfos)
3159 Accesses.push_back({S.Store, S.BeginOffset, S.EndOffset, true});
3160 llvm::sort(Accesses, [](const Access &A, const Access &B) {
3161 return A.Inst->comesBefore(B.Inst);
3162 });
3163
3164 // Ordering constraint 1: InitStore must come before every partial
3165 // access — they read/write the RMW state initialised by InitStore.
3166 // Accesses is sorted by block order, so the first element is the
3167 // earliest; checking it is enough.
3168 if (!InitStore->comesBefore(Accesses.front().Inst))
3169 return std::nullopt;
3170 // Ordering constraint 2: when FullLoad shares the block with the
3171 // partial accesses, it must come after every one of them — otherwise
3172 // it could read a stale value. Accesses is sorted, so the last
3173 // element is the latest; checking it is enough. If FullLoad is in
3174 // another block, mem2reg forwards the merged store to it.
3175 if (FullLoad && FullLoad->getParent() == StoreBB &&
3176 !Accesses.back().Inst->comesBefore(FullLoad))
3177 return std::nullopt;
3178
3179 // Coverage check: the distinct [begin, end) ranges touched by the
3180 // partial loads and stores must tile the alloca disjointly. That is
3181 // the only precondition the per-range SliceValues tracking below
3182 // needs — a disjoint tile guarantees the entries don't alias each
3183 // other. We don't check per-range load/store counts: a range with
3184 // only loads ends with SliceValues[r] = the init extract
3185 // (contributed to the final tree-merge), and a range with only
3186 // stores ends with SliceValues[r] = its last stored value. Both are
3187 // correct.
3188 using SliceRange = std::pair<uint64_t, uint64_t>;
3189 SmallVector<SliceRange, 8> SortedRanges;
3190 SortedRanges.reserve(Accesses.size());
3191 for (auto &Acc : Accesses)
3192 SortedRanges.emplace_back(Acc.BeginOffset, Acc.EndOffset);
3193 llvm::sort(SortedRanges);
3194 SortedRanges.erase(llvm::unique(SortedRanges), SortedRanges.end());
3195 // Disjoint + contiguous tile of the whole alloca.
3196 uint64_t Expected = NewAllocaBeginOffset;
3197 for (auto &Range : SortedRanges) {
3198 if (Range.first != Expected)
3199 return std::nullopt;
3200 Expected = Range.second;
3201 }
3202 if (Expected != NewAllocaEndOffset)
3203 return std::nullopt;
3204
3205 LLVM_DEBUG({
3206 dbgs() << "Tree structured merge rewrite (RMW):\n";
3207 dbgs() << " Init store: " << *InitStore << "\n";
3208 if (FullLoad)
3209 dbgs() << " Final load: " << *FullLoad << "\n";
3210 dbgs() << " Slice ranges (" << SortedRanges.size() << "):\n";
3211 for (auto &Range : SortedRanges)
3212 dbgs() << " [" << Range.first << ", " << Range.second << ")\n";
3213 });
3214
3215 // Initialize SliceValues: one SSA value per slice range, tracking
3216 // the value the alloca currently holds at that range. Each entry
3217 // starts at the corresponding piece of the init store, obtained by
3218 // bitcasting the init value to the alloca's vector type (if needed)
3219 // and extracting the slice's sub-range.
3220 IRB.SetInsertPoint(InitStore->getNextNode());
3221 Value *InitVec = InitStore->getValueOperand();
3222 if (InitVec->getType() != NewAllocaTy)
3223 InitVec = IRB.CreateBitCast(InitVec, NewAllocaTy, "init.cast");
3224 DenseMap<SliceRange, Value *> SliceValues;
3225 for (auto &Range : SortedRanges) {
3226 unsigned BeginIdx = getIndex(Range.first);
3227 unsigned EndIdx = getIndex(Range.second);
3228 SliceValues[Range] = IRB.CreateShuffleVector(
3229 InitVec, createSequentialMask(BeginIdx, EndIdx - BeginIdx, 0),
3230 "init.extract");
3231 }
3232 // The init store itself becomes dead — its value is consumed via the
3233 // extracts above.
3234 DeletedValues.push_back(InitStore);
3235
3236 // Walk accesses in block order:
3237 // - partial load at range r: replace with SliceValues[r] (bitcast
3238 // if the load's type differs from the current tracked value's
3239 // type, e.g. because a previous store wrote a vector with a
3240 // different element type);
3241 // - partial store at range r: update SliceValues[r] to the stored
3242 // value and drop the store.
3243 for (auto &Acc : Accesses) {
3244 SliceRange Range{Acc.BeginOffset, Acc.EndOffset};
3245 if (!Acc.IsStore) {
3246 Value *V = SliceValues[Range];
3247 if (V->getType() != Acc.Inst->getType()) {
3248 IRB.SetInsertPoint(cast<LoadInst>(Acc.Inst));
3249 V = IRB.CreateBitCast(V, Acc.Inst->getType());
3250 }
3251 Acc.Inst->replaceAllUsesWith(V);
3252 } else {
3253 SliceValues[Range] = cast<StoreInst>(Acc.Inst)->getValueOperand();
3254 }
3255 DeletedValues.push_back(Acc.Inst);
3256 }
3257
3258 // Tree-merge the final per-range values (in range order) into the
3259 // alloca's final vector value. Anchor the IRBuilder to FullLoad (when it
3260 // shares the partial-access block) or otherwise to the block's
3261 // terminator — never to a partial access, since those are queued for
3262 // deletion. Both anchors are guaranteed to dominate every SliceValues
3263 // entry: each one is either an init extract (before any access) or a
3264 // stored value defined before its (now-deleted) store.
3265 IRBuilder<> Builder(FullLoad && FullLoad->getParent() == StoreBB
3266 ? cast<Instruction>(FullLoad)
3267 : StoreBB->getTerminator());
3268 SmallVector<Value *, 8> Vals;
3269 for (auto &Range : SortedRanges)
3270 Vals.push_back(SliceValues[Range]);
3271 Value *Merged = TreeMerge(Vals, Builder);
3272 Builder.CreateAlignedStore(Merged, &NewAI, getSliceAlign());
3273
3274 // Replace the optional final full-width load with a load of the newly
3275 // merged alloca. Later promotion will forward the store above to it.
3276 if (FullLoad)
3277 ReplaceFullLoad(FullLoad, Merged);
3278
3279 return DeletedValues;
3280 }
3281
3282private:
3283 // Make sure the other visit overloads are visible.
3284 using Base::visit;
3285
3286 // Every instruction which can end up as a user must have a rewrite rule.
3287 bool visitInstruction(Instruction &I) {
3288 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
3289 llvm_unreachable("No rewrite rule for this instruction!");
3290 }
3291
3292 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
3293 // Note that the offset computation can use BeginOffset or NewBeginOffset
3294 // interchangeably for unsplit slices.
3295 assert(IsSplit || BeginOffset == NewBeginOffset);
3296 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3297
3298 StringRef OldName = OldPtr->getName();
3299 // Skip through the last '.sroa.' component of the name.
3300 size_t LastSROAPrefix = OldName.rfind(".sroa.");
3301 if (LastSROAPrefix != StringRef::npos) {
3302 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
3303 // Look for an SROA slice index.
3304 size_t IndexEnd = OldName.find_first_not_of("0123456789");
3305 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
3306 // Strip the index and look for the offset.
3307 OldName = OldName.substr(IndexEnd + 1);
3308 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
3309 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
3310 // Strip the offset.
3311 OldName = OldName.substr(OffsetEnd + 1);
3312 }
3313 }
3314 // Strip any SROA suffixes as well.
3315 OldName = OldName.substr(0, OldName.find(".sroa_"));
3316
3317 return getAdjustedPtr(IRB, DL, &NewAI,
3318 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
3319 PointerTy, Twine(OldName) + ".");
3320 }
3321
3322 /// Compute suitable alignment to access this slice of the *new*
3323 /// alloca.
3324 ///
3325 /// You can optionally pass a type to this routine and if that type's ABI
3326 /// alignment is itself suitable, this will return zero.
3327 Align getSliceAlign() {
3328 return commonAlignment(NewAI.getAlign(),
3329 NewBeginOffset - NewAllocaBeginOffset);
3330 }
3331
3332 unsigned getIndex(uint64_t Offset) {
3333 assert(VecTy && "Can only call getIndex when rewriting a vector");
3334 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
3335 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
3336 uint32_t Index = RelOffset / ElementSize;
3337 assert(Index * ElementSize == RelOffset);
3338 return Index;
3339 }
3340
3341 void deleteIfTriviallyDead(Value *V) {
3344 Pass.DeadInsts.push_back(I);
3345 }
3346
3347 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
3348 unsigned BeginIndex = getIndex(NewBeginOffset);
3349 unsigned EndIndex = getIndex(NewEndOffset);
3350 assert(EndIndex > BeginIndex && "Empty vector!");
3351
3352 LoadInst *Load =
3353 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3354
3355 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3356 LLVMContext::MD_access_group});
3357 return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
3358 }
3359
3360 Value *rewriteIntegerLoad(LoadInst &LI) {
3361 assert(IntTy && "We cannot insert an integer to the alloca");
3362 assert(!LI.isVolatile());
3363 Value *V =
3364 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3365 V = IRB.CreateBitPreservingCastChain(DL, V, IntTy);
3366 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3367 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3368 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
3369 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
3370 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
3371 }
3372 // It is possible that the extracted type is not the load type. This
3373 // happens if there is a load past the end of the alloca, and as
3374 // a consequence the slice is narrower but still a candidate for integer
3375 // lowering. To handle this case, we just zero extend the extracted
3376 // integer.
3377 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
3378 "Can only handle an extract for an overly wide load");
3379 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
3380 V = IRB.CreateZExt(V, LI.getType());
3381 return V;
3382 }
3383
3384 bool visitLoadInst(LoadInst &LI) {
3385 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
3386 Value *OldOp = LI.getOperand(0);
3387 assert(OldOp == OldPtr);
3388
3389 AAMDNodes AATags = LI.getAAMetadata();
3390
3391 unsigned AS = LI.getPointerAddressSpace();
3392
3393 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
3394 : LI.getType();
3395 bool IsPtrAdjusted = false;
3396 Value *V;
3397 if (VecTy) {
3398 V = rewriteVectorizedLoadInst(LI);
3399 } else if (IntTy && LI.getType()->isIntegerTy()) {
3400 V = rewriteIntegerLoad(LI);
3401 } else if (NewBeginOffset == NewAllocaBeginOffset &&
3402 NewEndOffset == NewAllocaEndOffset &&
3403 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
3404 (NewAllocaTy->isIntegerTy() && TargetTy->isIntegerTy() &&
3405 DL.getTypeStoreSize(TargetTy).getFixedValue() > SliceSize &&
3406 !LI.isVolatile()))) {
3407 Value *NewPtr =
3408 getPtrToNewAI(LI.getPointerAddressSpace(), LI.isVolatile());
3409 LoadInst *NewLI = IRB.CreateAlignedLoad(
3410 NewAllocaTy, NewPtr, NewAI.getAlign(), LI.isVolatile(), LI.getName());
3411 if (LI.isVolatile())
3412 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3413 if (NewLI->isAtomic())
3414 NewLI->setAlignment(LI.getAlign());
3415
3416 // Copy any metadata that is valid for the new load. This may require
3417 // conversion to a different kind of metadata, e.g. !nonnull might change
3418 // to !range or vice versa.
3419 copyMetadataForLoad(*NewLI, LI);
3420
3421 // Do this after copyMetadataForLoad() to preserve the TBAA shift.
3422 if (AATags)
3423 NewLI->setAAMetadata(AATags.adjustForAccess(
3424 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3425
3426 // Try to preserve nonnull metadata
3427 V = NewLI;
3428
3429 // If this is an integer load past the end of the slice (which means the
3430 // bytes outside the slice are undef or this load is dead) just forcibly
3431 // fix the integer size with correct handling of endianness.
3432 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
3433 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
3434 if (AITy->getBitWidth() < TITy->getBitWidth()) {
3435 V = IRB.CreateZExt(V, TITy, "load.ext");
3436 if (DL.isBigEndian())
3437 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
3438 "endian_shift");
3439 }
3440 } else {
3441 Type *LTy = IRB.getPtrTy(AS);
3442 LoadInst *NewLI =
3443 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
3444 getSliceAlign(), LI.isVolatile(), LI.getName());
3445
3446 if (AATags)
3447 NewLI->setAAMetadata(AATags.adjustForAccess(
3448 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3449
3450 if (LI.isVolatile())
3451 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3452 NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3453 LLVMContext::MD_access_group});
3454
3455 V = NewLI;
3456 IsPtrAdjusted = true;
3457 }
3458 V = IRB.CreateBitPreservingCastChain(DL, V, TargetTy);
3459
3460 if (IsSplit) {
3461 assert(!LI.isVolatile());
3462 assert(LI.getType()->isIntegerTy() &&
3463 "Only integer type loads and stores are split");
3464 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedValue() &&
3465 "Split load isn't smaller than original load");
3466 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
3467 "Non-byte-multiple bit width");
3468 // Move the insertion point just past the load so that we can refer to it.
3469 BasicBlock::iterator LIIt = std::next(LI.getIterator());
3470 // Ensure the insertion point comes before any debug-info immediately
3471 // after the load, so that variable values referring to the load are
3472 // dominated by it.
3473 LIIt.setHeadBit(true);
3474 IRB.SetInsertPoint(LI.getParent(), LIIt);
3475 // Create a placeholder value with the same type as LI to use as the
3476 // basis for the new value. This allows us to replace the uses of LI with
3477 // the computed value, and then replace the placeholder with LI, leaving
3478 // LI only used for this computation.
3479 Value *Placeholder =
3480 new LoadInst(LI.getType(), PoisonValue::get(IRB.getPtrTy(AS)), "",
3481 false, Align(1));
3482 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
3483 "insert");
3484 LI.replaceAllUsesWith(V);
3485 Placeholder->replaceAllUsesWith(&LI);
3486 Placeholder->deleteValue();
3487 } else {
3488 LI.replaceAllUsesWith(V);
3489 }
3490
3491 Pass.DeadInsts.push_back(&LI);
3492 deleteIfTriviallyDead(OldOp);
3493 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
3494 return !LI.isVolatile() && !IsPtrAdjusted;
3495 }
3496
3497 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
3498 AAMDNodes AATags) {
3499 // Capture V for the purpose of debug-info accounting once it's converted
3500 // to a vector store.
3501 Value *OrigV = V;
3502 if (V->getType() != VecTy) {
3503 unsigned BeginIndex = getIndex(NewBeginOffset);
3504 unsigned EndIndex = getIndex(NewEndOffset);
3505 assert(EndIndex > BeginIndex && "Empty vector!");
3506 unsigned NumElements = EndIndex - BeginIndex;
3507 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3508 "Too many elements!");
3509 Type *SliceTy = (NumElements == 1)
3510 ? ElementTy
3511 : FixedVectorType::get(ElementTy, NumElements);
3512 if (V->getType() != SliceTy)
3513 V = IRB.CreateBitPreservingCastChain(DL, V, SliceTy);
3514
3515 // Mix in the existing elements.
3516 Value *Old =
3517 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3518 V = insertVector(IRB, Old, V, BeginIndex, "vec");
3519 }
3520 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3521 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3522 LLVMContext::MD_access_group});
3523 if (AATags)
3524 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3525 V->getType(), DL));
3526 Pass.DeadInsts.push_back(&SI);
3527
3528 // NOTE: Careful to use OrigV rather than V.
3529 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3530 Store, Store->getPointerOperand(), OrigV, DL);
3531 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3532 return true;
3533 }
3534
3535 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
3536 assert(IntTy && "We cannot extract an integer from the alloca");
3537 assert(!SI.isVolatile());
3538 if (DL.getTypeSizeInBits(V->getType()).getFixedValue() !=
3539 IntTy->getBitWidth()) {
3540 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3541 "oldload");
3542 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3543 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3544 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
3545 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
3546 }
3547 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3548 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3549 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3550 LLVMContext::MD_access_group});
3551 if (AATags)
3552 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3553 V->getType(), DL));
3554
3555 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3556 Store, Store->getPointerOperand(),
3557 Store->getValueOperand(), DL);
3558
3559 Pass.DeadInsts.push_back(&SI);
3560 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3561 return true;
3562 }
3563
3564 bool visitStoreInst(StoreInst &SI) {
3565 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
3566 Value *OldOp = SI.getOperand(1);
3567 assert(OldOp == OldPtr);
3568
3569 AAMDNodes AATags = SI.getAAMetadata();
3570 Value *V = SI.getValueOperand();
3571
3572 // Strip all inbounds GEPs and pointer casts to try to dig out any root
3573 // alloca that should be re-examined after promoting this alloca.
3574 if (V->getType()->isPointerTy())
3575 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
3576 Pass.PostPromotionWorklist.insert(AI);
3577
3578 TypeSize StoreSize = DL.getTypeStoreSize(V->getType());
3579 if (StoreSize.isFixed() && SliceSize < StoreSize.getFixedValue()) {
3580 assert(!SI.isVolatile());
3581 assert(V->getType()->isIntegerTy() &&
3582 "Only integer type loads and stores are split");
3583 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
3584 "Non-byte-multiple bit width");
3585 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
3586 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
3587 "extract");
3588 }
3589
3590 if (VecTy)
3591 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
3592 if (IntTy && V->getType()->isIntegerTy())
3593 return rewriteIntegerStore(V, SI, AATags);
3594
3595 StoreInst *NewSI;
3596 if (NewBeginOffset == NewAllocaBeginOffset &&
3597 NewEndOffset == NewAllocaEndOffset &&
3598 canConvertValue(DL, V->getType(), NewAllocaTy)) {
3599 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3600 Value *NewPtr =
3601 getPtrToNewAI(SI.getPointerAddressSpace(), SI.isVolatile());
3602
3603 NewSI =
3604 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), SI.isVolatile());
3605 } else {
3606 unsigned AS = SI.getPointerAddressSpace();
3607 Value *NewPtr = getNewAllocaSlicePtr(IRB, IRB.getPtrTy(AS));
3608 NewSI =
3609 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
3610 }
3611 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3612 LLVMContext::MD_access_group});
3613 if (AATags)
3614 NewSI->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3615 V->getType(), DL));
3616 if (SI.isVolatile())
3617 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
3618 if (NewSI->isAtomic())
3619 NewSI->setAlignment(SI.getAlign());
3620
3621 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3622 NewSI, NewSI->getPointerOperand(),
3623 NewSI->getValueOperand(), DL);
3624
3625 Pass.DeadInsts.push_back(&SI);
3626 deleteIfTriviallyDead(OldOp);
3627
3628 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
3629 return NewSI->getPointerOperand() == &NewAI &&
3630 NewSI->getValueOperand()->getType() == NewAllocaTy &&
3631 !SI.isVolatile();
3632 }
3633
3634 /// Compute an integer value from splatting an i8 across the given
3635 /// number of bytes.
3636 ///
3637 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
3638 /// call this routine.
3639 /// FIXME: Heed the advice above.
3640 ///
3641 /// \param V The i8 value to splat.
3642 /// \param Size The number of bytes in the output (assuming i8 is one byte)
3643 Value *getIntegerSplat(Value *V, unsigned Size) {
3644 assert(Size > 0 && "Expected a positive number of bytes.");
3645 IntegerType *VTy = cast<IntegerType>(V->getType());
3646 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
3647 if (Size == 1)
3648 return V;
3649
3650 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
3651 V = IRB.CreateMul(
3652 IRB.CreateZExt(V, SplatIntTy, "zext"),
3653 IRB.CreateUDiv(Constant::getAllOnesValue(SplatIntTy),
3654 IRB.CreateZExt(Constant::getAllOnesValue(V->getType()),
3655 SplatIntTy)),
3656 "isplat");
3657 return V;
3658 }
3659
3660 /// Compute a vector splat for a given element value.
3661 Value *getVectorSplat(Value *V, unsigned NumElements) {
3662 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
3663 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
3664 return V;
3665 }
3666
3667 bool visitMemSetInst(MemSetInst &II) {
3668 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3669 assert(II.getRawDest() == OldPtr);
3670
3671 AAMDNodes AATags = II.getAAMetadata();
3672
3673 // If the memset has a variable size, it cannot be split, just adjust the
3674 // pointer to the new alloca.
3675 if (!isa<ConstantInt>(II.getLength())) {
3676 assert(!IsSplit);
3677 assert(NewBeginOffset == BeginOffset);
3678 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
3679 II.setDestAlignment(getSliceAlign());
3680 // In theory we should call migrateDebugInfo here. However, we do not
3681 // emit dbg.assign intrinsics for mem intrinsics storing through non-
3682 // constant geps, or storing a variable number of bytes.
3684 "AT: Unexpected link to non-const GEP");
3685 deleteIfTriviallyDead(OldPtr);
3686 return false;
3687 }
3688
3689 // Record this instruction for deletion.
3690 Pass.DeadInsts.push_back(&II);
3691
3692 Type *ScalarTy = NewAllocaTy->getScalarType();
3693
3694 const bool CanContinue = [&]() {
3695 if (VecTy || IntTy)
3696 return true;
3697 if (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset)
3698 return false;
3699 // Length must be in range for FixedVectorType.
3700 auto *C = cast<ConstantInt>(II.getLength());
3701 const uint64_t Len = C->getLimitedValue();
3702 if (Len > std::numeric_limits<unsigned>::max())
3703 return false;
3704 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
3705 auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
3706 return canConvertValue(DL, SrcTy, NewAllocaTy) &&
3707 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedValue());
3708 }();
3709
3710 // If this doesn't map cleanly onto the alloca type, and that type isn't
3711 // a single value type, just emit a memset.
3712 if (!CanContinue) {
3713 Type *SizeTy = II.getLength()->getType();
3714 unsigned Sz = NewEndOffset - NewBeginOffset;
3715 Constant *Size = ConstantInt::get(SizeTy, Sz);
3716 MemIntrinsic *New = cast<MemIntrinsic>(IRB.CreateMemSet(
3717 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
3718 MaybeAlign(getSliceAlign()), II.isVolatile()));
3719 if (AATags)
3720 New->setAAMetadata(
3721 AATags.adjustForAccess(NewBeginOffset - BeginOffset, Sz));
3722
3723 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3724 New, New->getRawDest(), nullptr, DL);
3725
3726 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3727 return false;
3728 }
3729
3730 // If we can represent this as a simple value, we have to build the actual
3731 // value to store, which requires expanding the byte present in memset to
3732 // a sensible representation for the alloca type. This is essentially
3733 // splatting the byte to a sufficiently wide integer, splatting it across
3734 // any desired vector width, and bitcasting to the final type.
3735 Value *V;
3736
3737 if (VecTy) {
3738 // If this is a memset of a vectorized alloca, insert it.
3739 assert(ElementTy == ScalarTy);
3740
3741 unsigned BeginIndex = getIndex(NewBeginOffset);
3742 unsigned EndIndex = getIndex(NewEndOffset);
3743 assert(EndIndex > BeginIndex && "Empty vector!");
3744 unsigned NumElements = EndIndex - BeginIndex;
3745 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3746 "Too many elements!");
3747
3748 Value *Splat = getIntegerSplat(
3749 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8);
3750 Splat = IRB.CreateBitPreservingCastChain(DL, Splat, ElementTy);
3751 if (NumElements > 1)
3752 Splat = getVectorSplat(Splat, NumElements);
3753
3754 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3755 "oldload");
3756 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
3757 } else if (IntTy) {
3758 // If this is a memset on an alloca where we can widen stores, insert the
3759 // set integer.
3760 assert(!II.isVolatile());
3761
3762 uint64_t Size = NewEndOffset - NewBeginOffset;
3763 V = getIntegerSplat(II.getValue(), Size);
3764
3765 if (IntTy && (NewBeginOffset != NewAllocaBeginOffset ||
3766 NewEndOffset != NewAllocaEndOffset)) {
3767 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI,
3768 NewAI.getAlign(), "oldload");
3769 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3770 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3771 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
3772 } else {
3773 assert(V->getType() == IntTy &&
3774 "Wrong type for an alloca wide integer!");
3775 }
3776 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3777 } else {
3778 // Established these invariants above.
3779 assert(NewBeginOffset == NewAllocaBeginOffset);
3780 assert(NewEndOffset == NewAllocaEndOffset);
3781
3782 V = getIntegerSplat(II.getValue(),
3783 DL.getTypeSizeInBits(ScalarTy).getFixedValue() / 8);
3784 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(NewAllocaTy))
3785 V = getVectorSplat(
3786 V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
3787
3788 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3789 }
3790
3791 Value *NewPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3792 StoreInst *New =
3793 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), II.isVolatile());
3794 New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3795 LLVMContext::MD_access_group});
3796 if (AATags)
3797 New->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3798 V->getType(), DL));
3799
3800 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3801 New, New->getPointerOperand(), V, DL);
3802
3803 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3804 return !II.isVolatile();
3805 }
3806
3807 bool visitMemTransferInst(MemTransferInst &II) {
3808 // Rewriting of memory transfer instructions can be a bit tricky. We break
3809 // them into two categories: split intrinsics and unsplit intrinsics.
3810
3811 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3812
3813 AAMDNodes AATags = II.getAAMetadata();
3814
3815 bool IsDest = &II.getRawDestUse() == OldUse;
3816 assert((IsDest && II.getRawDest() == OldPtr) ||
3817 (!IsDest && II.getRawSource() == OldPtr));
3818
3819 Align SliceAlign = getSliceAlign();
3820 // For unsplit intrinsics, we simply modify the source and destination
3821 // pointers in place. This isn't just an optimization, it is a matter of
3822 // correctness. With unsplit intrinsics we may be dealing with transfers
3823 // within a single alloca before SROA ran, or with transfers that have
3824 // a variable length. We may also be dealing with memmove instead of
3825 // memcpy, and so simply updating the pointers is the necessary for us to
3826 // update both source and dest of a single call.
3827 if (!IsSplittable) {
3828 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3829 if (IsDest) {
3830 // Update the address component of linked dbg.assigns.
3831 for (DbgVariableRecord *DbgAssign : at::getDVRAssignmentMarkers(&II)) {
3832 if (llvm::is_contained(DbgAssign->location_ops(), II.getDest()) ||
3833 DbgAssign->getAddress() == II.getDest())
3834 DbgAssign->replaceVariableLocationOp(II.getDest(), AdjustedPtr);
3835 }
3836 II.setDest(AdjustedPtr);
3837 II.setDestAlignment(SliceAlign);
3838 } else {
3839 II.setSource(AdjustedPtr);
3840 II.setSourceAlignment(SliceAlign);
3841 }
3842
3843 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
3844 deleteIfTriviallyDead(OldPtr);
3845 return false;
3846 }
3847 // For split transfer intrinsics we have an incredibly useful assurance:
3848 // the source and destination do not reside within the same alloca, and at
3849 // least one of them does not escape. This means that we can replace
3850 // memmove with memcpy, and we don't need to worry about all manner of
3851 // downsides to splitting and transforming the operations.
3852
3853 // If this doesn't map cleanly onto the alloca type, and that type isn't
3854 // a single value type, just emit a memcpy.
3855 bool EmitMemCpy =
3856 !VecTy && !IntTy &&
3857 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
3858 SliceSize != DL.getTypeStoreSize(NewAllocaTy).getFixedValue() ||
3859 !DL.typeSizeEqualsStoreSize(NewAllocaTy) ||
3860 !NewAllocaTy->isSingleValueType());
3861
3862 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
3863 // size hasn't been shrunk based on analysis of the viable range, this is
3864 // a no-op.
3865 if (EmitMemCpy && &OldAI == &NewAI) {
3866 // Ensure the start lines up.
3867 assert(NewBeginOffset == BeginOffset);
3868
3869 // Rewrite the size as needed.
3870 if (NewEndOffset != EndOffset)
3871 II.setLength(NewEndOffset - NewBeginOffset);
3872 return false;
3873 }
3874 // Record this instruction for deletion.
3875 Pass.DeadInsts.push_back(&II);
3876
3877 // Strip all inbounds GEPs and pointer casts to try to dig out any root
3878 // alloca that should be re-examined after rewriting this instruction.
3879 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
3880 if (AllocaInst *AI =
3882 assert(AI != &OldAI && AI != &NewAI &&
3883 "Splittable transfers cannot reach the same alloca on both ends.");
3884 Pass.Worklist.insert(AI);
3885 }
3886
3887 Type *OtherPtrTy = OtherPtr->getType();
3888 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
3889
3890 // Compute the relative offset for the other pointer within the transfer.
3891 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
3892 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
3893 Align OtherAlign =
3894 (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
3895 OtherAlign =
3896 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
3897
3898 if (EmitMemCpy) {
3899 // Compute the other pointer, folding as much as possible to produce
3900 // a single, simple GEP in most cases.
3901 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3902 OtherPtr->getName() + ".");
3903
3904 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3905 Type *SizeTy = II.getLength()->getType();
3906 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
3907
3908 Value *DestPtr, *SrcPtr;
3909 MaybeAlign DestAlign, SrcAlign;
3910 // Note: IsDest is true iff we're copying into the new alloca slice
3911 if (IsDest) {
3912 DestPtr = OurPtr;
3913 DestAlign = SliceAlign;
3914 SrcPtr = OtherPtr;
3915 SrcAlign = OtherAlign;
3916 } else {
3917 DestPtr = OtherPtr;
3918 DestAlign = OtherAlign;
3919 SrcPtr = OurPtr;
3920 SrcAlign = SliceAlign;
3921 }
3922 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
3923 Size, II.isVolatile());
3924 if (AATags)
3925 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
3926
3927 APInt Offset(DL.getIndexTypeSizeInBits(DestPtr->getType()), 0);
3928 if (IsDest) {
3929 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8,
3930 &II, New, DestPtr, nullptr, DL);
3931 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
3933 DL, Offset, /*AllowNonInbounds*/ true))) {
3934 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8,
3935 SliceSize * 8, &II, New, DestPtr, nullptr, DL);
3936 }
3937 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3938 return false;
3939 }
3940
3941 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
3942 NewEndOffset == NewAllocaEndOffset;
3943 uint64_t Size = NewEndOffset - NewBeginOffset;
3944 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3945 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
3946 unsigned NumElements = EndIndex - BeginIndex;
3947 IntegerType *SubIntTy =
3948 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
3949
3950 // Reset the other pointer type to match the register type we're going to
3951 // use, but using the address space of the original other pointer.
3952 Type *OtherTy;
3953 if (VecTy && !IsWholeAlloca) {
3954 if (NumElements == 1)
3955 OtherTy = VecTy->getElementType();
3956 else
3957 OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
3958 } else if (IntTy && !IsWholeAlloca) {
3959 OtherTy = SubIntTy;
3960 } else {
3961 OtherTy = NewAllocaTy;
3962 }
3963
3964 Value *AdjPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3965 OtherPtr->getName() + ".");
3966 MaybeAlign SrcAlign = OtherAlign;
3967 MaybeAlign DstAlign = SliceAlign;
3968 if (!IsDest)
3969 std::swap(SrcAlign, DstAlign);
3970
3971 Value *SrcPtr;
3972 Value *DstPtr;
3973
3974 if (IsDest) {
3975 DstPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3976 SrcPtr = AdjPtr;
3977 } else {
3978 DstPtr = AdjPtr;
3979 SrcPtr = getPtrToNewAI(II.getSourceAddressSpace(), II.isVolatile());
3980 }
3981
3982 Value *Src;
3983 if (VecTy && !IsWholeAlloca && !IsDest) {
3984 Src =
3985 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3986 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3987 } else if (IntTy && !IsWholeAlloca && !IsDest) {
3988 Src =
3989 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3990 Src = IRB.CreateBitPreservingCastChain(DL, Src, IntTy);
3991 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3992 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3993 } else {
3994 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3995 II.isVolatile(), "copyload");
3996 Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3997 LLVMContext::MD_access_group});
3998 if (AATags)
3999 Load->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4000 Load->getType(), DL));
4001 Src = Load;
4002 }
4003
4004 if (VecTy && !IsWholeAlloca && IsDest) {
4005 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4006 "oldload");
4007 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
4008 } else if (IntTy && !IsWholeAlloca && IsDest) {
4009 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4010 "oldload");
4011 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
4012 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
4013 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
4014 Src = IRB.CreateBitPreservingCastChain(DL, Src, NewAllocaTy);
4015 }
4016
4017 StoreInst *Store = cast<StoreInst>(
4018 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
4019 Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
4020 LLVMContext::MD_access_group});
4021 if (AATags)
4022 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4023 Src->getType(), DL));
4024
4025 APInt Offset(DL.getIndexTypeSizeInBits(DstPtr->getType()), 0);
4026 if (IsDest) {
4027
4028 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
4029 Store, DstPtr, Src, DL);
4030 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
4032 DL, Offset, /*AllowNonInbounds*/ true))) {
4033 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8, SliceSize * 8,
4034 &II, Store, DstPtr, Src, DL);
4035 }
4036
4037 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4038 return !II.isVolatile();
4039 }
4040
4041 bool visitIntrinsicInst(IntrinsicInst &II) {
4042 assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&
4043 "Unexpected intrinsic!");
4044 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
4045
4046 // Record this instruction for deletion.
4047 Pass.DeadInsts.push_back(&II);
4048
4049 if (II.isDroppable()) {
4050 assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume");
4051 // TODO For now we forget assumed information, this can be improved.
4052 OldPtr->dropDroppableUsesIn(II);
4053 return true;
4054 }
4055
4056 assert(II.getArgOperand(0) == OldPtr);
4057 Type *PointerTy = IRB.getPtrTy(OldPtr->getType()->getPointerAddressSpace());
4058 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
4059 Value *New;
4060 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
4061 New = IRB.CreateLifetimeStart(Ptr);
4062 else
4063 New = IRB.CreateLifetimeEnd(Ptr);
4064
4065 (void)New;
4066 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
4067
4068 return true;
4069 }
4070
4071 void fixLoadStoreAlign(Instruction &Root) {
4072 // This algorithm implements the same visitor loop as
4073 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
4074 // or store found.
4075 SmallPtrSet<Instruction *, 4> Visited;
4076 SmallVector<Instruction *, 4> Uses;
4077 Visited.insert(&Root);
4078 Uses.push_back(&Root);
4079 do {
4080 Instruction *I = Uses.pop_back_val();
4081
4082 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4083 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
4084 continue;
4085 }
4086 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4087 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
4088 continue;
4089 }
4090
4094 for (User *U : I->users())
4095 if (Visited.insert(cast<Instruction>(U)).second)
4096 Uses.push_back(cast<Instruction>(U));
4097 } while (!Uses.empty());
4098 }
4099
4100 bool visitPHINode(PHINode &PN) {
4101 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
4102 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
4103 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
4104
4105 // We would like to compute a new pointer in only one place, but have it be
4106 // as local as possible to the PHI. To do that, we re-use the location of
4107 // the old pointer, which necessarily must be in the right position to
4108 // dominate the PHI.
4109 IRBuilderBase::InsertPointGuard Guard(IRB);
4110 if (isa<PHINode>(OldPtr))
4111 IRB.SetInsertPoint(OldPtr->getParent(),
4112 OldPtr->getParent()->getFirstInsertionPt());
4113 else
4114 IRB.SetInsertPoint(OldPtr);
4115 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
4116
4117 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4118 // Replace the operands which were using the old pointer.
4119 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
4120
4121 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
4122 deleteIfTriviallyDead(OldPtr);
4123
4124 // Fix the alignment of any loads or stores using this PHI node.
4125 fixLoadStoreAlign(PN);
4126
4127 // PHIs can't be promoted on their own, but often can be speculated. We
4128 // check the speculation outside of the rewriter so that we see the
4129 // fully-rewritten alloca.
4130 PHIUsers.insert(&PN);
4131 return true;
4132 }
4133
4134 bool visitSelectInst(SelectInst &SI) {
4135 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4136 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
4137 "Pointer isn't an operand!");
4138 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
4139 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
4140
4141 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4142 // Replace the operands which were using the old pointer.
4143 if (SI.getOperand(1) == OldPtr)
4144 SI.setOperand(1, NewPtr);
4145 if (SI.getOperand(2) == OldPtr)
4146 SI.setOperand(2, NewPtr);
4147
4148 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
4149 deleteIfTriviallyDead(OldPtr);
4150
4151 // Fix the alignment of any loads or stores using this select.
4152 fixLoadStoreAlign(SI);
4153
4154 // Selects can't be promoted on their own, but often can be speculated. We
4155 // check the speculation outside of the rewriter so that we see the
4156 // fully-rewritten alloca.
4157 SelectUsers.insert(&SI);
4158 return true;
4159 }
4160};
4161
4162/// Visitor to rewrite aggregate loads and stores as scalar.
4163///
4164/// This pass aggressively rewrites all aggregate loads and stores on
4165/// a particular pointer (or any pointer derived from it which we can identify)
4166/// with scalar loads and stores.
4167class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
4168 // Befriend the base class so it can delegate to private visit methods.
4169 friend class InstVisitor<AggLoadStoreRewriter, bool>;
4170
4171 /// Queue of pointer uses to analyze and potentially rewrite.
4173
4174 /// Set to prevent us from cycling with phi nodes and loops.
4175 SmallPtrSet<User *, 8> Visited;
4176
4177 /// The current pointer use being rewritten. This is used to dig up the used
4178 /// value (as opposed to the user).
4179 Use *U = nullptr;
4180
4181 /// Used to calculate offsets, and hence alignment, of subobjects.
4182 const DataLayout &DL;
4183
4184 IRBuilderTy &IRB;
4185
4186public:
4187 AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
4188 : DL(DL), IRB(IRB) {}
4189
4190 /// Rewrite loads and stores through a pointer and all pointers derived from
4191 /// it.
4192 bool rewrite(Instruction &I) {
4193 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
4194 enqueueUsers(I);
4195 bool Changed = false;
4196 while (!Queue.empty()) {
4197 U = Queue.pop_back_val();
4198 Changed |= visit(cast<Instruction>(U->getUser()));
4199 }
4200 return Changed;
4201 }
4202
4203private:
4204 /// Enqueue all the users of the given instruction for further processing.
4205 /// This uses a set to de-duplicate users.
4206 void enqueueUsers(Instruction &I) {
4207 for (Use &U : I.uses())
4208 if (Visited.insert(U.getUser()).second)
4209 Queue.push_back(&U);
4210 }
4211
4212 // Conservative default is to not rewrite anything.
4213 bool visitInstruction(Instruction &I) { return false; }
4214
4215 /// Generic recursive split emission class.
4216 template <typename Derived> class OpSplitter {
4217 protected:
4218 /// The builder used to form new instructions.
4219 IRBuilderTy &IRB;
4220
4221 /// The indices which to be used with insert- or extractvalue to select the
4222 /// appropriate value within the aggregate.
4223 SmallVector<unsigned, 4> Indices;
4224
4225 /// The indices to a GEP instruction which will move Ptr to the correct slot
4226 /// within the aggregate.
4227 SmallVector<Value *, 4> GEPIndices;
4228
4229 /// The base pointer of the original op, used as a base for GEPing the
4230 /// split operations.
4231 Value *Ptr;
4232
4233 /// The base pointee type being GEPed into.
4234 Type *BaseTy;
4235
4236 /// Known alignment of the base pointer.
4237 Align BaseAlign;
4238
4239 /// To calculate offset of each component so we can correctly deduce
4240 /// alignments.
4241 const DataLayout &DL;
4242
4243 /// Initialize the splitter with an insertion point, Ptr and start with a
4244 /// single zero GEP index.
4245 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4246 Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
4247 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
4248 BaseAlign(BaseAlign), DL(DL) {
4249 IRB.SetInsertPoint(InsertionPoint);
4250 }
4251
4252 public:
4253 /// Generic recursive split emission routine.
4254 ///
4255 /// This method recursively splits an aggregate op (load or store) into
4256 /// scalar or vector ops. It splits recursively until it hits a single value
4257 /// and emits that single value operation via the template argument.
4258 ///
4259 /// The logic of this routine relies on GEPs and insertvalue and
4260 /// extractvalue all operating with the same fundamental index list, merely
4261 /// formatted differently (GEPs need actual values).
4262 ///
4263 /// \param Ty The type being split recursively into smaller ops.
4264 /// \param Agg The aggregate value being built up or stored, depending on
4265 /// whether this is splitting a load or a store respectively.
4266 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
4267 if (Ty->isSingleValueType()) {
4268 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
4269 return static_cast<Derived *>(this)->emitFunc(
4270 Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
4271 }
4272
4273 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
4274 unsigned OldSize = Indices.size();
4275 (void)OldSize;
4276 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
4277 ++Idx) {
4278 assert(Indices.size() == OldSize && "Did not return to the old size");
4279 Indices.push_back(Idx);
4280 GEPIndices.push_back(IRB.getInt32(Idx));
4281 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
4282 GEPIndices.pop_back();
4283 Indices.pop_back();
4284 }
4285 return;
4286 }
4287
4288 if (StructType *STy = dyn_cast<StructType>(Ty)) {
4289 unsigned OldSize = Indices.size();
4290 (void)OldSize;
4291 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
4292 ++Idx) {
4293 assert(Indices.size() == OldSize && "Did not return to the old size");
4294 Indices.push_back(Idx);
4295 GEPIndices.push_back(IRB.getInt32(Idx));
4296 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
4297 GEPIndices.pop_back();
4298 Indices.pop_back();
4299 }
4300 return;
4301 }
4302
4303 llvm_unreachable("Only arrays and structs are aggregate loadable types");
4304 }
4305 };
4306
4307 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
4308 AAMDNodes AATags;
4309 // A vector to hold the split components that we want to emit
4310 // separate fake uses for.
4311 SmallVector<Value *, 4> Components;
4312 // A vector to hold all the fake uses of the struct that we are splitting.
4313 // Usually there should only be one, but we are handling the general case.
4315
4316 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4317 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
4318 IRBuilderTy &IRB)
4319 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
4320 IRB),
4321 AATags(AATags) {}
4322
4323 /// Emit a leaf load of a single value. This is called at the leaves of the
4324 /// recursive emission to actually load values.
4325 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4327 // Load the single value and insert it using the indices.
4328 Value *GEP =
4329 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4330 LoadInst *Load =
4331 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
4332
4333 APInt Offset(
4334 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4335 if (AATags &&
4336 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
4337 Load->setAAMetadata(
4338 AATags.adjustForAccess(Offset.getZExtValue(), Load->getType(), DL));
4339 // Record the load so we can generate a fake use for this aggregate
4340 // component.
4341 Components.push_back(Load);
4342
4343 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
4344 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
4345 }
4346
4347 // Stash the fake uses that use the value generated by this instruction.
4348 void recordFakeUses(LoadInst &LI) {
4349 for (Use &U : LI.uses())
4350 if (auto *II = dyn_cast<IntrinsicInst>(U.getUser()))
4351 if (II->getIntrinsicID() == Intrinsic::fake_use)
4352 FakeUses.push_back(II);
4353 }
4354
4355 // Replace all fake uses of the aggregate with a series of fake uses, one
4356 // for each split component.
4357 void emitFakeUses() {
4358 for (Instruction *I : FakeUses) {
4359 IRB.SetInsertPoint(I);
4360 for (auto *V : Components)
4361 IRB.CreateIntrinsic(Intrinsic::fake_use, {V});
4362 I->eraseFromParent();
4363 }
4364 }
4365 };
4366
4367 bool visitLoadInst(LoadInst &LI) {
4368 assert(LI.getPointerOperand() == *U);
4369 if (!LI.isSimple() || LI.getType()->isSingleValueType())
4370 return false;
4371
4372 // We have an aggregate being loaded, split it apart.
4373 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
4374 LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
4375 getAdjustedAlignment(&LI, 0), DL, IRB);
4376 Splitter.recordFakeUses(LI);
4378 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
4379 Splitter.emitFakeUses();
4380 Visited.erase(&LI);
4381 LI.replaceAllUsesWith(V);
4382 LI.eraseFromParent();
4383 return true;
4384 }
4385
4386 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
4387 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4388 AAMDNodes AATags, StoreInst *AggStore, Align BaseAlign,
4389 const DataLayout &DL, IRBuilderTy &IRB)
4390 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
4391 DL, IRB),
4392 AATags(AATags), AggStore(AggStore) {}
4393 AAMDNodes AATags;
4394 StoreInst *AggStore;
4395 /// Emit a leaf store of a single value. This is called at the leaves of the
4396 /// recursive emission to actually produce stores.
4397 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4399 // Extract the single value and store it using the indices.
4400 //
4401 // The gep and extractvalue values are factored out of the CreateStore
4402 // call to make the output independent of the argument evaluation order.
4403 Value *ExtractValue =
4404 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
4405 Value *InBoundsGEP =
4406 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4407 StoreInst *Store =
4408 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
4409
4410 APInt Offset(
4411 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4412 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset);
4413 if (AATags) {
4414 Store->setAAMetadata(AATags.adjustForAccess(
4415 Offset.getZExtValue(), ExtractValue->getType(), DL));
4416 }
4417
4418 // migrateDebugInfo requires the base Alloca. Walk to it from this gep.
4419 // If we cannot (because there's an intervening non-const or unbounded
4420 // gep) then we wouldn't expect to see dbg.assign intrinsics linked to
4421 // this instruction.
4423 if (auto *OldAI = dyn_cast<AllocaInst>(Base)) {
4424 uint64_t SizeInBits =
4425 DL.getTypeSizeInBits(Store->getValueOperand()->getType());
4426 migrateDebugInfo(OldAI, /*IsSplit*/ true, Offset.getZExtValue() * 8,
4427 SizeInBits, AggStore, Store,
4428 Store->getPointerOperand(), Store->getValueOperand(),
4429 DL);
4430 } else {
4432 "AT: unexpected debug.assign linked to store through "
4433 "unbounded GEP");
4434 }
4435 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4436 }
4437 };
4438
4439 bool visitStoreInst(StoreInst &SI) {
4440 if (!SI.isSimple() || SI.getPointerOperand() != *U)
4441 return false;
4442 Value *V = SI.getValueOperand();
4443 if (V->getType()->isSingleValueType())
4444 return false;
4445
4446 // We have an aggregate being stored, split it apart.
4447 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4448 StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(), &SI,
4449 getAdjustedAlignment(&SI, 0), DL, IRB);
4450 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
4451 Visited.erase(&SI);
4452 // The stores replacing SI each have markers describing fragments of the
4453 // assignment so delete the assignment markers linked to SI.
4455 SI.eraseFromParent();
4456 return true;
4457 }
4458
4459 bool visitBitCastInst(BitCastInst &BC) {
4460 enqueueUsers(BC);
4461 return false;
4462 }
4463
4464 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
4465 enqueueUsers(ASC);
4466 return false;
4467 }
4468
4469 // Unfold gep (select cond, ptr1, ptr2), idx
4470 // => select cond, gep(ptr1, idx), gep(ptr2, idx)
4471 // and gep ptr, (select cond, idx1, idx2)
4472 // => select cond, gep(ptr, idx1), gep(ptr, idx2)
4473 // We also allow for i1 zext indices, which are equivalent to selects.
4474 bool unfoldGEPSelect(GetElementPtrInst &GEPI) {
4475 // Check whether the GEP has exactly one select operand and all indices
4476 // will become constant after the transform.
4478 for (Value *Op : GEPI.indices()) {
4479 if (auto *SI = dyn_cast<SelectInst>(Op)) {
4480 if (Sel)
4481 return false;
4482
4483 Sel = SI;
4484 if (!isa<ConstantInt>(SI->getTrueValue()) ||
4485 !isa<ConstantInt>(SI->getFalseValue()))
4486 return false;
4487 continue;
4488 }
4489 if (auto *ZI = dyn_cast<ZExtInst>(Op)) {
4490 if (Sel)
4491 return false;
4492 Sel = ZI;
4493 if (!ZI->getSrcTy()->isIntegerTy(1))
4494 return false;
4495 continue;
4496 }
4497
4498 if (!isa<ConstantInt>(Op))
4499 return false;
4500 }
4501
4502 if (!Sel)
4503 return false;
4504
4505 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):\n";
4506 dbgs() << " original: " << *Sel << "\n";
4507 dbgs() << " " << GEPI << "\n";);
4508
4509 auto GetNewOps = [&](Value *SelOp) {
4510 SmallVector<Value *> NewOps;
4511 for (Value *Op : GEPI.operands())
4512 if (Op == Sel)
4513 NewOps.push_back(SelOp);
4514 else
4515 NewOps.push_back(Op);
4516 return NewOps;
4517 };
4518
4519 Value *Cond, *True, *False;
4520 Instruction *MDFrom = nullptr;
4521 if (auto *SI = dyn_cast<SelectInst>(Sel)) {
4522 Cond = SI->getCondition();
4523 True = SI->getTrueValue();
4524 False = SI->getFalseValue();
4526 MDFrom = SI;
4527 } else {
4528 Cond = Sel->getOperand(0);
4529 True = ConstantInt::get(Sel->getType(), 1);
4530 False = ConstantInt::get(Sel->getType(), 0);
4531 }
4532 SmallVector<Value *> TrueOps = GetNewOps(True);
4533 SmallVector<Value *> FalseOps = GetNewOps(False);
4534
4535 IRB.SetInsertPoint(&GEPI);
4536 GEPNoWrapFlags NW = GEPI.getNoWrapFlags();
4537
4538 Type *Ty = GEPI.getSourceElementType();
4539 Value *NTrue = IRB.CreateGEP(Ty, TrueOps[0], ArrayRef(TrueOps).drop_front(),
4540 True->getName() + ".sroa.gep", NW);
4541
4542 Value *NFalse =
4543 IRB.CreateGEP(Ty, FalseOps[0], ArrayRef(FalseOps).drop_front(),
4544 False->getName() + ".sroa.gep", NW);
4545
4546 Value *NSel = MDFrom
4547 ? IRB.CreateSelect(Cond, NTrue, NFalse,
4548 Sel->getName() + ".sroa.sel", MDFrom)
4549 : IRB.CreateSelectWithUnknownProfile(
4550 Cond, NTrue, NFalse, DEBUG_TYPE,
4551 Sel->getName() + ".sroa.sel");
4552 Visited.erase(&GEPI);
4553 GEPI.replaceAllUsesWith(NSel);
4554 GEPI.eraseFromParent();
4555 Instruction *NSelI = cast<Instruction>(NSel);
4556 Visited.insert(NSelI);
4557 enqueueUsers(*NSelI);
4558
4559 LLVM_DEBUG(dbgs() << " to: " << *NTrue << "\n";
4560 dbgs() << " " << *NFalse << "\n";
4561 dbgs() << " " << *NSel << "\n";);
4562
4563 return true;
4564 }
4565
4566 // Unfold gep (phi ptr1, ptr2), idx
4567 // => phi ((gep ptr1, idx), (gep ptr2, idx))
4568 // and gep ptr, (phi idx1, idx2)
4569 // => phi ((gep ptr, idx1), (gep ptr, idx2))
4570 bool unfoldGEPPhi(GetElementPtrInst &GEPI) {
4571 // To prevent infinitely expanding recursive phis, bail if the GEP pointer
4572 // operand (looking through the phi if it is the phi we want to unfold) is
4573 // an instruction besides a static alloca.
4574 PHINode *Phi = dyn_cast<PHINode>(GEPI.getPointerOperand());
4575 auto IsInvalidPointerOperand = [](Value *V) {
4576 if (!isa<Instruction>(V))
4577 return false;
4578 if (auto *AI = dyn_cast<AllocaInst>(V))
4579 return !AI->isStaticAlloca();
4580 return true;
4581 };
4582 if (Phi) {
4583 if (any_of(Phi->operands(), IsInvalidPointerOperand))
4584 return false;
4585 } else {
4586 if (IsInvalidPointerOperand(GEPI.getPointerOperand()))
4587 return false;
4588 }
4589 // Check whether the GEP has exactly one phi operand (including the pointer
4590 // operand) and all indices will become constant after the transform.
4591 for (Value *Op : GEPI.indices()) {
4592 if (auto *SI = dyn_cast<PHINode>(Op)) {
4593 if (Phi)
4594 return false;
4595
4596 Phi = SI;
4597 if (!all_of(Phi->incoming_values(),
4598 [](Value *V) { return isa<ConstantInt>(V); }))
4599 return false;
4600 continue;
4601 }
4602
4603 if (!isa<ConstantInt>(Op))
4604 return false;
4605 }
4606
4607 if (!Phi)
4608 return false;
4609
4610 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):\n";
4611 dbgs() << " original: " << *Phi << "\n";
4612 dbgs() << " " << GEPI << "\n";);
4613
4614 auto GetNewOps = [&](Value *PhiOp) {
4615 SmallVector<Value *> NewOps;
4616 for (Value *Op : GEPI.operands())
4617 if (Op == Phi)
4618 NewOps.push_back(PhiOp);
4619 else
4620 NewOps.push_back(Op);
4621 return NewOps;
4622 };
4623
4624 IRB.SetInsertPoint(Phi);
4625 PHINode *NewPhi = IRB.CreatePHI(GEPI.getType(), Phi->getNumIncomingValues(),
4626 Phi->getName() + ".sroa.phi");
4627
4628 Type *SourceTy = GEPI.getSourceElementType();
4629 // We only handle arguments, constants, and static allocas here, so we can
4630 // insert GEPs at the end of the entry block.
4631 IRB.SetInsertPoint(GEPI.getFunction()->getEntryBlock().getTerminator());
4632 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
4633 Value *Op = Phi->getIncomingValue(I);
4634 BasicBlock *BB = Phi->getIncomingBlock(I);
4635 Value *NewGEP;
4636 if (int NI = NewPhi->getBasicBlockIndex(BB); NI >= 0) {
4637 NewGEP = NewPhi->getIncomingValue(NI);
4638 } else {
4639 SmallVector<Value *> NewOps = GetNewOps(Op);
4640 NewGEP =
4641 IRB.CreateGEP(SourceTy, NewOps[0], ArrayRef(NewOps).drop_front(),
4642 Phi->getName() + ".sroa.gep", GEPI.getNoWrapFlags());
4643 }
4644 NewPhi->addIncoming(NewGEP, BB);
4645 }
4646
4647 Visited.erase(&GEPI);
4648 GEPI.replaceAllUsesWith(NewPhi);
4649 GEPI.eraseFromParent();
4650 Visited.insert(NewPhi);
4651 enqueueUsers(*NewPhi);
4652
4653 LLVM_DEBUG(dbgs() << " to: ";
4654 for (Value *In
4655 : NewPhi->incoming_values()) dbgs()
4656 << "\n " << *In;
4657 dbgs() << "\n " << *NewPhi << '\n');
4658
4659 return true;
4660 }
4661
4662 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
4663 if (unfoldGEPSelect(GEPI))
4664 return true;
4665
4666 if (unfoldGEPPhi(GEPI))
4667 return true;
4668
4669 enqueueUsers(GEPI);
4670 return false;
4671 }
4672
4673 bool visitPHINode(PHINode &PN) {
4674 enqueueUsers(PN);
4675 return false;
4676 }
4677
4678 bool visitSelectInst(SelectInst &SI) {
4679 enqueueUsers(SI);
4680 return false;
4681 }
4682};
4683
4684} // end anonymous namespace
4685
4686/// Strip aggregate type wrapping.
4687///
4688/// This removes no-op aggregate types wrapping an underlying type. It will
4689/// strip as many layers of types as it can without changing either the type
4690/// size or the allocated size.
4692 if (Ty->isSingleValueType())
4693 return Ty;
4694
4695 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedValue();
4696 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
4697
4698 Type *InnerTy;
4699 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
4700 InnerTy = ArrTy->getElementType();
4701 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
4702 const StructLayout *SL = DL.getStructLayout(STy);
4703 unsigned Index = SL->getElementContainingOffset(0);
4704 InnerTy = STy->getElementType(Index);
4705 } else {
4706 return Ty;
4707 }
4708
4709 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedValue() ||
4710 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedValue())
4711 return Ty;
4712
4713 return stripAggregateTypeWrapping(DL, InnerTy);
4714}
4715
4716/// Try to find a partition of the aggregate type passed in for a given
4717/// offset and size.
4718///
4719/// This recurses through the aggregate type and tries to compute a subtype
4720/// based on the offset and size. When the offset and size span a sub-section
4721/// of an array, it will even compute a new array type for that sub-section,
4722/// and the same for structs.
4723///
4724/// Note that this routine is very strict and tries to find a partition of the
4725/// type which produces the *exact* right offset and size. It is not forgiving
4726/// when the size or offset cause either end of type-based partition to be off.
4727/// Also, this is a best-effort routine. It is reasonable to give up and not
4728/// return a type if necessary.
4730 uint64_t Size) {
4731 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedValue() == Size)
4732 return stripAggregateTypeWrapping(DL, Ty);
4733 if (Offset > DL.getTypeAllocSize(Ty).getFixedValue() ||
4734 (DL.getTypeAllocSize(Ty).getFixedValue() - Offset) < Size)
4735 return nullptr;
4736
4737 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
4738 Type *ElementTy;
4739 uint64_t TyNumElements;
4740 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
4741 ElementTy = AT->getElementType();
4742 TyNumElements = AT->getNumElements();
4743 } else {
4744 // FIXME: This isn't right for vectors with non-byte-sized or
4745 // non-power-of-two sized elements.
4746 auto *VT = cast<FixedVectorType>(Ty);
4747 ElementTy = VT->getElementType();
4748 TyNumElements = VT->getNumElements();
4749 }
4750 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4751 uint64_t NumSkippedElements = Offset / ElementSize;
4752 if (NumSkippedElements >= TyNumElements)
4753 return nullptr;
4754 Offset -= NumSkippedElements * ElementSize;
4755
4756 // First check if we need to recurse.
4757 if (Offset > 0 || Size < ElementSize) {
4758 // Bail if the partition ends in a different array element.
4759 if ((Offset + Size) > ElementSize)
4760 return nullptr;
4761 // Recurse through the element type trying to peel off offset bytes.
4762 return getTypePartition(DL, ElementTy, Offset, Size);
4763 }
4764 assert(Offset == 0);
4765
4766 if (Size == ElementSize)
4767 return stripAggregateTypeWrapping(DL, ElementTy);
4768 assert(Size > ElementSize);
4769 uint64_t NumElements = Size / ElementSize;
4770 if (NumElements * ElementSize != Size)
4771 return nullptr;
4772 return ArrayType::get(ElementTy, NumElements);
4773 }
4774
4776 if (!STy)
4777 return nullptr;
4778
4779 const StructLayout *SL = DL.getStructLayout(STy);
4780
4781 if (SL->getSizeInBits().isScalable())
4782 return nullptr;
4783
4784 if (Offset >= SL->getSizeInBytes())
4785 return nullptr;
4786 uint64_t EndOffset = Offset + Size;
4787 if (EndOffset > SL->getSizeInBytes())
4788 return nullptr;
4789
4790 unsigned Index = SL->getElementContainingOffset(Offset);
4791 Offset -= SL->getElementOffset(Index);
4792
4793 Type *ElementTy = STy->getElementType(Index);
4794 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4795 if (Offset >= ElementSize)
4796 return nullptr; // The offset points into alignment padding.
4797
4798 // See if any partition must be contained by the element.
4799 if (Offset > 0 || Size < ElementSize) {
4800 if ((Offset + Size) > ElementSize)
4801 return nullptr;
4802 return getTypePartition(DL, ElementTy, Offset, Size);
4803 }
4804 assert(Offset == 0);
4805
4806 if (Size == ElementSize)
4807 return stripAggregateTypeWrapping(DL, ElementTy);
4808
4809 StructType::element_iterator EI = STy->element_begin() + Index,
4810 EE = STy->element_end();
4811 if (EndOffset < SL->getSizeInBytes()) {
4812 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
4813 if (Index == EndIndex)
4814 return nullptr; // Within a single element and its padding.
4815
4816 // Don't try to form "natural" types if the elements don't line up with the
4817 // expected size.
4818 // FIXME: We could potentially recurse down through the last element in the
4819 // sub-struct to find a natural end point.
4820 if (SL->getElementOffset(EndIndex) != EndOffset)
4821 return nullptr;
4822
4823 assert(Index < EndIndex);
4824 EE = STy->element_begin() + EndIndex;
4825 }
4826
4827 // Try to build up a sub-structure.
4828 StructType *SubTy =
4829 StructType::get(STy->getContext(), ArrayRef(EI, EE), STy->isPacked());
4830 const StructLayout *SubSL = DL.getStructLayout(SubTy);
4831 if (Size != SubSL->getSizeInBytes())
4832 return nullptr; // The sub-struct doesn't have quite the size needed.
4833
4834 return SubTy;
4835}
4836
4837/// Pre-split loads and stores to simplify rewriting.
4838///
4839/// We want to break up the splittable load+store pairs as much as
4840/// possible. This is important to do as a preprocessing step, as once we
4841/// start rewriting the accesses to partitions of the alloca we lose the
4842/// necessary information to correctly split apart paired loads and stores
4843/// which both point into this alloca. The case to consider is something like
4844/// the following:
4845///
4846/// %a = alloca [12 x i8]
4847/// %gep1 = getelementptr i8, ptr %a, i32 0
4848/// %gep2 = getelementptr i8, ptr %a, i32 4
4849/// %gep3 = getelementptr i8, ptr %a, i32 8
4850/// store float 0.0, ptr %gep1
4851/// store float 1.0, ptr %gep2
4852/// %v = load i64, ptr %gep1
4853/// store i64 %v, ptr %gep2
4854/// %f1 = load float, ptr %gep2
4855/// %f2 = load float, ptr %gep3
4856///
4857/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
4858/// promote everything so we recover the 2 SSA values that should have been
4859/// there all along.
4860///
4861/// \returns true if any changes are made.
4862bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
4863 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
4864
4865 // Track the loads and stores which are candidates for pre-splitting here, in
4866 // the order they first appear during the partition scan. These give stable
4867 // iteration order and a basis for tracking which loads and stores we
4868 // actually split.
4871
4872 // We need to accumulate the splits required of each load or store where we
4873 // can find them via a direct lookup. This is important to cross-check loads
4874 // and stores against each other. We also track the slice so that we can kill
4875 // all the slices that end up split.
4876 struct SplitOffsets {
4877 Slice *S;
4878 std::vector<uint64_t> Splits;
4879 };
4880 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
4881
4882 // Track loads out of this alloca which cannot, for any reason, be pre-split.
4883 // This is important as we also cannot pre-split stores of those loads!
4884 // FIXME: This is all pretty gross. It means that we can be more aggressive
4885 // in pre-splitting when the load feeding the store happens to come from
4886 // a separate alloca. Put another way, the effectiveness of SROA would be
4887 // decreased by a frontend which just concatenated all of its local allocas
4888 // into one big flat alloca. But defeating such patterns is exactly the job
4889 // SROA is tasked with! Sadly, to not have this discrepancy we would have
4890 // change store pre-splitting to actually force pre-splitting of the load
4891 // that feeds it *and all stores*. That makes pre-splitting much harder, but
4892 // maybe it would make it more principled?
4893 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
4894
4895 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
4896 for (auto &P : AS.partitions()) {
4897 for (Slice &S : P) {
4898 Instruction *I = cast<Instruction>(S.getUse()->getUser());
4899 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
4900 // If this is a load we have to track that it can't participate in any
4901 // pre-splitting. If this is a store of a load we have to track that
4902 // that load also can't participate in any pre-splitting.
4903 if (auto *LI = dyn_cast<LoadInst>(I))
4904 UnsplittableLoads.insert(LI);
4905 else if (auto *SI = dyn_cast<StoreInst>(I))
4906 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
4907 UnsplittableLoads.insert(LI);
4908 continue;
4909 }
4910 assert(P.endOffset() > S.beginOffset() &&
4911 "Empty or backwards partition!");
4912
4913 // Determine if this is a pre-splittable slice.
4914 if (auto *LI = dyn_cast<LoadInst>(I)) {
4915 assert(!LI->isVolatile() && "Cannot split volatile loads!");
4916
4917 // The load must be used exclusively to store into other pointers for
4918 // us to be able to arbitrarily pre-split it. The stores must also be
4919 // simple to avoid changing semantics.
4920 auto IsLoadSimplyStored = [](LoadInst *LI) {
4921 for (User *LU : LI->users()) {
4922 auto *SI = dyn_cast<StoreInst>(LU);
4923 if (!SI || !SI->isSimple())
4924 return false;
4925 }
4926 return true;
4927 };
4928 if (!IsLoadSimplyStored(LI)) {
4929 UnsplittableLoads.insert(LI);
4930 continue;
4931 }
4932
4933 Loads.push_back(LI);
4934 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
4935 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
4936 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
4937 continue;
4938 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
4939 if (!StoredLoad || !StoredLoad->isSimple())
4940 continue;
4941 assert(!SI->isVolatile() && "Cannot split volatile stores!");
4942
4943 Stores.push_back(SI);
4944 } else {
4945 // Other uses cannot be pre-split.
4946 continue;
4947 }
4948
4949 // Record the initial split.
4950 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
4951 auto &Offsets = SplitOffsetsMap[I];
4952 assert(Offsets.Splits.empty() &&
4953 "Should not have splits the first time we see an instruction!");
4954 Offsets.S = &S;
4955 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
4956 }
4957
4958 // Now scan the already split slices, and add a split for any of them which
4959 // we're going to pre-split.
4960 for (Slice *S : P.splitSliceTails()) {
4961 auto SplitOffsetsMapI =
4962 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
4963 if (SplitOffsetsMapI == SplitOffsetsMap.end())
4964 continue;
4965 auto &Offsets = SplitOffsetsMapI->second;
4966
4967 assert(Offsets.S == S && "Found a mismatched slice!");
4968 assert(!Offsets.Splits.empty() &&
4969 "Cannot have an empty set of splits on the second partition!");
4970 assert(Offsets.Splits.back() ==
4971 P.beginOffset() - Offsets.S->beginOffset() &&
4972 "Previous split does not end where this one begins!");
4973
4974 // Record each split. The last partition's end isn't needed as the size
4975 // of the slice dictates that.
4976 if (S->endOffset() > P.endOffset())
4977 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
4978 }
4979 }
4980
4981 // We may have split loads where some of their stores are split stores. For
4982 // such loads and stores, we can only pre-split them if their splits exactly
4983 // match relative to their starting offset. We have to verify this prior to
4984 // any rewriting.
4985 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
4986 // Lookup the load we are storing in our map of split
4987 // offsets.
4988 auto *LI = cast<LoadInst>(SI->getValueOperand());
4989 // If it was completely unsplittable, then we're done,
4990 // and this store can't be pre-split.
4991 if (UnsplittableLoads.count(LI))
4992 return true;
4993
4994 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
4995 if (LoadOffsetsI == SplitOffsetsMap.end())
4996 return false; // Unrelated loads are definitely safe.
4997 auto &LoadOffsets = LoadOffsetsI->second;
4998
4999 // Now lookup the store's offsets.
5000 auto &StoreOffsets = SplitOffsetsMap[SI];
5001
5002 // If the relative offsets of each split in the load and
5003 // store match exactly, then we can split them and we
5004 // don't need to remove them here.
5005 if (LoadOffsets.Splits == StoreOffsets.Splits)
5006 return false;
5007
5008 LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"
5009 << " " << *LI << "\n"
5010 << " " << *SI << "\n");
5011
5012 // We've found a store and load that we need to split
5013 // with mismatched relative splits. Just give up on them
5014 // and remove both instructions from our list of
5015 // candidates.
5016 UnsplittableLoads.insert(LI);
5017 return true;
5018 });
5019 // Now we have to go *back* through all the stores, because a later store may
5020 // have caused an earlier store's load to become unsplittable and if it is
5021 // unsplittable for the later store, then we can't rely on it being split in
5022 // the earlier store either.
5023 llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
5024 auto *LI = cast<LoadInst>(SI->getValueOperand());
5025 return UnsplittableLoads.count(LI);
5026 });
5027 // Once we've established all the loads that can't be split for some reason,
5028 // filter any that made it into our list out.
5029 llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
5030 return UnsplittableLoads.count(LI);
5031 });
5032
5033 // If no loads or stores are left, there is no pre-splitting to be done for
5034 // this alloca.
5035 if (Loads.empty() && Stores.empty())
5036 return false;
5037
5038 // From here on, we can't fail and will be building new accesses, so rig up
5039 // an IR builder.
5040 IRBuilderTy IRB(&AI);
5041
5042 // Collect the new slices which we will merge into the alloca slices.
5043 SmallVector<Slice, 4> NewSlices;
5044
5045 // Track any allocas we end up splitting loads and stores for so we iterate
5046 // on them.
5047 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
5048
5049 // At this point, we have collected all of the loads and stores we can
5050 // pre-split, and the specific splits needed for them. We actually do the
5051 // splitting in a specific order in order to handle when one of the loads in
5052 // the value operand to one of the stores.
5053 //
5054 // First, we rewrite all of the split loads, and just accumulate each split
5055 // load in a parallel structure. We also build the slices for them and append
5056 // them to the alloca slices.
5057 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
5058 std::vector<LoadInst *> SplitLoads;
5059 const DataLayout &DL = AI.getDataLayout();
5060 for (LoadInst *LI : Loads) {
5061 SplitLoads.clear();
5062
5063 auto &Offsets = SplitOffsetsMap[LI];
5064 unsigned SliceSize = Offsets.S->endOffset() - Offsets.S->beginOffset();
5065 assert(LI->getType()->getIntegerBitWidth() % 8 == 0 &&
5066 "Load must have type size equal to store size");
5067 assert(LI->getType()->getIntegerBitWidth() / 8 >= SliceSize &&
5068 "Load must be >= slice size");
5069
5070 uint64_t BaseOffset = Offsets.S->beginOffset();
5071 assert(BaseOffset + SliceSize > BaseOffset &&
5072 "Cannot represent alloca access size using 64-bit integers!");
5073
5075 IRB.SetInsertPoint(LI);
5076
5077 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
5078
5079 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
5080 int Idx = 0, Size = Offsets.Splits.size();
5081 for (;;) {
5082 auto *PartTy = Type::getIntNTy(LI->getContext(), PartSize * 8);
5083 auto AS = LI->getPointerAddressSpace();
5084 auto *PartPtrTy = LI->getPointerOperandType();
5085 LoadInst *PLoad = IRB.CreateAlignedLoad(
5086 PartTy,
5087 getAdjustedPtr(IRB, DL, BasePtr,
5088 APInt(DL.getIndexSizeInBits(AS), PartOffset),
5089 PartPtrTy, BasePtr->getName() + "."),
5090 getAdjustedAlignment(LI, PartOffset),
5091 /*IsVolatile*/ false, LI->getName());
5092 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
5093 LLVMContext::MD_access_group});
5094
5095 // Append this load onto the list of split loads so we can find it later
5096 // to rewrite the stores.
5097 SplitLoads.push_back(PLoad);
5098
5099 // Now build a new slice for the alloca.
5100 NewSlices.push_back(
5101 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
5102 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
5103 /*IsSplittable*/ false));
5104 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
5105 << ", " << NewSlices.back().endOffset()
5106 << "): " << *PLoad << "\n");
5107
5108 // See if we've handled all the splits.
5109 if (Idx >= Size)
5110 break;
5111
5112 // Setup the next partition.
5113 PartOffset = Offsets.Splits[Idx];
5114 ++Idx;
5115 PartSize = (Idx < Size ? Offsets.Splits[Idx] : SliceSize) - PartOffset;
5116 }
5117
5118 // Now that we have the split loads, do the slow walk over all uses of the
5119 // load and rewrite them as split stores, or save the split loads to use
5120 // below if the store is going to be split there anyways.
5121 bool DeferredStores = false;
5122 for (User *LU : LI->users()) {
5123 StoreInst *SI = cast<StoreInst>(LU);
5124 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
5125 DeferredStores = true;
5126 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
5127 << "\n");
5128 continue;
5129 }
5130
5131 Value *StoreBasePtr = SI->getPointerOperand();
5132 IRB.SetInsertPoint(SI);
5133 AAMDNodes AATags = SI->getAAMetadata();
5134
5135 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
5136
5137 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
5138 LoadInst *PLoad = SplitLoads[Idx];
5139 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
5140 auto *PartPtrTy = SI->getPointerOperandType();
5141
5142 auto AS = SI->getPointerAddressSpace();
5143 StoreInst *PStore = IRB.CreateAlignedStore(
5144 PLoad,
5145 getAdjustedPtr(IRB, DL, StoreBasePtr,
5146 APInt(DL.getIndexSizeInBits(AS), PartOffset),
5147 PartPtrTy, StoreBasePtr->getName() + "."),
5148 getAdjustedAlignment(SI, PartOffset),
5149 /*IsVolatile*/ false);
5150 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
5151 LLVMContext::MD_access_group,
5152 LLVMContext::MD_DIAssignID});
5153
5154 if (AATags)
5155 PStore->setAAMetadata(
5156 AATags.adjustForAccess(PartOffset, PLoad->getType(), DL));
5157 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
5158 }
5159
5160 // We want to immediately iterate on any allocas impacted by splitting
5161 // this store, and we have to track any promotable alloca (indicated by
5162 // a direct store) as needing to be resplit because it is no longer
5163 // promotable.
5164 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
5165 ResplitPromotableAllocas.insert(OtherAI);
5166 Worklist.insert(OtherAI);
5167 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
5168 StoreBasePtr->stripInBoundsOffsets())) {
5169 Worklist.insert(OtherAI);
5170 }
5171
5172 // Mark the original store as dead.
5173 DeadInsts.push_back(SI);
5174 }
5175
5176 // Save the split loads if there are deferred stores among the users.
5177 if (DeferredStores)
5178 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
5179
5180 // Mark the original load as dead and kill the original slice.
5181 DeadInsts.push_back(LI);
5182 Offsets.S->kill();
5183 }
5184
5185 // Second, we rewrite all of the split stores. At this point, we know that
5186 // all loads from this alloca have been split already. For stores of such
5187 // loads, we can simply look up the pre-existing split loads. For stores of
5188 // other loads, we split those loads first and then write split stores of
5189 // them.
5190 for (StoreInst *SI : Stores) {
5191 auto *LI = cast<LoadInst>(SI->getValueOperand());
5192 IntegerType *Ty = cast<IntegerType>(LI->getType());
5193 assert(Ty->getBitWidth() % 8 == 0);
5194 uint64_t StoreSize = Ty->getBitWidth() / 8;
5195 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
5196
5197 auto &Offsets = SplitOffsetsMap[SI];
5198 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
5199 "Slice size should always match load size exactly!");
5200 uint64_t BaseOffset = Offsets.S->beginOffset();
5201 assert(BaseOffset + StoreSize > BaseOffset &&
5202 "Cannot represent alloca access size using 64-bit integers!");
5203
5204 Value *LoadBasePtr = LI->getPointerOperand();
5205 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
5206
5207 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
5208
5209 // Check whether we have an already split load.
5210 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
5211 std::vector<LoadInst *> *SplitLoads = nullptr;
5212 if (SplitLoadsMapI != SplitLoadsMap.end()) {
5213 SplitLoads = &SplitLoadsMapI->second;
5214 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
5215 "Too few split loads for the number of splits in the store!");
5216 } else {
5217 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
5218 }
5219
5220 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
5221 int Idx = 0, Size = Offsets.Splits.size();
5222 for (;;) {
5223 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
5224 auto *LoadPartPtrTy = LI->getPointerOperandType();
5225 auto *StorePartPtrTy = SI->getPointerOperandType();
5226
5227 // Either lookup a split load or create one.
5228 LoadInst *PLoad;
5229 if (SplitLoads) {
5230 PLoad = (*SplitLoads)[Idx];
5231 } else {
5232 IRB.SetInsertPoint(LI);
5233 auto AS = LI->getPointerAddressSpace();
5234 PLoad = IRB.CreateAlignedLoad(
5235 PartTy,
5236 getAdjustedPtr(IRB, DL, LoadBasePtr,
5237 APInt(DL.getIndexSizeInBits(AS), PartOffset),
5238 LoadPartPtrTy, LoadBasePtr->getName() + "."),
5239 getAdjustedAlignment(LI, PartOffset),
5240 /*IsVolatile*/ false, LI->getName());
5241 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
5242 LLVMContext::MD_access_group});
5243 }
5244
5245 // And store this partition.
5246 IRB.SetInsertPoint(SI);
5247 auto AS = SI->getPointerAddressSpace();
5248 StoreInst *PStore = IRB.CreateAlignedStore(
5249 PLoad,
5250 getAdjustedPtr(IRB, DL, StoreBasePtr,
5251 APInt(DL.getIndexSizeInBits(AS), PartOffset),
5252 StorePartPtrTy, StoreBasePtr->getName() + "."),
5253 getAdjustedAlignment(SI, PartOffset),
5254 /*IsVolatile*/ false);
5255 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
5256 LLVMContext::MD_access_group});
5257
5258 // Now build a new slice for the alloca.
5259 NewSlices.push_back(
5260 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
5261 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
5262 /*IsSplittable*/ false));
5263 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
5264 << ", " << NewSlices.back().endOffset()
5265 << "): " << *PStore << "\n");
5266 if (!SplitLoads) {
5267 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
5268 }
5269
5270 // See if we've finished all the splits.
5271 if (Idx >= Size)
5272 break;
5273
5274 // Setup the next partition.
5275 PartOffset = Offsets.Splits[Idx];
5276 ++Idx;
5277 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
5278 }
5279
5280 // We want to immediately iterate on any allocas impacted by splitting
5281 // this load, which is only relevant if it isn't a load of this alloca and
5282 // thus we didn't already split the loads above. We also have to keep track
5283 // of any promotable allocas we split loads on as they can no longer be
5284 // promoted.
5285 if (!SplitLoads) {
5286 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
5287 assert(OtherAI != &AI && "We can't re-split our own alloca!");
5288 ResplitPromotableAllocas.insert(OtherAI);
5289 Worklist.insert(OtherAI);
5290 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
5291 LoadBasePtr->stripInBoundsOffsets())) {
5292 assert(OtherAI != &AI && "We can't re-split our own alloca!");
5293 Worklist.insert(OtherAI);
5294 }
5295 }
5296
5297 // Mark the original store as dead now that we've split it up and kill its
5298 // slice. Note that we leave the original load in place unless this store
5299 // was its only use. It may in turn be split up if it is an alloca load
5300 // for some other alloca, but it may be a normal load. This may introduce
5301 // redundant loads, but where those can be merged the rest of the optimizer
5302 // should handle the merging, and this uncovers SSA splits which is more
5303 // important. In practice, the original loads will almost always be fully
5304 // split and removed eventually, and the splits will be merged by any
5305 // trivial CSE, including instcombine.
5306 if (LI->hasOneUse()) {
5307 assert(*LI->user_begin() == SI && "Single use isn't this store!");
5308 DeadInsts.push_back(LI);
5309 }
5310 DeadInsts.push_back(SI);
5311 Offsets.S->kill();
5312 }
5313
5314 // Remove the killed slices that have ben pre-split.
5315 llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
5316
5317 // Insert our new slices. This will sort and merge them into the sorted
5318 // sequence.
5319 AS.insert(NewSlices);
5320
5321 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
5322#ifndef NDEBUG
5323 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
5324 LLVM_DEBUG(AS.print(dbgs(), I, " "));
5325#endif
5326
5327 // Finally, don't try to promote any allocas that new require re-splitting.
5328 // They have already been added to the worklist above.
5329 PromotableAllocas.set_subtract(ResplitPromotableAllocas);
5330
5331 return true;
5332}
5333
5334/// Try to canonicalize a homogeneous struct partition to a vector type.
5335///
5336/// We can do this if all the elements of the struct are the same and the
5337/// corresponding vector has the same byte-level layout. This can sometimes
5338/// eliminate allocas because structs cannot get promoted to LLVM values, but
5339/// vectors can.
5340///
5341/// We only apply this transformation when all users of the partition are memory
5342/// intrinsics. Otherwise, if there is a load or store of some other type to the
5343/// partition, SROA would select that type.
5344///
5345/// Applying this transformation too early may hinder memcpyopt, which may
5346/// generate better code when eliminating allocas. For example, see
5347/// `struct-to-vector-fp-store-only-tail.ll`, which demonstrates that applying
5348/// this before memcpyopt can initialize previously uninitialized memory when
5349/// the alloca gets promoted to an SSA value. For another example, see
5350/// `struct-to-vector-before-memcpyopt.ll`, which demonstrates that applying
5351/// this before memcpyopt can result in promoting an alloca so that we load a
5352/// temporary value instead of copying the temporary value into memory, whereas
5353/// memcpyopt eliminates the temporary altogether.
5354///
5355/// As such, we only apply this transformation after memcpyopt has run. We gate
5356/// this transformation by the "AggregateToVector" pass option.
5358 Partition &P,
5359 const DataLayout &DL) {
5360 unsigned NumElts = STy->getNumElements();
5361
5362 Type *EltTy = STy->getElementType(0);
5363 if (!llvm::all_equal(STy->elements()))
5364 return nullptr;
5365
5366 bool IsIntegralPointerTy =
5367 EltTy->isPointerTy() && !DL.isNonIntegralPointerType(EltTy);
5368 if (!EltTy->isIntegerTy() && !EltTy->isFloatingPointTy() &&
5369 !IsIntegralPointerTy)
5370 return nullptr;
5371
5372 // Ensure the struct is tightly packed so that the bit-layout is the same as
5373 // the corresponding vector. For example, this prevents a miscompile for
5374 // { i5, i5 }, which has padding after each i5 field, whereas <i5, i5> has
5375 // tightly packed elements and trailing padding.
5376 if (DL.getTypeSizeInBits(EltTy) != DL.getTypeAllocSizeInBits(EltTy))
5377 return nullptr;
5378
5379 auto *VTy = FixedVectorType::get(EltTy, NumElts);
5380 TypeSize StructSize = DL.getStructLayout(STy)->getSizeInBytes();
5381 TypeSize VectorSize = DL.getTypeStoreSize(VTy);
5382 // After ruling out per-element padding, make sure a vector load/store
5383 // covers the same number of bytes as the struct layout.
5384 if (StructSize != VectorSize)
5385 return nullptr;
5386
5387 auto IsIgnorableOrMemIntrinsicSlice = [](const Slice &S) {
5388 if (S.isDead())
5389 return true;
5390 auto *U = S.getUse();
5391 if (!U)
5392 return true;
5393
5394 User *Usr = U->getUser();
5396 return true;
5397
5398 return isa<MemIntrinsic>(Usr);
5399 };
5400
5401 for (const Slice &S : P)
5402 if (!IsIgnorableOrMemIntrinsicSlice(S))
5403 return nullptr;
5404
5405 for (const Slice *S : P.splitSliceTails())
5406 if (!IsIgnorableOrMemIntrinsicSlice(*S))
5407 return nullptr;
5408
5409 return VTy;
5410}
5411
5412/// Select a partition type for an alloca partition.
5413///
5414/// Try to compute a friendly type for this partition of the alloca. This
5415/// won't always succeed, in which case we fall back to a legal integer type
5416/// or an i8 array of an appropriate size.
5417///
5418/// \returns A tuple with the following elements:
5419/// - PartitionType: The computed type for this partition.
5420/// - IsIntegerWideningViable: True if integer widening promotion is used.
5421/// - VectorType: The vector type if vector promotion is used, otherwise
5422/// nullptr.
5423static std::tuple<Type *, bool, VectorType *>
5425 LLVMContext &C, bool AggregateToVector) {
5426 auto LogSelection = [&](StringRef Path, Type *SelectedTy,
5427 VectorType *SelectedVecTy, bool SelectedIntWidening) {
5428 LLVM_DEBUG({
5429 dbgs() << "selectPartitionType path=" << Path
5430 << " func=" << AI.getFunction()->getName() << " alloca=";
5431 if (AI.hasName())
5432 dbgs() << AI.getName();
5433 else
5434 dbgs() << "<unnamed>";
5435 dbgs() << " partition=[" << P.beginOffset() << "," << P.endOffset()
5436 << ") size=" << P.size();
5437 if (std::optional<TypeSize> AllocSize = AI.getAllocationSize(DL))
5438 dbgs() << " alloc-size=" << AllocSize->getKnownMinValue();
5439 if (SelectedTy)
5440 dbgs() << " chosen=" << *SelectedTy;
5441 if (SelectedVecTy)
5442 dbgs() << " vec=" << *SelectedVecTy;
5443 dbgs() << " intwiden=" << SelectedIntWidening << "\n";
5444 });
5445 };
5446 // First check if the partition is viable for vector promotion.
5447 //
5448 // We prefer vector promotion over integer widening promotion when:
5449 // - The vector element type is a floating-point type.
5450 // - All the loads/stores to the alloca are vector loads/stores to the
5451 // entire alloca or load/store a single element of the vector.
5452 //
5453 // Otherwise when there is an integer vector with mixed type loads/stores we
5454 // prefer integer widening promotion because it's more likely the user is
5455 // doing bitwise arithmetic and we generate better code.
5456 VectorType *VecTy =
5458 // If the vector element type is a floating-point type, we prefer vector
5459 // promotion. If the vector has one element, let the below code select
5460 // whether we promote with the vector or scalar.
5461 if (VecTy && VecTy->getElementType()->isFloatingPointTy() &&
5462 VecTy->getElementCount().getFixedValue() > 1) {
5463 LogSelection("direct-fp-vecty", VecTy, VecTy, false);
5464 return {VecTy, false, VecTy};
5465 }
5466
5467 // Check if there is a common type that all slices of the partition use that
5468 // spans the partition.
5469 auto [CommonUseTy, LargestIntTy] =
5470 findCommonType(P.begin(), P.end(), P.endOffset());
5471 if (CommonUseTy) {
5472 TypeSize CommonUseSize = DL.getTypeAllocSize(CommonUseTy);
5473 if (CommonUseSize.isFixed() && CommonUseSize.getFixedValue() >= P.size()) {
5474 // We prefer vector promotion here because if vector promotion is viable
5475 // and there is a common type used, then it implies the second listed
5476 // condition for preferring vector promotion is true.
5477 if (VecTy) {
5478 LogSelection("common-type-vecty", VecTy, VecTy, false);
5479 return {VecTy, false, VecTy};
5480 }
5481 bool IntWiden = isIntegerWideningViable(P, CommonUseTy, DL);
5482 LogSelection("common-type", CommonUseTy, nullptr, IntWiden);
5483 return {CommonUseTy, IntWiden, nullptr};
5484 }
5485 }
5486
5487 // Can we find an appropriate subtype in the original allocated
5488 // type?
5489 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
5490 P.beginOffset(), P.size())) {
5491 // If the partition is an integer array that can be spanned by a legal
5492 // integer type, prefer to represent it as a legal integer type because
5493 // it's more likely to be promotable.
5494 if (TypePartitionTy->isArrayTy() &&
5495 TypePartitionTy->getArrayElementType()->isIntegerTy() &&
5496 DL.isLegalInteger(P.size() * 8))
5497 TypePartitionTy = Type::getIntNTy(C, P.size() * 8);
5498 // There was no common type used, so we prefer integer widening promotion.
5499 if (isIntegerWideningViable(P, TypePartitionTy, DL)) {
5500 LogSelection("type-partition-int-widen", TypePartitionTy, nullptr, true);
5501 return {TypePartitionTy, true, nullptr};
5502 }
5503 if (VecTy) {
5504 LogSelection("type-partition-vecty", VecTy, VecTy, false);
5505 return {VecTy, false, VecTy};
5506 }
5507 // If we couldn't promote with TypePartitionTy, try with the largest
5508 // integer type used.
5509 if (LargestIntTy &&
5510 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size() &&
5511 isIntegerWideningViable(P, LargestIntTy, DL)) {
5512 LogSelection("largest-int-int-widen", LargestIntTy, nullptr, true);
5513 return {LargestIntTy, true, nullptr};
5514 }
5515
5516 // Try homogeneous struct to vector canonicalization when requested. Running
5517 // this too early can hide memcpy chains from MemCpyOpt.
5518 if (AggregateToVector) {
5519 if (auto *STy = dyn_cast<StructType>(TypePartitionTy)) {
5520 if (auto *VTy = tryCanonicalizeStructToVector(STy, P, DL)) {
5521 LogSelection("struct-fallback-vecty", VTy, nullptr, false);
5522 return {VTy, false, nullptr};
5523 }
5524 }
5525 }
5526
5527 // Fallback to TypePartitionTy and we probably won't promote.
5528 LogSelection("type-partition-fallback", TypePartitionTy, nullptr, false);
5529 return {TypePartitionTy, false, nullptr};
5530 }
5531
5532 // Select the largest integer type used if it spans the partition.
5533 if (LargestIntTy &&
5534 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size()) {
5535 LogSelection("largest-int-fallback", LargestIntTy, nullptr, false);
5536 return {LargestIntTy, false, nullptr};
5537 }
5538
5539 // Select a legal integer type if it spans the partition.
5540 if (DL.isLegalInteger(P.size() * 8)) {
5541 Type *IntTy = Type::getIntNTy(C, P.size() * 8);
5542 LogSelection("legal-int-fallback", IntTy, nullptr, false);
5543 return {IntTy, false, nullptr};
5544 }
5545
5546 // Fallback to an i8 array.
5547 Type *ArrayTy = ArrayType::get(Type::getInt8Ty(C), P.size());
5548 LogSelection("byte-array-fallback", ArrayTy, nullptr, false);
5549 return {ArrayTy, false, nullptr};
5550}
5551
5552/// Rewrite an alloca partition's users.
5553///
5554/// This routine drives both of the rewriting goals of the SROA pass. It tries
5555/// to rewrite uses of an alloca partition to be conducive for SSA value
5556/// promotion. If the partition needs a new, more refined alloca, this will
5557/// build that new alloca, preserving as much type information as possible, and
5558/// rewrite the uses of the old alloca to point at the new one and have the
5559/// appropriate new offsets. It also evaluates how successful the rewrite was
5560/// at enabling promotion and if it was successful queues the alloca to be
5561/// promoted.
5562std::pair<AllocaInst *, uint64_t>
5563SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &P) {
5564 const DataLayout &DL = AI.getDataLayout();
5565 // Select the type for the new alloca that spans the partition.
5566 auto [PartitionTy, IsIntegerWideningViable, VecTy] =
5567 selectPartitionType(P, DL, AI, *C, AggregateToVector);
5568
5569 // Check for the case where we're going to rewrite to a new alloca of the
5570 // exact same type as the original, and with the same access offsets. In that
5571 // case, re-use the existing alloca, but still run through the rewriter to
5572 // perform phi and select speculation.
5573 // P.beginOffset() can be non-zero even with the same type in a case with
5574 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
5575 AllocaInst *NewAI;
5576 if (PartitionTy == AI.getAllocatedType() && P.beginOffset() == 0) {
5577 NewAI = &AI;
5578 // FIXME: We should be able to bail at this point with "nothing changed".
5579 // FIXME: We might want to defer PHI speculation until after here.
5580 // FIXME: return nullptr;
5581 } else {
5582 // Make sure the alignment is compatible with P.beginOffset().
5583 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
5584 // If we will get at least this much alignment from the type alone, leave
5585 // the alloca's alignment unconstrained.
5586 const bool IsUnconstrained = Alignment <= DL.getABITypeAlign(PartitionTy);
5587 NewAI = new AllocaInst(
5588 PartitionTy, AI.getAddressSpace(), nullptr,
5589 IsUnconstrained ? DL.getPrefTypeAlign(PartitionTy) : Alignment,
5590 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()),
5591 AI.getIterator());
5592 // Copy the old AI debug location over to the new one.
5593 NewAI->setDebugLoc(AI.getDebugLoc());
5594 ++NumNewAllocas;
5595 }
5596
5597 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " << "[" << P.beginOffset()
5598 << "," << P.endOffset() << ") to: " << *NewAI << "\n");
5599
5600 // Track the high watermark on the worklist as it is only relevant for
5601 // promoted allocas. We will reset it to this point if the alloca is not in
5602 // fact scheduled for promotion.
5603 unsigned PPWOldSize = PostPromotionWorklist.size();
5604 unsigned NumUses = 0;
5605 SmallSetVector<PHINode *, 8> PHIUsers;
5606 SmallSetVector<SelectInst *, 8> SelectUsers;
5607
5608 AllocaSliceRewriter Rewriter(
5609 DL, AS, *this, AI, *NewAI, PartitionTy, P.beginOffset(), P.endOffset(),
5610 IsIntegerWideningViable, VecTy, PHIUsers, SelectUsers);
5611 bool Promotable = true;
5612 // Check whether we can have tree-structured merge.
5613 if (auto DeletedValues = Rewriter.rewriteTreeStructuredMerge(P)) {
5614 NumUses += DeletedValues->size() + 1;
5615 for (Value *V : *DeletedValues)
5616 DeadInsts.push_back(V);
5617 } else {
5618 for (Slice *S : P.splitSliceTails()) {
5619 Promotable &= Rewriter.visit(S);
5620 ++NumUses;
5621 }
5622 for (Slice &S : P) {
5623 Promotable &= Rewriter.visit(&S);
5624 ++NumUses;
5625 }
5626 }
5627
5628 NumAllocaPartitionUses += NumUses;
5629 MaxUsesPerAllocaPartition.updateMax(NumUses);
5630
5631 // Now that we've processed all the slices in the new partition, check if any
5632 // PHIs or Selects would block promotion.
5633 for (PHINode *PHI : PHIUsers)
5634 if (!isSafePHIToSpeculate(*PHI)) {
5635 Promotable = false;
5636 PHIUsers.clear();
5637 SelectUsers.clear();
5638 break;
5639 }
5640
5642 NewSelectsToRewrite;
5643 NewSelectsToRewrite.reserve(SelectUsers.size());
5644 for (SelectInst *Sel : SelectUsers) {
5645 std::optional<RewriteableMemOps> Ops =
5646 isSafeSelectToSpeculate(*Sel, PreserveCFG);
5647 if (!Ops) {
5648 Promotable = false;
5649 PHIUsers.clear();
5650 SelectUsers.clear();
5651 NewSelectsToRewrite.clear();
5652 break;
5653 }
5654 NewSelectsToRewrite.emplace_back(std::make_pair(Sel, *Ops));
5655 }
5656
5657 if (Promotable) {
5658 for (Use *U : AS.getDeadUsesIfPromotable()) {
5659 auto *OldInst = dyn_cast<Instruction>(U->get());
5660 Value::dropDroppableUse(*U);
5661 if (OldInst)
5662 if (isInstructionTriviallyDead(OldInst))
5663 DeadInsts.push_back(OldInst);
5664 }
5665 if (PHIUsers.empty() && SelectUsers.empty()) {
5666 // Promote the alloca.
5667 PromotableAllocas.insert(NewAI);
5668 } else {
5669 // If we have either PHIs or Selects to speculate, add them to those
5670 // worklists and re-queue the new alloca so that we promote in on the
5671 // next iteration.
5672 SpeculatablePHIs.insert_range(PHIUsers);
5673 SelectsToRewrite.reserve(SelectsToRewrite.size() +
5674 NewSelectsToRewrite.size());
5675 for (auto &&KV : llvm::make_range(
5676 std::make_move_iterator(NewSelectsToRewrite.begin()),
5677 std::make_move_iterator(NewSelectsToRewrite.end())))
5678 SelectsToRewrite.insert(std::move(KV));
5679 Worklist.insert(NewAI);
5680 }
5681 } else {
5682 // Drop any post-promotion work items if promotion didn't happen.
5683 while (PostPromotionWorklist.size() > PPWOldSize)
5684 PostPromotionWorklist.pop_back();
5685
5686 // We couldn't promote and we didn't create a new partition, nothing
5687 // happened.
5688 if (NewAI == &AI)
5689 return {nullptr, 0};
5690
5691 // If we can't promote the alloca, iterate on it to check for new
5692 // refinements exposed by splitting the current alloca. Don't iterate on an
5693 // alloca which didn't actually change and didn't get promoted.
5694 Worklist.insert(NewAI);
5695 }
5696
5697 return {NewAI, DL.getTypeSizeInBits(PartitionTy).getFixedValue()};
5698}
5699
5700// There isn't a shared interface to get the "address" parts out of a
5701// dbg.declare and dbg.assign, so provide some wrappers.
5704 return DVR->isKillAddress();
5705 return DVR->isKillLocation();
5706}
5707
5710 return DVR->getAddressExpression();
5711 return DVR->getExpression();
5712}
5713
5714/// Create or replace an existing fragment in a DIExpression with \p Frag.
5715/// If the expression already contains a DW_OP_LLVM_extract_bits_[sz]ext
5716/// operation, add \p BitExtractOffset to the offset part.
5717///
5718/// Returns the new expression, or nullptr if this fails (see details below).
5719///
5720/// This function is similar to DIExpression::createFragmentExpression except
5721/// for 3 important distinctions:
5722/// 1. The new fragment isn't relative to an existing fragment.
5723/// 2. It assumes the computed location is a memory location. This means we
5724/// don't need to perform checks that creating the fragment preserves the
5725/// expression semantics.
5726/// 3. Existing extract_bits are modified independently of fragment changes
5727/// using \p BitExtractOffset. A change to the fragment offset or size
5728/// may affect a bit extract. But a bit extract offset can change
5729/// independently of the fragment dimensions.
5730///
5731/// Returns the new expression, or nullptr if one couldn't be created.
5732/// Ideally this is only used to signal that a bit-extract has become
5733/// zero-sized (and thus the new debug record has no size and can be
5734/// dropped), however, it fails for other reasons too - see the FIXME below.
5735///
5736/// FIXME: To keep the change that introduces this function NFC it bails
5737/// in some situations unecessarily, e.g. when fragment and bit extract
5738/// sizes differ.
5741 int64_t BitExtractOffset) {
5743 bool HasFragment = false;
5744 bool HasBitExtract = false;
5745
5746 for (auto &Op : Expr->expr_ops()) {
5747 if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
5748 HasFragment = true;
5749 continue;
5750 }
5751 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
5752 HasBitExtract = true;
5753 int64_t ExtractOffsetInBits = Extract.getOffsetInBits();
5754 int64_t ExtractSizeInBits = Extract.getSizeInBits();
5755
5756 // DIExpression::createFragmentExpression doesn't know how to handle
5757 // a fragment that is smaller than the extract. Copy the behaviour
5758 // (bail) to avoid non-NFC changes.
5759 // FIXME: Don't do this.
5760 if (Frag.SizeInBits < uint64_t(ExtractSizeInBits))
5761 return nullptr;
5762
5763 assert(BitExtractOffset <= 0);
5764 int64_t AdjustedOffset = ExtractOffsetInBits + BitExtractOffset;
5765
5766 // DIExpression::createFragmentExpression doesn't know what to do
5767 // if the new extract starts "outside" the existing one. Copy the
5768 // behaviour (bail) to avoid non-NFC changes.
5769 // FIXME: Don't do this.
5770 if (AdjustedOffset < 0)
5771 return nullptr;
5772
5773 Ops.push_back(Op.getOp());
5774 Ops.push_back(std::max<int64_t>(0, AdjustedOffset));
5775 Ops.push_back(ExtractSizeInBits);
5776 continue;
5777 }
5778 Op.appendToVector(Ops);
5779 }
5780
5781 // Unsupported by createFragmentExpression, so don't support it here yet to
5782 // preserve NFC-ness.
5783 if (HasFragment && HasBitExtract)
5784 return nullptr;
5785
5786 if (!HasBitExtract) {
5788 Ops.push_back(Frag.OffsetInBits);
5789 Ops.push_back(Frag.SizeInBits);
5790 }
5791 return DIExpression::get(Expr->getContext(), Ops);
5792}
5793
5794/// Insert a new DbgRecord.
5795/// \p Orig Original to copy record type, debug loc and variable from, and
5796/// additionally value and value expression for dbg_assign records.
5797/// \p NewAddr Location's new base address.
5798/// \p NewAddrExpr New expression to apply to address.
5799/// \p BeforeInst Insert position.
5800/// \p NewFragment New fragment (absolute, non-relative).
5801/// \p BitExtractAdjustment Offset to apply to any extract_bits op.
5802static void
5804 DIExpression *NewAddrExpr, Instruction *BeforeInst,
5805 std::optional<DIExpression::FragmentInfo> NewFragment,
5806 int64_t BitExtractAdjustment) {
5807 (void)DIB;
5808
5809 // A dbg_assign puts fragment info in the value expression only. The address
5810 // expression has already been built: NewAddrExpr. A dbg_declare puts the
5811 // new fragment info into NewAddrExpr (as it only has one expression).
5812 DIExpression *NewFragmentExpr =
5813 Orig->isDbgAssign() ? Orig->getExpression() : NewAddrExpr;
5814 if (NewFragment)
5815 NewFragmentExpr = createOrReplaceFragment(NewFragmentExpr, *NewFragment,
5816 BitExtractAdjustment);
5817 if (!NewFragmentExpr)
5818 return;
5819
5820 if (Orig->isDbgDeclare()) {
5822 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
5823 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
5824 BeforeInst->getIterator());
5825 return;
5826 }
5827
5828 if (Orig->isDbgValue()) {
5830 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
5831 // Drop debug information if the expression doesn't start with a
5832 // DW_OP_deref. This is because without a DW_OP_deref, the #dbg_value
5833 // describes the address of alloca rather than the value inside the alloca.
5834 if (!NewFragmentExpr->startsWithDeref())
5835 DVR->setKillAddress();
5836 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
5837 BeforeInst->getIterator());
5838 return;
5839 }
5840
5841 // Apply a DIAssignID to the store if it doesn't already have it.
5842 if (!NewAddr->hasMetadata(LLVMContext::MD_DIAssignID)) {
5843 NewAddr->setMetadata(LLVMContext::MD_DIAssignID,
5845 }
5846
5848 NewAddr, Orig->getValue(), Orig->getVariable(), NewFragmentExpr, NewAddr,
5849 NewAddrExpr, Orig->getDebugLoc());
5850 LLVM_DEBUG(dbgs() << "Created new DVRAssign: " << *NewAssign << "\n");
5851 (void)NewAssign;
5852}
5853
5854/// Walks the slices of an alloca and form partitions based on them,
5855/// rewriting each of their uses.
5856bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
5857 if (AS.begin() == AS.end())
5858 return false;
5859
5860 unsigned NumPartitions = 0;
5861 bool Changed = false;
5862 const DataLayout &DL = AI.getModule()->getDataLayout();
5863
5864 // First try to pre-split loads and stores.
5865 Changed |= presplitLoadsAndStores(AI, AS);
5866
5867 // Now that we have identified any pre-splitting opportunities,
5868 // mark loads and stores unsplittable except for the following case.
5869 // We leave a slice splittable if all other slices are disjoint or fully
5870 // included in the slice, such as whole-alloca loads and stores.
5871 // If we fail to split these during pre-splitting, we want to force them
5872 // to be rewritten into a partition.
5873 bool IsSorted = true;
5874
5875 uint64_t AllocaSize = AI.getAllocationSize(DL)->getFixedValue();
5876 const uint64_t MaxBitVectorSize = 1024;
5877 if (AllocaSize <= MaxBitVectorSize) {
5878 // If a byte boundary is included in any load or store, a slice starting or
5879 // ending at the boundary is not splittable.
5880 SmallBitVector SplittableOffset(AllocaSize + 1, true);
5881 for (Slice &S : AS)
5882 for (unsigned O = S.beginOffset() + 1;
5883 O < S.endOffset() && O < AllocaSize; O++)
5884 SplittableOffset.reset(O);
5885
5886 for (Slice &S : AS) {
5887 if (!S.isSplittable())
5888 continue;
5889
5890 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
5891 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
5892 continue;
5893
5894 if (isa<LoadInst>(S.getUse()->getUser()) ||
5895 isa<StoreInst>(S.getUse()->getUser())) {
5896 S.makeUnsplittable();
5897 IsSorted = false;
5898 }
5899 }
5900 } else {
5901 // We only allow whole-alloca splittable loads and stores
5902 // for a large alloca to avoid creating too large BitVector.
5903 for (Slice &S : AS) {
5904 if (!S.isSplittable())
5905 continue;
5906
5907 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
5908 continue;
5909
5910 if (isa<LoadInst>(S.getUse()->getUser()) ||
5911 isa<StoreInst>(S.getUse()->getUser())) {
5912 S.makeUnsplittable();
5913 IsSorted = false;
5914 }
5915 }
5916 }
5917
5918 if (!IsSorted)
5920
5921 /// Describes the allocas introduced by rewritePartition in order to migrate
5922 /// the debug info.
5923 struct Fragment {
5924 AllocaInst *Alloca;
5926 uint64_t Size;
5927 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
5928 : Alloca(AI), Offset(O), Size(S) {}
5929 };
5930 SmallVector<Fragment, 4> Fragments;
5931
5932 // Rewrite each partition.
5933 for (auto &P : AS.partitions()) {
5934 auto [NewAI, ActiveBits] = rewritePartition(AI, AS, P);
5935 if (NewAI) {
5936 Changed = true;
5937 if (NewAI != &AI) {
5938 uint64_t SizeOfByte = 8;
5939 // Don't include any padding.
5940 uint64_t Size = std::min(ActiveBits, P.size() * SizeOfByte);
5941 Fragments.push_back(
5942 Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
5943 }
5944 }
5945 ++NumPartitions;
5946 }
5947
5948 NumAllocaPartitions += NumPartitions;
5949 MaxPartitionsPerAlloca.updateMax(NumPartitions);
5950
5951 // Migrate debug information from the old alloca to the new alloca(s)
5952 // and the individual partitions.
5953 auto MigrateOne = [&](DbgVariableRecord *DbgVariable) {
5954 // Can't overlap with undef memory.
5955 if (isKillAddress(DbgVariable))
5956 return;
5957
5958 const Value *DbgPtr = DbgVariable->getAddress();
5960 DbgVariable->getFragmentOrEntireVariable();
5961 // Get the address expression constant offset if one exists and the ops
5962 // that come after it.
5963 int64_t CurrentExprOffsetInBytes = 0;
5964 SmallVector<uint64_t> PostOffsetOps;
5965 if (!getAddressExpression(DbgVariable)
5966 ->extractLeadingOffset(CurrentExprOffsetInBytes, PostOffsetOps))
5967 return; // Couldn't interpret this DIExpression - drop the var.
5968
5969 // Offset defined by a DW_OP_LLVM_extract_bits_[sz]ext.
5970 int64_t ExtractOffsetInBits = 0;
5971 for (auto Op : getAddressExpression(DbgVariable)->expr_ops()) {
5972 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
5973 ExtractOffsetInBits = Extract.getOffsetInBits();
5974 break;
5975 }
5976 }
5977
5978 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
5979 for (auto Fragment : Fragments) {
5980 int64_t OffsetFromLocationInBits;
5981 std::optional<DIExpression::FragmentInfo> NewDbgFragment;
5982 // Find the variable fragment that the new alloca slice covers.
5983 // Drop debug info for this variable fragment if we can't compute an
5984 // intersect between it and the alloca slice.
5986 DL, &AI, Fragment.Offset, Fragment.Size, DbgPtr,
5987 CurrentExprOffsetInBytes * 8, ExtractOffsetInBits, VarFrag,
5988 NewDbgFragment, OffsetFromLocationInBits))
5989 continue; // Do not migrate this fragment to this slice.
5990
5991 // Zero sized fragment indicates there's no intersect between the variable
5992 // fragment and the alloca slice. Skip this slice for this variable
5993 // fragment.
5994 if (NewDbgFragment && !NewDbgFragment->SizeInBits)
5995 continue; // Do not migrate this fragment to this slice.
5996
5997 // No fragment indicates DbgVariable's variable or fragment exactly
5998 // overlaps the slice; copy its fragment (or nullopt if there isn't one).
5999 if (!NewDbgFragment)
6000 NewDbgFragment = DbgVariable->getFragment();
6001
6002 // Reduce the new expression offset by the bit-extract offset since
6003 // we'll be keeping that.
6004 int64_t OffestFromNewAllocaInBits =
6005 OffsetFromLocationInBits - ExtractOffsetInBits;
6006 // We need to adjust an existing bit extract if the offset expression
6007 // can't eat the slack (i.e., if the new offset would be negative).
6008 int64_t BitExtractOffset =
6009 std::min<int64_t>(0, OffestFromNewAllocaInBits);
6010 // The magnitude of a negative value indicates the number of bits into
6011 // the existing variable fragment that the memory region begins. The new
6012 // variable fragment already excludes those bits - the new DbgPtr offset
6013 // only needs to be applied if it's positive.
6014 OffestFromNewAllocaInBits =
6015 std::max(int64_t(0), OffestFromNewAllocaInBits);
6016
6017 // Rebuild the expression:
6018 // {Offset(OffestFromNewAllocaInBits), PostOffsetOps, NewDbgFragment}
6019 // Add NewDbgFragment later, because dbg.assigns don't want it in the
6020 // address expression but the value expression instead.
6021 DIExpression *NewExpr = DIExpression::get(AI.getContext(), PostOffsetOps);
6022 if (OffestFromNewAllocaInBits > 0) {
6023 int64_t OffsetInBytes = (OffestFromNewAllocaInBits + 7) / 8;
6024 NewExpr = DIExpression::prepend(NewExpr, /*flags=*/0, OffsetInBytes);
6025 }
6026
6027 // Remove any existing intrinsics on the new alloca describing
6028 // the variable fragment.
6029 auto RemoveOne = [DbgVariable](auto *OldDII) {
6030 auto SameVariableFragment = [](const auto *LHS, const auto *RHS) {
6031 return LHS->getVariable() == RHS->getVariable() &&
6032 LHS->getDebugLoc()->getInlinedAt() ==
6033 RHS->getDebugLoc()->getInlinedAt();
6034 };
6035 if (SameVariableFragment(OldDII, DbgVariable))
6036 OldDII->eraseFromParent();
6037 };
6038 for_each(findDVRDeclares(Fragment.Alloca), RemoveOne);
6039 for_each(findDVRValues(Fragment.Alloca), RemoveOne);
6040 insertNewDbgInst(DIB, DbgVariable, Fragment.Alloca, NewExpr, &AI,
6041 NewDbgFragment, BitExtractOffset);
6042 }
6043 };
6044
6045 // Migrate debug information from the old alloca to the new alloca(s)
6046 // and the individual partitions.
6047 for_each(findDVRDeclares(&AI), MigrateOne);
6048 for_each(findDVRValues(&AI), MigrateOne);
6049 for_each(at::getDVRAssignmentMarkers(&AI), MigrateOne);
6050
6051 return Changed;
6052}
6053
6054/// Clobber a use with poison, deleting the used value if it becomes dead.
6055void SROA::clobberUse(Use &U) {
6056 Value *OldV = U;
6057 // Replace the use with an poison value.
6058 U = PoisonValue::get(OldV->getType());
6059
6060 // Check for this making an instruction dead. We have to garbage collect
6061 // all the dead instructions to ensure the uses of any alloca end up being
6062 // minimal.
6063 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
6064 if (isInstructionTriviallyDead(OldI)) {
6065 DeadInsts.push_back(OldI);
6066 }
6067}
6068
6069/// A basic LoadAndStorePromoter that does not remove store nodes.
6071public:
6073 Type *ZeroType)
6074 : LoadAndStorePromoter(Insts, S), ZeroType(ZeroType) {}
6075 bool shouldDelete(Instruction *I) const override {
6076 return !isa<StoreInst>(I) && !isa<AllocaInst>(I);
6077 }
6078
6080 return UndefValue::get(ZeroType);
6081 }
6082
6083private:
6084 Type *ZeroType;
6085};
6086
6087bool SROA::propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS) {
6088 // Look through each "partition", looking for slices with the same start/end
6089 // that do not overlap with any before them. The slices are sorted by
6090 // increasing beginOffset. We don't use AS.partitions(), as it will use a more
6091 // sophisticated algorithm that takes splittable slices into account.
6092 LLVM_DEBUG(dbgs() << "Attempting to propagate values on " << AI << "\n");
6093 bool AllSameAndValid = true;
6094 Type *PartitionType = nullptr;
6095 SmallVector<Instruction *> Insts;
6096 uint64_t BeginOffset = 0;
6097 uint64_t EndOffset = 0;
6098
6099 auto Flush = [&]() {
6100 if (AllSameAndValid && !Insts.empty()) {
6101 LLVM_DEBUG(dbgs() << "Propagate values on slice [" << BeginOffset << ", "
6102 << EndOffset << ")\n");
6104 SSAUpdater SSA(&NewPHIs);
6105 Insts.push_back(&AI);
6106 BasicLoadAndStorePromoter Promoter(Insts, SSA, PartitionType);
6107 Promoter.run(Insts);
6108 }
6109 AllSameAndValid = true;
6110 PartitionType = nullptr;
6111 Insts.clear();
6112 };
6113
6114 for (Slice &S : AS) {
6115 auto *User = cast<Instruction>(S.getUse()->getUser());
6116 if (isAssumeLikeIntrinsic(User)) {
6117 LLVM_DEBUG({
6118 dbgs() << "Ignoring slice: ";
6119 AS.print(dbgs(), &S);
6120 });
6121 continue;
6122 }
6123 if (S.beginOffset() >= EndOffset) {
6124 Flush();
6125 BeginOffset = S.beginOffset();
6126 EndOffset = S.endOffset();
6127 } else if (S.beginOffset() != BeginOffset || S.endOffset() != EndOffset) {
6128 if (AllSameAndValid) {
6129 LLVM_DEBUG({
6130 dbgs() << "Slice does not match range [" << BeginOffset << ", "
6131 << EndOffset << ")";
6132 AS.print(dbgs(), &S);
6133 });
6134 AllSameAndValid = false;
6135 }
6136 EndOffset = std::max(EndOffset, S.endOffset());
6137 continue;
6138 }
6139
6140 if (auto *LI = dyn_cast<LoadInst>(User)) {
6141 Type *UserTy = LI->getType();
6142 // LoadAndStorePromoter requires all the types to be the same.
6143 if (!LI->isSimple() || (PartitionType && UserTy != PartitionType))
6144 AllSameAndValid = false;
6145 PartitionType = UserTy;
6146 Insts.push_back(User);
6147 } else if (auto *SI = dyn_cast<StoreInst>(User)) {
6148 Type *UserTy = SI->getValueOperand()->getType();
6149 if (!SI->isSimple() || (PartitionType && UserTy != PartitionType))
6150 AllSameAndValid = false;
6151 PartitionType = UserTy;
6152 Insts.push_back(User);
6153 } else {
6154 AllSameAndValid = false;
6155 }
6156 }
6157
6158 Flush();
6159 return true;
6160}
6161
6162/// Analyze an alloca for SROA.
6163///
6164/// This analyzes the alloca to ensure we can reason about it, builds
6165/// the slices of the alloca, and then hands it off to be split and
6166/// rewritten as needed.
6167std::pair<bool /*Changed*/, bool /*CFGChanged*/>
6168SROA::runOnAlloca(AllocaInst &AI) {
6169 bool Changed = false;
6170 bool CFGChanged = false;
6171
6172 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
6173 ++NumAllocasAnalyzed;
6174
6175 // Special case dead allocas, as they're trivial.
6176 if (AI.use_empty()) {
6177 AI.eraseFromParent();
6178 Changed = true;
6179 return {Changed, CFGChanged};
6180 }
6181 const DataLayout &DL = AI.getDataLayout();
6182
6183 // Skip alloca forms that this analysis can't handle.
6184 std::optional<TypeSize> Size = AI.getAllocationSize(DL);
6185 if (AI.isArrayAllocation() || !Size || Size->isScalable() || Size->isZero())
6186 return {Changed, CFGChanged};
6187
6188 // First, split any FCA loads and stores touching this alloca to promote
6189 // better splitting and promotion opportunities.
6190 IRBuilderTy IRB(&AI);
6191 AggLoadStoreRewriter AggRewriter(DL, IRB);
6192 Changed |= AggRewriter.rewrite(AI);
6193
6194 // Build the slices using a recursive instruction-visiting builder.
6195 AllocaSlices AS(DL, AI);
6196 LLVM_DEBUG(AS.print(dbgs()));
6197 if (AS.isEscaped())
6198 return {Changed, CFGChanged};
6199
6200 if (AS.isEscapedReadOnly()) {
6201 Changed |= propagateStoredValuesToLoads(AI, AS);
6202 return {Changed, CFGChanged};
6203 }
6204
6205 // Delete all the dead users of this alloca before splitting and rewriting it.
6206 for (Instruction *DeadUser : AS.getDeadUsers()) {
6207 // Free up everything used by this instruction.
6208 for (Use &DeadOp : DeadUser->operands())
6209 clobberUse(DeadOp);
6210
6211 // Now replace the uses of this instruction.
6212 DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
6213
6214 // And mark it for deletion.
6215 DeadInsts.push_back(DeadUser);
6216 Changed = true;
6217 }
6218 for (Use *DeadOp : AS.getDeadOperands()) {
6219 clobberUse(*DeadOp);
6220 Changed = true;
6221 }
6222
6223 // No slices to split. Leave the dead alloca for a later pass to clean up.
6224 if (AS.begin() == AS.end())
6225 return {Changed, CFGChanged};
6226
6227 Changed |= splitAlloca(AI, AS);
6228
6229 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
6230 while (!SpeculatablePHIs.empty())
6231 speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
6232
6233 LLVM_DEBUG(dbgs() << " Rewriting Selects\n");
6234 auto RemainingSelectsToRewrite = SelectsToRewrite.takeVector();
6235 while (!RemainingSelectsToRewrite.empty()) {
6236 const auto [K, V] = RemainingSelectsToRewrite.pop_back_val();
6237 CFGChanged |=
6238 rewriteSelectInstMemOps(*K, V, IRB, PreserveCFG ? nullptr : DTU);
6239 }
6240
6241 return {Changed, CFGChanged};
6242}
6243
6244/// Delete the dead instructions accumulated in this run.
6245///
6246/// Recursively deletes the dead instructions we've accumulated. This is done
6247/// at the very end to maximize locality of the recursive delete and to
6248/// minimize the problems of invalidated instruction pointers as such pointers
6249/// are used heavily in the intermediate stages of the algorithm.
6250///
6251/// We also record the alloca instructions deleted here so that they aren't
6252/// subsequently handed to mem2reg to promote.
6253bool SROA::deleteDeadInstructions(
6254 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
6255 bool Changed = false;
6256 while (!DeadInsts.empty()) {
6257 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
6258 if (!I)
6259 continue;
6260 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
6261
6262 // If the instruction is an alloca, find the possible dbg.declare connected
6263 // to it, and remove it too. We must do this before calling RAUW or we will
6264 // not be able to find it.
6265 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6266 DeletedAllocas.insert(AI);
6267 for (DbgVariableRecord *OldDII : findDVRDeclares(AI))
6268 OldDII->eraseFromParent();
6269 }
6270
6272 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6273
6274 for (Use &Operand : I->operands())
6275 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
6276 // Zero out the operand and see if it becomes trivially dead.
6277 Operand = nullptr;
6279 DeadInsts.push_back(U);
6280 }
6281
6282 ++NumDeleted;
6283 I->eraseFromParent();
6284 Changed = true;
6285 }
6286 return Changed;
6287}
6288/// Promote the allocas, using the best available technique.
6289///
6290/// This attempts to promote whatever allocas have been identified as viable in
6291/// the PromotableAllocas list. If that list is empty, there is nothing to do.
6292/// This function returns whether any promotion occurred.
6293bool SROA::promoteAllocas() {
6294 if (PromotableAllocas.empty())
6295 return false;
6296
6297 if (SROASkipMem2Reg) {
6298 LLVM_DEBUG(dbgs() << "Not promoting allocas with mem2reg!\n");
6299 } else {
6300 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
6301 NumPromoted += PromotableAllocas.size();
6302 PromoteMemToReg(PromotableAllocas.getArrayRef(), DTU->getDomTree(), AC);
6303 }
6304
6305 PromotableAllocas.clear();
6306 return true;
6307}
6308
6309std::pair<bool /*Changed*/, bool /*CFGChanged*/> SROA::runSROA(Function &F) {
6310 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
6311
6312 const DataLayout &DL = F.getDataLayout();
6313 BasicBlock &EntryBB = F.getEntryBlock();
6314 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
6315 I != E; ++I) {
6316 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6317 std::optional<TypeSize> Size = AI->getAllocationSize(DL);
6318 if (Size && Size->isScalable() && isAllocaPromotable(AI))
6319 PromotableAllocas.insert(AI);
6320 else
6321 Worklist.insert(AI);
6322 }
6323 }
6324
6325 bool Changed = false;
6326 bool CFGChanged = false;
6327 // A set of deleted alloca instruction pointers which should be removed from
6328 // the list of promotable allocas.
6329 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
6330
6331 do {
6332 while (!Worklist.empty()) {
6333 auto [IterationChanged, IterationCFGChanged] =
6334 runOnAlloca(*Worklist.pop_back_val());
6335 Changed |= IterationChanged;
6336 CFGChanged |= IterationCFGChanged;
6337
6338 Changed |= deleteDeadInstructions(DeletedAllocas);
6339
6340 // Remove the deleted allocas from various lists so that we don't try to
6341 // continue processing them.
6342 if (!DeletedAllocas.empty()) {
6343 Worklist.set_subtract(DeletedAllocas);
6344 PostPromotionWorklist.set_subtract(DeletedAllocas);
6345 PromotableAllocas.set_subtract(DeletedAllocas);
6346 DeletedAllocas.clear();
6347 }
6348 }
6349
6350 Changed |= promoteAllocas();
6351
6352 Worklist = PostPromotionWorklist;
6353 PostPromotionWorklist.clear();
6354 } while (!Worklist.empty());
6355
6356 assert((!CFGChanged || Changed) && "Can not only modify the CFG.");
6357 assert((!CFGChanged || !PreserveCFG) &&
6358 "Should not have modified the CFG when told to preserve it.");
6359
6360 if (Changed && isAssignmentTrackingEnabled(*F.getParent())) {
6361 for (auto &BB : F) {
6363 }
6364 }
6365
6366 return {Changed, CFGChanged};
6367}
6368
6372 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6373 auto [Changed, CFGChanged] =
6374 SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6375 if (!Changed)
6376 return PreservedAnalyses::all();
6378 if (!CFGChanged)
6381 return PA;
6382}
6383
6385 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6386 static_cast<PassInfoMixin<SROAPass> *>(this)->printPipeline(
6387 OS, MapClassName2PassName);
6388 OS << '<'
6389 << (Options.CFG == SROAOptions::PreserveCFG ? "preserve-cfg"
6390 : "modify-cfg");
6391 if (Options.AggregateToVector)
6392 OS << ";aggregate-to-vector";
6393 OS << '>';
6394}
6395
6396SROAPass::SROAPass(SROAOptions Options) : Options(Options) {}
6397
6398namespace {
6399
6400/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
6401class SROALegacyPass : public FunctionPass {
6403
6404public:
6405 static char ID;
6406
6408 : FunctionPass(ID), Options(Options) {
6410 }
6411
6412 bool runOnFunction(Function &F) override {
6413 if (skipFunction(F))
6414 return false;
6415
6416 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6417 AssumptionCache &AC =
6418 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6419 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6420 auto [Changed, _] = SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6421 return Changed;
6422 }
6423
6424 void getAnalysisUsage(AnalysisUsage &AU) const override {
6425 AU.addRequired<AssumptionCacheTracker>();
6426 AU.addRequired<DominatorTreeWrapperPass>();
6427 AU.addPreserved<GlobalsAAWrapperPass>();
6428 AU.addPreserved<DominatorTreeWrapperPass>();
6429 }
6430
6431 StringRef getPassName() const override { return "SROA"; }
6432};
6433
6434} // end anonymous namespace
6435
6436char SROALegacyPass::ID = 0;
6437
6438FunctionPass *llvm::createSROAPass(bool PreserveCFG, bool AggregateToVector) {
6439 return new SROALegacyPass(SROAOptions(PreserveCFG ? SROAOptions::PreserveCFG
6441 AggregateToVector));
6442}
6443
6444INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
6445 "Scalar Replacement Of Aggregates", false, false)
6448INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
Flatten the CFG
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:621
This file implements a map that provides insertion order iteration.
static std::optional< AllocFnsTy > getAllocationSize(const CallBase *CB, const TargetLibraryInfo *TLI)
static std::optional< uint64_t > getSizeInBytes(std::optional< uint64_t > SizeInBits)
Memory SSA
Definition MemorySSA.cpp:73
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
#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 defines the PointerIntPair class.
This file provides a collection of visitors which walk the (instruction) uses of a pointer.
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit, uint64_t OldAllocaOffsetInBits, uint64_t SliceSizeInBits, Instruction *OldInst, Instruction *Inst, Value *Dest, Value *Value, const DataLayout &DL)
Find linked dbg.assign and generate a new one with the correct FragmentInfo.
Definition SROA.cpp:342
static VectorType * isVectorPromotionViable(Partition &P, const DataLayout &DL, unsigned VScale)
Test whether the given alloca partitioning and range of slices can be promoted to a vector.
Definition SROA.cpp:2270
static Align getAdjustedAlignment(Instruction *I, uint64_t Offset)
Compute the adjusted alignment for a load or store from an offset.
Definition SROA.cpp:1943
static VectorType * checkVectorTypesForPromotion(Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool HaveCommonEltTy, Type *CommonEltTy, bool HaveVecPtrTy, bool HaveCommonVecPtrTy, VectorType *CommonVecPtrTy, unsigned VScale)
Test whether any vector type in CandidateTys is viable for promotion.
Definition SROA.cpp:2121
static std::pair< Type *, IntegerType * > findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E, uint64_t EndOffset)
Walk the range of a partitioning looking for a common type to cover this sequence of slices.
Definition SROA.cpp:1508
static Type * stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty)
Strip aggregate type wrapping.
Definition SROA.cpp:4691
static FragCalcResult calculateFragment(DILocalVariable *Variable, uint64_t NewStorageSliceOffsetInBits, uint64_t NewStorageSliceSizeInBits, std::optional< DIExpression::FragmentInfo > StorageFragment, std::optional< DIExpression::FragmentInfo > CurrentFragment, DIExpression::FragmentInfo &Target)
Definition SROA.cpp:277
static DIExpression * createOrReplaceFragment(const DIExpression *Expr, DIExpression::FragmentInfo Frag, int64_t BitExtractOffset)
Create or replace an existing fragment in a DIExpression with Frag.
Definition SROA.cpp:5739
static Value * insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, Value *V, uint64_t Offset, const Twine &Name)
Definition SROA.cpp:2513
static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, VectorType *Ty, uint64_t ElementSize, const DataLayout &DL, unsigned VScale)
Test whether the given slice use can be promoted to a vector.
Definition SROA.cpp:2041
static Value * getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, APInt Offset, Type *PointerTy, const Twine &NamePrefix)
Compute an adjusted pointer from Ptr by Offset bytes where the resulting pointer has PointerTy.
Definition SROA.cpp:1932
static bool isIntegerWideningViableForSlice(const Slice &S, uint64_t AllocBeginOffset, Type *AllocaTy, const DataLayout &DL, bool &WholeAllocaOp)
Test whether a slice of an alloca is valid for integer widening.
Definition SROA.cpp:2352
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
Definition SROA.cpp:2546
static Value * foldPHINodeOrSelectInst(Instruction &I)
A helper that folds a PHI node or a select.
Definition SROA.cpp:1004
static bool rewriteSelectInstMemOps(SelectInst &SI, const RewriteableMemOps &Ops, IRBuilderTy &IRB, DomTreeUpdater *DTU)
Definition SROA.cpp:1898
static void rewriteMemOpOfSelect(SelectInst &SI, T &I, SelectHandSpeculativity Spec, DomTreeUpdater &DTU)
Definition SROA.cpp:1831
static Value * foldSelectInst(SelectInst &SI)
Definition SROA.cpp:991
bool isKillAddress(const DbgVariableRecord *DVR)
Definition SROA.cpp:5702
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
Definition SROA.cpp:2567
static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, const DataLayout &DL)
Test whether the given alloca partition's integer operations can be widened to promotable ones.
Definition SROA.cpp:2447
static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN)
Definition SROA.cpp:1652
static VectorType * createAndCheckVectorTypesForPromotion(SetVector< Type * > &OtherTys, ArrayRef< VectorType * > CandidateTysCopy, function_ref< void(Type *)> CheckCandidateType, Partition &P, const DataLayout &DL, SmallVectorImpl< VectorType * > &CandidateTys, bool &HaveCommonEltTy, Type *&CommonEltTy, bool &HaveVecPtrTy, bool &HaveCommonVecPtrTy, VectorType *&CommonVecPtrTy, unsigned VScale)
Definition SROA.cpp:2226
static DebugVariable getAggregateVariable(DbgVariableRecord *DVR)
Definition SROA.cpp:323
static std::tuple< Type *, bool, VectorType * > selectPartitionType(Partition &P, const DataLayout &DL, AllocaInst &AI, LLVMContext &C, bool AggregateToVector)
Select a partition type for an alloca partition.
Definition SROA.cpp:5424
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
Definition SROA.cpp:1577
static FixedVectorType * tryCanonicalizeStructToVector(StructType *STy, Partition &P, const DataLayout &DL)
Try to canonicalize a homogeneous struct partition to a vector type.
Definition SROA.cpp:5357
static Value * extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, IntegerType *Ty, uint64_t Offset, const Twine &Name)
Definition SROA.cpp:2488
static void insertNewDbgInst(DIBuilder &DIB, DbgVariableRecord *Orig, AllocaInst *NewAddr, DIExpression *NewAddrExpr, Instruction *BeforeInst, std::optional< DIExpression::FragmentInfo > NewFragment, int64_t BitExtractAdjustment)
Insert a new DbgRecord.
Definition SROA.cpp:5803
static void speculateSelectInstLoads(SelectInst &SI, LoadInst &LI, IRBuilderTy &IRB)
Definition SROA.cpp:1792
static Value * mergeTwoVectors(Value *V0, Value *V1, const DataLayout &DL, Type *NewAIEltTy, IRBuilder<> &Builder)
This function takes two vector values and combines them into a single vector by concatenating their e...
Definition SROA.cpp:2638
const DIExpression * getAddressExpression(const DbgVariableRecord *DVR)
Definition SROA.cpp:5708
static Type * getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, uint64_t Size)
Try to find a partition of the aggregate type passed in for a given offset and size.
Definition SROA.cpp:4729
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy, unsigned VScale=0)
Test whether we can convert a value from the old to the new type.
Definition SROA.cpp:1953
static SelectHandSpeculativity isSafeLoadOfSelectToSpeculate(LoadInst &LI, SelectInst &SI, bool PreserveCFG)
Definition SROA.cpp:1733
static Type * findCommonTypeThroughPHIOrSelect(Instruction &I)
Find a common load/store type used through a pointer PHI or select.
Definition SROA.cpp:1484
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file implements the SmallBitVector class.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Virtual Register Rewriter
Value * RHS
Value * LHS
Builder for the alloca slices.
Definition SROA.cpp:1016
SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Definition SROA.cpp:1032
An iterator over partitions of the alloca's slices.
Definition SROA.cpp:804
bool operator==(const partition_iterator &RHS) const
Definition SROA.cpp:951
partition_iterator & operator++()
Definition SROA.cpp:971
bool shouldDelete(Instruction *I) const override
Return false if a sub-class wants to keep one of the loads/stores after the SSA construction.
Definition SROA.cpp:6075
BasicLoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, Type *ZeroType)
Definition SROA.cpp:6072
Value * getValueToUseForAlloca(Instruction *I) const override
Return the value to use for the point in the code that the alloca is positioned.
Definition SROA.cpp:6079
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
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:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
bool onlyReadsMemory(unsigned OpNo) const
bool isDataOperand(const Use *U) const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static DIAssignID * getDistinct(LLVMContext &Context)
LLVM_ABI DbgRecord * insertDbgAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *SrcVar, DIExpression *ValExpr, Value *Addr, DIExpression *AddrExpr, const DILocation *DL)
Insert a new dbg_assign record.
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
static LLVM_ABI bool calculateFragmentIntersect(const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits, int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag, std::optional< DIExpression::FragmentInfo > &Result, int64_t &OffsetFromLocationInBits)
Computes a fragment, bit-extract operation if needed, and new constant offset to describe a part of a...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void moveBefore(DbgRecord *MoveBefore)
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void setKillAddress()
Kill the address component.
LLVM_ABI bool isKillLocation() const
LLVM_ABI bool isKillAddress() const
Check whether this kills the address component.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
Value * getValue(unsigned OpIdx=0) const
static LLVM_ABI DbgVariableRecord * createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *Variable, DIExpression *Expression, Value *Address, DIExpression *AddressExpression, const DILocation *DI)
LLVM_ABI void setAssignId(DIAssignID *New)
DIExpression * getExpression() const
static LLVM_ABI DbgVariableRecord * createDVRDeclare(Value *Address, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
DILocalVariable * getVariable() const
DIExpression * getAddressExpression() const
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
Identifies a unique instance of a variable.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
unsigned getVScaleValue() const
Return the value for vscale based on the vscale_range attribute or 0 when unknown.
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset, function_ref< bool(Value &, APInt &)> ExternalAnalysis=nullptr) const
Accumulate the constant address offset of this GEP if possible.
Definition Operator.cpp:130
iterator_range< op_iterator > indices()
Type * getSourceElementType() const
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
Definition IRBuilder.h:61
virtual void InsertHelper(Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const
Definition IRBuilder.h:65
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2910
Base class for instruction visitors.
Definition InstVisitor.h:78
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
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...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI LoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, StringRef Name=StringRef())
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Type * getPointerOperandType() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
LLVMContext & getContext() const
Definition Metadata.h:1233
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
This is the common base class for memset/memcpy/memmove.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PointerIntPair - This class implements a pair of a pointer and small integer.
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
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
PtrUseVisitor(const DataLayout &DL)
LLVM_ABI SROAPass(SROAOptions Options)
If PreserveCFG is set, then the pass is not allowed to modify CFG in any way, even if it would update...
Definition SROA.cpp:6396
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition SROA.cpp:6369
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition SROA.cpp:6384
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::const_iterator const_iterator
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
Value * getValueOperand()
static unsigned getPointerOperandIndex()
Value * getPointerOperand()
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:365
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getSizeInBytes() const
Definition DataLayout.h:752
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
element_iterator element_end() const
ArrayRef< Type * > elements() const
element_iterator element_begin() const
bool isPacked() const
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Type::subtype_iterator element_iterator
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
const Use & getOperandUse(unsigned i) const
Definition User.h:220
Value * getOperand(unsigned i) const
Definition User.h:207
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:828
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI void dropDroppableUsesIn(User &Usr)
Remove every use of this value in User that can safely be removed.
Definition Value.cpp:215
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static VectorType * getWithSizeAndScalar(VectorType *SizeTy, Type *EltTy)
This static method attempts to construct a VectorType with the same size-in-bits as SizeTy but with a...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
Offsets
Offsets in bytes from the start of the input buffer.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:205
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:83
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< bool > SROASkipMem2Reg("sroa-skip-mem2reg", cl::init(false), cl::Hidden)
Disable running mem2reg during SROA in order to test or debug SROA.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
void stable_sort(R &&Range)
Definition STLExtras.h:2116
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2140
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI std::optional< RegOrConstant > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1447
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
void * PointerTy
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
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:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:396
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void initializeSROALegacyPassPass(PassRegistry &)
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...
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRValues(Value *V)
As above, for DVRValues.
Definition DebugInfo.cpp:82
LLVM_ABI void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
constexpr int PoisonMaskElem
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
DWARFExpression::Operation Op
LLVM_ABI FunctionPass * createSROAPass(bool PreserveCFG=true, bool AggregateToVector=false)
Definition SROA.cpp:6438
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
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:2192
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
Definition DebugInfo.cpp:48
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2166
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define NDEBUG
Definition regutils.h:48
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition Metadata.h:822
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Describes an element of a Bitfield.
Definition Bitfields.h:176
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223