xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/Local.cpp (revision 71ac745d76c3ba442e753daff1870893f272b29d)
1044eb2f6SDimitry Andric //===- Local.cpp - Functions to perform local transformations -------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This family of functions perform various local transformations to the
10009b1c42SEd Schouten // program.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "llvm/Transforms/Utils/Local.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/APInt.h"
161e7804dbSRoman Divacky #include "llvm/ADT/DenseMap.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/DenseMapInfo.h"
183a0822f0SDimitry Andric #include "llvm/ADT/DenseSet.h"
193a0822f0SDimitry Andric #include "llvm/ADT/Hashing.h"
204a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
21dd58ef01SDimitry Andric #include "llvm/ADT/SetVector.h"
22009b1c42SEd Schouten #include "llvm/ADT/SmallPtrSet.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
24f8af5cf6SDimitry Andric #include "llvm/ADT/Statistic.h"
25cfca06d7SDimitry Andric #include "llvm/Analysis/AssumeBundleQueries.h"
26044eb2f6SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
27e6d15924SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
28907da171SRoman Divacky #include "llvm/Analysis/InstructionSimplify.h"
297ab83427SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
30d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
31044eb2f6SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
32cf099d11SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
33d8e91e46SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
34044eb2f6SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
35044eb2f6SDimitry Andric #include "llvm/IR/Argument.h"
36044eb2f6SDimitry Andric #include "llvm/IR/Attributes.h"
37044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
385ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
39044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
4008bbd35aSDimitry Andric #include "llvm/IR/ConstantRange.h"
414a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
425ca98fd9SDimitry Andric #include "llvm/IR/DIBuilder.h"
434a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
44ecbca9f5SDimitry Andric #include "llvm/IR/DebugInfo.h"
45044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
46044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
474a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
485ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
497fa27ce4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
50044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
515ca98fd9SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
52044eb2f6SDimitry Andric #include "llvm/IR/GlobalObject.h"
534a16efa3SDimitry Andric #include "llvm/IR/IRBuilder.h"
54044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
55044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
564a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
574a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
584a16efa3SDimitry Andric #include "llvm/IR/Intrinsics.h"
59e3b55780SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
60044eb2f6SDimitry Andric #include "llvm/IR/LLVMContext.h"
614a16efa3SDimitry Andric #include "llvm/IR/MDBuilder.h"
62ac9a064cSDimitry Andric #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
634a16efa3SDimitry Andric #include "llvm/IR/Metadata.h"
64044eb2f6SDimitry Andric #include "llvm/IR/Module.h"
6501095a5dSDimitry Andric #include "llvm/IR/PatternMatch.h"
66e3b55780SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
67044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
68044eb2f6SDimitry Andric #include "llvm/IR/Use.h"
69044eb2f6SDimitry Andric #include "llvm/IR/User.h"
70044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
715ca98fd9SDimitry Andric #include "llvm/IR/ValueHandle.h"
72044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
73b1c73532SDimitry Andric #include "llvm/Support/CommandLine.h"
74907da171SRoman Divacky #include "llvm/Support/Debug.h"
75044eb2f6SDimitry Andric #include "llvm/Support/ErrorHandling.h"
7612f3ca4cSDimitry Andric #include "llvm/Support/KnownBits.h"
77907da171SRoman Divacky #include "llvm/Support/raw_ostream.h"
78cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
79eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
80044eb2f6SDimitry Andric #include <algorithm>
81044eb2f6SDimitry Andric #include <cassert>
82044eb2f6SDimitry Andric #include <cstdint>
83044eb2f6SDimitry Andric #include <iterator>
84044eb2f6SDimitry Andric #include <map>
85e3b55780SDimitry Andric #include <optional>
86044eb2f6SDimitry Andric #include <utility>
87044eb2f6SDimitry Andric 
88009b1c42SEd Schouten using namespace llvm;
8901095a5dSDimitry Andric using namespace llvm::PatternMatch;
90009b1c42SEd Schouten 
91b1c73532SDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
92b1c73532SDimitry Andric 
935ca98fd9SDimitry Andric #define DEBUG_TYPE "local"
945ca98fd9SDimitry Andric 
95f8af5cf6SDimitry Andric STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
96b60736ecSDimitry Andric STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
97b60736ecSDimitry Andric 
98b60736ecSDimitry Andric static cl::opt<bool> PHICSEDebugHash(
99b60736ecSDimitry Andric     "phicse-debug-hash",
100b60736ecSDimitry Andric #ifdef EXPENSIVE_CHECKS
101b60736ecSDimitry Andric     cl::init(true),
102b60736ecSDimitry Andric #else
103b60736ecSDimitry Andric     cl::init(false),
104b60736ecSDimitry Andric #endif
105b60736ecSDimitry Andric     cl::Hidden,
106b60736ecSDimitry Andric     cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
107b60736ecSDimitry Andric              "function is well-behaved w.r.t. its isEqual predicate"));
108b60736ecSDimitry Andric 
109b60736ecSDimitry Andric static cl::opt<unsigned> PHICSENumPHISmallSize(
110b60736ecSDimitry Andric     "phicse-num-phi-smallsize", cl::init(32), cl::Hidden,
111b60736ecSDimitry Andric     cl::desc(
112b60736ecSDimitry Andric         "When the basic block contains not more than this number of PHI nodes, "
113b60736ecSDimitry Andric         "perform a (faster!) exhaustive search instead of set-driven one."));
114f8af5cf6SDimitry Andric 
115e6d15924SDimitry Andric // Max recursion depth for collectBitParts used when detecting bswap and
116344a3780SDimitry Andric // bitreverse idioms.
117344a3780SDimitry Andric static const unsigned BitPartRecursionMaxDepth = 48;
118e6d15924SDimitry Andric 
119009b1c42SEd Schouten //===----------------------------------------------------------------------===//
120009b1c42SEd Schouten //  Local constant propagation.
121009b1c42SEd Schouten //
122009b1c42SEd Schouten 
12356fe8f14SDimitry Andric /// ConstantFoldTerminator - If a terminator instruction is predicated on a
12456fe8f14SDimitry Andric /// constant value, convert it into an unconditional branch to the constant
12556fe8f14SDimitry Andric /// destination.  This is a nontrivial operation because the successors of this
12656fe8f14SDimitry Andric /// basic block must have their PHI nodes updated.
12756fe8f14SDimitry Andric /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
12856fe8f14SDimitry Andric /// conditions and indirectbr addresses this might make dead if
12956fe8f14SDimitry Andric /// DeleteDeadConditions is true.
ConstantFoldTerminator(BasicBlock * BB,bool DeleteDeadConditions,const TargetLibraryInfo * TLI,DomTreeUpdater * DTU)130522600a2SDimitry Andric bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
131eb11fae6SDimitry Andric                                   const TargetLibraryInfo *TLI,
132d8e91e46SDimitry Andric                                   DomTreeUpdater *DTU) {
133d8e91e46SDimitry Andric   Instruction *T = BB->getTerminator();
13456fe8f14SDimitry Andric   IRBuilder<> Builder(T);
135009b1c42SEd Schouten 
136009b1c42SEd Schouten   // Branch - See if we are conditional jumping on constant
137eb11fae6SDimitry Andric   if (auto *BI = dyn_cast<BranchInst>(T)) {
138009b1c42SEd Schouten     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
139b60736ecSDimitry Andric 
140009b1c42SEd Schouten     BasicBlock *Dest1 = BI->getSuccessor(0);
141009b1c42SEd Schouten     BasicBlock *Dest2 = BI->getSuccessor(1);
142009b1c42SEd Schouten 
14336bf506aSRoman Divacky     if (Dest2 == Dest1) {       // Conditional branch to same location?
144009b1c42SEd Schouten       // This branch matches something like this:
145009b1c42SEd Schouten       //     br bool %cond, label %Dest, label %Dest
146009b1c42SEd Schouten       // and changes it into:  br label %Dest
147009b1c42SEd Schouten 
148009b1c42SEd Schouten       // Let the basic block know that we are letting go of one copy of it.
149009b1c42SEd Schouten       assert(BI->getParent() && "Terminator not inserted in block!");
150009b1c42SEd Schouten       Dest1->removePredecessor(BI->getParent());
151009b1c42SEd Schouten 
152cf099d11SDimitry Andric       // Replace the conditional branch with an unconditional one.
153344a3780SDimitry Andric       BranchInst *NewBI = Builder.CreateBr(Dest1);
154344a3780SDimitry Andric 
155344a3780SDimitry Andric       // Transfer the metadata to the new branch instruction.
156344a3780SDimitry Andric       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
157344a3780SDimitry Andric                                 LLVMContext::MD_annotation});
158344a3780SDimitry Andric 
15956fe8f14SDimitry Andric       Value *Cond = BI->getCondition();
160cf099d11SDimitry Andric       BI->eraseFromParent();
16156fe8f14SDimitry Andric       if (DeleteDeadConditions)
162522600a2SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
163009b1c42SEd Schouten       return true;
164009b1c42SEd Schouten     }
165b60736ecSDimitry Andric 
166b60736ecSDimitry Andric     if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
167b60736ecSDimitry Andric       // Are we branching on constant?
168b60736ecSDimitry Andric       // YES.  Change to unconditional branch...
169b60736ecSDimitry Andric       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
170b60736ecSDimitry Andric       BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
171b60736ecSDimitry Andric 
172b60736ecSDimitry Andric       // Let the basic block know that we are letting go of it.  Based on this,
173b60736ecSDimitry Andric       // it will adjust it's PHI nodes.
174b60736ecSDimitry Andric       OldDest->removePredecessor(BB);
175b60736ecSDimitry Andric 
176b60736ecSDimitry Andric       // Replace the conditional branch with an unconditional one.
177344a3780SDimitry Andric       BranchInst *NewBI = Builder.CreateBr(Destination);
178344a3780SDimitry Andric 
179344a3780SDimitry Andric       // Transfer the metadata to the new branch instruction.
180344a3780SDimitry Andric       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
181344a3780SDimitry Andric                                 LLVMContext::MD_annotation});
182344a3780SDimitry Andric 
183b60736ecSDimitry Andric       BI->eraseFromParent();
184b60736ecSDimitry Andric       if (DTU)
185b60736ecSDimitry Andric         DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
186b60736ecSDimitry Andric       return true;
187b60736ecSDimitry Andric     }
188b60736ecSDimitry Andric 
18936bf506aSRoman Divacky     return false;
19036bf506aSRoman Divacky   }
19136bf506aSRoman Divacky 
192eb11fae6SDimitry Andric   if (auto *SI = dyn_cast<SwitchInst>(T)) {
1935a5ac124SDimitry Andric     // If we are switching on a constant, we can convert the switch to an
1945a5ac124SDimitry Andric     // unconditional branch.
195eb11fae6SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
1965a5ac124SDimitry Andric     BasicBlock *DefaultDest = SI->getDefaultDest();
1975a5ac124SDimitry Andric     BasicBlock *TheOnlyDest = DefaultDest;
1985a5ac124SDimitry Andric 
1995a5ac124SDimitry Andric     // If the default is unreachable, ignore it when searching for TheOnlyDest.
2005a5ac124SDimitry Andric     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
2015a5ac124SDimitry Andric         SI->getNumCases() > 0) {
20271d5a254SDimitry Andric       TheOnlyDest = SI->case_begin()->getCaseSuccessor();
2035a5ac124SDimitry Andric     }
204009b1c42SEd Schouten 
205b60736ecSDimitry Andric     bool Changed = false;
206b60736ecSDimitry Andric 
20736bf506aSRoman Divacky     // Figure out which case it goes to.
2087fa27ce4SDimitry Andric     for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {
209009b1c42SEd Schouten       // Found case matching a constant operand?
2107fa27ce4SDimitry Andric       if (It->getCaseValue() == CI) {
2117fa27ce4SDimitry Andric         TheOnlyDest = It->getCaseSuccessor();
212009b1c42SEd Schouten         break;
213009b1c42SEd Schouten       }
214009b1c42SEd Schouten 
215009b1c42SEd Schouten       // Check to see if this branch is going to the same place as the default
216009b1c42SEd Schouten       // dest.  If so, eliminate it as an explicit compare.
2177fa27ce4SDimitry Andric       if (It->getCaseSuccessor() == DefaultDest) {
218e3b55780SDimitry Andric         MDNode *MD = getValidBranchWeightMDNode(*SI);
2195ca98fd9SDimitry Andric         unsigned NCases = SI->getNumCases();
2205ca98fd9SDimitry Andric         // Fold the case metadata into the default if there will be any branches
2215ca98fd9SDimitry Andric         // left, unless the metadata doesn't match the switch.
222e3b55780SDimitry Andric         if (NCases > 1 && MD) {
223522600a2SDimitry Andric           // Collect branch weights into a vector.
224522600a2SDimitry Andric           SmallVector<uint32_t, 8> Weights;
225e3b55780SDimitry Andric           extractBranchWeights(MD, Weights);
226e3b55780SDimitry Andric 
227522600a2SDimitry Andric           // Merge weight of this case to the default weight.
2287fa27ce4SDimitry Andric           unsigned Idx = It->getCaseIndex();
229e3b55780SDimitry Andric           // TODO: Add overflow check.
2307fa27ce4SDimitry Andric           Weights[0] += Weights[Idx + 1];
231522600a2SDimitry Andric           // Remove weight for this case.
2327fa27ce4SDimitry Andric           std::swap(Weights[Idx + 1], Weights.back());
233522600a2SDimitry Andric           Weights.pop_back();
234ac9a064cSDimitry Andric           setBranchWeights(*SI, Weights, hasBranchWeightOrigin(MD));
235522600a2SDimitry Andric         }
23636bf506aSRoman Divacky         // Remove this entry.
237eb11fae6SDimitry Andric         BasicBlock *ParentBB = SI->getParent();
238eb11fae6SDimitry Andric         DefaultDest->removePredecessor(ParentBB);
2397fa27ce4SDimitry Andric         It = SI->removeCase(It);
2407fa27ce4SDimitry Andric         End = SI->case_end();
241e3b55780SDimitry Andric 
242e3b55780SDimitry Andric         // Removing this case may have made the condition constant. In that
243e3b55780SDimitry Andric         // case, update CI and restart iteration through the cases.
244e3b55780SDimitry Andric         if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
245e3b55780SDimitry Andric           CI = NewCI;
2467fa27ce4SDimitry Andric           It = SI->case_begin();
247e3b55780SDimitry Andric         }
248e3b55780SDimitry Andric 
249b60736ecSDimitry Andric         Changed = true;
250009b1c42SEd Schouten         continue;
251009b1c42SEd Schouten       }
252009b1c42SEd Schouten 
253009b1c42SEd Schouten       // Otherwise, check to see if the switch only branches to one destination.
254009b1c42SEd Schouten       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
255009b1c42SEd Schouten       // destinations.
2567fa27ce4SDimitry Andric       if (It->getCaseSuccessor() != TheOnlyDest)
25771d5a254SDimitry Andric         TheOnlyDest = nullptr;
25871d5a254SDimitry Andric 
25971d5a254SDimitry Andric       // Increment this iterator as we haven't removed the case.
2607fa27ce4SDimitry Andric       ++It;
261009b1c42SEd Schouten     }
262009b1c42SEd Schouten 
263009b1c42SEd Schouten     if (CI && !TheOnlyDest) {
264009b1c42SEd Schouten       // Branching on a constant, but not any of the cases, go to the default
265009b1c42SEd Schouten       // successor.
266009b1c42SEd Schouten       TheOnlyDest = SI->getDefaultDest();
267009b1c42SEd Schouten     }
268009b1c42SEd Schouten 
269009b1c42SEd Schouten     // If we found a single destination that we can fold the switch into, do so
270009b1c42SEd Schouten     // now.
271009b1c42SEd Schouten     if (TheOnlyDest) {
27236bf506aSRoman Divacky       // Insert the new branch.
27356fe8f14SDimitry Andric       Builder.CreateBr(TheOnlyDest);
274009b1c42SEd Schouten       BasicBlock *BB = SI->getParent();
275b60736ecSDimitry Andric 
276344a3780SDimitry Andric       SmallSet<BasicBlock *, 8> RemovedSuccessors;
277009b1c42SEd Schouten 
278009b1c42SEd Schouten       // Remove entries from PHI nodes which we no longer branch to...
279b60736ecSDimitry Andric       BasicBlock *SuccToKeep = TheOnlyDest;
280d8e91e46SDimitry Andric       for (BasicBlock *Succ : successors(SI)) {
281b60736ecSDimitry Andric         if (DTU && Succ != TheOnlyDest)
282b60736ecSDimitry Andric           RemovedSuccessors.insert(Succ);
283009b1c42SEd Schouten         // Found case matching a constant operand?
284b60736ecSDimitry Andric         if (Succ == SuccToKeep) {
285b60736ecSDimitry Andric           SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
286eb11fae6SDimitry Andric         } else {
287009b1c42SEd Schouten           Succ->removePredecessor(BB);
288eb11fae6SDimitry Andric         }
289009b1c42SEd Schouten       }
290009b1c42SEd Schouten 
29136bf506aSRoman Divacky       // Delete the old switch.
29256fe8f14SDimitry Andric       Value *Cond = SI->getCondition();
29356fe8f14SDimitry Andric       SI->eraseFromParent();
29456fe8f14SDimitry Andric       if (DeleteDeadConditions)
295522600a2SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
296b60736ecSDimitry Andric       if (DTU) {
297b60736ecSDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
298b60736ecSDimitry Andric         Updates.reserve(RemovedSuccessors.size());
299b60736ecSDimitry Andric         for (auto *RemovedSuccessor : RemovedSuccessors)
300b60736ecSDimitry Andric           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
301b60736ecSDimitry Andric         DTU->applyUpdates(Updates);
302b60736ecSDimitry Andric       }
303009b1c42SEd Schouten       return true;
30436bf506aSRoman Divacky     }
30536bf506aSRoman Divacky 
30663faed5bSDimitry Andric     if (SI->getNumCases() == 1) {
307009b1c42SEd Schouten       // Otherwise, we can fold this switch into a conditional branch
308009b1c42SEd Schouten       // instruction if it has only one non-default destination.
30971d5a254SDimitry Andric       auto FirstCase = *SI->case_begin();
31056fe8f14SDimitry Andric       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
311f8af5cf6SDimitry Andric           FirstCase.getCaseValue(), "cond");
31256fe8f14SDimitry Andric 
31336bf506aSRoman Divacky       // Insert the new branch.
314522600a2SDimitry Andric       BranchInst *NewBr = Builder.CreateCondBr(Cond,
315522600a2SDimitry Andric                                                FirstCase.getCaseSuccessor(),
31663faed5bSDimitry Andric                                                SI->getDefaultDest());
317e3b55780SDimitry Andric       SmallVector<uint32_t> Weights;
318e3b55780SDimitry Andric       if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
319e3b55780SDimitry Andric         uint32_t DefWeight = Weights[0];
320e3b55780SDimitry Andric         uint32_t CaseWeight = Weights[1];
321522600a2SDimitry Andric         // The TrueWeight should be the weight for the single case of SI.
322522600a2SDimitry Andric         NewBr->setMetadata(LLVMContext::MD_prof,
323e3b55780SDimitry Andric                            MDBuilder(BB->getContext())
324e3b55780SDimitry Andric                                .createBranchWeights(CaseWeight, DefWeight));
325522600a2SDimitry Andric       }
326009b1c42SEd Schouten 
327dd58ef01SDimitry Andric       // Update make.implicit metadata to the newly-created conditional branch.
328dd58ef01SDimitry Andric       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
329dd58ef01SDimitry Andric       if (MakeImplicitMD)
330dd58ef01SDimitry Andric         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
331dd58ef01SDimitry Andric 
33236bf506aSRoman Divacky       // Delete the old switch.
333009b1c42SEd Schouten       SI->eraseFromParent();
334009b1c42SEd Schouten       return true;
335009b1c42SEd Schouten     }
336b60736ecSDimitry Andric     return Changed;
337009b1c42SEd Schouten   }
33836bf506aSRoman Divacky 
339eb11fae6SDimitry Andric   if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
34036bf506aSRoman Divacky     // indirectbr blockaddress(@F, @BB) -> br label @BB
341eb11fae6SDimitry Andric     if (auto *BA =
34236bf506aSRoman Divacky           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
34336bf506aSRoman Divacky       BasicBlock *TheOnlyDest = BA->getBasicBlock();
344344a3780SDimitry Andric       SmallSet<BasicBlock *, 8> RemovedSuccessors;
345eb11fae6SDimitry Andric 
34636bf506aSRoman Divacky       // Insert the new branch.
34756fe8f14SDimitry Andric       Builder.CreateBr(TheOnlyDest);
34836bf506aSRoman Divacky 
349b60736ecSDimitry Andric       BasicBlock *SuccToKeep = TheOnlyDest;
35036bf506aSRoman Divacky       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
351eb11fae6SDimitry Andric         BasicBlock *DestBB = IBI->getDestination(i);
352b60736ecSDimitry Andric         if (DTU && DestBB != TheOnlyDest)
353b60736ecSDimitry Andric           RemovedSuccessors.insert(DestBB);
354b60736ecSDimitry Andric         if (IBI->getDestination(i) == SuccToKeep) {
355b60736ecSDimitry Andric           SuccToKeep = nullptr;
356b60736ecSDimitry Andric         } else {
357b60736ecSDimitry Andric           DestBB->removePredecessor(BB);
358eb11fae6SDimitry Andric         }
35936bf506aSRoman Divacky       }
36056fe8f14SDimitry Andric       Value *Address = IBI->getAddress();
36136bf506aSRoman Divacky       IBI->eraseFromParent();
36256fe8f14SDimitry Andric       if (DeleteDeadConditions)
3631d5ae102SDimitry Andric         // Delete pointer cast instructions.
364522600a2SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
36536bf506aSRoman Divacky 
3661d5ae102SDimitry Andric       // Also zap the blockaddress constant if there are no users remaining,
3671d5ae102SDimitry Andric       // otherwise the destination is still marked as having its address taken.
3681d5ae102SDimitry Andric       if (BA->use_empty())
3691d5ae102SDimitry Andric         BA->destroyConstant();
3701d5ae102SDimitry Andric 
37136bf506aSRoman Divacky       // If we didn't find our destination in the IBI successor list, then we
37236bf506aSRoman Divacky       // have undefined behavior.  Replace the unconditional branch with an
37336bf506aSRoman Divacky       // 'unreachable' instruction.
374b60736ecSDimitry Andric       if (SuccToKeep) {
37536bf506aSRoman Divacky         BB->getTerminator()->eraseFromParent();
37636bf506aSRoman Divacky         new UnreachableInst(BB->getContext(), BB);
37736bf506aSRoman Divacky       }
37836bf506aSRoman Divacky 
379b60736ecSDimitry Andric       if (DTU) {
380b60736ecSDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
381b60736ecSDimitry Andric         Updates.reserve(RemovedSuccessors.size());
382b60736ecSDimitry Andric         for (auto *RemovedSuccessor : RemovedSuccessors)
383b60736ecSDimitry Andric           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
384b60736ecSDimitry Andric         DTU->applyUpdates(Updates);
385b60736ecSDimitry Andric       }
38636bf506aSRoman Divacky       return true;
38736bf506aSRoman Divacky     }
38836bf506aSRoman Divacky   }
38936bf506aSRoman Divacky 
390009b1c42SEd Schouten   return false;
391009b1c42SEd Schouten }
392009b1c42SEd Schouten 
393009b1c42SEd Schouten //===----------------------------------------------------------------------===//
394907da171SRoman Divacky //  Local dead code elimination.
395009b1c42SEd Schouten //
396009b1c42SEd Schouten 
397009b1c42SEd Schouten /// isInstructionTriviallyDead - Return true if the result produced by the
398009b1c42SEd Schouten /// instruction is not used, and the instruction has no side effects.
399009b1c42SEd Schouten ///
isInstructionTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)400522600a2SDimitry Andric bool llvm::isInstructionTriviallyDead(Instruction *I,
401522600a2SDimitry Andric                                       const TargetLibraryInfo *TLI) {
40271d5a254SDimitry Andric   if (!I->use_empty())
40371d5a254SDimitry Andric     return false;
40471d5a254SDimitry Andric   return wouldInstructionBeTriviallyDead(I, TLI);
40571d5a254SDimitry Andric }
40671d5a254SDimitry Andric 
wouldInstructionBeTriviallyDeadOnUnusedPaths(Instruction * I,const TargetLibraryInfo * TLI)40777fc4c14SDimitry Andric bool llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(
40877fc4c14SDimitry Andric     Instruction *I, const TargetLibraryInfo *TLI) {
40977fc4c14SDimitry Andric   // Instructions that are "markers" and have implied meaning on code around
41077fc4c14SDimitry Andric   // them (without explicit uses), are not dead on unused paths.
41177fc4c14SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
41277fc4c14SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::stacksave ||
41377fc4c14SDimitry Andric         II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
41477fc4c14SDimitry Andric         II->isLifetimeStartOrEnd())
41577fc4c14SDimitry Andric       return false;
41677fc4c14SDimitry Andric   return wouldInstructionBeTriviallyDead(I, TLI);
41777fc4c14SDimitry Andric }
41877fc4c14SDimitry Andric 
wouldInstructionBeTriviallyDead(const Instruction * I,const TargetLibraryInfo * TLI)419b1c73532SDimitry Andric bool llvm::wouldInstructionBeTriviallyDead(const Instruction *I,
42071d5a254SDimitry Andric                                            const TargetLibraryInfo *TLI) {
421d8e91e46SDimitry Andric   if (I->isTerminator())
42271d5a254SDimitry Andric     return false;
423009b1c42SEd Schouten 
424dd58ef01SDimitry Andric   // We don't want the landingpad-like instructions removed by anything this
425dd58ef01SDimitry Andric   // general.
426dd58ef01SDimitry Andric   if (I->isEHPad())
42730815c53SDimitry Andric     return false;
42830815c53SDimitry Andric 
4297fa27ce4SDimitry Andric   // We don't want debug info removed by anything this general.
4307fa27ce4SDimitry Andric   if (isa<DbgVariableIntrinsic>(I))
4316b943ff3SDimitry Andric     return false;
4327fa27ce4SDimitry Andric 
433b1c73532SDimitry Andric   if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
434eb11fae6SDimitry Andric     if (DLI->getLabel())
435eb11fae6SDimitry Andric       return false;
436eb11fae6SDimitry Andric     return true;
437eb11fae6SDimitry Andric   }
438009b1c42SEd Schouten 
4394b4fe385SDimitry Andric   if (auto *CB = dyn_cast<CallBase>(I))
4404b4fe385SDimitry Andric     if (isRemovableAlloc(CB, TLI))
4414b4fe385SDimitry Andric       return true;
4424b4fe385SDimitry Andric 
443e3b55780SDimitry Andric   if (!I->willReturn()) {
444e3b55780SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
445e3b55780SDimitry Andric     if (!II)
446b60736ecSDimitry Andric       return false;
447b60736ecSDimitry Andric 
448b1c73532SDimitry Andric     switch (II->getIntrinsicID()) {
449b1c73532SDimitry Andric     case Intrinsic::experimental_guard: {
450b1c73532SDimitry Andric       // Guards on true are operationally no-ops.  In the future we can
451b1c73532SDimitry Andric       // consider more sophisticated tradeoffs for guards considering potential
452b1c73532SDimitry Andric       // for check widening, but for now we keep things simple.
453b1c73532SDimitry Andric       auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));
454b1c73532SDimitry Andric       return Cond && Cond->isOne();
455b1c73532SDimitry Andric     }
456e3b55780SDimitry Andric     // TODO: These intrinsics are not safe to remove, because this may remove
457e3b55780SDimitry Andric     // a well-defined trap.
458e3b55780SDimitry Andric     case Intrinsic::wasm_trunc_signed:
459e3b55780SDimitry Andric     case Intrinsic::wasm_trunc_unsigned:
460e3b55780SDimitry Andric     case Intrinsic::ptrauth_auth:
461e3b55780SDimitry Andric     case Intrinsic::ptrauth_resign:
462e3b55780SDimitry Andric       return true;
463e3b55780SDimitry Andric     default:
464e3b55780SDimitry Andric       return false;
465e3b55780SDimitry Andric     }
466e3b55780SDimitry Andric   }
467e3b55780SDimitry Andric 
46871d5a254SDimitry Andric   if (!I->mayHaveSideEffects())
46971d5a254SDimitry Andric     return true;
470009b1c42SEd Schouten 
471009b1c42SEd Schouten   // Special case intrinsics that "may have side effects" but can be deleted
472009b1c42SEd Schouten   // when dead.
473b1c73532SDimitry Andric   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
474eb11fae6SDimitry Andric     // Safe to delete llvm.stacksave and launder.invariant.group if dead.
475eb11fae6SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::stacksave ||
476eb11fae6SDimitry Andric         II->getIntrinsicID() == Intrinsic::launder_invariant_group)
477009b1c42SEd Schouten       return true;
47830815c53SDimitry Andric 
479ac9a064cSDimitry Andric     // Intrinsics declare sideeffects to prevent them from moving, but they are
480ac9a064cSDimitry Andric     // nops without users.
481ac9a064cSDimitry Andric     if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
482ac9a064cSDimitry Andric         II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
483ac9a064cSDimitry Andric       return true;
484ac9a064cSDimitry Andric 
485cfca06d7SDimitry Andric     if (II->isLifetimeStartOrEnd()) {
486cfca06d7SDimitry Andric       auto *Arg = II->getArgOperand(1);
48730815c53SDimitry Andric       // Lifetime intrinsics are dead when their right-hand is undef.
488cfca06d7SDimitry Andric       if (isa<UndefValue>(Arg))
489cfca06d7SDimitry Andric         return true;
490cfca06d7SDimitry Andric       // If the right-hand is an alloc, global, or argument and the only uses
491cfca06d7SDimitry Andric       // are lifetime intrinsics then the intrinsics are dead.
492cfca06d7SDimitry Andric       if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
493cfca06d7SDimitry Andric         return llvm::all_of(Arg->uses(), [](Use &Use) {
494cfca06d7SDimitry Andric           if (IntrinsicInst *IntrinsicUse =
495cfca06d7SDimitry Andric                   dyn_cast<IntrinsicInst>(Use.getUser()))
496cfca06d7SDimitry Andric             return IntrinsicUse->isLifetimeStartOrEnd();
497cfca06d7SDimitry Andric           return false;
498cfca06d7SDimitry Andric         });
499cfca06d7SDimitry Andric       return false;
500cfca06d7SDimitry Andric     }
50167c32a98SDimitry Andric 
502b1c73532SDimitry Andric     // Assumptions are dead if their condition is trivially true.
503b1c73532SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::assume &&
504b1c73532SDimitry Andric         isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) {
50567c32a98SDimitry Andric       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
50667c32a98SDimitry Andric         return !Cond->isZero();
50767c32a98SDimitry Andric 
50867c32a98SDimitry Andric       return false;
50967c32a98SDimitry Andric     }
510344a3780SDimitry Andric 
511344a3780SDimitry Andric     if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
512e3b55780SDimitry Andric       std::optional<fp::ExceptionBehavior> ExBehavior =
513e3b55780SDimitry Andric           FPI->getExceptionBehavior();
514145449b1SDimitry Andric       return *ExBehavior != fp::ebStrict;
515344a3780SDimitry Andric     }
51630815c53SDimitry Andric   }
51763faed5bSDimitry Andric 
5184b4fe385SDimitry Andric   if (auto *Call = dyn_cast<CallBase>(I)) {
5194b4fe385SDimitry Andric     if (Value *FreedOp = getFreedOperand(Call, TLI))
5204b4fe385SDimitry Andric       if (Constant *C = dyn_cast<Constant>(FreedOp))
52163faed5bSDimitry Andric         return C->isNullValue() || isa<UndefValue>(C);
522e6d15924SDimitry Andric     if (isMathLibCallNoop(Call, TLI))
523b915e9e0SDimitry Andric       return true;
5244b4fe385SDimitry Andric   }
525b915e9e0SDimitry Andric 
526145449b1SDimitry Andric   // Non-volatile atomic loads from constants can be removed.
527145449b1SDimitry Andric   if (auto *LI = dyn_cast<LoadInst>(I))
528145449b1SDimitry Andric     if (auto *GV = dyn_cast<GlobalVariable>(
529145449b1SDimitry Andric             LI->getPointerOperand()->stripPointerCasts()))
530145449b1SDimitry Andric       if (!LI->isVolatile() && GV->isConstant())
531344a3780SDimitry Andric         return true;
532344a3780SDimitry Andric 
533009b1c42SEd Schouten   return false;
534009b1c42SEd Schouten }
535009b1c42SEd Schouten 
536009b1c42SEd Schouten /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
537009b1c42SEd Schouten /// trivially dead instruction, delete it.  If that makes any of its operands
538829000e0SRoman Divacky /// trivially dead, delete them too, recursively.  Return true if any
539829000e0SRoman Divacky /// instructions were deleted.
RecursivelyDeleteTriviallyDeadInstructions(Value * V,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)540d8e91e46SDimitry Andric bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
541b60736ecSDimitry Andric     Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
542b60736ecSDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
543009b1c42SEd Schouten   Instruction *I = dyn_cast<Instruction>(V);
544e6d15924SDimitry Andric   if (!I || !isInstructionTriviallyDead(I, TLI))
545829000e0SRoman Divacky     return false;
546009b1c42SEd Schouten 
547cfca06d7SDimitry Andric   SmallVector<WeakTrackingVH, 16> DeadInsts;
548009b1c42SEd Schouten   DeadInsts.push_back(I);
549b60736ecSDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
550b60736ecSDimitry Andric                                              AboutToDeleteCallback);
551009b1c42SEd Schouten 
552eb11fae6SDimitry Andric   return true;
553eb11fae6SDimitry Andric }
554eb11fae6SDimitry Andric 
RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)555cfca06d7SDimitry Andric bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
556cfca06d7SDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
557b60736ecSDimitry Andric     MemorySSAUpdater *MSSAU,
558b60736ecSDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
559cfca06d7SDimitry Andric   unsigned S = 0, E = DeadInsts.size(), Alive = 0;
560cfca06d7SDimitry Andric   for (; S != E; ++S) {
5617fa27ce4SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
562f65dcba8SDimitry Andric     if (!I || !isInstructionTriviallyDead(I)) {
563cfca06d7SDimitry Andric       DeadInsts[S] = nullptr;
564cfca06d7SDimitry Andric       ++Alive;
565cfca06d7SDimitry Andric     }
566cfca06d7SDimitry Andric   }
567cfca06d7SDimitry Andric   if (Alive == E)
568cfca06d7SDimitry Andric     return false;
569b60736ecSDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
570b60736ecSDimitry Andric                                              AboutToDeleteCallback);
571cfca06d7SDimitry Andric   return true;
572cfca06d7SDimitry Andric }
573cfca06d7SDimitry Andric 
RecursivelyDeleteTriviallyDeadInstructions(SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)574eb11fae6SDimitry Andric void llvm::RecursivelyDeleteTriviallyDeadInstructions(
575cfca06d7SDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
576b60736ecSDimitry Andric     MemorySSAUpdater *MSSAU,
577b60736ecSDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
578eb11fae6SDimitry Andric   // Process the dead instruction list until empty.
579eb11fae6SDimitry Andric   while (!DeadInsts.empty()) {
580cfca06d7SDimitry Andric     Value *V = DeadInsts.pop_back_val();
581cfca06d7SDimitry Andric     Instruction *I = cast_or_null<Instruction>(V);
582cfca06d7SDimitry Andric     if (!I)
583cfca06d7SDimitry Andric       continue;
584cfca06d7SDimitry Andric     assert(isInstructionTriviallyDead(I, TLI) &&
585eb11fae6SDimitry Andric            "Live instruction found in dead worklist!");
586cfca06d7SDimitry Andric     assert(I->use_empty() && "Instructions with uses are not dead.");
587eb11fae6SDimitry Andric 
588eb11fae6SDimitry Andric     // Don't lose the debug info while deleting the instructions.
589cfca06d7SDimitry Andric     salvageDebugInfo(*I);
590009b1c42SEd Schouten 
591b60736ecSDimitry Andric     if (AboutToDeleteCallback)
592b60736ecSDimitry Andric       AboutToDeleteCallback(I);
593b60736ecSDimitry Andric 
594009b1c42SEd Schouten     // Null out all of the instruction's operands to see if any operand becomes
595009b1c42SEd Schouten     // dead as we go.
596cfca06d7SDimitry Andric     for (Use &OpU : I->operands()) {
597eb11fae6SDimitry Andric       Value *OpV = OpU.get();
598eb11fae6SDimitry Andric       OpU.set(nullptr);
599009b1c42SEd Schouten 
600eb11fae6SDimitry Andric       if (!OpV->use_empty())
601eb11fae6SDimitry Andric         continue;
602009b1c42SEd Schouten 
603009b1c42SEd Schouten       // If the operand is an instruction that became dead as we nulled out the
604009b1c42SEd Schouten       // operand, and if it is 'trivially' dead, delete it in a future loop
605009b1c42SEd Schouten       // iteration.
606009b1c42SEd Schouten       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
607522600a2SDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
608009b1c42SEd Schouten           DeadInsts.push_back(OpI);
609009b1c42SEd Schouten     }
610d8e91e46SDimitry Andric     if (MSSAU)
611cfca06d7SDimitry Andric       MSSAU->removeMemoryAccess(I);
612009b1c42SEd Schouten 
613cfca06d7SDimitry Andric     I->eraseFromParent();
614eb11fae6SDimitry Andric   }
615009b1c42SEd Schouten }
616009b1c42SEd Schouten 
replaceDbgUsesWithUndef(Instruction * I)617d8e91e46SDimitry Andric bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
618d8e91e46SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
619ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
620b1c73532SDimitry Andric   findDbgUsers(DbgUsers, I, &DPUsers);
621e3b55780SDimitry Andric   for (auto *DII : DbgUsers)
622e3b55780SDimitry Andric     DII->setKillLocation();
623ac9a064cSDimitry Andric   for (auto *DVR : DPUsers)
624ac9a064cSDimitry Andric     DVR->setKillLocation();
625b1c73532SDimitry Andric   return !DbgUsers.empty() || !DPUsers.empty();
626d8e91e46SDimitry Andric }
627d8e91e46SDimitry Andric 
628cf099d11SDimitry Andric /// areAllUsesEqual - Check whether the uses of a value are all the same.
629cf099d11SDimitry Andric /// This is similar to Instruction::hasOneUse() except this will also return
630d0e4e96dSDimitry Andric /// true when there are no uses or multiple uses that all refer to the same
631d0e4e96dSDimitry Andric /// value.
areAllUsesEqual(Instruction * I)632cf099d11SDimitry Andric static bool areAllUsesEqual(Instruction *I) {
6335ca98fd9SDimitry Andric   Value::user_iterator UI = I->user_begin();
6345ca98fd9SDimitry Andric   Value::user_iterator UE = I->user_end();
635cf099d11SDimitry Andric   if (UI == UE)
636d0e4e96dSDimitry Andric     return true;
637cf099d11SDimitry Andric 
638cf099d11SDimitry Andric   User *TheUse = *UI;
639cf099d11SDimitry Andric   for (++UI; UI != UE; ++UI) {
640cf099d11SDimitry Andric     if (*UI != TheUse)
641cf099d11SDimitry Andric       return false;
642cf099d11SDimitry Andric   }
643cf099d11SDimitry Andric   return true;
644cf099d11SDimitry Andric }
645cf099d11SDimitry Andric 
646009b1c42SEd Schouten /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
647009b1c42SEd Schouten /// dead PHI node, due to being a def-use chain of single-use nodes that
648009b1c42SEd Schouten /// either forms a cycle or is terminated by a trivially dead instruction,
649009b1c42SEd Schouten /// delete it.  If that makes any of its operands trivially dead, delete them
650d0e4e96dSDimitry Andric /// too, recursively.  Return true if a change was made.
RecursivelyDeleteDeadPHINode(PHINode * PN,const TargetLibraryInfo * TLI,llvm::MemorySSAUpdater * MSSAU)651522600a2SDimitry Andric bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
652cfca06d7SDimitry Andric                                         const TargetLibraryInfo *TLI,
653cfca06d7SDimitry Andric                                         llvm::MemorySSAUpdater *MSSAU) {
654d0e4e96dSDimitry Andric   SmallPtrSet<Instruction*, 4> Visited;
655d0e4e96dSDimitry Andric   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
6565ca98fd9SDimitry Andric        I = cast<Instruction>(*I->user_begin())) {
657d0e4e96dSDimitry Andric     if (I->use_empty())
658cfca06d7SDimitry Andric       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
659009b1c42SEd Schouten 
660d0e4e96dSDimitry Andric     // If we find an instruction more than once, we're on a cycle that
661009b1c42SEd Schouten     // won't prove fruitful.
66267c32a98SDimitry Andric     if (!Visited.insert(I).second) {
663d0e4e96dSDimitry Andric       // Break the cycle and delete the instruction and its operands.
6644b4fe385SDimitry Andric       I->replaceAllUsesWith(PoisonValue::get(I->getType()));
665cfca06d7SDimitry Andric       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
666d0e4e96dSDimitry Andric       return true;
667009b1c42SEd Schouten     }
668d0e4e96dSDimitry Andric   }
669d0e4e96dSDimitry Andric   return false;
670829000e0SRoman Divacky }
671829000e0SRoman Divacky 
672dd58ef01SDimitry Andric static bool
simplifyAndDCEInstruction(Instruction * I,SmallSetVector<Instruction *,16> & WorkList,const DataLayout & DL,const TargetLibraryInfo * TLI)673dd58ef01SDimitry Andric simplifyAndDCEInstruction(Instruction *I,
674dd58ef01SDimitry Andric                           SmallSetVector<Instruction *, 16> &WorkList,
675dd58ef01SDimitry Andric                           const DataLayout &DL,
676dd58ef01SDimitry Andric                           const TargetLibraryInfo *TLI) {
677dd58ef01SDimitry Andric   if (isInstructionTriviallyDead(I, TLI)) {
678eb11fae6SDimitry Andric     salvageDebugInfo(*I);
679eb11fae6SDimitry Andric 
680dd58ef01SDimitry Andric     // Null out all of the instruction's operands to see if any operand becomes
681dd58ef01SDimitry Andric     // dead as we go.
682dd58ef01SDimitry Andric     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
683dd58ef01SDimitry Andric       Value *OpV = I->getOperand(i);
684dd58ef01SDimitry Andric       I->setOperand(i, nullptr);
685dd58ef01SDimitry Andric 
686dd58ef01SDimitry Andric       if (!OpV->use_empty() || I == OpV)
687dd58ef01SDimitry Andric         continue;
688dd58ef01SDimitry Andric 
689dd58ef01SDimitry Andric       // If the operand is an instruction that became dead as we nulled out the
690dd58ef01SDimitry Andric       // operand, and if it is 'trivially' dead, delete it in a future loop
691dd58ef01SDimitry Andric       // iteration.
692dd58ef01SDimitry Andric       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
693dd58ef01SDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
694dd58ef01SDimitry Andric           WorkList.insert(OpI);
695dd58ef01SDimitry Andric     }
696dd58ef01SDimitry Andric 
697dd58ef01SDimitry Andric     I->eraseFromParent();
698dd58ef01SDimitry Andric 
699dd58ef01SDimitry Andric     return true;
700dd58ef01SDimitry Andric   }
701dd58ef01SDimitry Andric 
702145449b1SDimitry Andric   if (Value *SimpleV = simplifyInstruction(I, DL)) {
703dd58ef01SDimitry Andric     // Add the users to the worklist. CAREFUL: an instruction can use itself,
704dd58ef01SDimitry Andric     // in the case of a phi node.
70501095a5dSDimitry Andric     for (User *U : I->users()) {
70601095a5dSDimitry Andric       if (U != I) {
707dd58ef01SDimitry Andric         WorkList.insert(cast<Instruction>(U));
70801095a5dSDimitry Andric       }
70901095a5dSDimitry Andric     }
710dd58ef01SDimitry Andric 
711dd58ef01SDimitry Andric     // Replace the instruction with its simplified value.
71201095a5dSDimitry Andric     bool Changed = false;
71301095a5dSDimitry Andric     if (!I->use_empty()) {
714dd58ef01SDimitry Andric       I->replaceAllUsesWith(SimpleV);
71501095a5dSDimitry Andric       Changed = true;
71601095a5dSDimitry Andric     }
71701095a5dSDimitry Andric     if (isInstructionTriviallyDead(I, TLI)) {
718dd58ef01SDimitry Andric       I->eraseFromParent();
71901095a5dSDimitry Andric       Changed = true;
72001095a5dSDimitry Andric     }
72101095a5dSDimitry Andric     return Changed;
722dd58ef01SDimitry Andric   }
723dd58ef01SDimitry Andric   return false;
724dd58ef01SDimitry Andric }
725dd58ef01SDimitry Andric 
726829000e0SRoman Divacky /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
727829000e0SRoman Divacky /// simplify any instructions in it and recursively delete dead instructions.
728829000e0SRoman Divacky ///
729829000e0SRoman Divacky /// This returns true if it changed the code, note that it can delete
730829000e0SRoman Divacky /// instructions in other blocks as well in this block.
SimplifyInstructionsInBlock(BasicBlock * BB,const TargetLibraryInfo * TLI)7315a5ac124SDimitry Andric bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
732522600a2SDimitry Andric                                        const TargetLibraryInfo *TLI) {
733829000e0SRoman Divacky   bool MadeChange = false;
734ac9a064cSDimitry Andric   const DataLayout &DL = BB->getDataLayout();
73563faed5bSDimitry Andric 
73663faed5bSDimitry Andric #ifndef NDEBUG
73763faed5bSDimitry Andric   // In debug builds, ensure that the terminator of the block is never replaced
73863faed5bSDimitry Andric   // or deleted by these simplifications. The idea of simplification is that it
73963faed5bSDimitry Andric   // cannot introduce new instructions, and there is no way to replace the
74063faed5bSDimitry Andric   // terminator of a block without introducing a new instruction.
741dd58ef01SDimitry Andric   AssertingVH<Instruction> TerminatorVH(&BB->back());
74263faed5bSDimitry Andric #endif
74363faed5bSDimitry Andric 
744dd58ef01SDimitry Andric   SmallSetVector<Instruction *, 16> WorkList;
745dd58ef01SDimitry Andric   // Iterate over the original function, only adding insts to the worklist
746dd58ef01SDimitry Andric   // if they actually need to be revisited. This avoids having to pre-init
747dd58ef01SDimitry Andric   // the worklist with the entire function's worth of instructions.
74801095a5dSDimitry Andric   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
74901095a5dSDimitry Andric        BI != E;) {
75063faed5bSDimitry Andric     assert(!BI->isTerminator());
751dd58ef01SDimitry Andric     Instruction *I = &*BI;
752dd58ef01SDimitry Andric     ++BI;
753829000e0SRoman Divacky 
754dd58ef01SDimitry Andric     // We're visiting this instruction now, so make sure it's not in the
755dd58ef01SDimitry Andric     // worklist from an earlier visit.
756dd58ef01SDimitry Andric     if (!WorkList.count(I))
757dd58ef01SDimitry Andric       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
758829000e0SRoman Divacky   }
759829000e0SRoman Divacky 
760dd58ef01SDimitry Andric   while (!WorkList.empty()) {
761dd58ef01SDimitry Andric     Instruction *I = WorkList.pop_back_val();
762dd58ef01SDimitry Andric     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
763829000e0SRoman Divacky   }
764829000e0SRoman Divacky   return MadeChange;
765009b1c42SEd Schouten }
766009b1c42SEd Schouten 
767009b1c42SEd Schouten //===----------------------------------------------------------------------===//
768907da171SRoman Divacky //  Control Flow Graph Restructuring.
769009b1c42SEd Schouten //
770009b1c42SEd Schouten 
MergeBasicBlockIntoOnlyPred(BasicBlock * DestBB,DomTreeUpdater * DTU)771d8e91e46SDimitry Andric void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
772d8e91e46SDimitry Andric                                        DomTreeUpdater *DTU) {
773eb11fae6SDimitry Andric 
774009b1c42SEd Schouten   // If BB has single-entry PHI nodes, fold them.
775009b1c42SEd Schouten   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
776009b1c42SEd Schouten     Value *NewVal = PN->getIncomingValue(0);
7774b4fe385SDimitry Andric     // Replace self referencing PHI with poison, it must be dead.
7784b4fe385SDimitry Andric     if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());
779009b1c42SEd Schouten     PN->replaceAllUsesWith(NewVal);
780009b1c42SEd Schouten     PN->eraseFromParent();
781009b1c42SEd Schouten   }
782009b1c42SEd Schouten 
783009b1c42SEd Schouten   BasicBlock *PredBB = DestBB->getSinglePredecessor();
784009b1c42SEd Schouten   assert(PredBB && "Block doesn't have a single predecessor!");
785009b1c42SEd Schouten 
786344a3780SDimitry Andric   bool ReplaceEntryBB = PredBB->isEntryBlock();
787eb11fae6SDimitry Andric 
788d8e91e46SDimitry Andric   // DTU updates: Collect all the edges that enter
789d8e91e46SDimitry Andric   // PredBB. These dominator edges will be redirected to DestBB.
790d8e91e46SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
791d8e91e46SDimitry Andric 
792d8e91e46SDimitry Andric   if (DTU) {
793f65dcba8SDimitry Andric     // To avoid processing the same predecessor more than once.
794f65dcba8SDimitry Andric     SmallPtrSet<BasicBlock *, 2> SeenPreds;
795f65dcba8SDimitry Andric     Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);
796f65dcba8SDimitry Andric     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
797eb11fae6SDimitry Andric       // This predecessor of PredBB may already have DestBB as a successor.
798344a3780SDimitry Andric       if (PredOfPredBB != PredBB)
799f65dcba8SDimitry Andric         if (SeenPreds.insert(PredOfPredBB).second)
800344a3780SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
801f65dcba8SDimitry Andric     SeenPreds.clear();
802f65dcba8SDimitry Andric     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
803f65dcba8SDimitry Andric       if (SeenPreds.insert(PredOfPredBB).second)
804344a3780SDimitry Andric         Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
805b60736ecSDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
806eb11fae6SDimitry Andric   }
807eb11fae6SDimitry Andric 
8086fe5c7aaSRoman Divacky   // Zap anything that took the address of DestBB.  Not doing this will give the
8096fe5c7aaSRoman Divacky   // address an invalid value.
8106fe5c7aaSRoman Divacky   if (DestBB->hasAddressTaken()) {
8116fe5c7aaSRoman Divacky     BlockAddress *BA = BlockAddress::get(DestBB);
8126fe5c7aaSRoman Divacky     Constant *Replacement =
813044eb2f6SDimitry Andric       ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
8146fe5c7aaSRoman Divacky     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
8156fe5c7aaSRoman Divacky                                                      BA->getType()));
8166fe5c7aaSRoman Divacky     BA->destroyConstant();
8176fe5c7aaSRoman Divacky   }
8186fe5c7aaSRoman Divacky 
819009b1c42SEd Schouten   // Anything that branched to PredBB now branches to DestBB.
820009b1c42SEd Schouten   PredBB->replaceAllUsesWith(DestBB);
821009b1c42SEd Schouten 
822411bd29eSDimitry Andric   // Splice all the instructions from PredBB to DestBB.
823411bd29eSDimitry Andric   PredBB->getTerminator()->eraseFromParent();
824e3b55780SDimitry Andric   DestBB->splice(DestBB->begin(), PredBB);
825d8e91e46SDimitry Andric   new UnreachableInst(PredBB->getContext(), PredBB);
826411bd29eSDimitry Andric 
8275ca98fd9SDimitry Andric   // If the PredBB is the entry block of the function, move DestBB up to
8285ca98fd9SDimitry Andric   // become the entry block after we erase PredBB.
829eb11fae6SDimitry Andric   if (ReplaceEntryBB)
8305ca98fd9SDimitry Andric     DestBB->moveAfter(PredBB);
8315ca98fd9SDimitry Andric 
832d8e91e46SDimitry Andric   if (DTU) {
833e3b55780SDimitry Andric     assert(PredBB->size() == 1 &&
834d8e91e46SDimitry Andric            isa<UnreachableInst>(PredBB->getTerminator()) &&
835d8e91e46SDimitry Andric            "The successor list of PredBB isn't empty before "
836d8e91e46SDimitry Andric            "applying corresponding DTU updates.");
837e6d15924SDimitry Andric     DTU->applyUpdatesPermissive(Updates);
838d8e91e46SDimitry Andric     DTU->deleteBB(PredBB);
839d8e91e46SDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
840d8e91e46SDimitry Andric     // the Entry BB is replaced.
841d8e91e46SDimitry Andric     if (ReplaceEntryBB && DTU->hasDomTree()) {
842d8e91e46SDimitry Andric       // The entry block was removed and there is no external interface for
843d8e91e46SDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
844d8e91e46SDimitry Andric       // we recalculate the entire tree.
845d8e91e46SDimitry Andric       DTU->recalculate(*(DestBB->getParent()));
84659850d08SRoman Divacky     }
847044eb2f6SDimitry Andric   }
848eb11fae6SDimitry Andric 
849d8e91e46SDimitry Andric   else {
850d8e91e46SDimitry Andric     PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
851eb11fae6SDimitry Andric   }
852009b1c42SEd Schouten }
853009b1c42SEd Schouten 
8541d5ae102SDimitry Andric /// Return true if we can choose one of these values to use in place of the
8551d5ae102SDimitry Andric /// other. Note that we will always choose the non-undef value to keep.
CanMergeValues(Value * First,Value * Second)856f8af5cf6SDimitry Andric static bool CanMergeValues(Value *First, Value *Second) {
857f8af5cf6SDimitry Andric   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
858f8af5cf6SDimitry Andric }
859f8af5cf6SDimitry Andric 
8601d5ae102SDimitry Andric /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
8611d5ae102SDimitry Andric /// branch to Succ, into Succ.
862907da171SRoman Divacky ///
863907da171SRoman Divacky /// Assumption: Succ is the single successor for BB.
864b1c73532SDimitry Andric static bool
CanPropagatePredecessorsForPHIs(BasicBlock * BB,BasicBlock * Succ,const SmallPtrSetImpl<BasicBlock * > & BBPreds)865b1c73532SDimitry Andric CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ,
866b1c73532SDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
867907da171SRoman Divacky   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
868907da171SRoman Divacky 
869eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
870907da171SRoman Divacky                     << Succ->getName() << "\n");
871907da171SRoman Divacky   // Shortcut, if there is only a single predecessor it must be BB and merging
872907da171SRoman Divacky   // is always safe
873b1c73532SDimitry Andric   if (Succ->getSinglePredecessor())
874b1c73532SDimitry Andric     return true;
875907da171SRoman Divacky 
876907da171SRoman Divacky   // Look at all the phi nodes in Succ, to see if they present a conflict when
877907da171SRoman Divacky   // merging these blocks
878907da171SRoman Divacky   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
879907da171SRoman Divacky     PHINode *PN = cast<PHINode>(I);
880907da171SRoman Divacky 
881907da171SRoman Divacky     // If the incoming value from BB is again a PHINode in
882907da171SRoman Divacky     // BB which has the same incoming value for *PI as PN does, we can
883907da171SRoman Divacky     // merge the phi nodes and then the blocks can still be merged
884907da171SRoman Divacky     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
885907da171SRoman Divacky     if (BBPN && BBPN->getParent() == BB) {
88663faed5bSDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
88763faed5bSDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
88863faed5bSDimitry Andric         if (BBPreds.count(IBB) &&
889f8af5cf6SDimitry Andric             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
890f8af5cf6SDimitry Andric                             PN->getIncomingValue(PI))) {
891eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs()
892eb11fae6SDimitry Andric                      << "Can't fold, phi node " << PN->getName() << " in "
893907da171SRoman Divacky                      << Succ->getName() << " is conflicting with "
894907da171SRoman Divacky                      << BBPN->getName() << " with regard to common predecessor "
89563faed5bSDimitry Andric                      << IBB->getName() << "\n");
896907da171SRoman Divacky           return false;
897907da171SRoman Divacky         }
898907da171SRoman Divacky       }
899907da171SRoman Divacky     } else {
900907da171SRoman Divacky       Value* Val = PN->getIncomingValueForBlock(BB);
90163faed5bSDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
902907da171SRoman Divacky         // See if the incoming value for the common predecessor is equal to the
903907da171SRoman Divacky         // one for BB, in which case this phi node will not prevent the merging
904907da171SRoman Divacky         // of the block.
90563faed5bSDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
906f8af5cf6SDimitry Andric         if (BBPreds.count(IBB) &&
907f8af5cf6SDimitry Andric             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
908eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
909eb11fae6SDimitry Andric                             << " in " << Succ->getName()
910eb11fae6SDimitry Andric                             << " is conflicting with regard to common "
91163faed5bSDimitry Andric                             << "predecessor " << IBB->getName() << "\n");
912907da171SRoman Divacky           return false;
913907da171SRoman Divacky         }
914907da171SRoman Divacky       }
915907da171SRoman Divacky     }
916907da171SRoman Divacky   }
917907da171SRoman Divacky 
918907da171SRoman Divacky   return true;
919907da171SRoman Divacky }
920907da171SRoman Divacky 
921044eb2f6SDimitry Andric using PredBlockVector = SmallVector<BasicBlock *, 16>;
922044eb2f6SDimitry Andric using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
923f8af5cf6SDimitry Andric 
924eb11fae6SDimitry Andric /// Determines the value to use as the phi node input for a block.
925f8af5cf6SDimitry Andric ///
926f8af5cf6SDimitry Andric /// Select between \p OldVal any value that we know flows from \p BB
927f8af5cf6SDimitry Andric /// to a particular phi on the basis of which one (if either) is not
928f8af5cf6SDimitry Andric /// undef. Update IncomingValues based on the selected value.
929f8af5cf6SDimitry Andric ///
930f8af5cf6SDimitry Andric /// \param OldVal The value we are considering selecting.
931f8af5cf6SDimitry Andric /// \param BB The block that the value flows in from.
932f8af5cf6SDimitry Andric /// \param IncomingValues A map from block-to-value for other phi inputs
933f8af5cf6SDimitry Andric /// that we have examined.
934f8af5cf6SDimitry Andric ///
935f8af5cf6SDimitry Andric /// \returns the selected value.
selectIncomingValueForBlock(Value * OldVal,BasicBlock * BB,IncomingValueMap & IncomingValues)936f8af5cf6SDimitry Andric static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
937f8af5cf6SDimitry Andric                                           IncomingValueMap &IncomingValues) {
938f8af5cf6SDimitry Andric   if (!isa<UndefValue>(OldVal)) {
939f8af5cf6SDimitry Andric     assert((!IncomingValues.count(BB) ||
940f8af5cf6SDimitry Andric             IncomingValues.find(BB)->second == OldVal) &&
941f8af5cf6SDimitry Andric            "Expected OldVal to match incoming value from BB!");
942f8af5cf6SDimitry Andric 
943f8af5cf6SDimitry Andric     IncomingValues.insert(std::make_pair(BB, OldVal));
944f8af5cf6SDimitry Andric     return OldVal;
945f8af5cf6SDimitry Andric   }
946f8af5cf6SDimitry Andric 
947f8af5cf6SDimitry Andric   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
948f8af5cf6SDimitry Andric   if (It != IncomingValues.end()) return It->second;
949f8af5cf6SDimitry Andric 
950f8af5cf6SDimitry Andric   return OldVal;
951f8af5cf6SDimitry Andric }
952f8af5cf6SDimitry Andric 
953eb11fae6SDimitry Andric /// Create a map from block to value for the operands of a
954f8af5cf6SDimitry Andric /// given phi.
955f8af5cf6SDimitry Andric ///
956f8af5cf6SDimitry Andric /// Create a map from block to value for each non-undef value flowing
957f8af5cf6SDimitry Andric /// into \p PN.
958f8af5cf6SDimitry Andric ///
959f8af5cf6SDimitry Andric /// \param PN The phi we are collecting the map for.
960f8af5cf6SDimitry Andric /// \param IncomingValues [out] The map from block to value for this phi.
gatherIncomingValuesToPhi(PHINode * PN,IncomingValueMap & IncomingValues)961f8af5cf6SDimitry Andric static void gatherIncomingValuesToPhi(PHINode *PN,
962f8af5cf6SDimitry Andric                                       IncomingValueMap &IncomingValues) {
963f8af5cf6SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
964f8af5cf6SDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
965f8af5cf6SDimitry Andric     Value *V = PN->getIncomingValue(i);
966f8af5cf6SDimitry Andric 
967f8af5cf6SDimitry Andric     if (!isa<UndefValue>(V))
968f8af5cf6SDimitry Andric       IncomingValues.insert(std::make_pair(BB, V));
969f8af5cf6SDimitry Andric   }
970f8af5cf6SDimitry Andric }
971f8af5cf6SDimitry Andric 
972eb11fae6SDimitry Andric /// Replace the incoming undef values to a phi with the values
973f8af5cf6SDimitry Andric /// from a block-to-value map.
974f8af5cf6SDimitry Andric ///
975f8af5cf6SDimitry Andric /// \param PN The phi we are replacing the undefs in.
976f8af5cf6SDimitry Andric /// \param IncomingValues A map from block to value.
replaceUndefValuesInPhi(PHINode * PN,const IncomingValueMap & IncomingValues)977f8af5cf6SDimitry Andric static void replaceUndefValuesInPhi(PHINode *PN,
978f8af5cf6SDimitry Andric                                     const IncomingValueMap &IncomingValues) {
979344a3780SDimitry Andric   SmallVector<unsigned> TrueUndefOps;
980f8af5cf6SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
981f8af5cf6SDimitry Andric     Value *V = PN->getIncomingValue(i);
982f8af5cf6SDimitry Andric 
983f8af5cf6SDimitry Andric     if (!isa<UndefValue>(V)) continue;
984f8af5cf6SDimitry Andric 
985f8af5cf6SDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
986f8af5cf6SDimitry Andric     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
987f8af5cf6SDimitry Andric 
988344a3780SDimitry Andric     // Keep track of undef/poison incoming values. Those must match, so we fix
989344a3780SDimitry Andric     // them up below if needed.
990344a3780SDimitry Andric     // Note: this is conservatively correct, but we could try harder and group
991344a3780SDimitry Andric     // the undef values per incoming basic block.
992344a3780SDimitry Andric     if (It == IncomingValues.end()) {
993344a3780SDimitry Andric       TrueUndefOps.push_back(i);
994344a3780SDimitry Andric       continue;
995344a3780SDimitry Andric     }
996344a3780SDimitry Andric 
997344a3780SDimitry Andric     // There is a defined value for this incoming block, so map this undef
998344a3780SDimitry Andric     // incoming value to the defined value.
999f8af5cf6SDimitry Andric     PN->setIncomingValue(i, It->second);
1000f8af5cf6SDimitry Andric   }
1001344a3780SDimitry Andric 
1002344a3780SDimitry Andric   // If there are both undef and poison values incoming, then convert those
1003344a3780SDimitry Andric   // values to undef. It is invalid to have different values for the same
1004344a3780SDimitry Andric   // incoming block.
1005344a3780SDimitry Andric   unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
1006344a3780SDimitry Andric     return isa<PoisonValue>(PN->getIncomingValue(i));
1007344a3780SDimitry Andric   });
1008344a3780SDimitry Andric   if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1009344a3780SDimitry Andric     for (unsigned i : TrueUndefOps)
1010344a3780SDimitry Andric       PN->setIncomingValue(i, UndefValue::get(PN->getType()));
1011344a3780SDimitry Andric   }
1012f8af5cf6SDimitry Andric }
1013f8af5cf6SDimitry Andric 
1014b1c73532SDimitry Andric // Only when they shares a single common predecessor, return true.
1015b1c73532SDimitry Andric // Only handles cases when BB can't be merged while its predecessors can be
1016b1c73532SDimitry Andric // redirected.
1017b1c73532SDimitry Andric static bool
CanRedirectPredsOfEmptyBBToSucc(BasicBlock * BB,BasicBlock * Succ,const SmallPtrSetImpl<BasicBlock * > & BBPreds,const SmallPtrSetImpl<BasicBlock * > & SuccPreds,BasicBlock * & CommonPred)1018b1c73532SDimitry Andric CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ,
1019b1c73532SDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1020b1c73532SDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &SuccPreds,
1021b1c73532SDimitry Andric                                 BasicBlock *&CommonPred) {
1022b1c73532SDimitry Andric 
1023b1c73532SDimitry Andric   // There must be phis in BB, otherwise BB will be merged into Succ directly
1024b1c73532SDimitry Andric   if (BB->phis().empty() || Succ->phis().empty())
1025b1c73532SDimitry Andric     return false;
1026b1c73532SDimitry Andric 
1027b1c73532SDimitry Andric   // BB must have predecessors not shared that can be redirected to Succ
1028b1c73532SDimitry Andric   if (!BB->hasNPredecessorsOrMore(2))
1029b1c73532SDimitry Andric     return false;
1030b1c73532SDimitry Andric 
1031f56b67c4SDimitry Andric   if (any_of(BBPreds, [](const BasicBlock *Pred) {
1032f56b67c4SDimitry Andric         return isa<IndirectBrInst>(Pred->getTerminator());
1033f56b67c4SDimitry Andric       }))
1034f56b67c4SDimitry Andric     return false;
1035f56b67c4SDimitry Andric 
1036f56b67c4SDimitry Andric   // Get the single common predecessor of both BB and Succ. Return false
1037f56b67c4SDimitry Andric   // when there are more than one common predecessors.
1038b1c73532SDimitry Andric   for (BasicBlock *SuccPred : SuccPreds) {
1039b1c73532SDimitry Andric     if (BBPreds.count(SuccPred)) {
1040b1c73532SDimitry Andric       if (CommonPred)
1041b1c73532SDimitry Andric         return false;
1042b1c73532SDimitry Andric       CommonPred = SuccPred;
1043b1c73532SDimitry Andric     }
1044b1c73532SDimitry Andric   }
1045b1c73532SDimitry Andric 
1046b1c73532SDimitry Andric   return true;
1047b1c73532SDimitry Andric }
1048b1c73532SDimitry Andric 
1049eb11fae6SDimitry Andric /// Replace a value flowing from a block to a phi with
1050f8af5cf6SDimitry Andric /// potentially multiple instances of that value flowing from the
1051f8af5cf6SDimitry Andric /// block's predecessors to the phi.
1052f8af5cf6SDimitry Andric ///
1053f8af5cf6SDimitry Andric /// \param BB The block with the value flowing into the phi.
1054f8af5cf6SDimitry Andric /// \param BBPreds The predecessors of BB.
1055f8af5cf6SDimitry Andric /// \param PN The phi that we are updating.
1056b1c73532SDimitry Andric /// \param CommonPred The common predecessor of BB and PN's BasicBlock
redirectValuesFromPredecessorsToPhi(BasicBlock * BB,const PredBlockVector & BBPreds,PHINode * PN,BasicBlock * CommonPred)1057f8af5cf6SDimitry Andric static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
1058f8af5cf6SDimitry Andric                                                 const PredBlockVector &BBPreds,
1059b1c73532SDimitry Andric                                                 PHINode *PN,
1060b1c73532SDimitry Andric                                                 BasicBlock *CommonPred) {
1061f8af5cf6SDimitry Andric   Value *OldVal = PN->removeIncomingValue(BB, false);
1062f8af5cf6SDimitry Andric   assert(OldVal && "No entry in PHI for Pred BB!");
1063f8af5cf6SDimitry Andric 
1064f8af5cf6SDimitry Andric   IncomingValueMap IncomingValues;
1065f8af5cf6SDimitry Andric 
1066f8af5cf6SDimitry Andric   // We are merging two blocks - BB, and the block containing PN - and
1067f8af5cf6SDimitry Andric   // as a result we need to redirect edges from the predecessors of BB
1068f8af5cf6SDimitry Andric   // to go to the block containing PN, and update PN
1069f8af5cf6SDimitry Andric   // accordingly. Since we allow merging blocks in the case where the
1070f8af5cf6SDimitry Andric   // predecessor and successor blocks both share some predecessors,
1071f8af5cf6SDimitry Andric   // and where some of those common predecessors might have undef
1072f8af5cf6SDimitry Andric   // values flowing into PN, we want to rewrite those values to be
1073f8af5cf6SDimitry Andric   // consistent with the non-undef values.
1074f8af5cf6SDimitry Andric 
1075f8af5cf6SDimitry Andric   gatherIncomingValuesToPhi(PN, IncomingValues);
1076f8af5cf6SDimitry Andric 
1077f8af5cf6SDimitry Andric   // If this incoming value is one of the PHI nodes in BB, the new entries
1078f8af5cf6SDimitry Andric   // in the PHI node are the entries from the old PHI.
1079f8af5cf6SDimitry Andric   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
1080f8af5cf6SDimitry Andric     PHINode *OldValPN = cast<PHINode>(OldVal);
1081f8af5cf6SDimitry Andric     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1082f8af5cf6SDimitry Andric       // Note that, since we are merging phi nodes and BB and Succ might
1083f8af5cf6SDimitry Andric       // have common predecessors, we could end up with a phi node with
1084f8af5cf6SDimitry Andric       // identical incoming branches. This will be cleaned up later (and
1085f8af5cf6SDimitry Andric       // will trigger asserts if we try to clean it up now, without also
1086f8af5cf6SDimitry Andric       // simplifying the corresponding conditional branch).
1087f8af5cf6SDimitry Andric       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1088b1c73532SDimitry Andric 
1089b1c73532SDimitry Andric       if (PredBB == CommonPred)
1090b1c73532SDimitry Andric         continue;
1091b1c73532SDimitry Andric 
1092f8af5cf6SDimitry Andric       Value *PredVal = OldValPN->getIncomingValue(i);
1093b1c73532SDimitry Andric       Value *Selected =
1094b1c73532SDimitry Andric           selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);
1095f8af5cf6SDimitry Andric 
1096f8af5cf6SDimitry Andric       // And add a new incoming value for this predecessor for the
1097f8af5cf6SDimitry Andric       // newly retargeted branch.
1098f8af5cf6SDimitry Andric       PN->addIncoming(Selected, PredBB);
1099f8af5cf6SDimitry Andric     }
1100b1c73532SDimitry Andric     if (CommonPred)
1101b1c73532SDimitry Andric       PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);
1102b1c73532SDimitry Andric 
1103f8af5cf6SDimitry Andric   } else {
1104ac9a064cSDimitry Andric     for (BasicBlock *PredBB : BBPreds) {
1105f8af5cf6SDimitry Andric       // Update existing incoming values in PN for this
1106f8af5cf6SDimitry Andric       // predecessor of BB.
1107b1c73532SDimitry Andric       if (PredBB == CommonPred)
1108b1c73532SDimitry Andric         continue;
1109b1c73532SDimitry Andric 
1110b1c73532SDimitry Andric       Value *Selected =
1111b1c73532SDimitry Andric           selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);
1112f8af5cf6SDimitry Andric 
1113f8af5cf6SDimitry Andric       // And add a new incoming value for this predecessor for the
1114f8af5cf6SDimitry Andric       // newly retargeted branch.
1115f8af5cf6SDimitry Andric       PN->addIncoming(Selected, PredBB);
1116f8af5cf6SDimitry Andric     }
1117b1c73532SDimitry Andric     if (CommonPred)
1118b1c73532SDimitry Andric       PN->addIncoming(OldVal, BB);
1119f8af5cf6SDimitry Andric   }
1120f8af5cf6SDimitry Andric 
1121f8af5cf6SDimitry Andric   replaceUndefValuesInPhi(PN, IncomingValues);
1122f8af5cf6SDimitry Andric }
1123f8af5cf6SDimitry Andric 
TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock * BB,DomTreeUpdater * DTU)1124eb11fae6SDimitry Andric bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1125d8e91e46SDimitry Andric                                                    DomTreeUpdater *DTU) {
1126d39c594dSDimitry Andric   assert(BB != &BB->getParent()->getEntryBlock() &&
1127d39c594dSDimitry Andric          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1128d39c594dSDimitry Andric 
1129b1c73532SDimitry Andric   // We can't simplify infinite loops.
1130907da171SRoman Divacky   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
1131b1c73532SDimitry Andric   if (BB == Succ)
1132b1c73532SDimitry Andric     return false;
1133907da171SRoman Divacky 
1134b1c73532SDimitry Andric   SmallPtrSet<BasicBlock *, 16> BBPreds(pred_begin(BB), pred_end(BB));
1135b1c73532SDimitry Andric   SmallPtrSet<BasicBlock *, 16> SuccPreds(pred_begin(Succ), pred_end(Succ));
1136b1c73532SDimitry Andric 
1137b1c73532SDimitry Andric   // The single common predecessor of BB and Succ when BB cannot be killed
1138b1c73532SDimitry Andric   BasicBlock *CommonPred = nullptr;
1139b1c73532SDimitry Andric 
1140b1c73532SDimitry Andric   bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
1141b1c73532SDimitry Andric 
1142f56b67c4SDimitry Andric   // Even if we can not fold BB into Succ, we may be able to redirect the
1143b1c73532SDimitry Andric   // predecessors of BB to Succ.
1144b1c73532SDimitry Andric   bool BBPhisMergeable =
1145b1c73532SDimitry Andric       BBKillable ||
1146b1c73532SDimitry Andric       CanRedirectPredsOfEmptyBBToSucc(BB, Succ, BBPreds, SuccPreds, CommonPred);
1147b1c73532SDimitry Andric 
1148b1c73532SDimitry Andric   if (!BBKillable && !BBPhisMergeable)
1149b1c73532SDimitry Andric     return false;
1150b1c73532SDimitry Andric 
1151b1c73532SDimitry Andric   // Check to see if merging these blocks/phis would cause conflicts for any of
1152b1c73532SDimitry Andric   // the phi nodes in BB or Succ. If not, we can safely merge.
1153907da171SRoman Divacky 
1154907da171SRoman Divacky   // Check for cases where Succ has multiple predecessors and a PHI node in BB
1155907da171SRoman Divacky   // has uses which will not disappear when the PHI nodes are merged.  It is
1156907da171SRoman Divacky   // possible to handle such cases, but difficult: it requires checking whether
1157907da171SRoman Divacky   // BB dominates Succ, which is non-trivial to calculate in the case where
1158907da171SRoman Divacky   // Succ has multiple predecessors.  Also, it requires checking whether
11594a16efa3SDimitry Andric   // constructing the necessary self-referential PHI node doesn't introduce any
1160907da171SRoman Divacky   // conflicts; this isn't too difficult, but the previous code for doing this
1161907da171SRoman Divacky   // was incorrect.
1162907da171SRoman Divacky   //
1163907da171SRoman Divacky   // Note that if this check finds a live use, BB dominates Succ, so BB is
1164907da171SRoman Divacky   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1165907da171SRoman Divacky   // folding the branch isn't profitable in that case anyway.
1166907da171SRoman Divacky   if (!Succ->getSinglePredecessor()) {
1167907da171SRoman Divacky     BasicBlock::iterator BBI = BB->begin();
1168907da171SRoman Divacky     while (isa<PHINode>(*BBI)) {
11695ca98fd9SDimitry Andric       for (Use &U : BBI->uses()) {
11705ca98fd9SDimitry Andric         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
11715ca98fd9SDimitry Andric           if (PN->getIncomingBlock(U) != BB)
1172907da171SRoman Divacky             return false;
1173907da171SRoman Divacky         } else {
1174907da171SRoman Divacky           return false;
1175907da171SRoman Divacky         }
1176907da171SRoman Divacky       }
1177907da171SRoman Divacky       ++BBI;
1178907da171SRoman Divacky     }
1179907da171SRoman Divacky   }
1180907da171SRoman Divacky 
1181b1c73532SDimitry Andric   if (BBPhisMergeable && CommonPred)
1182b1c73532SDimitry Andric     LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()
1183b1c73532SDimitry Andric                       << " and " << Succ->getName() << " : "
1184b1c73532SDimitry Andric                       << CommonPred->getName() << "\n");
1185b1c73532SDimitry Andric 
1186e3b55780SDimitry Andric   // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1187e3b55780SDimitry Andric   // metadata.
1188e3b55780SDimitry Andric   //
1189e3b55780SDimitry Andric   // FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1190e3b55780SDimitry Andric   // current status (that loop metadata is implemented as metadata attached to
1191e3b55780SDimitry Andric   // the branch instruction in the loop latch block). To quote from review
1192e3b55780SDimitry Andric   // comments, "the current representation of loop metadata (using a loop latch
1193e3b55780SDimitry Andric   // terminator attachment) is known to be fundamentally broken. Loop latches
1194e3b55780SDimitry Andric   // are not uniquely associated with loops (both in that a latch can be part of
1195e3b55780SDimitry Andric   // multiple loops and a loop may have multiple latches). Loop headers are. The
1196e3b55780SDimitry Andric   // solution to this problem is also known: Add support for basic block
1197e3b55780SDimitry Andric   // metadata, and attach loop metadata to the loop header."
1198e3b55780SDimitry Andric   //
1199e3b55780SDimitry Andric   // Why bail out:
1200e3b55780SDimitry Andric   // In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1201e3b55780SDimitry Andric   // the latch for inner-loop (see reason below), so bail out to prerserve
1202e3b55780SDimitry Andric   // inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1203e3b55780SDimitry Andric   // to this inner-loop.
1204e3b55780SDimitry Andric   // - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1205e3b55780SDimitry Andric   // loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1206e3b55780SDimitry Andric   // then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1207e3b55780SDimitry Andric   // one self-looping basic block, which is contradictory with the assumption.
1208e3b55780SDimitry Andric   //
1209e3b55780SDimitry Andric   // To illustrate how inner-loop metadata is dropped:
1210e3b55780SDimitry Andric   //
1211e3b55780SDimitry Andric   // CFG Before
1212e3b55780SDimitry Andric   //
1213e3b55780SDimitry Andric   // BB is while.cond.exit, attached with loop metdata md2.
1214e3b55780SDimitry Andric   // BB->Pred is for.body, attached with loop metadata md1.
1215e3b55780SDimitry Andric   //
1216e3b55780SDimitry Andric   //      entry
1217e3b55780SDimitry Andric   //        |
1218e3b55780SDimitry Andric   //        v
1219e3b55780SDimitry Andric   // ---> while.cond   ------------->  while.end
1220e3b55780SDimitry Andric   // |       |
1221e3b55780SDimitry Andric   // |       v
1222e3b55780SDimitry Andric   // |   while.body
1223e3b55780SDimitry Andric   // |       |
1224e3b55780SDimitry Andric   // |       v
1225e3b55780SDimitry Andric   // |    for.body <---- (md1)
1226e3b55780SDimitry Andric   // |       |  |______|
1227e3b55780SDimitry Andric   // |       v
1228e3b55780SDimitry Andric   // |    while.cond.exit (md2)
1229e3b55780SDimitry Andric   // |       |
1230e3b55780SDimitry Andric   // |_______|
1231e3b55780SDimitry Andric   //
1232e3b55780SDimitry Andric   // CFG After
1233e3b55780SDimitry Andric   //
1234e3b55780SDimitry Andric   // while.cond1 is the merge of while.cond.exit and while.cond above.
1235e3b55780SDimitry Andric   // for.body is attached with md2, and md1 is dropped.
1236e3b55780SDimitry Andric   // If LoopSimplify runs later (as a part of loop pass), it could create
1237e3b55780SDimitry Andric   // dedicated exits for inner-loop (essentially adding `while.cond.exit`
1238e3b55780SDimitry Andric   // back), but won't it won't see 'md1' nor restore it for the inner-loop.
1239e3b55780SDimitry Andric   //
1240e3b55780SDimitry Andric   //       entry
1241e3b55780SDimitry Andric   //         |
1242e3b55780SDimitry Andric   //         v
1243e3b55780SDimitry Andric   // ---> while.cond1  ------------->  while.end
1244e3b55780SDimitry Andric   // |       |
1245e3b55780SDimitry Andric   // |       v
1246e3b55780SDimitry Andric   // |   while.body
1247e3b55780SDimitry Andric   // |       |
1248e3b55780SDimitry Andric   // |       v
1249e3b55780SDimitry Andric   // |    for.body <---- (md2)
1250e3b55780SDimitry Andric   // |_______|  |______|
1251e3b55780SDimitry Andric   if (Instruction *TI = BB->getTerminator())
1252e3b55780SDimitry Andric     if (TI->hasMetadata(LLVMContext::MD_loop))
1253e3b55780SDimitry Andric       for (BasicBlock *Pred : predecessors(BB))
1254e3b55780SDimitry Andric         if (Instruction *PredTI = Pred->getTerminator())
1255e3b55780SDimitry Andric           if (PredTI->hasMetadata(LLVMContext::MD_loop))
1256e6d15924SDimitry Andric             return false;
1257e6d15924SDimitry Andric 
1258b1c73532SDimitry Andric   if (BBKillable)
1259eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1260b1c73532SDimitry Andric   else if (BBPhisMergeable)
1261b1c73532SDimitry Andric     LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);
1262eb11fae6SDimitry Andric 
1263d8e91e46SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
1264b1c73532SDimitry Andric 
1265d8e91e46SDimitry Andric   if (DTU) {
1266f65dcba8SDimitry Andric     // To avoid processing the same predecessor more than once.
1267f65dcba8SDimitry Andric     SmallPtrSet<BasicBlock *, 8> SeenPreds;
1268b1c73532SDimitry Andric     // All predecessors of BB (except the common predecessor) will be moved to
1269b1c73532SDimitry Andric     // Succ.
1270f65dcba8SDimitry Andric     Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);
1271b1c73532SDimitry Andric 
1272b1c73532SDimitry Andric     for (auto *PredOfBB : predecessors(BB)) {
1273b1c73532SDimitry Andric       // Do not modify those common predecessors of BB and Succ
1274b1c73532SDimitry Andric       if (!SuccPreds.contains(PredOfBB))
1275f65dcba8SDimitry Andric         if (SeenPreds.insert(PredOfBB).second)
1276344a3780SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
1277b1c73532SDimitry Andric     }
1278b1c73532SDimitry Andric 
1279f65dcba8SDimitry Andric     SeenPreds.clear();
1280b1c73532SDimitry Andric 
1281f65dcba8SDimitry Andric     for (auto *PredOfBB : predecessors(BB))
1282b1c73532SDimitry Andric       // When BB cannot be killed, do not remove the edge between BB and
1283b1c73532SDimitry Andric       // CommonPred.
1284b1c73532SDimitry Andric       if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)
1285344a3780SDimitry Andric         Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
1286b1c73532SDimitry Andric 
1287b1c73532SDimitry Andric     if (BBKillable)
1288b60736ecSDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, Succ});
1289eb11fae6SDimitry Andric   }
1290907da171SRoman Divacky 
1291907da171SRoman Divacky   if (isa<PHINode>(Succ->begin())) {
1292907da171SRoman Divacky     // If there is more than one pred of succ, and there are PHI nodes in
1293907da171SRoman Divacky     // the successor, then we need to add incoming edges for the PHI nodes
1294907da171SRoman Divacky     //
1295145449b1SDimitry Andric     const PredBlockVector BBPreds(predecessors(BB));
1296907da171SRoman Divacky 
1297907da171SRoman Divacky     // Loop over all of the PHI nodes in the successor of BB.
1298907da171SRoman Divacky     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1299907da171SRoman Divacky       PHINode *PN = cast<PHINode>(I);
1300b1c73532SDimitry Andric       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
1301907da171SRoman Divacky     }
1302907da171SRoman Divacky   }
1303907da171SRoman Divacky 
1304907da171SRoman Divacky   if (Succ->getSinglePredecessor()) {
1305907da171SRoman Divacky     // BB is the only predecessor of Succ, so Succ will end up with exactly
1306907da171SRoman Divacky     // the same predecessors BB had.
1307411bd29eSDimitry Andric     // Copy over any phi, debug or lifetime instruction.
1308411bd29eSDimitry Andric     BB->getTerminator()->eraseFromParent();
1309b1c73532SDimitry Andric     Succ->splice(Succ->getFirstNonPHIIt(), BB);
1310907da171SRoman Divacky   } else {
1311411bd29eSDimitry Andric     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1312b1c73532SDimitry Andric       // We explicitly check for such uses for merging phis.
1313907da171SRoman Divacky       assert(PN->use_empty() && "There shouldn't be any uses here!");
1314907da171SRoman Divacky       PN->eraseFromParent();
1315907da171SRoman Divacky     }
1316907da171SRoman Divacky   }
1317907da171SRoman Divacky 
1318b915e9e0SDimitry Andric   // If the unconditional branch we replaced contains llvm.loop metadata, we
1319b915e9e0SDimitry Andric   // add the metadata to the branch instructions in the predecessors.
13207fa27ce4SDimitry Andric   if (Instruction *TI = BB->getTerminator())
13217fa27ce4SDimitry Andric     if (MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop))
1322344a3780SDimitry Andric       for (BasicBlock *Pred : predecessors(BB))
13237fa27ce4SDimitry Andric         Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1324b915e9e0SDimitry Andric 
1325b1c73532SDimitry Andric   if (BBKillable) {
1326907da171SRoman Divacky     // Everything that jumped to BB now goes to Succ.
1327907da171SRoman Divacky     BB->replaceAllUsesWith(Succ);
1328b1c73532SDimitry Andric 
1329b1c73532SDimitry Andric     if (!Succ->hasName())
1330b1c73532SDimitry Andric       Succ->takeName(BB);
1331eb11fae6SDimitry Andric 
1332d8e91e46SDimitry Andric     // Clear the successor list of BB to match updates applying to DTU later.
1333d8e91e46SDimitry Andric     if (BB->getTerminator())
1334e3b55780SDimitry Andric       BB->back().eraseFromParent();
1335b1c73532SDimitry Andric 
1336d8e91e46SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
1337d8e91e46SDimitry Andric     assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1338d8e91e46SDimitry Andric                              "applying corresponding DTU updates.");
1339b1c73532SDimitry Andric   } else if (BBPhisMergeable) {
1340b1c73532SDimitry Andric     //  Everything except CommonPred that jumped to BB now goes to Succ.
1341b1c73532SDimitry Andric     BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) -> bool {
1342b1c73532SDimitry Andric       if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
1343b1c73532SDimitry Andric         return UseInst->getParent() != CommonPred &&
1344b1c73532SDimitry Andric                BBPreds.contains(UseInst->getParent());
1345b1c73532SDimitry Andric       return false;
1346b1c73532SDimitry Andric     });
1347b1c73532SDimitry Andric   }
1348d8e91e46SDimitry Andric 
1349344a3780SDimitry Andric   if (DTU)
1350b60736ecSDimitry Andric     DTU->applyUpdates(Updates);
1351344a3780SDimitry Andric 
1352b1c73532SDimitry Andric   if (BBKillable)
1353344a3780SDimitry Andric     DeleteDeadBlock(BB, DTU);
1354344a3780SDimitry Andric 
1355907da171SRoman Divacky   return true;
1356907da171SRoman Divacky }
1357907da171SRoman Divacky 
1358b1c73532SDimitry Andric static bool
EliminateDuplicatePHINodesNaiveImpl(BasicBlock * BB,SmallPtrSetImpl<PHINode * > & ToRemove)1359b1c73532SDimitry Andric EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,
1360b1c73532SDimitry Andric                                     SmallPtrSetImpl<PHINode *> &ToRemove) {
1361b60736ecSDimitry Andric   // This implementation doesn't currently consider undef operands
1362b60736ecSDimitry Andric   // specially. Theoretically, two phis which are identical except for
1363b60736ecSDimitry Andric   // one having an undef where the other doesn't could be collapsed.
1364b60736ecSDimitry Andric 
1365b60736ecSDimitry Andric   bool Changed = false;
1366b60736ecSDimitry Andric 
1367b60736ecSDimitry Andric   // Examine each PHI.
1368b60736ecSDimitry Andric   // Note that increment of I must *NOT* be in the iteration_expression, since
1369b60736ecSDimitry Andric   // we don't want to immediately advance when we restart from the beginning.
1370b60736ecSDimitry Andric   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
1371b60736ecSDimitry Andric     ++I;
1372b60736ecSDimitry Andric     // Is there an identical PHI node in this basic block?
1373b60736ecSDimitry Andric     // Note that we only look in the upper square's triangle,
1374b60736ecSDimitry Andric     // we already checked that the lower triangle PHI's aren't identical.
1375b60736ecSDimitry Andric     for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1376b1c73532SDimitry Andric       if (ToRemove.contains(DuplicatePN))
1377b1c73532SDimitry Andric         continue;
1378b60736ecSDimitry Andric       if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1379b60736ecSDimitry Andric         continue;
1380b60736ecSDimitry Andric       // A duplicate. Replace this PHI with the base PHI.
1381b60736ecSDimitry Andric       ++NumPHICSEs;
1382b60736ecSDimitry Andric       DuplicatePN->replaceAllUsesWith(PN);
1383b1c73532SDimitry Andric       ToRemove.insert(DuplicatePN);
1384b60736ecSDimitry Andric       Changed = true;
1385b60736ecSDimitry Andric 
1386b60736ecSDimitry Andric       // The RAUW can change PHIs that we already visited.
1387b60736ecSDimitry Andric       I = BB->begin();
1388b60736ecSDimitry Andric       break; // Start over from the beginning.
1389b60736ecSDimitry Andric     }
1390b60736ecSDimitry Andric   }
1391b60736ecSDimitry Andric   return Changed;
1392b60736ecSDimitry Andric }
1393b60736ecSDimitry Andric 
1394b1c73532SDimitry Andric static bool
EliminateDuplicatePHINodesSetBasedImpl(BasicBlock * BB,SmallPtrSetImpl<PHINode * > & ToRemove)1395b1c73532SDimitry Andric EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,
1396b1c73532SDimitry Andric                                        SmallPtrSetImpl<PHINode *> &ToRemove) {
1397571945e6SRoman Divacky   // This implementation doesn't currently consider undef operands
1398411bd29eSDimitry Andric   // specially. Theoretically, two phis which are identical except for
1399571945e6SRoman Divacky   // one having an undef where the other doesn't could be collapsed.
1400571945e6SRoman Divacky 
14013a0822f0SDimitry Andric   struct PHIDenseMapInfo {
14023a0822f0SDimitry Andric     static PHINode *getEmptyKey() {
14033a0822f0SDimitry Andric       return DenseMapInfo<PHINode *>::getEmptyKey();
14043a0822f0SDimitry Andric     }
1405044eb2f6SDimitry Andric 
14063a0822f0SDimitry Andric     static PHINode *getTombstoneKey() {
14073a0822f0SDimitry Andric       return DenseMapInfo<PHINode *>::getTombstoneKey();
14083a0822f0SDimitry Andric     }
1409044eb2f6SDimitry Andric 
1410b60736ecSDimitry Andric     static bool isSentinel(PHINode *PN) {
1411b60736ecSDimitry Andric       return PN == getEmptyKey() || PN == getTombstoneKey();
1412b60736ecSDimitry Andric     }
1413b60736ecSDimitry Andric 
1414b60736ecSDimitry Andric     // WARNING: this logic must be kept in sync with
1415b60736ecSDimitry Andric     //          Instruction::isIdenticalToWhenDefined()!
1416b60736ecSDimitry Andric     static unsigned getHashValueImpl(PHINode *PN) {
14173a0822f0SDimitry Andric       // Compute a hash value on the operands. Instcombine will likely have
14183a0822f0SDimitry Andric       // sorted them, which helps expose duplicates, but we have to check all
14193a0822f0SDimitry Andric       // the operands to be safe in case instcombine hasn't run.
14203a0822f0SDimitry Andric       return static_cast<unsigned>(hash_combine(
14213a0822f0SDimitry Andric           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
14223a0822f0SDimitry Andric           hash_combine_range(PN->block_begin(), PN->block_end())));
14233a0822f0SDimitry Andric     }
1424044eb2f6SDimitry Andric 
1425b60736ecSDimitry Andric     static unsigned getHashValue(PHINode *PN) {
1426b60736ecSDimitry Andric #ifndef NDEBUG
1427b60736ecSDimitry Andric       // If -phicse-debug-hash was specified, return a constant -- this
1428b60736ecSDimitry Andric       // will force all hashing to collide, so we'll exhaustively search
1429b60736ecSDimitry Andric       // the table for a match, and the assertion in isEqual will fire if
1430b60736ecSDimitry Andric       // there's a bug causing equal keys to hash differently.
1431b60736ecSDimitry Andric       if (PHICSEDebugHash)
1432b60736ecSDimitry Andric         return 0;
1433b60736ecSDimitry Andric #endif
1434b60736ecSDimitry Andric       return getHashValueImpl(PN);
1435b60736ecSDimitry Andric     }
1436b60736ecSDimitry Andric 
1437b60736ecSDimitry Andric     static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1438b60736ecSDimitry Andric       if (isSentinel(LHS) || isSentinel(RHS))
14393a0822f0SDimitry Andric         return LHS == RHS;
14403a0822f0SDimitry Andric       return LHS->isIdenticalTo(RHS);
14413a0822f0SDimitry Andric     }
1442b60736ecSDimitry Andric 
1443b60736ecSDimitry Andric     static bool isEqual(PHINode *LHS, PHINode *RHS) {
1444b60736ecSDimitry Andric       // These comparisons are nontrivial, so assert that equality implies
1445b60736ecSDimitry Andric       // hash equality (DenseMap demands this as an invariant).
1446b60736ecSDimitry Andric       bool Result = isEqualImpl(LHS, RHS);
1447b60736ecSDimitry Andric       assert(!Result || (isSentinel(LHS) && LHS == RHS) ||
1448b60736ecSDimitry Andric              getHashValueImpl(LHS) == getHashValueImpl(RHS));
1449b60736ecSDimitry Andric       return Result;
1450b60736ecSDimitry Andric     }
14513a0822f0SDimitry Andric   };
1452571945e6SRoman Divacky 
14533a0822f0SDimitry Andric   // Set of unique PHINodes.
14543a0822f0SDimitry Andric   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1455b60736ecSDimitry Andric   PHISet.reserve(4 * PHICSENumPHISmallSize);
1456571945e6SRoman Divacky 
1457571945e6SRoman Divacky   // Examine each PHI.
14583a0822f0SDimitry Andric   bool Changed = false;
14593a0822f0SDimitry Andric   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1460b1c73532SDimitry Andric     if (ToRemove.contains(PN))
1461b1c73532SDimitry Andric       continue;
14623a0822f0SDimitry Andric     auto Inserted = PHISet.insert(PN);
14633a0822f0SDimitry Andric     if (!Inserted.second) {
1464571945e6SRoman Divacky       // A duplicate. Replace this PHI with its duplicate.
1465b60736ecSDimitry Andric       ++NumPHICSEs;
14663a0822f0SDimitry Andric       PN->replaceAllUsesWith(*Inserted.first);
1467b1c73532SDimitry Andric       ToRemove.insert(PN);
1468571945e6SRoman Divacky       Changed = true;
14692fe5752eSDimitry Andric 
14702fe5752eSDimitry Andric       // The RAUW can change PHIs that we already visited. Start over from the
14712fe5752eSDimitry Andric       // beginning.
14722fe5752eSDimitry Andric       PHISet.clear();
14732fe5752eSDimitry Andric       I = BB->begin();
1474571945e6SRoman Divacky     }
1475571945e6SRoman Divacky   }
1476571945e6SRoman Divacky 
1477571945e6SRoman Divacky   return Changed;
1478571945e6SRoman Divacky }
1479cf099d11SDimitry Andric 
EliminateDuplicatePHINodes(BasicBlock * BB,SmallPtrSetImpl<PHINode * > & ToRemove)1480b1c73532SDimitry Andric bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB,
1481b1c73532SDimitry Andric                                       SmallPtrSetImpl<PHINode *> &ToRemove) {
1482b60736ecSDimitry Andric   if (
1483b60736ecSDimitry Andric #ifndef NDEBUG
1484b60736ecSDimitry Andric       !PHICSEDebugHash &&
1485b60736ecSDimitry Andric #endif
1486b60736ecSDimitry Andric       hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))
1487b1c73532SDimitry Andric     return EliminateDuplicatePHINodesNaiveImpl(BB, ToRemove);
1488b1c73532SDimitry Andric   return EliminateDuplicatePHINodesSetBasedImpl(BB, ToRemove);
1489b60736ecSDimitry Andric }
1490dadbdfffSDimitry Andric 
EliminateDuplicatePHINodes(BasicBlock * BB)1491b1c73532SDimitry Andric bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1492b1c73532SDimitry Andric   SmallPtrSet<PHINode *, 8> ToRemove;
1493b1c73532SDimitry Andric   bool Changed = EliminateDuplicatePHINodes(BB, ToRemove);
1494b1c73532SDimitry Andric   for (PHINode *PN : ToRemove)
1495b1c73532SDimitry Andric     PN->eraseFromParent();
1496b1c73532SDimitry Andric   return Changed;
1497b1c73532SDimitry Andric }
1498b1c73532SDimitry Andric 
tryEnforceAlignment(Value * V,Align PrefAlign,const DataLayout & DL)1499b1c73532SDimitry Andric Align llvm::tryEnforceAlignment(Value *V, Align PrefAlign,
1500b60736ecSDimitry Andric                                 const DataLayout &DL) {
1501411bd29eSDimitry Andric   V = V->stripPointerCasts();
1502cf099d11SDimitry Andric 
1503411bd29eSDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1504b60736ecSDimitry Andric     // TODO: Ideally, this function would not be called if PrefAlign is smaller
1505b60736ecSDimitry Andric     // than the current alignment, as the known bits calculation should have
1506b60736ecSDimitry Andric     // already taken it into account. However, this is not always the case,
1507b60736ecSDimitry Andric     // as computeKnownBits() has a depth limit, while stripPointerCasts()
1508b60736ecSDimitry Andric     // doesn't.
1509b60736ecSDimitry Andric     Align CurrentAlign = AI->getAlign();
1510b60736ecSDimitry Andric     if (PrefAlign <= CurrentAlign)
1511b60736ecSDimitry Andric       return CurrentAlign;
1512dadbdfffSDimitry Andric 
151330815c53SDimitry Andric     // If the preferred alignment is greater than the natural stack alignment
151430815c53SDimitry Andric     // then don't round up. This avoids dynamic stack realignment.
1515cfca06d7SDimitry Andric     if (DL.exceedsNaturalStackAlignment(PrefAlign))
1516b60736ecSDimitry Andric       return CurrentAlign;
1517cfca06d7SDimitry Andric     AI->setAlignment(PrefAlign);
1518cf099d11SDimitry Andric     return PrefAlign;
1519cf099d11SDimitry Andric   }
1520cf099d11SDimitry Andric 
15215ca98fd9SDimitry Andric   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1522dadbdfffSDimitry Andric     // TODO: as above, this shouldn't be necessary.
1523b60736ecSDimitry Andric     Align CurrentAlign = GO->getPointerAlignment(DL);
1524b60736ecSDimitry Andric     if (PrefAlign <= CurrentAlign)
1525b60736ecSDimitry Andric       return CurrentAlign;
1526dadbdfffSDimitry Andric 
1527cf099d11SDimitry Andric     // If there is a large requested alignment and we can, bump up the alignment
1528ee8648bdSDimitry Andric     // of the global.  If the memory we set aside for the global may not be the
1529ee8648bdSDimitry Andric     // memory used by the final program then it is impossible for us to reliably
1530ee8648bdSDimitry Andric     // enforce the preferred alignment.
1531dadbdfffSDimitry Andric     if (!GO->canIncreaseAlignment())
1532b60736ecSDimitry Andric       return CurrentAlign;
1533cf099d11SDimitry Andric 
15347fa27ce4SDimitry Andric     if (GO->isThreadLocal()) {
15357fa27ce4SDimitry Andric       unsigned MaxTLSAlign = GO->getParent()->getMaxTLSAlignment() / CHAR_BIT;
15367fa27ce4SDimitry Andric       if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))
15377fa27ce4SDimitry Andric         PrefAlign = Align(MaxTLSAlign);
15387fa27ce4SDimitry Andric     }
15397fa27ce4SDimitry Andric 
1540cfca06d7SDimitry Andric     GO->setAlignment(PrefAlign);
1541dadbdfffSDimitry Andric     return PrefAlign;
1542cf099d11SDimitry Andric   }
1543cf099d11SDimitry Andric 
1544b60736ecSDimitry Andric   return Align(1);
1545cf099d11SDimitry Andric }
1546cf099d11SDimitry Andric 
getOrEnforceKnownAlignment(Value * V,MaybeAlign PrefAlign,const DataLayout & DL,const Instruction * CxtI,AssumptionCache * AC,const DominatorTree * DT)1547cfca06d7SDimitry Andric Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
15485a5ac124SDimitry Andric                                        const DataLayout &DL,
154967c32a98SDimitry Andric                                        const Instruction *CxtI,
15505a5ac124SDimitry Andric                                        AssumptionCache *AC,
155167c32a98SDimitry Andric                                        const DominatorTree *DT) {
1552cf099d11SDimitry Andric   assert(V->getType()->isPointerTy() &&
1553cf099d11SDimitry Andric          "getOrEnforceKnownAlignment expects a pointer!");
1554f8af5cf6SDimitry Andric 
1555ab44ce3dSDimitry Andric   KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
15566b3f41edSDimitry Andric   unsigned TrailZ = Known.countMinTrailingZeros();
1557cf099d11SDimitry Andric 
1558f8af5cf6SDimitry Andric   // Avoid trouble with ridiculously large TrailZ values, such as
1559cf099d11SDimitry Andric   // those computed from a null pointer.
1560cfca06d7SDimitry Andric   // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1561cfca06d7SDimitry Andric   TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1562cf099d11SDimitry Andric 
1563cfca06d7SDimitry Andric   Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1564cf099d11SDimitry Andric 
1565cfca06d7SDimitry Andric   if (PrefAlign && *PrefAlign > Alignment)
1566b60736ecSDimitry Andric     Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
1567cf099d11SDimitry Andric 
1568cf099d11SDimitry Andric   // We don't need to make any adjustment.
1569cfca06d7SDimitry Andric   return Alignment;
1570cf099d11SDimitry Andric }
1571cf099d11SDimitry Andric 
15726b943ff3SDimitry Andric ///===---------------------------------------------------------------------===//
15736b943ff3SDimitry Andric ///  Dbg Intrinsic utilities
15746b943ff3SDimitry Andric ///
15756b943ff3SDimitry Andric 
1576b915e9e0SDimitry Andric /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
PhiHasDebugValue(DILocalVariable * DIVar,DIExpression * DIExpr,PHINode * APN)1577b915e9e0SDimitry Andric static bool PhiHasDebugValue(DILocalVariable *DIVar,
1578b915e9e0SDimitry Andric                              DIExpression *DIExpr,
1579b915e9e0SDimitry Andric                              PHINode *APN) {
1580145449b1SDimitry Andric   // Since we can't guarantee that the original dbg.declare intrinsic
1581b915e9e0SDimitry Andric   // is removed by LowerDbgDeclare(), we need to make sure that we are
1582b915e9e0SDimitry Andric   // not inserting the same dbg.value intrinsic over and over.
158371d5a254SDimitry Andric   SmallVector<DbgValueInst *, 1> DbgValues;
1584ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
1585ac9a064cSDimitry Andric   findDbgValues(DbgValues, APN, &DbgVariableRecords);
158671d5a254SDimitry Andric   for (auto *DVI : DbgValues) {
1587344a3780SDimitry Andric     assert(is_contained(DVI->getValues(), APN));
1588b915e9e0SDimitry Andric     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1589b915e9e0SDimitry Andric       return true;
1590b915e9e0SDimitry Andric   }
1591ac9a064cSDimitry Andric   for (auto *DVR : DbgVariableRecords) {
1592ac9a064cSDimitry Andric     assert(is_contained(DVR->location_ops(), APN));
1593ac9a064cSDimitry Andric     if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1594b1c73532SDimitry Andric       return true;
1595b1c73532SDimitry Andric   }
1596b915e9e0SDimitry Andric   return false;
1597b915e9e0SDimitry Andric }
1598b915e9e0SDimitry Andric 
1599eb11fae6SDimitry Andric /// Check if the alloc size of \p ValTy is large enough to cover the variable
1600eb11fae6SDimitry Andric /// (or fragment of the variable) described by \p DII.
1601eb11fae6SDimitry Andric ///
1602eb11fae6SDimitry Andric /// This is primarily intended as a helper for the different
16037fa27ce4SDimitry Andric /// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
16047fa27ce4SDimitry Andric /// describes an alloca'd variable, so we need to use the alloc size of the
16057fa27ce4SDimitry Andric /// value when doing the comparison. E.g. an i1 value will be identified as
16067fa27ce4SDimitry Andric /// covering an n-bit fragment, if the store size of i1 is at least n bits.
valueCoversEntireFragment(Type * ValTy,DbgVariableIntrinsic * DII)1607d8e91e46SDimitry Andric static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1608ac9a064cSDimitry Andric   const DataLayout &DL = DII->getDataLayout();
1609b60736ecSDimitry Andric   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1610ac9a064cSDimitry Andric   if (std::optional<uint64_t> FragmentSize =
1611ac9a064cSDimitry Andric           DII->getExpression()->getActiveBits(DII->getVariable()))
16127fa27ce4SDimitry Andric     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
16137fa27ce4SDimitry Andric 
1614eb11fae6SDimitry Andric   // We can't always calculate the size of the DI variable (e.g. if it is a
1615eb11fae6SDimitry Andric   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1616eb11fae6SDimitry Andric   // intead.
1617344a3780SDimitry Andric   if (DII->isAddressOfVariable()) {
1618344a3780SDimitry Andric     // DII should have exactly 1 location when it is an address.
1619344a3780SDimitry Andric     assert(DII->getNumVariableLocationOps() == 1 &&
1620344a3780SDimitry Andric            "address of variable must have exactly 1 location operand.");
1621344a3780SDimitry Andric     if (auto *AI =
1622344a3780SDimitry Andric             dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
1623e3b55780SDimitry Andric       if (std::optional<TypeSize> FragmentSize =
1624e3b55780SDimitry Andric               AI->getAllocationSizeInBits(DL)) {
1625b60736ecSDimitry Andric         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1626b60736ecSDimitry Andric       }
1627344a3780SDimitry Andric     }
1628344a3780SDimitry Andric   }
1629eb11fae6SDimitry Andric   // Could not determine size of variable. Conservatively return false.
1630eb11fae6SDimitry Andric   return false;
1631eb11fae6SDimitry Andric }
1632ac9a064cSDimitry Andric // RemoveDIs: duplicate implementation of the above, using DbgVariableRecords,
1633ac9a064cSDimitry Andric // the replacement for dbg.values.
valueCoversEntireFragment(Type * ValTy,DbgVariableRecord * DVR)1634ac9a064cSDimitry Andric static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR) {
1635ac9a064cSDimitry Andric   const DataLayout &DL = DVR->getModule()->getDataLayout();
1636b1c73532SDimitry Andric   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1637ac9a064cSDimitry Andric   if (std::optional<uint64_t> FragmentSize =
1638ac9a064cSDimitry Andric           DVR->getExpression()->getActiveBits(DVR->getVariable()))
1639b1c73532SDimitry Andric     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
1640b1c73532SDimitry Andric 
1641b1c73532SDimitry Andric   // We can't always calculate the size of the DI variable (e.g. if it is a
1642b1c73532SDimitry Andric   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1643b1c73532SDimitry Andric   // intead.
1644ac9a064cSDimitry Andric   if (DVR->isAddressOfVariable()) {
1645ac9a064cSDimitry Andric     // DVR should have exactly 1 location when it is an address.
1646ac9a064cSDimitry Andric     assert(DVR->getNumVariableLocationOps() == 1 &&
1647b1c73532SDimitry Andric            "address of variable must have exactly 1 location operand.");
1648b1c73532SDimitry Andric     if (auto *AI =
1649ac9a064cSDimitry Andric             dyn_cast_or_null<AllocaInst>(DVR->getVariableLocationOp(0))) {
1650b1c73532SDimitry Andric       if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1651b1c73532SDimitry Andric         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1652b1c73532SDimitry Andric       }
1653b1c73532SDimitry Andric     }
1654b1c73532SDimitry Andric   }
1655b1c73532SDimitry Andric   // Could not determine size of variable. Conservatively return false.
1656b1c73532SDimitry Andric   return false;
1657b1c73532SDimitry Andric }
1658b1c73532SDimitry Andric 
insertDbgValueOrDbgVariableRecord(DIBuilder & Builder,Value * DV,DILocalVariable * DIVar,DIExpression * DIExpr,const DebugLoc & NewLoc,BasicBlock::iterator Instr)1659ac9a064cSDimitry Andric static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV,
1660b1c73532SDimitry Andric                                               DILocalVariable *DIVar,
1661b1c73532SDimitry Andric                                               DIExpression *DIExpr,
1662b1c73532SDimitry Andric                                               const DebugLoc &NewLoc,
1663b1c73532SDimitry Andric                                               BasicBlock::iterator Instr) {
1664b1c73532SDimitry Andric   if (!UseNewDbgInfoFormat) {
1665ac9a064cSDimitry Andric     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1666b1c73532SDimitry Andric                                                   (Instruction *)nullptr);
1667ac9a064cSDimitry Andric     DbgVal.get<Instruction *>()->insertBefore(Instr);
1668b1c73532SDimitry Andric   } else {
1669b1c73532SDimitry Andric     // RemoveDIs: if we're using the new debug-info format, allocate a
1670ac9a064cSDimitry Andric     // DbgVariableRecord directly instead of a dbg.value intrinsic.
1671b1c73532SDimitry Andric     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1672ac9a064cSDimitry Andric     DbgVariableRecord *DV =
1673ac9a064cSDimitry Andric         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1674ac9a064cSDimitry Andric     Instr->getParent()->insertDbgRecordBefore(DV, Instr);
1675b1c73532SDimitry Andric   }
1676b1c73532SDimitry Andric }
1677b1c73532SDimitry Andric 
insertDbgValueOrDbgVariableRecordAfter(DIBuilder & Builder,Value * DV,DILocalVariable * DIVar,DIExpression * DIExpr,const DebugLoc & NewLoc,BasicBlock::iterator Instr)1678ac9a064cSDimitry Andric static void insertDbgValueOrDbgVariableRecordAfter(
1679ac9a064cSDimitry Andric     DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr,
1680ac9a064cSDimitry Andric     const DebugLoc &NewLoc, BasicBlock::iterator Instr) {
1681b1c73532SDimitry Andric   if (!UseNewDbgInfoFormat) {
1682ac9a064cSDimitry Andric     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1683b1c73532SDimitry Andric                                                   (Instruction *)nullptr);
1684ac9a064cSDimitry Andric     DbgVal.get<Instruction *>()->insertAfter(&*Instr);
1685b1c73532SDimitry Andric   } else {
1686b1c73532SDimitry Andric     // RemoveDIs: if we're using the new debug-info format, allocate a
1687ac9a064cSDimitry Andric     // DbgVariableRecord directly instead of a dbg.value intrinsic.
1688b1c73532SDimitry Andric     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1689ac9a064cSDimitry Andric     DbgVariableRecord *DV =
1690ac9a064cSDimitry Andric         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1691ac9a064cSDimitry Andric     Instr->getParent()->insertDbgRecordAfter(DV, &*Instr);
1692b1c73532SDimitry Andric   }
1693b1c73532SDimitry Andric }
1694eb11fae6SDimitry Andric 
169559d6cff9SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
16967fa27ce4SDimitry Andric /// that has an associated llvm.dbg.declare intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,StoreInst * SI,DIBuilder & Builder)1697d8e91e46SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
16986b943ff3SDimitry Andric                                            StoreInst *SI, DIBuilder &Builder) {
1699e3b55780SDimitry Andric   assert(DII->isAddressOfVariable() || isa<DbgAssignIntrinsic>(DII));
1700044eb2f6SDimitry Andric   auto *DIVar = DII->getVariable();
17015a5ac124SDimitry Andric   assert(DIVar && "Missing variable");
1702044eb2f6SDimitry Andric   auto *DIExpr = DII->getExpression();
1703e6d15924SDimitry Andric   Value *DV = SI->getValueOperand();
17046b943ff3SDimitry Andric 
1705e3b55780SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
1706e6d15924SDimitry Andric 
17077fa27ce4SDimitry Andric   // If the alloca describes the variable itself, i.e. the expression in the
17087fa27ce4SDimitry Andric   // dbg.declare doesn't start with a dereference, we can perform the
17097fa27ce4SDimitry Andric   // conversion if the value covers the entire fragment of DII.
17107fa27ce4SDimitry Andric   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
17117fa27ce4SDimitry Andric   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
17127fa27ce4SDimitry Andric   // We conservatively ignore other dereferences, because the following two are
17137fa27ce4SDimitry Andric   // not equivalent:
17147fa27ce4SDimitry Andric   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
17157fa27ce4SDimitry Andric   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
17167fa27ce4SDimitry Andric   // The former is adding 2 to the address of the variable, whereas the latter
17177fa27ce4SDimitry Andric   // is adding 2 to the value of the variable. As such, we insist on just a
17187fa27ce4SDimitry Andric   // deref expression.
17197fa27ce4SDimitry Andric   bool CanConvert =
17207fa27ce4SDimitry Andric       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
17217fa27ce4SDimitry Andric                             valueCoversEntireFragment(DV->getType(), DII));
17227fa27ce4SDimitry Andric   if (CanConvert) {
1723ac9a064cSDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1724b1c73532SDimitry Andric                                       SI->getIterator());
17257fa27ce4SDimitry Andric     return;
17267fa27ce4SDimitry Andric   }
17277fa27ce4SDimitry Andric 
1728eb11fae6SDimitry Andric   // FIXME: If storing to a part of the variable described by the dbg.declare,
1729eb11fae6SDimitry Andric   // then we want to insert a dbg.value for the corresponding fragment.
17307fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DII
17317fa27ce4SDimitry Andric                     << '\n');
1732eb11fae6SDimitry Andric   // For now, when there is a store to parts of the variable (but we do not
1733145449b1SDimitry Andric   // know which part) we insert an dbg.value intrinsic to indicate that we
1734eb11fae6SDimitry Andric   // know nothing about the variable's content.
1735eb11fae6SDimitry Andric   DV = UndefValue::get(DV->getType());
1736ac9a064cSDimitry Andric   insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1737b1c73532SDimitry Andric                                     SI->getIterator());
1738b1c73532SDimitry Andric }
1739b1c73532SDimitry Andric 
174059d6cff9SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
17417fa27ce4SDimitry Andric /// that has an associated llvm.dbg.declare intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,LoadInst * LI,DIBuilder & Builder)1742d8e91e46SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
17436b943ff3SDimitry Andric                                            LoadInst *LI, DIBuilder &Builder) {
1744044eb2f6SDimitry Andric   auto *DIVar = DII->getVariable();
1745044eb2f6SDimitry Andric   auto *DIExpr = DII->getExpression();
17465a5ac124SDimitry Andric   assert(DIVar && "Missing variable");
17476b943ff3SDimitry Andric 
1748eb11fae6SDimitry Andric   if (!valueCoversEntireFragment(LI->getType(), DII)) {
1749eb11fae6SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
1750eb11fae6SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
1751eb11fae6SDimitry Andric     // fragment.
1752eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1753eb11fae6SDimitry Andric                       << *DII << '\n');
1754eb11fae6SDimitry Andric     return;
1755eb11fae6SDimitry Andric   }
1756eb11fae6SDimitry Andric 
1757e3b55780SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
1758e6d15924SDimitry Andric 
1759dd58ef01SDimitry Andric   // We are now tracking the loaded value instead of the address. In the
1760dd58ef01SDimitry Andric   // future if multi-location support is added to the IR, it might be
1761dd58ef01SDimitry Andric   // preferable to keep tracking both the loaded value and the original
1762dd58ef01SDimitry Andric   // address in case the alloca can not be elided.
1763ac9a064cSDimitry Andric   insertDbgValueOrDbgVariableRecordAfter(Builder, LI, DIVar, DIExpr, NewLoc,
1764b1c73532SDimitry Andric                                          LI->getIterator());
1765b1c73532SDimitry Andric }
1766b1c73532SDimitry Andric 
ConvertDebugDeclareToDebugValue(DbgVariableRecord * DVR,StoreInst * SI,DIBuilder & Builder)1767ac9a064cSDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
1768ac9a064cSDimitry Andric                                            StoreInst *SI, DIBuilder &Builder) {
1769ac9a064cSDimitry Andric   assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
1770ac9a064cSDimitry Andric   auto *DIVar = DVR->getVariable();
1771b1c73532SDimitry Andric   assert(DIVar && "Missing variable");
1772ac9a064cSDimitry Andric   auto *DIExpr = DVR->getExpression();
1773b1c73532SDimitry Andric   Value *DV = SI->getValueOperand();
1774b1c73532SDimitry Andric 
1775ac9a064cSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
1776b1c73532SDimitry Andric 
1777312c0ed1SDimitry Andric   // If the alloca describes the variable itself, i.e. the expression in the
1778312c0ed1SDimitry Andric   // dbg.declare doesn't start with a dereference, we can perform the
1779312c0ed1SDimitry Andric   // conversion if the value covers the entire fragment of DII.
1780312c0ed1SDimitry Andric   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
1781312c0ed1SDimitry Andric   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
1782312c0ed1SDimitry Andric   // We conservatively ignore other dereferences, because the following two are
1783312c0ed1SDimitry Andric   // not equivalent:
1784312c0ed1SDimitry Andric   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1785312c0ed1SDimitry Andric   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1786312c0ed1SDimitry Andric   // The former is adding 2 to the address of the variable, whereas the latter
1787312c0ed1SDimitry Andric   // is adding 2 to the value of the variable. As such, we insist on just a
1788312c0ed1SDimitry Andric   // deref expression.
1789312c0ed1SDimitry Andric   bool CanConvert =
1790312c0ed1SDimitry Andric       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1791ac9a064cSDimitry Andric                             valueCoversEntireFragment(DV->getType(), DVR));
1792312c0ed1SDimitry Andric   if (CanConvert) {
1793ac9a064cSDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1794312c0ed1SDimitry Andric                                       SI->getIterator());
1795b1c73532SDimitry Andric     return;
1796b1c73532SDimitry Andric   }
1797b1c73532SDimitry Andric 
1798312c0ed1SDimitry Andric   // FIXME: If storing to a part of the variable described by the dbg.declare,
1799312c0ed1SDimitry Andric   // then we want to insert a dbg.value for the corresponding fragment.
1800ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR
1801312c0ed1SDimitry Andric                     << '\n');
1802b1c73532SDimitry Andric   assert(UseNewDbgInfoFormat);
1803312c0ed1SDimitry Andric 
1804312c0ed1SDimitry Andric   // For now, when there is a store to parts of the variable (but we do not
1805312c0ed1SDimitry Andric   // know which part) we insert an dbg.value intrinsic to indicate that we
1806312c0ed1SDimitry Andric   // know nothing about the variable's content.
1807312c0ed1SDimitry Andric   DV = UndefValue::get(DV->getType());
1808b1c73532SDimitry Andric   ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1809ac9a064cSDimitry Andric   DbgVariableRecord *NewDVR =
1810ac9a064cSDimitry Andric       new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1811ac9a064cSDimitry Andric   SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
1812b915e9e0SDimitry Andric }
1813b915e9e0SDimitry Andric 
1814044eb2f6SDimitry Andric /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
18157fa27ce4SDimitry Andric /// llvm.dbg.declare intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,PHINode * APN,DIBuilder & Builder)1816d8e91e46SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1817b915e9e0SDimitry Andric                                            PHINode *APN, DIBuilder &Builder) {
1818044eb2f6SDimitry Andric   auto *DIVar = DII->getVariable();
1819044eb2f6SDimitry Andric   auto *DIExpr = DII->getExpression();
1820b915e9e0SDimitry Andric   assert(DIVar && "Missing variable");
1821b915e9e0SDimitry Andric 
1822b915e9e0SDimitry Andric   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1823b915e9e0SDimitry Andric     return;
1824b915e9e0SDimitry Andric 
1825eb11fae6SDimitry Andric   if (!valueCoversEntireFragment(APN->getType(), DII)) {
1826eb11fae6SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
1827eb11fae6SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
1828eb11fae6SDimitry Andric     // fragment.
1829eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1830eb11fae6SDimitry Andric                       << *DII << '\n');
1831eb11fae6SDimitry Andric     return;
1832eb11fae6SDimitry Andric   }
1833eb11fae6SDimitry Andric 
1834b915e9e0SDimitry Andric   BasicBlock *BB = APN->getParent();
1835b915e9e0SDimitry Andric   auto InsertionPt = BB->getFirstInsertionPt();
1836b915e9e0SDimitry Andric 
1837e3b55780SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
1838e6d15924SDimitry Andric 
1839b915e9e0SDimitry Andric   // The block may be a catchswitch block, which does not have a valid
1840b915e9e0SDimitry Andric   // insertion point.
1841b915e9e0SDimitry Andric   // FIXME: Insert dbg.value markers in the successors when appropriate.
1842b1c73532SDimitry Andric   if (InsertionPt != BB->end()) {
1843ac9a064cSDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1844ac9a064cSDimitry Andric                                       InsertionPt);
1845b1c73532SDimitry Andric   }
1846b1c73532SDimitry Andric }
1847b1c73532SDimitry Andric 
ConvertDebugDeclareToDebugValue(DbgVariableRecord * DVR,LoadInst * LI,DIBuilder & Builder)1848ac9a064cSDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, LoadInst *LI,
1849b1c73532SDimitry Andric                                            DIBuilder &Builder) {
1850ac9a064cSDimitry Andric   auto *DIVar = DVR->getVariable();
1851ac9a064cSDimitry Andric   auto *DIExpr = DVR->getExpression();
1852b1c73532SDimitry Andric   assert(DIVar && "Missing variable");
1853b1c73532SDimitry Andric 
1854ac9a064cSDimitry Andric   if (!valueCoversEntireFragment(LI->getType(), DVR)) {
1855b1c73532SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
1856ac9a064cSDimitry Andric     // dbg.declare, then we want to insert a DbgVariableRecord for the
1857ac9a064cSDimitry Andric     // corresponding fragment.
1858ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1859ac9a064cSDimitry Andric                       << *DVR << '\n');
1860b1c73532SDimitry Andric     return;
1861b1c73532SDimitry Andric   }
1862b1c73532SDimitry Andric 
1863ac9a064cSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
1864b1c73532SDimitry Andric 
1865b1c73532SDimitry Andric   // We are now tracking the loaded value instead of the address. In the
1866b1c73532SDimitry Andric   // future if multi-location support is added to the IR, it might be
1867b1c73532SDimitry Andric   // preferable to keep tracking both the loaded value and the original
1868b1c73532SDimitry Andric   // address in case the alloca can not be elided.
1869b1c73532SDimitry Andric   assert(UseNewDbgInfoFormat);
1870b1c73532SDimitry Andric 
1871ac9a064cSDimitry Andric   // Create a DbgVariableRecord directly and insert.
1872b1c73532SDimitry Andric   ValueAsMetadata *LIVAM = ValueAsMetadata::get(LI);
1873ac9a064cSDimitry Andric   DbgVariableRecord *DV =
1874ac9a064cSDimitry Andric       new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
1875ac9a064cSDimitry Andric   LI->getParent()->insertDbgRecordAfter(DV, LI);
18766b943ff3SDimitry Andric }
18776b943ff3SDimitry Andric 
18785ca98fd9SDimitry Andric /// Determine whether this alloca is either a VLA or an array.
isArray(AllocaInst * AI)18795ca98fd9SDimitry Andric static bool isArray(AllocaInst *AI) {
18805ca98fd9SDimitry Andric   return AI->isArrayAllocation() ||
18811d5ae102SDimitry Andric          (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
18821d5ae102SDimitry Andric }
18831d5ae102SDimitry Andric 
18841d5ae102SDimitry Andric /// Determine whether this alloca is a structure.
isStructure(AllocaInst * AI)18851d5ae102SDimitry Andric static bool isStructure(AllocaInst *AI) {
18861d5ae102SDimitry Andric   return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
18875ca98fd9SDimitry Andric }
ConvertDebugDeclareToDebugValue(DbgVariableRecord * DVR,PHINode * APN,DIBuilder & Builder)1888ac9a064cSDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, PHINode *APN,
1889b1c73532SDimitry Andric                                            DIBuilder &Builder) {
1890ac9a064cSDimitry Andric   auto *DIVar = DVR->getVariable();
1891ac9a064cSDimitry Andric   auto *DIExpr = DVR->getExpression();
1892b1c73532SDimitry Andric   assert(DIVar && "Missing variable");
1893b1c73532SDimitry Andric 
1894b1c73532SDimitry Andric   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1895b1c73532SDimitry Andric     return;
1896b1c73532SDimitry Andric 
1897ac9a064cSDimitry Andric   if (!valueCoversEntireFragment(APN->getType(), DVR)) {
1898b1c73532SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
1899ac9a064cSDimitry Andric     // dbg.declare, then we want to insert a DbgVariableRecord for the
1900ac9a064cSDimitry Andric     // corresponding fragment.
1901ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1902ac9a064cSDimitry Andric                       << *DVR << '\n');
1903b1c73532SDimitry Andric     return;
1904b1c73532SDimitry Andric   }
1905b1c73532SDimitry Andric 
1906b1c73532SDimitry Andric   BasicBlock *BB = APN->getParent();
1907b1c73532SDimitry Andric   auto InsertionPt = BB->getFirstInsertionPt();
1908b1c73532SDimitry Andric 
1909ac9a064cSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
1910b1c73532SDimitry Andric 
1911b1c73532SDimitry Andric   // The block may be a catchswitch block, which does not have a valid
1912b1c73532SDimitry Andric   // insertion point.
1913ac9a064cSDimitry Andric   // FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
1914b1c73532SDimitry Andric   if (InsertionPt != BB->end()) {
1915ac9a064cSDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1916ac9a064cSDimitry Andric                                       InsertionPt);
1917b1c73532SDimitry Andric   }
1918b1c73532SDimitry Andric }
19195ca98fd9SDimitry Andric 
19206b943ff3SDimitry Andric /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
19216b943ff3SDimitry Andric /// of llvm.dbg.value intrinsics.
LowerDbgDeclare(Function & F)19226b943ff3SDimitry Andric bool llvm::LowerDbgDeclare(Function &F) {
1923cfca06d7SDimitry Andric   bool Changed = false;
192467c32a98SDimitry Andric   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
19256b943ff3SDimitry Andric   SmallVector<DbgDeclareInst *, 4> Dbgs;
1926ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *> DVRs;
1927312c0ed1SDimitry Andric   for (auto &FI : F) {
1928312c0ed1SDimitry Andric     for (Instruction &BI : FI) {
1929312c0ed1SDimitry Andric       if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
19306b943ff3SDimitry Andric         Dbgs.push_back(DDI);
1931ac9a064cSDimitry Andric       for (DbgVariableRecord &DVR : filterDbgVars(BI.getDbgRecordRange())) {
1932ac9a064cSDimitry Andric         if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
1933ac9a064cSDimitry Andric           DVRs.push_back(&DVR);
1934312c0ed1SDimitry Andric       }
1935312c0ed1SDimitry Andric     }
1936312c0ed1SDimitry Andric   }
19375ca98fd9SDimitry Andric 
1938ac9a064cSDimitry Andric   if (Dbgs.empty() && DVRs.empty())
1939cfca06d7SDimitry Andric     return Changed;
19406b943ff3SDimitry Andric 
1941312c0ed1SDimitry Andric   auto LowerOne = [&](auto *DDI) {
1942312c0ed1SDimitry Andric     AllocaInst *AI =
1943312c0ed1SDimitry Andric         dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
1944f8af5cf6SDimitry Andric     // If this is an alloca for a scalar variable, insert a dbg.value
1945f8af5cf6SDimitry Andric     // at each load and store to the alloca and erase the dbg.declare.
19465ca98fd9SDimitry Andric     // The dbg.values allow tracking a variable even if it is not
19475ca98fd9SDimitry Andric     // stored on the stack, while the dbg.declare can only describe
19485ca98fd9SDimitry Andric     // the stack slot (and at a lexical-scope granularity). Later
19495ca98fd9SDimitry Andric     // passes will attempt to elide the stack slot.
19501d5ae102SDimitry Andric     if (!AI || isArray(AI) || isStructure(AI))
1951312c0ed1SDimitry Andric       return;
1952eb11fae6SDimitry Andric 
1953eb11fae6SDimitry Andric     // A volatile load/store means that the alloca can't be elided anyway.
1954eb11fae6SDimitry Andric     if (llvm::any_of(AI->users(), [](User *U) -> bool {
1955eb11fae6SDimitry Andric           if (LoadInst *LI = dyn_cast<LoadInst>(U))
1956eb11fae6SDimitry Andric             return LI->isVolatile();
1957eb11fae6SDimitry Andric           if (StoreInst *SI = dyn_cast<StoreInst>(U))
1958eb11fae6SDimitry Andric             return SI->isVolatile();
1959eb11fae6SDimitry Andric           return false;
1960eb11fae6SDimitry Andric         }))
1961312c0ed1SDimitry Andric       return;
1962eb11fae6SDimitry Andric 
1963706b4fc4SDimitry Andric     SmallVector<const Value *, 8> WorkList;
1964706b4fc4SDimitry Andric     WorkList.push_back(AI);
1965706b4fc4SDimitry Andric     while (!WorkList.empty()) {
1966706b4fc4SDimitry Andric       const Value *V = WorkList.pop_back_val();
1967e3b55780SDimitry Andric       for (const auto &AIUse : V->uses()) {
196801095a5dSDimitry Andric         User *U = AIUse.getUser();
196901095a5dSDimitry Andric         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
197001095a5dSDimitry Andric           if (AIUse.getOperandNo() == 1)
19716b943ff3SDimitry Andric             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
197201095a5dSDimitry Andric         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
19736b943ff3SDimitry Andric           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
197401095a5dSDimitry Andric         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1975eb11fae6SDimitry Andric           // This is a call by-value or some other instruction that takes a
1976eb11fae6SDimitry Andric           // pointer to the variable. Insert a *value* intrinsic that describes
1977eb11fae6SDimitry Andric           // the variable by dereferencing the alloca.
1978706b4fc4SDimitry Andric           if (!CI->isLifetimeStartOrEnd()) {
1979e3b55780SDimitry Andric             DebugLoc NewLoc = getDebugValueLoc(DDI);
1980eb11fae6SDimitry Andric             auto *DerefExpr =
1981eb11fae6SDimitry Andric                 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1982ac9a064cSDimitry Andric             insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),
1983ac9a064cSDimitry Andric                                               DerefExpr, NewLoc,
1984ac9a064cSDimitry Andric                                               CI->getIterator());
1985706b4fc4SDimitry Andric           }
1986706b4fc4SDimitry Andric         } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1987706b4fc4SDimitry Andric           if (BI->getType()->isPointerTy())
1988706b4fc4SDimitry Andric             WorkList.push_back(BI);
1989706b4fc4SDimitry Andric         }
19905ca98fd9SDimitry Andric       }
199101095a5dSDimitry Andric     }
19926b943ff3SDimitry Andric     DDI->eraseFromParent();
1993cfca06d7SDimitry Andric     Changed = true;
1994312c0ed1SDimitry Andric   };
1995312c0ed1SDimitry Andric 
1996312c0ed1SDimitry Andric   for_each(Dbgs, LowerOne);
1997ac9a064cSDimitry Andric   for_each(DVRs, LowerOne);
1998cfca06d7SDimitry Andric 
1999cfca06d7SDimitry Andric   if (Changed)
2000cfca06d7SDimitry Andric     for (BasicBlock &BB : F)
2001cfca06d7SDimitry Andric       RemoveRedundantDbgInstrs(&BB);
2002cfca06d7SDimitry Andric 
2003cfca06d7SDimitry Andric   return Changed;
20046b943ff3SDimitry Andric }
200556fe8f14SDimitry Andric 
2006b1c73532SDimitry Andric // RemoveDIs: re-implementation of insertDebugValuesForPHIs, but which pulls the
2007ac9a064cSDimitry Andric // debug-info out of the block's DbgVariableRecords rather than dbg.value
2008ac9a064cSDimitry Andric // intrinsics.
2009ac9a064cSDimitry Andric static void
insertDbgVariableRecordsForPHIs(BasicBlock * BB,SmallVectorImpl<PHINode * > & InsertedPHIs)2010ac9a064cSDimitry Andric insertDbgVariableRecordsForPHIs(BasicBlock *BB,
2011b1c73532SDimitry Andric                                 SmallVectorImpl<PHINode *> &InsertedPHIs) {
2012ac9a064cSDimitry Andric   assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");
2013b1c73532SDimitry Andric   if (InsertedPHIs.size() == 0)
2014b1c73532SDimitry Andric     return;
2015b1c73532SDimitry Andric 
2016ac9a064cSDimitry Andric   // Map existing PHI nodes to their DbgVariableRecords.
2017ac9a064cSDimitry Andric   DenseMap<Value *, DbgVariableRecord *> DbgValueMap;
2018b1c73532SDimitry Andric   for (auto &I : *BB) {
2019ac9a064cSDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
2020ac9a064cSDimitry Andric       for (Value *V : DVR.location_ops())
2021b1c73532SDimitry Andric         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2022ac9a064cSDimitry Andric           DbgValueMap.insert({Loc, &DVR});
2023b1c73532SDimitry Andric     }
2024b1c73532SDimitry Andric   }
2025b1c73532SDimitry Andric   if (DbgValueMap.size() == 0)
2026b1c73532SDimitry Andric     return;
2027b1c73532SDimitry Andric 
2028ac9a064cSDimitry Andric   // Map a pair of the destination BB and old DbgVariableRecord to the new
2029ac9a064cSDimitry Andric   // DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
2030ac9a064cSDimitry Andric   // more than one of the inserted PHIs in the same destination BB, we can
2031ac9a064cSDimitry Andric   // update the same DbgVariableRecord with all the new PHIs instead of creating
2032ac9a064cSDimitry Andric   // one copy for each.
2033ac9a064cSDimitry Andric   MapVector<std::pair<BasicBlock *, DbgVariableRecord *>, DbgVariableRecord *>
2034ac9a064cSDimitry Andric       NewDbgValueMap;
2035b1c73532SDimitry Andric   // Then iterate through the new PHIs and look to see if they use one of the
2036ac9a064cSDimitry Andric   // previously mapped PHIs. If so, create a new DbgVariableRecord that will
2037ac9a064cSDimitry Andric   // propagate the info through the new PHI. If we use more than one new PHI in
2038ac9a064cSDimitry Andric   // a single destination BB with the same old dbg.value, merge the updates so
2039ac9a064cSDimitry Andric   // that we get a single new DbgVariableRecord with all the new PHIs.
2040b1c73532SDimitry Andric   for (auto PHI : InsertedPHIs) {
2041b1c73532SDimitry Andric     BasicBlock *Parent = PHI->getParent();
2042b1c73532SDimitry Andric     // Avoid inserting a debug-info record into an EH block.
2043b1c73532SDimitry Andric     if (Parent->getFirstNonPHI()->isEHPad())
2044b1c73532SDimitry Andric       continue;
2045b1c73532SDimitry Andric     for (auto VI : PHI->operand_values()) {
2046b1c73532SDimitry Andric       auto V = DbgValueMap.find(VI);
2047b1c73532SDimitry Andric       if (V != DbgValueMap.end()) {
2048ac9a064cSDimitry Andric         DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);
2049b1c73532SDimitry Andric         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2050b1c73532SDimitry Andric         if (NewDI == NewDbgValueMap.end()) {
2051ac9a064cSDimitry Andric           DbgVariableRecord *NewDbgII = DbgII->clone();
2052b1c73532SDimitry Andric           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2053b1c73532SDimitry Andric         }
2054ac9a064cSDimitry Andric         DbgVariableRecord *NewDbgII = NewDI->second;
2055b1c73532SDimitry Andric         // If PHI contains VI as an operand more than once, we may
2056b1c73532SDimitry Andric         // replaced it in NewDbgII; confirm that it is present.
2057b1c73532SDimitry Andric         if (is_contained(NewDbgII->location_ops(), VI))
2058b1c73532SDimitry Andric           NewDbgII->replaceVariableLocationOp(VI, PHI);
2059b1c73532SDimitry Andric       }
2060b1c73532SDimitry Andric     }
2061b1c73532SDimitry Andric   }
2062ac9a064cSDimitry Andric   // Insert the new DbgVariableRecords into their destination blocks.
2063b1c73532SDimitry Andric   for (auto DI : NewDbgValueMap) {
2064b1c73532SDimitry Andric     BasicBlock *Parent = DI.first.first;
2065ac9a064cSDimitry Andric     DbgVariableRecord *NewDbgII = DI.second;
2066b1c73532SDimitry Andric     auto InsertionPt = Parent->getFirstInsertionPt();
2067b1c73532SDimitry Andric     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
2068b1c73532SDimitry Andric 
2069ac9a064cSDimitry Andric     Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);
2070b1c73532SDimitry Andric   }
2071b1c73532SDimitry Andric }
2072b1c73532SDimitry Andric 
2073eb11fae6SDimitry Andric /// Propagate dbg.value intrinsics through the newly inserted PHIs.
insertDebugValuesForPHIs(BasicBlock * BB,SmallVectorImpl<PHINode * > & InsertedPHIs)2074eb11fae6SDimitry Andric void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
2075eb11fae6SDimitry Andric                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
2076eb11fae6SDimitry Andric   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
2077eb11fae6SDimitry Andric   if (InsertedPHIs.size() == 0)
2078eb11fae6SDimitry Andric     return;
2079eb11fae6SDimitry Andric 
2080ac9a064cSDimitry Andric   insertDbgVariableRecordsForPHIs(BB, InsertedPHIs);
2081b1c73532SDimitry Andric 
2082eb11fae6SDimitry Andric   // Map existing PHI nodes to their dbg.values.
2083eb11fae6SDimitry Andric   ValueToValueMapTy DbgValueMap;
2084eb11fae6SDimitry Andric   for (auto &I : *BB) {
2085d8e91e46SDimitry Andric     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
2086344a3780SDimitry Andric       for (Value *V : DbgII->location_ops())
2087344a3780SDimitry Andric         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2088eb11fae6SDimitry Andric           DbgValueMap.insert({Loc, DbgII});
2089eb11fae6SDimitry Andric     }
2090eb11fae6SDimitry Andric   }
2091eb11fae6SDimitry Andric   if (DbgValueMap.size() == 0)
2092eb11fae6SDimitry Andric     return;
2093eb11fae6SDimitry Andric 
2094344a3780SDimitry Andric   // Map a pair of the destination BB and old dbg.value to the new dbg.value,
2095344a3780SDimitry Andric   // so that if a dbg.value is being rewritten to use more than one of the
2096344a3780SDimitry Andric   // inserted PHIs in the same destination BB, we can update the same dbg.value
2097344a3780SDimitry Andric   // with all the new PHIs instead of creating one copy for each.
2098344a3780SDimitry Andric   MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
2099344a3780SDimitry Andric             DbgVariableIntrinsic *>
2100344a3780SDimitry Andric       NewDbgValueMap;
2101eb11fae6SDimitry Andric   // Then iterate through the new PHIs and look to see if they use one of the
2102344a3780SDimitry Andric   // previously mapped PHIs. If so, create a new dbg.value intrinsic that will
2103344a3780SDimitry Andric   // propagate the info through the new PHI. If we use more than one new PHI in
2104344a3780SDimitry Andric   // a single destination BB with the same old dbg.value, merge the updates so
2105344a3780SDimitry Andric   // that we get a single new dbg.value with all the new PHIs.
2106e3b55780SDimitry Andric   for (auto *PHI : InsertedPHIs) {
2107eb11fae6SDimitry Andric     BasicBlock *Parent = PHI->getParent();
2108eb11fae6SDimitry Andric     // Avoid inserting an intrinsic into an EH block.
2109eb11fae6SDimitry Andric     if (Parent->getFirstNonPHI()->isEHPad())
2110eb11fae6SDimitry Andric       continue;
2111e3b55780SDimitry Andric     for (auto *VI : PHI->operand_values()) {
2112eb11fae6SDimitry Andric       auto V = DbgValueMap.find(VI);
2113eb11fae6SDimitry Andric       if (V != DbgValueMap.end()) {
2114d8e91e46SDimitry Andric         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
2115344a3780SDimitry Andric         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2116344a3780SDimitry Andric         if (NewDI == NewDbgValueMap.end()) {
2117344a3780SDimitry Andric           auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());
2118344a3780SDimitry Andric           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2119344a3780SDimitry Andric         }
2120344a3780SDimitry Andric         DbgVariableIntrinsic *NewDbgII = NewDI->second;
2121344a3780SDimitry Andric         // If PHI contains VI as an operand more than once, we may
2122344a3780SDimitry Andric         // replaced it in NewDbgII; confirm that it is present.
2123344a3780SDimitry Andric         if (is_contained(NewDbgII->location_ops(), VI))
2124344a3780SDimitry Andric           NewDbgII->replaceVariableLocationOp(VI, PHI);
2125344a3780SDimitry Andric       }
2126344a3780SDimitry Andric     }
2127344a3780SDimitry Andric   }
2128344a3780SDimitry Andric   // Insert thew new dbg.values into their destination blocks.
2129344a3780SDimitry Andric   for (auto DI : NewDbgValueMap) {
2130344a3780SDimitry Andric     BasicBlock *Parent = DI.first.first;
2131344a3780SDimitry Andric     auto *NewDbgII = DI.second;
2132eb11fae6SDimitry Andric     auto InsertionPt = Parent->getFirstInsertionPt();
2133eb11fae6SDimitry Andric     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
2134eb11fae6SDimitry Andric     NewDbgII->insertBefore(&*InsertionPt);
2135eb11fae6SDimitry Andric   }
2136eb11fae6SDimitry Andric }
213701095a5dSDimitry Andric 
replaceDbgDeclare(Value * Address,Value * NewAddress,DIBuilder & Builder,uint8_t DIExprFlags,int Offset)2138dd58ef01SDimitry Andric bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
2139cfca06d7SDimitry Andric                              DIBuilder &Builder, uint8_t DIExprFlags,
2140cfca06d7SDimitry Andric                              int Offset) {
21414df029ccSDimitry Andric   TinyPtrVector<DbgDeclareInst *> DbgDeclares = findDbgDeclares(Address);
2142ac9a064cSDimitry Andric   TinyPtrVector<DbgVariableRecord *> DVRDeclares = findDVRDeclares(Address);
2143312c0ed1SDimitry Andric 
2144312c0ed1SDimitry Andric   auto ReplaceOne = [&](auto *DII) {
2145312c0ed1SDimitry Andric     assert(DII->getVariable() && "Missing variable");
2146044eb2f6SDimitry Andric     auto *DIExpr = DII->getExpression();
2147e6d15924SDimitry Andric     DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
2148312c0ed1SDimitry Andric     DII->setExpression(DIExpr);
2149312c0ed1SDimitry Andric     DII->replaceVariableLocationOp(Address, NewAddress);
2150312c0ed1SDimitry Andric   };
2151312c0ed1SDimitry Andric 
2152312c0ed1SDimitry Andric   for_each(DbgDeclares, ReplaceOne);
2153ac9a064cSDimitry Andric   for_each(DVRDeclares, ReplaceOne);
2154312c0ed1SDimitry Andric 
2155ac9a064cSDimitry Andric   return !DbgDeclares.empty() || !DVRDeclares.empty();
21564a16efa3SDimitry Andric }
21574a16efa3SDimitry Andric 
updateOneDbgValueForAlloca(const DebugLoc & Loc,DILocalVariable * DIVar,DIExpression * DIExpr,Value * NewAddress,DbgValueInst * DVI,DbgVariableRecord * DVR,DIBuilder & Builder,int Offset)2158b1c73532SDimitry Andric static void updateOneDbgValueForAlloca(const DebugLoc &Loc,
2159b1c73532SDimitry Andric                                        DILocalVariable *DIVar,
2160b1c73532SDimitry Andric                                        DIExpression *DIExpr, Value *NewAddress,
2161ac9a064cSDimitry Andric                                        DbgValueInst *DVI,
2162ac9a064cSDimitry Andric                                        DbgVariableRecord *DVR,
216301095a5dSDimitry Andric                                        DIBuilder &Builder, int Offset) {
216401095a5dSDimitry Andric   assert(DIVar && "Missing variable");
216501095a5dSDimitry Andric 
2166ac9a064cSDimitry Andric   // This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
2167ac9a064cSDimitry Andric   // should do with the alloca pointer is dereference it. Otherwise we don't
2168ac9a064cSDimitry Andric   // know how to handle it and give up.
216901095a5dSDimitry Andric   if (!DIExpr || DIExpr->getNumElements() < 1 ||
217001095a5dSDimitry Andric       DIExpr->getElement(0) != dwarf::DW_OP_deref)
217101095a5dSDimitry Andric     return;
217201095a5dSDimitry Andric 
21731d5ae102SDimitry Andric   // Insert the offset before the first deref.
21741d5ae102SDimitry Andric   if (Offset)
21751d5ae102SDimitry Andric     DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
217601095a5dSDimitry Andric 
2177b1c73532SDimitry Andric   if (DVI) {
2178b1c73532SDimitry Andric     DVI->setExpression(DIExpr);
2179b1c73532SDimitry Andric     DVI->replaceVariableLocationOp(0u, NewAddress);
2180b1c73532SDimitry Andric   } else {
2181ac9a064cSDimitry Andric     assert(DVR);
2182ac9a064cSDimitry Andric     DVR->setExpression(DIExpr);
2183ac9a064cSDimitry Andric     DVR->replaceVariableLocationOp(0u, NewAddress);
2184b1c73532SDimitry Andric   }
218501095a5dSDimitry Andric }
218601095a5dSDimitry Andric 
replaceDbgValueForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,int Offset)218701095a5dSDimitry Andric void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
218801095a5dSDimitry Andric                                     DIBuilder &Builder, int Offset) {
2189b1c73532SDimitry Andric   SmallVector<DbgValueInst *, 1> DbgUsers;
2190ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
2191b1c73532SDimitry Andric   findDbgValues(DbgUsers, AI, &DPUsers);
2192b1c73532SDimitry Andric 
2193b1c73532SDimitry Andric   // Attempt to replace dbg.values that use this alloca.
2194b1c73532SDimitry Andric   for (auto *DVI : DbgUsers)
2195b1c73532SDimitry Andric     updateOneDbgValueForAlloca(DVI->getDebugLoc(), DVI->getVariable(),
2196b1c73532SDimitry Andric                                DVI->getExpression(), NewAllocaAddress, DVI,
2197b1c73532SDimitry Andric                                nullptr, Builder, Offset);
2198b1c73532SDimitry Andric 
2199ac9a064cSDimitry Andric   // Replace any DbgVariableRecords that use this alloca.
2200ac9a064cSDimitry Andric   for (DbgVariableRecord *DVR : DPUsers)
2201ac9a064cSDimitry Andric     updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),
2202ac9a064cSDimitry Andric                                DVR->getExpression(), NewAllocaAddress, nullptr,
2203ac9a064cSDimitry Andric                                DVR, Builder, Offset);
220401095a5dSDimitry Andric }
220571d5a254SDimitry Andric 
2206e3b55780SDimitry Andric /// Where possible to salvage debug information for \p I do so.
2207e3b55780SDimitry Andric /// If not possible mark undef.
salvageDebugInfo(Instruction & I)2208cfca06d7SDimitry Andric void llvm::salvageDebugInfo(Instruction &I) {
2209d8e91e46SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2210ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
2211b1c73532SDimitry Andric   findDbgUsers(DbgUsers, &I, &DPUsers);
2212b1c73532SDimitry Andric   salvageDebugInfoForDbgValues(I, DbgUsers, DPUsers);
2213e6d15924SDimitry Andric }
2214e6d15924SDimitry Andric 
salvageDbgAssignAddress(T * Assign)22154df029ccSDimitry Andric template <typename T> static void salvageDbgAssignAddress(T *Assign) {
22164df029ccSDimitry Andric   Instruction *I = dyn_cast<Instruction>(Assign->getAddress());
2217e3b55780SDimitry Andric   // Only instructions can be salvaged at the moment.
2218e3b55780SDimitry Andric   if (!I)
2219e3b55780SDimitry Andric     return;
2220e3b55780SDimitry Andric 
22214df029ccSDimitry Andric   assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&
2222e3b55780SDimitry Andric          "address-expression shouldn't have fragment info");
2223e3b55780SDimitry Andric 
2224e3b55780SDimitry Andric   // The address component of a dbg.assign cannot be variadic.
2225e3b55780SDimitry Andric   uint64_t CurrentLocOps = 0;
2226e3b55780SDimitry Andric   SmallVector<Value *, 4> AdditionalValues;
2227e3b55780SDimitry Andric   SmallVector<uint64_t, 16> Ops;
2228e3b55780SDimitry Andric   Value *NewV = salvageDebugInfoImpl(*I, CurrentLocOps, Ops, AdditionalValues);
2229e3b55780SDimitry Andric 
2230e3b55780SDimitry Andric   // Check if the salvage failed.
2231e3b55780SDimitry Andric   if (!NewV)
2232e3b55780SDimitry Andric     return;
2233e3b55780SDimitry Andric 
2234e3b55780SDimitry Andric   DIExpression *SalvagedExpr = DIExpression::appendOpsToArg(
22354df029ccSDimitry Andric       Assign->getAddressExpression(), Ops, 0, /*StackValue=*/false);
2236e3b55780SDimitry Andric   assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2237e3b55780SDimitry Andric          "address-expression shouldn't have fragment info");
2238e3b55780SDimitry Andric 
2239ac9a064cSDimitry Andric   SalvagedExpr = SalvagedExpr->foldConstantMath();
2240ac9a064cSDimitry Andric 
2241e3b55780SDimitry Andric   // Salvage succeeds if no additional values are required.
2242e3b55780SDimitry Andric   if (AdditionalValues.empty()) {
22434df029ccSDimitry Andric     Assign->setAddress(NewV);
22444df029ccSDimitry Andric     Assign->setAddressExpression(SalvagedExpr);
2245e3b55780SDimitry Andric   } else {
22464df029ccSDimitry Andric     Assign->setKillAddress();
2247e3b55780SDimitry Andric   }
2248e3b55780SDimitry Andric }
2249e3b55780SDimitry Andric 
salvageDebugInfoForDbgValues(Instruction & I,ArrayRef<DbgVariableIntrinsic * > DbgUsers,ArrayRef<DbgVariableRecord * > DPUsers)2250cfca06d7SDimitry Andric void llvm::salvageDebugInfoForDbgValues(
2251b1c73532SDimitry Andric     Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers,
2252ac9a064cSDimitry Andric     ArrayRef<DbgVariableRecord *> DPUsers) {
2253c0981da4SDimitry Andric   // These are arbitrary chosen limits on the maximum number of values and the
2254c0981da4SDimitry Andric   // maximum size of a debug expression we can salvage up to, used for
2255c0981da4SDimitry Andric   // performance reasons.
2256344a3780SDimitry Andric   const unsigned MaxDebugArgs = 16;
2257c0981da4SDimitry Andric   const unsigned MaxExpressionSize = 128;
2258cfca06d7SDimitry Andric   bool Salvaged = false;
2259eb11fae6SDimitry Andric 
2260e6d15924SDimitry Andric   for (auto *DII : DbgUsers) {
2261e3b55780SDimitry Andric     if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII)) {
2262e3b55780SDimitry Andric       if (DAI->getAddress() == &I) {
2263e3b55780SDimitry Andric         salvageDbgAssignAddress(DAI);
2264e3b55780SDimitry Andric         Salvaged = true;
2265e3b55780SDimitry Andric       }
2266e3b55780SDimitry Andric       if (DAI->getValue() != &I)
2267e3b55780SDimitry Andric         continue;
2268e3b55780SDimitry Andric     }
2269e3b55780SDimitry Andric 
22707fa27ce4SDimitry Andric     // Do not add DW_OP_stack_value for DbgDeclare, because they are implicitly
22717fa27ce4SDimitry Andric     // pointing out the value as a DWARF memory location description.
2272e6d15924SDimitry Andric     bool StackValue = isa<DbgValueInst>(DII);
2273344a3780SDimitry Andric     auto DIILocation = DII->location_ops();
2274344a3780SDimitry Andric     assert(
2275344a3780SDimitry Andric         is_contained(DIILocation, &I) &&
2276344a3780SDimitry Andric         "DbgVariableIntrinsic must use salvaged instruction as its location");
2277344a3780SDimitry Andric     SmallVector<Value *, 4> AdditionalValues;
2278344a3780SDimitry Andric     // `I` may appear more than once in DII's location ops, and each use of `I`
2279344a3780SDimitry Andric     // must be updated in the DIExpression and potentially have additional
2280344a3780SDimitry Andric     // values added; thus we call salvageDebugInfoImpl for each `I` instance in
2281344a3780SDimitry Andric     // DIILocation.
2282c0981da4SDimitry Andric     Value *Op0 = nullptr;
2283344a3780SDimitry Andric     DIExpression *SalvagedExpr = DII->getExpression();
2284344a3780SDimitry Andric     auto LocItr = find(DIILocation, &I);
2285344a3780SDimitry Andric     while (SalvagedExpr && LocItr != DIILocation.end()) {
2286c0981da4SDimitry Andric       SmallVector<uint64_t, 16> Ops;
2287344a3780SDimitry Andric       unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
2288c0981da4SDimitry Andric       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2289c0981da4SDimitry Andric       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2290c0981da4SDimitry Andric       if (!Op0)
2291c0981da4SDimitry Andric         break;
2292c0981da4SDimitry Andric       SalvagedExpr =
2293c0981da4SDimitry Andric           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2294344a3780SDimitry Andric       LocItr = std::find(++LocItr, DIILocation.end(), &I);
2295344a3780SDimitry Andric     }
2296e6d15924SDimitry Andric     // salvageDebugInfoImpl should fail on examining the first element of
2297e6d15924SDimitry Andric     // DbgUsers, or none of them.
2298c0981da4SDimitry Andric     if (!Op0)
2299cfca06d7SDimitry Andric       break;
2300e6d15924SDimitry Andric 
2301ac9a064cSDimitry Andric     SalvagedExpr = SalvagedExpr->foldConstantMath();
2302c0981da4SDimitry Andric     DII->replaceVariableLocationOp(&I, Op0);
2303c0981da4SDimitry Andric     bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;
2304c0981da4SDimitry Andric     if (AdditionalValues.empty() && IsValidSalvageExpr) {
2305344a3780SDimitry Andric       DII->setExpression(SalvagedExpr);
23067fa27ce4SDimitry Andric     } else if (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&
2307344a3780SDimitry Andric                DII->getNumVariableLocationOps() + AdditionalValues.size() <=
2308344a3780SDimitry Andric                    MaxDebugArgs) {
2309344a3780SDimitry Andric       DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2310344a3780SDimitry Andric     } else {
23117fa27ce4SDimitry Andric       // Do not salvage using DIArgList for dbg.declare, as it is not currently
23127fa27ce4SDimitry Andric       // supported in those instructions. Also do not salvage if the resulting
23137fa27ce4SDimitry Andric       // DIArgList would contain an unreasonably large number of values.
2314e3b55780SDimitry Andric       DII->setKillLocation();
2315344a3780SDimitry Andric     }
2316eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
2317cfca06d7SDimitry Andric     Salvaged = true;
2318e6d15924SDimitry Andric   }
2319ac9a064cSDimitry Andric   // Duplicate of above block for DbgVariableRecords.
2320ac9a064cSDimitry Andric   for (auto *DVR : DPUsers) {
2321ac9a064cSDimitry Andric     if (DVR->isDbgAssign()) {
2322ac9a064cSDimitry Andric       if (DVR->getAddress() == &I) {
2323ac9a064cSDimitry Andric         salvageDbgAssignAddress(DVR);
23244df029ccSDimitry Andric         Salvaged = true;
23254df029ccSDimitry Andric       }
2326ac9a064cSDimitry Andric       if (DVR->getValue() != &I)
23274df029ccSDimitry Andric         continue;
23284df029ccSDimitry Andric     }
23294df029ccSDimitry Andric 
2330b1c73532SDimitry Andric     // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
2331b1c73532SDimitry Andric     // are implicitly pointing out the value as a DWARF memory location
2332b1c73532SDimitry Andric     // description.
2333ac9a064cSDimitry Andric     bool StackValue =
2334ac9a064cSDimitry Andric         DVR->getType() != DbgVariableRecord::LocationType::Declare;
2335ac9a064cSDimitry Andric     auto DVRLocation = DVR->location_ops();
2336b1c73532SDimitry Andric     assert(
2337ac9a064cSDimitry Andric         is_contained(DVRLocation, &I) &&
2338b1c73532SDimitry Andric         "DbgVariableIntrinsic must use salvaged instruction as its location");
2339b1c73532SDimitry Andric     SmallVector<Value *, 4> AdditionalValues;
2340ac9a064cSDimitry Andric     // 'I' may appear more than once in DVR's location ops, and each use of 'I'
2341b1c73532SDimitry Andric     // must be updated in the DIExpression and potentially have additional
2342b1c73532SDimitry Andric     // values added; thus we call salvageDebugInfoImpl for each 'I' instance in
2343ac9a064cSDimitry Andric     // DVRLocation.
2344b1c73532SDimitry Andric     Value *Op0 = nullptr;
2345ac9a064cSDimitry Andric     DIExpression *SalvagedExpr = DVR->getExpression();
2346ac9a064cSDimitry Andric     auto LocItr = find(DVRLocation, &I);
2347ac9a064cSDimitry Andric     while (SalvagedExpr && LocItr != DVRLocation.end()) {
2348b1c73532SDimitry Andric       SmallVector<uint64_t, 16> Ops;
2349ac9a064cSDimitry Andric       unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);
2350b1c73532SDimitry Andric       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2351b1c73532SDimitry Andric       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2352b1c73532SDimitry Andric       if (!Op0)
2353b1c73532SDimitry Andric         break;
2354b1c73532SDimitry Andric       SalvagedExpr =
2355b1c73532SDimitry Andric           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2356ac9a064cSDimitry Andric       LocItr = std::find(++LocItr, DVRLocation.end(), &I);
2357b1c73532SDimitry Andric     }
2358b1c73532SDimitry Andric     // salvageDebugInfoImpl should fail on examining the first element of
2359b1c73532SDimitry Andric     // DbgUsers, or none of them.
2360b1c73532SDimitry Andric     if (!Op0)
2361b1c73532SDimitry Andric       break;
2362b1c73532SDimitry Andric 
2363ac9a064cSDimitry Andric     SalvagedExpr = SalvagedExpr->foldConstantMath();
2364ac9a064cSDimitry Andric     DVR->replaceVariableLocationOp(&I, Op0);
2365b1c73532SDimitry Andric     bool IsValidSalvageExpr =
2366b1c73532SDimitry Andric         SalvagedExpr->getNumElements() <= MaxExpressionSize;
2367b1c73532SDimitry Andric     if (AdditionalValues.empty() && IsValidSalvageExpr) {
2368ac9a064cSDimitry Andric       DVR->setExpression(SalvagedExpr);
2369ac9a064cSDimitry Andric     } else if (DVR->getType() != DbgVariableRecord::LocationType::Declare &&
2370b1c73532SDimitry Andric                IsValidSalvageExpr &&
2371ac9a064cSDimitry Andric                DVR->getNumVariableLocationOps() + AdditionalValues.size() <=
2372b1c73532SDimitry Andric                    MaxDebugArgs) {
2373ac9a064cSDimitry Andric       DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2374b1c73532SDimitry Andric     } else {
2375b1c73532SDimitry Andric       // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
2376b1c73532SDimitry Andric       // currently only valid for stack value expressions.
2377b1c73532SDimitry Andric       // Also do not salvage if the resulting DIArgList would contain an
2378b1c73532SDimitry Andric       // unreasonably large number of values.
2379ac9a064cSDimitry Andric       DVR->setKillLocation();
2380b1c73532SDimitry Andric     }
2381ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');
2382b1c73532SDimitry Andric     Salvaged = true;
2383b1c73532SDimitry Andric   }
2384e6d15924SDimitry Andric 
2385cfca06d7SDimitry Andric   if (Salvaged)
2386cfca06d7SDimitry Andric     return;
2387cfca06d7SDimitry Andric 
2388e3b55780SDimitry Andric   for (auto *DII : DbgUsers)
2389e3b55780SDimitry Andric     DII->setKillLocation();
2390b1c73532SDimitry Andric 
2391ac9a064cSDimitry Andric   for (auto *DVR : DPUsers)
2392ac9a064cSDimitry Andric     DVR->setKillLocation();
2393e6d15924SDimitry Andric }
2394e6d15924SDimitry Andric 
getSalvageOpsForGEP(GetElementPtrInst * GEP,const DataLayout & DL,uint64_t CurrentLocOps,SmallVectorImpl<uint64_t> & Opcodes,SmallVectorImpl<Value * > & AdditionalValues)2395c0981da4SDimitry Andric Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
2396344a3780SDimitry Andric                            uint64_t CurrentLocOps,
2397344a3780SDimitry Andric                            SmallVectorImpl<uint64_t> &Opcodes,
2398344a3780SDimitry Andric                            SmallVectorImpl<Value *> &AdditionalValues) {
2399344a3780SDimitry Andric   unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
2400344a3780SDimitry Andric   // Rewrite a GEP into a DIExpression.
2401344a3780SDimitry Andric   MapVector<Value *, APInt> VariableOffsets;
2402344a3780SDimitry Andric   APInt ConstantOffset(BitWidth, 0);
2403344a3780SDimitry Andric   if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
2404c0981da4SDimitry Andric     return nullptr;
2405344a3780SDimitry Andric   if (!VariableOffsets.empty() && !CurrentLocOps) {
2406344a3780SDimitry Andric     Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
2407344a3780SDimitry Andric     CurrentLocOps = 1;
2408344a3780SDimitry Andric   }
24097fa27ce4SDimitry Andric   for (const auto &Offset : VariableOffsets) {
2410344a3780SDimitry Andric     AdditionalValues.push_back(Offset.first);
2411344a3780SDimitry Andric     assert(Offset.second.isStrictlyPositive() &&
2412344a3780SDimitry Andric            "Expected strictly positive multiplier for offset.");
2413344a3780SDimitry Andric     Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2414344a3780SDimitry Andric                     Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2415344a3780SDimitry Andric                     dwarf::DW_OP_plus});
2416344a3780SDimitry Andric   }
2417344a3780SDimitry Andric   DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
2418c0981da4SDimitry Andric   return GEP->getOperand(0);
2419344a3780SDimitry Andric }
2420344a3780SDimitry Andric 
getDwarfOpForBinOp(Instruction::BinaryOps Opcode)2421344a3780SDimitry Andric uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
2422344a3780SDimitry Andric   switch (Opcode) {
2423344a3780SDimitry Andric   case Instruction::Add:
2424344a3780SDimitry Andric     return dwarf::DW_OP_plus;
2425344a3780SDimitry Andric   case Instruction::Sub:
2426344a3780SDimitry Andric     return dwarf::DW_OP_minus;
2427344a3780SDimitry Andric   case Instruction::Mul:
2428344a3780SDimitry Andric     return dwarf::DW_OP_mul;
2429344a3780SDimitry Andric   case Instruction::SDiv:
2430344a3780SDimitry Andric     return dwarf::DW_OP_div;
2431344a3780SDimitry Andric   case Instruction::SRem:
2432344a3780SDimitry Andric     return dwarf::DW_OP_mod;
2433344a3780SDimitry Andric   case Instruction::Or:
2434344a3780SDimitry Andric     return dwarf::DW_OP_or;
2435344a3780SDimitry Andric   case Instruction::And:
2436344a3780SDimitry Andric     return dwarf::DW_OP_and;
2437344a3780SDimitry Andric   case Instruction::Xor:
2438344a3780SDimitry Andric     return dwarf::DW_OP_xor;
2439344a3780SDimitry Andric   case Instruction::Shl:
2440344a3780SDimitry Andric     return dwarf::DW_OP_shl;
2441344a3780SDimitry Andric   case Instruction::LShr:
2442344a3780SDimitry Andric     return dwarf::DW_OP_shr;
2443344a3780SDimitry Andric   case Instruction::AShr:
2444344a3780SDimitry Andric     return dwarf::DW_OP_shra;
2445344a3780SDimitry Andric   default:
2446344a3780SDimitry Andric     // TODO: Salvage from each kind of binop we know about.
2447344a3780SDimitry Andric     return 0;
2448344a3780SDimitry Andric   }
2449344a3780SDimitry Andric }
2450344a3780SDimitry Andric 
handleSSAValueOperands(uint64_t CurrentLocOps,SmallVectorImpl<uint64_t> & Opcodes,SmallVectorImpl<Value * > & AdditionalValues,Instruction * I)24517fa27ce4SDimitry Andric static void handleSSAValueOperands(uint64_t CurrentLocOps,
24527fa27ce4SDimitry Andric                                    SmallVectorImpl<uint64_t> &Opcodes,
24537fa27ce4SDimitry Andric                                    SmallVectorImpl<Value *> &AdditionalValues,
24547fa27ce4SDimitry Andric                                    Instruction *I) {
24557fa27ce4SDimitry Andric   if (!CurrentLocOps) {
24567fa27ce4SDimitry Andric     Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
24577fa27ce4SDimitry Andric     CurrentLocOps = 1;
24587fa27ce4SDimitry Andric   }
24597fa27ce4SDimitry Andric   Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
24607fa27ce4SDimitry Andric   AdditionalValues.push_back(I->getOperand(1));
24617fa27ce4SDimitry Andric }
24627fa27ce4SDimitry Andric 
getSalvageOpsForBinOp(BinaryOperator * BI,uint64_t CurrentLocOps,SmallVectorImpl<uint64_t> & Opcodes,SmallVectorImpl<Value * > & AdditionalValues)2463c0981da4SDimitry Andric Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
2464344a3780SDimitry Andric                              SmallVectorImpl<uint64_t> &Opcodes,
2465344a3780SDimitry Andric                              SmallVectorImpl<Value *> &AdditionalValues) {
2466344a3780SDimitry Andric   // Handle binary operations with constant integer operands as a special case.
2467344a3780SDimitry Andric   auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
2468344a3780SDimitry Andric   // Values wider than 64 bits cannot be represented within a DIExpression.
2469344a3780SDimitry Andric   if (ConstInt && ConstInt->getBitWidth() > 64)
2470c0981da4SDimitry Andric     return nullptr;
2471344a3780SDimitry Andric 
2472344a3780SDimitry Andric   Instruction::BinaryOps BinOpcode = BI->getOpcode();
2473344a3780SDimitry Andric   // Push any Constant Int operand onto the expression stack.
2474344a3780SDimitry Andric   if (ConstInt) {
2475344a3780SDimitry Andric     uint64_t Val = ConstInt->getSExtValue();
2476344a3780SDimitry Andric     // Add or Sub Instructions with a constant operand can potentially be
2477344a3780SDimitry Andric     // simplified.
2478344a3780SDimitry Andric     if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2479344a3780SDimitry Andric       uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2480344a3780SDimitry Andric       DIExpression::appendOffset(Opcodes, Offset);
2481c0981da4SDimitry Andric       return BI->getOperand(0);
2482344a3780SDimitry Andric     }
2483344a3780SDimitry Andric     Opcodes.append({dwarf::DW_OP_constu, Val});
2484344a3780SDimitry Andric   } else {
24857fa27ce4SDimitry Andric     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);
2486344a3780SDimitry Andric   }
2487344a3780SDimitry Andric 
2488344a3780SDimitry Andric   // Add salvaged binary operator to expression stack, if it has a valid
2489344a3780SDimitry Andric   // representation in a DIExpression.
2490344a3780SDimitry Andric   uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
2491344a3780SDimitry Andric   if (!DwarfBinOp)
2492c0981da4SDimitry Andric     return nullptr;
2493344a3780SDimitry Andric   Opcodes.push_back(DwarfBinOp);
2494c0981da4SDimitry Andric   return BI->getOperand(0);
2495344a3780SDimitry Andric }
2496344a3780SDimitry Andric 
getDwarfOpForIcmpPred(CmpInst::Predicate Pred)24977fa27ce4SDimitry Andric uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred) {
24987fa27ce4SDimitry Andric   // The signedness of the operation is implicit in the typed stack, signed and
24997fa27ce4SDimitry Andric   // unsigned instructions map to the same DWARF opcode.
25007fa27ce4SDimitry Andric   switch (Pred) {
25017fa27ce4SDimitry Andric   case CmpInst::ICMP_EQ:
25027fa27ce4SDimitry Andric     return dwarf::DW_OP_eq;
25037fa27ce4SDimitry Andric   case CmpInst::ICMP_NE:
25047fa27ce4SDimitry Andric     return dwarf::DW_OP_ne;
25057fa27ce4SDimitry Andric   case CmpInst::ICMP_UGT:
25067fa27ce4SDimitry Andric   case CmpInst::ICMP_SGT:
25077fa27ce4SDimitry Andric     return dwarf::DW_OP_gt;
25087fa27ce4SDimitry Andric   case CmpInst::ICMP_UGE:
25097fa27ce4SDimitry Andric   case CmpInst::ICMP_SGE:
25107fa27ce4SDimitry Andric     return dwarf::DW_OP_ge;
25117fa27ce4SDimitry Andric   case CmpInst::ICMP_ULT:
25127fa27ce4SDimitry Andric   case CmpInst::ICMP_SLT:
25137fa27ce4SDimitry Andric     return dwarf::DW_OP_lt;
25147fa27ce4SDimitry Andric   case CmpInst::ICMP_ULE:
25157fa27ce4SDimitry Andric   case CmpInst::ICMP_SLE:
25167fa27ce4SDimitry Andric     return dwarf::DW_OP_le;
25177fa27ce4SDimitry Andric   default:
25187fa27ce4SDimitry Andric     return 0;
25197fa27ce4SDimitry Andric   }
25207fa27ce4SDimitry Andric }
25217fa27ce4SDimitry Andric 
getSalvageOpsForIcmpOp(ICmpInst * Icmp,uint64_t CurrentLocOps,SmallVectorImpl<uint64_t> & Opcodes,SmallVectorImpl<Value * > & AdditionalValues)25227fa27ce4SDimitry Andric Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps,
25237fa27ce4SDimitry Andric                               SmallVectorImpl<uint64_t> &Opcodes,
25247fa27ce4SDimitry Andric                               SmallVectorImpl<Value *> &AdditionalValues) {
25257fa27ce4SDimitry Andric   // Handle icmp operations with constant integer operands as a special case.
25267fa27ce4SDimitry Andric   auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));
25277fa27ce4SDimitry Andric   // Values wider than 64 bits cannot be represented within a DIExpression.
25287fa27ce4SDimitry Andric   if (ConstInt && ConstInt->getBitWidth() > 64)
25297fa27ce4SDimitry Andric     return nullptr;
25307fa27ce4SDimitry Andric   // Push any Constant Int operand onto the expression stack.
25317fa27ce4SDimitry Andric   if (ConstInt) {
25327fa27ce4SDimitry Andric     if (Icmp->isSigned())
25337fa27ce4SDimitry Andric       Opcodes.push_back(dwarf::DW_OP_consts);
25347fa27ce4SDimitry Andric     else
25357fa27ce4SDimitry Andric       Opcodes.push_back(dwarf::DW_OP_constu);
25367fa27ce4SDimitry Andric     uint64_t Val = ConstInt->getSExtValue();
25377fa27ce4SDimitry Andric     Opcodes.push_back(Val);
25387fa27ce4SDimitry Andric   } else {
25397fa27ce4SDimitry Andric     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);
25407fa27ce4SDimitry Andric   }
25417fa27ce4SDimitry Andric 
25427fa27ce4SDimitry Andric   // Add salvaged binary operator to expression stack, if it has a valid
25437fa27ce4SDimitry Andric   // representation in a DIExpression.
25447fa27ce4SDimitry Andric   uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Icmp->getPredicate());
25457fa27ce4SDimitry Andric   if (!DwarfIcmpOp)
25467fa27ce4SDimitry Andric     return nullptr;
25477fa27ce4SDimitry Andric   Opcodes.push_back(DwarfIcmpOp);
25487fa27ce4SDimitry Andric   return Icmp->getOperand(0);
25497fa27ce4SDimitry Andric }
25507fa27ce4SDimitry Andric 
salvageDebugInfoImpl(Instruction & I,uint64_t CurrentLocOps,SmallVectorImpl<uint64_t> & Ops,SmallVectorImpl<Value * > & AdditionalValues)2551c0981da4SDimitry Andric Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
2552c0981da4SDimitry Andric                                   SmallVectorImpl<uint64_t> &Ops,
2553344a3780SDimitry Andric                                   SmallVectorImpl<Value *> &AdditionalValues) {
2554e6d15924SDimitry Andric   auto &M = *I.getModule();
2555e6d15924SDimitry Andric   auto &DL = M.getDataLayout();
2556e6d15924SDimitry Andric 
2557eb11fae6SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(&I)) {
2558c0981da4SDimitry Andric     Value *FromValue = CI->getOperand(0);
2559cfca06d7SDimitry Andric     // No-op casts are irrelevant for debug info.
2560c0981da4SDimitry Andric     if (CI->isNoopCast(DL)) {
2561c0981da4SDimitry Andric       return FromValue;
2562c0981da4SDimitry Andric     }
2563706b4fc4SDimitry Andric 
2564706b4fc4SDimitry Andric     Type *Type = CI->getType();
2565c0981da4SDimitry Andric     if (Type->isPointerTy())
2566c0981da4SDimitry Andric       Type = DL.getIntPtrType(Type);
2567cfca06d7SDimitry Andric     // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
2568cfca06d7SDimitry Andric     if (Type->isVectorTy() ||
2569c0981da4SDimitry Andric         !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||
2570c0981da4SDimitry Andric           isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))
2571e6d15924SDimitry Andric       return nullptr;
2572706b4fc4SDimitry Andric 
2573c0981da4SDimitry Andric     llvm::Type *FromType = FromValue->getType();
2574c0981da4SDimitry Andric     if (FromType->isPointerTy())
2575c0981da4SDimitry Andric       FromType = DL.getIntPtrType(FromType);
2576c0981da4SDimitry Andric 
2577c0981da4SDimitry Andric     unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2578706b4fc4SDimitry Andric     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
2579706b4fc4SDimitry Andric 
2580c0981da4SDimitry Andric     auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
2581c0981da4SDimitry Andric                                           isa<SExtInst>(&I));
2582c0981da4SDimitry Andric     Ops.append(ExtOps.begin(), ExtOps.end());
2583c0981da4SDimitry Andric     return FromValue;
2584706b4fc4SDimitry Andric   }
2585706b4fc4SDimitry Andric 
2586c0981da4SDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
2587c0981da4SDimitry Andric     return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);
2588c0981da4SDimitry Andric   if (auto *BI = dyn_cast<BinaryOperator>(&I))
2589c0981da4SDimitry Andric     return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
25907fa27ce4SDimitry Andric   if (auto *IC = dyn_cast<ICmpInst>(&I))
25917fa27ce4SDimitry Andric     return getSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);
2592c0981da4SDimitry Andric 
2593e6d15924SDimitry Andric   // *Not* to do: we should not attempt to salvage load instructions,
2594e6d15924SDimitry Andric   // because the validity and lifetime of a dbg.value containing
2595e6d15924SDimitry Andric   // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
2596e6d15924SDimitry Andric   return nullptr;
2597eb11fae6SDimitry Andric }
2598eb11fae6SDimitry Andric 
2599eb11fae6SDimitry Andric /// A replacement for a dbg.value expression.
2600e3b55780SDimitry Andric using DbgValReplacement = std::optional<DIExpression *>;
2601eb11fae6SDimitry Andric 
2602eb11fae6SDimitry Andric /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2603706b4fc4SDimitry Andric /// possibly moving/undefing users to prevent use-before-def. Returns true if
2604eb11fae6SDimitry Andric /// changes are made.
rewriteDebugUsers(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT,function_ref<DbgValReplacement (DbgVariableIntrinsic & DII)> RewriteExpr,function_ref<DbgValReplacement (DbgVariableRecord & DVR)> RewriteDVRExpr)2605eb11fae6SDimitry Andric static bool rewriteDebugUsers(
2606eb11fae6SDimitry Andric     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
2607b1c73532SDimitry Andric     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr,
2608ac9a064cSDimitry Andric     function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
2609eb11fae6SDimitry Andric   // Find debug users of From.
2610d8e91e46SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> Users;
2611ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
2612b1c73532SDimitry Andric   findDbgUsers(Users, &From, &DPUsers);
2613b1c73532SDimitry Andric   if (Users.empty() && DPUsers.empty())
2614eb11fae6SDimitry Andric     return false;
2615eb11fae6SDimitry Andric 
2616eb11fae6SDimitry Andric   // Prevent use-before-def of To.
2617eb11fae6SDimitry Andric   bool Changed = false;
2618b1c73532SDimitry Andric 
2619706b4fc4SDimitry Andric   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
2620ac9a064cSDimitry Andric   SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
2621eb11fae6SDimitry Andric   if (isa<Instruction>(&To)) {
2622eb11fae6SDimitry Andric     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
2623eb11fae6SDimitry Andric 
2624eb11fae6SDimitry Andric     for (auto *DII : Users) {
2625eb11fae6SDimitry Andric       // It's common to see a debug user between From and DomPoint. Move it
2626eb11fae6SDimitry Andric       // after DomPoint to preserve the variable update without any reordering.
2627eb11fae6SDimitry Andric       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
2628eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
2629eb11fae6SDimitry Andric         DII->moveAfter(&DomPoint);
2630eb11fae6SDimitry Andric         Changed = true;
2631eb11fae6SDimitry Andric 
2632eb11fae6SDimitry Andric       // Users which otherwise aren't dominated by the replacement value must
2633eb11fae6SDimitry Andric       // be salvaged or deleted.
2634eb11fae6SDimitry Andric       } else if (!DT.dominates(&DomPoint, DII)) {
2635706b4fc4SDimitry Andric         UndefOrSalvage.insert(DII);
263671d5a254SDimitry Andric       }
263771d5a254SDimitry Andric     }
2638b1c73532SDimitry Andric 
2639ac9a064cSDimitry Andric     // DbgVariableRecord implementation of the above.
2640ac9a064cSDimitry Andric     for (auto *DVR : DPUsers) {
2641ac9a064cSDimitry Andric       Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
2642b1c73532SDimitry Andric       Instruction *NextNonDebug = MarkedInstr;
2643b1c73532SDimitry Andric       // The next instruction might still be a dbg.declare, skip over it.
2644b1c73532SDimitry Andric       if (isa<DbgVariableIntrinsic>(NextNonDebug))
2645b1c73532SDimitry Andric         NextNonDebug = NextNonDebug->getNextNonDebugInstruction();
2646b1c73532SDimitry Andric 
2647b1c73532SDimitry Andric       if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2648ac9a064cSDimitry Andric         LLVM_DEBUG(dbgs() << "MOVE:  " << *DVR << '\n');
2649ac9a064cSDimitry Andric         DVR->removeFromParent();
2650b1c73532SDimitry Andric         // Ensure there's a marker.
2651ac9a064cSDimitry Andric         DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2652b1c73532SDimitry Andric         Changed = true;
2653b1c73532SDimitry Andric       } else if (!DT.dominates(&DomPoint, MarkedInstr)) {
2654ac9a064cSDimitry Andric         UndefOrSalvageDVR.insert(DVR);
2655b1c73532SDimitry Andric       }
2656b1c73532SDimitry Andric     }
265771d5a254SDimitry Andric   }
265871d5a254SDimitry Andric 
2659eb11fae6SDimitry Andric   // Update debug users without use-before-def risk.
2660eb11fae6SDimitry Andric   for (auto *DII : Users) {
2661706b4fc4SDimitry Andric     if (UndefOrSalvage.count(DII))
2662eb11fae6SDimitry Andric       continue;
2663eb11fae6SDimitry Andric 
2664ac9a064cSDimitry Andric     DbgValReplacement DVRepl = RewriteExpr(*DII);
2665ac9a064cSDimitry Andric     if (!DVRepl)
2666eb11fae6SDimitry Andric       continue;
2667eb11fae6SDimitry Andric 
2668344a3780SDimitry Andric     DII->replaceVariableLocationOp(&From, &To);
2669ac9a064cSDimitry Andric     DII->setExpression(*DVRepl);
2670eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
2671eb11fae6SDimitry Andric     Changed = true;
2672eb11fae6SDimitry Andric   }
2673ac9a064cSDimitry Andric   for (auto *DVR : DPUsers) {
2674ac9a064cSDimitry Andric     if (UndefOrSalvageDVR.count(DVR))
2675b1c73532SDimitry Andric       continue;
2676eb11fae6SDimitry Andric 
2677ac9a064cSDimitry Andric     DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
2678ac9a064cSDimitry Andric     if (!DVRepl)
2679b1c73532SDimitry Andric       continue;
2680b1c73532SDimitry Andric 
2681ac9a064cSDimitry Andric     DVR->replaceVariableLocationOp(&From, &To);
2682ac9a064cSDimitry Andric     DVR->setExpression(*DVRepl);
2683ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "REWRITE:  " << DVR << '\n');
2684b1c73532SDimitry Andric     Changed = true;
2685b1c73532SDimitry Andric   }
2686b1c73532SDimitry Andric 
2687ac9a064cSDimitry Andric   if (!UndefOrSalvage.empty() || !UndefOrSalvageDVR.empty()) {
2688eb11fae6SDimitry Andric     // Try to salvage the remaining debug users.
2689cfca06d7SDimitry Andric     salvageDebugInfo(From);
2690eb11fae6SDimitry Andric     Changed = true;
2691eb11fae6SDimitry Andric   }
2692eb11fae6SDimitry Andric 
2693eb11fae6SDimitry Andric   return Changed;
2694eb11fae6SDimitry Andric }
2695eb11fae6SDimitry Andric 
2696eb11fae6SDimitry Andric /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2697eb11fae6SDimitry Andric /// losslessly preserve the bits and semantics of the value. This predicate is
2698eb11fae6SDimitry Andric /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2699eb11fae6SDimitry Andric ///
2700eb11fae6SDimitry Andric /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2701eb11fae6SDimitry Andric /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2702eb11fae6SDimitry Andric /// and also does not allow lossless pointer <-> integer conversions.
isBitCastSemanticsPreserving(const DataLayout & DL,Type * FromTy,Type * ToTy)2703eb11fae6SDimitry Andric static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
2704eb11fae6SDimitry Andric                                          Type *ToTy) {
2705eb11fae6SDimitry Andric   // Trivially compatible types.
2706eb11fae6SDimitry Andric   if (FromTy == ToTy)
2707eb11fae6SDimitry Andric     return true;
2708eb11fae6SDimitry Andric 
2709eb11fae6SDimitry Andric   // Handle compatible pointer <-> integer conversions.
2710eb11fae6SDimitry Andric   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2711eb11fae6SDimitry Andric     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
2712eb11fae6SDimitry Andric     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
2713eb11fae6SDimitry Andric                               !DL.isNonIntegralPointerType(ToTy);
2714eb11fae6SDimitry Andric     return SameSize && LosslessConversion;
2715eb11fae6SDimitry Andric   }
2716eb11fae6SDimitry Andric 
2717eb11fae6SDimitry Andric   // TODO: This is not exhaustive.
2718eb11fae6SDimitry Andric   return false;
2719eb11fae6SDimitry Andric }
2720eb11fae6SDimitry Andric 
replaceAllDbgUsesWith(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT)2721eb11fae6SDimitry Andric bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
2722eb11fae6SDimitry Andric                                  Instruction &DomPoint, DominatorTree &DT) {
2723eb11fae6SDimitry Andric   // Exit early if From has no debug users.
2724eb11fae6SDimitry Andric   if (!From.isUsedByMetadata())
2725eb11fae6SDimitry Andric     return false;
2726eb11fae6SDimitry Andric 
2727eb11fae6SDimitry Andric   assert(&From != &To && "Can't replace something with itself");
2728eb11fae6SDimitry Andric 
2729eb11fae6SDimitry Andric   Type *FromTy = From.getType();
2730eb11fae6SDimitry Andric   Type *ToTy = To.getType();
2731eb11fae6SDimitry Andric 
2732d8e91e46SDimitry Andric   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2733eb11fae6SDimitry Andric     return DII.getExpression();
2734eb11fae6SDimitry Andric   };
2735ac9a064cSDimitry Andric   auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2736ac9a064cSDimitry Andric     return DVR.getExpression();
2737b1c73532SDimitry Andric   };
2738eb11fae6SDimitry Andric 
2739eb11fae6SDimitry Andric   // Handle no-op conversions.
2740eb11fae6SDimitry Andric   Module &M = *From.getModule();
2741eb11fae6SDimitry Andric   const DataLayout &DL = M.getDataLayout();
2742eb11fae6SDimitry Andric   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2743ac9a064cSDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2744eb11fae6SDimitry Andric 
2745eb11fae6SDimitry Andric   // Handle integer-to-integer widening and narrowing.
2746eb11fae6SDimitry Andric   // FIXME: Use DW_OP_convert when it's available everywhere.
2747eb11fae6SDimitry Andric   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2748eb11fae6SDimitry Andric     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
2749eb11fae6SDimitry Andric     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
2750eb11fae6SDimitry Andric     assert(FromBits != ToBits && "Unexpected no-op conversion");
2751eb11fae6SDimitry Andric 
2752eb11fae6SDimitry Andric     // When the width of the result grows, assume that a debugger will only
2753eb11fae6SDimitry Andric     // access the low `FromBits` bits when inspecting the source variable.
2754eb11fae6SDimitry Andric     if (FromBits < ToBits)
2755ac9a064cSDimitry Andric       return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2756eb11fae6SDimitry Andric 
2757eb11fae6SDimitry Andric     // The width of the result has shrunk. Use sign/zero extension to describe
2758eb11fae6SDimitry Andric     // the source variable's high bits.
2759d8e91e46SDimitry Andric     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2760eb11fae6SDimitry Andric       DILocalVariable *Var = DII.getVariable();
2761eb11fae6SDimitry Andric 
2762eb11fae6SDimitry Andric       // Without knowing signedness, sign/zero extension isn't possible.
2763eb11fae6SDimitry Andric       auto Signedness = Var->getSignedness();
2764eb11fae6SDimitry Andric       if (!Signedness)
2765e3b55780SDimitry Andric         return std::nullopt;
2766eb11fae6SDimitry Andric 
2767eb11fae6SDimitry Andric       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2768706b4fc4SDimitry Andric       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
2769706b4fc4SDimitry Andric                                      Signed);
2770eb11fae6SDimitry Andric     };
2771ac9a064cSDimitry Andric     // RemoveDIs: duplicate implementation working on DbgVariableRecords rather
2772ac9a064cSDimitry Andric     // than on dbg.value intrinsics.
2773ac9a064cSDimitry Andric     auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2774ac9a064cSDimitry Andric       DILocalVariable *Var = DVR.getVariable();
2775b1c73532SDimitry Andric 
2776b1c73532SDimitry Andric       // Without knowing signedness, sign/zero extension isn't possible.
2777b1c73532SDimitry Andric       auto Signedness = Var->getSignedness();
2778b1c73532SDimitry Andric       if (!Signedness)
2779b1c73532SDimitry Andric         return std::nullopt;
2780b1c73532SDimitry Andric 
2781b1c73532SDimitry Andric       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2782ac9a064cSDimitry Andric       return DIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,
2783b1c73532SDimitry Andric                                      Signed);
2784b1c73532SDimitry Andric     };
2785b1c73532SDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt,
2786ac9a064cSDimitry Andric                              SignOrZeroExtDVR);
2787eb11fae6SDimitry Andric   }
2788eb11fae6SDimitry Andric 
2789eb11fae6SDimitry Andric   // TODO: Floating-point conversions, vectors.
2790eb11fae6SDimitry Andric   return false;
2791eb11fae6SDimitry Andric }
2792eb11fae6SDimitry Andric 
handleUnreachableTerminator(Instruction * I,SmallVectorImpl<Value * > & PoisonedValues)2793ac9a064cSDimitry Andric bool llvm::handleUnreachableTerminator(
2794ac9a064cSDimitry Andric     Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {
2795ac9a064cSDimitry Andric   bool Changed = false;
2796ac9a064cSDimitry Andric   // RemoveDIs: erase debug-info on this instruction manually.
2797ac9a064cSDimitry Andric   I->dropDbgRecords();
2798ac9a064cSDimitry Andric   for (Use &U : I->operands()) {
2799ac9a064cSDimitry Andric     Value *Op = U.get();
2800ac9a064cSDimitry Andric     if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {
2801ac9a064cSDimitry Andric       U.set(PoisonValue::get(Op->getType()));
2802ac9a064cSDimitry Andric       PoisonedValues.push_back(Op);
2803ac9a064cSDimitry Andric       Changed = true;
2804ac9a064cSDimitry Andric     }
2805ac9a064cSDimitry Andric   }
2806ac9a064cSDimitry Andric 
2807ac9a064cSDimitry Andric   return Changed;
2808ac9a064cSDimitry Andric }
2809ac9a064cSDimitry Andric 
2810b60736ecSDimitry Andric std::pair<unsigned, unsigned>
removeAllNonTerminatorAndEHPadInstructions(BasicBlock * BB)2811b60736ecSDimitry Andric llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
281201095a5dSDimitry Andric   unsigned NumDeadInst = 0;
2813b60736ecSDimitry Andric   unsigned NumDeadDbgInst = 0;
281401095a5dSDimitry Andric   // Delete the instructions backwards, as it has a reduced likelihood of
281501095a5dSDimitry Andric   // having to update as many def-use and use-def chains.
281601095a5dSDimitry Andric   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2817ac9a064cSDimitry Andric   SmallVector<Value *> Uses;
2818ac9a064cSDimitry Andric   handleUnreachableTerminator(EndInst, Uses);
2819ac9a064cSDimitry Andric 
282001095a5dSDimitry Andric   while (EndInst != &BB->front()) {
282101095a5dSDimitry Andric     // Delete the next to last instruction.
282201095a5dSDimitry Andric     Instruction *Inst = &*--EndInst->getIterator();
282301095a5dSDimitry Andric     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
28244b4fe385SDimitry Andric       Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
282501095a5dSDimitry Andric     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2826ac9a064cSDimitry Andric       // EHPads can't have DbgVariableRecords attached to them, but it might be
2827ac9a064cSDimitry Andric       // possible for things with token type.
2828ac9a064cSDimitry Andric       Inst->dropDbgRecords();
282901095a5dSDimitry Andric       EndInst = Inst;
283001095a5dSDimitry Andric       continue;
283101095a5dSDimitry Andric     }
2832b60736ecSDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
2833b60736ecSDimitry Andric       ++NumDeadDbgInst;
2834b60736ecSDimitry Andric     else
283501095a5dSDimitry Andric       ++NumDeadInst;
2836b1c73532SDimitry Andric     // RemoveDIs: erasing debug-info must be done manually.
2837ac9a064cSDimitry Andric     Inst->dropDbgRecords();
283801095a5dSDimitry Andric     Inst->eraseFromParent();
283901095a5dSDimitry Andric   }
2840b60736ecSDimitry Andric   return {NumDeadInst, NumDeadDbgInst};
284101095a5dSDimitry Andric }
284201095a5dSDimitry Andric 
changeToUnreachable(Instruction * I,bool PreserveLCSSA,DomTreeUpdater * DTU,MemorySSAUpdater * MSSAU)2843344a3780SDimitry Andric unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2844344a3780SDimitry Andric                                    DomTreeUpdater *DTU,
2845e6d15924SDimitry Andric                                    MemorySSAUpdater *MSSAU) {
2846f8af5cf6SDimitry Andric   BasicBlock *BB = I->getParent();
2847eb11fae6SDimitry Andric 
2848e6d15924SDimitry Andric   if (MSSAU)
2849e6d15924SDimitry Andric     MSSAU->changeToUnreachable(I);
2850e6d15924SDimitry Andric 
2851344a3780SDimitry Andric   SmallSet<BasicBlock *, 8> UniqueSuccessors;
2852b60736ecSDimitry Andric 
2853f8af5cf6SDimitry Andric   // Loop over all of the successors, removing BB's entry from any PHI
2854f8af5cf6SDimitry Andric   // nodes.
2855eb11fae6SDimitry Andric   for (BasicBlock *Successor : successors(BB)) {
2856b915e9e0SDimitry Andric     Successor->removePredecessor(BB, PreserveLCSSA);
2857d8e91e46SDimitry Andric     if (DTU)
2858b60736ecSDimitry Andric       UniqueSuccessors.insert(Successor);
2859eb11fae6SDimitry Andric   }
2860ac9a064cSDimitry Andric   auto *UI = new UnreachableInst(I->getContext(), I->getIterator());
2861d8e91e46SDimitry Andric   UI->setDebugLoc(I->getDebugLoc());
2862f8af5cf6SDimitry Andric 
2863f8af5cf6SDimitry Andric   // All instructions after this are dead.
286401095a5dSDimitry Andric   unsigned NumInstrsRemoved = 0;
2865dd58ef01SDimitry Andric   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2866f8af5cf6SDimitry Andric   while (BBI != BBE) {
2867f8af5cf6SDimitry Andric     if (!BBI->use_empty())
28684b4fe385SDimitry Andric       BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
2869e3b55780SDimitry Andric     BBI++->eraseFromParent();
287001095a5dSDimitry Andric     ++NumInstrsRemoved;
2871f8af5cf6SDimitry Andric   }
2872b60736ecSDimitry Andric   if (DTU) {
2873b60736ecSDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> Updates;
2874b60736ecSDimitry Andric     Updates.reserve(UniqueSuccessors.size());
2875b60736ecSDimitry Andric     for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2876b60736ecSDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2877b60736ecSDimitry Andric     DTU->applyUpdates(Updates);
2878b60736ecSDimitry Andric   }
2879ac9a064cSDimitry Andric   BB->flushTerminatorDbgRecords();
288001095a5dSDimitry Andric   return NumInstrsRemoved;
2881f8af5cf6SDimitry Andric }
2882f8af5cf6SDimitry Andric 
createCallMatchingInvoke(InvokeInst * II)28831d5ae102SDimitry Andric CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2884b60736ecSDimitry Andric   SmallVector<Value *, 8> Args(II->args());
2885dd58ef01SDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
2886dd58ef01SDimitry Andric   II->getOperandBundlesAsDefs(OpBundles);
28871d5ae102SDimitry Andric   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
2888cfca06d7SDimitry Andric                                        II->getCalledOperand(), Args, OpBundles);
2889f8af5cf6SDimitry Andric   NewCall->setCallingConv(II->getCallingConv());
2890f8af5cf6SDimitry Andric   NewCall->setAttributes(II->getAttributes());
2891f8af5cf6SDimitry Andric   NewCall->setDebugLoc(II->getDebugLoc());
2892d8e91e46SDimitry Andric   NewCall->copyMetadata(*II);
2893cfca06d7SDimitry Andric 
2894cfca06d7SDimitry Andric   // If the invoke had profile metadata, try converting them for CallInst.
2895cfca06d7SDimitry Andric   uint64_t TotalWeight;
2896cfca06d7SDimitry Andric   if (NewCall->extractProfTotalWeight(TotalWeight)) {
2897cfca06d7SDimitry Andric     // Set the total weight if it fits into i32, otherwise reset.
2898cfca06d7SDimitry Andric     MDBuilder MDB(NewCall->getContext());
2899cfca06d7SDimitry Andric     auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2900cfca06d7SDimitry Andric                           ? nullptr
2901cfca06d7SDimitry Andric                           : MDB.createBranchWeights({uint32_t(TotalWeight)});
2902cfca06d7SDimitry Andric     NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2903cfca06d7SDimitry Andric   }
2904cfca06d7SDimitry Andric 
29051d5ae102SDimitry Andric   return NewCall;
29061d5ae102SDimitry Andric }
29071d5ae102SDimitry Andric 
29086f8fc217SDimitry Andric // changeToCall - Convert the specified invoke into a normal call.
changeToCall(InvokeInst * II,DomTreeUpdater * DTU)29096f8fc217SDimitry Andric CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
29101d5ae102SDimitry Andric   CallInst *NewCall = createCallMatchingInvoke(II);
29111d5ae102SDimitry Andric   NewCall->takeName(II);
29121d5ae102SDimitry Andric   NewCall->insertBefore(II);
2913f8af5cf6SDimitry Andric   II->replaceAllUsesWith(NewCall);
2914f8af5cf6SDimitry Andric 
2915f8af5cf6SDimitry Andric   // Follow the call by a branch to the normal destination.
2916eb11fae6SDimitry Andric   BasicBlock *NormalDestBB = II->getNormalDest();
2917ac9a064cSDimitry Andric   BranchInst::Create(NormalDestBB, II->getIterator());
2918f8af5cf6SDimitry Andric 
2919f8af5cf6SDimitry Andric   // Update PHI nodes in the unwind destination
2920eb11fae6SDimitry Andric   BasicBlock *BB = II->getParent();
2921eb11fae6SDimitry Andric   BasicBlock *UnwindDestBB = II->getUnwindDest();
2922eb11fae6SDimitry Andric   UnwindDestBB->removePredecessor(BB);
2923f8af5cf6SDimitry Andric   II->eraseFromParent();
2924d8e91e46SDimitry Andric   if (DTU)
2925b60736ecSDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
29266f8fc217SDimitry Andric   return NewCall;
2927f8af5cf6SDimitry Andric }
2928f8af5cf6SDimitry Andric 
changeToInvokeAndSplitBasicBlock(CallInst * CI,BasicBlock * UnwindEdge,DomTreeUpdater * DTU)2929b915e9e0SDimitry Andric BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2930344a3780SDimitry Andric                                                    BasicBlock *UnwindEdge,
2931344a3780SDimitry Andric                                                    DomTreeUpdater *DTU) {
2932b915e9e0SDimitry Andric   BasicBlock *BB = CI->getParent();
2933b915e9e0SDimitry Andric 
2934b915e9e0SDimitry Andric   // Convert this function call into an invoke instruction.  First, split the
2935b915e9e0SDimitry Andric   // basic block.
2936344a3780SDimitry Andric   BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2937344a3780SDimitry Andric                                  CI->getName() + ".noexc");
2938b915e9e0SDimitry Andric 
2939344a3780SDimitry Andric   // Delete the unconditional branch inserted by SplitBlock
2940e3b55780SDimitry Andric   BB->back().eraseFromParent();
2941b915e9e0SDimitry Andric 
2942b915e9e0SDimitry Andric   // Create the new invoke instruction.
2943b60736ecSDimitry Andric   SmallVector<Value *, 8> InvokeArgs(CI->args());
2944b915e9e0SDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
2945b915e9e0SDimitry Andric 
2946b915e9e0SDimitry Andric   CI->getOperandBundlesAsDefs(OpBundles);
2947b915e9e0SDimitry Andric 
2948b915e9e0SDimitry Andric   // Note: we're round tripping operand bundles through memory here, and that
2949b915e9e0SDimitry Andric   // can potentially be avoided with a cleverer API design that we do not have
2950b915e9e0SDimitry Andric   // as of this time.
2951b915e9e0SDimitry Andric 
2952e6d15924SDimitry Andric   InvokeInst *II =
2953cfca06d7SDimitry Andric       InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2954e6d15924SDimitry Andric                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2955b915e9e0SDimitry Andric   II->setDebugLoc(CI->getDebugLoc());
2956b915e9e0SDimitry Andric   II->setCallingConv(CI->getCallingConv());
2957b915e9e0SDimitry Andric   II->setAttributes(CI->getAttributes());
2958145449b1SDimitry Andric   II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
2959b915e9e0SDimitry Andric 
2960344a3780SDimitry Andric   if (DTU)
2961344a3780SDimitry Andric     DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2962344a3780SDimitry Andric 
2963b915e9e0SDimitry Andric   // Make sure that anything using the call now uses the invoke!  This also
2964a303c417SDimitry Andric   // updates the CallGraph if present, because it uses a WeakTrackingVH.
2965b915e9e0SDimitry Andric   CI->replaceAllUsesWith(II);
2966b915e9e0SDimitry Andric 
2967b915e9e0SDimitry Andric   // Delete the original call
2968e3b55780SDimitry Andric   Split->front().eraseFromParent();
2969b915e9e0SDimitry Andric   return Split;
2970b915e9e0SDimitry Andric }
2971b915e9e0SDimitry Andric 
markAliveBlocks(Function & F,SmallPtrSetImpl<BasicBlock * > & Reachable,DomTreeUpdater * DTU=nullptr)29723a0822f0SDimitry Andric static bool markAliveBlocks(Function &F,
2973eb11fae6SDimitry Andric                             SmallPtrSetImpl<BasicBlock *> &Reachable,
2974d8e91e46SDimitry Andric                             DomTreeUpdater *DTU = nullptr) {
29754a16efa3SDimitry Andric   SmallVector<BasicBlock*, 128> Worklist;
2976dd58ef01SDimitry Andric   BasicBlock *BB = &F.front();
2977f8af5cf6SDimitry Andric   Worklist.push_back(BB);
2978f8af5cf6SDimitry Andric   Reachable.insert(BB);
2979f8af5cf6SDimitry Andric   bool Changed = false;
29804a16efa3SDimitry Andric   do {
2981f8af5cf6SDimitry Andric     BB = Worklist.pop_back_val();
2982f8af5cf6SDimitry Andric 
2983f8af5cf6SDimitry Andric     // Do a quick scan of the basic block, turning any obviously unreachable
2984f8af5cf6SDimitry Andric     // instructions into LLVM unreachable insts.  The instruction combining pass
2985f8af5cf6SDimitry Andric     // canonicalizes unreachable insts into stores to null or undef.
298601095a5dSDimitry Andric     for (Instruction &I : *BB) {
2987eb11fae6SDimitry Andric       if (auto *CI = dyn_cast<CallInst>(&I)) {
2988cfca06d7SDimitry Andric         Value *Callee = CI->getCalledOperand();
2989eb11fae6SDimitry Andric         // Handle intrinsic calls.
2990eb11fae6SDimitry Andric         if (Function *F = dyn_cast<Function>(Callee)) {
2991eb11fae6SDimitry Andric           auto IntrinsicID = F->getIntrinsicID();
2992eb11fae6SDimitry Andric           // Assumptions that are known to be false are equivalent to
2993eb11fae6SDimitry Andric           // unreachable. Also, if the condition is undefined, then we make the
2994eb11fae6SDimitry Andric           // choice most beneficial to the optimizer, and choose that to also be
2995eb11fae6SDimitry Andric           // unreachable.
2996eb11fae6SDimitry Andric           if (IntrinsicID == Intrinsic::assume) {
2997eb11fae6SDimitry Andric             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
299867c32a98SDimitry Andric               // Don't insert a call to llvm.trap right before the unreachable.
2999344a3780SDimitry Andric               changeToUnreachable(CI, false, DTU);
300067c32a98SDimitry Andric               Changed = true;
300167c32a98SDimitry Andric               break;
300267c32a98SDimitry Andric             }
3003eb11fae6SDimitry Andric           } else if (IntrinsicID == Intrinsic::experimental_guard) {
3004eb11fae6SDimitry Andric             // A call to the guard intrinsic bails out of the current
3005eb11fae6SDimitry Andric             // compilation unit if the predicate passed to it is false. If the
3006eb11fae6SDimitry Andric             // predicate is a constant false, then we know the guard will bail
3007eb11fae6SDimitry Andric             // out of the current compile unconditionally, so all code following
3008eb11fae6SDimitry Andric             // it is dead.
300901095a5dSDimitry Andric             //
301001095a5dSDimitry Andric             // Note: unlike in llvm.assume, it is not "obviously profitable" for
301101095a5dSDimitry Andric             // guards to treat `undef` as `false` since a guard on `undef` can
301201095a5dSDimitry Andric             // still be useful for widening.
3013eb11fae6SDimitry Andric             if (match(CI->getArgOperand(0), m_Zero()))
3014eb11fae6SDimitry Andric               if (!isa<UnreachableInst>(CI->getNextNode())) {
3015344a3780SDimitry Andric                 changeToUnreachable(CI->getNextNode(), false, DTU);
301601095a5dSDimitry Andric                 Changed = true;
301701095a5dSDimitry Andric                 break;
301801095a5dSDimitry Andric               }
301901095a5dSDimitry Andric           }
3020eb11fae6SDimitry Andric         } else if ((isa<ConstantPointerNull>(Callee) &&
3021e3b55780SDimitry Andric                     !NullPointerIsDefined(CI->getFunction(),
3022e3b55780SDimitry Andric                                           cast<PointerType>(Callee->getType())
3023e3b55780SDimitry Andric                                               ->getAddressSpace())) ||
3024eb11fae6SDimitry Andric                    isa<UndefValue>(Callee)) {
3025344a3780SDimitry Andric           changeToUnreachable(CI, false, DTU);
302601095a5dSDimitry Andric           Changed = true;
302701095a5dSDimitry Andric           break;
302801095a5dSDimitry Andric         }
3029e6d15924SDimitry Andric         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
3030f8af5cf6SDimitry Andric           // If we found a call to a no-return function, insert an unreachable
3031f8af5cf6SDimitry Andric           // instruction after it.  Make sure there isn't *already* one there
3032f8af5cf6SDimitry Andric           // though.
3033b1c73532SDimitry Andric           if (!isa<UnreachableInst>(CI->getNextNonDebugInstruction())) {
3034f8af5cf6SDimitry Andric             // Don't insert a call to llvm.trap right before the unreachable.
3035b1c73532SDimitry Andric             changeToUnreachable(CI->getNextNonDebugInstruction(), false, DTU);
3036f8af5cf6SDimitry Andric             Changed = true;
3037f8af5cf6SDimitry Andric           }
3038f8af5cf6SDimitry Andric           break;
3039f8af5cf6SDimitry Andric         }
3040eb11fae6SDimitry Andric       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
3041eb11fae6SDimitry Andric         // Store to undef and store to null are undefined and used to signal
3042eb11fae6SDimitry Andric         // that they should be changed to unreachable by passes that can't
3043eb11fae6SDimitry Andric         // modify the CFG.
3044f8af5cf6SDimitry Andric 
3045f8af5cf6SDimitry Andric         // Don't touch volatile stores.
3046f8af5cf6SDimitry Andric         if (SI->isVolatile()) continue;
3047f8af5cf6SDimitry Andric 
3048f8af5cf6SDimitry Andric         Value *Ptr = SI->getOperand(1);
3049f8af5cf6SDimitry Andric 
3050f8af5cf6SDimitry Andric         if (isa<UndefValue>(Ptr) ||
3051f8af5cf6SDimitry Andric             (isa<ConstantPointerNull>(Ptr) &&
3052eb11fae6SDimitry Andric              !NullPointerIsDefined(SI->getFunction(),
3053eb11fae6SDimitry Andric                                    SI->getPointerAddressSpace()))) {
3054344a3780SDimitry Andric           changeToUnreachable(SI, false, DTU);
3055f8af5cf6SDimitry Andric           Changed = true;
3056f8af5cf6SDimitry Andric           break;
3057f8af5cf6SDimitry Andric         }
3058f8af5cf6SDimitry Andric       }
3059f8af5cf6SDimitry Andric     }
3060f8af5cf6SDimitry Andric 
3061d8e91e46SDimitry Andric     Instruction *Terminator = BB->getTerminator();
30628a6c1c25SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
3063f8af5cf6SDimitry Andric       // Turn invokes that call 'nounwind' functions into ordinary calls.
3064cfca06d7SDimitry Andric       Value *Callee = II->getCalledOperand();
3065eb11fae6SDimitry Andric       if ((isa<ConstantPointerNull>(Callee) &&
3066eb11fae6SDimitry Andric            !NullPointerIsDefined(BB->getParent())) ||
3067eb11fae6SDimitry Andric           isa<UndefValue>(Callee)) {
3068344a3780SDimitry Andric         changeToUnreachable(II, false, DTU);
3069f8af5cf6SDimitry Andric         Changed = true;
3070145449b1SDimitry Andric       } else {
3071145449b1SDimitry Andric         if (II->doesNotReturn() &&
3072145449b1SDimitry Andric             !isa<UnreachableInst>(II->getNormalDest()->front())) {
3073145449b1SDimitry Andric           // If we found an invoke of a no-return function,
3074145449b1SDimitry Andric           // create a new empty basic block with an `unreachable` terminator,
3075145449b1SDimitry Andric           // and set it as the normal destination for the invoke,
3076145449b1SDimitry Andric           // unless that is already the case.
3077145449b1SDimitry Andric           // Note that the original normal destination could have other uses.
3078145449b1SDimitry Andric           BasicBlock *OrigNormalDest = II->getNormalDest();
3079145449b1SDimitry Andric           OrigNormalDest->removePredecessor(II->getParent());
3080145449b1SDimitry Andric           LLVMContext &Ctx = II->getContext();
3081145449b1SDimitry Andric           BasicBlock *UnreachableNormalDest = BasicBlock::Create(
3082145449b1SDimitry Andric               Ctx, OrigNormalDest->getName() + ".unreachable",
3083145449b1SDimitry Andric               II->getFunction(), OrigNormalDest);
3084145449b1SDimitry Andric           new UnreachableInst(Ctx, UnreachableNormalDest);
3085145449b1SDimitry Andric           II->setNormalDest(UnreachableNormalDest);
3086145449b1SDimitry Andric           if (DTU)
3087145449b1SDimitry Andric             DTU->applyUpdates(
3088145449b1SDimitry Andric                 {{DominatorTree::Delete, BB, OrigNormalDest},
3089145449b1SDimitry Andric                  {DominatorTree::Insert, BB, UnreachableNormalDest}});
3090145449b1SDimitry Andric           Changed = true;
3091145449b1SDimitry Andric         }
3092145449b1SDimitry Andric         if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
3093145449b1SDimitry Andric           if (II->use_empty() && !II->mayHaveSideEffects()) {
3094f8af5cf6SDimitry Andric             // jump to the normal destination branch.
3095eb11fae6SDimitry Andric             BasicBlock *NormalDestBB = II->getNormalDest();
3096eb11fae6SDimitry Andric             BasicBlock *UnwindDestBB = II->getUnwindDest();
3097ac9a064cSDimitry Andric             BranchInst::Create(NormalDestBB, II->getIterator());
3098eb11fae6SDimitry Andric             UnwindDestBB->removePredecessor(II->getParent());
3099f8af5cf6SDimitry Andric             II->eraseFromParent();
3100d8e91e46SDimitry Andric             if (DTU)
3101b60736ecSDimitry Andric               DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
3102f8af5cf6SDimitry Andric           } else
3103d8e91e46SDimitry Andric             changeToCall(II, DTU);
3104f8af5cf6SDimitry Andric           Changed = true;
3105f8af5cf6SDimitry Andric         }
3106145449b1SDimitry Andric       }
31078a6c1c25SDimitry Andric     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
31088a6c1c25SDimitry Andric       // Remove catchpads which cannot be reached.
31098a6c1c25SDimitry Andric       struct CatchPadDenseMapInfo {
31108a6c1c25SDimitry Andric         static CatchPadInst *getEmptyKey() {
31118a6c1c25SDimitry Andric           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
31128a6c1c25SDimitry Andric         }
3113044eb2f6SDimitry Andric 
31148a6c1c25SDimitry Andric         static CatchPadInst *getTombstoneKey() {
31158a6c1c25SDimitry Andric           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
31168a6c1c25SDimitry Andric         }
3117044eb2f6SDimitry Andric 
31188a6c1c25SDimitry Andric         static unsigned getHashValue(CatchPadInst *CatchPad) {
31198a6c1c25SDimitry Andric           return static_cast<unsigned>(hash_combine_range(
31208a6c1c25SDimitry Andric               CatchPad->value_op_begin(), CatchPad->value_op_end()));
31218a6c1c25SDimitry Andric         }
3122044eb2f6SDimitry Andric 
31238a6c1c25SDimitry Andric         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
31248a6c1c25SDimitry Andric           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
31258a6c1c25SDimitry Andric               RHS == getEmptyKey() || RHS == getTombstoneKey())
31268a6c1c25SDimitry Andric             return LHS == RHS;
31278a6c1c25SDimitry Andric           return LHS->isIdenticalTo(RHS);
31288a6c1c25SDimitry Andric         }
31298a6c1c25SDimitry Andric       };
31308a6c1c25SDimitry Andric 
3131344a3780SDimitry Andric       SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
31328a6c1c25SDimitry Andric       // Set of unique CatchPads.
31338a6c1c25SDimitry Andric       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
31348a6c1c25SDimitry Andric                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
31358a6c1c25SDimitry Andric           HandlerSet;
31368a6c1c25SDimitry Andric       detail::DenseSetEmpty Empty;
31378a6c1c25SDimitry Andric       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
31388a6c1c25SDimitry Andric                                              E = CatchSwitch->handler_end();
31398a6c1c25SDimitry Andric            I != E; ++I) {
31408a6c1c25SDimitry Andric         BasicBlock *HandlerBB = *I;
3141344a3780SDimitry Andric         if (DTU)
3142b60736ecSDimitry Andric           ++NumPerSuccessorCases[HandlerBB];
31438a6c1c25SDimitry Andric         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
31448a6c1c25SDimitry Andric         if (!HandlerSet.insert({CatchPad, Empty}).second) {
3145344a3780SDimitry Andric           if (DTU)
3146b60736ecSDimitry Andric             --NumPerSuccessorCases[HandlerBB];
31478a6c1c25SDimitry Andric           CatchSwitch->removeHandler(I);
31488a6c1c25SDimitry Andric           --I;
31498a6c1c25SDimitry Andric           --E;
31508a6c1c25SDimitry Andric           Changed = true;
31518a6c1c25SDimitry Andric         }
31528a6c1c25SDimitry Andric       }
3153344a3780SDimitry Andric       if (DTU) {
3154b60736ecSDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
3155b60736ecSDimitry Andric         for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
3156b60736ecSDimitry Andric           if (I.second == 0)
3157b60736ecSDimitry Andric             Updates.push_back({DominatorTree::Delete, BB, I.first});
3158b60736ecSDimitry Andric         DTU->applyUpdates(Updates);
3159f8af5cf6SDimitry Andric       }
3160344a3780SDimitry Andric     }
3161f8af5cf6SDimitry Andric 
3162d8e91e46SDimitry Andric     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
316301095a5dSDimitry Andric     for (BasicBlock *Successor : successors(BB))
316401095a5dSDimitry Andric       if (Reachable.insert(Successor).second)
316501095a5dSDimitry Andric         Worklist.push_back(Successor);
31664a16efa3SDimitry Andric   } while (!Worklist.empty());
3167f8af5cf6SDimitry Andric   return Changed;
31684a16efa3SDimitry Andric }
31694a16efa3SDimitry Andric 
removeUnwindEdge(BasicBlock * BB,DomTreeUpdater * DTU)3170e3b55780SDimitry Andric Instruction *llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
3171d8e91e46SDimitry Andric   Instruction *TI = BB->getTerminator();
3172dd58ef01SDimitry Andric 
3173e3b55780SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
3174e3b55780SDimitry Andric     return changeToCall(II, DTU);
3175dd58ef01SDimitry Andric 
3176d8e91e46SDimitry Andric   Instruction *NewTI;
3177dd58ef01SDimitry Andric   BasicBlock *UnwindDest;
3178dd58ef01SDimitry Andric 
3179dd58ef01SDimitry Andric   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3180ac9a064cSDimitry Andric     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI->getIterator());
3181dd58ef01SDimitry Andric     UnwindDest = CRI->getUnwindDest();
3182dd58ef01SDimitry Andric   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
3183dd58ef01SDimitry Andric     auto *NewCatchSwitch = CatchSwitchInst::Create(
3184dd58ef01SDimitry Andric         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
3185ac9a064cSDimitry Andric         CatchSwitch->getName(), CatchSwitch->getIterator());
3186dd58ef01SDimitry Andric     for (BasicBlock *PadBB : CatchSwitch->handlers())
3187dd58ef01SDimitry Andric       NewCatchSwitch->addHandler(PadBB);
3188dd58ef01SDimitry Andric 
3189dd58ef01SDimitry Andric     NewTI = NewCatchSwitch;
3190dd58ef01SDimitry Andric     UnwindDest = CatchSwitch->getUnwindDest();
3191dd58ef01SDimitry Andric   } else {
3192dd58ef01SDimitry Andric     llvm_unreachable("Could not find unwind successor");
3193dd58ef01SDimitry Andric   }
3194dd58ef01SDimitry Andric 
3195dd58ef01SDimitry Andric   NewTI->takeName(TI);
3196dd58ef01SDimitry Andric   NewTI->setDebugLoc(TI->getDebugLoc());
3197dd58ef01SDimitry Andric   UnwindDest->removePredecessor(BB);
3198dd58ef01SDimitry Andric   TI->replaceAllUsesWith(NewTI);
3199dd58ef01SDimitry Andric   TI->eraseFromParent();
3200d8e91e46SDimitry Andric   if (DTU)
3201b60736ecSDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
3202e3b55780SDimitry Andric   return NewTI;
3203dd58ef01SDimitry Andric }
3204dd58ef01SDimitry Andric 
3205ca089b24SDimitry Andric /// removeUnreachableBlocks - Remove blocks that are not reachable, even
3206f8af5cf6SDimitry Andric /// if they are in a dead cycle.  Return true if a change was made, false
32071d5ae102SDimitry Andric /// otherwise.
removeUnreachableBlocks(Function & F,DomTreeUpdater * DTU,MemorySSAUpdater * MSSAU)32081d5ae102SDimitry Andric bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
3209d8e91e46SDimitry Andric                                    MemorySSAUpdater *MSSAU) {
321001095a5dSDimitry Andric   SmallPtrSet<BasicBlock *, 16> Reachable;
3211d8e91e46SDimitry Andric   bool Changed = markAliveBlocks(F, Reachable, DTU);
3212f8af5cf6SDimitry Andric 
3213f8af5cf6SDimitry Andric   // If there are unreachable blocks in the CFG...
3214f8af5cf6SDimitry Andric   if (Reachable.size() == F.size())
3215f8af5cf6SDimitry Andric     return Changed;
3216f8af5cf6SDimitry Andric 
3217f8af5cf6SDimitry Andric   assert(Reachable.size() < F.size());
3218f8af5cf6SDimitry Andric 
3219b60736ecSDimitry Andric   // Are there any blocks left to actually delete?
3220b60736ecSDimitry Andric   SmallSetVector<BasicBlock *, 8> BlocksToRemove;
32211d5ae102SDimitry Andric   for (BasicBlock &BB : F) {
32221d5ae102SDimitry Andric     // Skip reachable basic blocks
3223cfca06d7SDimitry Andric     if (Reachable.count(&BB))
3224f8af5cf6SDimitry Andric       continue;
3225b60736ecSDimitry Andric     // Skip already-deleted blocks
3226b60736ecSDimitry Andric     if (DTU && DTU->isBBPendingDeletion(&BB))
3227b60736ecSDimitry Andric       continue;
3228b60736ecSDimitry Andric     BlocksToRemove.insert(&BB);
3229d8e91e46SDimitry Andric   }
3230d8e91e46SDimitry Andric 
3231b60736ecSDimitry Andric   if (BlocksToRemove.empty())
3232b60736ecSDimitry Andric     return Changed;
3233d8e91e46SDimitry Andric 
3234b60736ecSDimitry Andric   Changed = true;
3235b60736ecSDimitry Andric   NumRemoved += BlocksToRemove.size();
3236b60736ecSDimitry Andric 
3237b60736ecSDimitry Andric   if (MSSAU)
3238b60736ecSDimitry Andric     MSSAU->removeBlocks(BlocksToRemove);
3239b60736ecSDimitry Andric 
3240344a3780SDimitry Andric   DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
32411d5ae102SDimitry Andric 
3242b60736ecSDimitry Andric   return Changed;
32434a16efa3SDimitry Andric }
324467c32a98SDimitry Andric 
combineMetadata(Instruction * K,const Instruction * J,ArrayRef<unsigned> KnownIDs,bool DoesKMove)3245dd58ef01SDimitry Andric void llvm::combineMetadata(Instruction *K, const Instruction *J,
3246d8e91e46SDimitry Andric                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
324767c32a98SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
3248dd58ef01SDimitry Andric   K->dropUnknownNonDebugMetadata(KnownIDs);
324967c32a98SDimitry Andric   K->getAllMetadataOtherThanDebugLoc(Metadata);
3250b915e9e0SDimitry Andric   for (const auto &MD : Metadata) {
3251b915e9e0SDimitry Andric     unsigned Kind = MD.first;
325267c32a98SDimitry Andric     MDNode *JMD = J->getMetadata(Kind);
3253b915e9e0SDimitry Andric     MDNode *KMD = MD.second;
325467c32a98SDimitry Andric 
325567c32a98SDimitry Andric     switch (Kind) {
325667c32a98SDimitry Andric       default:
325767c32a98SDimitry Andric         K->setMetadata(Kind, nullptr); // Remove unknown metadata
325867c32a98SDimitry Andric         break;
325967c32a98SDimitry Andric       case LLVMContext::MD_dbg:
326067c32a98SDimitry Andric         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
3261e3b55780SDimitry Andric       case LLVMContext::MD_DIAssignID:
3262e3b55780SDimitry Andric         K->mergeDIAssignID(J);
3263e3b55780SDimitry Andric         break;
326467c32a98SDimitry Andric       case LLVMContext::MD_tbaa:
326567c32a98SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
326667c32a98SDimitry Andric         break;
326767c32a98SDimitry Andric       case LLVMContext::MD_alias_scope:
3268608e6659SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
3269608e6659SDimitry Andric         break;
327067c32a98SDimitry Andric       case LLVMContext::MD_noalias:
327101095a5dSDimitry Andric       case LLVMContext::MD_mem_parallel_loop_access:
327267c32a98SDimitry Andric         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
327367c32a98SDimitry Andric         break;
3274d8e91e46SDimitry Andric       case LLVMContext::MD_access_group:
3275d8e91e46SDimitry Andric         K->setMetadata(LLVMContext::MD_access_group,
3276d8e91e46SDimitry Andric                        intersectAccessGroups(K, J));
3277d8e91e46SDimitry Andric         break;
327867c32a98SDimitry Andric       case LLVMContext::MD_range:
32797fa27ce4SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
328067c32a98SDimitry Andric           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
328167c32a98SDimitry Andric         break;
328267c32a98SDimitry Andric       case LLVMContext::MD_fpmath:
328367c32a98SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
328467c32a98SDimitry Andric         break;
328567c32a98SDimitry Andric       case LLVMContext::MD_invariant_load:
32867fa27ce4SDimitry Andric         // If K moves, only set the !invariant.load if it is present in both
32877fa27ce4SDimitry Andric         // instructions.
32887fa27ce4SDimitry Andric         if (DoesKMove)
328967c32a98SDimitry Andric           K->setMetadata(Kind, JMD);
329067c32a98SDimitry Andric         break;
329167c32a98SDimitry Andric       case LLVMContext::MD_nonnull:
32927fa27ce4SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
329367c32a98SDimitry Andric           K->setMetadata(Kind, JMD);
329467c32a98SDimitry Andric         break;
3295dd58ef01SDimitry Andric       case LLVMContext::MD_invariant_group:
3296dd58ef01SDimitry Andric         // Preserve !invariant.group in K.
3297dd58ef01SDimitry Andric         break;
3298ac9a064cSDimitry Andric       case LLVMContext::MD_mmra:
3299ac9a064cSDimitry Andric         // Combine MMRAs
3300ac9a064cSDimitry Andric         break;
3301dd58ef01SDimitry Andric       case LLVMContext::MD_align:
33027fa27ce4SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
33037fa27ce4SDimitry Andric           K->setMetadata(
33047fa27ce4SDimitry Andric               Kind, MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3305dd58ef01SDimitry Andric         break;
3306dd58ef01SDimitry Andric       case LLVMContext::MD_dereferenceable:
3307dd58ef01SDimitry Andric       case LLVMContext::MD_dereferenceable_or_null:
33087fa27ce4SDimitry Andric         if (DoesKMove)
3309dd58ef01SDimitry Andric           K->setMetadata(Kind,
3310dd58ef01SDimitry Andric             MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3311dd58ef01SDimitry Andric         break;
33121d5ae102SDimitry Andric       case LLVMContext::MD_preserve_access_index:
33131d5ae102SDimitry Andric         // Preserve !preserve.access.index in K.
33141d5ae102SDimitry Andric         break;
33157fa27ce4SDimitry Andric       case LLVMContext::MD_noundef:
33167fa27ce4SDimitry Andric         // If K does move, keep noundef if it is present in both instructions.
33177fa27ce4SDimitry Andric         if (DoesKMove)
33187fa27ce4SDimitry Andric           K->setMetadata(Kind, JMD);
33197fa27ce4SDimitry Andric         break;
33207fa27ce4SDimitry Andric       case LLVMContext::MD_nontemporal:
33217fa27ce4SDimitry Andric         // Preserve !nontemporal if it is present on both instructions.
33227fa27ce4SDimitry Andric         K->setMetadata(Kind, JMD);
33237fa27ce4SDimitry Andric         break;
33247fa27ce4SDimitry Andric       case LLVMContext::MD_prof:
33257fa27ce4SDimitry Andric         if (DoesKMove)
33267fa27ce4SDimitry Andric           K->setMetadata(Kind, MDNode::getMergedProfMetadata(KMD, JMD, K, J));
33277fa27ce4SDimitry Andric         break;
332867c32a98SDimitry Andric     }
332967c32a98SDimitry Andric   }
3330dd58ef01SDimitry Andric   // Set !invariant.group from J if J has it. If both instructions have it
3331dd58ef01SDimitry Andric   // then we will just pick it from J - even when they are different.
3332dd58ef01SDimitry Andric   // Also make sure that K is load or store - f.e. combining bitcast with load
3333dd58ef01SDimitry Andric   // could produce bitcast with invariant.group metadata, which is invalid.
3334dd58ef01SDimitry Andric   // FIXME: we should try to preserve both invariant.group md if they are
3335dd58ef01SDimitry Andric   // different, but right now instruction can only have one invariant.group.
3336dd58ef01SDimitry Andric   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
3337dd58ef01SDimitry Andric     if (isa<LoadInst>(K) || isa<StoreInst>(K))
3338dd58ef01SDimitry Andric       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
3339ac9a064cSDimitry Andric 
3340ac9a064cSDimitry Andric   // Merge MMRAs.
3341ac9a064cSDimitry Andric   // This is handled separately because we also want to handle cases where K
3342ac9a064cSDimitry Andric   // doesn't have tags but J does.
3343ac9a064cSDimitry Andric   auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);
3344ac9a064cSDimitry Andric   auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
3345ac9a064cSDimitry Andric   if (JMMRA || KMMRA) {
3346ac9a064cSDimitry Andric     K->setMetadata(LLVMContext::MD_mmra,
3347ac9a064cSDimitry Andric                    MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));
3348ac9a064cSDimitry Andric   }
334967c32a98SDimitry Andric }
33505a5ac124SDimitry Andric 
combineMetadataForCSE(Instruction * K,const Instruction * J,bool KDominatesJ)3351d8e91e46SDimitry Andric void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
3352d8e91e46SDimitry Andric                                  bool KDominatesJ) {
33537fa27ce4SDimitry Andric   unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
33547fa27ce4SDimitry Andric                          LLVMContext::MD_alias_scope,
33557fa27ce4SDimitry Andric                          LLVMContext::MD_noalias,
33567fa27ce4SDimitry Andric                          LLVMContext::MD_range,
33577fa27ce4SDimitry Andric                          LLVMContext::MD_fpmath,
33587fa27ce4SDimitry Andric                          LLVMContext::MD_invariant_load,
33597fa27ce4SDimitry Andric                          LLVMContext::MD_nonnull,
33607fa27ce4SDimitry Andric                          LLVMContext::MD_invariant_group,
33617fa27ce4SDimitry Andric                          LLVMContext::MD_align,
3362b915e9e0SDimitry Andric                          LLVMContext::MD_dereferenceable,
3363d8e91e46SDimitry Andric                          LLVMContext::MD_dereferenceable_or_null,
33647fa27ce4SDimitry Andric                          LLVMContext::MD_access_group,
33657fa27ce4SDimitry Andric                          LLVMContext::MD_preserve_access_index,
33667fa27ce4SDimitry Andric                          LLVMContext::MD_prof,
33677fa27ce4SDimitry Andric                          LLVMContext::MD_nontemporal,
3368ac9a064cSDimitry Andric                          LLVMContext::MD_noundef,
3369ac9a064cSDimitry Andric                          LLVMContext::MD_mmra};
3370d8e91e46SDimitry Andric   combineMetadata(K, J, KnownIDs, KDominatesJ);
3371d8e91e46SDimitry Andric }
3372d8e91e46SDimitry Andric 
copyMetadataForLoad(LoadInst & Dest,const LoadInst & Source)33731d5ae102SDimitry Andric void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
33741d5ae102SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
33751d5ae102SDimitry Andric   Source.getAllMetadata(MD);
33761d5ae102SDimitry Andric   MDBuilder MDB(Dest.getContext());
33771d5ae102SDimitry Andric   Type *NewType = Dest.getType();
3378ac9a064cSDimitry Andric   const DataLayout &DL = Source.getDataLayout();
33791d5ae102SDimitry Andric   for (const auto &MDPair : MD) {
33801d5ae102SDimitry Andric     unsigned ID = MDPair.first;
33811d5ae102SDimitry Andric     MDNode *N = MDPair.second;
33821d5ae102SDimitry Andric     // Note, essentially every kind of metadata should be preserved here! This
33831d5ae102SDimitry Andric     // routine is supposed to clone a load instruction changing *only its type*.
33841d5ae102SDimitry Andric     // The only metadata it makes sense to drop is metadata which is invalidated
33851d5ae102SDimitry Andric     // when the pointer type changes. This should essentially never be the case
33861d5ae102SDimitry Andric     // in LLVM, but we explicitly switch over only known metadata to be
33871d5ae102SDimitry Andric     // conservatively correct. If you are adding metadata to LLVM which pertains
33881d5ae102SDimitry Andric     // to loads, you almost certainly want to add it here.
33891d5ae102SDimitry Andric     switch (ID) {
33901d5ae102SDimitry Andric     case LLVMContext::MD_dbg:
33911d5ae102SDimitry Andric     case LLVMContext::MD_tbaa:
33921d5ae102SDimitry Andric     case LLVMContext::MD_prof:
33931d5ae102SDimitry Andric     case LLVMContext::MD_fpmath:
33941d5ae102SDimitry Andric     case LLVMContext::MD_tbaa_struct:
33951d5ae102SDimitry Andric     case LLVMContext::MD_invariant_load:
33961d5ae102SDimitry Andric     case LLVMContext::MD_alias_scope:
33971d5ae102SDimitry Andric     case LLVMContext::MD_noalias:
33981d5ae102SDimitry Andric     case LLVMContext::MD_nontemporal:
33991d5ae102SDimitry Andric     case LLVMContext::MD_mem_parallel_loop_access:
34001d5ae102SDimitry Andric     case LLVMContext::MD_access_group:
3401e3b55780SDimitry Andric     case LLVMContext::MD_noundef:
34021d5ae102SDimitry Andric       // All of these directly apply.
34031d5ae102SDimitry Andric       Dest.setMetadata(ID, N);
34041d5ae102SDimitry Andric       break;
34051d5ae102SDimitry Andric 
34061d5ae102SDimitry Andric     case LLVMContext::MD_nonnull:
34071d5ae102SDimitry Andric       copyNonnullMetadata(Source, N, Dest);
34081d5ae102SDimitry Andric       break;
34091d5ae102SDimitry Andric 
34101d5ae102SDimitry Andric     case LLVMContext::MD_align:
34111d5ae102SDimitry Andric     case LLVMContext::MD_dereferenceable:
34121d5ae102SDimitry Andric     case LLVMContext::MD_dereferenceable_or_null:
34131d5ae102SDimitry Andric       // These only directly apply if the new type is also a pointer.
34141d5ae102SDimitry Andric       if (NewType->isPointerTy())
34151d5ae102SDimitry Andric         Dest.setMetadata(ID, N);
34161d5ae102SDimitry Andric       break;
34171d5ae102SDimitry Andric 
34181d5ae102SDimitry Andric     case LLVMContext::MD_range:
34191d5ae102SDimitry Andric       copyRangeMetadata(DL, Source, N, Dest);
34201d5ae102SDimitry Andric       break;
34211d5ae102SDimitry Andric     }
34221d5ae102SDimitry Andric   }
34231d5ae102SDimitry Andric }
34241d5ae102SDimitry Andric 
patchReplacementInstruction(Instruction * I,Value * Repl)3425d8e91e46SDimitry Andric void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
3426d8e91e46SDimitry Andric   auto *ReplInst = dyn_cast<Instruction>(Repl);
3427d8e91e46SDimitry Andric   if (!ReplInst)
3428d8e91e46SDimitry Andric     return;
3429d8e91e46SDimitry Andric 
3430d8e91e46SDimitry Andric   // Patch the replacement so that it is not more restrictive than the value
3431d8e91e46SDimitry Andric   // being replaced.
3432ac9a064cSDimitry Andric   WithOverflowInst *UnusedWO;
3433ac9a064cSDimitry Andric   // When replacing the result of a llvm.*.with.overflow intrinsic with a
3434ac9a064cSDimitry Andric   // overflowing binary operator, nuw/nsw flags may no longer hold.
3435ac9a064cSDimitry Andric   if (isa<OverflowingBinaryOperator>(ReplInst) &&
3436ac9a064cSDimitry Andric       match(I, m_ExtractValue<0>(m_WithOverflowInst(UnusedWO))))
3437ac9a064cSDimitry Andric     ReplInst->dropPoisonGeneratingFlags();
3438d8e91e46SDimitry Andric   // Note that if 'I' is a load being replaced by some operation,
3439d8e91e46SDimitry Andric   // for example, by an arithmetic operation, then andIRFlags()
3440d8e91e46SDimitry Andric   // would just erase all math flags from the original arithmetic
3441d8e91e46SDimitry Andric   // operation, which is clearly not wanted and not needed.
3442ac9a064cSDimitry Andric   else if (!isa<LoadInst>(I))
3443d8e91e46SDimitry Andric     ReplInst->andIRFlags(I);
3444d8e91e46SDimitry Andric 
3445d8e91e46SDimitry Andric   // FIXME: If both the original and replacement value are part of the
3446d8e91e46SDimitry Andric   // same control-flow region (meaning that the execution of one
3447d8e91e46SDimitry Andric   // guarantees the execution of the other), then we can combine the
3448d8e91e46SDimitry Andric   // noalias scopes here and do better than the general conservative
3449d8e91e46SDimitry Andric   // answer used in combineMetadata().
3450d8e91e46SDimitry Andric 
3451d8e91e46SDimitry Andric   // In general, GVN unifies expressions over different control-flow
3452d8e91e46SDimitry Andric   // regions, and so we need a conservative combination of the noalias
3453d8e91e46SDimitry Andric   // scopes.
34547fa27ce4SDimitry Andric   combineMetadataForCSE(ReplInst, I, false);
3455b915e9e0SDimitry Andric }
3456b915e9e0SDimitry Andric 
3457ac9a064cSDimitry Andric template <typename RootType, typename ShouldReplaceFn>
replaceDominatedUsesWith(Value * From,Value * To,const RootType & Root,const ShouldReplaceFn & ShouldReplace)34586b3f41edSDimitry Andric static unsigned replaceDominatedUsesWith(Value *From, Value *To,
34596b3f41edSDimitry Andric                                          const RootType &Root,
3460ac9a064cSDimitry Andric                                          const ShouldReplaceFn &ShouldReplace) {
34615a5ac124SDimitry Andric   assert(From->getType() == To->getType());
34625a5ac124SDimitry Andric 
34635a5ac124SDimitry Andric   unsigned Count = 0;
3464c0981da4SDimitry Andric   for (Use &U : llvm::make_early_inc_range(From->uses())) {
3465ac9a064cSDimitry Andric     if (!ShouldReplace(Root, U))
34666b3f41edSDimitry Andric       continue;
3467b1c73532SDimitry Andric     LLVM_DEBUG(dbgs() << "Replace dominated use of '";
3468b1c73532SDimitry Andric                From->printAsOperand(dbgs());
3469b1c73532SDimitry Andric                dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");
3470dd58ef01SDimitry Andric     U.set(To);
3471dd58ef01SDimitry Andric     ++Count;
3472dd58ef01SDimitry Andric   }
3473dd58ef01SDimitry Andric   return Count;
3474dd58ef01SDimitry Andric }
3475dd58ef01SDimitry Andric 
replaceNonLocalUsesWith(Instruction * From,Value * To)3476ab44ce3dSDimitry Andric unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
3477ab44ce3dSDimitry Andric    assert(From->getType() == To->getType());
3478ab44ce3dSDimitry Andric    auto *BB = From->getParent();
3479ab44ce3dSDimitry Andric    unsigned Count = 0;
3480ab44ce3dSDimitry Andric 
3481c0981da4SDimitry Andric    for (Use &U : llvm::make_early_inc_range(From->uses())) {
3482ab44ce3dSDimitry Andric     auto *I = cast<Instruction>(U.getUser());
3483ab44ce3dSDimitry Andric     if (I->getParent() == BB)
3484ab44ce3dSDimitry Andric       continue;
3485ab44ce3dSDimitry Andric     U.set(To);
3486ab44ce3dSDimitry Andric     ++Count;
3487ab44ce3dSDimitry Andric   }
3488ab44ce3dSDimitry Andric   return Count;
3489ab44ce3dSDimitry Andric }
3490ab44ce3dSDimitry Andric 
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlockEdge & Root)34916b3f41edSDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
34926b3f41edSDimitry Andric                                         DominatorTree &DT,
34936b3f41edSDimitry Andric                                         const BasicBlockEdge &Root) {
34946b3f41edSDimitry Andric   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
34956b3f41edSDimitry Andric     return DT.dominates(Root, U);
34966b3f41edSDimitry Andric   };
34976b3f41edSDimitry Andric   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
34986b3f41edSDimitry Andric }
34996b3f41edSDimitry Andric 
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlock * BB)35006b3f41edSDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
35016b3f41edSDimitry Andric                                         DominatorTree &DT,
35026b3f41edSDimitry Andric                                         const BasicBlock *BB) {
3503344a3780SDimitry Andric   auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {
3504344a3780SDimitry Andric     return DT.dominates(BB, U);
35056b3f41edSDimitry Andric   };
3506344a3780SDimitry Andric   return ::replaceDominatedUsesWith(From, To, BB, Dominates);
35076b3f41edSDimitry Andric }
35086b3f41edSDimitry Andric 
replaceDominatedUsesWithIf(Value * From,Value * To,DominatorTree & DT,const BasicBlockEdge & Root,function_ref<bool (const Use & U,const Value * To)> ShouldReplace)3509ac9a064cSDimitry Andric unsigned llvm::replaceDominatedUsesWithIf(
3510ac9a064cSDimitry Andric     Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,
3511ac9a064cSDimitry Andric     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3512ac9a064cSDimitry Andric   auto DominatesAndShouldReplace =
3513ac9a064cSDimitry Andric       [&DT, &ShouldReplace, To](const BasicBlockEdge &Root, const Use &U) {
3514ac9a064cSDimitry Andric         return DT.dominates(Root, U) && ShouldReplace(U, To);
3515ac9a064cSDimitry Andric       };
3516ac9a064cSDimitry Andric   return ::replaceDominatedUsesWith(From, To, Root, DominatesAndShouldReplace);
3517ac9a064cSDimitry Andric }
3518ac9a064cSDimitry Andric 
replaceDominatedUsesWithIf(Value * From,Value * To,DominatorTree & DT,const BasicBlock * BB,function_ref<bool (const Use & U,const Value * To)> ShouldReplace)3519ac9a064cSDimitry Andric unsigned llvm::replaceDominatedUsesWithIf(
3520ac9a064cSDimitry Andric     Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
3521ac9a064cSDimitry Andric     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3522ac9a064cSDimitry Andric   auto DominatesAndShouldReplace = [&DT, &ShouldReplace,
3523ac9a064cSDimitry Andric                                     To](const BasicBlock *BB, const Use &U) {
3524ac9a064cSDimitry Andric     return DT.dominates(BB, U) && ShouldReplace(U, To);
3525ac9a064cSDimitry Andric   };
3526ac9a064cSDimitry Andric   return ::replaceDominatedUsesWith(From, To, BB, DominatesAndShouldReplace);
3527ac9a064cSDimitry Andric }
3528ac9a064cSDimitry Andric 
callsGCLeafFunction(const CallBase * Call,const TargetLibraryInfo & TLI)3529e6d15924SDimitry Andric bool llvm::callsGCLeafFunction(const CallBase *Call,
3530044eb2f6SDimitry Andric                                const TargetLibraryInfo &TLI) {
3531dd58ef01SDimitry Andric   // Check if the function is specifically marked as a gc leaf function.
3532e6d15924SDimitry Andric   if (Call->hasFnAttr("gc-leaf-function"))
35338a6c1c25SDimitry Andric     return true;
3534e6d15924SDimitry Andric   if (const Function *F = Call->getCalledFunction()) {
353501095a5dSDimitry Andric     if (F->hasFnAttribute("gc-leaf-function"))
353601095a5dSDimitry Andric       return true;
353701095a5dSDimitry Andric 
3538b60736ecSDimitry Andric     if (auto IID = F->getIntrinsicID()) {
353901095a5dSDimitry Andric       // Most LLVM intrinsics do not take safepoints.
354001095a5dSDimitry Andric       return IID != Intrinsic::experimental_gc_statepoint &&
3541b60736ecSDimitry Andric              IID != Intrinsic::experimental_deoptimize &&
3542b60736ecSDimitry Andric              IID != Intrinsic::memcpy_element_unordered_atomic &&
3543b60736ecSDimitry Andric              IID != Intrinsic::memmove_element_unordered_atomic;
3544b60736ecSDimitry Andric     }
354501095a5dSDimitry Andric   }
3546dd58ef01SDimitry Andric 
3547044eb2f6SDimitry Andric   // Lib calls can be materialized by some passes, and won't be
3548044eb2f6SDimitry Andric   // marked as 'gc-leaf-function.' All available Libcalls are
3549044eb2f6SDimitry Andric   // GC-leaf.
3550044eb2f6SDimitry Andric   LibFunc LF;
3551cfca06d7SDimitry Andric   if (TLI.getLibFunc(*Call, LF)) {
3552044eb2f6SDimitry Andric     return TLI.has(LF);
3553044eb2f6SDimitry Andric   }
3554044eb2f6SDimitry Andric 
3555dd58ef01SDimitry Andric   return false;
3556dd58ef01SDimitry Andric }
3557dadbdfffSDimitry Andric 
copyNonnullMetadata(const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)355808bbd35aSDimitry Andric void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
355908bbd35aSDimitry Andric                                LoadInst &NewLI) {
356008bbd35aSDimitry Andric   auto *NewTy = NewLI.getType();
356108bbd35aSDimitry Andric 
356208bbd35aSDimitry Andric   // This only directly applies if the new type is also a pointer.
356308bbd35aSDimitry Andric   if (NewTy->isPointerTy()) {
356408bbd35aSDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
356508bbd35aSDimitry Andric     return;
356608bbd35aSDimitry Andric   }
356708bbd35aSDimitry Andric 
356808bbd35aSDimitry Andric   // The only other translation we can do is to integral loads with !range
356908bbd35aSDimitry Andric   // metadata.
357008bbd35aSDimitry Andric   if (!NewTy->isIntegerTy())
357108bbd35aSDimitry Andric     return;
357208bbd35aSDimitry Andric 
357308bbd35aSDimitry Andric   MDBuilder MDB(NewLI.getContext());
357408bbd35aSDimitry Andric   const Value *Ptr = OldLI.getPointerOperand();
357508bbd35aSDimitry Andric   auto *ITy = cast<IntegerType>(NewTy);
357608bbd35aSDimitry Andric   auto *NullInt = ConstantExpr::getPtrToInt(
357708bbd35aSDimitry Andric       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
357808bbd35aSDimitry Andric   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
357908bbd35aSDimitry Andric   NewLI.setMetadata(LLVMContext::MD_range,
358008bbd35aSDimitry Andric                     MDB.createRange(NonNullInt, NullInt));
358108bbd35aSDimitry Andric }
358208bbd35aSDimitry Andric 
copyRangeMetadata(const DataLayout & DL,const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)358308bbd35aSDimitry Andric void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
358408bbd35aSDimitry Andric                              MDNode *N, LoadInst &NewLI) {
358508bbd35aSDimitry Andric   auto *NewTy = NewLI.getType();
3586e3b55780SDimitry Andric   // Simply copy the metadata if the type did not change.
3587e3b55780SDimitry Andric   if (NewTy == OldLI.getType()) {
3588e3b55780SDimitry Andric     NewLI.setMetadata(LLVMContext::MD_range, N);
3589e3b55780SDimitry Andric     return;
3590e3b55780SDimitry Andric   }
359108bbd35aSDimitry Andric 
359208bbd35aSDimitry Andric   // Give up unless it is converted to a pointer where there is a single very
359308bbd35aSDimitry Andric   // valuable mapping we can do reliably.
359408bbd35aSDimitry Andric   // FIXME: It would be nice to propagate this in more ways, but the type
359508bbd35aSDimitry Andric   // conversions make it hard.
359608bbd35aSDimitry Andric   if (!NewTy->isPointerTy())
359708bbd35aSDimitry Andric     return;
359808bbd35aSDimitry Andric 
3599706b4fc4SDimitry Andric   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
36007fa27ce4SDimitry Andric   if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
36017fa27ce4SDimitry Andric       !getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
3602e3b55780SDimitry Andric     MDNode *NN = MDNode::get(OldLI.getContext(), std::nullopt);
360308bbd35aSDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
360408bbd35aSDimitry Andric   }
360508bbd35aSDimitry Andric }
360608bbd35aSDimitry Andric 
dropDebugUsers(Instruction & I)3607d8e91e46SDimitry Andric void llvm::dropDebugUsers(Instruction &I) {
3608d8e91e46SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
3609ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
3610b1c73532SDimitry Andric   findDbgUsers(DbgUsers, &I, &DPUsers);
3611d8e91e46SDimitry Andric   for (auto *DII : DbgUsers)
3612d8e91e46SDimitry Andric     DII->eraseFromParent();
3613ac9a064cSDimitry Andric   for (auto *DVR : DPUsers)
3614ac9a064cSDimitry Andric     DVR->eraseFromParent();
3615d8e91e46SDimitry Andric }
3616d8e91e46SDimitry Andric 
hoistAllInstructionsInto(BasicBlock * DomBlock,Instruction * InsertPt,BasicBlock * BB)3617d8e91e46SDimitry Andric void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
3618d8e91e46SDimitry Andric                                     BasicBlock *BB) {
3619d8e91e46SDimitry Andric   // Since we are moving the instructions out of its basic block, we do not
3620d8e91e46SDimitry Andric   // retain their original debug locations (DILocations) and debug intrinsic
3621e6d15924SDimitry Andric   // instructions.
3622d8e91e46SDimitry Andric   //
3623d8e91e46SDimitry Andric   // Doing so would degrade the debugging experience and adversely affect the
3624d8e91e46SDimitry Andric   // accuracy of profiling information.
3625d8e91e46SDimitry Andric   //
3626d8e91e46SDimitry Andric   // Currently, when hoisting the instructions, we take the following actions:
3627e6d15924SDimitry Andric   // - Remove their debug intrinsic instructions.
3628d8e91e46SDimitry Andric   // - Set their debug locations to the values from the insertion point.
3629d8e91e46SDimitry Andric   //
3630d8e91e46SDimitry Andric   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
3631d8e91e46SDimitry Andric   // need to be deleted, is because there will not be any instructions with a
3632d8e91e46SDimitry Andric   // DILocation in either branch left after performing the transformation. We
3633d8e91e46SDimitry Andric   // can only insert a dbg.value after the two branches are joined again.
3634d8e91e46SDimitry Andric   //
3635d8e91e46SDimitry Andric   // See PR38762, PR39243 for more details.
3636d8e91e46SDimitry Andric   //
3637d8e91e46SDimitry Andric   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
3638d8e91e46SDimitry Andric   // encode predicated DIExpressions that yield different results on different
3639d8e91e46SDimitry Andric   // code paths.
3640344a3780SDimitry Andric 
3641d8e91e46SDimitry Andric   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
3642d8e91e46SDimitry Andric     Instruction *I = &*II;
36437fa27ce4SDimitry Andric     I->dropUBImplyingAttrsAndMetadata();
3644d8e91e46SDimitry Andric     if (I->isUsedByMetadata())
3645d8e91e46SDimitry Andric       dropDebugUsers(*I);
3646b1c73532SDimitry Andric     // RemoveDIs: drop debug-info too as the following code does.
3647ac9a064cSDimitry Andric     I->dropDbgRecords();
3648344a3780SDimitry Andric     if (I->isDebugOrPseudoInst()) {
3649344a3780SDimitry Andric       // Remove DbgInfo and pseudo probe Intrinsics.
3650d8e91e46SDimitry Andric       II = I->eraseFromParent();
3651d8e91e46SDimitry Andric       continue;
3652d8e91e46SDimitry Andric     }
3653d8e91e46SDimitry Andric     I->setDebugLoc(InsertPt->getDebugLoc());
3654d8e91e46SDimitry Andric     ++II;
3655d8e91e46SDimitry Andric   }
3656e3b55780SDimitry Andric   DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
3657d8e91e46SDimitry Andric                    BB->getTerminator()->getIterator());
3658d8e91e46SDimitry Andric }
3659d8e91e46SDimitry Andric 
getExpressionForConstant(DIBuilder & DIB,const Constant & C,Type & Ty)3660b1c73532SDimitry Andric DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,
3661b1c73532SDimitry Andric                                              Type &Ty) {
3662b1c73532SDimitry Andric   // Create integer constant expression.
3663b1c73532SDimitry Andric   auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {
3664b1c73532SDimitry Andric     const APInt &API = cast<ConstantInt>(&CV)->getValue();
3665b1c73532SDimitry Andric     std::optional<int64_t> InitIntOpt = API.trySExtValue();
3666b1c73532SDimitry Andric     return InitIntOpt ? DIB.createConstantValueExpression(
3667b1c73532SDimitry Andric                             static_cast<uint64_t>(*InitIntOpt))
3668b1c73532SDimitry Andric                       : nullptr;
3669b1c73532SDimitry Andric   };
3670b1c73532SDimitry Andric 
3671b1c73532SDimitry Andric   if (isa<ConstantInt>(C))
3672b1c73532SDimitry Andric     return createIntegerExpression(C);
3673b1c73532SDimitry Andric 
367477dbea07SDimitry Andric   auto *FP = dyn_cast<ConstantFP>(&C);
3675ac9a064cSDimitry Andric   if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
367677dbea07SDimitry Andric     const APFloat &APF = FP->getValueAPF();
3677ac9a064cSDimitry Andric     APInt const &API = APF.bitcastToAPInt();
3678ac9a064cSDimitry Andric     if (auto Temp = API.getZExtValue())
3679ac9a064cSDimitry Andric       return DIB.createConstantValueExpression(static_cast<uint64_t>(Temp));
3680ac9a064cSDimitry Andric     return DIB.createConstantValueExpression(*API.getRawData());
3681b1c73532SDimitry Andric   }
3682b1c73532SDimitry Andric 
3683b1c73532SDimitry Andric   if (!Ty.isPointerTy())
3684b1c73532SDimitry Andric     return nullptr;
3685b1c73532SDimitry Andric 
3686b1c73532SDimitry Andric   if (isa<ConstantPointerNull>(C))
3687b1c73532SDimitry Andric     return DIB.createConstantValueExpression(0);
3688b1c73532SDimitry Andric 
3689b1c73532SDimitry Andric   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
3690b1c73532SDimitry Andric     if (CE->getOpcode() == Instruction::IntToPtr) {
3691b1c73532SDimitry Andric       const Value *V = CE->getOperand(0);
3692b1c73532SDimitry Andric       if (auto CI = dyn_cast_or_null<ConstantInt>(V))
3693b1c73532SDimitry Andric         return createIntegerExpression(*CI);
3694b1c73532SDimitry Andric     }
3695b1c73532SDimitry Andric   return nullptr;
3696b1c73532SDimitry Andric }
3697b1c73532SDimitry Andric 
remapDebugVariable(ValueToValueMapTy & Mapping,Instruction * Inst)3698ac9a064cSDimitry Andric void llvm::remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst) {
3699ac9a064cSDimitry Andric   auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {
3700ac9a064cSDimitry Andric     for (auto *Op : Set) {
3701ac9a064cSDimitry Andric       auto I = Mapping.find(Op);
3702ac9a064cSDimitry Andric       if (I != Mapping.end())
3703ac9a064cSDimitry Andric         DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);
3704ac9a064cSDimitry Andric     }
3705ac9a064cSDimitry Andric   };
3706ac9a064cSDimitry Andric   auto RemapAssignAddress = [&Mapping](auto *DA) {
3707ac9a064cSDimitry Andric     auto I = Mapping.find(DA->getAddress());
3708ac9a064cSDimitry Andric     if (I != Mapping.end())
3709ac9a064cSDimitry Andric       DA->setAddress(I->second);
3710ac9a064cSDimitry Andric   };
3711ac9a064cSDimitry Andric   if (auto DVI = dyn_cast<DbgVariableIntrinsic>(Inst))
3712ac9a064cSDimitry Andric     RemapDebugOperands(DVI, DVI->location_ops());
3713ac9a064cSDimitry Andric   if (auto DAI = dyn_cast<DbgAssignIntrinsic>(Inst))
3714ac9a064cSDimitry Andric     RemapAssignAddress(DAI);
3715ac9a064cSDimitry Andric   for (DbgVariableRecord &DVR : filterDbgVars(Inst->getDbgRecordRange())) {
3716ac9a064cSDimitry Andric     RemapDebugOperands(&DVR, DVR.location_ops());
3717ac9a064cSDimitry Andric     if (DVR.isDbgAssign())
3718ac9a064cSDimitry Andric       RemapAssignAddress(&DVR);
3719ac9a064cSDimitry Andric   }
3720ac9a064cSDimitry Andric }
3721ac9a064cSDimitry Andric 
3722b915e9e0SDimitry Andric namespace {
3723044eb2f6SDimitry Andric 
3724dadbdfffSDimitry Andric /// A potential constituent of a bitreverse or bswap expression. See
3725dadbdfffSDimitry Andric /// collectBitParts for a fuller explanation.
3726dadbdfffSDimitry Andric struct BitPart {
BitPart__anon2aa0128e1311::BitPart3727dadbdfffSDimitry Andric   BitPart(Value *P, unsigned BW) : Provider(P) {
3728dadbdfffSDimitry Andric     Provenance.resize(BW);
3729dadbdfffSDimitry Andric   }
3730dadbdfffSDimitry Andric 
3731dadbdfffSDimitry Andric   /// The Value that this is a bitreverse/bswap of.
3732dadbdfffSDimitry Andric   Value *Provider;
3733044eb2f6SDimitry Andric 
3734dadbdfffSDimitry Andric   /// The "provenance" of each bit. Provenance[A] = B means that bit A
3735dadbdfffSDimitry Andric   /// in Provider becomes bit B in the result of this expression.
3736dadbdfffSDimitry Andric   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
3737dadbdfffSDimitry Andric 
3738dadbdfffSDimitry Andric   enum { Unset = -1 };
3739dadbdfffSDimitry Andric };
3740044eb2f6SDimitry Andric 
3741b915e9e0SDimitry Andric } // end anonymous namespace
3742dadbdfffSDimitry Andric 
3743dadbdfffSDimitry Andric /// Analyze the specified subexpression and see if it is capable of providing
3744dadbdfffSDimitry Andric /// pieces of a bswap or bitreverse. The subexpression provides a potential
3745b60736ecSDimitry Andric /// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
3746dadbdfffSDimitry Andric /// the output of the expression came from a corresponding bit in some other
3747dadbdfffSDimitry Andric /// value. This function is recursive, and the end result is a mapping of
3748dadbdfffSDimitry Andric /// bitnumber to bitnumber. It is the caller's responsibility to validate that
3749dadbdfffSDimitry Andric /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
3750dadbdfffSDimitry Andric ///
3751dadbdfffSDimitry Andric /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
3752dadbdfffSDimitry Andric /// that the expression deposits the low byte of %X into the high byte of the
3753dadbdfffSDimitry Andric /// result and that all other bits are zero. This expression is accepted and a
3754dadbdfffSDimitry Andric /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
3755dadbdfffSDimitry Andric /// [0-7].
3756dadbdfffSDimitry Andric ///
3757b60736ecSDimitry Andric /// For vector types, all analysis is performed at the per-element level. No
3758b60736ecSDimitry Andric /// cross-element analysis is supported (shuffle/insertion/reduction), and all
3759b60736ecSDimitry Andric /// constant masks must be splatted across all elements.
3760b60736ecSDimitry Andric ///
3761dadbdfffSDimitry Andric /// To avoid revisiting values, the BitPart results are memoized into the
3762dadbdfffSDimitry Andric /// provided map. To avoid unnecessary copying of BitParts, BitParts are
3763dadbdfffSDimitry Andric /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
3764dadbdfffSDimitry Andric /// store BitParts objects, not pointers. As we need the concept of a nullptr
3765dadbdfffSDimitry Andric /// BitParts (Value has been analyzed and the analysis failed), we an Optional
3766dadbdfffSDimitry Andric /// type instead to provide the same functionality.
3767dadbdfffSDimitry Andric ///
3768dadbdfffSDimitry Andric /// Because we pass around references into \c BPS, we must use a container that
3769dadbdfffSDimitry Andric /// does not invalidate internal references (std::map instead of DenseMap).
3770e3b55780SDimitry Andric static const std::optional<BitPart> &
collectBitParts(Value * V,bool MatchBSwaps,bool MatchBitReversals,std::map<Value *,std::optional<BitPart>> & BPS,int Depth,bool & FoundRoot)3771dadbdfffSDimitry Andric collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
3772e3b55780SDimitry Andric                 std::map<Value *, std::optional<BitPart>> &BPS, int Depth,
3773344a3780SDimitry Andric                 bool &FoundRoot) {
3774dadbdfffSDimitry Andric   auto I = BPS.find(V);
3775dadbdfffSDimitry Andric   if (I != BPS.end())
3776dadbdfffSDimitry Andric     return I->second;
3777dadbdfffSDimitry Andric 
3778e3b55780SDimitry Andric   auto &Result = BPS[V] = std::nullopt;
3779b60736ecSDimitry Andric   auto BitWidth = V->getType()->getScalarSizeInBits();
3780dadbdfffSDimitry Andric 
3781344a3780SDimitry Andric   // Can't do integer/elements > 128 bits.
3782344a3780SDimitry Andric   if (BitWidth > 128)
3783344a3780SDimitry Andric     return Result;
3784344a3780SDimitry Andric 
3785e6d15924SDimitry Andric   // Prevent stack overflow by limiting the recursion depth
3786e6d15924SDimitry Andric   if (Depth == BitPartRecursionMaxDepth) {
3787e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
3788e6d15924SDimitry Andric     return Result;
3789e6d15924SDimitry Andric   }
3790e6d15924SDimitry Andric 
3791b60736ecSDimitry Andric   if (auto *I = dyn_cast<Instruction>(V)) {
3792b60736ecSDimitry Andric     Value *X, *Y;
3793b60736ecSDimitry Andric     const APInt *C;
3794b60736ecSDimitry Andric 
3795dadbdfffSDimitry Andric     // If this is an or instruction, it may be an inner node of the bswap.
3796b60736ecSDimitry Andric     if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
3797344a3780SDimitry Andric       // Check we have both sources and they are from the same provider.
3798344a3780SDimitry Andric       const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3799344a3780SDimitry Andric                                       Depth + 1, FoundRoot);
3800344a3780SDimitry Andric       if (!A || !A->Provider)
3801344a3780SDimitry Andric         return Result;
3802344a3780SDimitry Andric 
3803344a3780SDimitry Andric       const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3804344a3780SDimitry Andric                                       Depth + 1, FoundRoot);
3805344a3780SDimitry Andric       if (!B || A->Provider != B->Provider)
3806dadbdfffSDimitry Andric         return Result;
3807dadbdfffSDimitry Andric 
3808dadbdfffSDimitry Andric       // Try and merge the two together.
3809dadbdfffSDimitry Andric       Result = BitPart(A->Provider, BitWidth);
3810b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
3811b60736ecSDimitry Andric         if (A->Provenance[BitIdx] != BitPart::Unset &&
3812b60736ecSDimitry Andric             B->Provenance[BitIdx] != BitPart::Unset &&
3813b60736ecSDimitry Andric             A->Provenance[BitIdx] != B->Provenance[BitIdx])
3814e3b55780SDimitry Andric           return Result = std::nullopt;
3815dadbdfffSDimitry Andric 
3816b60736ecSDimitry Andric         if (A->Provenance[BitIdx] == BitPart::Unset)
3817b60736ecSDimitry Andric           Result->Provenance[BitIdx] = B->Provenance[BitIdx];
3818dadbdfffSDimitry Andric         else
3819b60736ecSDimitry Andric           Result->Provenance[BitIdx] = A->Provenance[BitIdx];
3820dadbdfffSDimitry Andric       }
3821dadbdfffSDimitry Andric 
3822dadbdfffSDimitry Andric       return Result;
3823dadbdfffSDimitry Andric     }
3824dadbdfffSDimitry Andric 
3825dadbdfffSDimitry Andric     // If this is a logical shift by a constant, recurse then shift the result.
3826b60736ecSDimitry Andric     if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
3827b60736ecSDimitry Andric       const APInt &BitShift = *C;
3828b60736ecSDimitry Andric 
3829dadbdfffSDimitry Andric       // Ensure the shift amount is defined.
3830b60736ecSDimitry Andric       if (BitShift.uge(BitWidth))
3831dadbdfffSDimitry Andric         return Result;
3832dadbdfffSDimitry Andric 
3833344a3780SDimitry Andric       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3834344a3780SDimitry Andric       if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3835344a3780SDimitry Andric         return Result;
3836344a3780SDimitry Andric 
3837344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3838344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3839dadbdfffSDimitry Andric       if (!Res)
3840dadbdfffSDimitry Andric         return Result;
3841dadbdfffSDimitry Andric       Result = Res;
3842dadbdfffSDimitry Andric 
3843dadbdfffSDimitry Andric       // Perform the "shift" on BitProvenance.
3844dadbdfffSDimitry Andric       auto &P = Result->Provenance;
3845dadbdfffSDimitry Andric       if (I->getOpcode() == Instruction::Shl) {
3846b60736ecSDimitry Andric         P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
3847b60736ecSDimitry Andric         P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
3848dadbdfffSDimitry Andric       } else {
3849b60736ecSDimitry Andric         P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
3850b60736ecSDimitry Andric         P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
3851dadbdfffSDimitry Andric       }
3852dadbdfffSDimitry Andric 
3853dadbdfffSDimitry Andric       return Result;
3854dadbdfffSDimitry Andric     }
3855dadbdfffSDimitry Andric 
3856dadbdfffSDimitry Andric     // If this is a logical 'and' with a mask that clears bits, recurse then
3857dadbdfffSDimitry Andric     // unset the appropriate bits.
3858b60736ecSDimitry Andric     if (match(V, m_And(m_Value(X), m_APInt(C)))) {
3859b60736ecSDimitry Andric       const APInt &AndMask = *C;
3860dadbdfffSDimitry Andric 
3861dadbdfffSDimitry Andric       // Check that the mask allows a multiple of 8 bits for a bswap, for an
3862dadbdfffSDimitry Andric       // early exit.
38637fa27ce4SDimitry Andric       unsigned NumMaskedBits = AndMask.popcount();
3864b60736ecSDimitry Andric       if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3865dadbdfffSDimitry Andric         return Result;
3866dadbdfffSDimitry Andric 
3867344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3868344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3869dadbdfffSDimitry Andric       if (!Res)
3870dadbdfffSDimitry Andric         return Result;
3871dadbdfffSDimitry Andric       Result = Res;
3872dadbdfffSDimitry Andric 
3873b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3874dadbdfffSDimitry Andric         // If the AndMask is zero for this bit, clear the bit.
3875b60736ecSDimitry Andric         if (AndMask[BitIdx] == 0)
3876b60736ecSDimitry Andric           Result->Provenance[BitIdx] = BitPart::Unset;
387701095a5dSDimitry Andric       return Result;
387801095a5dSDimitry Andric     }
3879dadbdfffSDimitry Andric 
388001095a5dSDimitry Andric     // If this is a zext instruction zero extend the result.
3881b60736ecSDimitry Andric     if (match(V, m_ZExt(m_Value(X)))) {
3882344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3883344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
388401095a5dSDimitry Andric       if (!Res)
388501095a5dSDimitry Andric         return Result;
388601095a5dSDimitry Andric 
388701095a5dSDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3888b60736ecSDimitry Andric       auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3889b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3890b60736ecSDimitry Andric         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3891b60736ecSDimitry Andric       for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3892b60736ecSDimitry Andric         Result->Provenance[BitIdx] = BitPart::Unset;
3893b60736ecSDimitry Andric       return Result;
3894b60736ecSDimitry Andric     }
3895b60736ecSDimitry Andric 
3896344a3780SDimitry Andric     // If this is a truncate instruction, extract the lower bits.
3897344a3780SDimitry Andric     if (match(V, m_Trunc(m_Value(X)))) {
3898344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3899344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3900344a3780SDimitry Andric       if (!Res)
3901344a3780SDimitry Andric         return Result;
3902344a3780SDimitry Andric 
3903344a3780SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3904344a3780SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3905344a3780SDimitry Andric         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3906344a3780SDimitry Andric       return Result;
3907344a3780SDimitry Andric     }
3908344a3780SDimitry Andric 
3909b60736ecSDimitry Andric     // BITREVERSE - most likely due to us previous matching a partial
3910b60736ecSDimitry Andric     // bitreverse.
3911b60736ecSDimitry Andric     if (match(V, m_BitReverse(m_Value(X)))) {
3912344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3913344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3914b60736ecSDimitry Andric       if (!Res)
3915b60736ecSDimitry Andric         return Result;
3916b60736ecSDimitry Andric 
3917b60736ecSDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3918b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3919b60736ecSDimitry Andric         Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3920b60736ecSDimitry Andric       return Result;
3921b60736ecSDimitry Andric     }
3922b60736ecSDimitry Andric 
3923b60736ecSDimitry Andric     // BSWAP - most likely due to us previous matching a partial bswap.
3924b60736ecSDimitry Andric     if (match(V, m_BSwap(m_Value(X)))) {
3925344a3780SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3926344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3927b60736ecSDimitry Andric       if (!Res)
3928b60736ecSDimitry Andric         return Result;
3929b60736ecSDimitry Andric 
3930b60736ecSDimitry Andric       unsigned ByteWidth = BitWidth / 8;
3931b60736ecSDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3932b60736ecSDimitry Andric       for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3933b60736ecSDimitry Andric         unsigned ByteBitOfs = ByteIdx * 8;
3934b60736ecSDimitry Andric         for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3935b60736ecSDimitry Andric           Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3936b60736ecSDimitry Andric               Res->Provenance[ByteBitOfs + BitIdx];
3937b60736ecSDimitry Andric       }
3938b60736ecSDimitry Andric       return Result;
3939b60736ecSDimitry Andric     }
3940b60736ecSDimitry Andric 
3941b60736ecSDimitry Andric     // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3942b60736ecSDimitry Andric     // amount (modulo).
3943b60736ecSDimitry Andric     // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3944b60736ecSDimitry Andric     // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3945b60736ecSDimitry Andric     if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
3946b60736ecSDimitry Andric         match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
3947b60736ecSDimitry Andric       // We can treat fshr as a fshl by flipping the modulo amount.
3948b60736ecSDimitry Andric       unsigned ModAmt = C->urem(BitWidth);
3949b60736ecSDimitry Andric       if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
3950b60736ecSDimitry Andric         ModAmt = BitWidth - ModAmt;
3951b60736ecSDimitry Andric 
3952344a3780SDimitry Andric       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3953344a3780SDimitry Andric       if (!MatchBitReversals && (ModAmt % 8) != 0)
3954344a3780SDimitry Andric         return Result;
3955b60736ecSDimitry Andric 
3956b60736ecSDimitry Andric       // Check we have both sources and they are from the same provider.
3957344a3780SDimitry Andric       const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3958344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3959344a3780SDimitry Andric       if (!LHS || !LHS->Provider)
3960344a3780SDimitry Andric         return Result;
3961344a3780SDimitry Andric 
3962344a3780SDimitry Andric       const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3963344a3780SDimitry Andric                                         Depth + 1, FoundRoot);
3964344a3780SDimitry Andric       if (!RHS || LHS->Provider != RHS->Provider)
3965b60736ecSDimitry Andric         return Result;
3966b60736ecSDimitry Andric 
3967b60736ecSDimitry Andric       unsigned StartBitRHS = BitWidth - ModAmt;
3968b60736ecSDimitry Andric       Result = BitPart(LHS->Provider, BitWidth);
3969b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3970b60736ecSDimitry Andric         Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
3971b60736ecSDimitry Andric       for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3972b60736ecSDimitry Andric         Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
3973dadbdfffSDimitry Andric       return Result;
3974dadbdfffSDimitry Andric     }
3975dadbdfffSDimitry Andric   }
3976dadbdfffSDimitry Andric 
3977344a3780SDimitry Andric   // If we've already found a root input value then we're never going to merge
3978344a3780SDimitry Andric   // these back together.
3979344a3780SDimitry Andric   if (FoundRoot)
3980344a3780SDimitry Andric     return Result;
3981344a3780SDimitry Andric 
3982344a3780SDimitry Andric   // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
3983344a3780SDimitry Andric   // be the root input value to the bswap/bitreverse.
3984344a3780SDimitry Andric   FoundRoot = true;
3985dadbdfffSDimitry Andric   Result = BitPart(V, BitWidth);
3986b60736ecSDimitry Andric   for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3987b60736ecSDimitry Andric     Result->Provenance[BitIdx] = BitIdx;
3988dadbdfffSDimitry Andric   return Result;
3989dadbdfffSDimitry Andric }
3990dadbdfffSDimitry Andric 
bitTransformIsCorrectForBSwap(unsigned From,unsigned To,unsigned BitWidth)3991dadbdfffSDimitry Andric static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
3992dadbdfffSDimitry Andric                                           unsigned BitWidth) {
3993dadbdfffSDimitry Andric   if (From % 8 != To % 8)
3994dadbdfffSDimitry Andric     return false;
3995dadbdfffSDimitry Andric   // Convert from bit indices to byte indices and check for a byte reversal.
3996dadbdfffSDimitry Andric   From >>= 3;
3997dadbdfffSDimitry Andric   To >>= 3;
3998dadbdfffSDimitry Andric   BitWidth >>= 3;
3999dadbdfffSDimitry Andric   return From == BitWidth - To - 1;
4000dadbdfffSDimitry Andric }
4001dadbdfffSDimitry Andric 
bitTransformIsCorrectForBitReverse(unsigned From,unsigned To,unsigned BitWidth)4002dadbdfffSDimitry Andric static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
4003dadbdfffSDimitry Andric                                                unsigned BitWidth) {
4004dadbdfffSDimitry Andric   return From == BitWidth - To - 1;
4005dadbdfffSDimitry Andric }
4006dadbdfffSDimitry Andric 
recognizeBSwapOrBitReverseIdiom(Instruction * I,bool MatchBSwaps,bool MatchBitReversals,SmallVectorImpl<Instruction * > & InsertedInsts)400701095a5dSDimitry Andric bool llvm::recognizeBSwapOrBitReverseIdiom(
4008dadbdfffSDimitry Andric     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
4009dadbdfffSDimitry Andric     SmallVectorImpl<Instruction *> &InsertedInsts) {
4010344a3780SDimitry Andric   if (!match(I, m_Or(m_Value(), m_Value())) &&
4011344a3780SDimitry Andric       !match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
4012950076cdSDimitry Andric       !match(I, m_FShr(m_Value(), m_Value(), m_Value())) &&
4013950076cdSDimitry Andric       !match(I, m_BSwap(m_Value())))
4014dadbdfffSDimitry Andric     return false;
4015dadbdfffSDimitry Andric   if (!MatchBSwaps && !MatchBitReversals)
4016dadbdfffSDimitry Andric     return false;
4017b60736ecSDimitry Andric   Type *ITy = I->getType();
4018b60736ecSDimitry Andric   if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
4019b60736ecSDimitry Andric     return false;  // Can't do integer/elements > 128 bits.
4020dadbdfffSDimitry Andric 
4021dadbdfffSDimitry Andric   // Try to find all the pieces corresponding to the bswap.
4022344a3780SDimitry Andric   bool FoundRoot = false;
4023e3b55780SDimitry Andric   std::map<Value *, std::optional<BitPart>> BPS;
4024344a3780SDimitry Andric   const auto &Res =
4025344a3780SDimitry Andric       collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
4026dadbdfffSDimitry Andric   if (!Res)
4027dadbdfffSDimitry Andric     return false;
4028b60736ecSDimitry Andric   ArrayRef<int8_t> BitProvenance = Res->Provenance;
4029b60736ecSDimitry Andric   assert(all_of(BitProvenance,
4030b60736ecSDimitry Andric                 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
4031b60736ecSDimitry Andric          "Illegal bit provenance index");
4032b60736ecSDimitry Andric 
4033b60736ecSDimitry Andric   // If the upper bits are zero, then attempt to perform as a truncated op.
40346f8fc217SDimitry Andric   Type *DemandedTy = ITy;
4035b60736ecSDimitry Andric   if (BitProvenance.back() == BitPart::Unset) {
4036b60736ecSDimitry Andric     while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
4037b60736ecSDimitry Andric       BitProvenance = BitProvenance.drop_back();
4038b60736ecSDimitry Andric     if (BitProvenance.empty())
4039b60736ecSDimitry Andric       return false; // TODO - handle null value?
4040b60736ecSDimitry Andric     DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
4041b60736ecSDimitry Andric     if (auto *IVecTy = dyn_cast<VectorType>(ITy))
4042b60736ecSDimitry Andric       DemandedTy = VectorType::get(DemandedTy, IVecTy);
4043b60736ecSDimitry Andric   }
4044b60736ecSDimitry Andric 
4045b60736ecSDimitry Andric   // Check BitProvenance hasn't found a source larger than the result type.
4046b60736ecSDimitry Andric   unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
4047b60736ecSDimitry Andric   if (DemandedBW > ITy->getScalarSizeInBits())
4048b60736ecSDimitry Andric     return false;
4049dadbdfffSDimitry Andric 
4050dadbdfffSDimitry Andric   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
4051dadbdfffSDimitry Andric   // only byteswap values with an even number of bytes.
4052c0981da4SDimitry Andric   APInt DemandedMask = APInt::getAllOnes(DemandedBW);
4053b60736ecSDimitry Andric   bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
4054b60736ecSDimitry Andric   bool OKForBitReverse = MatchBitReversals;
4055b60736ecSDimitry Andric   for (unsigned BitIdx = 0;
4056b60736ecSDimitry Andric        (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
4057b60736ecSDimitry Andric     if (BitProvenance[BitIdx] == BitPart::Unset) {
4058b60736ecSDimitry Andric       DemandedMask.clearBit(BitIdx);
4059b60736ecSDimitry Andric       continue;
4060b60736ecSDimitry Andric     }
4061b60736ecSDimitry Andric     OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
4062b60736ecSDimitry Andric                                                 DemandedBW);
4063b60736ecSDimitry Andric     OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
4064b60736ecSDimitry Andric                                                           BitIdx, DemandedBW);
4065dadbdfffSDimitry Andric   }
4066dadbdfffSDimitry Andric 
4067dadbdfffSDimitry Andric   Intrinsic::ID Intrin;
4068b60736ecSDimitry Andric   if (OKForBSwap)
4069dadbdfffSDimitry Andric     Intrin = Intrinsic::bswap;
4070b60736ecSDimitry Andric   else if (OKForBitReverse)
4071dadbdfffSDimitry Andric     Intrin = Intrinsic::bitreverse;
4072dadbdfffSDimitry Andric   else
4073dadbdfffSDimitry Andric     return false;
4074dadbdfffSDimitry Andric 
407501095a5dSDimitry Andric   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
407601095a5dSDimitry Andric   Value *Provider = Res->Provider;
4077b60736ecSDimitry Andric 
407801095a5dSDimitry Andric   // We may need to truncate the provider.
4079b60736ecSDimitry Andric   if (DemandedTy != Provider->getType()) {
4080b60736ecSDimitry Andric     auto *Trunc =
4081ac9a064cSDimitry Andric         CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I->getIterator());
408201095a5dSDimitry Andric     InsertedInsts.push_back(Trunc);
408301095a5dSDimitry Andric     Provider = Trunc;
408401095a5dSDimitry Andric   }
4085b60736ecSDimitry Andric 
4086ac9a064cSDimitry Andric   Instruction *Result = CallInst::Create(F, Provider, "rev", I->getIterator());
4087b60736ecSDimitry Andric   InsertedInsts.push_back(Result);
4088b60736ecSDimitry Andric 
4089c0981da4SDimitry Andric   if (!DemandedMask.isAllOnes()) {
4090b60736ecSDimitry Andric     auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
4091ac9a064cSDimitry Andric     Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I->getIterator());
4092b60736ecSDimitry Andric     InsertedInsts.push_back(Result);
409301095a5dSDimitry Andric   }
409401095a5dSDimitry Andric 
4095b60736ecSDimitry Andric   // We may need to zeroextend back to the result type.
4096b60736ecSDimitry Andric   if (ITy != Result->getType()) {
4097ac9a064cSDimitry Andric     auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I->getIterator());
4098b60736ecSDimitry Andric     InsertedInsts.push_back(ExtInst);
4099b60736ecSDimitry Andric   }
4100b60736ecSDimitry Andric 
4101dadbdfffSDimitry Andric   return true;
4102dadbdfffSDimitry Andric }
410301095a5dSDimitry Andric 
410401095a5dSDimitry Andric // CodeGen has special handling for some string functions that may replace
410501095a5dSDimitry Andric // them with target-specific intrinsics.  Since that'd skip our interceptors
410601095a5dSDimitry Andric // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
410701095a5dSDimitry Andric // we mark affected calls as NoBuiltin, which will disable optimization
410801095a5dSDimitry Andric // in CodeGen.
maybeMarkSanitizerLibraryCallNoBuiltin(CallInst * CI,const TargetLibraryInfo * TLI)4109b915e9e0SDimitry Andric void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
4110b915e9e0SDimitry Andric     CallInst *CI, const TargetLibraryInfo *TLI) {
411101095a5dSDimitry Andric   Function *F = CI->getCalledFunction();
411271d5a254SDimitry Andric   LibFunc Func;
4113b915e9e0SDimitry Andric   if (F && !F->hasLocalLinkage() && F->hasName() &&
4114b915e9e0SDimitry Andric       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
4115b915e9e0SDimitry Andric       !F->doesNotAccessMemory())
4116c0981da4SDimitry Andric     CI->addFnAttr(Attribute::NoBuiltin);
411701095a5dSDimitry Andric }
4118ab44ce3dSDimitry Andric 
canReplaceOperandWithVariable(const Instruction * I,unsigned OpIdx)4119ab44ce3dSDimitry Andric bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
4120ab44ce3dSDimitry Andric   // We can't have a PHI with a metadata type.
4121ab44ce3dSDimitry Andric   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
4122ab44ce3dSDimitry Andric     return false;
4123ab44ce3dSDimitry Andric 
4124ab44ce3dSDimitry Andric   // Early exit.
4125ab44ce3dSDimitry Andric   if (!isa<Constant>(I->getOperand(OpIdx)))
4126ab44ce3dSDimitry Andric     return true;
4127ab44ce3dSDimitry Andric 
4128ab44ce3dSDimitry Andric   switch (I->getOpcode()) {
4129ab44ce3dSDimitry Andric   default:
4130ab44ce3dSDimitry Andric     return true;
4131ab44ce3dSDimitry Andric   case Instruction::Call:
4132cfca06d7SDimitry Andric   case Instruction::Invoke: {
4133cfca06d7SDimitry Andric     const auto &CB = cast<CallBase>(*I);
4134cfca06d7SDimitry Andric 
4135ca089b24SDimitry Andric     // Can't handle inline asm. Skip it.
4136cfca06d7SDimitry Andric     if (CB.isInlineAsm())
4137ab44ce3dSDimitry Andric       return false;
4138ab44ce3dSDimitry Andric 
4139ab44ce3dSDimitry Andric     // Constant bundle operands may need to retain their constant-ness for
4140ab44ce3dSDimitry Andric     // correctness.
4141cfca06d7SDimitry Andric     if (CB.isBundleOperand(OpIdx))
4142ab44ce3dSDimitry Andric       return false;
4143cfca06d7SDimitry Andric 
4144c0981da4SDimitry Andric     if (OpIdx < CB.arg_size()) {
4145cfca06d7SDimitry Andric       // Some variadic intrinsics require constants in the variadic arguments,
4146cfca06d7SDimitry Andric       // which currently aren't markable as immarg.
4147cfca06d7SDimitry Andric       if (isa<IntrinsicInst>(CB) &&
4148cfca06d7SDimitry Andric           OpIdx >= CB.getFunctionType()->getNumParams()) {
4149cfca06d7SDimitry Andric         // This is known to be OK for stackmap.
4150cfca06d7SDimitry Andric         return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
4151cfca06d7SDimitry Andric       }
4152cfca06d7SDimitry Andric 
4153cfca06d7SDimitry Andric       // gcroot is a special case, since it requires a constant argument which
4154cfca06d7SDimitry Andric       // isn't also required to be a simple ConstantInt.
4155cfca06d7SDimitry Andric       if (CB.getIntrinsicID() == Intrinsic::gcroot)
4156cfca06d7SDimitry Andric         return false;
4157cfca06d7SDimitry Andric 
4158cfca06d7SDimitry Andric       // Some intrinsic operands are required to be immediates.
4159cfca06d7SDimitry Andric       return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
4160cfca06d7SDimitry Andric     }
4161cfca06d7SDimitry Andric 
4162cfca06d7SDimitry Andric     // It is never allowed to replace the call argument to an intrinsic, but it
4163cfca06d7SDimitry Andric     // may be possible for a call.
4164cfca06d7SDimitry Andric     return !isa<IntrinsicInst>(CB);
4165cfca06d7SDimitry Andric   }
4166ab44ce3dSDimitry Andric   case Instruction::ShuffleVector:
4167ab44ce3dSDimitry Andric     // Shufflevector masks are constant.
4168ab44ce3dSDimitry Andric     return OpIdx != 2;
4169ca089b24SDimitry Andric   case Instruction::Switch:
4170ab44ce3dSDimitry Andric   case Instruction::ExtractValue:
4171ab44ce3dSDimitry Andric     // All operands apart from the first are constant.
4172ab44ce3dSDimitry Andric     return OpIdx == 0;
4173ca089b24SDimitry Andric   case Instruction::InsertValue:
4174ca089b24SDimitry Andric     // All operands apart from the first and the second are constant.
4175ca089b24SDimitry Andric     return OpIdx < 2;
4176ab44ce3dSDimitry Andric   case Instruction::Alloca:
4177ca089b24SDimitry Andric     // Static allocas (constant size in the entry block) are handled by
4178ca089b24SDimitry Andric     // prologue/epilogue insertion so they're free anyway. We definitely don't
4179ca089b24SDimitry Andric     // want to make them non-constant.
4180eb11fae6SDimitry Andric     return !cast<AllocaInst>(I)->isStaticAlloca();
4181ab44ce3dSDimitry Andric   case Instruction::GetElementPtr:
4182ab44ce3dSDimitry Andric     if (OpIdx == 0)
4183ab44ce3dSDimitry Andric       return true;
4184ab44ce3dSDimitry Andric     gep_type_iterator It = gep_type_begin(I);
4185ab44ce3dSDimitry Andric     for (auto E = std::next(It, OpIdx); It != E; ++It)
4186ab44ce3dSDimitry Andric       if (It.isStruct())
4187ab44ce3dSDimitry Andric         return false;
4188ab44ce3dSDimitry Andric     return true;
4189ab44ce3dSDimitry Andric   }
4190ab44ce3dSDimitry Andric }
4191e6d15924SDimitry Andric 
invertCondition(Value * Condition)4192cfca06d7SDimitry Andric Value *llvm::invertCondition(Value *Condition) {
4193cfca06d7SDimitry Andric   // First: Check if it's a constant
4194cfca06d7SDimitry Andric   if (Constant *C = dyn_cast<Constant>(Condition))
4195cfca06d7SDimitry Andric     return ConstantExpr::getNot(C);
4196cfca06d7SDimitry Andric 
4197cfca06d7SDimitry Andric   // Second: If the condition is already inverted, return the original value
4198cfca06d7SDimitry Andric   Value *NotCondition;
4199cfca06d7SDimitry Andric   if (match(Condition, m_Not(m_Value(NotCondition))))
4200cfca06d7SDimitry Andric     return NotCondition;
4201cfca06d7SDimitry Andric 
4202cfca06d7SDimitry Andric   BasicBlock *Parent = nullptr;
4203cfca06d7SDimitry Andric   Instruction *Inst = dyn_cast<Instruction>(Condition);
4204cfca06d7SDimitry Andric   if (Inst)
4205cfca06d7SDimitry Andric     Parent = Inst->getParent();
4206cfca06d7SDimitry Andric   else if (Argument *Arg = dyn_cast<Argument>(Condition))
4207cfca06d7SDimitry Andric     Parent = &Arg->getParent()->getEntryBlock();
4208cfca06d7SDimitry Andric   assert(Parent && "Unsupported condition to invert");
4209cfca06d7SDimitry Andric 
4210cfca06d7SDimitry Andric   // Third: Check all the users for an invert
4211cfca06d7SDimitry Andric   for (User *U : Condition->users())
4212cfca06d7SDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(U))
4213cfca06d7SDimitry Andric       if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
4214cfca06d7SDimitry Andric         return I;
4215cfca06d7SDimitry Andric 
4216cfca06d7SDimitry Andric   // Last option: Create a new instruction
4217cfca06d7SDimitry Andric   auto *Inverted =
4218cfca06d7SDimitry Andric       BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
4219cfca06d7SDimitry Andric   if (Inst && !isa<PHINode>(Inst))
4220cfca06d7SDimitry Andric     Inverted->insertAfter(Inst);
4221cfca06d7SDimitry Andric   else
4222cfca06d7SDimitry Andric     Inverted->insertBefore(&*Parent->getFirstInsertionPt());
4223cfca06d7SDimitry Andric   return Inverted;
4224cfca06d7SDimitry Andric }
4225344a3780SDimitry Andric 
inferAttributesFromOthers(Function & F)4226344a3780SDimitry Andric bool llvm::inferAttributesFromOthers(Function &F) {
4227344a3780SDimitry Andric   // Note: We explicitly check for attributes rather than using cover functions
4228344a3780SDimitry Andric   // because some of the cover functions include the logic being implemented.
4229344a3780SDimitry Andric 
4230344a3780SDimitry Andric   bool Changed = false;
4231344a3780SDimitry Andric   // readnone + not convergent implies nosync
4232344a3780SDimitry Andric   if (!F.hasFnAttribute(Attribute::NoSync) &&
4233344a3780SDimitry Andric       F.doesNotAccessMemory() && !F.isConvergent()) {
4234344a3780SDimitry Andric     F.setNoSync();
4235344a3780SDimitry Andric     Changed = true;
4236344a3780SDimitry Andric   }
4237344a3780SDimitry Andric 
4238344a3780SDimitry Andric   // readonly implies nofree
4239344a3780SDimitry Andric   if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
4240344a3780SDimitry Andric     F.setDoesNotFreeMemory();
4241344a3780SDimitry Andric     Changed = true;
4242344a3780SDimitry Andric   }
4243344a3780SDimitry Andric 
4244344a3780SDimitry Andric   // willreturn implies mustprogress
4245344a3780SDimitry Andric   if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
4246344a3780SDimitry Andric     F.setMustProgress();
4247344a3780SDimitry Andric     Changed = true;
4248344a3780SDimitry Andric   }
4249344a3780SDimitry Andric 
4250344a3780SDimitry Andric   // TODO: There are a bunch of cases of restrictive memory effects we
4251344a3780SDimitry Andric   // can infer by inspecting arguments of argmemonly-ish functions.
4252344a3780SDimitry Andric 
4253344a3780SDimitry Andric   return Changed;
4254344a3780SDimitry Andric }
4255