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");
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(
3467 IRB, DL, &NewAI,
3468 APInt(DL.getIndexTypeSizeInBits(NewAI.getType()), Offset), PointerTy,
3469 Twine(OldName) + ".");
3470 }
3471
3472 /// Compute suitable alignment to access this slice of the *new*
3473 /// alloca.
3474 ///
3475 /// You can optionally pass a type to this routine and if that type's ABI
3476 /// alignment is itself suitable, this will return zero.
3477 Align getSliceAlign() {
3478 return commonAlignment(NewAI.getAlign(),
3479 NewBeginOffset - NewAllocaBeginOffset);
3480 }
3481
3482 unsigned getIndex(uint64_t Offset) {
3483 assert(VecTy && "Can only call getIndex when rewriting a vector");
3484 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
3485 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
3486 uint32_t Index = RelOffset / ElementSize;
3487 assert(Index * ElementSize == RelOffset);
3488 return Index;
3489 }
3490
3491 void deleteIfTriviallyDead(Value *V) {
3494 Pass.DeadInsts.push_back(I);
3495 }
3496
3497 Value *rewriteVectorizedLoadInst(LoadInst &LI) {
3498 unsigned BeginIndex = getIndex(NewBeginOffset);
3499 unsigned EndIndex = getIndex(NewEndOffset);
3500 assert(EndIndex > BeginIndex && "Empty vector!");
3501
3502 LoadInst *Load =
3503 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3504
3505 Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3506 LLVMContext::MD_access_group});
3507 return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
3508 }
3509
3510 Value *rewriteIntegerLoad(LoadInst &LI) {
3511 assert(IntTy && "We cannot insert an integer to the alloca");
3512 assert(!LI.isVolatile());
3513 Value *V =
3514 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3515 V = IRB.CreateBitPreservingCastChain(DL, V, IntTy);
3516 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3517 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3518 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
3519 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
3520 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
3521 }
3522 // It is possible that the extracted type is not the load type. This
3523 // happens if there is a load past the end of the alloca, and as
3524 // a consequence the slice is narrower but still a candidate for integer
3525 // lowering. To handle this case, we just zero extend the extracted
3526 // integer.
3527 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
3528 "Can only handle an extract for an overly wide load");
3529 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
3530 V = IRB.CreateZExt(V, LI.getType());
3531 return V;
3532 }
3533
3534 bool visitLoadInst(LoadInst &LI) {
3535 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
3536 Value *OldOp = LI.getOperand(0);
3537 assert(OldOp == OldPtr);
3538
3539 AAMDNodes AATags = LI.getAAMetadata();
3540
3541 unsigned AS = LI.getPointerAddressSpace();
3542
3543 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
3544 : LI.getType();
3545 bool IsPtrAdjusted = false;
3546 Value *V;
3547 if (VecTy) {
3548 V = rewriteVectorizedLoadInst(LI);
3549 } else if (IntTy && LI.getType()->isIntegerTy()) {
3550 V = rewriteIntegerLoad(LI);
3551 } else if (NewBeginOffset == NewAllocaBeginOffset &&
3552 NewEndOffset == NewAllocaEndOffset &&
3553 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
3554 (NewAllocaTy->isIntegerTy() && TargetTy->isIntegerTy() &&
3555 DL.getTypeStoreSize(TargetTy).getFixedValue() > SliceSize &&
3556 !LI.isVolatile()))) {
3557 Value *NewPtr =
3558 getPtrToNewAI(LI.getPointerAddressSpace(), LI.isVolatile());
3559 LoadInst *NewLI = IRB.CreateAlignedLoad(
3560 NewAllocaTy, NewPtr, NewAI.getAlign(), LI.isVolatile(), LI.getName());
3561 if (LI.isVolatile())
3562 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3563 if (NewLI->isAtomic())
3564 NewLI->setAlignment(LI.getAlign());
3565
3566 // Copy any metadata that is valid for the new load. This may require
3567 // conversion to a different kind of metadata, e.g. !nonnull might change
3568 // to !range or vice versa.
3569 copyMetadataForLoad(*NewLI, LI);
3570
3571 // Do this after copyMetadataForLoad() to preserve the TBAA shift.
3572 if (AATags)
3573 NewLI->setAAMetadata(AATags.adjustForAccess(
3574 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3575
3576 // Try to preserve nonnull metadata
3577 V = NewLI;
3578
3579 // If this is an integer load past the end of the slice (which means the
3580 // bytes outside the slice are undef or this load is dead) just forcibly
3581 // fix the integer size with correct handling of endianness.
3582 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
3583 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
3584 if (AITy->getBitWidth() < TITy->getBitWidth()) {
3585 V = IRB.CreateZExt(V, TITy, "load.ext");
3586 if (DL.isBigEndian())
3587 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
3588 "endian_shift");
3589 }
3590 } else {
3591 Type *LTy = IRB.getPtrTy(AS);
3592 LoadInst *NewLI =
3593 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
3594 getSliceAlign(), LI.isVolatile(), LI.getName());
3595
3596 if (AATags)
3597 NewLI->setAAMetadata(AATags.adjustForAccess(
3598 NewBeginOffset - BeginOffset, NewLI->getType(), DL));
3599
3600 if (LI.isVolatile())
3601 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
3602 NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
3603 LLVMContext::MD_access_group});
3604
3605 V = NewLI;
3606 IsPtrAdjusted = true;
3607 }
3608 V = IRB.CreateBitPreservingCastChain(DL, V, TargetTy);
3609
3610 if (IsSplit) {
3611 assert(!LI.isVolatile());
3612 assert(LI.getType()->isIntegerTy() &&
3613 "Only integer type loads and stores are split");
3614 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedValue() &&
3615 "Split load isn't smaller than original load");
3616 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
3617 "Non-byte-multiple bit width");
3618 // Move the insertion point just past the load so that we can refer to it.
3619 BasicBlock::iterator LIIt = std::next(LI.getIterator());
3620 // Ensure the insertion point comes before any debug-info immediately
3621 // after the load, so that variable values referring to the load are
3622 // dominated by it.
3623 LIIt.setHeadBit(true);
3624 IRB.SetInsertPoint(LIIt);
3625 // Create a placeholder value with the same type as LI to use as the
3626 // basis for the new value. This allows us to replace the uses of LI with
3627 // the computed value, and then replace the placeholder with LI, leaving
3628 // LI only used for this computation.
3629 Value *Placeholder =
3630 new LoadInst(LI.getType(), PoisonValue::get(IRB.getPtrTy(AS)), "",
3631 false, Align(1));
3632 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
3633 "insert");
3635 Placeholder->replaceAllUsesWith(&LI);
3636 Placeholder->deleteValue();
3637 } else {
3639 }
3640
3641 Pass.DeadInsts.push_back(&LI);
3642 deleteIfTriviallyDead(OldOp);
3643 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
3644 return !LI.isVolatile() && !IsPtrAdjusted;
3645 }
3646
3647 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
3648 AAMDNodes AATags) {
3649 // Capture V for the purpose of debug-info accounting once it's converted
3650 // to a vector store.
3651 Value *OrigV = V;
3652 if (V->getType() != VecTy) {
3653 unsigned BeginIndex = getIndex(NewBeginOffset);
3654 unsigned EndIndex = getIndex(NewEndOffset);
3655 assert(EndIndex > BeginIndex && "Empty vector!");
3656 unsigned NumElements = EndIndex - BeginIndex;
3657 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3658 "Too many elements!");
3659 Type *SliceTy = (NumElements == 1)
3660 ? ElementTy
3661 : FixedVectorType::get(ElementTy, NumElements);
3662 if (V->getType() != SliceTy)
3663 V = IRB.CreateBitPreservingCastChain(DL, V, SliceTy);
3664
3665 // Mix in the existing elements.
3666 Value *Old =
3667 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
3668 V = insertVector(IRB, Old, V, BeginIndex, "vec");
3669 }
3670 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3671 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3672 LLVMContext::MD_access_group});
3673 if (AATags)
3674 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3675 V->getType(), DL));
3676 Pass.DeadInsts.push_back(&SI);
3677
3678 // NOTE: Careful to use OrigV rather than V.
3679 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3680 Store, Store->getPointerOperand(), OrigV, DL);
3681 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3682 return true;
3683 }
3684
3685 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
3686 assert(IntTy && "We cannot extract an integer from the alloca");
3687 assert(!SI.isVolatile());
3688 if (DL.getTypeSizeInBits(V->getType()).getFixedValue() !=
3689 IntTy->getBitWidth()) {
3690 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3691 "oldload");
3692 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3693 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
3694 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
3695 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
3696 }
3697 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3698 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
3699 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3700 LLVMContext::MD_access_group});
3701 if (AATags)
3702 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3703 V->getType(), DL));
3704
3705 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3706 Store, Store->getPointerOperand(),
3707 Store->getValueOperand(), DL);
3708
3709 Pass.DeadInsts.push_back(&SI);
3710 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
3711 return true;
3712 }
3713
3714 bool visitStoreInst(StoreInst &SI) {
3715 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
3716 Value *OldOp = SI.getOperand(1);
3717 assert(OldOp == OldPtr);
3718
3719 AAMDNodes AATags = SI.getAAMetadata();
3720 Value *V = SI.getValueOperand();
3721
3722 // Strip all inbounds GEPs and pointer casts to try to dig out any root
3723 // alloca that should be re-examined after promoting this alloca.
3724 if (V->getType()->isPointerTy())
3725 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
3726 Pass.PostPromotionWorklist.insert(AI);
3727
3728 TypeSize StoreSize = DL.getTypeStoreSize(V->getType());
3729 if (StoreSize.isFixed() && SliceSize < StoreSize.getFixedValue()) {
3730 assert(!SI.isVolatile());
3731 assert(V->getType()->isIntegerTy() &&
3732 "Only integer type loads and stores are split");
3733 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
3734 "Non-byte-multiple bit width");
3735 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
3736 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
3737 "extract");
3738 }
3739
3740 if (VecTy)
3741 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
3742 if (IntTy && V->getType()->isIntegerTy())
3743 return rewriteIntegerStore(V, SI, AATags);
3744
3745 StoreInst *NewSI;
3746 if (NewBeginOffset == NewAllocaBeginOffset &&
3747 NewEndOffset == NewAllocaEndOffset &&
3748 canConvertValue(DL, V->getType(), NewAllocaTy)) {
3749 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3750 Value *NewPtr =
3751 getPtrToNewAI(SI.getPointerAddressSpace(), SI.isVolatile());
3752
3753 NewSI =
3754 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), SI.isVolatile());
3755 } else {
3756 unsigned AS = SI.getPointerAddressSpace();
3757 Value *NewPtr = getNewAllocaSlicePtr(IRB, IRB.getPtrTy(AS));
3758 NewSI =
3759 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
3760 }
3761 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
3762 LLVMContext::MD_access_group});
3763 if (AATags)
3764 NewSI->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3765 V->getType(), DL));
3766 if (SI.isVolatile())
3767 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
3768 if (NewSI->isAtomic())
3769 NewSI->setAlignment(SI.getAlign());
3770
3771 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
3772 NewSI, NewSI->getPointerOperand(),
3773 NewSI->getValueOperand(), DL);
3774
3775 Pass.DeadInsts.push_back(&SI);
3776 deleteIfTriviallyDead(OldOp);
3777
3778 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
3779 return NewSI->getPointerOperand() == &NewAI &&
3780 NewSI->getValueOperand()->getType() == NewAllocaTy &&
3781 !SI.isVolatile();
3782 }
3783
3784 /// Compute an integer value from splatting an i8 across the given
3785 /// number of bytes.
3786 ///
3787 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
3788 /// call this routine.
3789 /// FIXME: Heed the advice above.
3790 ///
3791 /// \param V The i8 value to splat.
3792 /// \param Size The number of bytes in the output (assuming i8 is one byte)
3793 Value *getIntegerSplat(Value *V, unsigned Size) {
3794 assert(Size > 0 && "Expected a positive number of bytes.");
3795 IntegerType *VTy = cast<IntegerType>(V->getType());
3796 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
3797 if (Size == 1)
3798 return V;
3799
3800 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
3801 V = IRB.CreateMul(
3802 IRB.CreateZExt(V, SplatIntTy, "zext"),
3803 IRB.CreateUDiv(Constant::getAllOnesValue(SplatIntTy),
3804 IRB.CreateZExt(Constant::getAllOnesValue(V->getType()),
3805 SplatIntTy)),
3806 "isplat");
3807 return V;
3808 }
3809
3810 /// Compute a vector splat for a given element value.
3811 Value *getVectorSplat(Value *V, unsigned NumElements) {
3812 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
3813 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
3814 return V;
3815 }
3816
3817 bool visitMemSetInst(MemSetInst &II) {
3818 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3819 assert(II.getRawDest() == OldPtr);
3820
3821 AAMDNodes AATags = II.getAAMetadata();
3822
3823 // If the memset has a variable size, it cannot be split, just adjust the
3824 // pointer to the new alloca.
3825 if (!isa<ConstantInt>(II.getLength())) {
3826 assert(!IsSplit);
3827 assert(NewBeginOffset == BeginOffset);
3828 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
3829 II.setDestAlignment(getSliceAlign());
3830 // In theory we should call migrateDebugInfo here. However, we do not
3831 // emit dbg.assign intrinsics for mem intrinsics storing through non-
3832 // constant geps, or storing a variable number of bytes.
3834 "AT: Unexpected link to non-const GEP");
3835 deleteIfTriviallyDead(OldPtr);
3836 return false;
3837 }
3838
3839 // Record this instruction for deletion.
3840 Pass.DeadInsts.push_back(&II);
3841
3842 Type *ScalarTy = NewAllocaTy->getScalarType();
3843
3844 const bool CanContinue = [&]() {
3845 if (VecTy || IntTy)
3846 return true;
3847 if (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset)
3848 return false;
3849 // Length must be in range for FixedVectorType.
3850 auto *C = cast<ConstantInt>(II.getLength());
3851 const uint64_t Len = C->getLimitedValue();
3852 if (Len > std::numeric_limits<unsigned>::max())
3853 return false;
3854 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
3855 auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
3856 return canConvertValue(DL, SrcTy, NewAllocaTy) &&
3857 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedValue());
3858 }();
3859
3860 // If this doesn't map cleanly onto the alloca type, and that type isn't
3861 // a single value type, just emit a memset.
3862 if (!CanContinue) {
3863 Type *SizeTy = II.getLength()->getType();
3864 unsigned Sz = NewEndOffset - NewBeginOffset;
3865 Constant *Size = ConstantInt::get(SizeTy, Sz);
3866 MemIntrinsic *New = cast<MemIntrinsic>(IRB.CreateMemSet(
3867 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
3868 MaybeAlign(getSliceAlign()), II.isVolatile()));
3869 if (AATags)
3870 New->setAAMetadata(
3871 AATags.adjustForAccess(NewBeginOffset - BeginOffset, Sz));
3872
3873 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3874 New, New->getRawDest(), nullptr, DL);
3875
3876 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3877 return false;
3878 }
3879
3880 // If we can represent this as a simple value, we have to build the actual
3881 // value to store, which requires expanding the byte present in memset to
3882 // a sensible representation for the alloca type. This is essentially
3883 // splatting the byte to a sufficiently wide integer, splatting it across
3884 // any desired vector width, and bitcasting to the final type.
3885 Value *V;
3886
3887 if (VecTy) {
3888 // If this is a memset of a vectorized alloca, insert it.
3889 assert(ElementTy == ScalarTy);
3890
3891 unsigned BeginIndex = getIndex(NewBeginOffset);
3892 unsigned EndIndex = getIndex(NewEndOffset);
3893 assert(EndIndex > BeginIndex && "Empty vector!");
3894 unsigned NumElements = EndIndex - BeginIndex;
3895 assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
3896 "Too many elements!");
3897
3898 Value *Splat = getIntegerSplat(
3899 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8);
3900 Splat = IRB.CreateBitPreservingCastChain(DL, Splat, ElementTy);
3901 if (NumElements > 1)
3902 Splat = getVectorSplat(Splat, NumElements);
3903
3904 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
3905 "oldload");
3906 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
3907 } else if (IntTy) {
3908 // If this is a memset on an alloca where we can widen stores, insert the
3909 // set integer.
3910 assert(!II.isVolatile());
3911
3912 uint64_t Size = NewEndOffset - NewBeginOffset;
3913 V = getIntegerSplat(II.getValue(), Size);
3914
3915 if (IntTy && (NewBeginOffset != NewAllocaBeginOffset ||
3916 NewEndOffset != NewAllocaEndOffset)) {
3917 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI,
3918 NewAI.getAlign(), "oldload");
3919 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
3920 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3921 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
3922 } else {
3923 assert(V->getType() == IntTy &&
3924 "Wrong type for an alloca wide integer!");
3925 }
3926 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3927 } else {
3928 // Established these invariants above.
3929 assert(NewBeginOffset == NewAllocaBeginOffset);
3930 assert(NewEndOffset == NewAllocaEndOffset);
3931
3932 V = getIntegerSplat(II.getValue(),
3933 DL.getTypeSizeInBits(ScalarTy).getFixedValue() / 8);
3934 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(NewAllocaTy))
3935 V = getVectorSplat(
3936 V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
3937
3938 V = IRB.CreateBitPreservingCastChain(DL, V, NewAllocaTy);
3939 }
3940
3941 Value *NewPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
3942 StoreInst *New =
3943 IRB.CreateAlignedStore(V, NewPtr, NewAI.getAlign(), II.isVolatile());
3944 New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
3945 LLVMContext::MD_access_group});
3946 if (AATags)
3947 New->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
3948 V->getType(), DL));
3949
3950 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
3951 New, New->getPointerOperand(), V, DL);
3952
3953 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
3954 return !II.isVolatile();
3955 }
3956
3957 bool visitMemTransferInst(MemTransferInst &II) {
3958 // Rewriting of memory transfer instructions can be a bit tricky. We break
3959 // them into two categories: split intrinsics and unsplit intrinsics.
3960
3961 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
3962
3963 AAMDNodes AATags = II.getAAMetadata();
3964
3965 bool IsDest = &II.getRawDestUse() == OldUse;
3966 assert((IsDest && II.getRawDest() == OldPtr) ||
3967 (!IsDest && II.getRawSource() == OldPtr));
3968
3969 Align SliceAlign = getSliceAlign();
3970 // For unsplit intrinsics, we simply modify the source and destination
3971 // pointers in place. This isn't just an optimization, it is a matter of
3972 // correctness. With unsplit intrinsics we may be dealing with transfers
3973 // within a single alloca before SROA ran, or with transfers that have
3974 // a variable length. We may also be dealing with memmove instead of
3975 // memcpy, and so simply updating the pointers is the necessary for us to
3976 // update both source and dest of a single call.
3977 if (!IsSplittable) {
3978 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3979 if (IsDest) {
3980 // Update the address component of linked dbg.assigns.
3981 for (DbgVariableRecord *DbgAssign : at::getDVRAssignmentMarkers(&II)) {
3982 if (llvm::is_contained(DbgAssign->location_ops(), II.getDest()) ||
3983 DbgAssign->getAddress() == II.getDest())
3984 DbgAssign->replaceVariableLocationOp(II.getDest(), AdjustedPtr);
3985 }
3986 II.setDest(AdjustedPtr);
3987 II.setDestAlignment(SliceAlign);
3988 } else {
3989 II.setSource(AdjustedPtr);
3990 II.setSourceAlignment(SliceAlign);
3991 }
3992
3993 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
3994 deleteIfTriviallyDead(OldPtr);
3995 return false;
3996 }
3997 // For split transfer intrinsics we have an incredibly useful assurance:
3998 // the source and destination do not reside within the same alloca, and at
3999 // least one of them does not escape. This means that we can replace
4000 // memmove with memcpy, and we don't need to worry about all manner of
4001 // downsides to splitting and transforming the operations.
4002
4003 // If this doesn't map cleanly onto the alloca type, and that type isn't
4004 // a single value type, just emit a memcpy.
4005 bool EmitMemCpy =
4006 !VecTy && !IntTy &&
4007 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
4008 SliceSize != DL.getTypeStoreSize(NewAllocaTy).getFixedValue() ||
4009 !DL.typeSizeEqualsStoreSize(NewAllocaTy) ||
4010 !NewAllocaTy->isSingleValueType());
4011
4012 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
4013 // size hasn't been shrunk based on analysis of the viable range, this is
4014 // a no-op.
4015 if (EmitMemCpy && &OldAI == &NewAI) {
4016 // Ensure the start lines up.
4017 assert(NewBeginOffset == BeginOffset);
4018
4019 // Rewrite the size as needed.
4020 if (NewEndOffset != EndOffset)
4021 II.setLength(NewEndOffset - NewBeginOffset);
4022 return false;
4023 }
4024 // Record this instruction for deletion.
4025 Pass.DeadInsts.push_back(&II);
4026
4027 // Strip all inbounds GEPs and pointer casts to try to dig out any root
4028 // alloca that should be re-examined after rewriting this instruction.
4029 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
4030 if (AllocaInst *AI =
4032 assert(AI != &OldAI && AI != &NewAI &&
4033 "Splittable transfers cannot reach the same alloca on both ends.");
4034 Pass.Worklist.insert(AI);
4035 }
4036
4037 Type *OtherPtrTy = OtherPtr->getType();
4038 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
4039
4040 // Compute the relative offset for the other pointer within the transfer.
4041 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
4042 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
4043 Align OtherAlign =
4044 (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
4045 OtherAlign =
4046 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
4047
4048 if (EmitMemCpy) {
4049 // Compute the other pointer, folding as much as possible to produce
4050 // a single, simple GEP in most cases.
4051 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
4052 OtherPtr->getName() + ".");
4053
4054 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4055 Type *SizeTy = II.getLength()->getType();
4056 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
4057
4058 Value *DestPtr, *SrcPtr;
4059 MaybeAlign DestAlign, SrcAlign;
4060 // Note: IsDest is true iff we're copying into the new alloca slice
4061 if (IsDest) {
4062 DestPtr = OurPtr;
4063 DestAlign = SliceAlign;
4064 SrcPtr = OtherPtr;
4065 SrcAlign = OtherAlign;
4066 } else {
4067 DestPtr = OtherPtr;
4068 DestAlign = OtherAlign;
4069 SrcPtr = OurPtr;
4070 SrcAlign = SliceAlign;
4071 }
4072 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
4073 Size, II.isVolatile());
4074 if (AATags)
4075 New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
4076
4077 APInt Offset(DL.getIndexTypeSizeInBits(DestPtr->getType()), 0);
4078 if (IsDest) {
4079 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8,
4080 &II, New, DestPtr, nullptr, DL);
4081 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
4083 DL, Offset, /*AllowNonInbounds*/ true))) {
4084 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8,
4085 SliceSize * 8, &II, New, DestPtr, nullptr, DL);
4086 }
4087 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
4088 return false;
4089 }
4090
4091 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
4092 NewEndOffset == NewAllocaEndOffset;
4093 uint64_t Size = NewEndOffset - NewBeginOffset;
4094 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
4095 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
4096 unsigned NumElements = EndIndex - BeginIndex;
4097 IntegerType *SubIntTy =
4098 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
4099
4100 // Reset the other pointer type to match the register type we're going to
4101 // use, but using the address space of the original other pointer.
4102 Type *OtherTy;
4103 if (VecTy && !IsWholeAlloca) {
4104 if (NumElements == 1)
4105 OtherTy = VecTy->getElementType();
4106 else
4107 OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
4108 } else if (IntTy && !IsWholeAlloca) {
4109 OtherTy = SubIntTy;
4110 } else {
4111 OtherTy = NewAllocaTy;
4112 }
4113
4114 Value *AdjPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
4115 OtherPtr->getName() + ".");
4116 MaybeAlign SrcAlign = OtherAlign;
4117 MaybeAlign DstAlign = SliceAlign;
4118 if (!IsDest)
4119 std::swap(SrcAlign, DstAlign);
4120
4121 Value *SrcPtr;
4122 Value *DstPtr;
4123
4124 if (IsDest) {
4125 DstPtr = getPtrToNewAI(II.getDestAddressSpace(), II.isVolatile());
4126 SrcPtr = AdjPtr;
4127 } else {
4128 DstPtr = AdjPtr;
4129 SrcPtr = getPtrToNewAI(II.getSourceAddressSpace(), II.isVolatile());
4130 }
4131
4132 Value *Src;
4133 if (VecTy && !IsWholeAlloca && !IsDest) {
4134 Src =
4135 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
4136 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
4137 } else if (IntTy && !IsWholeAlloca && !IsDest) {
4138 Src =
4139 IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(), "load");
4140 Src = IRB.CreateBitPreservingCastChain(DL, Src, IntTy);
4141 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
4142 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
4143 } else {
4144 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
4145 II.isVolatile(), "copyload");
4146 Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
4147 LLVMContext::MD_access_group});
4148 if (AATags)
4149 Load->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4150 Load->getType(), DL));
4151 Src = Load;
4152 }
4153
4154 if (VecTy && !IsWholeAlloca && IsDest) {
4155 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4156 "oldload");
4157 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
4158 } else if (IntTy && !IsWholeAlloca && IsDest) {
4159 Value *Old = IRB.CreateAlignedLoad(NewAllocaTy, &NewAI, NewAI.getAlign(),
4160 "oldload");
4161 Old = IRB.CreateBitPreservingCastChain(DL, Old, IntTy);
4162 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
4163 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
4164 Src = IRB.CreateBitPreservingCastChain(DL, Src, NewAllocaTy);
4165 }
4166
4167 StoreInst *Store = cast<StoreInst>(
4168 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
4169 Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
4170 LLVMContext::MD_access_group});
4171 if (AATags)
4172 Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
4173 Src->getType(), DL));
4174
4175 APInt Offset(DL.getIndexTypeSizeInBits(DstPtr->getType()), 0);
4176 if (IsDest) {
4177
4178 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &II,
4179 Store, DstPtr, Src, DL);
4180 } else if (AllocaInst *Base = dyn_cast<AllocaInst>(
4182 DL, Offset, /*AllowNonInbounds*/ true))) {
4183 migrateDebugInfo(Base, IsSplit, Offset.getZExtValue() * 8, SliceSize * 8,
4184 &II, Store, DstPtr, Src, DL);
4185 }
4186
4187 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4188 return !II.isVolatile();
4189 }
4190
4191 bool visitIntrinsicInst(IntrinsicInst &II) {
4192 assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&
4193 "Unexpected intrinsic!");
4194 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
4195
4196 // Record this instruction for deletion.
4197 Pass.DeadInsts.push_back(&II);
4198
4199 if (II.isDroppable()) {
4200 assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume");
4201 // TODO For now we forget assumed information, this can be improved.
4202 OldPtr->dropDroppableUsesIn(II);
4203 return true;
4204 }
4205
4206 assert(II.getArgOperand(0) == OldPtr);
4207 Type *PointerTy = IRB.getPtrTy(OldPtr->getType()->getPointerAddressSpace());
4208 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
4209 Value *New;
4210 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
4211 New = IRB.CreateLifetimeStart(Ptr);
4212 else
4213 New = IRB.CreateLifetimeEnd(Ptr);
4214
4215 (void)New;
4216 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
4217
4218 return true;
4219 }
4220
4221 void fixLoadStoreAlign(Instruction &Root) {
4222 // This algorithm implements the same visitor loop as
4223 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
4224 // or store found.
4225 SmallPtrSet<Instruction *, 4> Visited;
4226 SmallVector<Instruction *, 4> Uses;
4227 Visited.insert(&Root);
4228 Uses.push_back(&Root);
4229 do {
4230 Instruction *I = Uses.pop_back_val();
4231
4232 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4233 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
4234 continue;
4235 }
4236 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4237 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
4238 continue;
4239 }
4240
4244 for (User *U : I->users())
4245 if (Visited.insert(cast<Instruction>(U)).second)
4246 Uses.push_back(cast<Instruction>(U));
4247 } while (!Uses.empty());
4248 }
4249
4250 bool visitPHINode(PHINode &PN) {
4251 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
4252 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
4253 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
4254
4255 // We would like to compute a new pointer in only one place, but have it be
4256 // as local as possible to the PHI. To do that, we re-use the location of
4257 // the old pointer, which necessarily must be in the right position to
4258 // dominate the PHI.
4259 IRBuilderBase::InsertPointGuard Guard(IRB);
4260 if (isa<PHINode>(OldPtr))
4261 IRB.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
4262 else
4263 IRB.SetInsertPoint(OldPtr);
4264 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
4265
4266 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4267 // Replace the operands which were using the old pointer.
4268 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
4269
4270 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
4271 deleteIfTriviallyDead(OldPtr);
4272
4273 // Fix the alignment of any loads or stores using this PHI node.
4274 fixLoadStoreAlign(PN);
4275
4276 // PHIs can't be promoted on their own, but often can be speculated. We
4277 // check the speculation outside of the rewriter so that we see the
4278 // fully-rewritten alloca.
4279 PHIUsers.insert(&PN);
4280 return true;
4281 }
4282
4283 bool visitSelectInst(SelectInst &SI) {
4284 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4285 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
4286 "Pointer isn't an operand!");
4287 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
4288 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
4289
4290 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4291 // Replace the operands which were using the old pointer.
4292 if (SI.getOperand(1) == OldPtr)
4293 SI.setOperand(1, NewPtr);
4294 if (SI.getOperand(2) == OldPtr)
4295 SI.setOperand(2, NewPtr);
4296
4297 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
4298 deleteIfTriviallyDead(OldPtr);
4299
4300 // Fix the alignment of any loads or stores using this select.
4301 fixLoadStoreAlign(SI);
4302
4303 // Selects can't be promoted on their own, but often can be speculated. We
4304 // check the speculation outside of the rewriter so that we see the
4305 // fully-rewritten alloca.
4306 SelectUsers.insert(&SI);
4307 return true;
4308 }
4309};
4310
4311/// Visitor to rewrite aggregate loads and stores as scalar.
4312///
4313/// This pass aggressively rewrites all aggregate loads and stores on
4314/// a particular pointer (or any pointer derived from it which we can identify)
4315/// with scalar loads and stores.
4316class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
4317 // Befriend the base class so it can delegate to private visit methods.
4318 friend class InstVisitor<AggLoadStoreRewriter, bool>;
4319
4320 /// Queue of pointer uses to analyze and potentially rewrite.
4322
4323 /// Set to prevent us from cycling with phi nodes and loops.
4324 SmallPtrSet<User *, 8> Visited;
4325
4326 /// The current pointer use being rewritten. This is used to dig up the used
4327 /// value (as opposed to the user).
4328 Use *U = nullptr;
4329
4330 /// Used to calculate offsets, and hence alignment, of subobjects.
4331 const DataLayout &DL;
4332
4333 IRBuilderTy &IRB;
4334
4335public:
4336 AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
4337 : DL(DL), IRB(IRB) {}
4338
4339 /// Rewrite loads and stores through a pointer and all pointers derived from
4340 /// it.
4341 bool rewrite(Instruction &I) {
4342 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
4343 enqueueUsers(I);
4344 bool Changed = false;
4345 while (!Queue.empty()) {
4346 U = Queue.pop_back_val();
4347 Changed |= visit(cast<Instruction>(U->getUser()));
4348 }
4349 return Changed;
4350 }
4351
4352private:
4353 /// Enqueue all the users of the given instruction for further processing.
4354 /// This uses a set to de-duplicate users.
4355 void enqueueUsers(Instruction &I) {
4356 for (Use &U : I.uses())
4357 if (Visited.insert(U.getUser()).second)
4358 Queue.push_back(&U);
4359 }
4360
4361 // Conservative default is to not rewrite anything.
4362 bool visitInstruction(Instruction &I) { return false; }
4363
4364 /// Generic recursive split emission class.
4365 template <typename Derived> class OpSplitter {
4366 protected:
4367 /// The builder used to form new instructions.
4368 IRBuilderTy &IRB;
4369
4370 /// The indices which to be used with insert- or extractvalue to select the
4371 /// appropriate value within the aggregate.
4372 SmallVector<unsigned, 4> Indices;
4373
4374 /// The indices to a GEP instruction which will move Ptr to the correct slot
4375 /// within the aggregate.
4376 SmallVector<Value *, 4> GEPIndices;
4377
4378 /// The base pointer of the original op, used as a base for GEPing the
4379 /// split operations.
4380 Value *Ptr;
4381
4382 /// The base pointee type being GEPed into.
4383 Type *BaseTy;
4384
4385 /// Known alignment of the base pointer.
4386 Align BaseAlign;
4387
4388 /// To calculate offset of each component so we can correctly deduce
4389 /// alignments.
4390 const DataLayout &DL;
4391
4392 /// Initialize the splitter with an insertion point, Ptr and start with a
4393 /// single zero GEP index.
4394 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4395 Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
4396 : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
4397 BaseAlign(BaseAlign), DL(DL) {
4398 IRB.SetInsertPoint(InsertionPoint);
4399 }
4400
4401 public:
4402 /// Generic recursive split emission routine.
4403 ///
4404 /// This method recursively splits an aggregate op (load or store) into
4405 /// scalar or vector ops. It splits recursively until it hits a single value
4406 /// and emits that single value operation via the template argument.
4407 ///
4408 /// The logic of this routine relies on GEPs and insertvalue and
4409 /// extractvalue all operating with the same fundamental index list, merely
4410 /// formatted differently (GEPs need actual values).
4411 ///
4412 /// \param Ty The type being split recursively into smaller ops.
4413 /// \param Agg The aggregate value being built up or stored, depending on
4414 /// whether this is splitting a load or a store respectively.
4415 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
4416 if (Ty->isSingleValueType()) {
4417 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
4418 return static_cast<Derived *>(this)->emitFunc(
4419 Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
4420 }
4421
4422 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
4423 unsigned OldSize = Indices.size();
4424 (void)OldSize;
4425 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
4426 ++Idx) {
4427 assert(Indices.size() == OldSize && "Did not return to the old size");
4428 Indices.push_back(Idx);
4429 GEPIndices.push_back(IRB.getInt32(Idx));
4430 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
4431 GEPIndices.pop_back();
4432 Indices.pop_back();
4433 }
4434 return;
4435 }
4436
4437 if (StructType *STy = dyn_cast<StructType>(Ty)) {
4438 unsigned OldSize = Indices.size();
4439 (void)OldSize;
4440 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
4441 ++Idx) {
4442 assert(Indices.size() == OldSize && "Did not return to the old size");
4443 Indices.push_back(Idx);
4444 GEPIndices.push_back(IRB.getInt32(Idx));
4445 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
4446 GEPIndices.pop_back();
4447 Indices.pop_back();
4448 }
4449 return;
4450 }
4451
4452 llvm_unreachable("Only arrays and structs are aggregate loadable types");
4453 }
4454 };
4455
4456 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
4457 AAMDNodes AATags;
4458 // A vector to hold the split components that we want to emit
4459 // separate fake uses for.
4460 SmallVector<Value *, 4> Components;
4461 // A vector to hold all the fake uses of the struct that we are splitting.
4462 // Usually there should only be one, but we are handling the general case.
4464
4465 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4466 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
4467 IRBuilderTy &IRB)
4468 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
4469 IRB),
4470 AATags(AATags) {}
4471
4472 /// Emit a leaf load of a single value. This is called at the leaves of the
4473 /// recursive emission to actually load values.
4474 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4476 // Load the single value and insert it using the indices.
4477 Value *GEP =
4478 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4479 LoadInst *Load =
4480 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
4481
4482 APInt Offset(
4483 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4484 if (AATags &&
4485 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
4486 Load->setAAMetadata(
4487 AATags.adjustForAccess(Offset.getZExtValue(), Load->getType(), DL));
4488 // Record the load so we can generate a fake use for this aggregate
4489 // component.
4490 Components.push_back(Load);
4491
4492 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
4493 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
4494 }
4495
4496 // Stash the fake uses that use the value generated by this instruction.
4497 void recordFakeUses(LoadInst &LI) {
4498 for (Use &U : LI.uses())
4499 if (auto *II = dyn_cast<IntrinsicInst>(U.getUser()))
4500 if (II->getIntrinsicID() == Intrinsic::fake_use)
4501 FakeUses.push_back(II);
4502 }
4503
4504 // Replace all fake uses of the aggregate with a series of fake uses, one
4505 // for each split component.
4506 void emitFakeUses() {
4507 for (Instruction *I : FakeUses) {
4508 IRB.SetInsertPoint(I);
4509 for (auto *V : Components)
4510 IRB.CreateIntrinsic(Intrinsic::fake_use, {V});
4511 I->eraseFromParent();
4512 }
4513 }
4514 };
4515
4516 bool visitLoadInst(LoadInst &LI) {
4517 assert(LI.getPointerOperand() == *U);
4518 if (!LI.isSimple() || LI.getType()->isSingleValueType())
4519 return false;
4520
4521 // We have an aggregate being loaded, split it apart.
4522 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
4523 LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
4524 getAdjustedAlignment(&LI, 0), DL, IRB);
4525 Splitter.recordFakeUses(LI);
4527 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
4528 Splitter.emitFakeUses();
4529 Visited.erase(&LI);
4531 LI.eraseFromParent();
4532 return true;
4533 }
4534
4535 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
4536 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
4537 AAMDNodes AATags, StoreInst *AggStore, Align BaseAlign,
4538 const DataLayout &DL, IRBuilderTy &IRB)
4539 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
4540 DL, IRB),
4541 AATags(AATags), AggStore(AggStore) {}
4542 AAMDNodes AATags;
4543 StoreInst *AggStore;
4544 /// Emit a leaf store of a single value. This is called at the leaves of the
4545 /// recursive emission to actually produce stores.
4546 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
4548 // Extract the single value and store it using the indices.
4549 //
4550 // The gep and extractvalue values are factored out of the CreateStore
4551 // call to make the output independent of the argument evaluation order.
4552 Value *ExtractValue =
4553 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
4554 Value *InBoundsGEP =
4555 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
4556 StoreInst *Store =
4557 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
4558
4559 APInt Offset(
4560 DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
4561 GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset);
4562 if (AATags) {
4563 Store->setAAMetadata(AATags.adjustForAccess(
4564 Offset.getZExtValue(), ExtractValue->getType(), DL));
4565 }
4566
4567 // migrateDebugInfo requires the base Alloca. Walk to it from this gep.
4568 // If we cannot (because there's an intervening non-const or unbounded
4569 // gep) then we wouldn't expect to see dbg.assign intrinsics linked to
4570 // this instruction.
4572 if (auto *OldAI = dyn_cast<AllocaInst>(Base)) {
4573 uint64_t SizeInBits =
4574 DL.getTypeSizeInBits(Store->getValueOperand()->getType());
4575 migrateDebugInfo(OldAI, /*IsSplit*/ true, Offset.getZExtValue() * 8,
4576 SizeInBits, AggStore, Store,
4577 Store->getPointerOperand(), Store->getValueOperand(),
4578 DL);
4579 } else {
4581 "AT: unexpected debug.assign linked to store through "
4582 "unbounded GEP");
4583 }
4584 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
4585 }
4586 };
4587
4588 bool visitStoreInst(StoreInst &SI) {
4589 if (!SI.isSimple() || SI.getPointerOperand() != *U)
4590 return false;
4591 Value *V = SI.getValueOperand();
4592 if (V->getType()->isSingleValueType())
4593 return false;
4594
4595 // We have an aggregate being stored, split it apart.
4596 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
4597 StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(), &SI,
4598 getAdjustedAlignment(&SI, 0), DL, IRB);
4599 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
4600 Visited.erase(&SI);
4601 // The stores replacing SI each have markers describing fragments of the
4602 // assignment so delete the assignment markers linked to SI.
4604 SI.eraseFromParent();
4605 return true;
4606 }
4607
4608 bool visitBitCastInst(BitCastInst &BC) {
4609 enqueueUsers(BC);
4610 return false;
4611 }
4612
4613 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
4614 enqueueUsers(ASC);
4615 return false;
4616 }
4617
4618 // Unfold gep (select cond, ptr1, ptr2), idx
4619 // => select cond, gep(ptr1, idx), gep(ptr2, idx)
4620 // and gep ptr, (select cond, idx1, idx2)
4621 // => select cond, gep(ptr, idx1), gep(ptr, idx2)
4622 // We also allow for i1 zext indices, which are equivalent to selects.
4623 bool unfoldGEPSelect(GetElementPtrInst &GEPI) {
4624 // Check whether the GEP has exactly one select operand and all indices
4625 // will become constant after the transform.
4627 for (Value *Op : GEPI.indices()) {
4628 if (auto *SI = dyn_cast<SelectInst>(Op)) {
4629 if (Sel)
4630 return false;
4631
4632 Sel = SI;
4633 if (!isa<ConstantInt>(SI->getTrueValue()) ||
4634 !isa<ConstantInt>(SI->getFalseValue()))
4635 return false;
4636 continue;
4637 }
4638 if (auto *ZI = dyn_cast<ZExtInst>(Op)) {
4639 if (Sel)
4640 return false;
4641 Sel = ZI;
4642 if (!ZI->getSrcTy()->isIntegerTy(1))
4643 return false;
4644 continue;
4645 }
4646
4647 if (!isa<ConstantInt>(Op))
4648 return false;
4649 }
4650
4651 if (!Sel)
4652 return false;
4653
4654 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):\n";
4655 dbgs() << " original: " << *Sel << "\n";
4656 dbgs() << " " << GEPI << "\n";);
4657
4658 auto GetNewOps = [&](Value *SelOp) {
4659 SmallVector<Value *> NewOps;
4660 for (Value *Op : GEPI.operands())
4661 if (Op == Sel)
4662 NewOps.push_back(SelOp);
4663 else
4664 NewOps.push_back(Op);
4665 return NewOps;
4666 };
4667
4668 Value *Cond, *True, *False;
4669 Instruction *MDFrom = nullptr;
4670 if (auto *SI = dyn_cast<SelectInst>(Sel)) {
4671 Cond = SI->getCondition();
4672 True = SI->getTrueValue();
4673 False = SI->getFalseValue();
4674 MDFrom = SI;
4675 } else {
4676 Cond = Sel->getOperand(0);
4677 True = ConstantInt::get(Sel->getType(), 1);
4678 False = ConstantInt::get(Sel->getType(), 0);
4679 }
4680 SmallVector<Value *> TrueOps = GetNewOps(True);
4681 SmallVector<Value *> FalseOps = GetNewOps(False);
4682
4683 IRB.SetInsertPoint(&GEPI);
4684 GEPNoWrapFlags NW = GEPI.getNoWrapFlags();
4685
4686 Type *Ty = GEPI.getSourceElementType();
4687 Value *NTrue = IRB.CreateGEP(Ty, TrueOps[0], ArrayRef(TrueOps).drop_front(),
4688 True->getName() + ".sroa.gep", NW);
4689
4690 Value *NFalse =
4691 IRB.CreateGEP(Ty, FalseOps[0], ArrayRef(FalseOps).drop_front(),
4692 False->getName() + ".sroa.gep", NW);
4693
4694 Value *NSel = MDFrom
4695 ? IRB.CreateSelect(Cond, NTrue, NFalse,
4696 Sel->getName() + ".sroa.sel", MDFrom)
4697 : IRB.CreateSelectWithUnknownProfile(
4698 Cond, NTrue, NFalse, DEBUG_TYPE,
4699 Sel->getName() + ".sroa.sel");
4700 Visited.erase(&GEPI);
4701 GEPI.replaceAllUsesWith(NSel);
4702 GEPI.eraseFromParent();
4703 Instruction *NSelI = cast<Instruction>(NSel);
4704 Visited.insert(NSelI);
4705 enqueueUsers(*NSelI);
4706
4707 LLVM_DEBUG(dbgs() << " to: " << *NTrue << "\n";
4708 dbgs() << " " << *NFalse << "\n";
4709 dbgs() << " " << *NSel << "\n";);
4710
4711 return true;
4712 }
4713
4714 // Unfold gep (phi ptr1, ptr2), idx
4715 // => phi ((gep ptr1, idx), (gep ptr2, idx))
4716 // and gep ptr, (phi idx1, idx2)
4717 // => phi ((gep ptr, idx1), (gep ptr, idx2))
4718 bool unfoldGEPPhi(GetElementPtrInst &GEPI) {
4719 // To prevent infinitely expanding recursive phis, bail if the GEP pointer
4720 // operand (looking through the phi if it is the phi we want to unfold) is
4721 // an instruction besides a static alloca.
4722 PHINode *Phi = dyn_cast<PHINode>(GEPI.getPointerOperand());
4723 auto IsInvalidPointerOperand = [](Value *V) {
4724 if (!isa<Instruction>(V))
4725 return false;
4726 if (auto *AI = dyn_cast<AllocaInst>(V))
4727 return !AI->isStaticAlloca();
4728 return true;
4729 };
4730 if (Phi) {
4731 if (any_of(Phi->operands(), IsInvalidPointerOperand))
4732 return false;
4733 } else {
4734 if (IsInvalidPointerOperand(GEPI.getPointerOperand()))
4735 return false;
4736 }
4737 // Check whether the GEP has exactly one phi operand (including the pointer
4738 // operand) and all indices will become constant after the transform.
4739 for (Value *Op : GEPI.indices()) {
4740 if (auto *SI = dyn_cast<PHINode>(Op)) {
4741 if (Phi)
4742 return false;
4743
4744 Phi = SI;
4745 if (!all_of(Phi->incoming_values(),
4746 [](Value *V) { return isa<ConstantInt>(V); }))
4747 return false;
4748 continue;
4749 }
4750
4751 if (!isa<ConstantInt>(Op))
4752 return false;
4753 }
4754
4755 if (!Phi)
4756 return false;
4757
4758 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):\n";
4759 dbgs() << " original: " << *Phi << "\n";
4760 dbgs() << " " << GEPI << "\n";);
4761
4762 auto GetNewOps = [&](Value *PhiOp) {
4763 SmallVector<Value *> NewOps;
4764 for (Value *Op : GEPI.operands())
4765 if (Op == Phi)
4766 NewOps.push_back(PhiOp);
4767 else
4768 NewOps.push_back(Op);
4769 return NewOps;
4770 };
4771
4772 IRB.SetInsertPoint(Phi);
4773 PHINode *NewPhi = IRB.CreatePHI(GEPI.getType(), Phi->getNumIncomingValues(),
4774 Phi->getName() + ".sroa.phi");
4775
4776 Type *SourceTy = GEPI.getSourceElementType();
4777 // We only handle arguments, constants, and static allocas here, so we can
4778 // insert GEPs at the end of the entry block.
4779 IRB.SetInsertPoint(GEPI.getFunction()->getEntryBlock().getTerminator());
4780 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
4781 Value *Op = Phi->getIncomingValue(I);
4782 BasicBlock *BB = Phi->getIncomingBlock(I);
4783 Value *NewGEP;
4784 if (int NI = NewPhi->getBasicBlockIndex(BB); NI >= 0) {
4785 NewGEP = NewPhi->getIncomingValue(NI);
4786 } else {
4787 SmallVector<Value *> NewOps = GetNewOps(Op);
4788 NewGEP =
4789 IRB.CreateGEP(SourceTy, NewOps[0], ArrayRef(NewOps).drop_front(),
4790 Phi->getName() + ".sroa.gep", GEPI.getNoWrapFlags());
4791 }
4792 NewPhi->addIncoming(NewGEP, BB);
4793 }
4794
4795 Visited.erase(&GEPI);
4796 GEPI.replaceAllUsesWith(NewPhi);
4797 GEPI.eraseFromParent();
4798 Visited.insert(NewPhi);
4799 enqueueUsers(*NewPhi);
4800
4801 LLVM_DEBUG(dbgs() << " to: ";
4802 for (Value *In
4803 : NewPhi->incoming_values()) dbgs()
4804 << "\n " << *In;
4805 dbgs() << "\n " << *NewPhi << '\n');
4806
4807 return true;
4808 }
4809
4810 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
4811 if (unfoldGEPSelect(GEPI))
4812 return true;
4813
4814 if (unfoldGEPPhi(GEPI))
4815 return true;
4816
4817 enqueueUsers(GEPI);
4818 return false;
4819 }
4820
4821 bool visitPHINode(PHINode &PN) {
4822 enqueueUsers(PN);
4823 return false;
4824 }
4825
4826 bool visitSelectInst(SelectInst &SI) {
4827 enqueueUsers(SI);
4828 return false;
4829 }
4830};
4831
4832} // end anonymous namespace
4833
4834/// Strip aggregate type wrapping.
4835///
4836/// This removes no-op aggregate types wrapping an underlying type. It will
4837/// strip as many layers of types as it can without changing either the type
4838/// size or the allocated size.
4840 if (Ty->isSingleValueType())
4841 return Ty;
4842
4843 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedValue();
4844 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedValue();
4845
4846 Type *InnerTy;
4847 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
4848 InnerTy = ArrTy->getElementType();
4849 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
4850 const StructLayout *SL = DL.getStructLayout(STy);
4851 unsigned Index = SL->getElementContainingOffset(0);
4852 InnerTy = STy->getElementType(Index);
4853 } else {
4854 return Ty;
4855 }
4856
4857 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedValue() ||
4858 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedValue())
4859 return Ty;
4860
4861 return stripAggregateTypeWrapping(DL, InnerTy);
4862}
4863
4864/// Try to find a partition of the aggregate type passed in for a given
4865/// offset and size.
4866///
4867/// This recurses through the aggregate type and tries to compute a subtype
4868/// based on the offset and size. When the offset and size span a sub-section
4869/// of an array, it will even compute a new array type for that sub-section,
4870/// and the same for structs.
4871///
4872/// Note that this routine is very strict and tries to find a partition of the
4873/// type which produces the *exact* right offset and size. It is not forgiving
4874/// when the size or offset cause either end of type-based partition to be off.
4875/// Also, this is a best-effort routine. It is reasonable to give up and not
4876/// return a type if necessary.
4878 uint64_t Size) {
4879 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedValue() == Size)
4880 return stripAggregateTypeWrapping(DL, Ty);
4881 if (Offset > DL.getTypeAllocSize(Ty).getFixedValue() ||
4882 (DL.getTypeAllocSize(Ty).getFixedValue() - Offset) < Size)
4883 return nullptr;
4884
4885 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
4886 Type *ElementTy;
4887 uint64_t TyNumElements;
4888 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
4889 ElementTy = AT->getElementType();
4890 TyNumElements = AT->getNumElements();
4891 } else {
4892 // FIXME: This isn't right for vectors with non-byte-sized or
4893 // non-power-of-two sized elements.
4894 auto *VT = cast<FixedVectorType>(Ty);
4895 ElementTy = VT->getElementType();
4896 TyNumElements = VT->getNumElements();
4897 }
4898 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4899 uint64_t NumSkippedElements = Offset / ElementSize;
4900 if (NumSkippedElements >= TyNumElements)
4901 return nullptr;
4902 Offset -= NumSkippedElements * ElementSize;
4903
4904 // First check if we need to recurse.
4905 if (Offset > 0 || Size < ElementSize) {
4906 // Bail if the partition ends in a different array element.
4907 if ((Offset + Size) > ElementSize)
4908 return nullptr;
4909 // Recurse through the element type trying to peel off offset bytes.
4910 return getTypePartition(DL, ElementTy, Offset, Size);
4911 }
4912 assert(Offset == 0);
4913
4914 if (Size == ElementSize)
4915 return stripAggregateTypeWrapping(DL, ElementTy);
4916 assert(Size > ElementSize);
4917 uint64_t NumElements = Size / ElementSize;
4918 if (NumElements * ElementSize != Size)
4919 return nullptr;
4920 return ArrayType::get(ElementTy, NumElements);
4921 }
4922
4924 if (!STy)
4925 return nullptr;
4926
4927 const StructLayout *SL = DL.getStructLayout(STy);
4928
4929 if (SL->getSizeInBits().isScalable())
4930 return nullptr;
4931
4932 if (Offset >= SL->getSizeInBytes())
4933 return nullptr;
4934 uint64_t EndOffset = Offset + Size;
4935 if (EndOffset > SL->getSizeInBytes())
4936 return nullptr;
4937
4938 unsigned Index = SL->getElementContainingOffset(Offset);
4939 Offset -= SL->getElementOffset(Index);
4940
4941 Type *ElementTy = STy->getElementType(Index);
4942 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedValue();
4943 if (Offset >= ElementSize)
4944 return nullptr; // The offset points into alignment padding.
4945
4946 // See if any partition must be contained by the element.
4947 if (Offset > 0 || Size < ElementSize) {
4948 if ((Offset + Size) > ElementSize)
4949 return nullptr;
4950 return getTypePartition(DL, ElementTy, Offset, Size);
4951 }
4952 assert(Offset == 0);
4953
4954 if (Size == ElementSize)
4955 return stripAggregateTypeWrapping(DL, ElementTy);
4956
4957 StructType::element_iterator EI = STy->element_begin() + Index,
4958 EE = STy->element_end();
4959 if (EndOffset < SL->getSizeInBytes()) {
4960 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
4961 if (Index == EndIndex)
4962 return nullptr; // Within a single element and its padding.
4963
4964 // Don't try to form "natural" types if the elements don't line up with the
4965 // expected size.
4966 // FIXME: We could potentially recurse down through the last element in the
4967 // sub-struct to find a natural end point.
4968 if (SL->getElementOffset(EndIndex) != EndOffset)
4969 return nullptr;
4970
4971 assert(Index < EndIndex);
4972 EE = STy->element_begin() + EndIndex;
4973 }
4974
4975 // Try to build up a sub-structure.
4976 StructType *SubTy =
4977 StructType::get(STy->getContext(), ArrayRef(EI, EE), STy->isPacked());
4978 const StructLayout *SubSL = DL.getStructLayout(SubTy);
4979 if (Size != SubSL->getSizeInBytes())
4980 return nullptr; // The sub-struct doesn't have quite the size needed.
4981
4982 return SubTy;
4983}
4984
4985/// This is a helper class that's used by presplitLoadsAndStores to split a
4986/// slice into smaller slices, including splitting the corresponding load/store
4987/// instruction.
4989 IRBuilderTy &IRB;
4990 const DataLayout &DL;
4991
4992 /// The split points that the slice is being split at. These are byte offsets
4993 /// within the slice, and are used to form the start/end offsets of the slices
4994 /// that we generate, plus the implicit offsets from the start and end of the
4995 /// slice that's being split.
4996 const std::vector<uint64_t> &Splits;
4997
4998 /// The size of the slice that's being split.
4999 unsigned SliceSize;
5000
5001public:
5002 SliceSplitter(IRBuilderTy &IRB, const DataLayout &DL,
5003 std::vector<uint64_t> &Splits, unsigned SliceSize)
5004 : IRB(IRB), DL(DL), Splits(Splits), SliceSize(SliceSize) {}
5005
5006 /// An iterator which iterates over the sub-slices that we want to split the
5007 /// slice into.
5009 : public iterator_facade_base<Iterator, std::forward_iterator_tag,
5010 const Iterator> {
5012 unsigned Idx;
5013 Iterator(SliceSplitter &SS, bool IsEnd) : SS(SS) {
5014 Idx = IsEnd ? SS.Splits.size() + 1 : 0;
5015 }
5016 bool operator==(const Iterator &Other) const { return Idx == Other.Idx; }
5017 uint64_t getOffset() const { return Idx == 0 ? 0 : SS.Splits[Idx - 1]; }
5018 uint64_t getSize() const {
5019 uint64_t NextOffset =
5020 Idx < SS.Splits.size() ? SS.Splits[Idx] : SS.SliceSize;
5021 return NextOffset - getOffset();
5022 }
5024 ++Idx;
5025 return *this;
5026 }
5027 const Iterator &operator*() const { return *this; }
5028 };
5029
5030 Iterator begin() { return Iterator(*this, false); }
5031
5032 Iterator end() { return Iterator(*this, true); }
5033
5034 LoadInst *createLoad(Value *BasePtr, Iterator &It, Instruction *SplitI) {
5035 Type *PartTy = Type::getIntNTy(SplitI->getContext(), It.getSize() * 8);
5036 Type *PartPtrTy = BasePtr->getType();
5037 unsigned AS = getLoadStoreAddressSpace(SplitI);
5038 LoadInst *PLoad = IRB.CreateAlignedLoad(
5039 PartTy,
5040 getAdjustedPtr(IRB, DL, BasePtr,
5041 APInt(DL.getIndexSizeInBits(AS), It.getOffset()),
5042 PartPtrTy, BasePtr->getName() + "."),
5043 getAdjustedAlignment(SplitI, It.getOffset()),
5044 /*IsVolatile*/ false, SplitI->getName());
5045 PLoad->copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5046 LLVMContext::MD_access_group});
5047 return PLoad;
5048 }
5049
5050 StoreInst *createStore(Value *StoreVal, Value *BasePtr, Iterator &It,
5051 Instruction *SplitI) {
5052 Type *PartPtrTy = BasePtr->getType();
5053 unsigned AS = getLoadStoreAddressSpace(SplitI);
5054 StoreInst *PStore = IRB.CreateAlignedStore(
5055 StoreVal,
5056 getAdjustedPtr(IRB, DL, BasePtr,
5057 APInt(DL.getIndexSizeInBits(AS), It.getOffset()),
5058 PartPtrTy, BasePtr->getName() + "."),
5059 getAdjustedAlignment(SplitI, It.getOffset()),
5060 /*IsVolatile*/ false);
5061 PStore->copyMetadata(*SplitI, {LLVMContext::MD_mem_parallel_loop_access,
5062 LLVMContext::MD_access_group,
5063 LLVMContext::MD_DIAssignID});
5064 AAMDNodes AATags = SplitI->getAAMetadata();
5065 if (AATags)
5066 PStore->setAAMetadata(
5067 AATags.adjustForAccess(It.getOffset(), StoreVal->getType(), DL));
5068
5069 return PStore;
5070 }
5071
5072 Slice createSlice(Instruction *I, uint64_t BaseOffset, Iterator &It) {
5073 unsigned PtrIdx = 0;
5074 if (auto *LI = dyn_cast<LoadInst>(I))
5075 PtrIdx = LI->getPointerOperandIndex();
5076 else if (auto *SI = dyn_cast<StoreInst>(I))
5077 PtrIdx = SI->getPointerOperandIndex();
5078 else
5079 llvm_unreachable("Slice must be for a load or store");
5080 // BaseOffset is the offset of the original slice within the alloca, so the
5081 // start and end offsets of this slice are offset from that.
5082 Slice S(BaseOffset + It.getOffset(),
5083 BaseOffset + It.getOffset() + It.getSize(),
5084 &I->getOperandUse(PtrIdx), /*IsSplittable*/ false);
5085 LLVM_DEBUG(dbgs() << " new slice [" << S.beginOffset() << ", "
5086 << S.endOffset() << "): " << *I << "\n");
5087 return S;
5088 }
5089};
5090
5091/// Try to find a slice in the map that partially overlaps with S, i.e. some but
5092/// not all of its range is contained within the range of S, and which forms a
5093/// load/store pair with S (i.e. the two slices are used to perform a
5094/// memmove-like copy). SliceMap is expected to contain the slices for a single
5095/// Partition.
5096static Slice *findOverlappingCopySlice(Slice &S,
5097 InstructionSliceMap &SliceMap) {
5098 // Single byte slices can't partially overlap anything
5099 if (S.endOffset() - S.beginOffset() == 1)
5100 return nullptr;
5101 // The source/destination of this slice needs to be a memory instruction
5102 // whose slice overlaps this one.
5103 Instruction *I = cast<Instruction>(S.getUse()->getUser());
5104 Instruction *J = nullptr;
5105 if (auto *LI = dyn_cast<LoadInst>(I)) {
5106 if (!LI->hasOneUser())
5107 return nullptr;
5108 J = cast<Instruction>(*LI->user_begin());
5109 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
5110 J = dyn_cast<Instruction>(SI->getValueOperand());
5111 if (!J || !J->hasOneUser())
5112 return nullptr;
5113 } else {
5114 return nullptr;
5115 }
5116 // Check if there's a slice that corresponds to J that overlaps this slice
5117 for (Slice *JS : SliceMap[J]) {
5118 if (S.beginOffset() > JS->beginOffset() &&
5119 S.beginOffset() < JS->endOffset())
5120 return JS;
5121 if (JS->beginOffset() > S.beginOffset() &&
5122 JS->beginOffset() < S.endOffset())
5123 return JS;
5124 }
5125 return nullptr;
5126}
5127
5128/// Pre-split loads and stores to simplify rewriting.
5129///
5130/// We want to break up the splittable load+store pairs as much as
5131/// possible. This is important to do as a preprocessing step, as once we
5132/// start rewriting the accesses to partitions of the alloca we lose the
5133/// necessary information to correctly split apart paired loads and stores
5134/// which both point into this alloca. The case to consider is something like
5135/// the following:
5136///
5137/// %a = alloca [12 x i8]
5138/// %gep1 = getelementptr i8, ptr %a, i32 0
5139/// %gep2 = getelementptr i8, ptr %a, i32 4
5140/// %gep3 = getelementptr i8, ptr %a, i32 8
5141/// store float 0.0, ptr %gep1
5142/// store float 1.0, ptr %gep2
5143/// %v = load i64, ptr %gep1
5144/// store i64 %v, ptr %gep2
5145/// %f1 = load float, ptr %gep2
5146/// %f2 = load float, ptr %gep3
5147///
5148/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
5149/// promote everything so we recover the 2 SSA values that should have been
5150/// there all along.
5151///
5152/// \returns true if any changes are made.
5153bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
5154 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
5155
5156 // Track the loads and stores which are candidates for pre-splitting here, in
5157 // the order they first appear during the partition scan. These give stable
5158 // iteration order and a basis for tracking which loads and stores we
5159 // actually split.
5162
5163 // We need to accumulate the splits required of each load or store where we
5164 // can find them via a direct lookup. This is important to cross-check loads
5165 // and stores against each other. We also track the slice so that we can kill
5166 // all the slices that end up split.
5167 struct SplitOffsets {
5168 Slice *S;
5169 std::vector<uint64_t> Splits;
5170 };
5171 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
5172
5173 // Track loads out of this alloca which cannot, for any reason, be pre-split.
5174 // This is important as we also cannot pre-split stores of those loads!
5175 // FIXME: This is all pretty gross. It means that we can be more aggressive
5176 // in pre-splitting when the load feeding the store happens to come from
5177 // a separate alloca. Put another way, the effectiveness of SROA would be
5178 // decreased by a frontend which just concatenated all of its local allocas
5179 // into one big flat alloca. But defeating such patterns is exactly the job
5180 // SROA is tasked with! Sadly, to not have this discrepancy we would have
5181 // change store pre-splitting to actually force pre-splitting of the load
5182 // that feeds it *and all stores*. That makes pre-splitting much harder, but
5183 // maybe it would make it more principled?
5184 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
5185
5186 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
5187 for (auto &P : AS.partitions()) {
5188 InstructionSliceMap SliceMap;
5189 for (Slice &S : P) {
5190 SliceMap[cast<Instruction>(S.getUse()->getUser())].insert(&S);
5191 }
5192 for (Slice &S : P) {
5193 Instruction *I = cast<Instruction>(S.getUse()->getUser());
5194 bool ExtendsPastPartitionEnd = S.endOffset() > P.endOffset();
5195 Slice *CopyOverlap = findOverlappingCopySlice(S, SliceMap);
5196 if (!S.isSplittable() || (!ExtendsPastPartitionEnd && !CopyOverlap)) {
5197 // If this is a load we have to track that it can't participate in any
5198 // pre-splitting. If this is a store of a load we have to track that
5199 // that load also can't participate in any pre-splitting.
5200 if (auto *LI = dyn_cast<LoadInst>(I))
5201 UnsplittableLoads.insert(LI);
5202 else if (auto *SI = dyn_cast<StoreInst>(I))
5203 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
5204 UnsplittableLoads.insert(LI);
5205 continue;
5206 }
5207 assert(P.endOffset() > S.beginOffset() &&
5208 "Empty or backwards partition!");
5209
5210 // Determine if this is a pre-splittable slice.
5211 if (auto *LI = dyn_cast<LoadInst>(I)) {
5212 assert(!LI->isVolatile() && "Cannot split volatile loads!");
5213
5214 // The load must be used exclusively to store into other pointers for
5215 // us to be able to arbitrarily pre-split it. The stores must also be
5216 // simple to avoid changing semantics.
5217 auto IsLoadSimplyStored = [](LoadInst *LI) {
5218 for (User *LU : LI->users()) {
5219 auto *SI = dyn_cast<StoreInst>(LU);
5220 if (!SI || !SI->isSimple())
5221 return false;
5222 }
5223 return true;
5224 };
5225 if (!IsLoadSimplyStored(LI)) {
5226 UnsplittableLoads.insert(LI);
5227 continue;
5228 }
5229
5230 Loads.push_back(LI);
5231 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
5232 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
5233 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
5234 continue;
5235 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
5236 if (!StoredLoad || !StoredLoad->isSimple())
5237 continue;
5238 assert(!SI->isVolatile() && "Cannot split volatile stores!");
5239
5240 Stores.push_back(SI);
5241 } else {
5242 // Other uses cannot be pre-split.
5243 continue;
5244 }
5245
5246 // Record the initial split.
5247 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
5248 auto &Offsets = SplitOffsetsMap[I];
5249 assert(Offsets.Splits.empty() &&
5250 "Should not have splits the first time we see an instruction!");
5251 Offsets.S = &S;
5252 if (CopyOverlap) {
5253 // S is being moved to CopyOverlap, which overlaps with S, so we split S
5254 // into three parts:
5255 // * Initially outside the overlap and copied into the overlap.
5256 // * Either initially inside the overlap and remains inside it after
5257 // the copy, or initially outside and remains outside, depending on
5258 // if the overlap or non-overlap area is larger, and which will be
5259 // empty if they are equal.
5260 // * Initially inside the overlap and copied outside the overlap.
5261 // This should result in the first and last parts being promoted to
5262 // scalars. If the middle part is an overlapping copy then we repeat
5263 // this process until it isn't.
5264 uint64_t OverlapStart =
5265 std::max(S.beginOffset(), CopyOverlap->beginOffset());
5266 uint64_t OverlapEnd = std::min(S.endOffset(), CopyOverlap->endOffset());
5267 uint64_t OverlapSize = OverlapEnd - OverlapStart;
5268 uint64_t SliceSize = S.endOffset() - S.beginOffset();
5269 uint64_t NonOverlapSize = SliceSize - OverlapSize;
5270 if (OverlapSize < NonOverlapSize) {
5271 // When the overlap area is smaller the middle part is initially and
5272 // remains outside the overlap, so splitting once is enough. The size
5273 // of the first and last part both equal the overlap size, so the
5274 // split points are that amount from the start and end of the slice.
5275 Offsets.Splits.push_back(OverlapSize);
5276 Offsets.Splits.push_back(SliceSize - OverlapSize);
5277 } else if (OverlapSize > NonOverlapSize) {
5278 // When the overlap area is larger the middle part is initially and
5279 // remains inside the overlap, so we repeatedly split it.
5280 for (uint64_t Split = NonOverlapSize; Split <= SliceSize / 2;
5281 Split += NonOverlapSize) {
5282 Offsets.Splits.push_back(Split);
5283 if (Split != SliceSize - Split) {
5284 Offsets.Splits.push_back(SliceSize - Split);
5285 }
5286 }
5287 // Sort the splits as they need to be in ascending order.
5288 llvm::sort(Offsets.Splits);
5289 } else {
5290 // Here the overlap and non-overlap size are the same, so the middle
5291 // part is empty and the slice is split exactly in the center.
5292 Offsets.Splits.push_back(OverlapSize);
5293 }
5294 } else {
5295 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
5296 }
5297 }
5298 }
5299
5300 // We may have split loads where some of their stores are split stores. For
5301 // such loads and stores, we can only pre-split them if their splits exactly
5302 // match relative to their starting offset. We have to verify this prior to
5303 // any rewriting.
5304 llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
5305 // Lookup the load we are storing in our map of split
5306 // offsets.
5307 auto *LI = cast<LoadInst>(SI->getValueOperand());
5308 // If it was completely unsplittable, then we're done,
5309 // and this store can't be pre-split.
5310 if (UnsplittableLoads.count(LI))
5311 return true;
5312
5313 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
5314 if (LoadOffsetsI == SplitOffsetsMap.end())
5315 return false; // Unrelated loads are definitely safe.
5316 auto &LoadOffsets = LoadOffsetsI->second;
5317
5318 // Now lookup the store's offsets.
5319 auto &StoreOffsets = SplitOffsetsMap[SI];
5320
5321 // If the relative offsets of each split in the load and
5322 // store match exactly, then we can split them and we
5323 // don't need to remove them here.
5324 if (LoadOffsets.Splits == StoreOffsets.Splits)
5325 return false;
5326
5327 LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"
5328 << " " << *LI << "\n"
5329 << " " << *SI << "\n");
5330
5331 // We've found a store and load that we need to split
5332 // with mismatched relative splits. Just give up on them
5333 // and remove both instructions from our list of
5334 // candidates.
5335 UnsplittableLoads.insert(LI);
5336 return true;
5337 });
5338 // Now we have to go *back* through all the stores, because a later store may
5339 // have caused an earlier store's load to become unsplittable and if it is
5340 // unsplittable for the later store, then we can't rely on it being split in
5341 // the earlier store either.
5342 llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
5343 auto *LI = cast<LoadInst>(SI->getValueOperand());
5344 return UnsplittableLoads.count(LI);
5345 });
5346 // Once we've established all the loads that can't be split for some reason,
5347 // filter any that made it into our list out.
5348 llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
5349 return UnsplittableLoads.count(LI);
5350 });
5351
5352 // If no loads or stores are left, there is no pre-splitting to be done for
5353 // this alloca.
5354 if (Loads.empty() && Stores.empty())
5355 return false;
5356
5357 // From here on, we can't fail and will be building new accesses, so rig up
5358 // an IR builder.
5359 IRBuilderTy IRB(&AI);
5360
5361 // Collect the new slices which we will merge into the alloca slices.
5362 SmallVector<Slice, 4> NewSlices;
5363
5364 // Track any allocas we end up splitting loads and stores for so we iterate
5365 // on them.
5366 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
5367
5368 // At this point, we have collected all of the loads and stores we can
5369 // pre-split, and the specific splits needed for them. We actually do the
5370 // splitting in a specific order in order to handle when one of the loads in
5371 // the value operand to one of the stores.
5372 //
5373 // First, we rewrite all of the split loads, and just accumulate each split
5374 // load in a parallel structure. We also build the slices for them and append
5375 // them to the alloca slices.
5376 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
5377 std::vector<LoadInst *> SplitLoads;
5378 const DataLayout &DL = AI.getDataLayout();
5379 for (LoadInst *LI : Loads) {
5380 SplitLoads.clear();
5381
5382 auto &Offsets = SplitOffsetsMap[LI];
5383 unsigned SliceSize = Offsets.S->endOffset() - Offsets.S->beginOffset();
5384 assert(LI->getType()->getIntegerBitWidth() % 8 == 0 &&
5385 "Load must have type size equal to store size");
5386 assert(LI->getType()->getIntegerBitWidth() / 8 >= SliceSize &&
5387 "Load must be >= slice size");
5388
5389 uint64_t BaseOffset = Offsets.S->beginOffset();
5390 assert(BaseOffset + SliceSize > BaseOffset &&
5391 "Cannot represent alloca access size using 64-bit integers!");
5392
5394 IRB.SetInsertPoint(LI);
5395
5396 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
5397
5398 SliceSplitter Splitter(IRB, DL, Offsets.Splits, SliceSize);
5399 for (auto Part : Splitter) {
5400 LoadInst *PLoad = Splitter.createLoad(BasePtr, Part, LI);
5401
5402 // Append this load onto the list of split loads so we can find it later
5403 // to rewrite the stores.
5404 SplitLoads.push_back(PLoad);
5405
5406 // Now build a new slice for the alloca.
5407 NewSlices.push_back(Splitter.createSlice(PLoad, BaseOffset, Part));
5408 }
5409
5410 // Now that we have the split loads, do the slow walk over all uses of the
5411 // load and rewrite them as split stores, or save the split loads to use
5412 // below if the store is going to be split there anyways.
5413 bool DeferredStores = false;
5414 for (User *LU : LI->users()) {
5415 StoreInst *SI = cast<StoreInst>(LU);
5416 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
5417 DeferredStores = true;
5418 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
5419 << "\n");
5420 continue;
5421 }
5422
5423 Value *StoreBasePtr = SI->getPointerOperand();
5424 IRB.SetInsertPoint(SI);
5425
5426 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
5427
5428 for (auto Part : Splitter) {
5429 LoadInst *PLoad = SplitLoads[Part.Idx];
5430 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5431 (void)PStore;
5432 LLVM_DEBUG(dbgs() << " +" << Part.getOffset() << ":" << *PStore
5433 << "\n");
5434 }
5435
5436 // We want to immediately iterate on any allocas impacted by splitting
5437 // this store, and we have to track any promotable alloca (indicated by
5438 // a direct store) as needing to be resplit because it is no longer
5439 // promotable.
5440 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
5441 ResplitPromotableAllocas.insert(OtherAI);
5442 Worklist.insert(OtherAI);
5443 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
5444 StoreBasePtr->stripInBoundsOffsets())) {
5445 Worklist.insert(OtherAI);
5446 }
5447
5448 // Mark the original store as dead.
5449 DeadInsts.push_back(SI);
5450 }
5451
5452 // Save the split loads if there are deferred stores among the users.
5453 if (DeferredStores)
5454 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
5455
5456 // Mark the original load as dead and kill the original slice.
5457 DeadInsts.push_back(LI);
5458 Offsets.S->kill();
5459 }
5460
5461 // Second, we rewrite all of the split stores. At this point, we know that
5462 // all loads from this alloca have been split already. For stores of such
5463 // loads, we can simply look up the pre-existing split loads. For stores of
5464 // other loads, we split those loads first and then write split stores of
5465 // them.
5466 for (StoreInst *SI : Stores) {
5467 auto *LI = cast<LoadInst>(SI->getValueOperand());
5468 IntegerType *Ty = cast<IntegerType>(LI->getType());
5469 assert(Ty->getBitWidth() % 8 == 0);
5470 uint64_t StoreSize = Ty->getBitWidth() / 8;
5471 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
5472
5473 auto &Offsets = SplitOffsetsMap[SI];
5474 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
5475 "Slice size should always match load size exactly!");
5476 uint64_t BaseOffset = Offsets.S->beginOffset();
5477 assert(BaseOffset + StoreSize > BaseOffset &&
5478 "Cannot represent alloca access size using 64-bit integers!");
5479
5480 Value *LoadBasePtr = LI->getPointerOperand();
5481 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
5482
5483 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
5484
5485 // Check whether we have an already split load.
5486 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
5487 std::vector<LoadInst *> *SplitLoads = nullptr;
5488 if (SplitLoadsMapI != SplitLoadsMap.end()) {
5489 SplitLoads = &SplitLoadsMapI->second;
5490 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
5491 "Too few split loads for the number of splits in the store!");
5492 } else {
5493 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
5494 }
5495
5496 SliceSplitter Splitter(IRB, DL, Offsets.Splits, StoreSize);
5497 for (auto Part : Splitter) {
5498 // Either lookup a split load or create one.
5499 LoadInst *PLoad;
5500 if (SplitLoads) {
5501 PLoad = (*SplitLoads)[Part.Idx];
5502 } else {
5503 IRB.SetInsertPoint(LI);
5504 PLoad = Splitter.createLoad(LoadBasePtr, Part, LI);
5505 }
5506
5507 // And store this partition.
5508 IRB.SetInsertPoint(SI);
5509 StoreInst *PStore = Splitter.createStore(PLoad, StoreBasePtr, Part, SI);
5510
5511 // Now build a new slice for the alloca.
5512 NewSlices.push_back(Splitter.createSlice(PStore, BaseOffset, Part));
5513 if (!SplitLoads) {
5514 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
5515 }
5516 }
5517
5518 // We want to immediately iterate on any allocas impacted by splitting
5519 // this load, which is only relevant if it isn't a load of this alloca and
5520 // thus we didn't already split the loads above. We also have to keep track
5521 // of any promotable allocas we split loads on as they can no longer be
5522 // promoted.
5523 if (!SplitLoads) {
5524 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
5525 assert(OtherAI != &AI && "We can't re-split our own alloca!");
5526 ResplitPromotableAllocas.insert(OtherAI);
5527 Worklist.insert(OtherAI);
5528 } else if (AllocaInst *StrippedAI = dyn_cast<AllocaInst>(
5529 LoadBasePtr->stripInBoundsOffsets())) {
5530 assert(StrippedAI != &AI && "We can't re-split our own alloca!");
5531 Worklist.insert(StrippedAI);
5532 }
5533 }
5534
5535 // Mark the original store as dead now that we've split it up and kill its
5536 // slice. Note that we leave the original load in place unless this store
5537 // was its only use. It may in turn be split up if it is an alloca load
5538 // for some other alloca, but it may be a normal load. This may introduce
5539 // redundant loads, but where those can be merged the rest of the optimizer
5540 // should handle the merging, and this uncovers SSA splits which is more
5541 // important. In practice, the original loads will almost always be fully
5542 // split and removed eventually, and the splits will be merged by any
5543 // trivial CSE, including instcombine.
5544 if (LI->hasOneUse()) {
5545 assert(*LI->user_begin() == SI && "Single use isn't this store!");
5546 DeadInsts.push_back(LI);
5547 }
5548 DeadInsts.push_back(SI);
5549 Offsets.S->kill();
5550 }
5551
5552 // Remove the killed slices that have ben pre-split.
5553 llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
5554
5555 // Insert our new slices. This will sort and merge them into the sorted
5556 // sequence.
5557 AS.insert(NewSlices);
5558
5559 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
5560#ifndef NDEBUG
5561 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
5562 LLVM_DEBUG(AS.print(dbgs(), I, " "));
5563#endif
5564
5565 // Finally, don't try to promote any allocas that new require re-splitting.
5566 // They have already been added to the worklist above.
5567 PromotableAllocas.set_subtract(ResplitPromotableAllocas);
5568
5569 return true;
5570}
5571
5572/// Try to canonicalize a homogeneous struct partition to a vector type.
5573///
5574/// We can do this if all the elements of the struct are the same and the
5575/// corresponding vector has the same byte-level layout. This can sometimes
5576/// eliminate allocas because structs cannot get promoted to LLVM values, but
5577/// vectors can.
5578///
5579/// We only apply this transformation when all users of the partition are memory
5580/// intrinsics. Otherwise, if there is a load or store of some other type to the
5581/// partition, SROA would select that type.
5582///
5583/// Applying this transformation too early may hinder memcpyopt, which may
5584/// generate better code when eliminating allocas. For example, see
5585/// `struct-to-vector-fp-store-only-tail.ll`, which demonstrates that applying
5586/// this before memcpyopt can initialize previously uninitialized memory when
5587/// the alloca gets promoted to an SSA value. For another example, see
5588/// `struct-to-vector-before-memcpyopt.ll`, which demonstrates that applying
5589/// this before memcpyopt can result in promoting an alloca so that we load a
5590/// temporary value instead of copying the temporary value into memory, whereas
5591/// memcpyopt eliminates the temporary altogether.
5592///
5593/// As such, we only apply this transformation after memcpyopt has run. We gate
5594/// this transformation by the "AggregateToVector" pass option.
5596 Partition &P,
5597 const DataLayout &DL) {
5598 unsigned NumElts = STy->getNumElements();
5599
5600 Type *EltTy = STy->getElementType(0);
5601 if (!llvm::all_equal(STy->elements()))
5602 return nullptr;
5603
5604 bool IsIntegralPointerTy =
5605 EltTy->isPointerTy() && !DL.isNonIntegralPointerType(EltTy);
5606 if (!EltTy->isIntegerTy() && !EltTy->isFloatingPointTy() &&
5607 !IsIntegralPointerTy)
5608 return nullptr;
5609
5610 // Ensure the struct is tightly packed so that the bit-layout is the same as
5611 // the corresponding vector. For example, this prevents a miscompile for
5612 // { i5, i5 }, which has padding after each i5 field, whereas <i5, i5> has
5613 // tightly packed elements and trailing padding.
5614 if (DL.getTypeSizeInBits(EltTy) != DL.getTypeAllocSizeInBits(EltTy))
5615 return nullptr;
5616
5617 auto *VTy = FixedVectorType::get(EltTy, NumElts);
5618 TypeSize StructSize = DL.getStructLayout(STy)->getSizeInBytes();
5619 TypeSize VectorSize = DL.getTypeStoreSize(VTy);
5620 // After ruling out per-element padding, make sure a vector load/store
5621 // covers the same number of bytes as the struct layout.
5622 if (StructSize != VectorSize)
5623 return nullptr;
5624
5625 auto IsIgnorableOrMemIntrinsicSlice = [](const Slice &S) {
5626 if (S.isDead())
5627 return true;
5628 auto *U = S.getUse();
5629 return !U || isa<LifetimeIntrinsic, MemIntrinsic>(U->getUser());
5630 };
5631
5632 for (const Slice &S : P)
5633 if (!IsIgnorableOrMemIntrinsicSlice(S))
5634 return nullptr;
5635
5636 for (const Slice *S : P.splitSliceTails())
5637 if (!IsIgnorableOrMemIntrinsicSlice(*S))
5638 return nullptr;
5639
5640 return VTy;
5641}
5642
5643/// Select a partition type for an alloca partition.
5644///
5645/// Try to compute a friendly type for this partition of the alloca. This
5646/// won't always succeed, in which case we fall back to a legal integer type
5647/// or an i8 array of an appropriate size.
5648///
5649/// \returns A tuple with the following elements:
5650/// - PartitionType: The computed type for this partition.
5651/// - IsIntegerWideningViable: True if integer widening promotion is used.
5652/// - VectorType: The vector type if vector promotion is used, otherwise
5653/// nullptr.
5654static std::tuple<Type *, bool, VectorType *>
5656 LLVMContext &C, bool AggregateToVector) {
5657 auto LogSelection = [&](StringRef Path, Type *SelectedTy,
5658 VectorType *SelectedVecTy, bool SelectedIntWidening) {
5659 LLVM_DEBUG({
5660 dbgs() << "selectPartitionType path=" << Path
5661 << " func=" << AI.getFunction()->getName() << " alloca=";
5662 if (AI.hasName())
5663 dbgs() << AI.getName();
5664 else
5665 dbgs() << "<unnamed>";
5666 dbgs() << " partition=[" << P.beginOffset() << "," << P.endOffset()
5667 << ") size=" << P.size();
5668 if (std::optional<TypeSize> AllocSize = AI.getAllocationSize(DL))
5669 dbgs() << " alloc-size=" << AllocSize->getKnownMinValue();
5670 if (SelectedTy)
5671 dbgs() << " chosen=" << *SelectedTy;
5672 if (SelectedVecTy)
5673 dbgs() << " vec=" << *SelectedVecTy;
5674 dbgs() << " intwiden=" << SelectedIntWidening << "\n";
5675 });
5676 };
5677 // First check if the partition is viable for vector promotion.
5678 //
5679 // We prefer vector promotion over integer widening promotion when:
5680 // - The vector element type is a floating-point type.
5681 // - All the loads/stores to the alloca are vector loads/stores to the
5682 // entire alloca or load/store a single element of the vector.
5683 //
5684 // Otherwise when there is an integer vector with mixed type loads/stores we
5685 // prefer integer widening promotion because it's more likely the user is
5686 // doing bitwise arithmetic and we generate better code.
5687 VectorType *VecTy =
5689 // If the vector element type is a floating-point type, we prefer vector
5690 // promotion. If the vector has one element, let the below code select
5691 // whether we promote with the vector or scalar.
5692 if (VecTy && VecTy->getElementType()->isFloatingPointTy() &&
5693 VecTy->getElementCount().getFixedValue() > 1) {
5694 LogSelection("direct-fp-vecty", VecTy, VecTy, false);
5695 return {VecTy, false, VecTy};
5696 }
5697
5698 // Check if there is a common type that all slices of the partition use that
5699 // spans the partition.
5700 auto [CommonUseTy, LargestIntTy] =
5701 findCommonType(P.begin(), P.end(), P.endOffset());
5702 if (CommonUseTy) {
5703 TypeSize CommonUseSize = DL.getTypeAllocSize(CommonUseTy);
5704 if (CommonUseSize.isFixed() && CommonUseSize.getFixedValue() >= P.size()) {
5705 // We prefer vector promotion here because if vector promotion is viable
5706 // and there is a common type used, then it implies the second listed
5707 // condition for preferring vector promotion is true.
5708 if (VecTy) {
5709 LogSelection("common-type-vecty", VecTy, VecTy, false);
5710 return {VecTy, false, VecTy};
5711 }
5712 bool IntWiden = isIntegerWideningViable(P, CommonUseTy, DL);
5713 LogSelection("common-type", CommonUseTy, nullptr, IntWiden);
5714 return {CommonUseTy, IntWiden, nullptr};
5715 }
5716 }
5717
5718 // Can we find an appropriate subtype in the original allocated
5719 // type?
5720 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
5721 P.beginOffset(), P.size())) {
5722 // If the partition is an integer array that can be spanned by a legal
5723 // integer type, prefer to represent it as a legal integer type because
5724 // it's more likely to be promotable.
5725 if (TypePartitionTy->isArrayTy() &&
5726 TypePartitionTy->getArrayElementType()->isIntegerTy() &&
5727 DL.isLegalInteger(P.size() * 8))
5728 TypePartitionTy = Type::getIntNTy(C, P.size() * 8);
5729 // There was no common type used, so we prefer integer widening promotion.
5730 if (isIntegerWideningViable(P, TypePartitionTy, DL)) {
5731 LogSelection("type-partition-int-widen", TypePartitionTy, nullptr, true);
5732 return {TypePartitionTy, true, nullptr};
5733 }
5734 if (VecTy) {
5735 LogSelection("type-partition-vecty", VecTy, VecTy, false);
5736 return {VecTy, false, VecTy};
5737 }
5738 // If we couldn't promote with TypePartitionTy, try with the largest
5739 // integer type used.
5740 if (LargestIntTy &&
5741 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size() &&
5742 isIntegerWideningViable(P, LargestIntTy, DL)) {
5743 LogSelection("largest-int-int-widen", LargestIntTy, nullptr, true);
5744 return {LargestIntTy, true, nullptr};
5745 }
5746
5747 // Try homogeneous struct to vector canonicalization when requested. Running
5748 // this too early can hide memcpy chains from MemCpyOpt.
5749 if (AggregateToVector) {
5750 if (auto *STy = dyn_cast<StructType>(TypePartitionTy)) {
5751 if (auto *VTy = tryCanonicalizeStructToVector(STy, P, DL)) {
5752 LogSelection("struct-fallback-vecty", VTy, nullptr, false);
5753 return {VTy, false, nullptr};
5754 }
5755 }
5756 }
5757
5758 // Fallback to TypePartitionTy and we probably won't promote.
5759 LogSelection("type-partition-fallback", TypePartitionTy, nullptr, false);
5760 return {TypePartitionTy, false, nullptr};
5761 }
5762
5763 // Select the largest integer type used if it spans the partition.
5764 if (LargestIntTy &&
5765 DL.getTypeAllocSize(LargestIntTy).getFixedValue() >= P.size()) {
5766 LogSelection("largest-int-fallback", LargestIntTy, nullptr, false);
5767 return {LargestIntTy, false, nullptr};
5768 }
5769
5770 // Select a legal integer type if it spans the partition.
5771 if (DL.isLegalInteger(P.size() * 8)) {
5772 Type *IntTy = Type::getIntNTy(C, P.size() * 8);
5773 LogSelection("legal-int-fallback", IntTy, nullptr, false);
5774 return {IntTy, false, nullptr};
5775 }
5776
5777 // Fallback to an i8 array.
5778 Type *ArrayTy = ArrayType::get(Type::getInt8Ty(C), P.size());
5779 LogSelection("byte-array-fallback", ArrayTy, nullptr, false);
5780 return {ArrayTy, false, nullptr};
5781}
5782
5783/// Rewrite an alloca partition's users.
5784///
5785/// This routine drives both of the rewriting goals of the SROA pass. It tries
5786/// to rewrite uses of an alloca partition to be conducive for SSA value
5787/// promotion. If the partition needs a new, more refined alloca, this will
5788/// build that new alloca, preserving as much type information as possible, and
5789/// rewrite the uses of the old alloca to point at the new one and have the
5790/// appropriate new offsets. It also evaluates how successful the rewrite was
5791/// at enabling promotion and if it was successful queues the alloca to be
5792/// promoted.
5793std::pair<AllocaInst *, uint64_t>
5794SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, Partition &P) {
5795 const DataLayout &DL = AI.getDataLayout();
5796 // Select the type for the new alloca that spans the partition.
5797 auto [PartitionTy, IsIntegerWideningViable, VecTy] =
5798 selectPartitionType(P, DL, AI, *C, AggregateToVector);
5799
5800 // Check for the case where we're going to rewrite to a new alloca of the
5801 // exact same type as the original, and with the same access offsets. In that
5802 // case, re-use the existing alloca, but still run through the rewriter to
5803 // perform phi and select speculation.
5804 // P.beginOffset() can be non-zero even with the same type in a case with
5805 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
5806 AllocaInst *NewAI;
5807 if (PartitionTy == AI.getAllocatedType() && P.beginOffset() == 0) {
5808 NewAI = &AI;
5809 // FIXME: We should be able to bail at this point with "nothing changed".
5810 // FIXME: We might want to defer PHI speculation until after here.
5811 // FIXME: return nullptr;
5812 } else {
5813 // Make sure the alignment is compatible with P.beginOffset().
5814 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
5815 NewAI =
5816 new AllocaInst(PartitionTy, AI.getAddressSpace(), nullptr, Alignment,
5817 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()),
5818 AI.getIterator());
5819 tryEnforceAlignment(NewAI, DL.getPrefTypeAlign(PartitionTy), DL);
5820 // Copy the old AI debug location over to the new one.
5821 NewAI->setDebugLoc(AI.getDebugLoc());
5822 ++NumNewAllocas;
5823 }
5824
5825 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " << "[" << P.beginOffset()
5826 << "," << P.endOffset() << ") to: " << *NewAI << "\n");
5827
5828 // Track the high watermark on the worklist as it is only relevant for
5829 // promoted allocas. We will reset it to this point if the alloca is not in
5830 // fact scheduled for promotion.
5831 unsigned PPWOldSize = PostPromotionWorklist.size();
5832 unsigned NumUses = 0;
5833 SmallSetVector<PHINode *, 8> PHIUsers;
5834 SmallSetVector<SelectInst *, 8> SelectUsers;
5835
5836 AllocaSliceRewriter Rewriter(
5837 DL, AS, *this, AI, *NewAI, PartitionTy, P.beginOffset(), P.endOffset(),
5838 IsIntegerWideningViable, VecTy, PHIUsers, SelectUsers);
5839 bool Promotable = true;
5840 // Check whether we can have tree-structured merge.
5841 if (auto DeletedValues = Rewriter.rewriteTreeStructuredMerge(P)) {
5842 NumUses += DeletedValues->size() + 1;
5843 for (Value *V : *DeletedValues)
5844 DeadInsts.push_back(V);
5845 } else {
5846 for (Slice *S : P.splitSliceTails()) {
5847 Promotable &= Rewriter.visit(S);
5848 ++NumUses;
5849 }
5850 for (Slice &S : P) {
5851 Promotable &= Rewriter.visit(&S);
5852 ++NumUses;
5853 }
5854 }
5855
5856 NumAllocaPartitionUses += NumUses;
5857 MaxUsesPerAllocaPartition.updateMax(NumUses);
5858
5859 // Now that we've processed all the slices in the new partition, check if any
5860 // PHIs or Selects would block promotion.
5861 SmallVector<PHINode *, 8> NewSpeculatablePHIs;
5862 SmallVector<PHINode *, 2> NewPHIsWithStoreToRewrite;
5863 for (PHINode *PHI : PHIUsers) {
5864 if (isSafePHIToSpeculate(*PHI)) {
5865 NewSpeculatablePHIs.push_back(PHI);
5866 continue;
5867 }
5868 if (getPHIStoreToRewrite(*PHI, PreserveCFG, DTU->getDomTree())) {
5869 NewPHIsWithStoreToRewrite.push_back(PHI);
5870 continue;
5871 }
5872
5873 Promotable = false;
5874 SelectUsers.clear();
5875 break;
5876 }
5877
5879 NewSelectsToRewrite;
5880 NewSelectsToRewrite.reserve(SelectUsers.size());
5881 for (SelectInst *Sel : SelectUsers) {
5882 std::optional<RewriteableMemOps> Ops =
5883 isSafeSelectToSpeculateOrPredicate(*Sel, PreserveCFG);
5884 if (!Ops) {
5885 Promotable = false;
5886 break;
5887 }
5888 NewSelectsToRewrite.emplace_back(std::make_pair(Sel, *Ops));
5889 }
5890
5891 if (Promotable) {
5892 for (Use *U : AS.getDeadUsesIfPromotable()) {
5893 auto *OldInst = dyn_cast<Instruction>(U->get());
5894 Value::dropDroppableUse(*U);
5895 if (OldInst)
5896 if (isInstructionTriviallyDead(OldInst))
5897 DeadInsts.push_back(OldInst);
5898 }
5899 if (NewSpeculatablePHIs.empty() && NewPHIsWithStoreToRewrite.empty() &&
5900 SelectUsers.empty()) {
5901 // Promote the alloca.
5902 PromotableAllocas.insert(NewAI);
5903 } else {
5904 // If we have either PHIs or Selects to rewrite, add them to those
5905 // worklists and re-queue the new alloca so that we promote it on the next
5906 // iteration.
5907 SpeculatablePHIs.insert_range(NewSpeculatablePHIs);
5908 PHIsWithStoreToRewrite.insert_range(NewPHIsWithStoreToRewrite);
5909 SelectsToRewrite.reserve(SelectsToRewrite.size() +
5910 NewSelectsToRewrite.size());
5911 for (auto &&KV : llvm::make_range(
5912 std::make_move_iterator(NewSelectsToRewrite.begin()),
5913 std::make_move_iterator(NewSelectsToRewrite.end())))
5914 SelectsToRewrite.insert(std::move(KV));
5915 Worklist.insert(NewAI);
5916 }
5917 } else {
5918 // Drop any post-promotion work items if promotion didn't happen.
5919 while (PostPromotionWorklist.size() > PPWOldSize)
5920 PostPromotionWorklist.pop_back();
5921
5922 // We couldn't promote and we didn't create a new partition, nothing
5923 // happened.
5924 if (NewAI == &AI)
5925 return {nullptr, 0};
5926
5927 // If we can't promote the alloca, iterate on it to check for new
5928 // refinements exposed by splitting the current alloca. Don't iterate on an
5929 // alloca which didn't actually change and didn't get promoted.
5930 Worklist.insert(NewAI);
5931 }
5932
5933 return {NewAI, DL.getTypeSizeInBits(PartitionTy).getFixedValue()};
5934}
5935
5936// There isn't a shared interface to get the "address" parts out of a
5937// dbg.declare and dbg.assign, so provide some wrappers.
5940 return DVR->isKillAddress();
5941 return DVR->isKillLocation();
5942}
5943
5946 return DVR->getAddressExpression();
5947 return DVR->getExpression();
5948}
5949
5950/// Create or replace an existing fragment in a DIExpression with \p Frag.
5951/// If the expression already contains a DW_OP_LLVM_extract_bits_[sz]ext
5952/// operation, add \p BitExtractOffset to the offset part.
5953///
5954/// Returns the new expression, or nullptr if this fails (see details below).
5955///
5956/// This function is similar to DIExpression::createFragmentExpression except
5957/// for 3 important distinctions:
5958/// 1. The new fragment isn't relative to an existing fragment.
5959/// 2. It assumes the computed location is a memory location. This means we
5960/// don't need to perform checks that creating the fragment preserves the
5961/// expression semantics.
5962/// 3. Existing extract_bits are modified independently of fragment changes
5963/// using \p BitExtractOffset. A change to the fragment offset or size
5964/// may affect a bit extract. But a bit extract offset can change
5965/// independently of the fragment dimensions.
5966///
5967/// Returns the new expression, or nullptr if one couldn't be created.
5968/// Ideally this is only used to signal that a bit-extract has become
5969/// zero-sized (and thus the new debug record has no size and can be
5970/// dropped), however, it fails for other reasons too - see the FIXME below.
5971///
5972/// FIXME: To keep the change that introduces this function NFC it bails
5973/// in some situations unecessarily, e.g. when fragment and bit extract
5974/// sizes differ.
5977 int64_t BitExtractOffset) {
5979 bool HasFragment = false;
5980 bool HasBitExtract = false;
5981
5982 for (auto &Op : Expr->expr_ops()) {
5983 if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
5984 HasFragment = true;
5985 continue;
5986 }
5987 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
5988 HasBitExtract = true;
5989 int64_t ExtractOffsetInBits = Extract.getOffsetInBits();
5990 int64_t ExtractSizeInBits = Extract.getSizeInBits();
5991
5992 // DIExpression::createFragmentExpression doesn't know how to handle
5993 // a fragment that is smaller than the extract. Copy the behaviour
5994 // (bail) to avoid non-NFC changes.
5995 // FIXME: Don't do this.
5996 if (Frag.SizeInBits < uint64_t(ExtractSizeInBits))
5997 return nullptr;
5998
5999 assert(BitExtractOffset <= 0);
6000 int64_t AdjustedOffset = ExtractOffsetInBits + BitExtractOffset;
6001
6002 // DIExpression::createFragmentExpression doesn't know what to do
6003 // if the new extract starts "outside" the existing one. Copy the
6004 // behaviour (bail) to avoid non-NFC changes.
6005 // FIXME: Don't do this.
6006 if (AdjustedOffset < 0)
6007 return nullptr;
6008
6009 Ops.push_back(Op.getOp());
6010 Ops.push_back(std::max<int64_t>(0, AdjustedOffset));
6011 Ops.push_back(ExtractSizeInBits);
6012 continue;
6013 }
6014 Op.appendToVector(Ops);
6015 }
6016
6017 // Unsupported by createFragmentExpression, so don't support it here yet to
6018 // preserve NFC-ness.
6019 if (HasFragment && HasBitExtract)
6020 return nullptr;
6021
6022 if (!HasBitExtract) {
6024 Ops.push_back(Frag.OffsetInBits);
6025 Ops.push_back(Frag.SizeInBits);
6026 }
6027 return DIExpression::get(Expr->getContext(), Ops);
6028}
6029
6030/// Insert a new DbgRecord.
6031/// \p Orig Original to copy record type, debug loc and variable from, and
6032/// additionally value and value expression for dbg_assign records.
6033/// \p NewAddr Location's new base address.
6034/// \p NewAddrExpr New expression to apply to address.
6035/// \p BeforeInst Insert position.
6036/// \p NewFragment New fragment (absolute, non-relative).
6037/// \p BitExtractAdjustment Offset to apply to any extract_bits op.
6038static void
6040 DIExpression *NewAddrExpr, Instruction *BeforeInst,
6041 std::optional<DIExpression::FragmentInfo> NewFragment,
6042 int64_t BitExtractAdjustment) {
6043 (void)DIB;
6044
6045 // A dbg_assign puts fragment info in the value expression only. The address
6046 // expression has already been built: NewAddrExpr. A dbg_declare puts the
6047 // new fragment info into NewAddrExpr (as it only has one expression).
6048 DIExpression *NewFragmentExpr =
6049 Orig->isDbgAssign() ? Orig->getExpression() : NewAddrExpr;
6050 if (NewFragment)
6051 NewFragmentExpr = createOrReplaceFragment(NewFragmentExpr, *NewFragment,
6052 BitExtractAdjustment);
6053 if (!NewFragmentExpr)
6054 return;
6055
6056 if (Orig->isDbgDeclare()) {
6058 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
6059 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
6060 BeforeInst->getIterator());
6061 return;
6062 }
6063
6064 if (Orig->isDbgValue()) {
6066 NewAddr, Orig->getVariable(), NewFragmentExpr, Orig->getDebugLoc());
6067 // Drop debug information if the expression doesn't start with a
6068 // DW_OP_deref. This is because without a DW_OP_deref, the #dbg_value
6069 // describes the address of alloca rather than the value inside the alloca.
6070 if (!NewFragmentExpr->startsWithDeref())
6071 DVR->setKillAddress();
6072 BeforeInst->getParent()->insertDbgRecordBefore(DVR,
6073 BeforeInst->getIterator());
6074 return;
6075 }
6076
6077 // Apply a DIAssignID to the store if it doesn't already have it.
6078 if (!NewAddr->hasMetadata(LLVMContext::MD_DIAssignID)) {
6079 NewAddr->setMetadata(LLVMContext::MD_DIAssignID,
6081 }
6082
6084 NewAddr, Orig->getValue(), Orig->getVariable(), NewFragmentExpr, NewAddr,
6085 NewAddrExpr, Orig->getDebugLoc());
6086 LLVM_DEBUG(dbgs() << "Created new DVRAssign: " << *NewAssign << "\n");
6087 (void)NewAssign;
6088}
6089
6090/// Walks the slices of an alloca and form partitions based on them,
6091/// rewriting each of their uses.
6092bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
6093 if (AS.begin() == AS.end())
6094 return false;
6095
6096 unsigned NumPartitions = 0;
6097 bool Changed = false;
6098 const DataLayout &DL = AI.getDataLayout();
6099
6100 // First try to pre-split loads and stores.
6101 Changed |= presplitLoadsAndStores(AI, AS);
6102
6103 // Now that we have identified any pre-splitting opportunities,
6104 // mark loads and stores unsplittable except for the following case.
6105 // We leave a slice splittable if all other slices are disjoint or fully
6106 // included in the slice, such as whole-alloca loads and stores.
6107 // If we fail to split these during pre-splitting, we want to force them
6108 // to be rewritten into a partition.
6109 bool IsSorted = true;
6110
6111 uint64_t AllocaSize = AI.getAllocationSize(DL)->getFixedValue();
6112 // We can split at the begin and end offsets of each slice, but only if those
6113 // offsets don't lie inside another slice. Because slices are ordered by
6114 // increasing begin offset, and then decreasing end offset, we can consider
6115 // the slices as being split up into sets with the same begin offset where we
6116 // can ignore every slice except the first (the begin offset will already be
6117 // handled as the begin offset of the set, and the end offset we know is not a
6118 // splittable offset as it's inside the first slice of the set).
6119 SparseBitVector<> SplittableOffset;
6120 uint64_t CurBegin = 0, CurEnd = 0;
6121 for (Slice &S : AS) {
6122 // Check if we have a new set of slices
6123 if (S.beginOffset() > CurBegin || S.endOffset() > CurEnd) {
6124 // If the start isn't inside the previous set it's splittable
6125 if (S.beginOffset() >= CurEnd) {
6126 SplittableOffset.set(S.beginOffset());
6127 }
6128 // If the previous end is inside this slice then remove it
6129 if (CurEnd > S.beginOffset() && CurEnd < S.endOffset()) {
6130 SplittableOffset.reset(CurEnd);
6131 }
6132 CurBegin = S.beginOffset();
6133 // If the end offset isn't inside the previous set it's splittable. We
6134 // also don't update the end offset in that case, as the next set may also
6135 // be inside the previous set.
6136 if (S.endOffset() > CurEnd) {
6137 CurEnd = S.endOffset();
6138 SplittableOffset.set(CurEnd);
6139 }
6140 }
6141 }
6142
6143 for (Slice &S : AS) {
6144 if (!S.isSplittable())
6145 continue;
6146
6147 if ((S.beginOffset() > AllocaSize ||
6148 SplittableOffset.test(S.beginOffset())) &&
6149 (S.endOffset() > AllocaSize || SplittableOffset.test(S.endOffset())))
6150 continue;
6151
6152 if (isa<LoadInst>(S.getUse()->getUser()) ||
6153 isa<StoreInst>(S.getUse()->getUser())) {
6154 S.makeUnsplittable();
6155 IsSorted = false;
6156 }
6157 }
6158
6159 if (!IsSorted)
6161
6162 /// Describes the allocas introduced by rewritePartition in order to migrate
6163 /// the debug info.
6164 struct Fragment {
6165 AllocaInst *Alloca;
6167 uint64_t Size;
6168 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
6169 : Alloca(AI), Offset(O), Size(S) {}
6170 };
6171 SmallVector<Fragment, 4> Fragments;
6172
6173 // Rewrite each partition.
6174 for (auto &P : AS.partitions()) {
6175 auto [NewAI, ActiveBits] = rewritePartition(AI, AS, P);
6176 if (NewAI) {
6177 Changed = true;
6178 if (NewAI != &AI) {
6179 uint64_t SizeOfByte = 8;
6180 // Don't include any padding.
6181 uint64_t Size = std::min(ActiveBits, P.size() * SizeOfByte);
6182 Fragments.push_back(
6183 Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
6184 }
6185 }
6186 ++NumPartitions;
6187 }
6188
6189 NumAllocaPartitions += NumPartitions;
6190 MaxPartitionsPerAlloca.updateMax(NumPartitions);
6191
6192 // Migrate debug information from the old alloca to the new alloca(s)
6193 // and the individual partitions.
6194 auto MigrateOne = [&](DbgVariableRecord *DbgVariable) {
6195 // Can't overlap with undef memory.
6196 if (isKillAddress(DbgVariable))
6197 return;
6198
6199 const Value *DbgPtr = DbgVariable->getAddress();
6201 DbgVariable->getFragmentOrEntireVariable();
6202 // Get the address expression constant offset if one exists and the ops
6203 // that come after it.
6204 int64_t CurrentExprOffsetInBytes = 0;
6205 SmallVector<uint64_t> PostOffsetOps;
6206 if (!getAddressExpression(DbgVariable)
6207 ->extractLeadingOffset(CurrentExprOffsetInBytes, PostOffsetOps))
6208 return; // Couldn't interpret this DIExpression - drop the var.
6209
6210 // Offset defined by a DW_OP_LLVM_extract_bits_[sz]ext.
6211 int64_t ExtractOffsetInBits = 0;
6212 for (auto Op : getAddressExpression(DbgVariable)->expr_ops()) {
6213 if (auto Extract = dyn_cast<DIExpression::ExtractBitsOp>(Op)) {
6214 ExtractOffsetInBits = Extract.getOffsetInBits();
6215 break;
6216 }
6217 }
6218
6219 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
6220 for (auto Fragment : Fragments) {
6221 int64_t OffsetFromLocationInBits;
6222 std::optional<DIExpression::FragmentInfo> NewDbgFragment;
6223 // Find the variable fragment that the new alloca slice covers.
6224 // Drop debug info for this variable fragment if we can't compute an
6225 // intersect between it and the alloca slice.
6227 DL, &AI, Fragment.Offset, Fragment.Size, DbgPtr,
6228 CurrentExprOffsetInBytes * 8, ExtractOffsetInBits, VarFrag,
6229 NewDbgFragment, OffsetFromLocationInBits))
6230 continue; // Do not migrate this fragment to this slice.
6231
6232 // Zero sized fragment indicates there's no intersect between the variable
6233 // fragment and the alloca slice. Skip this slice for this variable
6234 // fragment.
6235 if (NewDbgFragment && !NewDbgFragment->SizeInBits)
6236 continue; // Do not migrate this fragment to this slice.
6237
6238 // No fragment indicates DbgVariable's variable or fragment exactly
6239 // overlaps the slice; copy its fragment (or nullopt if there isn't one).
6240 if (!NewDbgFragment)
6241 NewDbgFragment = DbgVariable->getFragment();
6242
6243 // Reduce the new expression offset by the bit-extract offset since
6244 // we'll be keeping that.
6245 int64_t OffestFromNewAllocaInBits =
6246 OffsetFromLocationInBits - ExtractOffsetInBits;
6247 // We need to adjust an existing bit extract if the offset expression
6248 // can't eat the slack (i.e., if the new offset would be negative).
6249 int64_t BitExtractOffset =
6250 std::min<int64_t>(0, OffestFromNewAllocaInBits);
6251 // The magnitude of a negative value indicates the number of bits into
6252 // the existing variable fragment that the memory region begins. The new
6253 // variable fragment already excludes those bits - the new DbgPtr offset
6254 // only needs to be applied if it's positive.
6255 OffestFromNewAllocaInBits =
6256 std::max(int64_t(0), OffestFromNewAllocaInBits);
6257
6258 // Rebuild the expression:
6259 // {Offset(OffestFromNewAllocaInBits), PostOffsetOps, NewDbgFragment}
6260 // Add NewDbgFragment later, because dbg.assigns don't want it in the
6261 // address expression but the value expression instead.
6262 DIExpression *NewExpr = DIExpression::get(AI.getContext(), PostOffsetOps);
6263 if (OffestFromNewAllocaInBits > 0) {
6264 int64_t OffsetInBytes = (OffestFromNewAllocaInBits + 7) / 8;
6265 NewExpr = DIExpression::prepend(NewExpr, /*flags=*/0, OffsetInBytes);
6266 }
6267
6268 // Remove any existing intrinsics on the new alloca describing
6269 // the variable fragment.
6270 auto RemoveOne = [DbgVariable](auto *OldDII) {
6271 auto SameVariableFragment = [](const auto *LHS, const auto *RHS) {
6272 return LHS->getVariable() == RHS->getVariable() &&
6273 LHS->getDebugLoc()->getInlinedAt() ==
6274 RHS->getDebugLoc()->getInlinedAt();
6275 };
6276 if (SameVariableFragment(OldDII, DbgVariable))
6277 OldDII->eraseFromParent();
6278 };
6279 for_each(findDVRDeclares(Fragment.Alloca), RemoveOne);
6280 for_each(findDVRValues(Fragment.Alloca), RemoveOne);
6281 insertNewDbgInst(DIB, DbgVariable, Fragment.Alloca, NewExpr, &AI,
6282 NewDbgFragment, BitExtractOffset);
6283 }
6284 };
6285
6286 // Migrate debug information from the old alloca to the new alloca(s)
6287 // and the individual partitions.
6288 for_each(findDVRDeclares(&AI), MigrateOne);
6289 for_each(findDVRValues(&AI), MigrateOne);
6290 for_each(at::getDVRAssignmentMarkers(&AI), MigrateOne);
6291
6292 return Changed;
6293}
6294
6295/// Clobber a use with poison, deleting the used value if it becomes dead.
6296void SROA::clobberUse(Use &U) {
6297 Value *OldV = U;
6298 // Replace the use with an poison value.
6299 U = PoisonValue::get(OldV->getType());
6300
6301 // Check for this making an instruction dead. We have to garbage collect
6302 // all the dead instructions to ensure the uses of any alloca end up being
6303 // minimal.
6304 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
6305 if (isInstructionTriviallyDead(OldI)) {
6306 DeadInsts.push_back(OldI);
6307 }
6308}
6309
6310/// A basic LoadAndStorePromoter that does not remove store nodes.
6312public:
6314 Type *ZeroType)
6315 : LoadAndStorePromoter(Insts, S), ZeroType(ZeroType) {}
6316 bool shouldDelete(Instruction *I) const override {
6317 return !isa<StoreInst>(I) && !isa<AllocaInst>(I);
6318 }
6319
6321 return UndefValue::get(ZeroType);
6322 }
6323
6324private:
6325 Type *ZeroType;
6326};
6327
6328bool SROA::propagateStoredValuesToLoads(AllocaInst &AI, AllocaSlices &AS) {
6329 // Look through each "partition", looking for slices with the same start/end
6330 // that do not overlap with any before them. The slices are sorted by
6331 // increasing beginOffset. We don't use AS.partitions(), as it will use a more
6332 // sophisticated algorithm that takes splittable slices into account.
6333 LLVM_DEBUG(dbgs() << "Attempting to propagate values on " << AI << "\n");
6334 bool AllSameAndValid = true;
6335 Type *PartitionType = nullptr;
6336 SmallVector<Instruction *> Insts;
6337 uint64_t BeginOffset = 0;
6338 uint64_t EndOffset = 0;
6339
6340 auto Flush = [&]() {
6341 if (AllSameAndValid && !Insts.empty()) {
6342 LLVM_DEBUG(dbgs() << "Propagate values on slice [" << BeginOffset << ", "
6343 << EndOffset << ")\n");
6345 SSAUpdater SSA(&NewPHIs);
6346 Insts.push_back(&AI);
6347 BasicLoadAndStorePromoter Promoter(Insts, SSA, PartitionType);
6348 Promoter.run(Insts);
6349 }
6350 AllSameAndValid = true;
6351 PartitionType = nullptr;
6352 Insts.clear();
6353 };
6354
6355 for (Slice &S : AS) {
6356 auto *User = cast<Instruction>(S.getUse()->getUser());
6357 if (isAssumeLikeIntrinsic(User)) {
6358 LLVM_DEBUG({
6359 dbgs() << "Ignoring slice: ";
6360 AS.print(dbgs(), &S);
6361 });
6362 continue;
6363 }
6364 if (S.beginOffset() >= EndOffset) {
6365 Flush();
6366 BeginOffset = S.beginOffset();
6367 EndOffset = S.endOffset();
6368 } else if (S.beginOffset() != BeginOffset || S.endOffset() != EndOffset) {
6369 if (AllSameAndValid) {
6370 LLVM_DEBUG({
6371 dbgs() << "Slice does not match range [" << BeginOffset << ", "
6372 << EndOffset << ")";
6373 AS.print(dbgs(), &S);
6374 });
6375 AllSameAndValid = false;
6376 }
6377 EndOffset = std::max(EndOffset, S.endOffset());
6378 continue;
6379 }
6380
6381 if (auto *LI = dyn_cast<LoadInst>(User)) {
6382 Type *UserTy = LI->getType();
6383 // LoadAndStorePromoter requires all the types to be the same.
6384 if (!LI->isSimple() || (PartitionType && UserTy != PartitionType))
6385 AllSameAndValid = false;
6386 PartitionType = UserTy;
6387 Insts.push_back(User);
6388 } else if (auto *SI = dyn_cast<StoreInst>(User)) {
6389 Type *UserTy = SI->getValueOperand()->getType();
6390 if (!SI->isSimple() || (PartitionType && UserTy != PartitionType))
6391 AllSameAndValid = false;
6392 PartitionType = UserTy;
6393 Insts.push_back(User);
6394 } else {
6395 AllSameAndValid = false;
6396 }
6397 }
6398
6399 Flush();
6400 return true;
6401}
6402
6403/// Analyze an alloca for SROA.
6404///
6405/// This analyzes the alloca to ensure we can reason about it, builds
6406/// the slices of the alloca, and then hands it off to be split and
6407/// rewritten as needed.
6408std::pair<bool /*Changed*/, bool /*CFGChanged*/>
6409SROA::runOnAlloca(AllocaInst &AI) {
6410 bool Changed = false;
6411 bool CFGChanged = false;
6412
6413 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
6414 ++NumAllocasAnalyzed;
6415
6416 // Special case dead allocas, as they're trivial.
6417 if (AI.use_empty()) {
6418 AI.eraseFromParent();
6419 Changed = true;
6420 return {Changed, CFGChanged};
6421 }
6422 const DataLayout &DL = AI.getDataLayout();
6423
6424 // Skip alloca forms that this analysis can't handle.
6425 std::optional<TypeSize> Size = AI.getAllocationSize(DL);
6426 if (AI.isArrayAllocation() || !Size || Size->isScalable() || Size->isZero())
6427 return {Changed, CFGChanged};
6428
6429 // First, split any FCA loads and stores touching this alloca to promote
6430 // better splitting and promotion opportunities.
6431 IRBuilderTy IRB(&AI);
6432 AggLoadStoreRewriter AggRewriter(DL, IRB);
6433 Changed |= AggRewriter.rewrite(AI);
6434
6435 // Build the slices using a recursive instruction-visiting builder.
6436 AllocaSlices AS(DL, AI);
6437 LLVM_DEBUG(AS.print(dbgs()));
6438 if (AS.isEscaped())
6439 return {Changed, CFGChanged};
6440
6441 if (AS.isEscapedReadOnly()) {
6442 Changed |= propagateStoredValuesToLoads(AI, AS);
6443 return {Changed, CFGChanged};
6444 }
6445
6446 // Delete all the dead users of this alloca before splitting and rewriting it.
6447 for (Instruction *DeadUser : AS.getDeadUsers()) {
6448 // Free up everything used by this instruction.
6449 for (Use &DeadOp : DeadUser->operands())
6450 clobberUse(DeadOp);
6451
6452 // Now replace the uses of this instruction.
6453 DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
6454
6455 // And mark it for deletion.
6456 DeadInsts.push_back(DeadUser);
6457 Changed = true;
6458 }
6459 for (Use *DeadOp : AS.getDeadOperands()) {
6460 clobberUse(*DeadOp);
6461 Changed = true;
6462 }
6463
6464 // No slices to split. Leave the dead alloca for a later pass to clean up.
6465 if (AS.begin() == AS.end())
6466 return {Changed, CFGChanged};
6467
6468 Changed |= splitAlloca(AI, AS);
6469
6470 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
6471 while (!SpeculatablePHIs.empty())
6472 speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
6473
6474 LLVM_DEBUG(dbgs() << " Rewriting stores through PHIs\n");
6475 auto RemainingPHIsWithStoreToRewrite = PHIsWithStoreToRewrite.takeVector();
6476 while (!RemainingPHIsWithStoreToRewrite.empty()) {
6477 PHINode *PN = RemainingPHIsWithStoreToRewrite.pop_back_val();
6478 auto *SI = cast<StoreInst>(PN->user_back());
6479 CFGChanged |= rewritePHINodeStore(*PN, *SI, *DTU, Worklist);
6480 }
6481
6482 LLVM_DEBUG(dbgs() << " Rewriting Selects\n");
6483 auto RemainingSelectsToRewrite = SelectsToRewrite.takeVector();
6484 while (!RemainingSelectsToRewrite.empty()) {
6485 const auto [K, V] = RemainingSelectsToRewrite.pop_back_val();
6486 CFGChanged |=
6487 rewriteSelectInstMemOps(*K, V, IRB, PreserveCFG ? nullptr : DTU);
6488 }
6489
6490 return {Changed, CFGChanged};
6491}
6492
6493/// Delete the dead instructions accumulated in this run.
6494///
6495/// Recursively deletes the dead instructions we've accumulated. This is done
6496/// at the very end to maximize locality of the recursive delete and to
6497/// minimize the problems of invalidated instruction pointers as such pointers
6498/// are used heavily in the intermediate stages of the algorithm.
6499///
6500/// We also record the alloca instructions deleted here so that they aren't
6501/// subsequently handed to mem2reg to promote.
6502bool SROA::deleteDeadInstructions(
6503 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
6504 bool Changed = false;
6505 while (!DeadInsts.empty()) {
6506 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
6507 if (!I)
6508 continue;
6509 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
6510
6511 // If the instruction is an alloca, find the possible dbg.declare connected
6512 // to it, and remove it too. We must do this before calling RAUW or we will
6513 // not be able to find it.
6514 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6515 DeletedAllocas.insert(AI);
6516 for (DbgVariableRecord *OldDII : findDVRDeclares(AI))
6517 OldDII->eraseFromParent();
6518 }
6519
6521 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6522
6523 for (Use &Operand : I->operands())
6524 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
6525 // Zero out the operand and see if it becomes trivially dead.
6526 Operand = nullptr;
6528 DeadInsts.push_back(U);
6529 }
6530
6531 ++NumDeleted;
6532 I->eraseFromParent();
6533 Changed = true;
6534 }
6535 return Changed;
6536}
6537/// Promote the allocas, using the best available technique.
6538///
6539/// This attempts to promote whatever allocas have been identified as viable in
6540/// the PromotableAllocas list. If that list is empty, there is nothing to do.
6541/// This function returns whether any promotion occurred.
6542bool SROA::promoteAllocas() {
6543 if (PromotableAllocas.empty())
6544 return false;
6545
6546 if (getScalarOptions(*C).sroa_skip_mem2reg) {
6547 LLVM_DEBUG(dbgs() << "Not promoting allocas with mem2reg!\n");
6548 } else {
6549 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
6550 NumPromoted += PromotableAllocas.size();
6551 PromoteMemToReg(PromotableAllocas.getArrayRef(), DTU->getDomTree(), AC);
6552 }
6553
6554 PromotableAllocas.clear();
6555 return true;
6556}
6557
6558std::pair<bool /*Changed*/, bool /*CFGChanged*/> SROA::runSROA(Function &F) {
6559 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
6560
6561 const DataLayout &DL = F.getDataLayout();
6562 BasicBlock &EntryBB = F.getEntryBlock();
6563 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
6564 I != E; ++I) {
6565 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
6566 std::optional<TypeSize> Size = AI->getAllocationSize(DL);
6567 if (Size && Size->isScalable() && isAllocaPromotable(AI))
6568 PromotableAllocas.insert(AI);
6569 else
6570 Worklist.insert(AI);
6571 }
6572 }
6573
6574 bool Changed = false;
6575 bool CFGChanged = false;
6576 // A set of deleted alloca instruction pointers which should be removed from
6577 // the list of promotable allocas.
6578 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
6579
6580 do {
6581 while (!Worklist.empty()) {
6582 auto [IterationChanged, IterationCFGChanged] =
6583 runOnAlloca(*Worklist.pop_back_val());
6584 Changed |= IterationChanged;
6585 CFGChanged |= IterationCFGChanged;
6586
6587 Changed |= deleteDeadInstructions(DeletedAllocas);
6588
6589 // Remove the deleted allocas from various lists so that we don't try to
6590 // continue processing them.
6591 if (!DeletedAllocas.empty()) {
6592 Worklist.set_subtract(DeletedAllocas);
6593 PostPromotionWorklist.set_subtract(DeletedAllocas);
6594 PromotableAllocas.set_subtract(DeletedAllocas);
6595 DeletedAllocas.clear();
6596 }
6597 }
6598
6599 Changed |= promoteAllocas();
6600
6601 Worklist = PostPromotionWorklist;
6602 PostPromotionWorklist.clear();
6603 } while (!Worklist.empty());
6604
6605 assert((!CFGChanged || Changed) && "Can not only modify the CFG.");
6606 assert((!CFGChanged || !PreserveCFG) &&
6607 "Should not have modified the CFG when told to preserve it.");
6608
6609 if (Changed && isAssignmentTrackingEnabled(*F.getParent())) {
6610 for (auto &BB : F) {
6612 }
6613 }
6614
6615 return {Changed, CFGChanged};
6616}
6617
6621 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6622 auto [Changed, CFGChanged] =
6623 SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6624 if (!Changed)
6625 return PreservedAnalyses::all();
6627 if (!CFGChanged)
6630 return PA;
6631}
6632
6634 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6635 static_cast<PassInfoMixin<SROAPass> *>(this)->printPipeline(
6636 OS, MapClassName2PassName);
6637 OS << '<'
6638 << (Options.CFG == SROAOptions::PreserveCFG ? "preserve-cfg"
6639 : "modify-cfg");
6640 if (Options.AggregateToVector)
6641 OS << ";aggregate-to-vector";
6642 OS << '>';
6643}
6644
6645SROAPass::SROAPass(SROAOptions Options) : Options(Options) {}
6646
6647namespace {
6648
6649/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
6650class SROALegacyPass : public FunctionPass {
6652
6653public:
6654 static char ID;
6655
6657 : FunctionPass(ID), Options(Options) {
6659 }
6660
6661 bool runOnFunction(Function &F) override {
6662 if (skipFunction(F))
6663 return false;
6664
6665 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6666 AssumptionCache &AC =
6667 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6668 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
6669 auto [Changed, _] = SROA(&F.getContext(), &DTU, &AC, Options).runSROA(F);
6670 return Changed;
6671 }
6672
6673 void getAnalysisUsage(AnalysisUsage &AU) const override {
6674 AU.addRequired<AssumptionCacheTracker>();
6675 AU.addRequired<DominatorTreeWrapperPass>();
6676 AU.addPreserved<GlobalsAAWrapperPass>();
6677 AU.addPreserved<DominatorTreeWrapperPass>();
6678 }
6679
6680 StringRef getPassName() const override { return "SROA"; }
6681};
6682
6683} // end anonymous namespace
6684
6685char SROALegacyPass::ID = 0;
6686
6687FunctionPass *llvm::createSROAPass(bool PreserveCFG, bool AggregateToVector) {
6688 return new SROALegacyPass(SROAOptions(PreserveCFG ? SROAOptions::PreserveCFG
6690 AggregateToVector));
6691}
6692
6693INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
6694 "Scalar Replacement Of Aggregates", false, false)
6697INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
SDValue Pred
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:4839
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:5975
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:5096
static Value * foldSelectInst(SelectInst &SI)
Definition SROA.cpp:1021
bool isKillAddress(const DbgVariableRecord *DVR)
Definition SROA.cpp:5938
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:5655
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:5595
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:6039
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:5944
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:4877
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:6316
BasicLoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, Type *ZeroType)
Definition SROA.cpp:6313
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:6320
SliceSplitter(IRBuilderTy &IRB, const DataLayout &DL, std::vector< uint64_t > &Splits, unsigned SliceSize)
Definition SROA.cpp:5002
StoreInst * createStore(Value *StoreVal, Value *BasePtr, Iterator &It, Instruction *SplitI)
Definition SROA.cpp:5050
Iterator begin()
Definition SROA.cpp:5030
Slice createSlice(Instruction *I, uint64_t BaseOffset, Iterator &It)
Definition SROA.cpp:5072
LoadInst * createLoad(Value *BasePtr, Iterator &It, Instruction *SplitI)
Definition SROA.cpp:5034
Iterator end()
Definition SROA.cpp:5032
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:2947
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:6645
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition SROA.cpp:6618
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition SROA.cpp:6633
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:456
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:1513
LLVM_ABI FunctionPass * createSROAPass(bool PreserveCFG=true, bool AggregateToVector=false)
Definition SROA.cpp:6687
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:1465
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:320
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:5010
Iterator & operator++()
Definition SROA.cpp:5023
SliceSplitter & SS
Definition SROA.cpp:5011
uint64_t getSize() const
Definition SROA.cpp:5018
bool operator==(const Iterator &Other) const
Definition SROA.cpp:5016
const Iterator & operator*() const
Definition SROA.cpp:5027
uint64_t getOffset() const
Definition SROA.cpp:5017
Iterator(SliceSplitter &SS, bool IsEnd)
Definition SROA.cpp:5013
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