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