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