1*9880d681SAndroid Build Coastguard Worker //===-- Local.cpp - Functions to perform local transformations ------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This family of functions perform various local transformations to the
11*9880d681SAndroid Build Coastguard Worker // program.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseSet.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Hashing.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/EHPersonalities.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LazyValueInfo.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DIBuilder.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DebugInfo.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GetElementPtrTypeIterator.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GlobalAlias.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GlobalVariable.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Intrinsics.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/MDBuilder.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Metadata.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Operator.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MathExtras.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
50*9880d681SAndroid Build Coastguard Worker using namespace llvm;
51*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
52*9880d681SAndroid Build Coastguard Worker
53*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "local"
54*9880d681SAndroid Build Coastguard Worker
55*9880d681SAndroid Build Coastguard Worker STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
56*9880d681SAndroid Build Coastguard Worker
57*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
58*9880d681SAndroid Build Coastguard Worker // Local constant propagation.
59*9880d681SAndroid Build Coastguard Worker //
60*9880d681SAndroid Build Coastguard Worker
61*9880d681SAndroid Build Coastguard Worker /// ConstantFoldTerminator - If a terminator instruction is predicated on a
62*9880d681SAndroid Build Coastguard Worker /// constant value, convert it into an unconditional branch to the constant
63*9880d681SAndroid Build Coastguard Worker /// destination. This is a nontrivial operation because the successors of this
64*9880d681SAndroid Build Coastguard Worker /// basic block must have their PHI nodes updated.
65*9880d681SAndroid Build Coastguard Worker /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
66*9880d681SAndroid Build Coastguard Worker /// conditions and indirectbr addresses this might make dead if
67*9880d681SAndroid Build Coastguard Worker /// DeleteDeadConditions is true.
ConstantFoldTerminator(BasicBlock * BB,bool DeleteDeadConditions,const TargetLibraryInfo * TLI)68*9880d681SAndroid Build Coastguard Worker bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
69*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
70*9880d681SAndroid Build Coastguard Worker TerminatorInst *T = BB->getTerminator();
71*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(T);
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker // Branch - See if we are conditional jumping on constant
74*9880d681SAndroid Build Coastguard Worker if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
75*9880d681SAndroid Build Coastguard Worker if (BI->isUnconditional()) return false; // Can't optimize uncond branch
76*9880d681SAndroid Build Coastguard Worker BasicBlock *Dest1 = BI->getSuccessor(0);
77*9880d681SAndroid Build Coastguard Worker BasicBlock *Dest2 = BI->getSuccessor(1);
78*9880d681SAndroid Build Coastguard Worker
79*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
80*9880d681SAndroid Build Coastguard Worker // Are we branching on constant?
81*9880d681SAndroid Build Coastguard Worker // YES. Change to unconditional branch...
82*9880d681SAndroid Build Coastguard Worker BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
83*9880d681SAndroid Build Coastguard Worker BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker //cerr << "Function: " << T->getParent()->getParent()
86*9880d681SAndroid Build Coastguard Worker // << "\nRemoving branch from " << T->getParent()
87*9880d681SAndroid Build Coastguard Worker // << "\n\nTo: " << OldDest << endl;
88*9880d681SAndroid Build Coastguard Worker
89*9880d681SAndroid Build Coastguard Worker // Let the basic block know that we are letting go of it. Based on this,
90*9880d681SAndroid Build Coastguard Worker // it will adjust it's PHI nodes.
91*9880d681SAndroid Build Coastguard Worker OldDest->removePredecessor(BB);
92*9880d681SAndroid Build Coastguard Worker
93*9880d681SAndroid Build Coastguard Worker // Replace the conditional branch with an unconditional one.
94*9880d681SAndroid Build Coastguard Worker Builder.CreateBr(Destination);
95*9880d681SAndroid Build Coastguard Worker BI->eraseFromParent();
96*9880d681SAndroid Build Coastguard Worker return true;
97*9880d681SAndroid Build Coastguard Worker }
98*9880d681SAndroid Build Coastguard Worker
99*9880d681SAndroid Build Coastguard Worker if (Dest2 == Dest1) { // Conditional branch to same location?
100*9880d681SAndroid Build Coastguard Worker // This branch matches something like this:
101*9880d681SAndroid Build Coastguard Worker // br bool %cond, label %Dest, label %Dest
102*9880d681SAndroid Build Coastguard Worker // and changes it into: br label %Dest
103*9880d681SAndroid Build Coastguard Worker
104*9880d681SAndroid Build Coastguard Worker // Let the basic block know that we are letting go of one copy of it.
105*9880d681SAndroid Build Coastguard Worker assert(BI->getParent() && "Terminator not inserted in block!");
106*9880d681SAndroid Build Coastguard Worker Dest1->removePredecessor(BI->getParent());
107*9880d681SAndroid Build Coastguard Worker
108*9880d681SAndroid Build Coastguard Worker // Replace the conditional branch with an unconditional one.
109*9880d681SAndroid Build Coastguard Worker Builder.CreateBr(Dest1);
110*9880d681SAndroid Build Coastguard Worker Value *Cond = BI->getCondition();
111*9880d681SAndroid Build Coastguard Worker BI->eraseFromParent();
112*9880d681SAndroid Build Coastguard Worker if (DeleteDeadConditions)
113*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
114*9880d681SAndroid Build Coastguard Worker return true;
115*9880d681SAndroid Build Coastguard Worker }
116*9880d681SAndroid Build Coastguard Worker return false;
117*9880d681SAndroid Build Coastguard Worker }
118*9880d681SAndroid Build Coastguard Worker
119*9880d681SAndroid Build Coastguard Worker if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
120*9880d681SAndroid Build Coastguard Worker // If we are switching on a constant, we can convert the switch to an
121*9880d681SAndroid Build Coastguard Worker // unconditional branch.
122*9880d681SAndroid Build Coastguard Worker ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
123*9880d681SAndroid Build Coastguard Worker BasicBlock *DefaultDest = SI->getDefaultDest();
124*9880d681SAndroid Build Coastguard Worker BasicBlock *TheOnlyDest = DefaultDest;
125*9880d681SAndroid Build Coastguard Worker
126*9880d681SAndroid Build Coastguard Worker // If the default is unreachable, ignore it when searching for TheOnlyDest.
127*9880d681SAndroid Build Coastguard Worker if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
128*9880d681SAndroid Build Coastguard Worker SI->getNumCases() > 0) {
129*9880d681SAndroid Build Coastguard Worker TheOnlyDest = SI->case_begin().getCaseSuccessor();
130*9880d681SAndroid Build Coastguard Worker }
131*9880d681SAndroid Build Coastguard Worker
132*9880d681SAndroid Build Coastguard Worker // Figure out which case it goes to.
133*9880d681SAndroid Build Coastguard Worker for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
134*9880d681SAndroid Build Coastguard Worker i != e; ++i) {
135*9880d681SAndroid Build Coastguard Worker // Found case matching a constant operand?
136*9880d681SAndroid Build Coastguard Worker if (i.getCaseValue() == CI) {
137*9880d681SAndroid Build Coastguard Worker TheOnlyDest = i.getCaseSuccessor();
138*9880d681SAndroid Build Coastguard Worker break;
139*9880d681SAndroid Build Coastguard Worker }
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard Worker // Check to see if this branch is going to the same place as the default
142*9880d681SAndroid Build Coastguard Worker // dest. If so, eliminate it as an explicit compare.
143*9880d681SAndroid Build Coastguard Worker if (i.getCaseSuccessor() == DefaultDest) {
144*9880d681SAndroid Build Coastguard Worker MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
145*9880d681SAndroid Build Coastguard Worker unsigned NCases = SI->getNumCases();
146*9880d681SAndroid Build Coastguard Worker // Fold the case metadata into the default if there will be any branches
147*9880d681SAndroid Build Coastguard Worker // left, unless the metadata doesn't match the switch.
148*9880d681SAndroid Build Coastguard Worker if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
149*9880d681SAndroid Build Coastguard Worker // Collect branch weights into a vector.
150*9880d681SAndroid Build Coastguard Worker SmallVector<uint32_t, 8> Weights;
151*9880d681SAndroid Build Coastguard Worker for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
152*9880d681SAndroid Build Coastguard Worker ++MD_i) {
153*9880d681SAndroid Build Coastguard Worker auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
154*9880d681SAndroid Build Coastguard Worker Weights.push_back(CI->getValue().getZExtValue());
155*9880d681SAndroid Build Coastguard Worker }
156*9880d681SAndroid Build Coastguard Worker // Merge weight of this case to the default weight.
157*9880d681SAndroid Build Coastguard Worker unsigned idx = i.getCaseIndex();
158*9880d681SAndroid Build Coastguard Worker Weights[0] += Weights[idx+1];
159*9880d681SAndroid Build Coastguard Worker // Remove weight for this case.
160*9880d681SAndroid Build Coastguard Worker std::swap(Weights[idx+1], Weights.back());
161*9880d681SAndroid Build Coastguard Worker Weights.pop_back();
162*9880d681SAndroid Build Coastguard Worker SI->setMetadata(LLVMContext::MD_prof,
163*9880d681SAndroid Build Coastguard Worker MDBuilder(BB->getContext()).
164*9880d681SAndroid Build Coastguard Worker createBranchWeights(Weights));
165*9880d681SAndroid Build Coastguard Worker }
166*9880d681SAndroid Build Coastguard Worker // Remove this entry.
167*9880d681SAndroid Build Coastguard Worker DefaultDest->removePredecessor(SI->getParent());
168*9880d681SAndroid Build Coastguard Worker SI->removeCase(i);
169*9880d681SAndroid Build Coastguard Worker --i; --e;
170*9880d681SAndroid Build Coastguard Worker continue;
171*9880d681SAndroid Build Coastguard Worker }
172*9880d681SAndroid Build Coastguard Worker
173*9880d681SAndroid Build Coastguard Worker // Otherwise, check to see if the switch only branches to one destination.
174*9880d681SAndroid Build Coastguard Worker // We do this by reseting "TheOnlyDest" to null when we find two non-equal
175*9880d681SAndroid Build Coastguard Worker // destinations.
176*9880d681SAndroid Build Coastguard Worker if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
177*9880d681SAndroid Build Coastguard Worker }
178*9880d681SAndroid Build Coastguard Worker
179*9880d681SAndroid Build Coastguard Worker if (CI && !TheOnlyDest) {
180*9880d681SAndroid Build Coastguard Worker // Branching on a constant, but not any of the cases, go to the default
181*9880d681SAndroid Build Coastguard Worker // successor.
182*9880d681SAndroid Build Coastguard Worker TheOnlyDest = SI->getDefaultDest();
183*9880d681SAndroid Build Coastguard Worker }
184*9880d681SAndroid Build Coastguard Worker
185*9880d681SAndroid Build Coastguard Worker // If we found a single destination that we can fold the switch into, do so
186*9880d681SAndroid Build Coastguard Worker // now.
187*9880d681SAndroid Build Coastguard Worker if (TheOnlyDest) {
188*9880d681SAndroid Build Coastguard Worker // Insert the new branch.
189*9880d681SAndroid Build Coastguard Worker Builder.CreateBr(TheOnlyDest);
190*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = SI->getParent();
191*9880d681SAndroid Build Coastguard Worker
192*9880d681SAndroid Build Coastguard Worker // Remove entries from PHI nodes which we no longer branch to...
193*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Succ : SI->successors()) {
194*9880d681SAndroid Build Coastguard Worker // Found case matching a constant operand?
195*9880d681SAndroid Build Coastguard Worker if (Succ == TheOnlyDest)
196*9880d681SAndroid Build Coastguard Worker TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
197*9880d681SAndroid Build Coastguard Worker else
198*9880d681SAndroid Build Coastguard Worker Succ->removePredecessor(BB);
199*9880d681SAndroid Build Coastguard Worker }
200*9880d681SAndroid Build Coastguard Worker
201*9880d681SAndroid Build Coastguard Worker // Delete the old switch.
202*9880d681SAndroid Build Coastguard Worker Value *Cond = SI->getCondition();
203*9880d681SAndroid Build Coastguard Worker SI->eraseFromParent();
204*9880d681SAndroid Build Coastguard Worker if (DeleteDeadConditions)
205*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
206*9880d681SAndroid Build Coastguard Worker return true;
207*9880d681SAndroid Build Coastguard Worker }
208*9880d681SAndroid Build Coastguard Worker
209*9880d681SAndroid Build Coastguard Worker if (SI->getNumCases() == 1) {
210*9880d681SAndroid Build Coastguard Worker // Otherwise, we can fold this switch into a conditional branch
211*9880d681SAndroid Build Coastguard Worker // instruction if it has only one non-default destination.
212*9880d681SAndroid Build Coastguard Worker SwitchInst::CaseIt FirstCase = SI->case_begin();
213*9880d681SAndroid Build Coastguard Worker Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
214*9880d681SAndroid Build Coastguard Worker FirstCase.getCaseValue(), "cond");
215*9880d681SAndroid Build Coastguard Worker
216*9880d681SAndroid Build Coastguard Worker // Insert the new branch.
217*9880d681SAndroid Build Coastguard Worker BranchInst *NewBr = Builder.CreateCondBr(Cond,
218*9880d681SAndroid Build Coastguard Worker FirstCase.getCaseSuccessor(),
219*9880d681SAndroid Build Coastguard Worker SI->getDefaultDest());
220*9880d681SAndroid Build Coastguard Worker MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
221*9880d681SAndroid Build Coastguard Worker if (MD && MD->getNumOperands() == 3) {
222*9880d681SAndroid Build Coastguard Worker ConstantInt *SICase =
223*9880d681SAndroid Build Coastguard Worker mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
224*9880d681SAndroid Build Coastguard Worker ConstantInt *SIDef =
225*9880d681SAndroid Build Coastguard Worker mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
226*9880d681SAndroid Build Coastguard Worker assert(SICase && SIDef);
227*9880d681SAndroid Build Coastguard Worker // The TrueWeight should be the weight for the single case of SI.
228*9880d681SAndroid Build Coastguard Worker NewBr->setMetadata(LLVMContext::MD_prof,
229*9880d681SAndroid Build Coastguard Worker MDBuilder(BB->getContext()).
230*9880d681SAndroid Build Coastguard Worker createBranchWeights(SICase->getValue().getZExtValue(),
231*9880d681SAndroid Build Coastguard Worker SIDef->getValue().getZExtValue()));
232*9880d681SAndroid Build Coastguard Worker }
233*9880d681SAndroid Build Coastguard Worker
234*9880d681SAndroid Build Coastguard Worker // Update make.implicit metadata to the newly-created conditional branch.
235*9880d681SAndroid Build Coastguard Worker MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
236*9880d681SAndroid Build Coastguard Worker if (MakeImplicitMD)
237*9880d681SAndroid Build Coastguard Worker NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
238*9880d681SAndroid Build Coastguard Worker
239*9880d681SAndroid Build Coastguard Worker // Delete the old switch.
240*9880d681SAndroid Build Coastguard Worker SI->eraseFromParent();
241*9880d681SAndroid Build Coastguard Worker return true;
242*9880d681SAndroid Build Coastguard Worker }
243*9880d681SAndroid Build Coastguard Worker return false;
244*9880d681SAndroid Build Coastguard Worker }
245*9880d681SAndroid Build Coastguard Worker
246*9880d681SAndroid Build Coastguard Worker if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
247*9880d681SAndroid Build Coastguard Worker // indirectbr blockaddress(@F, @BB) -> br label @BB
248*9880d681SAndroid Build Coastguard Worker if (BlockAddress *BA =
249*9880d681SAndroid Build Coastguard Worker dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
250*9880d681SAndroid Build Coastguard Worker BasicBlock *TheOnlyDest = BA->getBasicBlock();
251*9880d681SAndroid Build Coastguard Worker // Insert the new branch.
252*9880d681SAndroid Build Coastguard Worker Builder.CreateBr(TheOnlyDest);
253*9880d681SAndroid Build Coastguard Worker
254*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
255*9880d681SAndroid Build Coastguard Worker if (IBI->getDestination(i) == TheOnlyDest)
256*9880d681SAndroid Build Coastguard Worker TheOnlyDest = nullptr;
257*9880d681SAndroid Build Coastguard Worker else
258*9880d681SAndroid Build Coastguard Worker IBI->getDestination(i)->removePredecessor(IBI->getParent());
259*9880d681SAndroid Build Coastguard Worker }
260*9880d681SAndroid Build Coastguard Worker Value *Address = IBI->getAddress();
261*9880d681SAndroid Build Coastguard Worker IBI->eraseFromParent();
262*9880d681SAndroid Build Coastguard Worker if (DeleteDeadConditions)
263*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
264*9880d681SAndroid Build Coastguard Worker
265*9880d681SAndroid Build Coastguard Worker // If we didn't find our destination in the IBI successor list, then we
266*9880d681SAndroid Build Coastguard Worker // have undefined behavior. Replace the unconditional branch with an
267*9880d681SAndroid Build Coastguard Worker // 'unreachable' instruction.
268*9880d681SAndroid Build Coastguard Worker if (TheOnlyDest) {
269*9880d681SAndroid Build Coastguard Worker BB->getTerminator()->eraseFromParent();
270*9880d681SAndroid Build Coastguard Worker new UnreachableInst(BB->getContext(), BB);
271*9880d681SAndroid Build Coastguard Worker }
272*9880d681SAndroid Build Coastguard Worker
273*9880d681SAndroid Build Coastguard Worker return true;
274*9880d681SAndroid Build Coastguard Worker }
275*9880d681SAndroid Build Coastguard Worker }
276*9880d681SAndroid Build Coastguard Worker
277*9880d681SAndroid Build Coastguard Worker return false;
278*9880d681SAndroid Build Coastguard Worker }
279*9880d681SAndroid Build Coastguard Worker
280*9880d681SAndroid Build Coastguard Worker
281*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
282*9880d681SAndroid Build Coastguard Worker // Local dead code elimination.
283*9880d681SAndroid Build Coastguard Worker //
284*9880d681SAndroid Build Coastguard Worker
285*9880d681SAndroid Build Coastguard Worker /// isInstructionTriviallyDead - Return true if the result produced by the
286*9880d681SAndroid Build Coastguard Worker /// instruction is not used, and the instruction has no side effects.
287*9880d681SAndroid Build Coastguard Worker ///
isInstructionTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)288*9880d681SAndroid Build Coastguard Worker bool llvm::isInstructionTriviallyDead(Instruction *I,
289*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
290*9880d681SAndroid Build Coastguard Worker if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
291*9880d681SAndroid Build Coastguard Worker
292*9880d681SAndroid Build Coastguard Worker // We don't want the landingpad-like instructions removed by anything this
293*9880d681SAndroid Build Coastguard Worker // general.
294*9880d681SAndroid Build Coastguard Worker if (I->isEHPad())
295*9880d681SAndroid Build Coastguard Worker return false;
296*9880d681SAndroid Build Coastguard Worker
297*9880d681SAndroid Build Coastguard Worker // We don't want debug info removed by anything this general, unless
298*9880d681SAndroid Build Coastguard Worker // debug info is empty.
299*9880d681SAndroid Build Coastguard Worker if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
300*9880d681SAndroid Build Coastguard Worker if (DDI->getAddress())
301*9880d681SAndroid Build Coastguard Worker return false;
302*9880d681SAndroid Build Coastguard Worker return true;
303*9880d681SAndroid Build Coastguard Worker }
304*9880d681SAndroid Build Coastguard Worker if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
305*9880d681SAndroid Build Coastguard Worker if (DVI->getValue())
306*9880d681SAndroid Build Coastguard Worker return false;
307*9880d681SAndroid Build Coastguard Worker return true;
308*9880d681SAndroid Build Coastguard Worker }
309*9880d681SAndroid Build Coastguard Worker
310*9880d681SAndroid Build Coastguard Worker if (!I->mayHaveSideEffects()) return true;
311*9880d681SAndroid Build Coastguard Worker
312*9880d681SAndroid Build Coastguard Worker // Special case intrinsics that "may have side effects" but can be deleted
313*9880d681SAndroid Build Coastguard Worker // when dead.
314*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
315*9880d681SAndroid Build Coastguard Worker // Safe to delete llvm.stacksave if dead.
316*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::stacksave)
317*9880d681SAndroid Build Coastguard Worker return true;
318*9880d681SAndroid Build Coastguard Worker
319*9880d681SAndroid Build Coastguard Worker // Lifetime intrinsics are dead when their right-hand is undef.
320*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
321*9880d681SAndroid Build Coastguard Worker II->getIntrinsicID() == Intrinsic::lifetime_end)
322*9880d681SAndroid Build Coastguard Worker return isa<UndefValue>(II->getArgOperand(1));
323*9880d681SAndroid Build Coastguard Worker
324*9880d681SAndroid Build Coastguard Worker // Assumptions are dead if their condition is trivially true. Guards on
325*9880d681SAndroid Build Coastguard Worker // true are operationally no-ops. In the future we can consider more
326*9880d681SAndroid Build Coastguard Worker // sophisticated tradeoffs for guards considering potential for check
327*9880d681SAndroid Build Coastguard Worker // widening, but for now we keep things simple.
328*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::assume ||
329*9880d681SAndroid Build Coastguard Worker II->getIntrinsicID() == Intrinsic::experimental_guard) {
330*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
331*9880d681SAndroid Build Coastguard Worker return !Cond->isZero();
332*9880d681SAndroid Build Coastguard Worker
333*9880d681SAndroid Build Coastguard Worker return false;
334*9880d681SAndroid Build Coastguard Worker }
335*9880d681SAndroid Build Coastguard Worker }
336*9880d681SAndroid Build Coastguard Worker
337*9880d681SAndroid Build Coastguard Worker if (isAllocLikeFn(I, TLI)) return true;
338*9880d681SAndroid Build Coastguard Worker
339*9880d681SAndroid Build Coastguard Worker if (CallInst *CI = isFreeCall(I, TLI))
340*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
341*9880d681SAndroid Build Coastguard Worker return C->isNullValue() || isa<UndefValue>(C);
342*9880d681SAndroid Build Coastguard Worker
343*9880d681SAndroid Build Coastguard Worker return false;
344*9880d681SAndroid Build Coastguard Worker }
345*9880d681SAndroid Build Coastguard Worker
346*9880d681SAndroid Build Coastguard Worker /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
347*9880d681SAndroid Build Coastguard Worker /// trivially dead instruction, delete it. If that makes any of its operands
348*9880d681SAndroid Build Coastguard Worker /// trivially dead, delete them too, recursively. Return true if any
349*9880d681SAndroid Build Coastguard Worker /// instructions were deleted.
350*9880d681SAndroid Build Coastguard Worker bool
RecursivelyDeleteTriviallyDeadInstructions(Value * V,const TargetLibraryInfo * TLI)351*9880d681SAndroid Build Coastguard Worker llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
352*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
353*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
354*9880d681SAndroid Build Coastguard Worker if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
355*9880d681SAndroid Build Coastguard Worker return false;
356*9880d681SAndroid Build Coastguard Worker
357*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction*, 16> DeadInsts;
358*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(I);
359*9880d681SAndroid Build Coastguard Worker
360*9880d681SAndroid Build Coastguard Worker do {
361*9880d681SAndroid Build Coastguard Worker I = DeadInsts.pop_back_val();
362*9880d681SAndroid Build Coastguard Worker
363*9880d681SAndroid Build Coastguard Worker // Null out all of the instruction's operands to see if any operand becomes
364*9880d681SAndroid Build Coastguard Worker // dead as we go.
365*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
366*9880d681SAndroid Build Coastguard Worker Value *OpV = I->getOperand(i);
367*9880d681SAndroid Build Coastguard Worker I->setOperand(i, nullptr);
368*9880d681SAndroid Build Coastguard Worker
369*9880d681SAndroid Build Coastguard Worker if (!OpV->use_empty()) continue;
370*9880d681SAndroid Build Coastguard Worker
371*9880d681SAndroid Build Coastguard Worker // If the operand is an instruction that became dead as we nulled out the
372*9880d681SAndroid Build Coastguard Worker // operand, and if it is 'trivially' dead, delete it in a future loop
373*9880d681SAndroid Build Coastguard Worker // iteration.
374*9880d681SAndroid Build Coastguard Worker if (Instruction *OpI = dyn_cast<Instruction>(OpV))
375*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(OpI, TLI))
376*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(OpI);
377*9880d681SAndroid Build Coastguard Worker }
378*9880d681SAndroid Build Coastguard Worker
379*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
380*9880d681SAndroid Build Coastguard Worker } while (!DeadInsts.empty());
381*9880d681SAndroid Build Coastguard Worker
382*9880d681SAndroid Build Coastguard Worker return true;
383*9880d681SAndroid Build Coastguard Worker }
384*9880d681SAndroid Build Coastguard Worker
385*9880d681SAndroid Build Coastguard Worker /// areAllUsesEqual - Check whether the uses of a value are all the same.
386*9880d681SAndroid Build Coastguard Worker /// This is similar to Instruction::hasOneUse() except this will also return
387*9880d681SAndroid Build Coastguard Worker /// true when there are no uses or multiple uses that all refer to the same
388*9880d681SAndroid Build Coastguard Worker /// value.
areAllUsesEqual(Instruction * I)389*9880d681SAndroid Build Coastguard Worker static bool areAllUsesEqual(Instruction *I) {
390*9880d681SAndroid Build Coastguard Worker Value::user_iterator UI = I->user_begin();
391*9880d681SAndroid Build Coastguard Worker Value::user_iterator UE = I->user_end();
392*9880d681SAndroid Build Coastguard Worker if (UI == UE)
393*9880d681SAndroid Build Coastguard Worker return true;
394*9880d681SAndroid Build Coastguard Worker
395*9880d681SAndroid Build Coastguard Worker User *TheUse = *UI;
396*9880d681SAndroid Build Coastguard Worker for (++UI; UI != UE; ++UI) {
397*9880d681SAndroid Build Coastguard Worker if (*UI != TheUse)
398*9880d681SAndroid Build Coastguard Worker return false;
399*9880d681SAndroid Build Coastguard Worker }
400*9880d681SAndroid Build Coastguard Worker return true;
401*9880d681SAndroid Build Coastguard Worker }
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
404*9880d681SAndroid Build Coastguard Worker /// dead PHI node, due to being a def-use chain of single-use nodes that
405*9880d681SAndroid Build Coastguard Worker /// either forms a cycle or is terminated by a trivially dead instruction,
406*9880d681SAndroid Build Coastguard Worker /// delete it. If that makes any of its operands trivially dead, delete them
407*9880d681SAndroid Build Coastguard Worker /// too, recursively. Return true if a change was made.
RecursivelyDeleteDeadPHINode(PHINode * PN,const TargetLibraryInfo * TLI)408*9880d681SAndroid Build Coastguard Worker bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
409*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
410*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Instruction*, 4> Visited;
411*9880d681SAndroid Build Coastguard Worker for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
412*9880d681SAndroid Build Coastguard Worker I = cast<Instruction>(*I->user_begin())) {
413*9880d681SAndroid Build Coastguard Worker if (I->use_empty())
414*9880d681SAndroid Build Coastguard Worker return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
415*9880d681SAndroid Build Coastguard Worker
416*9880d681SAndroid Build Coastguard Worker // If we find an instruction more than once, we're on a cycle that
417*9880d681SAndroid Build Coastguard Worker // won't prove fruitful.
418*9880d681SAndroid Build Coastguard Worker if (!Visited.insert(I).second) {
419*9880d681SAndroid Build Coastguard Worker // Break the cycle and delete the instruction and its operands.
420*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(UndefValue::get(I->getType()));
421*9880d681SAndroid Build Coastguard Worker (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
422*9880d681SAndroid Build Coastguard Worker return true;
423*9880d681SAndroid Build Coastguard Worker }
424*9880d681SAndroid Build Coastguard Worker }
425*9880d681SAndroid Build Coastguard Worker return false;
426*9880d681SAndroid Build Coastguard Worker }
427*9880d681SAndroid Build Coastguard Worker
428*9880d681SAndroid Build Coastguard Worker static bool
simplifyAndDCEInstruction(Instruction * I,SmallSetVector<Instruction *,16> & WorkList,const DataLayout & DL,const TargetLibraryInfo * TLI)429*9880d681SAndroid Build Coastguard Worker simplifyAndDCEInstruction(Instruction *I,
430*9880d681SAndroid Build Coastguard Worker SmallSetVector<Instruction *, 16> &WorkList,
431*9880d681SAndroid Build Coastguard Worker const DataLayout &DL,
432*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
433*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I, TLI)) {
434*9880d681SAndroid Build Coastguard Worker // Null out all of the instruction's operands to see if any operand becomes
435*9880d681SAndroid Build Coastguard Worker // dead as we go.
436*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
437*9880d681SAndroid Build Coastguard Worker Value *OpV = I->getOperand(i);
438*9880d681SAndroid Build Coastguard Worker I->setOperand(i, nullptr);
439*9880d681SAndroid Build Coastguard Worker
440*9880d681SAndroid Build Coastguard Worker if (!OpV->use_empty() || I == OpV)
441*9880d681SAndroid Build Coastguard Worker continue;
442*9880d681SAndroid Build Coastguard Worker
443*9880d681SAndroid Build Coastguard Worker // If the operand is an instruction that became dead as we nulled out the
444*9880d681SAndroid Build Coastguard Worker // operand, and if it is 'trivially' dead, delete it in a future loop
445*9880d681SAndroid Build Coastguard Worker // iteration.
446*9880d681SAndroid Build Coastguard Worker if (Instruction *OpI = dyn_cast<Instruction>(OpV))
447*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(OpI, TLI))
448*9880d681SAndroid Build Coastguard Worker WorkList.insert(OpI);
449*9880d681SAndroid Build Coastguard Worker }
450*9880d681SAndroid Build Coastguard Worker
451*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
452*9880d681SAndroid Build Coastguard Worker
453*9880d681SAndroid Build Coastguard Worker return true;
454*9880d681SAndroid Build Coastguard Worker }
455*9880d681SAndroid Build Coastguard Worker
456*9880d681SAndroid Build Coastguard Worker if (Value *SimpleV = SimplifyInstruction(I, DL)) {
457*9880d681SAndroid Build Coastguard Worker // Add the users to the worklist. CAREFUL: an instruction can use itself,
458*9880d681SAndroid Build Coastguard Worker // in the case of a phi node.
459*9880d681SAndroid Build Coastguard Worker for (User *U : I->users()) {
460*9880d681SAndroid Build Coastguard Worker if (U != I) {
461*9880d681SAndroid Build Coastguard Worker WorkList.insert(cast<Instruction>(U));
462*9880d681SAndroid Build Coastguard Worker }
463*9880d681SAndroid Build Coastguard Worker }
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard Worker // Replace the instruction with its simplified value.
466*9880d681SAndroid Build Coastguard Worker bool Changed = false;
467*9880d681SAndroid Build Coastguard Worker if (!I->use_empty()) {
468*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(SimpleV);
469*9880d681SAndroid Build Coastguard Worker Changed = true;
470*9880d681SAndroid Build Coastguard Worker }
471*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I, TLI)) {
472*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
473*9880d681SAndroid Build Coastguard Worker Changed = true;
474*9880d681SAndroid Build Coastguard Worker }
475*9880d681SAndroid Build Coastguard Worker return Changed;
476*9880d681SAndroid Build Coastguard Worker }
477*9880d681SAndroid Build Coastguard Worker return false;
478*9880d681SAndroid Build Coastguard Worker }
479*9880d681SAndroid Build Coastguard Worker
480*9880d681SAndroid Build Coastguard Worker /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
481*9880d681SAndroid Build Coastguard Worker /// simplify any instructions in it and recursively delete dead instructions.
482*9880d681SAndroid Build Coastguard Worker ///
483*9880d681SAndroid Build Coastguard Worker /// This returns true if it changed the code, note that it can delete
484*9880d681SAndroid Build Coastguard Worker /// instructions in other blocks as well in this block.
SimplifyInstructionsInBlock(BasicBlock * BB,const TargetLibraryInfo * TLI)485*9880d681SAndroid Build Coastguard Worker bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
486*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
487*9880d681SAndroid Build Coastguard Worker bool MadeChange = false;
488*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = BB->getModule()->getDataLayout();
489*9880d681SAndroid Build Coastguard Worker
490*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
491*9880d681SAndroid Build Coastguard Worker // In debug builds, ensure that the terminator of the block is never replaced
492*9880d681SAndroid Build Coastguard Worker // or deleted by these simplifications. The idea of simplification is that it
493*9880d681SAndroid Build Coastguard Worker // cannot introduce new instructions, and there is no way to replace the
494*9880d681SAndroid Build Coastguard Worker // terminator of a block without introducing a new instruction.
495*9880d681SAndroid Build Coastguard Worker AssertingVH<Instruction> TerminatorVH(&BB->back());
496*9880d681SAndroid Build Coastguard Worker #endif
497*9880d681SAndroid Build Coastguard Worker
498*9880d681SAndroid Build Coastguard Worker SmallSetVector<Instruction *, 16> WorkList;
499*9880d681SAndroid Build Coastguard Worker // Iterate over the original function, only adding insts to the worklist
500*9880d681SAndroid Build Coastguard Worker // if they actually need to be revisited. This avoids having to pre-init
501*9880d681SAndroid Build Coastguard Worker // the worklist with the entire function's worth of instructions.
502*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
503*9880d681SAndroid Build Coastguard Worker BI != E;) {
504*9880d681SAndroid Build Coastguard Worker assert(!BI->isTerminator());
505*9880d681SAndroid Build Coastguard Worker Instruction *I = &*BI;
506*9880d681SAndroid Build Coastguard Worker ++BI;
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard Worker // We're visiting this instruction now, so make sure it's not in the
509*9880d681SAndroid Build Coastguard Worker // worklist from an earlier visit.
510*9880d681SAndroid Build Coastguard Worker if (!WorkList.count(I))
511*9880d681SAndroid Build Coastguard Worker MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
512*9880d681SAndroid Build Coastguard Worker }
513*9880d681SAndroid Build Coastguard Worker
514*9880d681SAndroid Build Coastguard Worker while (!WorkList.empty()) {
515*9880d681SAndroid Build Coastguard Worker Instruction *I = WorkList.pop_back_val();
516*9880d681SAndroid Build Coastguard Worker MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
517*9880d681SAndroid Build Coastguard Worker }
518*9880d681SAndroid Build Coastguard Worker return MadeChange;
519*9880d681SAndroid Build Coastguard Worker }
520*9880d681SAndroid Build Coastguard Worker
521*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
522*9880d681SAndroid Build Coastguard Worker // Control Flow Graph Restructuring.
523*9880d681SAndroid Build Coastguard Worker //
524*9880d681SAndroid Build Coastguard Worker
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
527*9880d681SAndroid Build Coastguard Worker /// method is called when we're about to delete Pred as a predecessor of BB. If
528*9880d681SAndroid Build Coastguard Worker /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
529*9880d681SAndroid Build Coastguard Worker ///
530*9880d681SAndroid Build Coastguard Worker /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
531*9880d681SAndroid Build Coastguard Worker /// nodes that collapse into identity values. For example, if we have:
532*9880d681SAndroid Build Coastguard Worker /// x = phi(1, 0, 0, 0)
533*9880d681SAndroid Build Coastguard Worker /// y = and x, z
534*9880d681SAndroid Build Coastguard Worker ///
535*9880d681SAndroid Build Coastguard Worker /// .. and delete the predecessor corresponding to the '1', this will attempt to
536*9880d681SAndroid Build Coastguard Worker /// recursively fold the and to 0.
RemovePredecessorAndSimplify(BasicBlock * BB,BasicBlock * Pred)537*9880d681SAndroid Build Coastguard Worker void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
538*9880d681SAndroid Build Coastguard Worker // This only adjusts blocks with PHI nodes.
539*9880d681SAndroid Build Coastguard Worker if (!isa<PHINode>(BB->begin()))
540*9880d681SAndroid Build Coastguard Worker return;
541*9880d681SAndroid Build Coastguard Worker
542*9880d681SAndroid Build Coastguard Worker // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
543*9880d681SAndroid Build Coastguard Worker // them down. This will leave us with single entry phi nodes and other phis
544*9880d681SAndroid Build Coastguard Worker // that can be removed.
545*9880d681SAndroid Build Coastguard Worker BB->removePredecessor(Pred, true);
546*9880d681SAndroid Build Coastguard Worker
547*9880d681SAndroid Build Coastguard Worker WeakVH PhiIt = &BB->front();
548*9880d681SAndroid Build Coastguard Worker while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
549*9880d681SAndroid Build Coastguard Worker PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
550*9880d681SAndroid Build Coastguard Worker Value *OldPhiIt = PhiIt;
551*9880d681SAndroid Build Coastguard Worker
552*9880d681SAndroid Build Coastguard Worker if (!recursivelySimplifyInstruction(PN))
553*9880d681SAndroid Build Coastguard Worker continue;
554*9880d681SAndroid Build Coastguard Worker
555*9880d681SAndroid Build Coastguard Worker // If recursive simplification ended up deleting the next PHI node we would
556*9880d681SAndroid Build Coastguard Worker // iterate to, then our iterator is invalid, restart scanning from the top
557*9880d681SAndroid Build Coastguard Worker // of the block.
558*9880d681SAndroid Build Coastguard Worker if (PhiIt != OldPhiIt) PhiIt = &BB->front();
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker }
561*9880d681SAndroid Build Coastguard Worker
562*9880d681SAndroid Build Coastguard Worker
563*9880d681SAndroid Build Coastguard Worker /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
564*9880d681SAndroid Build Coastguard Worker /// predecessor is known to have one successor (DestBB!). Eliminate the edge
565*9880d681SAndroid Build Coastguard Worker /// between them, moving the instructions in the predecessor into DestBB and
566*9880d681SAndroid Build Coastguard Worker /// deleting the predecessor block.
567*9880d681SAndroid Build Coastguard Worker ///
MergeBasicBlockIntoOnlyPred(BasicBlock * DestBB,DominatorTree * DT)568*9880d681SAndroid Build Coastguard Worker void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
569*9880d681SAndroid Build Coastguard Worker // If BB has single-entry PHI nodes, fold them.
570*9880d681SAndroid Build Coastguard Worker while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
571*9880d681SAndroid Build Coastguard Worker Value *NewVal = PN->getIncomingValue(0);
572*9880d681SAndroid Build Coastguard Worker // Replace self referencing PHI with undef, it must be dead.
573*9880d681SAndroid Build Coastguard Worker if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
574*9880d681SAndroid Build Coastguard Worker PN->replaceAllUsesWith(NewVal);
575*9880d681SAndroid Build Coastguard Worker PN->eraseFromParent();
576*9880d681SAndroid Build Coastguard Worker }
577*9880d681SAndroid Build Coastguard Worker
578*9880d681SAndroid Build Coastguard Worker BasicBlock *PredBB = DestBB->getSinglePredecessor();
579*9880d681SAndroid Build Coastguard Worker assert(PredBB && "Block doesn't have a single predecessor!");
580*9880d681SAndroid Build Coastguard Worker
581*9880d681SAndroid Build Coastguard Worker // Zap anything that took the address of DestBB. Not doing this will give the
582*9880d681SAndroid Build Coastguard Worker // address an invalid value.
583*9880d681SAndroid Build Coastguard Worker if (DestBB->hasAddressTaken()) {
584*9880d681SAndroid Build Coastguard Worker BlockAddress *BA = BlockAddress::get(DestBB);
585*9880d681SAndroid Build Coastguard Worker Constant *Replacement =
586*9880d681SAndroid Build Coastguard Worker ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
587*9880d681SAndroid Build Coastguard Worker BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
588*9880d681SAndroid Build Coastguard Worker BA->getType()));
589*9880d681SAndroid Build Coastguard Worker BA->destroyConstant();
590*9880d681SAndroid Build Coastguard Worker }
591*9880d681SAndroid Build Coastguard Worker
592*9880d681SAndroid Build Coastguard Worker // Anything that branched to PredBB now branches to DestBB.
593*9880d681SAndroid Build Coastguard Worker PredBB->replaceAllUsesWith(DestBB);
594*9880d681SAndroid Build Coastguard Worker
595*9880d681SAndroid Build Coastguard Worker // Splice all the instructions from PredBB to DestBB.
596*9880d681SAndroid Build Coastguard Worker PredBB->getTerminator()->eraseFromParent();
597*9880d681SAndroid Build Coastguard Worker DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
598*9880d681SAndroid Build Coastguard Worker
599*9880d681SAndroid Build Coastguard Worker // If the PredBB is the entry block of the function, move DestBB up to
600*9880d681SAndroid Build Coastguard Worker // become the entry block after we erase PredBB.
601*9880d681SAndroid Build Coastguard Worker if (PredBB == &DestBB->getParent()->getEntryBlock())
602*9880d681SAndroid Build Coastguard Worker DestBB->moveAfter(PredBB);
603*9880d681SAndroid Build Coastguard Worker
604*9880d681SAndroid Build Coastguard Worker if (DT) {
605*9880d681SAndroid Build Coastguard Worker BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
606*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(DestBB, PredBBIDom);
607*9880d681SAndroid Build Coastguard Worker DT->eraseNode(PredBB);
608*9880d681SAndroid Build Coastguard Worker }
609*9880d681SAndroid Build Coastguard Worker // Nuke BB.
610*9880d681SAndroid Build Coastguard Worker PredBB->eraseFromParent();
611*9880d681SAndroid Build Coastguard Worker }
612*9880d681SAndroid Build Coastguard Worker
613*9880d681SAndroid Build Coastguard Worker /// CanMergeValues - Return true if we can choose one of these values to use
614*9880d681SAndroid Build Coastguard Worker /// in place of the other. Note that we will always choose the non-undef
615*9880d681SAndroid Build Coastguard Worker /// value to keep.
CanMergeValues(Value * First,Value * Second)616*9880d681SAndroid Build Coastguard Worker static bool CanMergeValues(Value *First, Value *Second) {
617*9880d681SAndroid Build Coastguard Worker return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
618*9880d681SAndroid Build Coastguard Worker }
619*9880d681SAndroid Build Coastguard Worker
620*9880d681SAndroid Build Coastguard Worker /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
621*9880d681SAndroid Build Coastguard Worker /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
622*9880d681SAndroid Build Coastguard Worker ///
623*9880d681SAndroid Build Coastguard Worker /// Assumption: Succ is the single successor for BB.
624*9880d681SAndroid Build Coastguard Worker ///
CanPropagatePredecessorsForPHIs(BasicBlock * BB,BasicBlock * Succ)625*9880d681SAndroid Build Coastguard Worker static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
626*9880d681SAndroid Build Coastguard Worker assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
627*9880d681SAndroid Build Coastguard Worker
628*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
629*9880d681SAndroid Build Coastguard Worker << Succ->getName() << "\n");
630*9880d681SAndroid Build Coastguard Worker // Shortcut, if there is only a single predecessor it must be BB and merging
631*9880d681SAndroid Build Coastguard Worker // is always safe
632*9880d681SAndroid Build Coastguard Worker if (Succ->getSinglePredecessor()) return true;
633*9880d681SAndroid Build Coastguard Worker
634*9880d681SAndroid Build Coastguard Worker // Make a list of the predecessors of BB
635*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
636*9880d681SAndroid Build Coastguard Worker
637*9880d681SAndroid Build Coastguard Worker // Look at all the phi nodes in Succ, to see if they present a conflict when
638*9880d681SAndroid Build Coastguard Worker // merging these blocks
639*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
640*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I);
641*9880d681SAndroid Build Coastguard Worker
642*9880d681SAndroid Build Coastguard Worker // If the incoming value from BB is again a PHINode in
643*9880d681SAndroid Build Coastguard Worker // BB which has the same incoming value for *PI as PN does, we can
644*9880d681SAndroid Build Coastguard Worker // merge the phi nodes and then the blocks can still be merged
645*9880d681SAndroid Build Coastguard Worker PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
646*9880d681SAndroid Build Coastguard Worker if (BBPN && BBPN->getParent() == BB) {
647*9880d681SAndroid Build Coastguard Worker for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
648*9880d681SAndroid Build Coastguard Worker BasicBlock *IBB = PN->getIncomingBlock(PI);
649*9880d681SAndroid Build Coastguard Worker if (BBPreds.count(IBB) &&
650*9880d681SAndroid Build Coastguard Worker !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
651*9880d681SAndroid Build Coastguard Worker PN->getIncomingValue(PI))) {
652*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
653*9880d681SAndroid Build Coastguard Worker << Succ->getName() << " is conflicting with "
654*9880d681SAndroid Build Coastguard Worker << BBPN->getName() << " with regard to common predecessor "
655*9880d681SAndroid Build Coastguard Worker << IBB->getName() << "\n");
656*9880d681SAndroid Build Coastguard Worker return false;
657*9880d681SAndroid Build Coastguard Worker }
658*9880d681SAndroid Build Coastguard Worker }
659*9880d681SAndroid Build Coastguard Worker } else {
660*9880d681SAndroid Build Coastguard Worker Value* Val = PN->getIncomingValueForBlock(BB);
661*9880d681SAndroid Build Coastguard Worker for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
662*9880d681SAndroid Build Coastguard Worker // See if the incoming value for the common predecessor is equal to the
663*9880d681SAndroid Build Coastguard Worker // one for BB, in which case this phi node will not prevent the merging
664*9880d681SAndroid Build Coastguard Worker // of the block.
665*9880d681SAndroid Build Coastguard Worker BasicBlock *IBB = PN->getIncomingBlock(PI);
666*9880d681SAndroid Build Coastguard Worker if (BBPreds.count(IBB) &&
667*9880d681SAndroid Build Coastguard Worker !CanMergeValues(Val, PN->getIncomingValue(PI))) {
668*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
669*9880d681SAndroid Build Coastguard Worker << Succ->getName() << " is conflicting with regard to common "
670*9880d681SAndroid Build Coastguard Worker << "predecessor " << IBB->getName() << "\n");
671*9880d681SAndroid Build Coastguard Worker return false;
672*9880d681SAndroid Build Coastguard Worker }
673*9880d681SAndroid Build Coastguard Worker }
674*9880d681SAndroid Build Coastguard Worker }
675*9880d681SAndroid Build Coastguard Worker }
676*9880d681SAndroid Build Coastguard Worker
677*9880d681SAndroid Build Coastguard Worker return true;
678*9880d681SAndroid Build Coastguard Worker }
679*9880d681SAndroid Build Coastguard Worker
680*9880d681SAndroid Build Coastguard Worker typedef SmallVector<BasicBlock *, 16> PredBlockVector;
681*9880d681SAndroid Build Coastguard Worker typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
682*9880d681SAndroid Build Coastguard Worker
683*9880d681SAndroid Build Coastguard Worker /// \brief Determines the value to use as the phi node input for a block.
684*9880d681SAndroid Build Coastguard Worker ///
685*9880d681SAndroid Build Coastguard Worker /// Select between \p OldVal any value that we know flows from \p BB
686*9880d681SAndroid Build Coastguard Worker /// to a particular phi on the basis of which one (if either) is not
687*9880d681SAndroid Build Coastguard Worker /// undef. Update IncomingValues based on the selected value.
688*9880d681SAndroid Build Coastguard Worker ///
689*9880d681SAndroid Build Coastguard Worker /// \param OldVal The value we are considering selecting.
690*9880d681SAndroid Build Coastguard Worker /// \param BB The block that the value flows in from.
691*9880d681SAndroid Build Coastguard Worker /// \param IncomingValues A map from block-to-value for other phi inputs
692*9880d681SAndroid Build Coastguard Worker /// that we have examined.
693*9880d681SAndroid Build Coastguard Worker ///
694*9880d681SAndroid Build Coastguard Worker /// \returns the selected value.
selectIncomingValueForBlock(Value * OldVal,BasicBlock * BB,IncomingValueMap & IncomingValues)695*9880d681SAndroid Build Coastguard Worker static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
696*9880d681SAndroid Build Coastguard Worker IncomingValueMap &IncomingValues) {
697*9880d681SAndroid Build Coastguard Worker if (!isa<UndefValue>(OldVal)) {
698*9880d681SAndroid Build Coastguard Worker assert((!IncomingValues.count(BB) ||
699*9880d681SAndroid Build Coastguard Worker IncomingValues.find(BB)->second == OldVal) &&
700*9880d681SAndroid Build Coastguard Worker "Expected OldVal to match incoming value from BB!");
701*9880d681SAndroid Build Coastguard Worker
702*9880d681SAndroid Build Coastguard Worker IncomingValues.insert(std::make_pair(BB, OldVal));
703*9880d681SAndroid Build Coastguard Worker return OldVal;
704*9880d681SAndroid Build Coastguard Worker }
705*9880d681SAndroid Build Coastguard Worker
706*9880d681SAndroid Build Coastguard Worker IncomingValueMap::const_iterator It = IncomingValues.find(BB);
707*9880d681SAndroid Build Coastguard Worker if (It != IncomingValues.end()) return It->second;
708*9880d681SAndroid Build Coastguard Worker
709*9880d681SAndroid Build Coastguard Worker return OldVal;
710*9880d681SAndroid Build Coastguard Worker }
711*9880d681SAndroid Build Coastguard Worker
712*9880d681SAndroid Build Coastguard Worker /// \brief Create a map from block to value for the operands of a
713*9880d681SAndroid Build Coastguard Worker /// given phi.
714*9880d681SAndroid Build Coastguard Worker ///
715*9880d681SAndroid Build Coastguard Worker /// Create a map from block to value for each non-undef value flowing
716*9880d681SAndroid Build Coastguard Worker /// into \p PN.
717*9880d681SAndroid Build Coastguard Worker ///
718*9880d681SAndroid Build Coastguard Worker /// \param PN The phi we are collecting the map for.
719*9880d681SAndroid Build Coastguard Worker /// \param IncomingValues [out] The map from block to value for this phi.
gatherIncomingValuesToPhi(PHINode * PN,IncomingValueMap & IncomingValues)720*9880d681SAndroid Build Coastguard Worker static void gatherIncomingValuesToPhi(PHINode *PN,
721*9880d681SAndroid Build Coastguard Worker IncomingValueMap &IncomingValues) {
722*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
723*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = PN->getIncomingBlock(i);
724*9880d681SAndroid Build Coastguard Worker Value *V = PN->getIncomingValue(i);
725*9880d681SAndroid Build Coastguard Worker
726*9880d681SAndroid Build Coastguard Worker if (!isa<UndefValue>(V))
727*9880d681SAndroid Build Coastguard Worker IncomingValues.insert(std::make_pair(BB, V));
728*9880d681SAndroid Build Coastguard Worker }
729*9880d681SAndroid Build Coastguard Worker }
730*9880d681SAndroid Build Coastguard Worker
731*9880d681SAndroid Build Coastguard Worker /// \brief Replace the incoming undef values to a phi with the values
732*9880d681SAndroid Build Coastguard Worker /// from a block-to-value map.
733*9880d681SAndroid Build Coastguard Worker ///
734*9880d681SAndroid Build Coastguard Worker /// \param PN The phi we are replacing the undefs in.
735*9880d681SAndroid Build Coastguard Worker /// \param IncomingValues A map from block to value.
replaceUndefValuesInPhi(PHINode * PN,const IncomingValueMap & IncomingValues)736*9880d681SAndroid Build Coastguard Worker static void replaceUndefValuesInPhi(PHINode *PN,
737*9880d681SAndroid Build Coastguard Worker const IncomingValueMap &IncomingValues) {
738*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
739*9880d681SAndroid Build Coastguard Worker Value *V = PN->getIncomingValue(i);
740*9880d681SAndroid Build Coastguard Worker
741*9880d681SAndroid Build Coastguard Worker if (!isa<UndefValue>(V)) continue;
742*9880d681SAndroid Build Coastguard Worker
743*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = PN->getIncomingBlock(i);
744*9880d681SAndroid Build Coastguard Worker IncomingValueMap::const_iterator It = IncomingValues.find(BB);
745*9880d681SAndroid Build Coastguard Worker if (It == IncomingValues.end()) continue;
746*9880d681SAndroid Build Coastguard Worker
747*9880d681SAndroid Build Coastguard Worker PN->setIncomingValue(i, It->second);
748*9880d681SAndroid Build Coastguard Worker }
749*9880d681SAndroid Build Coastguard Worker }
750*9880d681SAndroid Build Coastguard Worker
751*9880d681SAndroid Build Coastguard Worker /// \brief Replace a value flowing from a block to a phi with
752*9880d681SAndroid Build Coastguard Worker /// potentially multiple instances of that value flowing from the
753*9880d681SAndroid Build Coastguard Worker /// block's predecessors to the phi.
754*9880d681SAndroid Build Coastguard Worker ///
755*9880d681SAndroid Build Coastguard Worker /// \param BB The block with the value flowing into the phi.
756*9880d681SAndroid Build Coastguard Worker /// \param BBPreds The predecessors of BB.
757*9880d681SAndroid Build Coastguard Worker /// \param PN The phi that we are updating.
redirectValuesFromPredecessorsToPhi(BasicBlock * BB,const PredBlockVector & BBPreds,PHINode * PN)758*9880d681SAndroid Build Coastguard Worker static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
759*9880d681SAndroid Build Coastguard Worker const PredBlockVector &BBPreds,
760*9880d681SAndroid Build Coastguard Worker PHINode *PN) {
761*9880d681SAndroid Build Coastguard Worker Value *OldVal = PN->removeIncomingValue(BB, false);
762*9880d681SAndroid Build Coastguard Worker assert(OldVal && "No entry in PHI for Pred BB!");
763*9880d681SAndroid Build Coastguard Worker
764*9880d681SAndroid Build Coastguard Worker IncomingValueMap IncomingValues;
765*9880d681SAndroid Build Coastguard Worker
766*9880d681SAndroid Build Coastguard Worker // We are merging two blocks - BB, and the block containing PN - and
767*9880d681SAndroid Build Coastguard Worker // as a result we need to redirect edges from the predecessors of BB
768*9880d681SAndroid Build Coastguard Worker // to go to the block containing PN, and update PN
769*9880d681SAndroid Build Coastguard Worker // accordingly. Since we allow merging blocks in the case where the
770*9880d681SAndroid Build Coastguard Worker // predecessor and successor blocks both share some predecessors,
771*9880d681SAndroid Build Coastguard Worker // and where some of those common predecessors might have undef
772*9880d681SAndroid Build Coastguard Worker // values flowing into PN, we want to rewrite those values to be
773*9880d681SAndroid Build Coastguard Worker // consistent with the non-undef values.
774*9880d681SAndroid Build Coastguard Worker
775*9880d681SAndroid Build Coastguard Worker gatherIncomingValuesToPhi(PN, IncomingValues);
776*9880d681SAndroid Build Coastguard Worker
777*9880d681SAndroid Build Coastguard Worker // If this incoming value is one of the PHI nodes in BB, the new entries
778*9880d681SAndroid Build Coastguard Worker // in the PHI node are the entries from the old PHI.
779*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
780*9880d681SAndroid Build Coastguard Worker PHINode *OldValPN = cast<PHINode>(OldVal);
781*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
782*9880d681SAndroid Build Coastguard Worker // Note that, since we are merging phi nodes and BB and Succ might
783*9880d681SAndroid Build Coastguard Worker // have common predecessors, we could end up with a phi node with
784*9880d681SAndroid Build Coastguard Worker // identical incoming branches. This will be cleaned up later (and
785*9880d681SAndroid Build Coastguard Worker // will trigger asserts if we try to clean it up now, without also
786*9880d681SAndroid Build Coastguard Worker // simplifying the corresponding conditional branch).
787*9880d681SAndroid Build Coastguard Worker BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
788*9880d681SAndroid Build Coastguard Worker Value *PredVal = OldValPN->getIncomingValue(i);
789*9880d681SAndroid Build Coastguard Worker Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
790*9880d681SAndroid Build Coastguard Worker IncomingValues);
791*9880d681SAndroid Build Coastguard Worker
792*9880d681SAndroid Build Coastguard Worker // And add a new incoming value for this predecessor for the
793*9880d681SAndroid Build Coastguard Worker // newly retargeted branch.
794*9880d681SAndroid Build Coastguard Worker PN->addIncoming(Selected, PredBB);
795*9880d681SAndroid Build Coastguard Worker }
796*9880d681SAndroid Build Coastguard Worker } else {
797*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
798*9880d681SAndroid Build Coastguard Worker // Update existing incoming values in PN for this
799*9880d681SAndroid Build Coastguard Worker // predecessor of BB.
800*9880d681SAndroid Build Coastguard Worker BasicBlock *PredBB = BBPreds[i];
801*9880d681SAndroid Build Coastguard Worker Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
802*9880d681SAndroid Build Coastguard Worker IncomingValues);
803*9880d681SAndroid Build Coastguard Worker
804*9880d681SAndroid Build Coastguard Worker // And add a new incoming value for this predecessor for the
805*9880d681SAndroid Build Coastguard Worker // newly retargeted branch.
806*9880d681SAndroid Build Coastguard Worker PN->addIncoming(Selected, PredBB);
807*9880d681SAndroid Build Coastguard Worker }
808*9880d681SAndroid Build Coastguard Worker }
809*9880d681SAndroid Build Coastguard Worker
810*9880d681SAndroid Build Coastguard Worker replaceUndefValuesInPhi(PN, IncomingValues);
811*9880d681SAndroid Build Coastguard Worker }
812*9880d681SAndroid Build Coastguard Worker
813*9880d681SAndroid Build Coastguard Worker /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
814*9880d681SAndroid Build Coastguard Worker /// unconditional branch, and contains no instructions other than PHI nodes,
815*9880d681SAndroid Build Coastguard Worker /// potential side-effect free intrinsics and the branch. If possible,
816*9880d681SAndroid Build Coastguard Worker /// eliminate BB by rewriting all the predecessors to branch to the successor
817*9880d681SAndroid Build Coastguard Worker /// block and return true. If we can't transform, return false.
TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock * BB)818*9880d681SAndroid Build Coastguard Worker bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
819*9880d681SAndroid Build Coastguard Worker assert(BB != &BB->getParent()->getEntryBlock() &&
820*9880d681SAndroid Build Coastguard Worker "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
821*9880d681SAndroid Build Coastguard Worker
822*9880d681SAndroid Build Coastguard Worker // We can't eliminate infinite loops.
823*9880d681SAndroid Build Coastguard Worker BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
824*9880d681SAndroid Build Coastguard Worker if (BB == Succ) return false;
825*9880d681SAndroid Build Coastguard Worker
826*9880d681SAndroid Build Coastguard Worker // Check to see if merging these blocks would cause conflicts for any of the
827*9880d681SAndroid Build Coastguard Worker // phi nodes in BB or Succ. If not, we can safely merge.
828*9880d681SAndroid Build Coastguard Worker if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
829*9880d681SAndroid Build Coastguard Worker
830*9880d681SAndroid Build Coastguard Worker // Check for cases where Succ has multiple predecessors and a PHI node in BB
831*9880d681SAndroid Build Coastguard Worker // has uses which will not disappear when the PHI nodes are merged. It is
832*9880d681SAndroid Build Coastguard Worker // possible to handle such cases, but difficult: it requires checking whether
833*9880d681SAndroid Build Coastguard Worker // BB dominates Succ, which is non-trivial to calculate in the case where
834*9880d681SAndroid Build Coastguard Worker // Succ has multiple predecessors. Also, it requires checking whether
835*9880d681SAndroid Build Coastguard Worker // constructing the necessary self-referential PHI node doesn't introduce any
836*9880d681SAndroid Build Coastguard Worker // conflicts; this isn't too difficult, but the previous code for doing this
837*9880d681SAndroid Build Coastguard Worker // was incorrect.
838*9880d681SAndroid Build Coastguard Worker //
839*9880d681SAndroid Build Coastguard Worker // Note that if this check finds a live use, BB dominates Succ, so BB is
840*9880d681SAndroid Build Coastguard Worker // something like a loop pre-header (or rarely, a part of an irreducible CFG);
841*9880d681SAndroid Build Coastguard Worker // folding the branch isn't profitable in that case anyway.
842*9880d681SAndroid Build Coastguard Worker if (!Succ->getSinglePredecessor()) {
843*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BBI = BB->begin();
844*9880d681SAndroid Build Coastguard Worker while (isa<PHINode>(*BBI)) {
845*9880d681SAndroid Build Coastguard Worker for (Use &U : BBI->uses()) {
846*9880d681SAndroid Build Coastguard Worker if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
847*9880d681SAndroid Build Coastguard Worker if (PN->getIncomingBlock(U) != BB)
848*9880d681SAndroid Build Coastguard Worker return false;
849*9880d681SAndroid Build Coastguard Worker } else {
850*9880d681SAndroid Build Coastguard Worker return false;
851*9880d681SAndroid Build Coastguard Worker }
852*9880d681SAndroid Build Coastguard Worker }
853*9880d681SAndroid Build Coastguard Worker ++BBI;
854*9880d681SAndroid Build Coastguard Worker }
855*9880d681SAndroid Build Coastguard Worker }
856*9880d681SAndroid Build Coastguard Worker
857*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
858*9880d681SAndroid Build Coastguard Worker
859*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(Succ->begin())) {
860*9880d681SAndroid Build Coastguard Worker // If there is more than one pred of succ, and there are PHI nodes in
861*9880d681SAndroid Build Coastguard Worker // the successor, then we need to add incoming edges for the PHI nodes
862*9880d681SAndroid Build Coastguard Worker //
863*9880d681SAndroid Build Coastguard Worker const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
864*9880d681SAndroid Build Coastguard Worker
865*9880d681SAndroid Build Coastguard Worker // Loop over all of the PHI nodes in the successor of BB.
866*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
867*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I);
868*9880d681SAndroid Build Coastguard Worker
869*9880d681SAndroid Build Coastguard Worker redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
870*9880d681SAndroid Build Coastguard Worker }
871*9880d681SAndroid Build Coastguard Worker }
872*9880d681SAndroid Build Coastguard Worker
873*9880d681SAndroid Build Coastguard Worker if (Succ->getSinglePredecessor()) {
874*9880d681SAndroid Build Coastguard Worker // BB is the only predecessor of Succ, so Succ will end up with exactly
875*9880d681SAndroid Build Coastguard Worker // the same predecessors BB had.
876*9880d681SAndroid Build Coastguard Worker
877*9880d681SAndroid Build Coastguard Worker // Copy over any phi, debug or lifetime instruction.
878*9880d681SAndroid Build Coastguard Worker BB->getTerminator()->eraseFromParent();
879*9880d681SAndroid Build Coastguard Worker Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
880*9880d681SAndroid Build Coastguard Worker BB->getInstList());
881*9880d681SAndroid Build Coastguard Worker } else {
882*9880d681SAndroid Build Coastguard Worker while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
883*9880d681SAndroid Build Coastguard Worker // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
884*9880d681SAndroid Build Coastguard Worker assert(PN->use_empty() && "There shouldn't be any uses here!");
885*9880d681SAndroid Build Coastguard Worker PN->eraseFromParent();
886*9880d681SAndroid Build Coastguard Worker }
887*9880d681SAndroid Build Coastguard Worker }
888*9880d681SAndroid Build Coastguard Worker
889*9880d681SAndroid Build Coastguard Worker // Everything that jumped to BB now goes to Succ.
890*9880d681SAndroid Build Coastguard Worker BB->replaceAllUsesWith(Succ);
891*9880d681SAndroid Build Coastguard Worker if (!Succ->hasName()) Succ->takeName(BB);
892*9880d681SAndroid Build Coastguard Worker BB->eraseFromParent(); // Delete the old basic block.
893*9880d681SAndroid Build Coastguard Worker return true;
894*9880d681SAndroid Build Coastguard Worker }
895*9880d681SAndroid Build Coastguard Worker
896*9880d681SAndroid Build Coastguard Worker /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
897*9880d681SAndroid Build Coastguard Worker /// nodes in this block. This doesn't try to be clever about PHI nodes
898*9880d681SAndroid Build Coastguard Worker /// which differ only in the order of the incoming values, but instcombine
899*9880d681SAndroid Build Coastguard Worker /// orders them so it usually won't matter.
900*9880d681SAndroid Build Coastguard Worker ///
EliminateDuplicatePHINodes(BasicBlock * BB)901*9880d681SAndroid Build Coastguard Worker bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
902*9880d681SAndroid Build Coastguard Worker // This implementation doesn't currently consider undef operands
903*9880d681SAndroid Build Coastguard Worker // specially. Theoretically, two phis which are identical except for
904*9880d681SAndroid Build Coastguard Worker // one having an undef where the other doesn't could be collapsed.
905*9880d681SAndroid Build Coastguard Worker
906*9880d681SAndroid Build Coastguard Worker struct PHIDenseMapInfo {
907*9880d681SAndroid Build Coastguard Worker static PHINode *getEmptyKey() {
908*9880d681SAndroid Build Coastguard Worker return DenseMapInfo<PHINode *>::getEmptyKey();
909*9880d681SAndroid Build Coastguard Worker }
910*9880d681SAndroid Build Coastguard Worker static PHINode *getTombstoneKey() {
911*9880d681SAndroid Build Coastguard Worker return DenseMapInfo<PHINode *>::getTombstoneKey();
912*9880d681SAndroid Build Coastguard Worker }
913*9880d681SAndroid Build Coastguard Worker static unsigned getHashValue(PHINode *PN) {
914*9880d681SAndroid Build Coastguard Worker // Compute a hash value on the operands. Instcombine will likely have
915*9880d681SAndroid Build Coastguard Worker // sorted them, which helps expose duplicates, but we have to check all
916*9880d681SAndroid Build Coastguard Worker // the operands to be safe in case instcombine hasn't run.
917*9880d681SAndroid Build Coastguard Worker return static_cast<unsigned>(hash_combine(
918*9880d681SAndroid Build Coastguard Worker hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
919*9880d681SAndroid Build Coastguard Worker hash_combine_range(PN->block_begin(), PN->block_end())));
920*9880d681SAndroid Build Coastguard Worker }
921*9880d681SAndroid Build Coastguard Worker static bool isEqual(PHINode *LHS, PHINode *RHS) {
922*9880d681SAndroid Build Coastguard Worker if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
923*9880d681SAndroid Build Coastguard Worker RHS == getEmptyKey() || RHS == getTombstoneKey())
924*9880d681SAndroid Build Coastguard Worker return LHS == RHS;
925*9880d681SAndroid Build Coastguard Worker return LHS->isIdenticalTo(RHS);
926*9880d681SAndroid Build Coastguard Worker }
927*9880d681SAndroid Build Coastguard Worker };
928*9880d681SAndroid Build Coastguard Worker
929*9880d681SAndroid Build Coastguard Worker // Set of unique PHINodes.
930*9880d681SAndroid Build Coastguard Worker DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
931*9880d681SAndroid Build Coastguard Worker
932*9880d681SAndroid Build Coastguard Worker // Examine each PHI.
933*9880d681SAndroid Build Coastguard Worker bool Changed = false;
934*9880d681SAndroid Build Coastguard Worker for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
935*9880d681SAndroid Build Coastguard Worker auto Inserted = PHISet.insert(PN);
936*9880d681SAndroid Build Coastguard Worker if (!Inserted.second) {
937*9880d681SAndroid Build Coastguard Worker // A duplicate. Replace this PHI with its duplicate.
938*9880d681SAndroid Build Coastguard Worker PN->replaceAllUsesWith(*Inserted.first);
939*9880d681SAndroid Build Coastguard Worker PN->eraseFromParent();
940*9880d681SAndroid Build Coastguard Worker Changed = true;
941*9880d681SAndroid Build Coastguard Worker
942*9880d681SAndroid Build Coastguard Worker // The RAUW can change PHIs that we already visited. Start over from the
943*9880d681SAndroid Build Coastguard Worker // beginning.
944*9880d681SAndroid Build Coastguard Worker PHISet.clear();
945*9880d681SAndroid Build Coastguard Worker I = BB->begin();
946*9880d681SAndroid Build Coastguard Worker }
947*9880d681SAndroid Build Coastguard Worker }
948*9880d681SAndroid Build Coastguard Worker
949*9880d681SAndroid Build Coastguard Worker return Changed;
950*9880d681SAndroid Build Coastguard Worker }
951*9880d681SAndroid Build Coastguard Worker
952*9880d681SAndroid Build Coastguard Worker /// enforceKnownAlignment - If the specified pointer points to an object that
953*9880d681SAndroid Build Coastguard Worker /// we control, modify the object's alignment to PrefAlign. This isn't
954*9880d681SAndroid Build Coastguard Worker /// often possible though. If alignment is important, a more reliable approach
955*9880d681SAndroid Build Coastguard Worker /// is to simply align all global variables and allocation instructions to
956*9880d681SAndroid Build Coastguard Worker /// their preferred alignment from the beginning.
957*9880d681SAndroid Build Coastguard Worker ///
enforceKnownAlignment(Value * V,unsigned Align,unsigned PrefAlign,const DataLayout & DL)958*9880d681SAndroid Build Coastguard Worker static unsigned enforceKnownAlignment(Value *V, unsigned Align,
959*9880d681SAndroid Build Coastguard Worker unsigned PrefAlign,
960*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
961*9880d681SAndroid Build Coastguard Worker assert(PrefAlign > Align);
962*9880d681SAndroid Build Coastguard Worker
963*9880d681SAndroid Build Coastguard Worker V = V->stripPointerCasts();
964*9880d681SAndroid Build Coastguard Worker
965*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
966*9880d681SAndroid Build Coastguard Worker // TODO: ideally, computeKnownBits ought to have used
967*9880d681SAndroid Build Coastguard Worker // AllocaInst::getAlignment() in its computation already, making
968*9880d681SAndroid Build Coastguard Worker // the below max redundant. But, as it turns out,
969*9880d681SAndroid Build Coastguard Worker // stripPointerCasts recurses through infinite layers of bitcasts,
970*9880d681SAndroid Build Coastguard Worker // while computeKnownBits is not allowed to traverse more than 6
971*9880d681SAndroid Build Coastguard Worker // levels.
972*9880d681SAndroid Build Coastguard Worker Align = std::max(AI->getAlignment(), Align);
973*9880d681SAndroid Build Coastguard Worker if (PrefAlign <= Align)
974*9880d681SAndroid Build Coastguard Worker return Align;
975*9880d681SAndroid Build Coastguard Worker
976*9880d681SAndroid Build Coastguard Worker // If the preferred alignment is greater than the natural stack alignment
977*9880d681SAndroid Build Coastguard Worker // then don't round up. This avoids dynamic stack realignment.
978*9880d681SAndroid Build Coastguard Worker if (DL.exceedsNaturalStackAlignment(PrefAlign))
979*9880d681SAndroid Build Coastguard Worker return Align;
980*9880d681SAndroid Build Coastguard Worker AI->setAlignment(PrefAlign);
981*9880d681SAndroid Build Coastguard Worker return PrefAlign;
982*9880d681SAndroid Build Coastguard Worker }
983*9880d681SAndroid Build Coastguard Worker
984*9880d681SAndroid Build Coastguard Worker if (auto *GO = dyn_cast<GlobalObject>(V)) {
985*9880d681SAndroid Build Coastguard Worker // TODO: as above, this shouldn't be necessary.
986*9880d681SAndroid Build Coastguard Worker Align = std::max(GO->getAlignment(), Align);
987*9880d681SAndroid Build Coastguard Worker if (PrefAlign <= Align)
988*9880d681SAndroid Build Coastguard Worker return Align;
989*9880d681SAndroid Build Coastguard Worker
990*9880d681SAndroid Build Coastguard Worker // If there is a large requested alignment and we can, bump up the alignment
991*9880d681SAndroid Build Coastguard Worker // of the global. If the memory we set aside for the global may not be the
992*9880d681SAndroid Build Coastguard Worker // memory used by the final program then it is impossible for us to reliably
993*9880d681SAndroid Build Coastguard Worker // enforce the preferred alignment.
994*9880d681SAndroid Build Coastguard Worker if (!GO->canIncreaseAlignment())
995*9880d681SAndroid Build Coastguard Worker return Align;
996*9880d681SAndroid Build Coastguard Worker
997*9880d681SAndroid Build Coastguard Worker GO->setAlignment(PrefAlign);
998*9880d681SAndroid Build Coastguard Worker return PrefAlign;
999*9880d681SAndroid Build Coastguard Worker }
1000*9880d681SAndroid Build Coastguard Worker
1001*9880d681SAndroid Build Coastguard Worker return Align;
1002*9880d681SAndroid Build Coastguard Worker }
1003*9880d681SAndroid Build Coastguard Worker
1004*9880d681SAndroid Build Coastguard Worker /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
1005*9880d681SAndroid Build Coastguard Worker /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
1006*9880d681SAndroid Build Coastguard Worker /// and it is more than the alignment of the ultimate object, see if we can
1007*9880d681SAndroid Build Coastguard Worker /// increase the alignment of the ultimate object, making this check succeed.
getOrEnforceKnownAlignment(Value * V,unsigned PrefAlign,const DataLayout & DL,const Instruction * CxtI,AssumptionCache * AC,const DominatorTree * DT)1008*9880d681SAndroid Build Coastguard Worker unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
1009*9880d681SAndroid Build Coastguard Worker const DataLayout &DL,
1010*9880d681SAndroid Build Coastguard Worker const Instruction *CxtI,
1011*9880d681SAndroid Build Coastguard Worker AssumptionCache *AC,
1012*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT) {
1013*9880d681SAndroid Build Coastguard Worker assert(V->getType()->isPointerTy() &&
1014*9880d681SAndroid Build Coastguard Worker "getOrEnforceKnownAlignment expects a pointer!");
1015*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
1016*9880d681SAndroid Build Coastguard Worker
1017*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1018*9880d681SAndroid Build Coastguard Worker computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
1019*9880d681SAndroid Build Coastguard Worker unsigned TrailZ = KnownZero.countTrailingOnes();
1020*9880d681SAndroid Build Coastguard Worker
1021*9880d681SAndroid Build Coastguard Worker // Avoid trouble with ridiculously large TrailZ values, such as
1022*9880d681SAndroid Build Coastguard Worker // those computed from a null pointer.
1023*9880d681SAndroid Build Coastguard Worker TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
1024*9880d681SAndroid Build Coastguard Worker
1025*9880d681SAndroid Build Coastguard Worker unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
1026*9880d681SAndroid Build Coastguard Worker
1027*9880d681SAndroid Build Coastguard Worker // LLVM doesn't support alignments larger than this currently.
1028*9880d681SAndroid Build Coastguard Worker Align = std::min(Align, +Value::MaximumAlignment);
1029*9880d681SAndroid Build Coastguard Worker
1030*9880d681SAndroid Build Coastguard Worker if (PrefAlign > Align)
1031*9880d681SAndroid Build Coastguard Worker Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
1032*9880d681SAndroid Build Coastguard Worker
1033*9880d681SAndroid Build Coastguard Worker // We don't need to make any adjustment.
1034*9880d681SAndroid Build Coastguard Worker return Align;
1035*9880d681SAndroid Build Coastguard Worker }
1036*9880d681SAndroid Build Coastguard Worker
1037*9880d681SAndroid Build Coastguard Worker ///===---------------------------------------------------------------------===//
1038*9880d681SAndroid Build Coastguard Worker /// Dbg Intrinsic utilities
1039*9880d681SAndroid Build Coastguard Worker ///
1040*9880d681SAndroid Build Coastguard Worker
1041*9880d681SAndroid Build Coastguard Worker /// See if there is a dbg.value intrinsic for DIVar before I.
LdStHasDebugValue(DILocalVariable * DIVar,DIExpression * DIExpr,Instruction * I)1042*9880d681SAndroid Build Coastguard Worker static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1043*9880d681SAndroid Build Coastguard Worker Instruction *I) {
1044*9880d681SAndroid Build Coastguard Worker // Since we can't guarantee that the original dbg.declare instrinsic
1045*9880d681SAndroid Build Coastguard Worker // is removed by LowerDbgDeclare(), we need to make sure that we are
1046*9880d681SAndroid Build Coastguard Worker // not inserting the same dbg.value intrinsic over and over.
1047*9880d681SAndroid Build Coastguard Worker llvm::BasicBlock::InstListType::iterator PrevI(I);
1048*9880d681SAndroid Build Coastguard Worker if (PrevI != I->getParent()->getInstList().begin()) {
1049*9880d681SAndroid Build Coastguard Worker --PrevI;
1050*9880d681SAndroid Build Coastguard Worker if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1051*9880d681SAndroid Build Coastguard Worker if (DVI->getValue() == I->getOperand(0) &&
1052*9880d681SAndroid Build Coastguard Worker DVI->getOffset() == 0 &&
1053*9880d681SAndroid Build Coastguard Worker DVI->getVariable() == DIVar &&
1054*9880d681SAndroid Build Coastguard Worker DVI->getExpression() == DIExpr)
1055*9880d681SAndroid Build Coastguard Worker return true;
1056*9880d681SAndroid Build Coastguard Worker }
1057*9880d681SAndroid Build Coastguard Worker return false;
1058*9880d681SAndroid Build Coastguard Worker }
1059*9880d681SAndroid Build Coastguard Worker
1060*9880d681SAndroid Build Coastguard Worker /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1061*9880d681SAndroid Build Coastguard Worker /// that has an associated llvm.dbg.decl intrinsic.
ConvertDebugDeclareToDebugValue(DbgDeclareInst * DDI,StoreInst * SI,DIBuilder & Builder)1062*9880d681SAndroid Build Coastguard Worker bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1063*9880d681SAndroid Build Coastguard Worker StoreInst *SI, DIBuilder &Builder) {
1064*9880d681SAndroid Build Coastguard Worker auto *DIVar = DDI->getVariable();
1065*9880d681SAndroid Build Coastguard Worker auto *DIExpr = DDI->getExpression();
1066*9880d681SAndroid Build Coastguard Worker assert(DIVar && "Missing variable");
1067*9880d681SAndroid Build Coastguard Worker
1068*9880d681SAndroid Build Coastguard Worker // If an argument is zero extended then use argument directly. The ZExt
1069*9880d681SAndroid Build Coastguard Worker // may be zapped by an optimization pass in future.
1070*9880d681SAndroid Build Coastguard Worker Argument *ExtendedArg = nullptr;
1071*9880d681SAndroid Build Coastguard Worker if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1072*9880d681SAndroid Build Coastguard Worker ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1073*9880d681SAndroid Build Coastguard Worker if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1074*9880d681SAndroid Build Coastguard Worker ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1075*9880d681SAndroid Build Coastguard Worker if (ExtendedArg) {
1076*9880d681SAndroid Build Coastguard Worker // We're now only describing a subset of the variable. The piece we're
1077*9880d681SAndroid Build Coastguard Worker // describing will always be smaller than the variable size, because
1078*9880d681SAndroid Build Coastguard Worker // VariableSize == Size of Alloca described by DDI. Since SI stores
1079*9880d681SAndroid Build Coastguard Worker // to the alloca described by DDI, if it's first operand is an extend,
1080*9880d681SAndroid Build Coastguard Worker // we're guaranteed that before extension, the value was narrower than
1081*9880d681SAndroid Build Coastguard Worker // the size of the alloca, hence the size of the described variable.
1082*9880d681SAndroid Build Coastguard Worker SmallVector<uint64_t, 3> Ops;
1083*9880d681SAndroid Build Coastguard Worker unsigned PieceOffset = 0;
1084*9880d681SAndroid Build Coastguard Worker // If this already is a bit piece, we drop the bit piece from the expression
1085*9880d681SAndroid Build Coastguard Worker // and record the offset.
1086*9880d681SAndroid Build Coastguard Worker if (DIExpr->isBitPiece()) {
1087*9880d681SAndroid Build Coastguard Worker Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
1088*9880d681SAndroid Build Coastguard Worker PieceOffset = DIExpr->getBitPieceOffset();
1089*9880d681SAndroid Build Coastguard Worker } else {
1090*9880d681SAndroid Build Coastguard Worker Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
1091*9880d681SAndroid Build Coastguard Worker }
1092*9880d681SAndroid Build Coastguard Worker Ops.push_back(dwarf::DW_OP_bit_piece);
1093*9880d681SAndroid Build Coastguard Worker Ops.push_back(PieceOffset); // Offset
1094*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = DDI->getModule()->getDataLayout();
1095*9880d681SAndroid Build Coastguard Worker Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); // Size
1096*9880d681SAndroid Build Coastguard Worker auto NewDIExpr = Builder.createExpression(Ops);
1097*9880d681SAndroid Build Coastguard Worker if (!LdStHasDebugValue(DIVar, NewDIExpr, SI))
1098*9880d681SAndroid Build Coastguard Worker Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr,
1099*9880d681SAndroid Build Coastguard Worker DDI->getDebugLoc(), SI);
1100*9880d681SAndroid Build Coastguard Worker } else if (!LdStHasDebugValue(DIVar, DIExpr, SI))
1101*9880d681SAndroid Build Coastguard Worker Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
1102*9880d681SAndroid Build Coastguard Worker DDI->getDebugLoc(), SI);
1103*9880d681SAndroid Build Coastguard Worker return true;
1104*9880d681SAndroid Build Coastguard Worker }
1105*9880d681SAndroid Build Coastguard Worker
1106*9880d681SAndroid Build Coastguard Worker /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1107*9880d681SAndroid Build Coastguard Worker /// that has an associated llvm.dbg.decl intrinsic.
ConvertDebugDeclareToDebugValue(DbgDeclareInst * DDI,LoadInst * LI,DIBuilder & Builder)1108*9880d681SAndroid Build Coastguard Worker bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1109*9880d681SAndroid Build Coastguard Worker LoadInst *LI, DIBuilder &Builder) {
1110*9880d681SAndroid Build Coastguard Worker auto *DIVar = DDI->getVariable();
1111*9880d681SAndroid Build Coastguard Worker auto *DIExpr = DDI->getExpression();
1112*9880d681SAndroid Build Coastguard Worker assert(DIVar && "Missing variable");
1113*9880d681SAndroid Build Coastguard Worker
1114*9880d681SAndroid Build Coastguard Worker if (LdStHasDebugValue(DIVar, DIExpr, LI))
1115*9880d681SAndroid Build Coastguard Worker return true;
1116*9880d681SAndroid Build Coastguard Worker
1117*9880d681SAndroid Build Coastguard Worker // We are now tracking the loaded value instead of the address. In the
1118*9880d681SAndroid Build Coastguard Worker // future if multi-location support is added to the IR, it might be
1119*9880d681SAndroid Build Coastguard Worker // preferable to keep tracking both the loaded value and the original
1120*9880d681SAndroid Build Coastguard Worker // address in case the alloca can not be elided.
1121*9880d681SAndroid Build Coastguard Worker Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1122*9880d681SAndroid Build Coastguard Worker LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
1123*9880d681SAndroid Build Coastguard Worker DbgValue->insertAfter(LI);
1124*9880d681SAndroid Build Coastguard Worker return true;
1125*9880d681SAndroid Build Coastguard Worker }
1126*9880d681SAndroid Build Coastguard Worker
1127*9880d681SAndroid Build Coastguard Worker /// Determine whether this alloca is either a VLA or an array.
isArray(AllocaInst * AI)1128*9880d681SAndroid Build Coastguard Worker static bool isArray(AllocaInst *AI) {
1129*9880d681SAndroid Build Coastguard Worker return AI->isArrayAllocation() ||
1130*9880d681SAndroid Build Coastguard Worker AI->getType()->getElementType()->isArrayTy();
1131*9880d681SAndroid Build Coastguard Worker }
1132*9880d681SAndroid Build Coastguard Worker
1133*9880d681SAndroid Build Coastguard Worker /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1134*9880d681SAndroid Build Coastguard Worker /// of llvm.dbg.value intrinsics.
LowerDbgDeclare(Function & F)1135*9880d681SAndroid Build Coastguard Worker bool llvm::LowerDbgDeclare(Function &F) {
1136*9880d681SAndroid Build Coastguard Worker DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1137*9880d681SAndroid Build Coastguard Worker SmallVector<DbgDeclareInst *, 4> Dbgs;
1138*9880d681SAndroid Build Coastguard Worker for (auto &FI : F)
1139*9880d681SAndroid Build Coastguard Worker for (Instruction &BI : FI)
1140*9880d681SAndroid Build Coastguard Worker if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1141*9880d681SAndroid Build Coastguard Worker Dbgs.push_back(DDI);
1142*9880d681SAndroid Build Coastguard Worker
1143*9880d681SAndroid Build Coastguard Worker if (Dbgs.empty())
1144*9880d681SAndroid Build Coastguard Worker return false;
1145*9880d681SAndroid Build Coastguard Worker
1146*9880d681SAndroid Build Coastguard Worker for (auto &I : Dbgs) {
1147*9880d681SAndroid Build Coastguard Worker DbgDeclareInst *DDI = I;
1148*9880d681SAndroid Build Coastguard Worker AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1149*9880d681SAndroid Build Coastguard Worker // If this is an alloca for a scalar variable, insert a dbg.value
1150*9880d681SAndroid Build Coastguard Worker // at each load and store to the alloca and erase the dbg.declare.
1151*9880d681SAndroid Build Coastguard Worker // The dbg.values allow tracking a variable even if it is not
1152*9880d681SAndroid Build Coastguard Worker // stored on the stack, while the dbg.declare can only describe
1153*9880d681SAndroid Build Coastguard Worker // the stack slot (and at a lexical-scope granularity). Later
1154*9880d681SAndroid Build Coastguard Worker // passes will attempt to elide the stack slot.
1155*9880d681SAndroid Build Coastguard Worker if (AI && !isArray(AI)) {
1156*9880d681SAndroid Build Coastguard Worker for (auto &AIUse : AI->uses()) {
1157*9880d681SAndroid Build Coastguard Worker User *U = AIUse.getUser();
1158*9880d681SAndroid Build Coastguard Worker if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1159*9880d681SAndroid Build Coastguard Worker if (AIUse.getOperandNo() == 1)
1160*9880d681SAndroid Build Coastguard Worker ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1161*9880d681SAndroid Build Coastguard Worker } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1162*9880d681SAndroid Build Coastguard Worker ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1163*9880d681SAndroid Build Coastguard Worker } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1164*9880d681SAndroid Build Coastguard Worker // This is a call by-value or some other instruction that
1165*9880d681SAndroid Build Coastguard Worker // takes a pointer to the variable. Insert a *value*
1166*9880d681SAndroid Build Coastguard Worker // intrinsic that describes the alloca.
1167*9880d681SAndroid Build Coastguard Worker SmallVector<uint64_t, 1> NewDIExpr;
1168*9880d681SAndroid Build Coastguard Worker auto *DIExpr = DDI->getExpression();
1169*9880d681SAndroid Build Coastguard Worker NewDIExpr.push_back(dwarf::DW_OP_deref);
1170*9880d681SAndroid Build Coastguard Worker NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1171*9880d681SAndroid Build Coastguard Worker DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
1172*9880d681SAndroid Build Coastguard Worker DIB.createExpression(NewDIExpr),
1173*9880d681SAndroid Build Coastguard Worker DDI->getDebugLoc(), CI);
1174*9880d681SAndroid Build Coastguard Worker }
1175*9880d681SAndroid Build Coastguard Worker }
1176*9880d681SAndroid Build Coastguard Worker DDI->eraseFromParent();
1177*9880d681SAndroid Build Coastguard Worker }
1178*9880d681SAndroid Build Coastguard Worker }
1179*9880d681SAndroid Build Coastguard Worker return true;
1180*9880d681SAndroid Build Coastguard Worker }
1181*9880d681SAndroid Build Coastguard Worker
1182*9880d681SAndroid Build Coastguard Worker /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1183*9880d681SAndroid Build Coastguard Worker /// alloca 'V', if any.
FindAllocaDbgDeclare(Value * V)1184*9880d681SAndroid Build Coastguard Worker DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1185*9880d681SAndroid Build Coastguard Worker if (auto *L = LocalAsMetadata::getIfExists(V))
1186*9880d681SAndroid Build Coastguard Worker if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1187*9880d681SAndroid Build Coastguard Worker for (User *U : MDV->users())
1188*9880d681SAndroid Build Coastguard Worker if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1189*9880d681SAndroid Build Coastguard Worker return DDI;
1190*9880d681SAndroid Build Coastguard Worker
1191*9880d681SAndroid Build Coastguard Worker return nullptr;
1192*9880d681SAndroid Build Coastguard Worker }
1193*9880d681SAndroid Build Coastguard Worker
DIExprAddDeref(SmallVectorImpl<uint64_t> & Expr)1194*9880d681SAndroid Build Coastguard Worker static void DIExprAddDeref(SmallVectorImpl<uint64_t> &Expr) {
1195*9880d681SAndroid Build Coastguard Worker Expr.push_back(dwarf::DW_OP_deref);
1196*9880d681SAndroid Build Coastguard Worker }
1197*9880d681SAndroid Build Coastguard Worker
DIExprAddOffset(SmallVectorImpl<uint64_t> & Expr,int Offset)1198*9880d681SAndroid Build Coastguard Worker static void DIExprAddOffset(SmallVectorImpl<uint64_t> &Expr, int Offset) {
1199*9880d681SAndroid Build Coastguard Worker if (Offset > 0) {
1200*9880d681SAndroid Build Coastguard Worker Expr.push_back(dwarf::DW_OP_plus);
1201*9880d681SAndroid Build Coastguard Worker Expr.push_back(Offset);
1202*9880d681SAndroid Build Coastguard Worker } else if (Offset < 0) {
1203*9880d681SAndroid Build Coastguard Worker Expr.push_back(dwarf::DW_OP_minus);
1204*9880d681SAndroid Build Coastguard Worker Expr.push_back(-Offset);
1205*9880d681SAndroid Build Coastguard Worker }
1206*9880d681SAndroid Build Coastguard Worker }
1207*9880d681SAndroid Build Coastguard Worker
BuildReplacementDIExpr(DIBuilder & Builder,DIExpression * DIExpr,bool Deref,int Offset)1208*9880d681SAndroid Build Coastguard Worker static DIExpression *BuildReplacementDIExpr(DIBuilder &Builder,
1209*9880d681SAndroid Build Coastguard Worker DIExpression *DIExpr, bool Deref,
1210*9880d681SAndroid Build Coastguard Worker int Offset) {
1211*9880d681SAndroid Build Coastguard Worker if (!Deref && !Offset)
1212*9880d681SAndroid Build Coastguard Worker return DIExpr;
1213*9880d681SAndroid Build Coastguard Worker // Create a copy of the original DIDescriptor for user variable, prepending
1214*9880d681SAndroid Build Coastguard Worker // "deref" operation to a list of address elements, as new llvm.dbg.declare
1215*9880d681SAndroid Build Coastguard Worker // will take a value storing address of the memory for variable, not
1216*9880d681SAndroid Build Coastguard Worker // alloca itself.
1217*9880d681SAndroid Build Coastguard Worker SmallVector<uint64_t, 4> NewDIExpr;
1218*9880d681SAndroid Build Coastguard Worker if (Deref)
1219*9880d681SAndroid Build Coastguard Worker DIExprAddDeref(NewDIExpr);
1220*9880d681SAndroid Build Coastguard Worker DIExprAddOffset(NewDIExpr, Offset);
1221*9880d681SAndroid Build Coastguard Worker if (DIExpr)
1222*9880d681SAndroid Build Coastguard Worker NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1223*9880d681SAndroid Build Coastguard Worker return Builder.createExpression(NewDIExpr);
1224*9880d681SAndroid Build Coastguard Worker }
1225*9880d681SAndroid Build Coastguard Worker
replaceDbgDeclare(Value * Address,Value * NewAddress,Instruction * InsertBefore,DIBuilder & Builder,bool Deref,int Offset)1226*9880d681SAndroid Build Coastguard Worker bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1227*9880d681SAndroid Build Coastguard Worker Instruction *InsertBefore, DIBuilder &Builder,
1228*9880d681SAndroid Build Coastguard Worker bool Deref, int Offset) {
1229*9880d681SAndroid Build Coastguard Worker DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
1230*9880d681SAndroid Build Coastguard Worker if (!DDI)
1231*9880d681SAndroid Build Coastguard Worker return false;
1232*9880d681SAndroid Build Coastguard Worker DebugLoc Loc = DDI->getDebugLoc();
1233*9880d681SAndroid Build Coastguard Worker auto *DIVar = DDI->getVariable();
1234*9880d681SAndroid Build Coastguard Worker auto *DIExpr = DDI->getExpression();
1235*9880d681SAndroid Build Coastguard Worker assert(DIVar && "Missing variable");
1236*9880d681SAndroid Build Coastguard Worker
1237*9880d681SAndroid Build Coastguard Worker DIExpr = BuildReplacementDIExpr(Builder, DIExpr, Deref, Offset);
1238*9880d681SAndroid Build Coastguard Worker
1239*9880d681SAndroid Build Coastguard Worker // Insert llvm.dbg.declare immediately after the original alloca, and remove
1240*9880d681SAndroid Build Coastguard Worker // old llvm.dbg.declare.
1241*9880d681SAndroid Build Coastguard Worker Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1242*9880d681SAndroid Build Coastguard Worker DDI->eraseFromParent();
1243*9880d681SAndroid Build Coastguard Worker return true;
1244*9880d681SAndroid Build Coastguard Worker }
1245*9880d681SAndroid Build Coastguard Worker
replaceDbgDeclareForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,bool Deref,int Offset)1246*9880d681SAndroid Build Coastguard Worker bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1247*9880d681SAndroid Build Coastguard Worker DIBuilder &Builder, bool Deref, int Offset) {
1248*9880d681SAndroid Build Coastguard Worker return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1249*9880d681SAndroid Build Coastguard Worker Deref, Offset);
1250*9880d681SAndroid Build Coastguard Worker }
1251*9880d681SAndroid Build Coastguard Worker
replaceOneDbgValueForAlloca(DbgValueInst * DVI,Value * NewAddress,DIBuilder & Builder,int Offset)1252*9880d681SAndroid Build Coastguard Worker static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1253*9880d681SAndroid Build Coastguard Worker DIBuilder &Builder, int Offset) {
1254*9880d681SAndroid Build Coastguard Worker DebugLoc Loc = DVI->getDebugLoc();
1255*9880d681SAndroid Build Coastguard Worker auto *DIVar = DVI->getVariable();
1256*9880d681SAndroid Build Coastguard Worker auto *DIExpr = DVI->getExpression();
1257*9880d681SAndroid Build Coastguard Worker assert(DIVar && "Missing variable");
1258*9880d681SAndroid Build Coastguard Worker
1259*9880d681SAndroid Build Coastguard Worker // This is an alloca-based llvm.dbg.value. The first thing it should do with
1260*9880d681SAndroid Build Coastguard Worker // the alloca pointer is dereference it. Otherwise we don't know how to handle
1261*9880d681SAndroid Build Coastguard Worker // it and give up.
1262*9880d681SAndroid Build Coastguard Worker if (!DIExpr || DIExpr->getNumElements() < 1 ||
1263*9880d681SAndroid Build Coastguard Worker DIExpr->getElement(0) != dwarf::DW_OP_deref)
1264*9880d681SAndroid Build Coastguard Worker return;
1265*9880d681SAndroid Build Coastguard Worker
1266*9880d681SAndroid Build Coastguard Worker // Insert the offset immediately after the first deref.
1267*9880d681SAndroid Build Coastguard Worker // We could just change the offset argument of dbg.value, but it's unsigned...
1268*9880d681SAndroid Build Coastguard Worker if (Offset) {
1269*9880d681SAndroid Build Coastguard Worker SmallVector<uint64_t, 4> NewDIExpr;
1270*9880d681SAndroid Build Coastguard Worker DIExprAddDeref(NewDIExpr);
1271*9880d681SAndroid Build Coastguard Worker DIExprAddOffset(NewDIExpr, Offset);
1272*9880d681SAndroid Build Coastguard Worker NewDIExpr.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1273*9880d681SAndroid Build Coastguard Worker DIExpr = Builder.createExpression(NewDIExpr);
1274*9880d681SAndroid Build Coastguard Worker }
1275*9880d681SAndroid Build Coastguard Worker
1276*9880d681SAndroid Build Coastguard Worker Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr,
1277*9880d681SAndroid Build Coastguard Worker Loc, DVI);
1278*9880d681SAndroid Build Coastguard Worker DVI->eraseFromParent();
1279*9880d681SAndroid Build Coastguard Worker }
1280*9880d681SAndroid Build Coastguard Worker
replaceDbgValueForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,int Offset)1281*9880d681SAndroid Build Coastguard Worker void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1282*9880d681SAndroid Build Coastguard Worker DIBuilder &Builder, int Offset) {
1283*9880d681SAndroid Build Coastguard Worker if (auto *L = LocalAsMetadata::getIfExists(AI))
1284*9880d681SAndroid Build Coastguard Worker if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1285*9880d681SAndroid Build Coastguard Worker for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1286*9880d681SAndroid Build Coastguard Worker Use &U = *UI++;
1287*9880d681SAndroid Build Coastguard Worker if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1288*9880d681SAndroid Build Coastguard Worker replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1289*9880d681SAndroid Build Coastguard Worker }
1290*9880d681SAndroid Build Coastguard Worker }
1291*9880d681SAndroid Build Coastguard Worker
removeAllNonTerminatorAndEHPadInstructions(BasicBlock * BB)1292*9880d681SAndroid Build Coastguard Worker unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1293*9880d681SAndroid Build Coastguard Worker unsigned NumDeadInst = 0;
1294*9880d681SAndroid Build Coastguard Worker // Delete the instructions backwards, as it has a reduced likelihood of
1295*9880d681SAndroid Build Coastguard Worker // having to update as many def-use and use-def chains.
1296*9880d681SAndroid Build Coastguard Worker Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1297*9880d681SAndroid Build Coastguard Worker while (EndInst != &BB->front()) {
1298*9880d681SAndroid Build Coastguard Worker // Delete the next to last instruction.
1299*9880d681SAndroid Build Coastguard Worker Instruction *Inst = &*--EndInst->getIterator();
1300*9880d681SAndroid Build Coastguard Worker if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1301*9880d681SAndroid Build Coastguard Worker Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1302*9880d681SAndroid Build Coastguard Worker if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1303*9880d681SAndroid Build Coastguard Worker EndInst = Inst;
1304*9880d681SAndroid Build Coastguard Worker continue;
1305*9880d681SAndroid Build Coastguard Worker }
1306*9880d681SAndroid Build Coastguard Worker if (!isa<DbgInfoIntrinsic>(Inst))
1307*9880d681SAndroid Build Coastguard Worker ++NumDeadInst;
1308*9880d681SAndroid Build Coastguard Worker Inst->eraseFromParent();
1309*9880d681SAndroid Build Coastguard Worker }
1310*9880d681SAndroid Build Coastguard Worker return NumDeadInst;
1311*9880d681SAndroid Build Coastguard Worker }
1312*9880d681SAndroid Build Coastguard Worker
changeToUnreachable(Instruction * I,bool UseLLVMTrap)1313*9880d681SAndroid Build Coastguard Worker unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
1314*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = I->getParent();
1315*9880d681SAndroid Build Coastguard Worker // Loop over all of the successors, removing BB's entry from any PHI
1316*9880d681SAndroid Build Coastguard Worker // nodes.
1317*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Successor : successors(BB))
1318*9880d681SAndroid Build Coastguard Worker Successor->removePredecessor(BB);
1319*9880d681SAndroid Build Coastguard Worker
1320*9880d681SAndroid Build Coastguard Worker // Insert a call to llvm.trap right before this. This turns the undefined
1321*9880d681SAndroid Build Coastguard Worker // behavior into a hard fail instead of falling through into random code.
1322*9880d681SAndroid Build Coastguard Worker if (UseLLVMTrap) {
1323*9880d681SAndroid Build Coastguard Worker Function *TrapFn =
1324*9880d681SAndroid Build Coastguard Worker Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1325*9880d681SAndroid Build Coastguard Worker CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1326*9880d681SAndroid Build Coastguard Worker CallTrap->setDebugLoc(I->getDebugLoc());
1327*9880d681SAndroid Build Coastguard Worker }
1328*9880d681SAndroid Build Coastguard Worker new UnreachableInst(I->getContext(), I);
1329*9880d681SAndroid Build Coastguard Worker
1330*9880d681SAndroid Build Coastguard Worker // All instructions after this are dead.
1331*9880d681SAndroid Build Coastguard Worker unsigned NumInstrsRemoved = 0;
1332*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1333*9880d681SAndroid Build Coastguard Worker while (BBI != BBE) {
1334*9880d681SAndroid Build Coastguard Worker if (!BBI->use_empty())
1335*9880d681SAndroid Build Coastguard Worker BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1336*9880d681SAndroid Build Coastguard Worker BB->getInstList().erase(BBI++);
1337*9880d681SAndroid Build Coastguard Worker ++NumInstrsRemoved;
1338*9880d681SAndroid Build Coastguard Worker }
1339*9880d681SAndroid Build Coastguard Worker return NumInstrsRemoved;
1340*9880d681SAndroid Build Coastguard Worker }
1341*9880d681SAndroid Build Coastguard Worker
1342*9880d681SAndroid Build Coastguard Worker /// changeToCall - Convert the specified invoke into a normal call.
changeToCall(InvokeInst * II)1343*9880d681SAndroid Build Coastguard Worker static void changeToCall(InvokeInst *II) {
1344*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
1345*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
1346*9880d681SAndroid Build Coastguard Worker II->getOperandBundlesAsDefs(OpBundles);
1347*9880d681SAndroid Build Coastguard Worker CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1348*9880d681SAndroid Build Coastguard Worker "", II);
1349*9880d681SAndroid Build Coastguard Worker NewCall->takeName(II);
1350*9880d681SAndroid Build Coastguard Worker NewCall->setCallingConv(II->getCallingConv());
1351*9880d681SAndroid Build Coastguard Worker NewCall->setAttributes(II->getAttributes());
1352*9880d681SAndroid Build Coastguard Worker NewCall->setDebugLoc(II->getDebugLoc());
1353*9880d681SAndroid Build Coastguard Worker II->replaceAllUsesWith(NewCall);
1354*9880d681SAndroid Build Coastguard Worker
1355*9880d681SAndroid Build Coastguard Worker // Follow the call by a branch to the normal destination.
1356*9880d681SAndroid Build Coastguard Worker BranchInst::Create(II->getNormalDest(), II);
1357*9880d681SAndroid Build Coastguard Worker
1358*9880d681SAndroid Build Coastguard Worker // Update PHI nodes in the unwind destination
1359*9880d681SAndroid Build Coastguard Worker II->getUnwindDest()->removePredecessor(II->getParent());
1360*9880d681SAndroid Build Coastguard Worker II->eraseFromParent();
1361*9880d681SAndroid Build Coastguard Worker }
1362*9880d681SAndroid Build Coastguard Worker
markAliveBlocks(Function & F,SmallPtrSetImpl<BasicBlock * > & Reachable)1363*9880d681SAndroid Build Coastguard Worker static bool markAliveBlocks(Function &F,
1364*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<BasicBlock*> &Reachable) {
1365*9880d681SAndroid Build Coastguard Worker
1366*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock*, 128> Worklist;
1367*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = &F.front();
1368*9880d681SAndroid Build Coastguard Worker Worklist.push_back(BB);
1369*9880d681SAndroid Build Coastguard Worker Reachable.insert(BB);
1370*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1371*9880d681SAndroid Build Coastguard Worker do {
1372*9880d681SAndroid Build Coastguard Worker BB = Worklist.pop_back_val();
1373*9880d681SAndroid Build Coastguard Worker
1374*9880d681SAndroid Build Coastguard Worker // Do a quick scan of the basic block, turning any obviously unreachable
1375*9880d681SAndroid Build Coastguard Worker // instructions into LLVM unreachable insts. The instruction combining pass
1376*9880d681SAndroid Build Coastguard Worker // canonicalizes unreachable insts into stores to null or undef.
1377*9880d681SAndroid Build Coastguard Worker for (Instruction &I : *BB) {
1378*9880d681SAndroid Build Coastguard Worker // Assumptions that are known to be false are equivalent to unreachable.
1379*9880d681SAndroid Build Coastguard Worker // Also, if the condition is undefined, then we make the choice most
1380*9880d681SAndroid Build Coastguard Worker // beneficial to the optimizer, and choose that to also be unreachable.
1381*9880d681SAndroid Build Coastguard Worker if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
1382*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::assume) {
1383*9880d681SAndroid Build Coastguard Worker if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
1384*9880d681SAndroid Build Coastguard Worker // Don't insert a call to llvm.trap right before the unreachable.
1385*9880d681SAndroid Build Coastguard Worker changeToUnreachable(II, false);
1386*9880d681SAndroid Build Coastguard Worker Changed = true;
1387*9880d681SAndroid Build Coastguard Worker break;
1388*9880d681SAndroid Build Coastguard Worker }
1389*9880d681SAndroid Build Coastguard Worker }
1390*9880d681SAndroid Build Coastguard Worker
1391*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
1392*9880d681SAndroid Build Coastguard Worker // A call to the guard intrinsic bails out of the current compilation
1393*9880d681SAndroid Build Coastguard Worker // unit if the predicate passed to it is false. If the predicate is a
1394*9880d681SAndroid Build Coastguard Worker // constant false, then we know the guard will bail out of the current
1395*9880d681SAndroid Build Coastguard Worker // compile unconditionally, so all code following it is dead.
1396*9880d681SAndroid Build Coastguard Worker //
1397*9880d681SAndroid Build Coastguard Worker // Note: unlike in llvm.assume, it is not "obviously profitable" for
1398*9880d681SAndroid Build Coastguard Worker // guards to treat `undef` as `false` since a guard on `undef` can
1399*9880d681SAndroid Build Coastguard Worker // still be useful for widening.
1400*9880d681SAndroid Build Coastguard Worker if (match(II->getArgOperand(0), m_Zero()))
1401*9880d681SAndroid Build Coastguard Worker if (!isa<UnreachableInst>(II->getNextNode())) {
1402*9880d681SAndroid Build Coastguard Worker changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
1403*9880d681SAndroid Build Coastguard Worker Changed = true;
1404*9880d681SAndroid Build Coastguard Worker break;
1405*9880d681SAndroid Build Coastguard Worker }
1406*9880d681SAndroid Build Coastguard Worker }
1407*9880d681SAndroid Build Coastguard Worker }
1408*9880d681SAndroid Build Coastguard Worker
1409*9880d681SAndroid Build Coastguard Worker if (auto *CI = dyn_cast<CallInst>(&I)) {
1410*9880d681SAndroid Build Coastguard Worker Value *Callee = CI->getCalledValue();
1411*9880d681SAndroid Build Coastguard Worker if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1412*9880d681SAndroid Build Coastguard Worker changeToUnreachable(CI, /*UseLLVMTrap=*/false);
1413*9880d681SAndroid Build Coastguard Worker Changed = true;
1414*9880d681SAndroid Build Coastguard Worker break;
1415*9880d681SAndroid Build Coastguard Worker }
1416*9880d681SAndroid Build Coastguard Worker if (CI->doesNotReturn()) {
1417*9880d681SAndroid Build Coastguard Worker // If we found a call to a no-return function, insert an unreachable
1418*9880d681SAndroid Build Coastguard Worker // instruction after it. Make sure there isn't *already* one there
1419*9880d681SAndroid Build Coastguard Worker // though.
1420*9880d681SAndroid Build Coastguard Worker if (!isa<UnreachableInst>(CI->getNextNode())) {
1421*9880d681SAndroid Build Coastguard Worker // Don't insert a call to llvm.trap right before the unreachable.
1422*9880d681SAndroid Build Coastguard Worker changeToUnreachable(CI->getNextNode(), false);
1423*9880d681SAndroid Build Coastguard Worker Changed = true;
1424*9880d681SAndroid Build Coastguard Worker }
1425*9880d681SAndroid Build Coastguard Worker break;
1426*9880d681SAndroid Build Coastguard Worker }
1427*9880d681SAndroid Build Coastguard Worker }
1428*9880d681SAndroid Build Coastguard Worker
1429*9880d681SAndroid Build Coastguard Worker // Store to undef and store to null are undefined and used to signal that
1430*9880d681SAndroid Build Coastguard Worker // they should be changed to unreachable by passes that can't modify the
1431*9880d681SAndroid Build Coastguard Worker // CFG.
1432*9880d681SAndroid Build Coastguard Worker if (auto *SI = dyn_cast<StoreInst>(&I)) {
1433*9880d681SAndroid Build Coastguard Worker // Don't touch volatile stores.
1434*9880d681SAndroid Build Coastguard Worker if (SI->isVolatile()) continue;
1435*9880d681SAndroid Build Coastguard Worker
1436*9880d681SAndroid Build Coastguard Worker Value *Ptr = SI->getOperand(1);
1437*9880d681SAndroid Build Coastguard Worker
1438*9880d681SAndroid Build Coastguard Worker if (isa<UndefValue>(Ptr) ||
1439*9880d681SAndroid Build Coastguard Worker (isa<ConstantPointerNull>(Ptr) &&
1440*9880d681SAndroid Build Coastguard Worker SI->getPointerAddressSpace() == 0)) {
1441*9880d681SAndroid Build Coastguard Worker changeToUnreachable(SI, true);
1442*9880d681SAndroid Build Coastguard Worker Changed = true;
1443*9880d681SAndroid Build Coastguard Worker break;
1444*9880d681SAndroid Build Coastguard Worker }
1445*9880d681SAndroid Build Coastguard Worker }
1446*9880d681SAndroid Build Coastguard Worker }
1447*9880d681SAndroid Build Coastguard Worker
1448*9880d681SAndroid Build Coastguard Worker TerminatorInst *Terminator = BB->getTerminator();
1449*9880d681SAndroid Build Coastguard Worker if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1450*9880d681SAndroid Build Coastguard Worker // Turn invokes that call 'nounwind' functions into ordinary calls.
1451*9880d681SAndroid Build Coastguard Worker Value *Callee = II->getCalledValue();
1452*9880d681SAndroid Build Coastguard Worker if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1453*9880d681SAndroid Build Coastguard Worker changeToUnreachable(II, true);
1454*9880d681SAndroid Build Coastguard Worker Changed = true;
1455*9880d681SAndroid Build Coastguard Worker } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
1456*9880d681SAndroid Build Coastguard Worker if (II->use_empty() && II->onlyReadsMemory()) {
1457*9880d681SAndroid Build Coastguard Worker // jump to the normal destination branch.
1458*9880d681SAndroid Build Coastguard Worker BranchInst::Create(II->getNormalDest(), II);
1459*9880d681SAndroid Build Coastguard Worker II->getUnwindDest()->removePredecessor(II->getParent());
1460*9880d681SAndroid Build Coastguard Worker II->eraseFromParent();
1461*9880d681SAndroid Build Coastguard Worker } else
1462*9880d681SAndroid Build Coastguard Worker changeToCall(II);
1463*9880d681SAndroid Build Coastguard Worker Changed = true;
1464*9880d681SAndroid Build Coastguard Worker }
1465*9880d681SAndroid Build Coastguard Worker } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1466*9880d681SAndroid Build Coastguard Worker // Remove catchpads which cannot be reached.
1467*9880d681SAndroid Build Coastguard Worker struct CatchPadDenseMapInfo {
1468*9880d681SAndroid Build Coastguard Worker static CatchPadInst *getEmptyKey() {
1469*9880d681SAndroid Build Coastguard Worker return DenseMapInfo<CatchPadInst *>::getEmptyKey();
1470*9880d681SAndroid Build Coastguard Worker }
1471*9880d681SAndroid Build Coastguard Worker static CatchPadInst *getTombstoneKey() {
1472*9880d681SAndroid Build Coastguard Worker return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
1473*9880d681SAndroid Build Coastguard Worker }
1474*9880d681SAndroid Build Coastguard Worker static unsigned getHashValue(CatchPadInst *CatchPad) {
1475*9880d681SAndroid Build Coastguard Worker return static_cast<unsigned>(hash_combine_range(
1476*9880d681SAndroid Build Coastguard Worker CatchPad->value_op_begin(), CatchPad->value_op_end()));
1477*9880d681SAndroid Build Coastguard Worker }
1478*9880d681SAndroid Build Coastguard Worker static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
1479*9880d681SAndroid Build Coastguard Worker if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1480*9880d681SAndroid Build Coastguard Worker RHS == getEmptyKey() || RHS == getTombstoneKey())
1481*9880d681SAndroid Build Coastguard Worker return LHS == RHS;
1482*9880d681SAndroid Build Coastguard Worker return LHS->isIdenticalTo(RHS);
1483*9880d681SAndroid Build Coastguard Worker }
1484*9880d681SAndroid Build Coastguard Worker };
1485*9880d681SAndroid Build Coastguard Worker
1486*9880d681SAndroid Build Coastguard Worker // Set of unique CatchPads.
1487*9880d681SAndroid Build Coastguard Worker SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
1488*9880d681SAndroid Build Coastguard Worker CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
1489*9880d681SAndroid Build Coastguard Worker HandlerSet;
1490*9880d681SAndroid Build Coastguard Worker detail::DenseSetEmpty Empty;
1491*9880d681SAndroid Build Coastguard Worker for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
1492*9880d681SAndroid Build Coastguard Worker E = CatchSwitch->handler_end();
1493*9880d681SAndroid Build Coastguard Worker I != E; ++I) {
1494*9880d681SAndroid Build Coastguard Worker BasicBlock *HandlerBB = *I;
1495*9880d681SAndroid Build Coastguard Worker auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
1496*9880d681SAndroid Build Coastguard Worker if (!HandlerSet.insert({CatchPad, Empty}).second) {
1497*9880d681SAndroid Build Coastguard Worker CatchSwitch->removeHandler(I);
1498*9880d681SAndroid Build Coastguard Worker --I;
1499*9880d681SAndroid Build Coastguard Worker --E;
1500*9880d681SAndroid Build Coastguard Worker Changed = true;
1501*9880d681SAndroid Build Coastguard Worker }
1502*9880d681SAndroid Build Coastguard Worker }
1503*9880d681SAndroid Build Coastguard Worker }
1504*9880d681SAndroid Build Coastguard Worker
1505*9880d681SAndroid Build Coastguard Worker Changed |= ConstantFoldTerminator(BB, true);
1506*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Successor : successors(BB))
1507*9880d681SAndroid Build Coastguard Worker if (Reachable.insert(Successor).second)
1508*9880d681SAndroid Build Coastguard Worker Worklist.push_back(Successor);
1509*9880d681SAndroid Build Coastguard Worker } while (!Worklist.empty());
1510*9880d681SAndroid Build Coastguard Worker return Changed;
1511*9880d681SAndroid Build Coastguard Worker }
1512*9880d681SAndroid Build Coastguard Worker
removeUnwindEdge(BasicBlock * BB)1513*9880d681SAndroid Build Coastguard Worker void llvm::removeUnwindEdge(BasicBlock *BB) {
1514*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = BB->getTerminator();
1515*9880d681SAndroid Build Coastguard Worker
1516*9880d681SAndroid Build Coastguard Worker if (auto *II = dyn_cast<InvokeInst>(TI)) {
1517*9880d681SAndroid Build Coastguard Worker changeToCall(II);
1518*9880d681SAndroid Build Coastguard Worker return;
1519*9880d681SAndroid Build Coastguard Worker }
1520*9880d681SAndroid Build Coastguard Worker
1521*9880d681SAndroid Build Coastguard Worker TerminatorInst *NewTI;
1522*9880d681SAndroid Build Coastguard Worker BasicBlock *UnwindDest;
1523*9880d681SAndroid Build Coastguard Worker
1524*9880d681SAndroid Build Coastguard Worker if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1525*9880d681SAndroid Build Coastguard Worker NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
1526*9880d681SAndroid Build Coastguard Worker UnwindDest = CRI->getUnwindDest();
1527*9880d681SAndroid Build Coastguard Worker } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1528*9880d681SAndroid Build Coastguard Worker auto *NewCatchSwitch = CatchSwitchInst::Create(
1529*9880d681SAndroid Build Coastguard Worker CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
1530*9880d681SAndroid Build Coastguard Worker CatchSwitch->getName(), CatchSwitch);
1531*9880d681SAndroid Build Coastguard Worker for (BasicBlock *PadBB : CatchSwitch->handlers())
1532*9880d681SAndroid Build Coastguard Worker NewCatchSwitch->addHandler(PadBB);
1533*9880d681SAndroid Build Coastguard Worker
1534*9880d681SAndroid Build Coastguard Worker NewTI = NewCatchSwitch;
1535*9880d681SAndroid Build Coastguard Worker UnwindDest = CatchSwitch->getUnwindDest();
1536*9880d681SAndroid Build Coastguard Worker } else {
1537*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Could not find unwind successor");
1538*9880d681SAndroid Build Coastguard Worker }
1539*9880d681SAndroid Build Coastguard Worker
1540*9880d681SAndroid Build Coastguard Worker NewTI->takeName(TI);
1541*9880d681SAndroid Build Coastguard Worker NewTI->setDebugLoc(TI->getDebugLoc());
1542*9880d681SAndroid Build Coastguard Worker UnwindDest->removePredecessor(BB);
1543*9880d681SAndroid Build Coastguard Worker TI->replaceAllUsesWith(NewTI);
1544*9880d681SAndroid Build Coastguard Worker TI->eraseFromParent();
1545*9880d681SAndroid Build Coastguard Worker }
1546*9880d681SAndroid Build Coastguard Worker
1547*9880d681SAndroid Build Coastguard Worker /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1548*9880d681SAndroid Build Coastguard Worker /// if they are in a dead cycle. Return true if a change was made, false
1549*9880d681SAndroid Build Coastguard Worker /// otherwise.
removeUnreachableBlocks(Function & F,LazyValueInfo * LVI)1550*9880d681SAndroid Build Coastguard Worker bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
1551*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock*, 16> Reachable;
1552*9880d681SAndroid Build Coastguard Worker bool Changed = markAliveBlocks(F, Reachable);
1553*9880d681SAndroid Build Coastguard Worker
1554*9880d681SAndroid Build Coastguard Worker // If there are unreachable blocks in the CFG...
1555*9880d681SAndroid Build Coastguard Worker if (Reachable.size() == F.size())
1556*9880d681SAndroid Build Coastguard Worker return Changed;
1557*9880d681SAndroid Build Coastguard Worker
1558*9880d681SAndroid Build Coastguard Worker assert(Reachable.size() < F.size());
1559*9880d681SAndroid Build Coastguard Worker NumRemoved += F.size()-Reachable.size();
1560*9880d681SAndroid Build Coastguard Worker
1561*9880d681SAndroid Build Coastguard Worker // Loop over all of the basic blocks that are not reachable, dropping all of
1562*9880d681SAndroid Build Coastguard Worker // their internal references...
1563*9880d681SAndroid Build Coastguard Worker for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1564*9880d681SAndroid Build Coastguard Worker if (Reachable.count(&*BB))
1565*9880d681SAndroid Build Coastguard Worker continue;
1566*9880d681SAndroid Build Coastguard Worker
1567*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Successor : successors(&*BB))
1568*9880d681SAndroid Build Coastguard Worker if (Reachable.count(Successor))
1569*9880d681SAndroid Build Coastguard Worker Successor->removePredecessor(&*BB);
1570*9880d681SAndroid Build Coastguard Worker if (LVI)
1571*9880d681SAndroid Build Coastguard Worker LVI->eraseBlock(&*BB);
1572*9880d681SAndroid Build Coastguard Worker BB->dropAllReferences();
1573*9880d681SAndroid Build Coastguard Worker }
1574*9880d681SAndroid Build Coastguard Worker
1575*9880d681SAndroid Build Coastguard Worker for (Function::iterator I = ++F.begin(); I != F.end();)
1576*9880d681SAndroid Build Coastguard Worker if (!Reachable.count(&*I))
1577*9880d681SAndroid Build Coastguard Worker I = F.getBasicBlockList().erase(I);
1578*9880d681SAndroid Build Coastguard Worker else
1579*9880d681SAndroid Build Coastguard Worker ++I;
1580*9880d681SAndroid Build Coastguard Worker
1581*9880d681SAndroid Build Coastguard Worker return true;
1582*9880d681SAndroid Build Coastguard Worker }
1583*9880d681SAndroid Build Coastguard Worker
combineMetadata(Instruction * K,const Instruction * J,ArrayRef<unsigned> KnownIDs)1584*9880d681SAndroid Build Coastguard Worker void llvm::combineMetadata(Instruction *K, const Instruction *J,
1585*9880d681SAndroid Build Coastguard Worker ArrayRef<unsigned> KnownIDs) {
1586*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1587*9880d681SAndroid Build Coastguard Worker K->dropUnknownNonDebugMetadata(KnownIDs);
1588*9880d681SAndroid Build Coastguard Worker K->getAllMetadataOtherThanDebugLoc(Metadata);
1589*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
1590*9880d681SAndroid Build Coastguard Worker unsigned Kind = Metadata[i].first;
1591*9880d681SAndroid Build Coastguard Worker MDNode *JMD = J->getMetadata(Kind);
1592*9880d681SAndroid Build Coastguard Worker MDNode *KMD = Metadata[i].second;
1593*9880d681SAndroid Build Coastguard Worker
1594*9880d681SAndroid Build Coastguard Worker switch (Kind) {
1595*9880d681SAndroid Build Coastguard Worker default:
1596*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, nullptr); // Remove unknown metadata
1597*9880d681SAndroid Build Coastguard Worker break;
1598*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_dbg:
1599*9880d681SAndroid Build Coastguard Worker llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1600*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_tbaa:
1601*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1602*9880d681SAndroid Build Coastguard Worker break;
1603*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_alias_scope:
1604*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1605*9880d681SAndroid Build Coastguard Worker break;
1606*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_noalias:
1607*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_mem_parallel_loop_access:
1608*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1609*9880d681SAndroid Build Coastguard Worker break;
1610*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_range:
1611*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1612*9880d681SAndroid Build Coastguard Worker break;
1613*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_fpmath:
1614*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1615*9880d681SAndroid Build Coastguard Worker break;
1616*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_invariant_load:
1617*9880d681SAndroid Build Coastguard Worker // Only set the !invariant.load if it is present in both instructions.
1618*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, JMD);
1619*9880d681SAndroid Build Coastguard Worker break;
1620*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_nonnull:
1621*9880d681SAndroid Build Coastguard Worker // Only set the !nonnull if it is present in both instructions.
1622*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind, JMD);
1623*9880d681SAndroid Build Coastguard Worker break;
1624*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_invariant_group:
1625*9880d681SAndroid Build Coastguard Worker // Preserve !invariant.group in K.
1626*9880d681SAndroid Build Coastguard Worker break;
1627*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_align:
1628*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind,
1629*9880d681SAndroid Build Coastguard Worker MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1630*9880d681SAndroid Build Coastguard Worker break;
1631*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_dereferenceable:
1632*9880d681SAndroid Build Coastguard Worker case LLVMContext::MD_dereferenceable_or_null:
1633*9880d681SAndroid Build Coastguard Worker K->setMetadata(Kind,
1634*9880d681SAndroid Build Coastguard Worker MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1635*9880d681SAndroid Build Coastguard Worker break;
1636*9880d681SAndroid Build Coastguard Worker }
1637*9880d681SAndroid Build Coastguard Worker }
1638*9880d681SAndroid Build Coastguard Worker // Set !invariant.group from J if J has it. If both instructions have it
1639*9880d681SAndroid Build Coastguard Worker // then we will just pick it from J - even when they are different.
1640*9880d681SAndroid Build Coastguard Worker // Also make sure that K is load or store - f.e. combining bitcast with load
1641*9880d681SAndroid Build Coastguard Worker // could produce bitcast with invariant.group metadata, which is invalid.
1642*9880d681SAndroid Build Coastguard Worker // FIXME: we should try to preserve both invariant.group md if they are
1643*9880d681SAndroid Build Coastguard Worker // different, but right now instruction can only have one invariant.group.
1644*9880d681SAndroid Build Coastguard Worker if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
1645*9880d681SAndroid Build Coastguard Worker if (isa<LoadInst>(K) || isa<StoreInst>(K))
1646*9880d681SAndroid Build Coastguard Worker K->setMetadata(LLVMContext::MD_invariant_group, JMD);
1647*9880d681SAndroid Build Coastguard Worker }
1648*9880d681SAndroid Build Coastguard Worker
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlockEdge & Root)1649*9880d681SAndroid Build Coastguard Worker unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1650*9880d681SAndroid Build Coastguard Worker DominatorTree &DT,
1651*9880d681SAndroid Build Coastguard Worker const BasicBlockEdge &Root) {
1652*9880d681SAndroid Build Coastguard Worker assert(From->getType() == To->getType());
1653*9880d681SAndroid Build Coastguard Worker
1654*9880d681SAndroid Build Coastguard Worker unsigned Count = 0;
1655*9880d681SAndroid Build Coastguard Worker for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1656*9880d681SAndroid Build Coastguard Worker UI != UE; ) {
1657*9880d681SAndroid Build Coastguard Worker Use &U = *UI++;
1658*9880d681SAndroid Build Coastguard Worker if (DT.dominates(Root, U)) {
1659*9880d681SAndroid Build Coastguard Worker U.set(To);
1660*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Replace dominated use of '"
1661*9880d681SAndroid Build Coastguard Worker << From->getName() << "' as "
1662*9880d681SAndroid Build Coastguard Worker << *To << " in " << *U << "\n");
1663*9880d681SAndroid Build Coastguard Worker ++Count;
1664*9880d681SAndroid Build Coastguard Worker }
1665*9880d681SAndroid Build Coastguard Worker }
1666*9880d681SAndroid Build Coastguard Worker return Count;
1667*9880d681SAndroid Build Coastguard Worker }
1668*9880d681SAndroid Build Coastguard Worker
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlock * BB)1669*9880d681SAndroid Build Coastguard Worker unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1670*9880d681SAndroid Build Coastguard Worker DominatorTree &DT,
1671*9880d681SAndroid Build Coastguard Worker const BasicBlock *BB) {
1672*9880d681SAndroid Build Coastguard Worker assert(From->getType() == To->getType());
1673*9880d681SAndroid Build Coastguard Worker
1674*9880d681SAndroid Build Coastguard Worker unsigned Count = 0;
1675*9880d681SAndroid Build Coastguard Worker for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1676*9880d681SAndroid Build Coastguard Worker UI != UE;) {
1677*9880d681SAndroid Build Coastguard Worker Use &U = *UI++;
1678*9880d681SAndroid Build Coastguard Worker auto *I = cast<Instruction>(U.getUser());
1679*9880d681SAndroid Build Coastguard Worker if (DT.properlyDominates(BB, I->getParent())) {
1680*9880d681SAndroid Build Coastguard Worker U.set(To);
1681*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
1682*9880d681SAndroid Build Coastguard Worker << *To << " in " << *U << "\n");
1683*9880d681SAndroid Build Coastguard Worker ++Count;
1684*9880d681SAndroid Build Coastguard Worker }
1685*9880d681SAndroid Build Coastguard Worker }
1686*9880d681SAndroid Build Coastguard Worker return Count;
1687*9880d681SAndroid Build Coastguard Worker }
1688*9880d681SAndroid Build Coastguard Worker
callsGCLeafFunction(ImmutableCallSite CS)1689*9880d681SAndroid Build Coastguard Worker bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
1690*9880d681SAndroid Build Coastguard Worker // Check if the function is specifically marked as a gc leaf function.
1691*9880d681SAndroid Build Coastguard Worker if (CS.hasFnAttr("gc-leaf-function"))
1692*9880d681SAndroid Build Coastguard Worker return true;
1693*9880d681SAndroid Build Coastguard Worker if (const Function *F = CS.getCalledFunction()) {
1694*9880d681SAndroid Build Coastguard Worker if (F->hasFnAttribute("gc-leaf-function"))
1695*9880d681SAndroid Build Coastguard Worker return true;
1696*9880d681SAndroid Build Coastguard Worker
1697*9880d681SAndroid Build Coastguard Worker if (auto IID = F->getIntrinsicID())
1698*9880d681SAndroid Build Coastguard Worker // Most LLVM intrinsics do not take safepoints.
1699*9880d681SAndroid Build Coastguard Worker return IID != Intrinsic::experimental_gc_statepoint &&
1700*9880d681SAndroid Build Coastguard Worker IID != Intrinsic::experimental_deoptimize;
1701*9880d681SAndroid Build Coastguard Worker }
1702*9880d681SAndroid Build Coastguard Worker
1703*9880d681SAndroid Build Coastguard Worker return false;
1704*9880d681SAndroid Build Coastguard Worker }
1705*9880d681SAndroid Build Coastguard Worker
1706*9880d681SAndroid Build Coastguard Worker /// A potential constituent of a bitreverse or bswap expression. See
1707*9880d681SAndroid Build Coastguard Worker /// collectBitParts for a fuller explanation.
1708*9880d681SAndroid Build Coastguard Worker struct BitPart {
BitPartBitPart1709*9880d681SAndroid Build Coastguard Worker BitPart(Value *P, unsigned BW) : Provider(P) {
1710*9880d681SAndroid Build Coastguard Worker Provenance.resize(BW);
1711*9880d681SAndroid Build Coastguard Worker }
1712*9880d681SAndroid Build Coastguard Worker
1713*9880d681SAndroid Build Coastguard Worker /// The Value that this is a bitreverse/bswap of.
1714*9880d681SAndroid Build Coastguard Worker Value *Provider;
1715*9880d681SAndroid Build Coastguard Worker /// The "provenance" of each bit. Provenance[A] = B means that bit A
1716*9880d681SAndroid Build Coastguard Worker /// in Provider becomes bit B in the result of this expression.
1717*9880d681SAndroid Build Coastguard Worker SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
1718*9880d681SAndroid Build Coastguard Worker
1719*9880d681SAndroid Build Coastguard Worker enum { Unset = -1 };
1720*9880d681SAndroid Build Coastguard Worker };
1721*9880d681SAndroid Build Coastguard Worker
1722*9880d681SAndroid Build Coastguard Worker /// Analyze the specified subexpression and see if it is capable of providing
1723*9880d681SAndroid Build Coastguard Worker /// pieces of a bswap or bitreverse. The subexpression provides a potential
1724*9880d681SAndroid Build Coastguard Worker /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1725*9880d681SAndroid Build Coastguard Worker /// the output of the expression came from a corresponding bit in some other
1726*9880d681SAndroid Build Coastguard Worker /// value. This function is recursive, and the end result is a mapping of
1727*9880d681SAndroid Build Coastguard Worker /// bitnumber to bitnumber. It is the caller's responsibility to validate that
1728*9880d681SAndroid Build Coastguard Worker /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
1729*9880d681SAndroid Build Coastguard Worker ///
1730*9880d681SAndroid Build Coastguard Worker /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1731*9880d681SAndroid Build Coastguard Worker /// that the expression deposits the low byte of %X into the high byte of the
1732*9880d681SAndroid Build Coastguard Worker /// result and that all other bits are zero. This expression is accepted and a
1733*9880d681SAndroid Build Coastguard Worker /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
1734*9880d681SAndroid Build Coastguard Worker /// [0-7].
1735*9880d681SAndroid Build Coastguard Worker ///
1736*9880d681SAndroid Build Coastguard Worker /// To avoid revisiting values, the BitPart results are memoized into the
1737*9880d681SAndroid Build Coastguard Worker /// provided map. To avoid unnecessary copying of BitParts, BitParts are
1738*9880d681SAndroid Build Coastguard Worker /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
1739*9880d681SAndroid Build Coastguard Worker /// store BitParts objects, not pointers. As we need the concept of a nullptr
1740*9880d681SAndroid Build Coastguard Worker /// BitParts (Value has been analyzed and the analysis failed), we an Optional
1741*9880d681SAndroid Build Coastguard Worker /// type instead to provide the same functionality.
1742*9880d681SAndroid Build Coastguard Worker ///
1743*9880d681SAndroid Build Coastguard Worker /// Because we pass around references into \c BPS, we must use a container that
1744*9880d681SAndroid Build Coastguard Worker /// does not invalidate internal references (std::map instead of DenseMap).
1745*9880d681SAndroid Build Coastguard Worker ///
1746*9880d681SAndroid Build Coastguard Worker static const Optional<BitPart> &
collectBitParts(Value * V,bool MatchBSwaps,bool MatchBitReversals,std::map<Value *,Optional<BitPart>> & BPS)1747*9880d681SAndroid Build Coastguard Worker collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
1748*9880d681SAndroid Build Coastguard Worker std::map<Value *, Optional<BitPart>> &BPS) {
1749*9880d681SAndroid Build Coastguard Worker auto I = BPS.find(V);
1750*9880d681SAndroid Build Coastguard Worker if (I != BPS.end())
1751*9880d681SAndroid Build Coastguard Worker return I->second;
1752*9880d681SAndroid Build Coastguard Worker
1753*9880d681SAndroid Build Coastguard Worker auto &Result = BPS[V] = None;
1754*9880d681SAndroid Build Coastguard Worker auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1755*9880d681SAndroid Build Coastguard Worker
1756*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(V)) {
1757*9880d681SAndroid Build Coastguard Worker // If this is an or instruction, it may be an inner node of the bswap.
1758*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::Or) {
1759*9880d681SAndroid Build Coastguard Worker auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
1760*9880d681SAndroid Build Coastguard Worker MatchBitReversals, BPS);
1761*9880d681SAndroid Build Coastguard Worker auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
1762*9880d681SAndroid Build Coastguard Worker MatchBitReversals, BPS);
1763*9880d681SAndroid Build Coastguard Worker if (!A || !B)
1764*9880d681SAndroid Build Coastguard Worker return Result;
1765*9880d681SAndroid Build Coastguard Worker
1766*9880d681SAndroid Build Coastguard Worker // Try and merge the two together.
1767*9880d681SAndroid Build Coastguard Worker if (!A->Provider || A->Provider != B->Provider)
1768*9880d681SAndroid Build Coastguard Worker return Result;
1769*9880d681SAndroid Build Coastguard Worker
1770*9880d681SAndroid Build Coastguard Worker Result = BitPart(A->Provider, BitWidth);
1771*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < A->Provenance.size(); ++i) {
1772*9880d681SAndroid Build Coastguard Worker if (A->Provenance[i] != BitPart::Unset &&
1773*9880d681SAndroid Build Coastguard Worker B->Provenance[i] != BitPart::Unset &&
1774*9880d681SAndroid Build Coastguard Worker A->Provenance[i] != B->Provenance[i])
1775*9880d681SAndroid Build Coastguard Worker return Result = None;
1776*9880d681SAndroid Build Coastguard Worker
1777*9880d681SAndroid Build Coastguard Worker if (A->Provenance[i] == BitPart::Unset)
1778*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = B->Provenance[i];
1779*9880d681SAndroid Build Coastguard Worker else
1780*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = A->Provenance[i];
1781*9880d681SAndroid Build Coastguard Worker }
1782*9880d681SAndroid Build Coastguard Worker
1783*9880d681SAndroid Build Coastguard Worker return Result;
1784*9880d681SAndroid Build Coastguard Worker }
1785*9880d681SAndroid Build Coastguard Worker
1786*9880d681SAndroid Build Coastguard Worker // If this is a logical shift by a constant, recurse then shift the result.
1787*9880d681SAndroid Build Coastguard Worker if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1788*9880d681SAndroid Build Coastguard Worker unsigned BitShift =
1789*9880d681SAndroid Build Coastguard Worker cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1790*9880d681SAndroid Build Coastguard Worker // Ensure the shift amount is defined.
1791*9880d681SAndroid Build Coastguard Worker if (BitShift > BitWidth)
1792*9880d681SAndroid Build Coastguard Worker return Result;
1793*9880d681SAndroid Build Coastguard Worker
1794*9880d681SAndroid Build Coastguard Worker auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1795*9880d681SAndroid Build Coastguard Worker MatchBitReversals, BPS);
1796*9880d681SAndroid Build Coastguard Worker if (!Res)
1797*9880d681SAndroid Build Coastguard Worker return Result;
1798*9880d681SAndroid Build Coastguard Worker Result = Res;
1799*9880d681SAndroid Build Coastguard Worker
1800*9880d681SAndroid Build Coastguard Worker // Perform the "shift" on BitProvenance.
1801*9880d681SAndroid Build Coastguard Worker auto &P = Result->Provenance;
1802*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::Shl) {
1803*9880d681SAndroid Build Coastguard Worker P.erase(std::prev(P.end(), BitShift), P.end());
1804*9880d681SAndroid Build Coastguard Worker P.insert(P.begin(), BitShift, BitPart::Unset);
1805*9880d681SAndroid Build Coastguard Worker } else {
1806*9880d681SAndroid Build Coastguard Worker P.erase(P.begin(), std::next(P.begin(), BitShift));
1807*9880d681SAndroid Build Coastguard Worker P.insert(P.end(), BitShift, BitPart::Unset);
1808*9880d681SAndroid Build Coastguard Worker }
1809*9880d681SAndroid Build Coastguard Worker
1810*9880d681SAndroid Build Coastguard Worker return Result;
1811*9880d681SAndroid Build Coastguard Worker }
1812*9880d681SAndroid Build Coastguard Worker
1813*9880d681SAndroid Build Coastguard Worker // If this is a logical 'and' with a mask that clears bits, recurse then
1814*9880d681SAndroid Build Coastguard Worker // unset the appropriate bits.
1815*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::And &&
1816*9880d681SAndroid Build Coastguard Worker isa<ConstantInt>(I->getOperand(1))) {
1817*9880d681SAndroid Build Coastguard Worker APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
1818*9880d681SAndroid Build Coastguard Worker const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1819*9880d681SAndroid Build Coastguard Worker
1820*9880d681SAndroid Build Coastguard Worker // Check that the mask allows a multiple of 8 bits for a bswap, for an
1821*9880d681SAndroid Build Coastguard Worker // early exit.
1822*9880d681SAndroid Build Coastguard Worker unsigned NumMaskedBits = AndMask.countPopulation();
1823*9880d681SAndroid Build Coastguard Worker if (!MatchBitReversals && NumMaskedBits % 8 != 0)
1824*9880d681SAndroid Build Coastguard Worker return Result;
1825*9880d681SAndroid Build Coastguard Worker
1826*9880d681SAndroid Build Coastguard Worker auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1827*9880d681SAndroid Build Coastguard Worker MatchBitReversals, BPS);
1828*9880d681SAndroid Build Coastguard Worker if (!Res)
1829*9880d681SAndroid Build Coastguard Worker return Result;
1830*9880d681SAndroid Build Coastguard Worker Result = Res;
1831*9880d681SAndroid Build Coastguard Worker
1832*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
1833*9880d681SAndroid Build Coastguard Worker // If the AndMask is zero for this bit, clear the bit.
1834*9880d681SAndroid Build Coastguard Worker if ((AndMask & Bit) == 0)
1835*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = BitPart::Unset;
1836*9880d681SAndroid Build Coastguard Worker return Result;
1837*9880d681SAndroid Build Coastguard Worker }
1838*9880d681SAndroid Build Coastguard Worker
1839*9880d681SAndroid Build Coastguard Worker // If this is a zext instruction zero extend the result.
1840*9880d681SAndroid Build Coastguard Worker if (I->getOpcode() == Instruction::ZExt) {
1841*9880d681SAndroid Build Coastguard Worker auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1842*9880d681SAndroid Build Coastguard Worker MatchBitReversals, BPS);
1843*9880d681SAndroid Build Coastguard Worker if (!Res)
1844*9880d681SAndroid Build Coastguard Worker return Result;
1845*9880d681SAndroid Build Coastguard Worker
1846*9880d681SAndroid Build Coastguard Worker Result = BitPart(Res->Provider, BitWidth);
1847*9880d681SAndroid Build Coastguard Worker auto NarrowBitWidth =
1848*9880d681SAndroid Build Coastguard Worker cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
1849*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < NarrowBitWidth; ++i)
1850*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = Res->Provenance[i];
1851*9880d681SAndroid Build Coastguard Worker for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
1852*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = BitPart::Unset;
1853*9880d681SAndroid Build Coastguard Worker return Result;
1854*9880d681SAndroid Build Coastguard Worker }
1855*9880d681SAndroid Build Coastguard Worker }
1856*9880d681SAndroid Build Coastguard Worker
1857*9880d681SAndroid Build Coastguard Worker // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1858*9880d681SAndroid Build Coastguard Worker // the input value to the bswap/bitreverse.
1859*9880d681SAndroid Build Coastguard Worker Result = BitPart(V, BitWidth);
1860*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < BitWidth; ++i)
1861*9880d681SAndroid Build Coastguard Worker Result->Provenance[i] = i;
1862*9880d681SAndroid Build Coastguard Worker return Result;
1863*9880d681SAndroid Build Coastguard Worker }
1864*9880d681SAndroid Build Coastguard Worker
bitTransformIsCorrectForBSwap(unsigned From,unsigned To,unsigned BitWidth)1865*9880d681SAndroid Build Coastguard Worker static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
1866*9880d681SAndroid Build Coastguard Worker unsigned BitWidth) {
1867*9880d681SAndroid Build Coastguard Worker if (From % 8 != To % 8)
1868*9880d681SAndroid Build Coastguard Worker return false;
1869*9880d681SAndroid Build Coastguard Worker // Convert from bit indices to byte indices and check for a byte reversal.
1870*9880d681SAndroid Build Coastguard Worker From >>= 3;
1871*9880d681SAndroid Build Coastguard Worker To >>= 3;
1872*9880d681SAndroid Build Coastguard Worker BitWidth >>= 3;
1873*9880d681SAndroid Build Coastguard Worker return From == BitWidth - To - 1;
1874*9880d681SAndroid Build Coastguard Worker }
1875*9880d681SAndroid Build Coastguard Worker
bitTransformIsCorrectForBitReverse(unsigned From,unsigned To,unsigned BitWidth)1876*9880d681SAndroid Build Coastguard Worker static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
1877*9880d681SAndroid Build Coastguard Worker unsigned BitWidth) {
1878*9880d681SAndroid Build Coastguard Worker return From == BitWidth - To - 1;
1879*9880d681SAndroid Build Coastguard Worker }
1880*9880d681SAndroid Build Coastguard Worker
1881*9880d681SAndroid Build Coastguard Worker /// Given an OR instruction, check to see if this is a bitreverse
1882*9880d681SAndroid Build Coastguard Worker /// idiom. If so, insert the new intrinsic and return true.
recognizeBSwapOrBitReverseIdiom(Instruction * I,bool MatchBSwaps,bool MatchBitReversals,SmallVectorImpl<Instruction * > & InsertedInsts)1883*9880d681SAndroid Build Coastguard Worker bool llvm::recognizeBSwapOrBitReverseIdiom(
1884*9880d681SAndroid Build Coastguard Worker Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
1885*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Instruction *> &InsertedInsts) {
1886*9880d681SAndroid Build Coastguard Worker if (Operator::getOpcode(I) != Instruction::Or)
1887*9880d681SAndroid Build Coastguard Worker return false;
1888*9880d681SAndroid Build Coastguard Worker if (!MatchBSwaps && !MatchBitReversals)
1889*9880d681SAndroid Build Coastguard Worker return false;
1890*9880d681SAndroid Build Coastguard Worker IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
1891*9880d681SAndroid Build Coastguard Worker if (!ITy || ITy->getBitWidth() > 128)
1892*9880d681SAndroid Build Coastguard Worker return false; // Can't do vectors or integers > 128 bits.
1893*9880d681SAndroid Build Coastguard Worker unsigned BW = ITy->getBitWidth();
1894*9880d681SAndroid Build Coastguard Worker
1895*9880d681SAndroid Build Coastguard Worker unsigned DemandedBW = BW;
1896*9880d681SAndroid Build Coastguard Worker IntegerType *DemandedTy = ITy;
1897*9880d681SAndroid Build Coastguard Worker if (I->hasOneUse()) {
1898*9880d681SAndroid Build Coastguard Worker if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
1899*9880d681SAndroid Build Coastguard Worker DemandedTy = cast<IntegerType>(Trunc->getType());
1900*9880d681SAndroid Build Coastguard Worker DemandedBW = DemandedTy->getBitWidth();
1901*9880d681SAndroid Build Coastguard Worker }
1902*9880d681SAndroid Build Coastguard Worker }
1903*9880d681SAndroid Build Coastguard Worker
1904*9880d681SAndroid Build Coastguard Worker // Try to find all the pieces corresponding to the bswap.
1905*9880d681SAndroid Build Coastguard Worker std::map<Value *, Optional<BitPart>> BPS;
1906*9880d681SAndroid Build Coastguard Worker auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
1907*9880d681SAndroid Build Coastguard Worker if (!Res)
1908*9880d681SAndroid Build Coastguard Worker return false;
1909*9880d681SAndroid Build Coastguard Worker auto &BitProvenance = Res->Provenance;
1910*9880d681SAndroid Build Coastguard Worker
1911*9880d681SAndroid Build Coastguard Worker // Now, is the bit permutation correct for a bswap or a bitreverse? We can
1912*9880d681SAndroid Build Coastguard Worker // only byteswap values with an even number of bytes.
1913*9880d681SAndroid Build Coastguard Worker bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
1914*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < DemandedBW; ++i) {
1915*9880d681SAndroid Build Coastguard Worker OKForBSwap &=
1916*9880d681SAndroid Build Coastguard Worker bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
1917*9880d681SAndroid Build Coastguard Worker OKForBitReverse &=
1918*9880d681SAndroid Build Coastguard Worker bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
1919*9880d681SAndroid Build Coastguard Worker }
1920*9880d681SAndroid Build Coastguard Worker
1921*9880d681SAndroid Build Coastguard Worker Intrinsic::ID Intrin;
1922*9880d681SAndroid Build Coastguard Worker if (OKForBSwap && MatchBSwaps)
1923*9880d681SAndroid Build Coastguard Worker Intrin = Intrinsic::bswap;
1924*9880d681SAndroid Build Coastguard Worker else if (OKForBitReverse && MatchBitReversals)
1925*9880d681SAndroid Build Coastguard Worker Intrin = Intrinsic::bitreverse;
1926*9880d681SAndroid Build Coastguard Worker else
1927*9880d681SAndroid Build Coastguard Worker return false;
1928*9880d681SAndroid Build Coastguard Worker
1929*9880d681SAndroid Build Coastguard Worker if (ITy != DemandedTy) {
1930*9880d681SAndroid Build Coastguard Worker Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
1931*9880d681SAndroid Build Coastguard Worker Value *Provider = Res->Provider;
1932*9880d681SAndroid Build Coastguard Worker IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
1933*9880d681SAndroid Build Coastguard Worker // We may need to truncate the provider.
1934*9880d681SAndroid Build Coastguard Worker if (DemandedTy != ProviderTy) {
1935*9880d681SAndroid Build Coastguard Worker auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
1936*9880d681SAndroid Build Coastguard Worker "trunc", I);
1937*9880d681SAndroid Build Coastguard Worker InsertedInsts.push_back(Trunc);
1938*9880d681SAndroid Build Coastguard Worker Provider = Trunc;
1939*9880d681SAndroid Build Coastguard Worker }
1940*9880d681SAndroid Build Coastguard Worker auto *CI = CallInst::Create(F, Provider, "rev", I);
1941*9880d681SAndroid Build Coastguard Worker InsertedInsts.push_back(CI);
1942*9880d681SAndroid Build Coastguard Worker auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
1943*9880d681SAndroid Build Coastguard Worker InsertedInsts.push_back(ExtInst);
1944*9880d681SAndroid Build Coastguard Worker return true;
1945*9880d681SAndroid Build Coastguard Worker }
1946*9880d681SAndroid Build Coastguard Worker
1947*9880d681SAndroid Build Coastguard Worker Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
1948*9880d681SAndroid Build Coastguard Worker InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
1949*9880d681SAndroid Build Coastguard Worker return true;
1950*9880d681SAndroid Build Coastguard Worker }
1951*9880d681SAndroid Build Coastguard Worker
1952*9880d681SAndroid Build Coastguard Worker // CodeGen has special handling for some string functions that may replace
1953*9880d681SAndroid Build Coastguard Worker // them with target-specific intrinsics. Since that'd skip our interceptors
1954*9880d681SAndroid Build Coastguard Worker // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
1955*9880d681SAndroid Build Coastguard Worker // we mark affected calls as NoBuiltin, which will disable optimization
1956*9880d681SAndroid Build Coastguard Worker // in CodeGen.
maybeMarkSanitizerLibraryCallNoBuiltin(CallInst * CI,const TargetLibraryInfo * TLI)1957*9880d681SAndroid Build Coastguard Worker void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI,
1958*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
1959*9880d681SAndroid Build Coastguard Worker Function *F = CI->getCalledFunction();
1960*9880d681SAndroid Build Coastguard Worker LibFunc::Func Func;
1961*9880d681SAndroid Build Coastguard Worker if (!F || F->hasLocalLinkage() || !F->hasName() ||
1962*9880d681SAndroid Build Coastguard Worker !TLI->getLibFunc(F->getName(), Func))
1963*9880d681SAndroid Build Coastguard Worker return;
1964*9880d681SAndroid Build Coastguard Worker switch (Func) {
1965*9880d681SAndroid Build Coastguard Worker default: break;
1966*9880d681SAndroid Build Coastguard Worker case LibFunc::memcmp:
1967*9880d681SAndroid Build Coastguard Worker case LibFunc::memchr:
1968*9880d681SAndroid Build Coastguard Worker case LibFunc::strcpy:
1969*9880d681SAndroid Build Coastguard Worker case LibFunc::stpcpy:
1970*9880d681SAndroid Build Coastguard Worker case LibFunc::strcmp:
1971*9880d681SAndroid Build Coastguard Worker case LibFunc::strlen:
1972*9880d681SAndroid Build Coastguard Worker case LibFunc::strnlen:
1973*9880d681SAndroid Build Coastguard Worker CI->addAttribute(AttributeSet::FunctionIndex, Attribute::NoBuiltin);
1974*9880d681SAndroid Build Coastguard Worker break;
1975*9880d681SAndroid Build Coastguard Worker }
1976*9880d681SAndroid Build Coastguard Worker }
1977