LLVM 24.0.0git
PromoteMemoryToRegister.cpp
Go to the documentation of this file.
1//===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file promotes memory references to be register references. It promotes
10// alloca instructions which only have loads and stores as uses. An alloca is
11// transformed by using iterated dominator frontiers to place PHI nodes, then
12// traversing the function in depth-first order to rewrite loads and stores as
13// appropriate.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/BitVector.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/Twine.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/CFG.h"
31#include "llvm/IR/Constant.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DIBuilder.h"
34#include "llvm/IR/DebugInfo.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/Operator.h"
46#include "llvm/IR/Type.h"
47#include "llvm/IR/User.h"
51#include <algorithm>
52#include <cassert>
53#include <iterator>
54#include <utility>
55#include <vector>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "mem2reg"
60
61STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
62STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
63STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
64STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
65
67 // Only allow direct and non-volatile loads and stores...
68 // All loads and stores must use the same type (determined by the first one
69 // seen). We don't require the type to match the alloca's declared type.
70 Type *ExpectedType = nullptr;
71 for (const User *U : AI->users()) {
72 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
73 // Note that atomic loads can be transformed; atomic semantics do
74 // not have any meaning for a local alloca.
75 if (LI->isVolatile())
76 return false;
77 if (!ExpectedType)
78 ExpectedType = LI->getType();
79 else if (LI->getType() != ExpectedType)
80 return false;
81 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
82 if (SI->getValueOperand() == AI)
83 return false; // Don't allow a store OF the AI, only INTO the AI.
84 // Note that atomic stores can be transformed; atomic semantics do
85 // not have any meaning for a local alloca.
86 if (SI->isVolatile())
87 return false;
88 Type *StoreType = SI->getValueOperand()->getType();
89 if (!ExpectedType)
90 ExpectedType = StoreType;
91 else if (StoreType != ExpectedType)
92 return false;
93 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
94 if (!II->isLifetimeStartOrEnd() && !II->isDroppable() &&
95 II->getIntrinsicID() != Intrinsic::fake_use)
96 return false;
97 } else {
98 return false;
99 }
100 }
101
102 return true;
103}
104
105namespace {
106
107static void createDebugValue(DIBuilder &DIB, Value *NewValue,
108 DILocalVariable *Variable,
110 DbgVariableRecord *InsertBefore) {
111 // FIXME: Merge these two functions now that DIBuilder supports
112 // DbgVariableRecords. We neeed the API to accept DbgVariableRecords as an
113 // insert point for that to work.
114 (void)DIB;
116 *InsertBefore);
117}
118
119/// Helper for updating assignment tracking debug info when promoting allocas.
120class AssignmentTrackingInfo {
121 /// DbgAssignIntrinsics linked to the alloca with at most one per variable
122 /// fragment. (i.e. not be a comprehensive set if there are multiple
123 /// dbg.assigns for one variable fragment).
125
126public:
127 void init(AllocaInst *AI) {
128 SmallSet<DebugVariable, 2> Vars;
129 for (DbgVariableRecord *DVR : at::getDVRAssignmentMarkers(AI)) {
130 if (Vars.insert(DebugVariable(DVR)).second)
131 DVRAssigns.push_back(DVR);
132 }
133 }
134
135 /// Update assignment tracking debug info given for the to-be-deleted store
136 /// \p ToDelete that stores to this alloca.
137 void updateForDeletedStore(
138 StoreInst *ToDelete, DIBuilder &DIB,
139 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) const {
140 // There's nothing to do if the alloca doesn't have any variables using
141 // assignment tracking.
142 if (DVRAssigns.empty())
143 return;
144
145 // Insert a dbg.value where the linked dbg.assign is and remember to delete
146 // the dbg.assign later. Demoting to dbg.value isn't necessary for
147 // correctness but does reduce compile time and memory usage by reducing
148 // unnecessary function-local metadata. Remember that we've seen a
149 // dbg.assign for each variable fragment for the untracked store handling
150 // (after this loop).
151 SmallSet<DebugVariableAggregate, 2> VarHasDbgAssignForStore;
152 auto InsertValueForAssign = [&](auto *DbgAssign, auto *&AssignList) {
153 VarHasDbgAssignForStore.insert(DebugVariableAggregate(DbgAssign));
154 AssignList->insert(DbgAssign);
155 createDebugValue(DIB, DbgAssign->getValue(), DbgAssign->getVariable(),
156 DbgAssign->getExpression(), DbgAssign->getDebugLoc(),
157 DbgAssign);
158 };
159 for (auto *Assign : at::getDVRAssignmentMarkers(ToDelete))
160 InsertValueForAssign(Assign, DVRAssignsToDelete);
161
162 // It's possible for variables using assignment tracking to have no
163 // dbg.assign linked to this store. These are variables in DVRAssigns that
164 // are missing from VarHasDbgAssignForStore. Since there isn't a dbg.assign
165 // to mark the assignment - and the store is going to be deleted - insert a
166 // dbg.value to do that now. An untracked store may be either one that
167 // cannot be represented using assignment tracking (non-const offset or
168 // size) or one that is trackable but has had its DIAssignID attachment
169 // dropped accidentally.
170 auto ConvertUnlinkedAssignToValue = [&](DbgVariableRecord *Assign) {
171 if (VarHasDbgAssignForStore.contains(DebugVariableAggregate(Assign)))
172 return;
173 ConvertDebugDeclareToDebugValue(Assign, ToDelete, DIB);
174 };
175 for_each(DVRAssigns, ConvertUnlinkedAssignToValue);
176 }
177
178 /// Update assignment tracking debug info given for the newly inserted PHI \p
179 /// NewPhi.
180 void updateForNewPhi(PHINode *NewPhi, DIBuilder &DIB) const {
181 // Regardless of the position of dbg.assigns relative to stores, the
182 // incoming values into a new PHI should be the same for the (imaginary)
183 // debug-phi.
184 for (auto *DVR : DVRAssigns)
185 ConvertDebugDeclareToDebugValue(DVR, NewPhi, DIB);
186 }
187
188 void clear() { DVRAssigns.clear(); }
189 bool empty() { return DVRAssigns.empty(); }
190};
191
192struct AllocaInfo {
193 using DPUserVec = SmallVector<DbgVariableRecord *, 1>;
194
195 SmallVector<BasicBlock *, 32> DefiningBlocks;
197
198 StoreInst *OnlyStore;
199 BasicBlock *OnlyBlock;
200 bool OnlyUsedInOneBlock;
201
202 /// The type used by all loads/stores of this alloca. This may differ from
203 /// the alloca's declared type if all accesses use a different type.
204 Type *ValueType;
205
206 /// Debug users of the alloca - does not include dbg.assign intrinsics.
207 DPUserVec DPUsers;
208 /// Helper to update assignment tracking debug info.
209 AssignmentTrackingInfo AssignmentTracking;
210
211 void clear() {
212 DefiningBlocks.clear();
213 UsingBlocks.clear();
214 OnlyStore = nullptr;
215 OnlyBlock = nullptr;
216 OnlyUsedInOneBlock = true;
217 ValueType = nullptr;
218 DPUsers.clear();
219 AssignmentTracking.clear();
220 }
221
222 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
223 /// by the rest of the pass to reason about the uses of this alloca.
224 void AnalyzeAlloca(AllocaInst *AI) {
225 clear();
226
227 // As we scan the uses of the alloca instruction, keep track of stores,
228 // and decide whether all of the loads and stores to the alloca are within
229 // the same basic block.
230 for (User *U : AI->users()) {
232
233 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
234 // Remember the basic blocks which define new values for the alloca
235 DefiningBlocks.push_back(SI->getParent());
236 OnlyStore = SI;
237 if (!ValueType)
238 ValueType = SI->getValueOperand()->getType();
239 else
240 assert(ValueType == SI->getValueOperand()->getType() &&
241 "All stores were checked to have used the same type");
242 } else {
243 LoadInst *LI = cast<LoadInst>(User);
244 // Otherwise it must be a load instruction, keep track of variable
245 // reads.
246 UsingBlocks.push_back(LI->getParent());
247 if (!ValueType)
248 ValueType = LI->getType();
249 else
250 assert(ValueType == LI->getType() &&
251 "All loads where checked to have used the same type");
252 }
253
254 if (OnlyUsedInOneBlock) {
255 if (!OnlyBlock)
256 OnlyBlock = User->getParent();
257 else if (OnlyBlock != User->getParent())
258 OnlyUsedInOneBlock = false;
259 }
260 }
262 findDbgUsers(AI, AllDPUsers);
263 std::copy_if(AllDPUsers.begin(), AllDPUsers.end(),
264 std::back_inserter(DPUsers),
265 [](DbgVariableRecord *DVR) { return !DVR->isDbgAssign(); });
266 AssignmentTracking.init(AI);
267 }
268};
269
270template <typename T> class VectorWithUndo {
273
274public:
275 void undo(size_t S) {
276 assert(S <= Undo.size());
277 while (S < Undo.size()) {
278 Vals[Undo.back().first] = Undo.back().second;
279 Undo.pop_back();
280 }
281 }
282
283 void resize(size_t Sz) { Vals.resize(Sz); }
284
285 size_t undoSize() const { return Undo.size(); }
286
287 const T &operator[](size_t Idx) const { return Vals[Idx]; }
288
289 void set(size_t Idx, const T &Val) {
290 if (Vals[Idx] == Val)
291 return;
292 Undo.emplace_back(Idx, Vals[Idx]);
293 Vals[Idx] = Val;
294 }
295
296 void init(size_t Idx, const T &Val) {
297 assert(Undo.empty());
298 Vals[Idx] = Val;
299 }
300};
301
302/// Data package used by RenamePass().
303struct RenamePassData {
304 RenamePassData(BasicBlock *B, BasicBlock *P, size_t V, size_t L)
305 : BB(B), Pred(P), UndoVals(V), UndoLocs(L) {}
306
307 BasicBlock *BB;
308 BasicBlock *Pred;
309
310 size_t UndoVals;
311 size_t UndoLocs;
312};
313
314/// This assigns and keeps a per-bb relative ordering of load/store
315/// instructions in the block that directly load or store an alloca.
316///
317/// This functionality is important because it avoids scanning large basic
318/// blocks multiple times when promoting many allocas in the same block.
319class LargeBlockInfo {
320 /// For each instruction that we track, keep the index of the
321 /// instruction.
322 ///
323 /// The index starts out as the number of the instruction from the start of
324 /// the block.
325 DenseMap<const Instruction *, unsigned> InstNumbers;
326
327public:
328
329 /// This code only looks at accesses to allocas.
330 static bool isInterestingInstruction(const Instruction *I) {
331 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
332 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
333 }
334
335 /// Get or calculate the index of the specified instruction.
336 unsigned getInstructionIndex(const Instruction *I) {
337 assert(isInterestingInstruction(I) &&
338 "Not a load/store to/from an alloca?");
339
340 // If we already have this instruction number, return it.
341 auto It = InstNumbers.find(I);
342 if (It != InstNumbers.end())
343 return It->second;
344
345 // Scan the whole block to get the instruction. This accumulates
346 // information for every interesting instruction in the block, in order to
347 // avoid gratuitus rescans.
348 const BasicBlock *BB = I->getParent();
349 unsigned InstNo = 0;
350 for (const Instruction &BBI : *BB)
351 if (isInterestingInstruction(&BBI))
352 InstNumbers[&BBI] = InstNo++;
353 It = InstNumbers.find(I);
354
355 assert(It != InstNumbers.end() && "Didn't insert instruction?");
356 return It->second;
357 }
358
359 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
360
361 void clear() { InstNumbers.clear(); }
362};
363
364struct PromoteMem2Reg {
365 /// The alloca instructions being promoted.
366 std::vector<AllocaInst *> Allocas;
367
368 DominatorTree &DT;
369 DIBuilder DIB;
370
371 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
372 AssumptionCache *AC;
373
374 const SimplifyQuery SQ;
375
376 /// Reverse mapping of Allocas.
377 DenseMap<AllocaInst *, unsigned> AllocaLookup;
378
379 /// The PhiNodes we're adding.
380 ///
381 /// That map is used to simplify some Phi nodes as we iterate over it, so
382 /// it should have deterministic iterators. We could use a MapVector, but
383 /// since basic blocks have numbers, using these are more efficient.
384 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
385
386 /// For each PHI node, keep track of which entry in Allocas it corresponds
387 /// to.
388 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
389
390 /// For each alloca, we keep track of the dbg.declare record that
391 /// describes it, if any, so that we can convert it to a dbg.value
392 /// record if the alloca gets promoted.
394
395 /// For each alloca, keep an instance of a helper class that gives us an easy
396 /// way to update assignment tracking debug info if the alloca is promoted.
398 /// For each alloca, the type used by all loads/stores of this alloca.
399 SmallVector<Type *, 8> AllocaValueTypes;
400 /// A set of dbg.assigns to delete because they've been demoted to
401 /// dbg.values. Call cleanUpDbgAssigns to delete them.
402 SmallPtrSet<DbgVariableRecord *, 8> DVRAssignsToDelete;
403
404 /// The set of basic blocks the renamer has already visited.
405 BitVector Visited;
406
407 /// Lazily compute the number of predecessors a block has, indexed by block
408 /// number.
409 SmallVector<unsigned> BBNumPreds;
410
411 /// The state of incoming values for the current DFS step.
412 VectorWithUndo<Value *> IncomingVals;
413
414 /// The state of incoming locations for the current DFS step.
415 VectorWithUndo<DebugLoc> IncomingLocs;
416
417 // DFS work stack.
419
420 /// Whether the function has the no-signed-zeros-fp-math attribute set.
421 bool NoSignedZeros = false;
422
423public:
424 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
425 AssumptionCache *AC)
426 : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
427 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
428 AC(AC), SQ(DT.getRoot()->getDataLayout(),
429 nullptr, &DT, AC) {}
430
431 void run();
432
433private:
434 void RemoveFromAllocasList(unsigned &AllocaIdx) {
435 Allocas[AllocaIdx] = Allocas.back();
436 Allocas.pop_back();
437 --AllocaIdx;
438 }
439
440 unsigned getNumPreds(const BasicBlock *BB) {
441 // BBNumPreds is resized to getMaxBlockNumber() at the beginning.
442 unsigned &NP = BBNumPreds[BB->getNumber()];
443 if (NP == 0)
444 NP = pred_size(BB) + 1;
445 return NP - 1;
446 }
447
448 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
449 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
450 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
451 void RenamePass(BasicBlock *BB, BasicBlock *Pred);
452 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
453
454 /// Delete dbg.assigns that have been demoted to dbg.values.
455 void cleanUpDbgAssigns() {
456 for (auto *DVR : DVRAssignsToDelete)
457 DVR->eraseFromParent();
458 DVRAssignsToDelete.clear();
459 }
460
461 void pushToWorklist(BasicBlock *BB, BasicBlock *Pred) {
462 Worklist.emplace_back(BB, Pred, IncomingVals.undoSize(),
463 IncomingLocs.undoSize());
464 }
465
466 RenamePassData popFromWorklist() {
467 RenamePassData R = Worklist.back();
468 Worklist.pop_back();
469 IncomingVals.undo(R.UndoVals);
470 IncomingLocs.undo(R.UndoLocs);
471 return R;
472 }
473};
474
475} // end anonymous namespace
476
477/// Given a LoadInst LI this adds assume(LI != null) after it.
479 Function *AssumeIntrinsic =
480 Intrinsic::getOrInsertDeclaration(LI->getModule(), Intrinsic::assume);
481 ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
483 LoadNotNull->insertAfter(LI->getIterator());
484 CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
485 CI->insertAfter(LoadNotNull->getIterator());
487}
488
490 const DataLayout &DL, AssumptionCache *AC,
491 const DominatorTree *DT) {
492 if (isa<UndefValue>(Val) && LI->hasMetadata(LLVMContext::MD_noundef)) {
493 // Insert non-terminator unreachable.
494 LLVMContext &Ctx = LI->getContext();
497 /*isVolatile=*/false, Align(1), LI->getIterator());
498 return;
499 }
500
501 // If the load was marked as nonnull we don't want to lose that information
502 // when we erase this Load. So we preserve it with an assume. As !nonnull
503 // returns poison while assume violations are immediate undefined behavior,
504 // we can only do this if the value is known non-poison.
505 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
506 LI->getMetadata(LLVMContext::MD_noundef) &&
507 !isKnownNonZero(Val, SimplifyQuery(DL, DT, AC, LI)))
508 addAssumeNonNull(AC, LI);
509}
510
512 // Knowing that this alloca is promotable, we know that it's safe to kill all
513 // instructions except for load and store.
514
515 // Determine the type used by loads/stores on this alloca. Per
516 // isAllocaPromotable, all loads/stores must use the same type, and GEP/
517 // bitcast/addrspacecast derived pointers cannot have load/store users, so
518 // loads/stores are always direct users of the alloca.
519 Type *PromotedType = nullptr;
520 for (User *U : AI->users()) {
521 if (auto *LI = dyn_cast<LoadInst>(U)) {
522 PromotedType = LI->getType();
523 break;
524 }
525 if (auto *SI = dyn_cast<StoreInst>(U)) {
526 PromotedType = SI->getValueOperand()->getType();
527 break;
528 }
529 }
530
531 for (Use &U : llvm::make_early_inc_range(AI->uses())) {
532 Instruction *I = cast<Instruction>(U.getUser());
534 continue;
535
536 // Drop the use of AI in droppable instructions.
537 if (I->isDroppable()) {
538 I->dropDroppableUse(U);
539 continue;
540 }
541
542 // If the alloca has no load/store users, PromotedType is null and the
543 // alloca will be deleted as dead, so no store is needed.
544 if (PromotedType)
545 if (auto *II = dyn_cast<IntrinsicInst>(I))
546 if (II->isLifetimeStartOrEnd()) {
547 auto *Store = new StoreInst(UndefValue::get(PromotedType), AI,
548 /*isVolatile=*/false, AI->getAlign(),
549 I->getIterator());
550 Store->setDebugLoc(II->getDebugLoc());
551 }
552
553 I->eraseFromParent();
554 }
555}
556
557/// Rewrite as many loads as possible given a single store.
558///
559/// When there is only a single store, we can use the domtree to trivially
560/// replace all of the dominated loads with the stored value. Do so, and return
561/// true if this has successfully promoted the alloca entirely. If this returns
562/// false there were some loads which were not dominated by the single store
563/// and thus must be phi-ed with undef. We fall back to the standard alloca
564/// promotion algorithm in that case.
566 AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL,
568 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
569 StoreInst *OnlyStore = Info.OnlyStore;
570 Value *ReplVal = OnlyStore->getOperand(0);
571 // Loads may either load the stored value or uninitialized memory (undef).
572 // If the stored value may be poison, then replacing an uninitialized memory
573 // load with it would be incorrect. If the store dominates the load, we know
574 // it is always initialized.
575 bool RequireDominatingStore =
576 isa<Instruction>(ReplVal) || !isGuaranteedNotToBePoison(ReplVal);
577 BasicBlock *StoreBB = OnlyStore->getParent();
578 int StoreIndex = -1;
579
580 // Clear out UsingBlocks. We will reconstruct it here if needed.
581 Info.UsingBlocks.clear();
582
583 for (User *U : make_early_inc_range(AI->users())) {
584 Instruction *UserInst = cast<Instruction>(U);
585 if (UserInst == OnlyStore)
586 continue;
587 LoadInst *LI = cast<LoadInst>(UserInst);
588
589 // Okay, if we have a load from the alloca, we want to replace it with the
590 // only value stored to the alloca. We can do this if the value is
591 // dominated by the store. If not, we use the rest of the mem2reg machinery
592 // to insert the phi nodes as needed.
593 if (RequireDominatingStore) {
594 if (LI->getParent() == StoreBB) {
595 // If we have a use that is in the same block as the store, compare the
596 // indices of the two instructions to see which one came first. If the
597 // load came before the store, we can't handle it.
598 if (StoreIndex == -1)
599 StoreIndex = LBI.getInstructionIndex(OnlyStore);
600
601 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
602 // Can't handle this load, bail out.
603 Info.UsingBlocks.push_back(StoreBB);
604 continue;
605 }
606 } else if (!DT.dominates(StoreBB, LI->getParent())) {
607 // If the load and store are in different blocks, use BB dominance to
608 // check their relationships. If the store doesn't dom the use, bail
609 // out.
610 Info.UsingBlocks.push_back(LI->getParent());
611 continue;
612 }
613 }
614
615 // Otherwise, we *can* safely rewrite this load.
616 // If the replacement value is the load, this must occur in unreachable
617 // code.
618 if (ReplVal == LI)
619 ReplVal = PoisonValue::get(LI->getType());
620
621 convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
622 LI->replaceAllUsesWith(ReplVal);
623 LI->eraseFromParent();
624 LBI.deleteValue(LI);
625 }
626
627 // Finally, after the scan, check to see if the store is all that is left.
628 if (!Info.UsingBlocks.empty())
629 return false; // If not, we'll have to fall back for the remainder.
630
631 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
632 // Update assignment tracking info for the store we're going to delete.
633 Info.AssignmentTracking.updateForDeletedStore(Info.OnlyStore, DIB,
634 DVRAssignsToDelete);
635
636 // Record debuginfo for the store and remove the declaration's
637 // debuginfo.
638 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
639 if (DbgItem->isAddressOfVariable()) {
640 ConvertDebugDeclareToDebugValue(DbgItem, Info.OnlyStore, DIB);
641 DbgItem->eraseFromParent();
642 } else if (DbgItem->isValueOfVariable() &&
643 DbgItem->getExpression()->startsWithDeref()) {
644 InsertDebugValueAtStoreLoc(DbgItem, Info.OnlyStore, DIB);
645 DbgItem->eraseFromParent();
646 } else if (DbgItem->getExpression()->startsWithDeref()) {
647 DbgItem->eraseFromParent();
648 }
649 }
650
651 // Remove dbg.assigns linked to the alloca as these are now redundant.
653
654 // Remove the (now dead) store and alloca.
655 Info.OnlyStore->eraseFromParent();
656 LBI.deleteValue(Info.OnlyStore);
657
658 AI->eraseFromParent();
659 return true;
660}
661
662/// Many allocas are only used within a single basic block. If this is the
663/// case, avoid traversing the CFG and inserting a lot of potentially useless
664/// PHI nodes by just performing a single linear pass over the basic block
665/// using the Alloca.
666///
667/// If we cannot promote this alloca (because it is read before it is written),
668/// return false. This is necessary in cases where, due to control flow, the
669/// alloca is undefined only on some control flow paths. e.g. code like
670/// this is correct in LLVM IR:
671/// // A is an alloca with no stores so far
672/// for (...) {
673/// int t = *A;
674/// if (!first_iteration)
675/// use(t);
676/// *A = 42;
677/// }
679 AllocaInst *AI, const AllocaInfo &Info, LargeBlockInfo &LBI,
681 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
682 // The trickiest case to handle is when we have large blocks. Because of this,
683 // this code is optimized assuming that large blocks happen. This does not
684 // significantly pessimize the small block case. This uses LargeBlockInfo to
685 // make it efficient to get the index of various operations in the block.
686
687 // Walk the use-def list of the alloca, getting the locations of all stores.
688 using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
689 StoresByIndexTy StoresByIndex;
690
691 for (User *U : AI->users())
693 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
694
695 // Sort the stores by their index, making it efficient to do a lookup with a
696 // binary search.
697 llvm::sort(StoresByIndex, less_first());
698
699 // Walk all of the loads from this alloca, replacing them with the nearest
700 // store above them, if any.
701 for (User *U : make_early_inc_range(AI->users())) {
703 if (!LI)
704 continue;
705
706 unsigned LoadIdx = LBI.getInstructionIndex(LI);
707
708 // Find the nearest store that has a lower index than this load.
709 StoresByIndexTy::iterator I = llvm::lower_bound(
710 StoresByIndex,
711 std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
712 less_first());
713 Value *ReplVal;
714 if (I == StoresByIndex.begin()) {
715 if (StoresByIndex.empty())
716 // If there are no stores, the load takes the undef value.
717 ReplVal = UndefValue::get(LI->getType());
718 else
719 // There is no store before this load, bail out (load may be affected
720 // by the following stores - see main comment).
721 return false;
722 } else {
723 // Otherwise, there was a store before this load, the load takes its
724 // value.
725 ReplVal = std::prev(I)->second->getOperand(0);
726 }
727
728 convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
729
730 // If the replacement value is the load, this must occur in unreachable
731 // code.
732 if (ReplVal == LI)
733 ReplVal = PoisonValue::get(LI->getType());
734
735 LI->replaceAllUsesWith(ReplVal);
736 LI->eraseFromParent();
737 LBI.deleteValue(LI);
738 }
739
740 // Remove the (now dead) stores and alloca.
741 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
742 while (!AI->use_empty()) {
744 // Update assignment tracking info for the store we're going to delete.
745 Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DVRAssignsToDelete);
746 // Record debuginfo for the store before removing it.
747 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
748 if (DbgItem->isAddressOfVariable()) {
749 ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
750 }
751 }
752
753 SI->eraseFromParent();
754 LBI.deleteValue(SI);
755 }
756
757 // Remove dbg.assigns linked to the alloca as these are now redundant.
759 AI->eraseFromParent();
760
761 // The alloca's debuginfo can be removed as well.
762 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
763 if (DbgItem->isAddressOfVariable() ||
764 DbgItem->getExpression()->startsWithDeref())
765 DbgItem->eraseFromParent();
766 }
767
768 ++NumLocalPromoted;
769 return true;
770}
771
772void PromoteMem2Reg::run() {
773 Function &F = *DT.getRoot()->getParent();
774
775 AllocaATInfo.resize(Allocas.size());
776 AllocaDPUsers.resize(Allocas.size());
777 AllocaValueTypes.resize(Allocas.size());
778
779 AllocaInfo Info;
780 LargeBlockInfo LBI;
781 ForwardIDFCalculator IDF(DT);
782
783 NoSignedZeros = F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool();
784
785 // removeIntrinsicUsers inserts StoreInst(undef). A cache miss on
786 // LBI.getInstructionIndex lookup causes a full O(|BB|) basic block rescan.
787 // Doing all inserts in advance lets us capture all the new instructions in
788 // just a single rescan.
789 for (AllocaInst *AI : Allocas) {
790 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
791 assert(AI->getParent()->getParent() == &F &&
792 "All allocas should be in the same function, which is same as DF!");
794 }
795
796 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
797 AllocaInst *AI = Allocas[AllocaNum];
798
799 if (AI->use_empty()) {
800 // If there are no uses of the alloca, just delete it now.
801 AI->eraseFromParent();
802
803 // Remove the alloca from the Allocas list, since it has been processed
804 RemoveFromAllocasList(AllocaNum);
805 ++NumDeadAlloca;
806 continue;
807 }
808
809 // Calculate the set of read and write-locations for each alloca. This is
810 // analogous to finding the 'uses' and 'definitions' of each variable.
811 Info.AnalyzeAlloca(AI);
812
813 // If there is only a single store to this value, replace any loads of
814 // it that are directly dominated by the definition with the value stored.
815 if (Info.DefiningBlocks.size() == 1) {
816 if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC,
817 &DVRAssignsToDelete)) {
818 // The alloca has been processed, move on.
819 RemoveFromAllocasList(AllocaNum);
820 ++NumSingleStore;
821 continue;
822 }
823 }
824
825 // If the alloca is only read and written in one basic block, just perform a
826 // linear sweep over the block to eliminate it.
827 if (Info.OnlyUsedInOneBlock &&
828 promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC,
829 &DVRAssignsToDelete)) {
830 // The alloca has been processed, move on.
831 RemoveFromAllocasList(AllocaNum);
832 continue;
833 }
834
835 // Initialize BBNumPreds lazily
836 if (BBNumPreds.empty())
837 BBNumPreds.resize(F.getMaxBlockNumber());
838
839 // Remember the dbg.declare record describing this alloca, if any.
840 if (!Info.AssignmentTracking.empty())
841 AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
842 if (!Info.DPUsers.empty())
843 AllocaDPUsers[AllocaNum] = Info.DPUsers;
844 AllocaValueTypes[AllocaNum] = Info.ValueType;
845
846 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
847 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
848
849 // Unique the set of defining blocks for efficient lookup.
850 SmallPtrSet<BasicBlock *, 32> DefBlocks(llvm::from_range,
851 Info.DefiningBlocks);
852
853 // Determine which blocks the value is live in. These are blocks which lead
854 // to uses.
855 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
856 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
857
858 // At this point, we're committed to promoting the alloca using IDF's, and
859 // the standard SSA construction algorithm. Determine which blocks need phi
860 // nodes and see if we can optimize out some work by avoiding insertion of
861 // dead phi nodes.
862 IDF.setLiveInBlocks(LiveInBlocks);
863 IDF.setDefiningBlocks(DefBlocks);
865 IDF.calculate(PHIBlocks);
866 llvm::sort(PHIBlocks, [](BasicBlock *A, BasicBlock *B) {
867 return A->getNumber() < B->getNumber();
868 });
869
870 unsigned CurrentVersion = 0;
871 for (BasicBlock *BB : PHIBlocks)
872 QueuePhiNode(BB, AllocaNum, CurrentVersion);
873 }
874
875 if (Allocas.empty()) {
876 cleanUpDbgAssigns();
877 return; // All of the allocas must have been trivial!
878 }
879 LBI.clear();
880
881 // Set the incoming values for the basic block to be null values for all of
882 // the alloca's. We do this in case there is a load of a value that has not
883 // been stored yet. In this case, it will get this null value.
884 IncomingVals.resize(Allocas.size());
885 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
886 IncomingVals.init(i, UndefValue::get(AllocaValueTypes[i]));
887
888 // When handling debug info, treat all incoming values as if they have
889 // compiler-generated (empty) locations, representing the uninitialized
890 // alloca, until proven otherwise.
891 IncomingLocs.resize(Allocas.size());
892 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
893 IncomingLocs.init(i, DebugLoc::getCompilerGenerated());
894
895 // The renamer uses the Visited set to avoid infinite loops.
896 Visited.resize(F.getMaxBlockNumber(), false);
897
898 // Add the entry block to the worklist, with a null predecessor.
899 pushToWorklist(&F.front(), nullptr);
900
901 do {
902 RenamePassData RPD = popFromWorklist();
903 RenamePass(RPD.BB, RPD.Pred);
904 } while (!Worklist.empty());
905
906 // Remove the allocas themselves from the function.
907 for (Instruction *A : Allocas) {
908 // Remove dbg.assigns linked to the alloca as these are now redundant.
910 // If there are any uses of the alloca instructions left, they must be in
911 // unreachable basic blocks that were not processed by walking the dominator
912 // tree. Just delete the users now.
913 if (!A->use_empty())
914 A->replaceAllUsesWith(PoisonValue::get(A->getType()));
915 A->eraseFromParent();
916 }
917
918 // Remove alloca's dbg.declare intrinsics from the function.
919 for (auto &DbgUsers : AllocaDPUsers) {
920 for (DbgVariableRecord *DbgItem : DbgUsers)
921 if (DbgItem->isAddressOfVariable() ||
922 DbgItem->getExpression()->startsWithDeref())
923 DbgItem->eraseFromParent();
924 }
925
926 // Loop over all of the PHI nodes and see if there are any that we can get
927 // rid of because they merge all of the same incoming values. This can
928 // happen due to undef values coming into the PHI nodes. This process is
929 // iterative, because eliminating one PHI node can cause others to be removed.
930 bool EliminatedAPHI = true;
931 while (EliminatedAPHI) {
932 EliminatedAPHI = false;
933
934 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
935 // simplify and RAUW them as we go. If it was not, we could add uses to
936 // the values we replace with in a non-deterministic order, thus creating
937 // non-deterministic def->use chains.
938 EliminatedAPHI = NewPhiNodes.remove_if([&](const auto &Entry) {
939 PHINode *PN = Entry.second;
940 // If this PHI node merges one value and/or undefs, get the value.
941 if (Value *V = simplifyInstruction(PN, SQ)) {
942 PN->replaceAllUsesWith(V);
943 PN->eraseFromParent();
944 return true;
945 }
946 return false;
947 });
948 }
949
950 // At this point, the renamer has added entries to PHI nodes for all reachable
951 // code. Unfortunately, there may be unreachable blocks which the renamer
952 // hasn't traversed. If this is the case, the PHI nodes may not
953 // have incoming values for all predecessors. Loop over all PHI nodes we have
954 // created, inserting poison values if they are missing any incoming values.
955 for (const auto &PhiNode : NewPhiNodes) {
956 // We want to do this once per basic block. As such, only process a block
957 // when we find the PHI that is the first entry in the block.
958 PHINode *SomePHI = PhiNode.second;
959 BasicBlock *BB = SomePHI->getParent();
960 if (&BB->front() != SomePHI)
961 continue;
962
963 // Only do work here if there the PHI nodes are missing incoming values. We
964 // know that all PHI nodes that were inserted in a block will have the same
965 // number of incoming values, so we can just check any of them.
966 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
967 continue;
968
969 // Get the preds for BB.
970 SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
971
972 // Ok, now we know that all of the PHI nodes are missing entries for some
973 // basic blocks. Start by sorting the incoming predecessors for efficient
974 // access.
975 auto CompareBBNumbers = [](BasicBlock *A, BasicBlock *B) {
976 return A->getNumber() < B->getNumber();
977 };
978 llvm::sort(Preds, CompareBBNumbers);
979
980 // Now we loop through all BB's which have entries in SomePHI and remove
981 // them from the Preds list.
982 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
983 // Do a log(n) search of the Preds list for the entry we want.
985 Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
986 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
987 "PHI node has entry for a block which is not a predecessor!");
988
989 // Remove the entry
990 Preds.erase(EntIt);
991 }
992
993 // At this point, the blocks left in the preds list must have dummy
994 // entries inserted into every PHI nodes for the block. Update all the phi
995 // nodes in this block that we are inserting (there could be phis before
996 // mem2reg runs).
997 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
998 BasicBlock::iterator BBI = BB->begin();
999 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
1000 SomePHI->getNumIncomingValues() == NumBadPreds) {
1001 Value *PoisonVal = PoisonValue::get(SomePHI->getType());
1002 for (BasicBlock *Pred : Preds)
1003 SomePHI->addIncoming(PoisonVal, Pred);
1004 }
1005 }
1006
1007 NewPhiNodes.clear();
1008 cleanUpDbgAssigns();
1009}
1010
1011/// Determine which blocks the value is live in.
1012///
1013/// These are blocks which lead to uses. Knowing this allows us to avoid
1014/// inserting PHI nodes into blocks which don't lead to uses (thus, the
1015/// inserted phi nodes would be dead).
1016void PromoteMem2Reg::ComputeLiveInBlocks(
1017 AllocaInst *AI, AllocaInfo &Info,
1018 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
1019 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
1020 // To determine liveness, we must iterate through the predecessors of blocks
1021 // where the def is live. Blocks are added to the worklist if we need to
1022 // check their predecessors. Start with all the using blocks.
1023 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
1024 Info.UsingBlocks.end());
1025
1026 // If any of the using blocks is also a definition block, check to see if the
1027 // definition occurs before or after the use. If it happens before the use,
1028 // the value isn't really live-in.
1029 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
1030 BasicBlock *BB = LiveInBlockWorklist[i];
1031 if (!DefBlocks.count(BB))
1032 continue;
1033
1034 // Okay, this is a block that both uses and defines the value. If the first
1035 // reference to the alloca is a def (store), then we know it isn't live-in.
1036 for (BasicBlock::iterator I = BB->begin();; ++I) {
1037 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1038 if (SI->getOperand(1) != AI)
1039 continue;
1040
1041 // We found a store to the alloca before a load. The alloca is not
1042 // actually live-in here.
1043 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
1044 LiveInBlockWorklist.pop_back();
1045 --i;
1046 --e;
1047 break;
1048 }
1049
1050 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1051 // Okay, we found a load before a store to the alloca. It is actually
1052 // live into this block.
1053 if (LI->getOperand(0) == AI)
1054 break;
1055 }
1056 }
1057
1058 // Now that we have a set of blocks where the phi is live-in, recursively add
1059 // their predecessors until we find the full region the value is live.
1060 while (!LiveInBlockWorklist.empty()) {
1061 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1062
1063 // The block really is live in here, insert it into the set. If already in
1064 // the set, then it has already been processed.
1065 if (!LiveInBlocks.insert(BB).second)
1066 continue;
1067
1068 // Since the value is live into BB, it is either defined in a predecessor or
1069 // live into it to. Add the preds to the worklist unless they are a
1070 // defining block.
1071 for (BasicBlock *P : predecessors(BB)) {
1072 // The value is not live into a predecessor if it defines the value.
1073 if (DefBlocks.count(P))
1074 continue;
1075
1076 // Otherwise it is, add to the worklist.
1077 LiveInBlockWorklist.push_back(P);
1078 }
1079 }
1080}
1081
1082/// Queue a phi-node to be added to a basic-block for a specific Alloca.
1083///
1084/// Returns true if there wasn't already a phi-node for that variable
1085bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
1086 unsigned &Version) {
1087 // Look up the basic-block in question.
1088 PHINode *&PN = NewPhiNodes[std::make_pair(BB->getNumber(), AllocaNo)];
1089
1090 // If the BB already has a phi node added for the i'th alloca then we're done!
1091 if (PN)
1092 return false;
1093
1094 // Create a PhiNode using the type from loads/stores... and add the phi-node
1095 // to the BasicBlock.
1096 PN = PHINode::Create(AllocaValueTypes[AllocaNo], getNumPreds(BB),
1097 Allocas[AllocaNo]->getName() + "." + Twine(Version++));
1098 PN->insertBefore(BB->begin());
1099 ++NumPHIInsert;
1100 PhiToAllocaMap[PN] = AllocaNo;
1101 return true;
1102}
1103
1104/// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
1105/// create a merged location incorporating \p DL, or to set \p DL directly.
1107 bool ApplyMergedLoc) {
1108 if (ApplyMergedLoc)
1110 else
1111 PN->setDebugLoc(DL);
1112}
1113
1114/// Recursively traverse the CFG of the function, renaming loads and
1115/// stores to the allocas which we are promoting.
1116///
1117/// IncomingVals indicates what value each Alloca contains on exit from the
1118/// predecessor block Pred.
1119void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred) {
1120 // If we are inserting any phi nodes into this BB, they will already be in the
1121 // block.
1122 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1123 // If we have PHI nodes to update, compute the number of edges from Pred to
1124 // BB.
1125 if (PhiToAllocaMap.count(APN)) {
1126 // We want to be able to distinguish between PHI nodes being inserted by
1127 // this invocation of mem2reg from those phi nodes that already existed in
1128 // the IR before mem2reg was run. We determine that APN is being inserted
1129 // because it is missing incoming edges. All other PHI nodes being
1130 // inserted by this pass of mem2reg will have the same number of incoming
1131 // operands so far. Remember this count.
1132 unsigned NewPHINumOperands = APN->getNumOperands();
1133
1134 unsigned NumEdges = llvm::count(successors(Pred), BB);
1135 assert(NumEdges && "Must be at least one edge from Pred to BB!");
1136
1137 // Add entries for all the phis.
1138 BasicBlock::iterator PNI = BB->begin();
1139 do {
1140 unsigned AllocaNo = PhiToAllocaMap[APN];
1141
1142 // Update the location of the phi node.
1143 updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
1144 APN->getNumIncomingValues() > 0);
1145
1146 // Add N incoming values to the PHI node.
1147 for (unsigned i = 0; i != NumEdges; ++i)
1148 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1149
1150 // For the sequence `return X > 0.0 ? X : -X`, it is expected that this
1151 // results in fabs intrinsic. However, without no-signed-zeros(nsz) flag
1152 // on the phi node generated at this stage, fabs folding does not
1153 // happen. So, we try to infer nsz flag from the function attributes to
1154 // enable this fabs folding.
1155 if (isa<FPMathOperator>(APN) && NoSignedZeros)
1156 APN->setHasNoSignedZeros(true);
1157
1158 // The currently active variable for this block is now the PHI.
1159 IncomingVals.set(AllocaNo, APN);
1160 AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1161 for (DbgVariableRecord *DbgItem : AllocaDPUsers[AllocaNo])
1162 if (DbgItem->isAddressOfVariable())
1163 ConvertDebugDeclareToDebugValue(DbgItem, APN, DIB);
1164
1165 // Get the next phi node.
1166 ++PNI;
1167 APN = dyn_cast<PHINode>(PNI);
1168 if (!APN)
1169 break;
1170
1171 // Verify that it is missing entries. If not, it is not being inserted
1172 // by this mem2reg invocation so we want to ignore it.
1173 } while (APN->getNumOperands() == NewPHINumOperands);
1174 }
1175 }
1176
1177 // Don't revisit blocks.
1178 if (Visited.test(BB->getNumber()))
1179 return;
1180 Visited.set(BB->getNumber());
1181
1182 for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
1183 Instruction *I = &*II++; // get the instruction, increment iterator
1184
1185 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1186 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1187 if (!Src)
1188 continue;
1189
1190 auto AI = AllocaLookup.find(Src);
1191 if (AI == AllocaLookup.end())
1192 continue;
1193
1194 Value *V = IncomingVals[AI->second];
1195 convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
1196
1197 // Anything using the load now uses the current value.
1198 LI->replaceAllUsesWith(V);
1199 LI->eraseFromParent();
1200 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1201 // Delete this instruction and mark the name as the current holder of the
1202 // value
1203 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1204 if (!Dest)
1205 continue;
1206
1207 auto ai = AllocaLookup.find(Dest);
1208 if (ai == AllocaLookup.end())
1209 continue;
1210
1211 // what value were we writing?
1212 unsigned AllocaNo = ai->second;
1213 IncomingVals.set(AllocaNo, SI->getOperand(0));
1214
1215 // Record debuginfo for the store before removing it.
1216 IncomingLocs.set(AllocaNo, SI->getDebugLoc());
1217 AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB,
1218 &DVRAssignsToDelete);
1219 for (DbgVariableRecord *DbgItem : AllocaDPUsers[ai->second])
1220 if (DbgItem->isAddressOfVariable())
1221 ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
1222 SI->eraseFromParent();
1223 }
1224 }
1225
1226 // 'Recurse' to our successors.
1227
1228 // Keep track of the successors so we don't visit the same successor twice
1229 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1230
1231 for (BasicBlock *S : reverse(successors(BB)))
1232 if (VisitedSuccs.insert(S).second)
1233 pushToWorklist(S, BB);
1234}
1235
1237 AssumptionCache *AC) {
1238 // If there is nothing to do, bail out...
1239 if (Allocas.empty())
1240 return;
1241
1242 PromoteMem2Reg(Allocas, DT, AC).run();
1243}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static DeltaTreeNode * getRoot(void *Root)
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
static void convertMetadataToAssumes(LoadInst *LI, Value *Val, const DataLayout &DL, AssumptionCache *AC, const DominatorTree *DT)
static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL, DominatorTree &DT, AssumptionCache *AC, SmallPtrSet< DbgVariableRecord *, 8 > *DVRAssignsToDelete)
Many allocas are only used within a single basic block.
static void removeIntrinsicUsers(AllocaInst *AI)
static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL, bool ApplyMergedLoc)
Update the debug location of a phi.
static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL, DominatorTree &DT, AssumptionCache *AC, SmallPtrSet< DbgVariableRecord *, 8 > *DVRAssignsToDelete)
Rewrite as many loads as possible given a single store.
static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI)
Given a LoadInst LI this adds assume(LI != null) after it.
static StringRef getName(Value *V)
static void ComputeLiveInBlocks(const SmallPtrSetImpl< BasicBlock * > &UsingBlocks, const SmallPtrSetImpl< BasicBlock * > &DefBlocks, SmallPtrSetImpl< BasicBlock * > &LiveInBlocks, PredIteratorCache &PredCache)
Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ ICMP_NE
not equal
Definition InstrTypes.h:762
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DWARF expression.
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void eraseFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
bool isValueOfVariable() const
Determine if this describes the value of a local variable.
bool isAddressOfVariable() const
Does this describe the address of a local variable.
DIExpression * getExpression() const
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
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
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:946
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 representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
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...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
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
An instruction for reading from memory.
Value * getPointerOperand()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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 PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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
Value * getOperand(unsigned i) const
Definition User.h:207
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 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
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
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.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
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
This is an optimization pass for GlobalISel generic memory operations.
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
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...
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)
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1705
constexpr from_range_t from_range
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
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1656
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IDFCalculator< false > ForwardIDFCalculator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
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 predecessors(const MachineBasicBlock *BB)
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
const DataLayout & DL
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455