blob: acbc131118f2f22f3023c92608ebc8ab4b8a067f [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/Hashing.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +000019#include "llvm/ADT/STLExtras.h"
Fiona Glaserf74cc402015-09-28 18:56:07 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000021#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbourne8d642de2013-08-12 22:38:43 +000022#include "llvm/ADT/Statistic.h"
David Majnemer70497c62015-12-02 23:06:39 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
25#include "llvm/Analysis/MemoryBuiltins.h"
David Majnemerd9833ea2016-01-10 07:13:04 +000026#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000028#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000030#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000035#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/GlobalAlias.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/MDBuilder.h"
43#include "llvm/IR/Metadata.h"
44#include "llvm/IR/Operator.h"
David Majnemer9f506252016-06-25 08:34:38 +000045#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000046#include "llvm/IR/ValueHandle.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000047#include "llvm/Support/Debug.h"
Chris Lattnerc13c7b92005-09-26 05:27:10 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000049#include "llvm/Support/raw_ostream.h"
Chris Lattner04efa4b2003-12-19 05:56:28 +000050using namespace llvm;
David Majnemer9f506252016-06-25 08:34:38 +000051using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chandler Carruthe96dd892014-04-21 22:55:11 +000053#define DEBUG_TYPE "local"
54
Peter Collingbourne8d642de2013-08-12 22:38:43 +000055STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
56
Chris Lattner28537df2002-05-07 18:07:59 +000057//===----------------------------------------------------------------------===//
Chris Lattnerc6c481c2008-11-27 22:57:53 +000058// Local constant propagation.
Chris Lattner28537df2002-05-07 18:07:59 +000059//
60
Frits van Bommelad964552011-05-22 16:24:18 +000061/// ConstantFoldTerminator - If a terminator instruction is predicated on a
62/// constant value, convert it into an unconditional branch to the constant
63/// destination. This is a nontrivial operation because the successors of this
64/// basic block must have their PHI nodes updated.
65/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
66/// conditions and indirectbr addresses this might make dead if
67/// DeleteDeadConditions is true.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000068bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
69 const TargetLibraryInfo *TLI) {
Chris Lattner4b009ad2002-05-21 20:04:50 +000070 TerminatorInst *T = BB->getTerminator();
Devang Patel1fabbe92011-05-18 17:26:46 +000071 IRBuilder<> Builder(T);
Misha Brukmanb1c93172005-04-21 23:48:37 +000072
Chris Lattner28537df2002-05-07 18:07:59 +000073 // Branch - See if we are conditional jumping on constant
74 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
75 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greif97f17202009-01-30 18:21:13 +000076 BasicBlock *Dest1 = BI->getSuccessor(0);
77 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner28537df2002-05-07 18:07:59 +000078
Zhou Sheng75b871f2007-01-11 12:24:14 +000079 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner28537df2002-05-07 18:07:59 +000080 // Are we branching on constant?
81 // YES. Change to unconditional branch...
Reid Spencercddc9df2007-01-12 04:24:46 +000082 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
83 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner28537df2002-05-07 18:07:59 +000084
Misha Brukmanb1c93172005-04-21 23:48:37 +000085 //cerr << "Function: " << T->getParent()->getParent()
86 // << "\nRemoving branch from " << T->getParent()
Chris Lattner28537df2002-05-07 18:07:59 +000087 // << "\n\nTo: " << OldDest << endl;
88
89 // Let the basic block know that we are letting go of it. Based on this,
90 // it will adjust it's PHI nodes.
Jay Foad6a85be22011-04-19 15:23:29 +000091 OldDest->removePredecessor(BB);
Chris Lattner28537df2002-05-07 18:07:59 +000092
Jay Foad89afb432011-01-07 20:25:56 +000093 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +000094 Builder.CreateBr(Destination);
Jay Foad89afb432011-01-07 20:25:56 +000095 BI->eraseFromParent();
Chris Lattner28537df2002-05-07 18:07:59 +000096 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +000097 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +000098
Chris Lattner54a4b842009-11-01 03:40:38 +000099 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanb1c93172005-04-21 23:48:37 +0000100 // This branch matches something like this:
Chris Lattner28537df2002-05-07 18:07:59 +0000101 // br bool %cond, label %Dest, label %Dest
102 // and changes it into: br label %Dest
103
104 // Let the basic block know that we are letting go of one copy of it.
105 assert(BI->getParent() && "Terminator not inserted in block!");
106 Dest1->removePredecessor(BI->getParent());
107
Jay Foad89afb432011-01-07 20:25:56 +0000108 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000109 Builder.CreateBr(Dest1);
Frits van Bommelad964552011-05-22 16:24:18 +0000110 Value *Cond = BI->getCondition();
Jay Foad89afb432011-01-07 20:25:56 +0000111 BI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000112 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000113 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner28537df2002-05-07 18:07:59 +0000114 return true;
115 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000116 return false;
117 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000118
Chris Lattner54a4b842009-11-01 03:40:38 +0000119 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
Hans Wennborg90b827c2015-01-26 19:52:24 +0000120 // If we are switching on a constant, we can convert the switch to an
121 // unconditional branch.
Chris Lattner821deee2003-08-17 20:21:14 +0000122 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
Hans Wennborg90b827c2015-01-26 19:52:24 +0000123 BasicBlock *DefaultDest = SI->getDefaultDest();
124 BasicBlock *TheOnlyDest = DefaultDest;
125
126 // If the default is unreachable, ignore it when searching for TheOnlyDest.
127 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
128 SI->getNumCases() > 0) {
129 TheOnlyDest = SI->case_begin().getCaseSuccessor();
130 }
Chris Lattner031340a2003-08-17 19:41:53 +0000131
Chris Lattner54a4b842009-11-01 03:40:38 +0000132 // Figure out which case it goes to.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000133 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000134 i != e; ++i) {
Chris Lattner821deee2003-08-17 20:21:14 +0000135 // Found case matching a constant operand?
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000136 if (i.getCaseValue() == CI) {
137 TheOnlyDest = i.getCaseSuccessor();
Chris Lattner821deee2003-08-17 20:21:14 +0000138 break;
139 }
Chris Lattner031340a2003-08-17 19:41:53 +0000140
Chris Lattnerc54d6082003-08-23 23:18:19 +0000141 // Check to see if this branch is going to the same place as the default
142 // dest. If so, eliminate it as an explicit compare.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000143 if (i.getCaseSuccessor() == DefaultDest) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000144 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Justin Bognera41a7b32013-12-10 00:13:41 +0000145 unsigned NCases = SI->getNumCases();
146 // Fold the case metadata into the default if there will be any branches
147 // left, unless the metadata doesn't match the switch.
148 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
Manman Ren49dbe252012-09-12 17:04:11 +0000149 // Collect branch weights into a vector.
150 SmallVector<uint32_t, 8> Weights;
151 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
152 ++MD_i) {
David Majnemer9f506252016-06-25 08:34:38 +0000153 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren49dbe252012-09-12 17:04:11 +0000154 Weights.push_back(CI->getValue().getZExtValue());
155 }
156 // Merge weight of this case to the default weight.
157 unsigned idx = i.getCaseIndex();
158 Weights[0] += Weights[idx+1];
159 // Remove weight for this case.
160 std::swap(Weights[idx+1], Weights.back());
161 Weights.pop_back();
162 SI->setMetadata(LLVMContext::MD_prof,
163 MDBuilder(BB->getContext()).
164 createBranchWeights(Weights));
165 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000166 // Remove this entry.
Chris Lattnerc54d6082003-08-23 23:18:19 +0000167 DefaultDest->removePredecessor(SI->getParent());
168 SI->removeCase(i);
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000169 --i; --e;
Chris Lattnerc54d6082003-08-23 23:18:19 +0000170 continue;
171 }
172
Chris Lattner821deee2003-08-17 20:21:14 +0000173 // Otherwise, check to see if the switch only branches to one destination.
174 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
175 // destinations.
Craig Topperf40110f2014-04-25 05:29:35 +0000176 if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
Chris Lattner031340a2003-08-17 19:41:53 +0000177 }
178
Chris Lattner821deee2003-08-17 20:21:14 +0000179 if (CI && !TheOnlyDest) {
180 // Branching on a constant, but not any of the cases, go to the default
181 // successor.
182 TheOnlyDest = SI->getDefaultDest();
183 }
184
185 // If we found a single destination that we can fold the switch into, do so
186 // now.
187 if (TheOnlyDest) {
Chris Lattner54a4b842009-11-01 03:40:38 +0000188 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000189 Builder.CreateBr(TheOnlyDest);
Chris Lattner821deee2003-08-17 20:21:14 +0000190 BasicBlock *BB = SI->getParent();
191
192 // Remove entries from PHI nodes which we no longer branch to...
Pete Cooperebcd7482015-08-06 20:22:46 +0000193 for (BasicBlock *Succ : SI->successors()) {
Chris Lattner821deee2003-08-17 20:21:14 +0000194 // Found case matching a constant operand?
Chris Lattner821deee2003-08-17 20:21:14 +0000195 if (Succ == TheOnlyDest)
Craig Topperf40110f2014-04-25 05:29:35 +0000196 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
Chris Lattner821deee2003-08-17 20:21:14 +0000197 else
198 Succ->removePredecessor(BB);
199 }
200
Chris Lattner54a4b842009-11-01 03:40:38 +0000201 // Delete the old switch.
Frits van Bommelad964552011-05-22 16:24:18 +0000202 Value *Cond = SI->getCondition();
203 SI->eraseFromParent();
204 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000205 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner821deee2003-08-17 20:21:14 +0000206 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000207 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000208
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000209 if (SI->getNumCases() == 1) {
Chris Lattner821deee2003-08-17 20:21:14 +0000210 // Otherwise, we can fold this switch into a conditional branch
211 // instruction if it has only one non-default destination.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000212 SwitchInst::CaseIt FirstCase = SI->case_begin();
Bob Wilsone4077362013-09-09 19:14:35 +0000213 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
214 FirstCase.getCaseValue(), "cond");
Devang Patel1fabbe92011-05-18 17:26:46 +0000215
Bob Wilsone4077362013-09-09 19:14:35 +0000216 // Insert the new branch.
217 BranchInst *NewBr = Builder.CreateCondBr(Cond,
218 FirstCase.getCaseSuccessor(),
219 SI->getDefaultDest());
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000220 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Bob Wilsone4077362013-09-09 19:14:35 +0000221 if (MD && MD->getNumOperands() == 3) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000222 ConstantInt *SICase =
223 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
224 ConstantInt *SIDef =
225 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
Bob Wilsone4077362013-09-09 19:14:35 +0000226 assert(SICase && SIDef);
227 // The TrueWeight should be the weight for the single case of SI.
228 NewBr->setMetadata(LLVMContext::MD_prof,
229 MDBuilder(BB->getContext()).
230 createBranchWeights(SICase->getValue().getZExtValue(),
231 SIDef->getValue().getZExtValue()));
Stepan Dyatkovskiy7a501552012-05-23 08:18:26 +0000232 }
Bob Wilsone4077362013-09-09 19:14:35 +0000233
Chen Lieafbc9d2015-08-07 19:30:12 +0000234 // Update make.implicit metadata to the newly-created conditional branch.
235 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
236 if (MakeImplicitMD)
237 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
238
Bob Wilsone4077362013-09-09 19:14:35 +0000239 // Delete the old switch.
240 SI->eraseFromParent();
241 return true;
Chris Lattner821deee2003-08-17 20:21:14 +0000242 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000243 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000244 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000245
246 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
247 // indirectbr blockaddress(@F, @BB) -> br label @BB
248 if (BlockAddress *BA =
249 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
250 BasicBlock *TheOnlyDest = BA->getBasicBlock();
251 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000252 Builder.CreateBr(TheOnlyDest);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000253
Chris Lattner54a4b842009-11-01 03:40:38 +0000254 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
255 if (IBI->getDestination(i) == TheOnlyDest)
Craig Topperf40110f2014-04-25 05:29:35 +0000256 TheOnlyDest = nullptr;
Chris Lattner54a4b842009-11-01 03:40:38 +0000257 else
258 IBI->getDestination(i)->removePredecessor(IBI->getParent());
259 }
Frits van Bommelad964552011-05-22 16:24:18 +0000260 Value *Address = IBI->getAddress();
Chris Lattner54a4b842009-11-01 03:40:38 +0000261 IBI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000262 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000263 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000264
Chris Lattner54a4b842009-11-01 03:40:38 +0000265 // If we didn't find our destination in the IBI successor list, then we
266 // have undefined behavior. Replace the unconditional branch with an
267 // 'unreachable' instruction.
268 if (TheOnlyDest) {
269 BB->getTerminator()->eraseFromParent();
270 new UnreachableInst(BB->getContext(), BB);
271 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000272
Chris Lattner54a4b842009-11-01 03:40:38 +0000273 return true;
274 }
275 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000276
Chris Lattner28537df2002-05-07 18:07:59 +0000277 return false;
278}
279
Chris Lattner28537df2002-05-07 18:07:59 +0000280
281//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000282// Local dead code elimination.
Chris Lattner28537df2002-05-07 18:07:59 +0000283//
284
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000285/// isInstructionTriviallyDead - Return true if the result produced by the
286/// instruction is not used, and the instruction has no side effects.
287///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000288bool llvm::isInstructionTriviallyDead(Instruction *I,
289 const TargetLibraryInfo *TLI) {
Daniel Berline3e69e12017-03-10 00:32:33 +0000290 if (!I->use_empty())
291 return false;
292 return wouldInstructionBeTriviallyDead(I, TLI);
293}
294
295bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
296 const TargetLibraryInfo *TLI) {
297 if (isa<TerminatorInst>(I))
298 return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000299
David Majnemer654e1302015-07-31 17:58:14 +0000300 // We don't want the landingpad-like instructions removed by anything this
301 // general.
302 if (I->isEHPad())
Bill Wendlingd9fb4702011-08-15 20:10:51 +0000303 return false;
304
Devang Patelc1431e62011-03-18 23:28:02 +0000305 // We don't want debug info removed by anything this general, unless
306 // debug info is empty.
307 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
Nick Lewycky99890a22011-08-02 21:19:27 +0000308 if (DDI->getAddress())
Devang Patelc1431e62011-03-18 23:28:02 +0000309 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000310 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000311 }
Devang Patel17bbd7f2011-03-21 22:04:45 +0000312 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patelc1431e62011-03-18 23:28:02 +0000313 if (DVI->getValue())
314 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000315 return true;
Devang Patelc1431e62011-03-18 23:28:02 +0000316 }
317
Daniel Berline3e69e12017-03-10 00:32:33 +0000318 if (!I->mayHaveSideEffects())
319 return true;
Duncan Sands1efabaa2009-05-06 06:49:50 +0000320
321 // Special case intrinsics that "may have side effects" but can be deleted
322 // when dead.
Nick Lewycky99890a22011-08-02 21:19:27 +0000323 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattnere9665832007-12-29 00:59:12 +0000324 // Safe to delete llvm.stacksave if dead.
325 if (II->getIntrinsicID() == Intrinsic::stacksave)
326 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000327
328 // Lifetime intrinsics are dead when their right-hand is undef.
329 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
330 II->getIntrinsicID() == Intrinsic::lifetime_end)
331 return isa<UndefValue>(II->getArgOperand(1));
Hal Finkel93046912014-07-25 21:13:35 +0000332
Sanjoy Das107aefc2016-04-29 22:23:16 +0000333 // Assumptions are dead if their condition is trivially true. Guards on
334 // true are operationally no-ops. In the future we can consider more
335 // sophisticated tradeoffs for guards considering potential for check
336 // widening, but for now we keep things simple.
337 if (II->getIntrinsicID() == Intrinsic::assume ||
338 II->getIntrinsicID() == Intrinsic::experimental_guard) {
Hal Finkel93046912014-07-25 21:13:35 +0000339 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
340 return !Cond->isZero();
341
342 return false;
343 }
Nick Lewycky99890a22011-08-02 21:19:27 +0000344 }
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000345
Daniel Berline3e69e12017-03-10 00:32:33 +0000346 if (isAllocLikeFn(I, TLI))
347 return true;
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000348
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000349 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000350 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
351 return C->isNullValue() || isa<UndefValue>(C);
352
Eli Friedmanb6befc32016-11-02 20:48:11 +0000353 if (CallSite CS = CallSite(I))
354 if (isMathLibCallNoop(CS, TLI))
355 return true;
356
Chris Lattnera36d5252005-05-06 05:27:34 +0000357 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000358}
359
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000360/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
361/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohmancb99fe92010-01-05 15:45:31 +0000362/// trivially dead, delete them too, recursively. Return true if any
363/// instructions were deleted.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000364bool
365llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
366 const TargetLibraryInfo *TLI) {
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000367 Instruction *I = dyn_cast<Instruction>(V);
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000368 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
Dan Gohmancb99fe92010-01-05 15:45:31 +0000369 return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000370
Chris Lattnere9f6c352008-11-28 01:20:46 +0000371 SmallVector<Instruction*, 16> DeadInsts;
372 DeadInsts.push_back(I);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000373
Dan Gohman28943872010-01-05 16:27:25 +0000374 do {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000375 I = DeadInsts.pop_back_val();
Chris Lattnerd4b5ba62008-11-28 00:58:15 +0000376
Chris Lattnere9f6c352008-11-28 01:20:46 +0000377 // Null out all of the instruction's operands to see if any operand becomes
378 // dead as we go.
379 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
380 Value *OpV = I->getOperand(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000381 I->setOperand(i, nullptr);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000382
Chris Lattnere9f6c352008-11-28 01:20:46 +0000383 if (!OpV->use_empty()) continue;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000384
Chris Lattnere9f6c352008-11-28 01:20:46 +0000385 // If the operand is an instruction that became dead as we nulled out the
386 // operand, and if it is 'trivially' dead, delete it in a future loop
387 // iteration.
388 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000389 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnere9f6c352008-11-28 01:20:46 +0000390 DeadInsts.push_back(OpI);
391 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000392
Chris Lattnere9f6c352008-11-28 01:20:46 +0000393 I->eraseFromParent();
Dan Gohman28943872010-01-05 16:27:25 +0000394 } while (!DeadInsts.empty());
Dan Gohmancb99fe92010-01-05 15:45:31 +0000395
396 return true;
Chris Lattner28537df2002-05-07 18:07:59 +0000397}
Chris Lattner99d68092008-11-27 07:43:12 +0000398
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000399/// areAllUsesEqual - Check whether the uses of a value are all the same.
400/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000401/// true when there are no uses or multiple uses that all refer to the same
402/// value.
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000403static bool areAllUsesEqual(Instruction *I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 Value::user_iterator UI = I->user_begin();
405 Value::user_iterator UE = I->user_end();
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000406 if (UI == UE)
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000407 return true;
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000408
409 User *TheUse = *UI;
410 for (++UI; UI != UE; ++UI) {
411 if (*UI != TheUse)
412 return false;
413 }
414 return true;
415}
416
Dan Gohmanff089952009-05-02 18:29:22 +0000417/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
418/// dead PHI node, due to being a def-use chain of single-use nodes that
419/// either forms a cycle or is terminated by a trivially dead instruction,
420/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sandsecbbf082011-02-21 17:32:05 +0000421/// too, recursively. Return true if a change was made.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000422bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
423 const TargetLibraryInfo *TLI) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000424 SmallPtrSet<Instruction*, 4> Visited;
425 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000426 I = cast<Instruction>(*I->user_begin())) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000427 if (I->use_empty())
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000428 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewycky183c24c2011-02-20 18:05:56 +0000429
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000430 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanff089952009-05-02 18:29:22 +0000431 // won't prove fruitful.
David Blaikie70573dc2014-11-19 07:49:26 +0000432 if (!Visited.insert(I).second) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000433 // Break the cycle and delete the instruction and its operands.
434 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000435 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sandsecbbf082011-02-21 17:32:05 +0000436 return true;
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000437 }
438 }
439 return false;
Dan Gohmanff089952009-05-02 18:29:22 +0000440}
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000441
Fiona Glaserf74cc402015-09-28 18:56:07 +0000442static bool
443simplifyAndDCEInstruction(Instruction *I,
444 SmallSetVector<Instruction *, 16> &WorkList,
445 const DataLayout &DL,
446 const TargetLibraryInfo *TLI) {
447 if (isInstructionTriviallyDead(I, TLI)) {
448 // Null out all of the instruction's operands to see if any operand becomes
449 // dead as we go.
450 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
451 Value *OpV = I->getOperand(i);
452 I->setOperand(i, nullptr);
453
454 if (!OpV->use_empty() || I == OpV)
455 continue;
456
457 // If the operand is an instruction that became dead as we nulled out the
458 // operand, and if it is 'trivially' dead, delete it in a future loop
459 // iteration.
460 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
461 if (isInstructionTriviallyDead(OpI, TLI))
462 WorkList.insert(OpI);
463 }
464
465 I->eraseFromParent();
466
467 return true;
468 }
469
470 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
471 // Add the users to the worklist. CAREFUL: an instruction can use itself,
472 // in the case of a phi node.
David Majnemerb8da3a22016-06-25 00:04:10 +0000473 for (User *U : I->users()) {
474 if (U != I) {
Fiona Glaserf74cc402015-09-28 18:56:07 +0000475 WorkList.insert(cast<Instruction>(U));
David Majnemerb8da3a22016-06-25 00:04:10 +0000476 }
477 }
Fiona Glaserf74cc402015-09-28 18:56:07 +0000478
479 // Replace the instruction with its simplified value.
David Majnemerb8da3a22016-06-25 00:04:10 +0000480 bool Changed = false;
481 if (!I->use_empty()) {
482 I->replaceAllUsesWith(SimpleV);
483 Changed = true;
484 }
485 if (isInstructionTriviallyDead(I, TLI)) {
486 I->eraseFromParent();
487 Changed = true;
488 }
489 return Changed;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000490 }
491 return false;
492}
493
Chris Lattner7c743f22010-01-12 19:40:54 +0000494/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
495/// simplify any instructions in it and recursively delete dead instructions.
496///
497/// This returns true if it changed the code, note that it can delete
498/// instructions in other blocks as well in this block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000499bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000500 const TargetLibraryInfo *TLI) {
Chris Lattner7c743f22010-01-12 19:40:54 +0000501 bool MadeChange = false;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000502 const DataLayout &DL = BB->getModule()->getDataLayout();
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000503
504#ifndef NDEBUG
505 // In debug builds, ensure that the terminator of the block is never replaced
506 // or deleted by these simplifications. The idea of simplification is that it
507 // cannot introduce new instructions, and there is no way to replace the
508 // terminator of a block without introducing a new instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000509 AssertingVH<Instruction> TerminatorVH(&BB->back());
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000510#endif
511
Fiona Glaserf74cc402015-09-28 18:56:07 +0000512 SmallSetVector<Instruction *, 16> WorkList;
513 // Iterate over the original function, only adding insts to the worklist
514 // if they actually need to be revisited. This avoids having to pre-init
515 // the worklist with the entire function's worth of instructions.
Chad Rosier56def252016-05-21 21:12:06 +0000516 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
517 BI != E;) {
Chandler Carruth17fc6ef2012-03-24 23:03:27 +0000518 assert(!BI->isTerminator());
Fiona Glaserf74cc402015-09-28 18:56:07 +0000519 Instruction *I = &*BI;
520 ++BI;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000521
Fiona Glaserf74cc402015-09-28 18:56:07 +0000522 // We're visiting this instruction now, so make sure it's not in the
523 // worklist from an earlier visit.
524 if (!WorkList.count(I))
525 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
526 }
Eli Friedman17bf4922011-04-02 22:45:17 +0000527
Fiona Glaserf74cc402015-09-28 18:56:07 +0000528 while (!WorkList.empty()) {
529 Instruction *I = WorkList.pop_back_val();
530 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
Chris Lattner7c743f22010-01-12 19:40:54 +0000531 }
532 return MadeChange;
533}
534
Chris Lattner99d68092008-11-27 07:43:12 +0000535//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000536// Control Flow Graph Restructuring.
Chris Lattner99d68092008-11-27 07:43:12 +0000537//
538
Chris Lattner852d6d62009-11-10 22:26:15 +0000539
540/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
541/// method is called when we're about to delete Pred as a predecessor of BB. If
542/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
543///
544/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
545/// nodes that collapse into identity values. For example, if we have:
546/// x = phi(1, 0, 0, 0)
547/// y = and x, z
548///
549/// .. and delete the predecessor corresponding to the '1', this will attempt to
550/// recursively fold the and to 0.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000551void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
Chris Lattner852d6d62009-11-10 22:26:15 +0000552 // This only adjusts blocks with PHI nodes.
553 if (!isa<PHINode>(BB->begin()))
554 return;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000555
Chris Lattner852d6d62009-11-10 22:26:15 +0000556 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
557 // them down. This will leave us with single entry phi nodes and other phis
558 // that can be removed.
559 BB->removePredecessor(Pred, true);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000560
Chris Lattner852d6d62009-11-10 22:26:15 +0000561 WeakVH PhiIt = &BB->front();
562 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
563 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattnere41ab072010-07-15 06:06:04 +0000564 Value *OldPhiIt = PhiIt;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000565
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000566 if (!recursivelySimplifyInstruction(PN))
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000567 continue;
568
Chris Lattner852d6d62009-11-10 22:26:15 +0000569 // If recursive simplification ended up deleting the next PHI node we would
570 // iterate to, then our iterator is invalid, restart scanning from the top
571 // of the block.
Chris Lattnere41ab072010-07-15 06:06:04 +0000572 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000573 }
574}
575
576
Chris Lattner99d68092008-11-27 07:43:12 +0000577/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
578/// predecessor is known to have one successor (DestBB!). Eliminate the edge
579/// between them, moving the instructions in the predecessor into DestBB and
580/// deleting the predecessor block.
581///
Chandler Carruth10f28f22015-01-20 01:37:09 +0000582void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
Chris Lattner99d68092008-11-27 07:43:12 +0000583 // If BB has single-entry PHI nodes, fold them.
584 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
585 Value *NewVal = PN->getIncomingValue(0);
586 // Replace self referencing PHI with undef, it must be dead.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000587 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner99d68092008-11-27 07:43:12 +0000588 PN->replaceAllUsesWith(NewVal);
589 PN->eraseFromParent();
590 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000591
Chris Lattner99d68092008-11-27 07:43:12 +0000592 BasicBlock *PredBB = DestBB->getSinglePredecessor();
593 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000594
Chris Lattner6fbfe582010-02-15 20:47:49 +0000595 // Zap anything that took the address of DestBB. Not doing this will give the
596 // address an invalid value.
597 if (DestBB->hasAddressTaken()) {
598 BlockAddress *BA = BlockAddress::get(DestBB);
599 Constant *Replacement =
600 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
601 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
602 BA->getType()));
603 BA->destroyConstant();
604 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000605
Chris Lattner99d68092008-11-27 07:43:12 +0000606 // Anything that branched to PredBB now branches to DestBB.
607 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000608
Jay Foad61ea0e42011-06-23 09:09:15 +0000609 // Splice all the instructions from PredBB to DestBB.
610 PredBB->getTerminator()->eraseFromParent();
Bill Wendling90dd90a2013-10-21 04:09:17 +0000611 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Jay Foad61ea0e42011-06-23 09:09:15 +0000612
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000613 // If the PredBB is the entry block of the function, move DestBB up to
614 // become the entry block after we erase PredBB.
615 if (PredBB == &DestBB->getParent()->getEntryBlock())
616 DestBB->moveAfter(PredBB);
617
Chandler Carruth10f28f22015-01-20 01:37:09 +0000618 if (DT) {
619 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
620 DT->changeImmediateDominator(DestBB, PredBBIDom);
621 DT->eraseNode(PredBB);
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000622 }
Chris Lattner99d68092008-11-27 07:43:12 +0000623 // Nuke BB.
624 PredBB->eraseFromParent();
625}
Devang Patelcaf44852009-02-10 07:00:59 +0000626
Duncan Sandse773c082013-07-11 08:28:20 +0000627/// CanMergeValues - Return true if we can choose one of these values to use
628/// in place of the other. Note that we will always choose the non-undef
629/// value to keep.
630static bool CanMergeValues(Value *First, Value *Second) {
631 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
632}
633
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000634/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
Mark Laceya2626552013-08-14 22:11:42 +0000635/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000636///
637/// Assumption: Succ is the single successor for BB.
638///
639static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
640 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
641
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000642 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000643 << Succ->getName() << "\n");
644 // Shortcut, if there is only a single predecessor it must be BB and merging
645 // is always safe
646 if (Succ->getSinglePredecessor()) return true;
647
648 // Make a list of the predecessors of BB
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000649 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000650
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000651 // Look at all the phi nodes in Succ, to see if they present a conflict when
652 // merging these blocks
653 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
654 PHINode *PN = cast<PHINode>(I);
655
656 // If the incoming value from BB is again a PHINode in
657 // BB which has the same incoming value for *PI as PN does, we can
658 // merge the phi nodes and then the blocks can still be merged
659 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
660 if (BBPN && BBPN->getParent() == BB) {
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000661 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
662 BasicBlock *IBB = PN->getIncomingBlock(PI);
663 if (BBPreds.count(IBB) &&
Duncan Sandse773c082013-07-11 08:28:20 +0000664 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
665 PN->getIncomingValue(PI))) {
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000666 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
667 << Succ->getName() << " is conflicting with "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000668 << BBPN->getName() << " with regard to common predecessor "
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000669 << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000670 return false;
671 }
672 }
673 } else {
674 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000675 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000676 // See if the incoming value for the common predecessor is equal to the
677 // one for BB, in which case this phi node will not prevent the merging
678 // of the block.
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000679 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandse773c082013-07-11 08:28:20 +0000680 if (BBPreds.count(IBB) &&
681 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000682 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000683 << Succ->getName() << " is conflicting with regard to common "
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000684 << "predecessor " << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000685 return false;
686 }
687 }
688 }
689 }
690
691 return true;
692}
693
Duncan Sandse773c082013-07-11 08:28:20 +0000694typedef SmallVector<BasicBlock *, 16> PredBlockVector;
695typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
696
697/// \brief Determines the value to use as the phi node input for a block.
698///
699/// Select between \p OldVal any value that we know flows from \p BB
700/// to a particular phi on the basis of which one (if either) is not
701/// undef. Update IncomingValues based on the selected value.
702///
703/// \param OldVal The value we are considering selecting.
704/// \param BB The block that the value flows in from.
705/// \param IncomingValues A map from block-to-value for other phi inputs
706/// that we have examined.
707///
708/// \returns the selected value.
709static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
710 IncomingValueMap &IncomingValues) {
711 if (!isa<UndefValue>(OldVal)) {
712 assert((!IncomingValues.count(BB) ||
713 IncomingValues.find(BB)->second == OldVal) &&
714 "Expected OldVal to match incoming value from BB!");
715
716 IncomingValues.insert(std::make_pair(BB, OldVal));
717 return OldVal;
718 }
719
720 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
721 if (It != IncomingValues.end()) return It->second;
722
723 return OldVal;
724}
725
726/// \brief Create a map from block to value for the operands of a
727/// given phi.
728///
729/// Create a map from block to value for each non-undef value flowing
730/// into \p PN.
731///
732/// \param PN The phi we are collecting the map for.
733/// \param IncomingValues [out] The map from block to value for this phi.
734static void gatherIncomingValuesToPhi(PHINode *PN,
735 IncomingValueMap &IncomingValues) {
736 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
737 BasicBlock *BB = PN->getIncomingBlock(i);
738 Value *V = PN->getIncomingValue(i);
739
740 if (!isa<UndefValue>(V))
741 IncomingValues.insert(std::make_pair(BB, V));
742 }
743}
744
745/// \brief Replace the incoming undef values to a phi with the values
746/// from a block-to-value map.
747///
748/// \param PN The phi we are replacing the undefs in.
749/// \param IncomingValues A map from block to value.
750static void replaceUndefValuesInPhi(PHINode *PN,
751 const IncomingValueMap &IncomingValues) {
752 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
753 Value *V = PN->getIncomingValue(i);
754
755 if (!isa<UndefValue>(V)) continue;
756
757 BasicBlock *BB = PN->getIncomingBlock(i);
758 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
759 if (It == IncomingValues.end()) continue;
760
761 PN->setIncomingValue(i, It->second);
762 }
763}
764
765/// \brief Replace a value flowing from a block to a phi with
766/// potentially multiple instances of that value flowing from the
767/// block's predecessors to the phi.
768///
769/// \param BB The block with the value flowing into the phi.
770/// \param BBPreds The predecessors of BB.
771/// \param PN The phi that we are updating.
772static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
773 const PredBlockVector &BBPreds,
774 PHINode *PN) {
775 Value *OldVal = PN->removeIncomingValue(BB, false);
776 assert(OldVal && "No entry in PHI for Pred BB!");
777
778 IncomingValueMap IncomingValues;
779
780 // We are merging two blocks - BB, and the block containing PN - and
781 // as a result we need to redirect edges from the predecessors of BB
782 // to go to the block containing PN, and update PN
783 // accordingly. Since we allow merging blocks in the case where the
784 // predecessor and successor blocks both share some predecessors,
785 // and where some of those common predecessors might have undef
786 // values flowing into PN, we want to rewrite those values to be
787 // consistent with the non-undef values.
788
789 gatherIncomingValuesToPhi(PN, IncomingValues);
790
791 // If this incoming value is one of the PHI nodes in BB, the new entries
792 // in the PHI node are the entries from the old PHI.
793 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
794 PHINode *OldValPN = cast<PHINode>(OldVal);
795 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
796 // Note that, since we are merging phi nodes and BB and Succ might
797 // have common predecessors, we could end up with a phi node with
798 // identical incoming branches. This will be cleaned up later (and
799 // will trigger asserts if we try to clean it up now, without also
800 // simplifying the corresponding conditional branch).
801 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
802 Value *PredVal = OldValPN->getIncomingValue(i);
803 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
804 IncomingValues);
805
806 // And add a new incoming value for this predecessor for the
807 // newly retargeted branch.
808 PN->addIncoming(Selected, PredBB);
809 }
810 } else {
811 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
812 // Update existing incoming values in PN for this
813 // predecessor of BB.
814 BasicBlock *PredBB = BBPreds[i];
815 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
816 IncomingValues);
817
818 // And add a new incoming value for this predecessor for the
819 // newly retargeted branch.
820 PN->addIncoming(Selected, PredBB);
821 }
822 }
823
824 replaceUndefValuesInPhi(PN, IncomingValues);
825}
826
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000827/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
828/// unconditional branch, and contains no instructions other than PHI nodes,
Rafael Espindolab10a0f22011-06-30 20:14:24 +0000829/// potential side-effect free intrinsics and the branch. If possible,
830/// eliminate BB by rewriting all the predecessors to branch to the successor
831/// block and return true. If we can't transform, return false.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000832bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
Dan Gohman4a63fad2010-08-14 00:29:42 +0000833 assert(BB != &BB->getParent()->getEntryBlock() &&
834 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
835
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000836 // We can't eliminate infinite loops.
837 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
838 if (BB == Succ) return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000839
Reid Klecknerbca59d22016-05-02 19:43:22 +0000840 // Check to see if merging these blocks would cause conflicts for any of the
841 // phi nodes in BB or Succ. If not, we can safely merge.
842 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000843
Reid Klecknerbca59d22016-05-02 19:43:22 +0000844 // Check for cases where Succ has multiple predecessors and a PHI node in BB
845 // has uses which will not disappear when the PHI nodes are merged. It is
846 // possible to handle such cases, but difficult: it requires checking whether
847 // BB dominates Succ, which is non-trivial to calculate in the case where
848 // Succ has multiple predecessors. Also, it requires checking whether
849 // constructing the necessary self-referential PHI node doesn't introduce any
850 // conflicts; this isn't too difficult, but the previous code for doing this
851 // was incorrect.
852 //
853 // Note that if this check finds a live use, BB dominates Succ, so BB is
854 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
855 // folding the branch isn't profitable in that case anyway.
856 if (!Succ->getSinglePredecessor()) {
857 BasicBlock::iterator BBI = BB->begin();
858 while (isa<PHINode>(*BBI)) {
859 for (Use &U : BBI->uses()) {
860 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
861 if (PN->getIncomingBlock(U) != BB)
Hans Wennborgb7599322016-05-02 17:22:54 +0000862 return false;
Reid Klecknerbca59d22016-05-02 19:43:22 +0000863 } else {
864 return false;
Hans Wennborgb7599322016-05-02 17:22:54 +0000865 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000866 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000867 ++BBI;
Hans Wennborgb7599322016-05-02 17:22:54 +0000868 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000869 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000870
871 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
872
873 if (isa<PHINode>(Succ->begin())) {
874 // If there is more than one pred of succ, and there are PHI nodes in
875 // the successor, then we need to add incoming edges for the PHI nodes
876 //
877 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
878
879 // Loop over all of the PHI nodes in the successor of BB.
880 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
881 PHINode *PN = cast<PHINode>(I);
882
883 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
884 }
885 }
886
887 if (Succ->getSinglePredecessor()) {
888 // BB is the only predecessor of Succ, so Succ will end up with exactly
889 // the same predecessors BB had.
890
891 // Copy over any phi, debug or lifetime instruction.
892 BB->getTerminator()->eraseFromParent();
893 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
894 BB->getInstList());
895 } else {
896 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
897 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
898 assert(PN->use_empty() && "There shouldn't be any uses here!");
899 PN->eraseFromParent();
900 }
901 }
902
Florian Hahn77382be2016-11-18 13:12:07 +0000903 // If the unconditional branch we replaced contains llvm.loop metadata, we
904 // add the metadata to the branch instructions in the predecessors.
905 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
906 Instruction *TI = BB->getTerminator();
907 if (TI)
908 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
909 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
910 BasicBlock *Pred = *PI;
911 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
912 }
913
Reid Klecknerbca59d22016-05-02 19:43:22 +0000914 // Everything that jumped to BB now goes to Succ.
915 BB->replaceAllUsesWith(Succ);
916 if (!Succ->hasName()) Succ->takeName(BB);
917 BB->eraseFromParent(); // Delete the old basic block.
918 return true;
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000919}
920
Jim Grosbachd831ef42009-12-02 17:06:45 +0000921/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
922/// nodes in this block. This doesn't try to be clever about PHI nodes
923/// which differ only in the order of the incoming values, but instcombine
924/// orders them so it usually won't matter.
925///
926bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
Jim Grosbachd831ef42009-12-02 17:06:45 +0000927 // This implementation doesn't currently consider undef operands
Nick Lewyckyfa44dc62011-06-28 03:57:31 +0000928 // specially. Theoretically, two phis which are identical except for
Jim Grosbachd831ef42009-12-02 17:06:45 +0000929 // one having an undef where the other doesn't could be collapsed.
930
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000931 struct PHIDenseMapInfo {
932 static PHINode *getEmptyKey() {
933 return DenseMapInfo<PHINode *>::getEmptyKey();
934 }
935 static PHINode *getTombstoneKey() {
936 return DenseMapInfo<PHINode *>::getTombstoneKey();
937 }
938 static unsigned getHashValue(PHINode *PN) {
939 // Compute a hash value on the operands. Instcombine will likely have
940 // sorted them, which helps expose duplicates, but we have to check all
941 // the operands to be safe in case instcombine hasn't run.
942 return static_cast<unsigned>(hash_combine(
943 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
944 hash_combine_range(PN->block_begin(), PN->block_end())));
945 }
946 static bool isEqual(PHINode *LHS, PHINode *RHS) {
947 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
948 RHS == getEmptyKey() || RHS == getTombstoneKey())
949 return LHS == RHS;
950 return LHS->isIdenticalTo(RHS);
951 }
952 };
Jim Grosbachd831ef42009-12-02 17:06:45 +0000953
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000954 // Set of unique PHINodes.
955 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
Jim Grosbachd831ef42009-12-02 17:06:45 +0000956
957 // Examine each PHI.
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +0000958 bool Changed = false;
959 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
960 auto Inserted = PHISet.insert(PN);
961 if (!Inserted.second) {
962 // A duplicate. Replace this PHI with its duplicate.
963 PN->replaceAllUsesWith(*Inserted.first);
964 PN->eraseFromParent();
965 Changed = true;
Benjamin Kramerf175e042015-09-02 19:52:23 +0000966
967 // The RAUW can change PHIs that we already visited. Start over from the
968 // beginning.
969 PHISet.clear();
970 I = BB->begin();
Jim Grosbachd831ef42009-12-02 17:06:45 +0000971 }
972 }
973
974 return Changed;
975}
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000976
977/// enforceKnownAlignment - If the specified pointer points to an object that
978/// we control, modify the object's alignment to PrefAlign. This isn't
979/// often possible though. If alignment is important, a more reliable approach
980/// is to simply align all global variables and allocation instructions to
981/// their preferred alignment from the beginning.
982///
Benjamin Kramer570dd782010-12-30 22:34:44 +0000983static unsigned enforceKnownAlignment(Value *V, unsigned Align,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000984 unsigned PrefAlign,
985 const DataLayout &DL) {
James Y Knightac03dca2016-01-15 16:33:06 +0000986 assert(PrefAlign > Align);
987
Eli Friedman19ace4c2011-06-15 21:08:25 +0000988 V = V->stripPointerCasts();
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000989
Eli Friedman19ace4c2011-06-15 21:08:25 +0000990 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +0000991 // TODO: ideally, computeKnownBits ought to have used
992 // AllocaInst::getAlignment() in its computation already, making
993 // the below max redundant. But, as it turns out,
994 // stripPointerCasts recurses through infinite layers of bitcasts,
995 // while computeKnownBits is not allowed to traverse more than 6
996 // levels.
997 Align = std::max(AI->getAlignment(), Align);
998 if (PrefAlign <= Align)
999 return Align;
1000
Lang Hamesde7ab802011-10-10 23:42:08 +00001001 // If the preferred alignment is greater than the natural stack alignment
1002 // then don't round up. This avoids dynamic stack realignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001003 if (DL.exceedsNaturalStackAlignment(PrefAlign))
Lang Hamesde7ab802011-10-10 23:42:08 +00001004 return Align;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001005 AI->setAlignment(PrefAlign);
1006 return PrefAlign;
1007 }
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001008
Rafael Espindola99e05cf2014-05-13 18:45:48 +00001009 if (auto *GO = dyn_cast<GlobalObject>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001010 // TODO: as above, this shouldn't be necessary.
1011 Align = std::max(GO->getAlignment(), Align);
1012 if (PrefAlign <= Align)
1013 return Align;
1014
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001015 // If there is a large requested alignment and we can, bump up the alignment
Reid Kleckner486fa392015-07-14 00:11:08 +00001016 // of the global. If the memory we set aside for the global may not be the
1017 // memory used by the final program then it is impossible for us to reliably
1018 // enforce the preferred alignment.
James Y Knightac03dca2016-01-15 16:33:06 +00001019 if (!GO->canIncreaseAlignment())
Rafael Espindolafc13db42014-05-09 16:01:06 +00001020 return Align;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001021
James Y Knightac03dca2016-01-15 16:33:06 +00001022 GO->setAlignment(PrefAlign);
1023 return PrefAlign;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001024 }
1025
1026 return Align;
1027}
1028
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001029unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001030 const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001031 const Instruction *CxtI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001032 AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001033 const DominatorTree *DT) {
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001034 assert(V->getType()->isPointerTy() &&
1035 "getOrEnforceKnownAlignment expects a pointer!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenault87dc6072013-08-01 22:42:18 +00001037
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001039 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001040 unsigned TrailZ = KnownZero.countTrailingOnes();
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001041
Matt Arsenaultf64212b2013-07-23 22:20:57 +00001042 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001043 // those computed from a null pointer.
1044 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001045
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001046 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001047
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001048 // LLVM doesn't support alignments larger than this currently.
1049 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001050
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001051 if (PrefAlign > Align)
Matt Arsenault87dc6072013-08-01 22:42:18 +00001052 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001053
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001054 // We don't need to make any adjustment.
1055 return Align;
1056}
1057
Devang Patel8c0b16b2011-03-17 21:58:19 +00001058///===---------------------------------------------------------------------===//
1059/// Dbg Intrinsic utilities
1060///
1061
Adrian Prantl29b9de72013-04-26 17:48:33 +00001062/// See if there is a dbg.value intrinsic for DIVar before I.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001063static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1064 Instruction *I) {
Adrian Prantl29b9de72013-04-26 17:48:33 +00001065 // Since we can't guarantee that the original dbg.declare instrinsic
1066 // is removed by LowerDbgDeclare(), we need to make sure that we are
1067 // not inserting the same dbg.value intrinsic over and over.
1068 llvm::BasicBlock::InstListType::iterator PrevI(I);
1069 if (PrevI != I->getParent()->getInstList().begin()) {
1070 --PrevI;
1071 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1072 if (DVI->getValue() == I->getOperand(0) &&
1073 DVI->getOffset() == 0 &&
Adrian Prantla5b2a642016-02-17 20:02:25 +00001074 DVI->getVariable() == DIVar &&
1075 DVI->getExpression() == DIExpr)
Adrian Prantl29b9de72013-04-26 17:48:33 +00001076 return true;
1077 }
1078 return false;
1079}
1080
Keith Walkerba159892016-09-22 14:13:25 +00001081/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1082static bool PhiHasDebugValue(DILocalVariable *DIVar,
1083 DIExpression *DIExpr,
1084 PHINode *APN) {
1085 // Since we can't guarantee that the original dbg.declare instrinsic
1086 // is removed by LowerDbgDeclare(), we need to make sure that we are
1087 // not inserting the same dbg.value intrinsic over and over.
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001088 SmallVector<DbgValueInst *, 1> DbgValues;
1089 findDbgValues(DbgValues, APN);
1090 for (auto *DVI : DbgValues) {
1091 assert(DVI->getValue() == APN);
1092 assert(DVI->getOffset() == 0);
1093 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1094 return true;
1095 }
1096 return false;
Keith Walkerba159892016-09-22 14:13:25 +00001097}
1098
Adrian Prantld00333a2013-04-26 18:10:50 +00001099/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Devang Patel8c0b16b2011-03-17 21:58:19 +00001100/// that has an associated llvm.dbg.decl intrinsic.
Keith Walkerba159892016-09-22 14:13:25 +00001101void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
Devang Patel8c0b16b2011-03-17 21:58:19 +00001102 StoreInst *SI, DIBuilder &Builder) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001103 auto *DIVar = DDI->getVariable();
1104 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001105 assert(DIVar && "Missing variable");
Devang Patel8c0b16b2011-03-17 21:58:19 +00001106
Devang Patel8e60ff12011-05-16 21:24:05 +00001107 // If an argument is zero extended then use argument directly. The ZExt
1108 // may be zapped by an optimization pass in future.
Craig Topperf40110f2014-04-25 05:29:35 +00001109 Argument *ExtendedArg = nullptr;
Devang Patel8e60ff12011-05-16 21:24:05 +00001110 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1111 ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1112 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1113 ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
Keno Fischer9aae4452016-01-12 22:46:09 +00001114 if (ExtendedArg) {
Adrian Prantl941fa752016-12-05 18:04:47 +00001115 // We're now only describing a subset of the variable. The fragment we're
Keno Fischer9aae4452016-01-12 22:46:09 +00001116 // describing will always be smaller than the variable size, because
1117 // VariableSize == Size of Alloca described by DDI. Since SI stores
1118 // to the alloca described by DDI, if it's first operand is an extend,
1119 // we're guaranteed that before extension, the value was narrower than
1120 // the size of the alloca, hence the size of the described variable.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001121 SmallVector<uint64_t, 3> Ops;
Adrian Prantl941fa752016-12-05 18:04:47 +00001122 unsigned FragmentOffset = 0;
1123 // If this already is a bit fragment, we drop the bit fragment from the
1124 // expression and record the offset.
Adrian Prantl49797ca2016-12-22 05:27:12 +00001125 auto Fragment = DIExpr->getFragmentInfo();
1126 if (Fragment) {
Adrian Prantla5b2a642016-02-17 20:02:25 +00001127 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
Adrian Prantl49797ca2016-12-22 05:27:12 +00001128 FragmentOffset = Fragment->OffsetInBits;
Keno Fischer9aae4452016-01-12 22:46:09 +00001129 } else {
Adrian Prantla5b2a642016-02-17 20:02:25 +00001130 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
Keno Fischer9aae4452016-01-12 22:46:09 +00001131 }
Adrian Prantl941fa752016-12-05 18:04:47 +00001132 Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1133 Ops.push_back(FragmentOffset);
Keno Fischer9aae4452016-01-12 22:46:09 +00001134 const DataLayout &DL = DDI->getModule()->getDataLayout();
Adrian Prantl941fa752016-12-05 18:04:47 +00001135 Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType()));
Adrian Prantla5b2a642016-02-17 20:02:25 +00001136 auto NewDIExpr = Builder.createExpression(Ops);
1137 if (!LdStHasDebugValue(DIVar, NewDIExpr, SI))
1138 Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr,
1139 DDI->getDebugLoc(), SI);
1140 } else if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Aaron Ballmana2f99432015-04-16 13:29:36 +00001141 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
1142 DDI->getDebugLoc(), SI);
Devang Patel8c0b16b2011-03-17 21:58:19 +00001143}
1144
Adrian Prantld00333a2013-04-26 18:10:50 +00001145/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Devang Patel2c7ee272011-03-18 23:45:43 +00001146/// that has an associated llvm.dbg.decl intrinsic.
Keith Walkerba159892016-09-22 14:13:25 +00001147void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
Devang Patel2c7ee272011-03-18 23:45:43 +00001148 LoadInst *LI, DIBuilder &Builder) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001149 auto *DIVar = DDI->getVariable();
1150 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001151 assert(DIVar && "Missing variable");
Devang Patel2c7ee272011-03-18 23:45:43 +00001152
Adrian Prantla5b2a642016-02-17 20:02:25 +00001153 if (LdStHasDebugValue(DIVar, DIExpr, LI))
Keith Walkerba159892016-09-22 14:13:25 +00001154 return;
Adrian Prantl29b9de72013-04-26 17:48:33 +00001155
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001156 // We are now tracking the loaded value instead of the address. In the
1157 // future if multi-location support is added to the IR, it might be
1158 // preferable to keep tracking both the loaded value and the original
1159 // address in case the alloca can not be elided.
1160 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1161 LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
1162 DbgValue->insertAfter(LI);
Keith Walkerba159892016-09-22 14:13:25 +00001163}
1164
1165/// Inserts a llvm.dbg.value intrinsic after a phi
1166/// that has an associated llvm.dbg.decl intrinsic.
1167void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1168 PHINode *APN, DIBuilder &Builder) {
1169 auto *DIVar = DDI->getVariable();
1170 auto *DIExpr = DDI->getExpression();
1171 assert(DIVar && "Missing variable");
1172
1173 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1174 return;
1175
Reid Kleckner64818222016-09-27 18:45:31 +00001176 BasicBlock *BB = APN->getParent();
Keith Walkerba159892016-09-22 14:13:25 +00001177 auto InsertionPt = BB->getFirstInsertionPt();
Reid Kleckner64818222016-09-27 18:45:31 +00001178
1179 // The block may be a catchswitch block, which does not have a valid
1180 // insertion point.
1181 // FIXME: Insert dbg.value markers in the successors when appropriate.
1182 if (InsertionPt != BB->end())
1183 Builder.insertDbgValueIntrinsic(APN, 0, DIVar, DIExpr, DDI->getDebugLoc(),
1184 &*InsertionPt);
Keith Walkerc9412522016-09-19 09:49:30 +00001185}
1186
Adrian Prantl232897f2014-04-25 23:00:25 +00001187/// Determine whether this alloca is either a VLA or an array.
1188static bool isArray(AllocaInst *AI) {
1189 return AI->isArrayAllocation() ||
1190 AI->getType()->getElementType()->isArrayTy();
1191}
1192
Devang Patelaad34d82011-03-17 22:18:16 +00001193/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1194/// of llvm.dbg.value intrinsics.
1195bool llvm::LowerDbgDeclare(Function &F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001196 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Devang Patelaad34d82011-03-17 22:18:16 +00001197 SmallVector<DbgDeclareInst *, 4> Dbgs;
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001198 for (auto &FI : F)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001199 for (Instruction &BI : FI)
1200 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Devang Patelaad34d82011-03-17 22:18:16 +00001201 Dbgs.push_back(DDI);
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001202
Devang Patelaad34d82011-03-17 22:18:16 +00001203 if (Dbgs.empty())
1204 return false;
1205
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001206 for (auto &I : Dbgs) {
1207 DbgDeclareInst *DDI = I;
Adrian Prantl8e10fdb2013-11-18 23:04:38 +00001208 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1209 // If this is an alloca for a scalar variable, insert a dbg.value
1210 // at each load and store to the alloca and erase the dbg.declare.
Adrian Prantl32da8892014-04-25 20:49:25 +00001211 // The dbg.values allow tracking a variable even if it is not
1212 // stored on the stack, while the dbg.declare can only describe
1213 // the stack slot (and at a lexical-scope granularity). Later
1214 // passes will attempt to elide the stack slot.
Adrian Prantl232897f2014-04-25 23:00:25 +00001215 if (AI && !isArray(AI)) {
Keno Fischer1dd319f2016-01-14 19:12:27 +00001216 for (auto &AIUse : AI->uses()) {
1217 User *U = AIUse.getUser();
1218 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1219 if (AIUse.getOperandNo() == 1)
1220 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1221 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Devang Patel2c7ee272011-03-18 23:45:43 +00001222 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Keno Fischer1dd319f2016-01-14 19:12:27 +00001223 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +00001224 // This is a call by-value or some other instruction that
1225 // takes a pointer to the variable. Insert a *value*
1226 // intrinsic that describes the alloca.
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001227 SmallVector<uint64_t, 1> NewDIExpr;
1228 auto *DIExpr = DDI->getExpression();
1229 NewDIExpr.push_back(dwarf::DW_OP_deref);
1230 NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001231 DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001232 DIB.createExpression(NewDIExpr),
1233 DDI->getDebugLoc(), CI);
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001234 }
Keno Fischer1dd319f2016-01-14 19:12:27 +00001235 }
Adrian Prantl32da8892014-04-25 20:49:25 +00001236 DDI->eraseFromParent();
Devang Patelaad34d82011-03-17 22:18:16 +00001237 }
Devang Patelaad34d82011-03-17 22:18:16 +00001238 }
1239 return true;
1240}
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001241
1242/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1243/// alloca 'V', if any.
1244DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001245 if (auto *L = LocalAsMetadata::getIfExists(V))
1246 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1247 for (User *U : MDV->users())
1248 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1249 return DDI;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001250
Craig Topperf40110f2014-04-25 05:29:35 +00001251 return nullptr;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001252}
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001253
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001254void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
Keith Walkerba159892016-09-22 14:13:25 +00001255 if (auto *L = LocalAsMetadata::getIfExists(V))
1256 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1257 for (User *U : MDV->users())
1258 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001259 DbgValues.push_back(DVI);
Keith Walkerba159892016-09-22 14:13:25 +00001260}
1261
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001262static void DIExprAddDeref(SmallVectorImpl<uint64_t> &Expr) {
1263 Expr.push_back(dwarf::DW_OP_deref);
1264}
1265
1266static void DIExprAddOffset(SmallVectorImpl<uint64_t> &Expr, int Offset) {
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001267 if (Offset > 0) {
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001268 Expr.push_back(dwarf::DW_OP_plus);
1269 Expr.push_back(Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001270 } else if (Offset < 0) {
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001271 Expr.push_back(dwarf::DW_OP_minus);
1272 Expr.push_back(-Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001273 }
1274}
1275
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001276static DIExpression *BuildReplacementDIExpr(DIBuilder &Builder,
1277 DIExpression *DIExpr, bool Deref,
1278 int Offset) {
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001279 if (!Deref && !Offset)
1280 return DIExpr;
1281 // Create a copy of the original DIDescriptor for user variable, prepending
1282 // "deref" operation to a list of address elements, as new llvm.dbg.declare
1283 // will take a value storing address of the memory for variable, not
1284 // alloca itself.
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001285 SmallVector<uint64_t, 4> NewDIExpr;
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001286 if (Deref)
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001287 DIExprAddDeref(NewDIExpr);
1288 DIExprAddOffset(NewDIExpr, Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001289 if (DIExpr)
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001290 NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1291 return Builder.createExpression(NewDIExpr);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001292}
1293
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001294bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1295 Instruction *InsertBefore, DIBuilder &Builder,
1296 bool Deref, int Offset) {
1297 DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001298 if (!DDI)
1299 return false;
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001300 DebugLoc Loc = DDI->getDebugLoc();
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001301 auto *DIVar = DDI->getVariable();
1302 auto *DIExpr = DDI->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001303 assert(DIVar && "Missing variable");
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001304
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001305 DIExpr = BuildReplacementDIExpr(Builder, DIExpr, Deref, Offset);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001306
Evgeniy Stepanovd8b86f72015-09-29 00:30:19 +00001307 // Insert llvm.dbg.declare immediately after the original alloca, and remove
1308 // old llvm.dbg.declare.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001309 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001310 DDI->eraseFromParent();
1311 return true;
1312}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001313
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001314bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1315 DIBuilder &Builder, bool Deref, int Offset) {
1316 return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1317 Deref, Offset);
1318}
1319
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001320static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1321 DIBuilder &Builder, int Offset) {
1322 DebugLoc Loc = DVI->getDebugLoc();
1323 auto *DIVar = DVI->getVariable();
1324 auto *DIExpr = DVI->getExpression();
1325 assert(DIVar && "Missing variable");
1326
1327 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1328 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1329 // it and give up.
1330 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1331 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1332 return;
1333
1334 // Insert the offset immediately after the first deref.
1335 // We could just change the offset argument of dbg.value, but it's unsigned...
1336 if (Offset) {
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001337 SmallVector<uint64_t, 4> NewDIExpr;
1338 DIExprAddDeref(NewDIExpr);
1339 DIExprAddOffset(NewDIExpr, Offset);
1340 NewDIExpr.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1341 DIExpr = Builder.createExpression(NewDIExpr);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001342 }
1343
1344 Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr,
1345 Loc, DVI);
1346 DVI->eraseFromParent();
1347}
1348
1349void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1350 DIBuilder &Builder, int Offset) {
1351 if (auto *L = LocalAsMetadata::getIfExists(AI))
1352 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1353 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1354 Use &U = *UI++;
1355 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1356 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1357 }
1358}
1359
David Majnemer35c46d32016-01-24 05:26:18 +00001360unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1361 unsigned NumDeadInst = 0;
1362 // Delete the instructions backwards, as it has a reduced likelihood of
1363 // having to update as many def-use and use-def chains.
1364 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001365 while (EndInst != &BB->front()) {
David Majnemer35c46d32016-01-24 05:26:18 +00001366 // Delete the next to last instruction.
1367 Instruction *Inst = &*--EndInst->getIterator();
1368 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1369 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1370 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1371 EndInst = Inst;
1372 continue;
1373 }
1374 if (!isa<DbgInfoIntrinsic>(Inst))
1375 ++NumDeadInst;
1376 Inst->eraseFromParent();
1377 }
1378 return NumDeadInst;
1379}
1380
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001381unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1382 bool PreserveLCSSA) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001383 BasicBlock *BB = I->getParent();
1384 // Loop over all of the successors, removing BB's entry from any PHI
1385 // nodes.
David Majnemer9f506252016-06-25 08:34:38 +00001386 for (BasicBlock *Successor : successors(BB))
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001387 Successor->removePredecessor(BB, PreserveLCSSA);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001388
David Majnemere14e7bc2016-06-25 08:19:55 +00001389 // Insert a call to llvm.trap right before this. This turns the undefined
1390 // behavior into a hard fail instead of falling through into random code.
1391 if (UseLLVMTrap) {
1392 Function *TrapFn =
1393 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1394 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1395 CallTrap->setDebugLoc(I->getDebugLoc());
1396 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001397 new UnreachableInst(I->getContext(), I);
1398
1399 // All instructions after this are dead.
David Majnemer88542a02016-01-24 06:26:47 +00001400 unsigned NumInstrsRemoved = 0;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001401 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001402 while (BBI != BBE) {
1403 if (!BBI->use_empty())
1404 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1405 BB->getInstList().erase(BBI++);
David Majnemer88542a02016-01-24 06:26:47 +00001406 ++NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001407 }
David Majnemer88542a02016-01-24 06:26:47 +00001408 return NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001409}
1410
1411/// changeToCall - Convert the specified invoke into a normal call.
1412static void changeToCall(InvokeInst *II) {
Sanjoy Dasccd14562015-12-10 06:39:02 +00001413 SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
Sanjoy Das8a954a02015-12-08 22:26:08 +00001414 SmallVector<OperandBundleDef, 1> OpBundles;
1415 II->getOperandBundlesAsDefs(OpBundles);
1416 CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1417 "", II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001418 NewCall->takeName(II);
1419 NewCall->setCallingConv(II->getCallingConv());
1420 NewCall->setAttributes(II->getAttributes());
1421 NewCall->setDebugLoc(II->getDebugLoc());
1422 II->replaceAllUsesWith(NewCall);
1423
1424 // Follow the call by a branch to the normal destination.
1425 BranchInst::Create(II->getNormalDest(), II);
1426
1427 // Update PHI nodes in the unwind destination
1428 II->getUnwindDest()->removePredecessor(II->getParent());
1429 II->eraseFromParent();
1430}
1431
Kuba Breckaddfdba32016-11-14 21:41:13 +00001432BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1433 BasicBlock *UnwindEdge) {
1434 BasicBlock *BB = CI->getParent();
1435
1436 // Convert this function call into an invoke instruction. First, split the
1437 // basic block.
1438 BasicBlock *Split =
1439 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1440
1441 // Delete the unconditional branch inserted by splitBasicBlock
1442 BB->getInstList().pop_back();
1443
1444 // Create the new invoke instruction.
1445 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1446 SmallVector<OperandBundleDef, 1> OpBundles;
1447
1448 CI->getOperandBundlesAsDefs(OpBundles);
1449
1450 // Note: we're round tripping operand bundles through memory here, and that
1451 // can potentially be avoided with a cleverer API design that we do not have
1452 // as of this time.
1453
1454 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
1455 InvokeArgs, OpBundles, CI->getName(), BB);
1456 II->setDebugLoc(CI->getDebugLoc());
1457 II->setCallingConv(CI->getCallingConv());
1458 II->setAttributes(CI->getAttributes());
1459
1460 // Make sure that anything using the call now uses the invoke! This also
1461 // updates the CallGraph if present, because it uses a WeakVH.
1462 CI->replaceAllUsesWith(II);
1463
1464 // Delete the original call
1465 Split->getInstList().pop_front();
1466 return Split;
1467}
1468
David Majnemer7fddecc2015-06-17 20:52:32 +00001469static bool markAliveBlocks(Function &F,
Craig Topper71b7b682014-08-21 05:55:13 +00001470 SmallPtrSetImpl<BasicBlock*> &Reachable) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001471
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001472 SmallVector<BasicBlock*, 128> Worklist;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001473 BasicBlock *BB = &F.front();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001474 Worklist.push_back(BB);
1475 Reachable.insert(BB);
1476 bool Changed = false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001477 do {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001478 BB = Worklist.pop_back_val();
1479
1480 // Do a quick scan of the basic block, turning any obviously unreachable
1481 // instructions into LLVM unreachable insts. The instruction combining pass
1482 // canonicalizes unreachable insts into stores to null or undef.
David Majnemer9f506252016-06-25 08:34:38 +00001483 for (Instruction &I : *BB) {
Hal Finkel93046912014-07-25 21:13:35 +00001484 // Assumptions that are known to be false are equivalent to unreachable.
1485 // Also, if the condition is undefined, then we make the choice most
1486 // beneficial to the optimizer, and choose that to also be unreachable.
David Majnemer9f506252016-06-25 08:34:38 +00001487 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
Hal Finkel93046912014-07-25 21:13:35 +00001488 if (II->getIntrinsicID() == Intrinsic::assume) {
David Majnemer9f506252016-06-25 08:34:38 +00001489 if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001490 // Don't insert a call to llvm.trap right before the unreachable.
David Majnemer9f506252016-06-25 08:34:38 +00001491 changeToUnreachable(II, false);
Hal Finkel93046912014-07-25 21:13:35 +00001492 Changed = true;
1493 break;
1494 }
1495 }
1496
Sanjoy Das54a3a002016-04-21 05:09:12 +00001497 if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
1498 // A call to the guard intrinsic bails out of the current compilation
1499 // unit if the predicate passed to it is false. If the predicate is a
1500 // constant false, then we know the guard will bail out of the current
1501 // compile unconditionally, so all code following it is dead.
1502 //
1503 // Note: unlike in llvm.assume, it is not "obviously profitable" for
1504 // guards to treat `undef` as `false` since a guard on `undef` can
1505 // still be useful for widening.
David Majnemer9f506252016-06-25 08:34:38 +00001506 if (match(II->getArgOperand(0), m_Zero()))
1507 if (!isa<UnreachableInst>(II->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001508 changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
Sanjoy Das54a3a002016-04-21 05:09:12 +00001509 Changed = true;
1510 break;
1511 }
1512 }
1513 }
1514
David Majnemer9f506252016-06-25 08:34:38 +00001515 if (auto *CI = dyn_cast<CallInst>(&I)) {
David Majnemer1fea77c2016-06-25 07:37:27 +00001516 Value *Callee = CI->getCalledValue();
1517 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001518 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemer1fea77c2016-06-25 07:37:27 +00001519 Changed = true;
1520 break;
1521 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001522 if (CI->doesNotReturn()) {
1523 // If we found a call to a no-return function, insert an unreachable
1524 // instruction after it. Make sure there isn't *already* one there
1525 // though.
David Majnemer9f506252016-06-25 08:34:38 +00001526 if (!isa<UnreachableInst>(CI->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001527 // Don't insert a call to llvm.trap right before the unreachable.
David Majnemer9f506252016-06-25 08:34:38 +00001528 changeToUnreachable(CI->getNextNode(), false);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001529 Changed = true;
1530 }
1531 break;
1532 }
1533 }
1534
1535 // Store to undef and store to null are undefined and used to signal that
1536 // they should be changed to unreachable by passes that can't modify the
1537 // CFG.
David Majnemer9f506252016-06-25 08:34:38 +00001538 if (auto *SI = dyn_cast<StoreInst>(&I)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001539 // Don't touch volatile stores.
1540 if (SI->isVolatile()) continue;
1541
1542 Value *Ptr = SI->getOperand(1);
1543
1544 if (isa<UndefValue>(Ptr) ||
1545 (isa<ConstantPointerNull>(Ptr) &&
1546 SI->getPointerAddressSpace() == 0)) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001547 changeToUnreachable(SI, true);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001548 Changed = true;
1549 break;
1550 }
1551 }
1552 }
1553
David Majnemer2fa86512016-01-05 06:27:50 +00001554 TerminatorInst *Terminator = BB->getTerminator();
1555 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1556 // Turn invokes that call 'nounwind' functions into ordinary calls.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001557 Value *Callee = II->getCalledValue();
1558 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
David Majnemere14e7bc2016-06-25 08:19:55 +00001559 changeToUnreachable(II, true);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001560 Changed = true;
David Majnemer7fddecc2015-06-17 20:52:32 +00001561 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001562 if (II->use_empty() && II->onlyReadsMemory()) {
1563 // jump to the normal destination branch.
1564 BranchInst::Create(II->getNormalDest(), II);
1565 II->getUnwindDest()->removePredecessor(II->getParent());
1566 II->eraseFromParent();
1567 } else
1568 changeToCall(II);
1569 Changed = true;
1570 }
David Majnemer2fa86512016-01-05 06:27:50 +00001571 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1572 // Remove catchpads which cannot be reached.
David Majnemer59eb7332016-01-05 07:42:17 +00001573 struct CatchPadDenseMapInfo {
1574 static CatchPadInst *getEmptyKey() {
1575 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
1576 }
1577 static CatchPadInst *getTombstoneKey() {
1578 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
1579 }
1580 static unsigned getHashValue(CatchPadInst *CatchPad) {
1581 return static_cast<unsigned>(hash_combine_range(
1582 CatchPad->value_op_begin(), CatchPad->value_op_end()));
1583 }
1584 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
1585 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1586 RHS == getEmptyKey() || RHS == getTombstoneKey())
1587 return LHS == RHS;
1588 return LHS->isIdenticalTo(RHS);
1589 }
1590 };
1591
1592 // Set of unique CatchPads.
1593 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
1594 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
1595 HandlerSet;
1596 detail::DenseSetEmpty Empty;
David Majnemer2fa86512016-01-05 06:27:50 +00001597 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
1598 E = CatchSwitch->handler_end();
1599 I != E; ++I) {
1600 BasicBlock *HandlerBB = *I;
David Majnemer59eb7332016-01-05 07:42:17 +00001601 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
1602 if (!HandlerSet.insert({CatchPad, Empty}).second) {
David Majnemer2fa86512016-01-05 06:27:50 +00001603 CatchSwitch->removeHandler(I);
1604 --I;
1605 --E;
1606 Changed = true;
1607 }
1608 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001609 }
1610
1611 Changed |= ConstantFoldTerminator(BB, true);
David Majnemer9f506252016-06-25 08:34:38 +00001612 for (BasicBlock *Successor : successors(BB))
1613 if (Reachable.insert(Successor).second)
1614 Worklist.push_back(Successor);
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001615 } while (!Worklist.empty());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001616 return Changed;
1617}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001618
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00001619void llvm::removeUnwindEdge(BasicBlock *BB) {
1620 TerminatorInst *TI = BB->getTerminator();
1621
1622 if (auto *II = dyn_cast<InvokeInst>(TI)) {
1623 changeToCall(II);
1624 return;
1625 }
1626
1627 TerminatorInst *NewTI;
1628 BasicBlock *UnwindDest;
1629
1630 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1631 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
1632 UnwindDest = CRI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00001633 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1634 auto *NewCatchSwitch = CatchSwitchInst::Create(
1635 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
1636 CatchSwitch->getName(), CatchSwitch);
1637 for (BasicBlock *PadBB : CatchSwitch->handlers())
1638 NewCatchSwitch->addHandler(PadBB);
1639
1640 NewTI = NewCatchSwitch;
1641 UnwindDest = CatchSwitch->getUnwindDest();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00001642 } else {
1643 llvm_unreachable("Could not find unwind successor");
1644 }
1645
1646 NewTI->takeName(TI);
1647 NewTI->setDebugLoc(TI->getDebugLoc());
1648 UnwindDest->removePredecessor(BB);
David Majnemer8a1c45d2015-12-12 05:38:55 +00001649 TI->replaceAllUsesWith(NewTI);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00001650 TI->eraseFromParent();
1651}
1652
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001653/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1654/// if they are in a dead cycle. Return true if a change was made, false
1655/// otherwise.
Igor Laevsky87f0d0e2016-06-16 16:25:53 +00001656bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001657 SmallPtrSet<BasicBlock*, 16> Reachable;
David Majnemer7fddecc2015-06-17 20:52:32 +00001658 bool Changed = markAliveBlocks(F, Reachable);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001659
1660 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001661 if (Reachable.size() == F.size())
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001662 return Changed;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001663
1664 assert(Reachable.size() < F.size());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001665 NumRemoved += F.size()-Reachable.size();
1666
1667 // Loop over all of the basic blocks that are not reachable, dropping all of
1668 // their internal references...
1669 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001670 if (Reachable.count(&*BB))
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001671 continue;
1672
David Majnemer9f506252016-06-25 08:34:38 +00001673 for (BasicBlock *Successor : successors(&*BB))
1674 if (Reachable.count(Successor))
1675 Successor->removePredecessor(&*BB);
David Majnemerd9833ea2016-01-10 07:13:04 +00001676 if (LVI)
1677 LVI->eraseBlock(&*BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001678 BB->dropAllReferences();
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001679 }
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00001680
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001681 for (Function::iterator I = ++F.begin(); I != F.end();)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001682 if (!Reachable.count(&*I))
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00001683 I = F.getBasicBlockList().erase(I);
1684 else
1685 ++I;
1686
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001687 return true;
1688}
Rafael Espindolaea46c322014-08-15 15:46:38 +00001689
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001690void llvm::combineMetadata(Instruction *K, const Instruction *J,
1691 ArrayRef<unsigned> KnownIDs) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001692 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001693 K->dropUnknownNonDebugMetadata(KnownIDs);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001694 K->getAllMetadataOtherThanDebugLoc(Metadata);
David Majnemer6f014d32016-07-25 02:21:19 +00001695 for (const auto &MD : Metadata) {
1696 unsigned Kind = MD.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001697 MDNode *JMD = J->getMetadata(Kind);
David Majnemer6f014d32016-07-25 02:21:19 +00001698 MDNode *KMD = MD.second;
Rafael Espindolaea46c322014-08-15 15:46:38 +00001699
1700 switch (Kind) {
1701 default:
1702 K->setMetadata(Kind, nullptr); // Remove unknown metadata
1703 break;
1704 case LLVMContext::MD_dbg:
1705 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1706 case LLVMContext::MD_tbaa:
1707 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1708 break;
1709 case LLVMContext::MD_alias_scope:
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +00001710 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1711 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00001712 case LLVMContext::MD_noalias:
Hal Finkele4c0c162016-04-26 02:06:06 +00001713 case LLVMContext::MD_mem_parallel_loop_access:
Rafael Espindolaea46c322014-08-15 15:46:38 +00001714 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1715 break;
1716 case LLVMContext::MD_range:
1717 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1718 break;
1719 case LLVMContext::MD_fpmath:
1720 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1721 break;
1722 case LLVMContext::MD_invariant_load:
1723 // Only set the !invariant.load if it is present in both instructions.
1724 K->setMetadata(Kind, JMD);
1725 break;
Philip Reamesd7c21362014-10-21 21:02:19 +00001726 case LLVMContext::MD_nonnull:
1727 // Only set the !nonnull if it is present in both instructions.
1728 K->setMetadata(Kind, JMD);
1729 break;
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001730 case LLVMContext::MD_invariant_group:
1731 // Preserve !invariant.group in K.
1732 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001733 case LLVMContext::MD_align:
1734 K->setMetadata(Kind,
1735 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1736 break;
1737 case LLVMContext::MD_dereferenceable:
1738 case LLVMContext::MD_dereferenceable_or_null:
1739 K->setMetadata(Kind,
1740 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1741 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00001742 }
1743 }
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001744 // Set !invariant.group from J if J has it. If both instructions have it
1745 // then we will just pick it from J - even when they are different.
1746 // Also make sure that K is load or store - f.e. combining bitcast with load
1747 // could produce bitcast with invariant.group metadata, which is invalid.
1748 // FIXME: we should try to preserve both invariant.group md if they are
1749 // different, but right now instruction can only have one invariant.group.
1750 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
1751 if (isa<LoadInst>(K) || isa<StoreInst>(K))
1752 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001753}
Philip Reames7c78ef72015-05-22 23:53:24 +00001754
Eli Friedman02419a92016-08-08 04:10:22 +00001755void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) {
1756 unsigned KnownIDs[] = {
1757 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1758 LLVMContext::MD_noalias, LLVMContext::MD_range,
1759 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
1760 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
1761 LLVMContext::MD_dereferenceable,
1762 LLVMContext::MD_dereferenceable_or_null};
1763 combineMetadata(K, J, KnownIDs);
1764}
1765
Philip Reames7c78ef72015-05-22 23:53:24 +00001766unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1767 DominatorTree &DT,
1768 const BasicBlockEdge &Root) {
1769 assert(From->getType() == To->getType());
1770
1771 unsigned Count = 0;
1772 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1773 UI != UE; ) {
1774 Use &U = *UI++;
1775 if (DT.dominates(Root, U)) {
1776 U.set(To);
1777 DEBUG(dbgs() << "Replace dominated use of '"
1778 << From->getName() << "' as "
1779 << *To << " in " << *U << "\n");
1780 ++Count;
1781 }
1782 }
1783 return Count;
1784}
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001785
1786unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1787 DominatorTree &DT,
Dehao Chendb381072016-09-08 15:25:12 +00001788 const BasicBlock *BB) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001789 assert(From->getType() == To->getType());
1790
1791 unsigned Count = 0;
1792 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1793 UI != UE;) {
1794 Use &U = *UI++;
1795 auto *I = cast<Instruction>(U.getUser());
Dehao Chendb381072016-09-08 15:25:12 +00001796 if (DT.properlyDominates(BB, I->getParent())) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001797 U.set(To);
1798 DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
1799 << *To << " in " << *U << "\n");
1800 ++Count;
1801 }
1802 }
1803 return Count;
1804}
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00001805
1806bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00001807 // Check if the function is specifically marked as a gc leaf function.
Manuel Jacob3eedd112016-01-05 23:59:08 +00001808 if (CS.hasFnAttr("gc-leaf-function"))
1809 return true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001810 if (const Function *F = CS.getCalledFunction()) {
1811 if (F->hasFnAttribute("gc-leaf-function"))
1812 return true;
1813
1814 if (auto IID = F->getIntrinsicID())
1815 // Most LLVM intrinsics do not take safepoints.
1816 return IID != Intrinsic::experimental_gc_statepoint &&
1817 IID != Intrinsic::experimental_deoptimize;
1818 }
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00001819
1820 return false;
1821}
James Molloyf01488e2016-01-15 09:20:19 +00001822
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001823namespace {
James Molloyf01488e2016-01-15 09:20:19 +00001824/// A potential constituent of a bitreverse or bswap expression. See
1825/// collectBitParts for a fuller explanation.
1826struct BitPart {
1827 BitPart(Value *P, unsigned BW) : Provider(P) {
1828 Provenance.resize(BW);
1829 }
1830
1831 /// The Value that this is a bitreverse/bswap of.
1832 Value *Provider;
1833 /// The "provenance" of each bit. Provenance[A] = B means that bit A
1834 /// in Provider becomes bit B in the result of this expression.
1835 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
1836
1837 enum { Unset = -1 };
1838};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001839} // end anonymous namespace
James Molloyf01488e2016-01-15 09:20:19 +00001840
1841/// Analyze the specified subexpression and see if it is capable of providing
1842/// pieces of a bswap or bitreverse. The subexpression provides a potential
1843/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1844/// the output of the expression came from a corresponding bit in some other
1845/// value. This function is recursive, and the end result is a mapping of
1846/// bitnumber to bitnumber. It is the caller's responsibility to validate that
1847/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
1848///
1849/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1850/// that the expression deposits the low byte of %X into the high byte of the
1851/// result and that all other bits are zero. This expression is accepted and a
1852/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
1853/// [0-7].
1854///
1855/// To avoid revisiting values, the BitPart results are memoized into the
1856/// provided map. To avoid unnecessary copying of BitParts, BitParts are
1857/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
1858/// store BitParts objects, not pointers. As we need the concept of a nullptr
1859/// BitParts (Value has been analyzed and the analysis failed), we an Optional
1860/// type instead to provide the same functionality.
1861///
1862/// Because we pass around references into \c BPS, we must use a container that
1863/// does not invalidate internal references (std::map instead of DenseMap).
1864///
1865static const Optional<BitPart> &
1866collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
1867 std::map<Value *, Optional<BitPart>> &BPS) {
1868 auto I = BPS.find(V);
1869 if (I != BPS.end())
1870 return I->second;
1871
1872 auto &Result = BPS[V] = None;
1873 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1874
1875 if (Instruction *I = dyn_cast<Instruction>(V)) {
1876 // If this is an or instruction, it may be an inner node of the bswap.
1877 if (I->getOpcode() == Instruction::Or) {
1878 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
1879 MatchBitReversals, BPS);
1880 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
1881 MatchBitReversals, BPS);
1882 if (!A || !B)
1883 return Result;
1884
1885 // Try and merge the two together.
1886 if (!A->Provider || A->Provider != B->Provider)
1887 return Result;
1888
1889 Result = BitPart(A->Provider, BitWidth);
1890 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
1891 if (A->Provenance[i] != BitPart::Unset &&
1892 B->Provenance[i] != BitPart::Unset &&
1893 A->Provenance[i] != B->Provenance[i])
1894 return Result = None;
1895
1896 if (A->Provenance[i] == BitPart::Unset)
1897 Result->Provenance[i] = B->Provenance[i];
1898 else
1899 Result->Provenance[i] = A->Provenance[i];
1900 }
1901
1902 return Result;
1903 }
1904
1905 // If this is a logical shift by a constant, recurse then shift the result.
1906 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1907 unsigned BitShift =
1908 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1909 // Ensure the shift amount is defined.
1910 if (BitShift > BitWidth)
1911 return Result;
1912
1913 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1914 MatchBitReversals, BPS);
1915 if (!Res)
1916 return Result;
1917 Result = Res;
1918
1919 // Perform the "shift" on BitProvenance.
1920 auto &P = Result->Provenance;
1921 if (I->getOpcode() == Instruction::Shl) {
1922 P.erase(std::prev(P.end(), BitShift), P.end());
1923 P.insert(P.begin(), BitShift, BitPart::Unset);
1924 } else {
1925 P.erase(P.begin(), std::next(P.begin(), BitShift));
1926 P.insert(P.end(), BitShift, BitPart::Unset);
1927 }
1928
1929 return Result;
1930 }
1931
1932 // If this is a logical 'and' with a mask that clears bits, recurse then
1933 // unset the appropriate bits.
1934 if (I->getOpcode() == Instruction::And &&
1935 isa<ConstantInt>(I->getOperand(1))) {
1936 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
1937 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1938
1939 // Check that the mask allows a multiple of 8 bits for a bswap, for an
1940 // early exit.
1941 unsigned NumMaskedBits = AndMask.countPopulation();
1942 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
1943 return Result;
1944
1945 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1946 MatchBitReversals, BPS);
1947 if (!Res)
1948 return Result;
1949 Result = Res;
1950
1951 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
1952 // If the AndMask is zero for this bit, clear the bit.
1953 if ((AndMask & Bit) == 0)
1954 Result->Provenance[i] = BitPart::Unset;
Chad Rosiere5819e22016-05-26 14:58:51 +00001955 return Result;
1956 }
James Molloyf01488e2016-01-15 09:20:19 +00001957
Chad Rosiere5819e22016-05-26 14:58:51 +00001958 // If this is a zext instruction zero extend the result.
1959 if (I->getOpcode() == Instruction::ZExt) {
1960 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1961 MatchBitReversals, BPS);
1962 if (!Res)
1963 return Result;
1964
1965 Result = BitPart(Res->Provider, BitWidth);
1966 auto NarrowBitWidth =
1967 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
1968 for (unsigned i = 0; i < NarrowBitWidth; ++i)
1969 Result->Provenance[i] = Res->Provenance[i];
1970 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
1971 Result->Provenance[i] = BitPart::Unset;
James Molloyf01488e2016-01-15 09:20:19 +00001972 return Result;
1973 }
1974 }
1975
1976 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1977 // the input value to the bswap/bitreverse.
1978 Result = BitPart(V, BitWidth);
1979 for (unsigned i = 0; i < BitWidth; ++i)
1980 Result->Provenance[i] = i;
1981 return Result;
1982}
1983
1984static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
1985 unsigned BitWidth) {
1986 if (From % 8 != To % 8)
1987 return false;
1988 // Convert from bit indices to byte indices and check for a byte reversal.
1989 From >>= 3;
1990 To >>= 3;
1991 BitWidth >>= 3;
1992 return From == BitWidth - To - 1;
1993}
1994
1995static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
1996 unsigned BitWidth) {
1997 return From == BitWidth - To - 1;
1998}
1999
2000/// Given an OR instruction, check to see if this is a bitreverse
2001/// idiom. If so, insert the new intrinsic and return true.
Chad Rosiera00df492016-05-25 16:22:14 +00002002bool llvm::recognizeBSwapOrBitReverseIdiom(
James Molloyf01488e2016-01-15 09:20:19 +00002003 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2004 SmallVectorImpl<Instruction *> &InsertedInsts) {
2005 if (Operator::getOpcode(I) != Instruction::Or)
2006 return false;
2007 if (!MatchBSwaps && !MatchBitReversals)
2008 return false;
2009 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2010 if (!ITy || ITy->getBitWidth() > 128)
2011 return false; // Can't do vectors or integers > 128 bits.
2012 unsigned BW = ITy->getBitWidth();
2013
Chad Rosiere5819e22016-05-26 14:58:51 +00002014 unsigned DemandedBW = BW;
2015 IntegerType *DemandedTy = ITy;
2016 if (I->hasOneUse()) {
2017 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2018 DemandedTy = cast<IntegerType>(Trunc->getType());
2019 DemandedBW = DemandedTy->getBitWidth();
2020 }
2021 }
2022
James Molloyf01488e2016-01-15 09:20:19 +00002023 // Try to find all the pieces corresponding to the bswap.
2024 std::map<Value *, Optional<BitPart>> BPS;
2025 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
2026 if (!Res)
2027 return false;
2028 auto &BitProvenance = Res->Provenance;
2029
2030 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2031 // only byteswap values with an even number of bytes.
Chad Rosiere5819e22016-05-26 14:58:51 +00002032 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2033 for (unsigned i = 0; i < DemandedBW; ++i) {
2034 OKForBSwap &=
2035 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002036 OKForBitReverse &=
Chad Rosiere5819e22016-05-26 14:58:51 +00002037 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002038 }
2039
2040 Intrinsic::ID Intrin;
2041 if (OKForBSwap && MatchBSwaps)
2042 Intrin = Intrinsic::bswap;
2043 else if (OKForBitReverse && MatchBitReversals)
2044 Intrin = Intrinsic::bitreverse;
2045 else
2046 return false;
2047
Chad Rosiere5819e22016-05-26 14:58:51 +00002048 if (ITy != DemandedTy) {
2049 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2050 Value *Provider = Res->Provider;
2051 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2052 // We may need to truncate the provider.
2053 if (DemandedTy != ProviderTy) {
2054 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2055 "trunc", I);
2056 InsertedInsts.push_back(Trunc);
2057 Provider = Trunc;
2058 }
2059 auto *CI = CallInst::Create(F, Provider, "rev", I);
2060 InsertedInsts.push_back(CI);
2061 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2062 InsertedInsts.push_back(ExtInst);
2063 return true;
2064 }
2065
James Molloyf01488e2016-01-15 09:20:19 +00002066 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2067 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2068 return true;
2069}
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002070
2071// CodeGen has special handling for some string functions that may replace
2072// them with target-specific intrinsics. Since that'd skip our interceptors
2073// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2074// we mark affected calls as NoBuiltin, which will disable optimization
2075// in CodeGen.
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002076void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2077 CallInst *CI, const TargetLibraryInfo *TLI) {
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002078 Function *F = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002079 LibFunc Func;
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002080 if (F && !F->hasLocalLinkage() && F->hasName() &&
2081 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2082 !F->doesNotAccessMemory())
2083 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::NoBuiltin);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002084}