blob: eabf4bfa422dad3532d96b737076e46e57f8ba1f [file] [log] [blame]
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001//===- Local.cpp - Functions to perform local transformations -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00008//
9// This family of functions perform various local transformations to the
10// program.
11//
12//===----------------------------------------------------------------------===//
13
David Blaikie31b98d22018-06-04 21:23:21 +000014#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000015#include "llvm/ADT/APInt.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000017#include "llvm/ADT/DenseMapInfo.h"
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +000018#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000020#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +000022#include "llvm/ADT/STLExtras.h"
Fiona Glaserf74cc402015-09-28 18:56:07 +000023#include "llvm/ADT/SetVector.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000024#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000025#include "llvm/ADT/SmallVector.h"
Peter Collingbourne8d642de2013-08-12 22:38:43 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000027#include "llvm/ADT/TinyPtrVector.h"
28#include "llvm/Analysis/ConstantFolding.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000029#include "llvm/Analysis/DomTreeUpdater.h"
David Majnemer70497c62015-12-02 23:06:39 +000030#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Analysis/InstructionSimplify.h"
David Majnemerd9833ea2016-01-10 07:13:04 +000032#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/Analysis/MemoryBuiltins.h"
Alina Sbirlea2ab544b2018-08-16 21:58:44 +000034#include "llvm/Analysis/MemorySSAUpdater.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/ValueTracking.h"
Michael Kruse978ba612018-12-20 04:58:07 +000037#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000038#include "llvm/BinaryFormat/Dwarf.h"
39#include "llvm/IR/Argument.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000042#include "llvm/IR/CFG.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000043#include "llvm/IR/CallSite.h"
44#include "llvm/IR/Constant.h"
Chandler Carruth2abb65a2017-06-26 03:31:31 +000045#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000047#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/DataLayout.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000049#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000054#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000055#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
61#include "llvm/IR/Intrinsics.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000062#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/MDBuilder.h"
64#include "llvm/IR/Metadata.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000065#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Operator.h"
David Majnemer9f506252016-06-25 08:34:38 +000067#include "llvm/IR/PatternMatch.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000073#include "llvm/Support/Casting.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000074#include "llvm/Support/Debug.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000075#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000076#include "llvm/Support/KnownBits.h"
Chris Lattnercbd18fc2009-11-10 05:59:26 +000077#include "llvm/Support/raw_ostream.h"
Vedant Kumar6bfc8692018-01-25 21:37:05 +000078#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000079#include <algorithm>
80#include <cassert>
81#include <climits>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <utility>
86
Chris Lattner04efa4b2003-12-19 05:56:28 +000087using namespace llvm;
David Majnemer9f506252016-06-25 08:34:38 +000088using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000089
Chandler Carruthe96dd892014-04-21 22:55:11 +000090#define DEBUG_TYPE "local"
91
Peter Collingbourne8d642de2013-08-12 22:38:43 +000092STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
93
David Stuttard411488b2019-05-09 15:02:10 +000094// Max recursion depth for collectBitParts used when detecting bswap and
95// bitreverse idioms
96static const unsigned BitPartRecursionMaxDepth = 64;
97
Chris Lattner28537df2002-05-07 18:07:59 +000098//===----------------------------------------------------------------------===//
Chris Lattnerc6c481c2008-11-27 22:57:53 +000099// Local constant propagation.
Chris Lattner28537df2002-05-07 18:07:59 +0000100//
101
Frits van Bommelad964552011-05-22 16:24:18 +0000102/// ConstantFoldTerminator - If a terminator instruction is predicated on a
103/// constant value, convert it into an unconditional branch to the constant
104/// destination. This is a nontrivial operation because the successors of this
105/// basic block must have their PHI nodes updated.
106/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
107/// conditions and indirectbr addresses this might make dead if
108/// DeleteDeadConditions is true.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000109bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000110 const TargetLibraryInfo *TLI,
Chijun Sima21a8b602018-08-03 05:08:17 +0000111 DomTreeUpdater *DTU) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000112 Instruction *T = BB->getTerminator();
Devang Patel1fabbe92011-05-18 17:26:46 +0000113 IRBuilder<> Builder(T);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000114
Chris Lattner28537df2002-05-07 18:07:59 +0000115 // Branch - See if we are conditional jumping on constant
Davide Italiano0512bf52017-12-31 16:51:50 +0000116 if (auto *BI = dyn_cast<BranchInst>(T)) {
Chris Lattner28537df2002-05-07 18:07:59 +0000117 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greif97f17202009-01-30 18:21:13 +0000118 BasicBlock *Dest1 = BI->getSuccessor(0);
119 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner28537df2002-05-07 18:07:59 +0000120
Davide Italiano0512bf52017-12-31 16:51:50 +0000121 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner28537df2002-05-07 18:07:59 +0000122 // Are we branching on constant?
123 // YES. Change to unconditional branch...
Reid Spencercddc9df2007-01-12 04:24:46 +0000124 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
125 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner28537df2002-05-07 18:07:59 +0000126
Chris Lattner28537df2002-05-07 18:07:59 +0000127 // Let the basic block know that we are letting go of it. Based on this,
128 // it will adjust it's PHI nodes.
Jay Foad6a85be22011-04-19 15:23:29 +0000129 OldDest->removePredecessor(BB);
Chris Lattner28537df2002-05-07 18:07:59 +0000130
Jay Foad89afb432011-01-07 20:25:56 +0000131 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000132 Builder.CreateBr(Destination);
Jay Foad89afb432011-01-07 20:25:56 +0000133 BI->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +0000134 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000135 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
Chris Lattner28537df2002-05-07 18:07:59 +0000136 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000137 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000138
Chris Lattner54a4b842009-11-01 03:40:38 +0000139 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanb1c93172005-04-21 23:48:37 +0000140 // This branch matches something like this:
Chris Lattner28537df2002-05-07 18:07:59 +0000141 // br bool %cond, label %Dest, label %Dest
142 // and changes it into: br label %Dest
143
144 // Let the basic block know that we are letting go of one copy of it.
145 assert(BI->getParent() && "Terminator not inserted in block!");
146 Dest1->removePredecessor(BI->getParent());
147
Jay Foad89afb432011-01-07 20:25:56 +0000148 // Replace the conditional branch with an unconditional one.
Devang Patel1fabbe92011-05-18 17:26:46 +0000149 Builder.CreateBr(Dest1);
Frits van Bommelad964552011-05-22 16:24:18 +0000150 Value *Cond = BI->getCondition();
Jay Foad89afb432011-01-07 20:25:56 +0000151 BI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000152 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000153 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chris Lattner28537df2002-05-07 18:07:59 +0000154 return true;
155 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000156 return false;
157 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000158
Davide Italiano0512bf52017-12-31 16:51:50 +0000159 if (auto *SI = dyn_cast<SwitchInst>(T)) {
Hans Wennborg90b827c2015-01-26 19:52:24 +0000160 // If we are switching on a constant, we can convert the switch to an
161 // unconditional branch.
Davide Italiano0512bf52017-12-31 16:51:50 +0000162 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
Hans Wennborg90b827c2015-01-26 19:52:24 +0000163 BasicBlock *DefaultDest = SI->getDefaultDest();
164 BasicBlock *TheOnlyDest = DefaultDest;
165
166 // If the default is unreachable, ignore it when searching for TheOnlyDest.
167 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
168 SI->getNumCases() > 0) {
Chandler Carruth927d8e62017-04-12 07:27:28 +0000169 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
Hans Wennborg90b827c2015-01-26 19:52:24 +0000170 }
Chris Lattner031340a2003-08-17 19:41:53 +0000171
Chris Lattner54a4b842009-11-01 03:40:38 +0000172 // Figure out which case it goes to.
Chandler Carruth0d256c02017-03-26 02:49:23 +0000173 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chris Lattner821deee2003-08-17 20:21:14 +0000174 // Found case matching a constant operand?
Chandler Carruth927d8e62017-04-12 07:27:28 +0000175 if (i->getCaseValue() == CI) {
176 TheOnlyDest = i->getCaseSuccessor();
Chris Lattner821deee2003-08-17 20:21:14 +0000177 break;
178 }
Chris Lattner031340a2003-08-17 19:41:53 +0000179
Chris Lattnerc54d6082003-08-23 23:18:19 +0000180 // Check to see if this branch is going to the same place as the default
181 // dest. If so, eliminate it as an explicit compare.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000182 if (i->getCaseSuccessor() == DefaultDest) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000183 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Justin Bognera41a7b32013-12-10 00:13:41 +0000184 unsigned NCases = SI->getNumCases();
185 // Fold the case metadata into the default if there will be any branches
186 // left, unless the metadata doesn't match the switch.
187 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
Manman Ren49dbe252012-09-12 17:04:11 +0000188 // Collect branch weights into a vector.
189 SmallVector<uint32_t, 8> Weights;
190 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
191 ++MD_i) {
David Majnemer9f506252016-06-25 08:34:38 +0000192 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren49dbe252012-09-12 17:04:11 +0000193 Weights.push_back(CI->getValue().getZExtValue());
194 }
195 // Merge weight of this case to the default weight.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000196 unsigned idx = i->getCaseIndex();
Manman Ren49dbe252012-09-12 17:04:11 +0000197 Weights[0] += Weights[idx+1];
198 // Remove weight for this case.
199 std::swap(Weights[idx+1], Weights.back());
200 Weights.pop_back();
201 SI->setMetadata(LLVMContext::MD_prof,
202 MDBuilder(BB->getContext()).
203 createBranchWeights(Weights));
204 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000205 // Remove this entry.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000206 BasicBlock *ParentBB = SI->getParent();
207 DefaultDest->removePredecessor(ParentBB);
Chandler Carruth0d256c02017-03-26 02:49:23 +0000208 i = SI->removeCase(i);
209 e = SI->case_end();
Chijun Sima21a8b602018-08-03 05:08:17 +0000210 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000211 DTU->applyUpdatesPermissive(
212 {{DominatorTree::Delete, ParentBB, DefaultDest}});
Chris Lattnerc54d6082003-08-23 23:18:19 +0000213 continue;
214 }
215
Chris Lattner821deee2003-08-17 20:21:14 +0000216 // Otherwise, check to see if the switch only branches to one destination.
217 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
218 // destinations.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000219 if (i->getCaseSuccessor() != TheOnlyDest)
220 TheOnlyDest = nullptr;
Chandler Carruth0d256c02017-03-26 02:49:23 +0000221
222 // Increment this iterator as we haven't removed the case.
223 ++i;
Chris Lattner031340a2003-08-17 19:41:53 +0000224 }
225
Chris Lattner821deee2003-08-17 20:21:14 +0000226 if (CI && !TheOnlyDest) {
227 // Branching on a constant, but not any of the cases, go to the default
228 // successor.
229 TheOnlyDest = SI->getDefaultDest();
230 }
231
232 // If we found a single destination that we can fold the switch into, do so
233 // now.
234 if (TheOnlyDest) {
Chris Lattner54a4b842009-11-01 03:40:38 +0000235 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000236 Builder.CreateBr(TheOnlyDest);
Chris Lattner821deee2003-08-17 20:21:14 +0000237 BasicBlock *BB = SI->getParent();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000238 std::vector <DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000239 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000240 Updates.reserve(SI->getNumSuccessors() - 1);
Chris Lattner821deee2003-08-17 20:21:14 +0000241
242 // Remove entries from PHI nodes which we no longer branch to...
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000243 for (BasicBlock *Succ : successors(SI)) {
Chris Lattner821deee2003-08-17 20:21:14 +0000244 // Found case matching a constant operand?
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000245 if (Succ == TheOnlyDest) {
Craig Topperf40110f2014-04-25 05:29:35 +0000246 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000247 } else {
Chris Lattner821deee2003-08-17 20:21:14 +0000248 Succ->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +0000249 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000250 Updates.push_back({DominatorTree::Delete, BB, Succ});
251 }
Chris Lattner821deee2003-08-17 20:21:14 +0000252 }
253
Chris Lattner54a4b842009-11-01 03:40:38 +0000254 // Delete the old switch.
Frits van Bommelad964552011-05-22 16:24:18 +0000255 Value *Cond = SI->getCondition();
256 SI->eraseFromParent();
257 if (DeleteDeadConditions)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000258 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
Chijun Sima21a8b602018-08-03 05:08:17 +0000259 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000260 DTU->applyUpdatesPermissive(Updates);
Chris Lattner821deee2003-08-17 20:21:14 +0000261 return true;
Chris Lattner54a4b842009-11-01 03:40:38 +0000262 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000263
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000264 if (SI->getNumCases() == 1) {
Chris Lattner821deee2003-08-17 20:21:14 +0000265 // Otherwise, we can fold this switch into a conditional branch
266 // instruction if it has only one non-default destination.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000267 auto FirstCase = *SI->case_begin();
Bob Wilsone4077362013-09-09 19:14:35 +0000268 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
269 FirstCase.getCaseValue(), "cond");
Devang Patel1fabbe92011-05-18 17:26:46 +0000270
Bob Wilsone4077362013-09-09 19:14:35 +0000271 // Insert the new branch.
272 BranchInst *NewBr = Builder.CreateCondBr(Cond,
273 FirstCase.getCaseSuccessor(),
274 SI->getDefaultDest());
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000275 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Bob Wilsone4077362013-09-09 19:14:35 +0000276 if (MD && MD->getNumOperands() == 3) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000277 ConstantInt *SICase =
278 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
279 ConstantInt *SIDef =
280 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
Bob Wilsone4077362013-09-09 19:14:35 +0000281 assert(SICase && SIDef);
282 // The TrueWeight should be the weight for the single case of SI.
283 NewBr->setMetadata(LLVMContext::MD_prof,
284 MDBuilder(BB->getContext()).
285 createBranchWeights(SICase->getValue().getZExtValue(),
286 SIDef->getValue().getZExtValue()));
Stepan Dyatkovskiy7a501552012-05-23 08:18:26 +0000287 }
Bob Wilsone4077362013-09-09 19:14:35 +0000288
Chen Lieafbc9d2015-08-07 19:30:12 +0000289 // Update make.implicit metadata to the newly-created conditional branch.
290 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
291 if (MakeImplicitMD)
292 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
293
Bob Wilsone4077362013-09-09 19:14:35 +0000294 // Delete the old switch.
295 SI->eraseFromParent();
296 return true;
Chris Lattner821deee2003-08-17 20:21:14 +0000297 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000298 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000299 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000300
Davide Italiano0512bf52017-12-31 16:51:50 +0000301 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
Chris Lattner54a4b842009-11-01 03:40:38 +0000302 // indirectbr blockaddress(@F, @BB) -> br label @BB
Davide Italiano0512bf52017-12-31 16:51:50 +0000303 if (auto *BA =
Chris Lattner54a4b842009-11-01 03:40:38 +0000304 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
305 BasicBlock *TheOnlyDest = BA->getBasicBlock();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000306 std::vector <DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000307 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000308 Updates.reserve(IBI->getNumDestinations() - 1);
309
Chris Lattner54a4b842009-11-01 03:40:38 +0000310 // Insert the new branch.
Devang Patel1fabbe92011-05-18 17:26:46 +0000311 Builder.CreateBr(TheOnlyDest);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000312
Chris Lattner54a4b842009-11-01 03:40:38 +0000313 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000314 if (IBI->getDestination(i) == TheOnlyDest) {
Craig Topperf40110f2014-04-25 05:29:35 +0000315 TheOnlyDest = nullptr;
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000316 } else {
317 BasicBlock *ParentBB = IBI->getParent();
318 BasicBlock *DestBB = IBI->getDestination(i);
319 DestBB->removePredecessor(ParentBB);
Chijun Sima21a8b602018-08-03 05:08:17 +0000320 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000321 Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
322 }
Chris Lattner54a4b842009-11-01 03:40:38 +0000323 }
Frits van Bommelad964552011-05-22 16:24:18 +0000324 Value *Address = IBI->getAddress();
Chris Lattner54a4b842009-11-01 03:40:38 +0000325 IBI->eraseFromParent();
Frits van Bommelad964552011-05-22 16:24:18 +0000326 if (DeleteDeadConditions)
Florian Hahn0a7faa42019-07-20 12:25:47 +0000327 // Delete pointer cast instructions.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000328 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000329
Florian Hahn0a7faa42019-07-20 12:25:47 +0000330 // Also zap the blockaddress constant if there are no users remaining,
331 // otherwise the destination is still marked as having its address taken.
332 if (BA->use_empty())
333 BA->destroyConstant();
334
Chris Lattner54a4b842009-11-01 03:40:38 +0000335 // If we didn't find our destination in the IBI successor list, then we
336 // have undefined behavior. Replace the unconditional branch with an
337 // 'unreachable' instruction.
338 if (TheOnlyDest) {
339 BB->getTerminator()->eraseFromParent();
340 new UnreachableInst(BB->getContext(), BB);
341 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000342
Chijun Sima21a8b602018-08-03 05:08:17 +0000343 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000344 DTU->applyUpdatesPermissive(Updates);
Chris Lattner54a4b842009-11-01 03:40:38 +0000345 return true;
346 }
347 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000348
Chris Lattner28537df2002-05-07 18:07:59 +0000349 return false;
350}
351
Chris Lattner28537df2002-05-07 18:07:59 +0000352//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000353// Local dead code elimination.
Chris Lattner28537df2002-05-07 18:07:59 +0000354//
355
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000356/// isInstructionTriviallyDead - Return true if the result produced by the
357/// instruction is not used, and the instruction has no side effects.
358///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000359bool llvm::isInstructionTriviallyDead(Instruction *I,
360 const TargetLibraryInfo *TLI) {
Daniel Berline3e69e12017-03-10 00:32:33 +0000361 if (!I->use_empty())
362 return false;
363 return wouldInstructionBeTriviallyDead(I, TLI);
364}
365
366bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
367 const TargetLibraryInfo *TLI) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000368 if (I->isTerminator())
Daniel Berline3e69e12017-03-10 00:32:33 +0000369 return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000370
David Majnemer654e1302015-07-31 17:58:14 +0000371 // We don't want the landingpad-like instructions removed by anything this
372 // general.
373 if (I->isEHPad())
Bill Wendlingd9fb4702011-08-15 20:10:51 +0000374 return false;
375
Devang Patelc1431e62011-03-18 23:28:02 +0000376 // We don't want debug info removed by anything this general, unless
377 // debug info is empty.
378 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
Nick Lewycky99890a22011-08-02 21:19:27 +0000379 if (DDI->getAddress())
Devang Patelc1431e62011-03-18 23:28:02 +0000380 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000381 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000382 }
Devang Patel17bbd7f2011-03-21 22:04:45 +0000383 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
Devang Patelc1431e62011-03-18 23:28:02 +0000384 if (DVI->getValue())
385 return false;
Devang Patel17bbd7f2011-03-21 22:04:45 +0000386 return true;
Devang Patelc1431e62011-03-18 23:28:02 +0000387 }
Shiva Chen2c864552018-05-09 02:40:45 +0000388 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
389 if (DLI->getLabel())
390 return false;
391 return true;
392 }
Devang Patelc1431e62011-03-18 23:28:02 +0000393
Daniel Berline3e69e12017-03-10 00:32:33 +0000394 if (!I->mayHaveSideEffects())
395 return true;
Duncan Sands1efabaa2009-05-06 06:49:50 +0000396
397 // Special case intrinsics that "may have side effects" but can be deleted
398 // when dead.
Nick Lewycky99890a22011-08-02 21:19:27 +0000399 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Piotr Padlewskia26a08c2018-05-18 23:52:57 +0000400 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
401 if (II->getIntrinsicID() == Intrinsic::stacksave ||
402 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
Chris Lattnere9665832007-12-29 00:59:12 +0000403 return true;
Nick Lewycky99890a22011-08-02 21:19:27 +0000404
405 // Lifetime intrinsics are dead when their right-hand is undef.
Vedant Kumarb264d692018-12-21 21:49:40 +0000406 if (II->isLifetimeStartOrEnd())
Nick Lewycky99890a22011-08-02 21:19:27 +0000407 return isa<UndefValue>(II->getArgOperand(1));
Hal Finkel93046912014-07-25 21:13:35 +0000408
Sanjoy Das107aefc2016-04-29 22:23:16 +0000409 // Assumptions are dead if their condition is trivially true. Guards on
410 // true are operationally no-ops. In the future we can consider more
411 // sophisticated tradeoffs for guards considering potential for check
412 // widening, but for now we keep things simple.
413 if (II->getIntrinsicID() == Intrinsic::assume ||
414 II->getIntrinsicID() == Intrinsic::experimental_guard) {
Hal Finkel93046912014-07-25 21:13:35 +0000415 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
416 return !Cond->isZero();
417
418 return false;
419 }
Nick Lewycky99890a22011-08-02 21:19:27 +0000420 }
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000421
Daniel Berline3e69e12017-03-10 00:32:33 +0000422 if (isAllocLikeFn(I, TLI))
423 return true;
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000424
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000425 if (CallInst *CI = isFreeCall(I, TLI))
Nick Lewyckydd1d3df2011-10-24 04:35:36 +0000426 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
427 return C->isNullValue() || isa<UndefValue>(C);
428
Chandler Carruth751d95f2019-02-11 07:51:44 +0000429 if (auto *Call = dyn_cast<CallBase>(I))
430 if (isMathLibCallNoop(Call, TLI))
Eli Friedmanb6befc32016-11-02 20:48:11 +0000431 return true;
432
Chris Lattnera36d5252005-05-06 05:27:34 +0000433 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000434}
435
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000436/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
437/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohmancb99fe92010-01-05 15:45:31 +0000438/// trivially dead, delete them too, recursively. Return true if any
439/// instructions were deleted.
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000440bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
441 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000442 Instruction *I = dyn_cast<Instruction>(V);
Fangrui Song709a3e72019-02-10 09:25:56 +0000443 if (!I || !isInstructionTriviallyDead(I, TLI))
Dan Gohmancb99fe92010-01-05 15:45:31 +0000444 return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000445
Chris Lattnere9f6c352008-11-28 01:20:46 +0000446 SmallVector<Instruction*, 16> DeadInsts;
447 DeadInsts.push_back(I);
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000448 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000449
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000450 return true;
451}
452
453void llvm::RecursivelyDeleteTriviallyDeadInstructions(
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000454 SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
455 MemorySSAUpdater *MSSAU) {
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000456 // Process the dead instruction list until empty.
457 while (!DeadInsts.empty()) {
458 Instruction &I = *DeadInsts.pop_back_val();
459 assert(I.use_empty() && "Instructions with uses are not dead.");
460 assert(isInstructionTriviallyDead(&I, TLI) &&
461 "Live instruction found in dead worklist!");
462
463 // Don't lose the debug info while deleting the instructions.
464 salvageDebugInfo(I);
Chris Lattnerd4b5ba62008-11-28 00:58:15 +0000465
Chris Lattnere9f6c352008-11-28 01:20:46 +0000466 // Null out all of the instruction's operands to see if any operand becomes
467 // dead as we go.
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000468 for (Use &OpU : I.operands()) {
469 Value *OpV = OpU.get();
470 OpU.set(nullptr);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000471
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000472 if (!OpV->use_empty())
473 continue;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000474
Chris Lattnere9f6c352008-11-28 01:20:46 +0000475 // If the operand is an instruction that became dead as we nulled out the
476 // operand, and if it is 'trivially' dead, delete it in a future loop
477 // iteration.
478 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000479 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnere9f6c352008-11-28 01:20:46 +0000480 DeadInsts.push_back(OpI);
481 }
Alina Sbirlea2ab544b2018-08-16 21:58:44 +0000482 if (MSSAU)
483 MSSAU->removeMemoryAccess(&I);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000484
Chandler Carruth4cbcbb02018-05-29 20:15:38 +0000485 I.eraseFromParent();
486 }
Chris Lattner28537df2002-05-07 18:07:59 +0000487}
Chris Lattner99d68092008-11-27 07:43:12 +0000488
Davide Italiano8ec77092018-12-10 22:17:04 +0000489bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
490 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
491 findDbgUsers(DbgUsers, I);
492 for (auto *DII : DbgUsers) {
493 Value *Undef = UndefValue::get(I->getType());
494 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
495 ValueAsMetadata::get(Undef)));
496 }
497 return !DbgUsers.empty();
498}
499
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000500/// areAllUsesEqual - Check whether the uses of a value are all the same.
501/// This is similar to Instruction::hasOneUse() except this will also return
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000502/// true when there are no uses or multiple uses that all refer to the same
503/// value.
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000504static bool areAllUsesEqual(Instruction *I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 Value::user_iterator UI = I->user_begin();
506 Value::user_iterator UE = I->user_end();
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000507 if (UI == UE)
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000508 return true;
Nick Lewyckyc8a15692011-02-20 08:38:20 +0000509
510 User *TheUse = *UI;
511 for (++UI; UI != UE; ++UI) {
512 if (*UI != TheUse)
513 return false;
514 }
515 return true;
516}
517
Dan Gohmanff089952009-05-02 18:29:22 +0000518/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
519/// dead PHI node, due to being a def-use chain of single-use nodes that
520/// either forms a cycle or is terminated by a trivially dead instruction,
521/// delete it. If that makes any of its operands trivially dead, delete them
Duncan Sandsecbbf082011-02-21 17:32:05 +0000522/// too, recursively. Return true if a change was made.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000523bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
524 const TargetLibraryInfo *TLI) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000525 SmallPtrSet<Instruction*, 4> Visited;
526 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000527 I = cast<Instruction>(*I->user_begin())) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000528 if (I->use_empty())
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000529 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Nick Lewycky183c24c2011-02-20 18:05:56 +0000530
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000531 // If we find an instruction more than once, we're on a cycle that
Dan Gohmanff089952009-05-02 18:29:22 +0000532 // won't prove fruitful.
David Blaikie70573dc2014-11-19 07:49:26 +0000533 if (!Visited.insert(I).second) {
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000534 // Break the cycle and delete the instruction and its operands.
535 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000536 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Duncan Sandsecbbf082011-02-21 17:32:05 +0000537 return true;
Duncan Sands6dcd49b2011-02-21 16:27:36 +0000538 }
539 }
540 return false;
Dan Gohmanff089952009-05-02 18:29:22 +0000541}
Chris Lattnerc6c481c2008-11-27 22:57:53 +0000542
Fiona Glaserf74cc402015-09-28 18:56:07 +0000543static bool
544simplifyAndDCEInstruction(Instruction *I,
545 SmallSetVector<Instruction *, 16> &WorkList,
546 const DataLayout &DL,
547 const TargetLibraryInfo *TLI) {
548 if (isInstructionTriviallyDead(I, TLI)) {
Vedant Kumarf69baf62018-03-02 22:46:48 +0000549 salvageDebugInfo(*I);
550
Fiona Glaserf74cc402015-09-28 18:56:07 +0000551 // Null out all of the instruction's operands to see if any operand becomes
552 // dead as we go.
553 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
554 Value *OpV = I->getOperand(i);
555 I->setOperand(i, nullptr);
556
557 if (!OpV->use_empty() || I == OpV)
558 continue;
559
560 // If the operand is an instruction that became dead as we nulled out the
561 // operand, and if it is 'trivially' dead, delete it in a future loop
562 // iteration.
563 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
564 if (isInstructionTriviallyDead(OpI, TLI))
565 WorkList.insert(OpI);
566 }
567
568 I->eraseFromParent();
569
570 return true;
571 }
572
573 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
574 // Add the users to the worklist. CAREFUL: an instruction can use itself,
575 // in the case of a phi node.
David Majnemerb8da3a22016-06-25 00:04:10 +0000576 for (User *U : I->users()) {
577 if (U != I) {
Fiona Glaserf74cc402015-09-28 18:56:07 +0000578 WorkList.insert(cast<Instruction>(U));
David Majnemerb8da3a22016-06-25 00:04:10 +0000579 }
580 }
Fiona Glaserf74cc402015-09-28 18:56:07 +0000581
582 // Replace the instruction with its simplified value.
David Majnemerb8da3a22016-06-25 00:04:10 +0000583 bool Changed = false;
584 if (!I->use_empty()) {
585 I->replaceAllUsesWith(SimpleV);
586 Changed = true;
587 }
588 if (isInstructionTriviallyDead(I, TLI)) {
589 I->eraseFromParent();
590 Changed = true;
591 }
592 return Changed;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000593 }
594 return false;
595}
596
Chris Lattner7c743f22010-01-12 19:40:54 +0000597/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
598/// simplify any instructions in it and recursively delete dead instructions.
599///
600/// This returns true if it changed the code, note that it can delete
601/// instructions in other blocks as well in this block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000602bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000603 const TargetLibraryInfo *TLI) {
Chris Lattner7c743f22010-01-12 19:40:54 +0000604 bool MadeChange = false;
Fiona Glaserf74cc402015-09-28 18:56:07 +0000605 const DataLayout &DL = BB->getModule()->getDataLayout();
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000606
607#ifndef NDEBUG
608 // In debug builds, ensure that the terminator of the block is never replaced
609 // or deleted by these simplifications. The idea of simplification is that it
610 // cannot introduce new instructions, and there is no way to replace the
611 // terminator of a block without introducing a new instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000612 AssertingVH<Instruction> TerminatorVH(&BB->back());
Chandler Carruth0c72e3f2012-03-25 03:29:25 +0000613#endif
614
Fiona Glaserf74cc402015-09-28 18:56:07 +0000615 SmallSetVector<Instruction *, 16> WorkList;
616 // Iterate over the original function, only adding insts to the worklist
617 // if they actually need to be revisited. This avoids having to pre-init
618 // the worklist with the entire function's worth of instructions.
Chad Rosier56def252016-05-21 21:12:06 +0000619 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
620 BI != E;) {
Chandler Carruth17fc6ef2012-03-24 23:03:27 +0000621 assert(!BI->isTerminator());
Fiona Glaserf74cc402015-09-28 18:56:07 +0000622 Instruction *I = &*BI;
623 ++BI;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000624
Fiona Glaserf74cc402015-09-28 18:56:07 +0000625 // We're visiting this instruction now, so make sure it's not in the
626 // worklist from an earlier visit.
627 if (!WorkList.count(I))
628 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
629 }
Eli Friedman17bf4922011-04-02 22:45:17 +0000630
Fiona Glaserf74cc402015-09-28 18:56:07 +0000631 while (!WorkList.empty()) {
632 Instruction *I = WorkList.pop_back_val();
633 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
Chris Lattner7c743f22010-01-12 19:40:54 +0000634 }
635 return MadeChange;
636}
637
Chris Lattner99d68092008-11-27 07:43:12 +0000638//===----------------------------------------------------------------------===//
Chris Lattner852d6d62009-11-10 22:26:15 +0000639// Control Flow Graph Restructuring.
Chris Lattner99d68092008-11-27 07:43:12 +0000640//
641
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000642void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
Chijun Sima21a8b602018-08-03 05:08:17 +0000643 DomTreeUpdater *DTU) {
Chris Lattner852d6d62009-11-10 22:26:15 +0000644 // This only adjusts blocks with PHI nodes.
645 if (!isa<PHINode>(BB->begin()))
646 return;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000647
Chris Lattner852d6d62009-11-10 22:26:15 +0000648 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
649 // them down. This will leave us with single entry phi nodes and other phis
650 // that can be removed.
651 BB->removePredecessor(Pred, true);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000652
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000653 WeakTrackingVH PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000654 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
655 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
Chris Lattnere41ab072010-07-15 06:06:04 +0000656 Value *OldPhiIt = PhiIt;
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000657
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000658 if (!recursivelySimplifyInstruction(PN))
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000659 continue;
660
Chris Lattner852d6d62009-11-10 22:26:15 +0000661 // If recursive simplification ended up deleting the next PHI node we would
662 // iterate to, then our iterator is invalid, restart scanning from the top
663 // of the block.
Chris Lattnere41ab072010-07-15 06:06:04 +0000664 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
Chris Lattner852d6d62009-11-10 22:26:15 +0000665 }
Chijun Sima21a8b602018-08-03 05:08:17 +0000666 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000667 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
Chris Lattner852d6d62009-11-10 22:26:15 +0000668}
669
Chijun Sima21a8b602018-08-03 05:08:17 +0000670void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
671 DomTreeUpdater *DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000672
Chris Lattner99d68092008-11-27 07:43:12 +0000673 // If BB has single-entry PHI nodes, fold them.
674 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
675 Value *NewVal = PN->getIncomingValue(0);
676 // Replace self referencing PHI with undef, it must be dead.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000677 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner99d68092008-11-27 07:43:12 +0000678 PN->replaceAllUsesWith(NewVal);
679 PN->eraseFromParent();
680 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000681
Chris Lattner99d68092008-11-27 07:43:12 +0000682 BasicBlock *PredBB = DestBB->getSinglePredecessor();
683 assert(PredBB && "Block doesn't have a single predecessor!");
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000684
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000685 bool ReplaceEntryBB = false;
686 if (PredBB == &DestBB->getParent()->getEntryBlock())
687 ReplaceEntryBB = true;
688
Chijun Sima21a8b602018-08-03 05:08:17 +0000689 // DTU updates: Collect all the edges that enter
690 // PredBB. These dominator edges will be redirected to DestBB.
Vedant Kumar4de31bb2018-11-19 19:54:27 +0000691 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000692
693 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000694 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
695 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
696 Updates.push_back({DominatorTree::Delete, *I, PredBB});
697 // This predecessor of PredBB may already have DestBB as a successor.
698 if (llvm::find(successors(*I), DestBB) == succ_end(*I))
699 Updates.push_back({DominatorTree::Insert, *I, DestBB});
700 }
701 }
702
Chris Lattner6fbfe582010-02-15 20:47:49 +0000703 // Zap anything that took the address of DestBB. Not doing this will give the
704 // address an invalid value.
705 if (DestBB->hasAddressTaken()) {
706 BlockAddress *BA = BlockAddress::get(DestBB);
707 Constant *Replacement =
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000708 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
Chris Lattner6fbfe582010-02-15 20:47:49 +0000709 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
710 BA->getType()));
711 BA->destroyConstant();
712 }
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000713
Chris Lattner99d68092008-11-27 07:43:12 +0000714 // Anything that branched to PredBB now branches to DestBB.
715 PredBB->replaceAllUsesWith(DestBB);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000716
Jay Foad61ea0e42011-06-23 09:09:15 +0000717 // Splice all the instructions from PredBB to DestBB.
718 PredBB->getTerminator()->eraseFromParent();
Bill Wendling90dd90a2013-10-21 04:09:17 +0000719 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000720 new UnreachableInst(PredBB->getContext(), PredBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000721
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000722 // If the PredBB is the entry block of the function, move DestBB up to
723 // become the entry block after we erase PredBB.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000724 if (ReplaceEntryBB)
Owen Andersona8d1c3e2014-07-12 07:12:47 +0000725 DestBB->moveAfter(PredBB);
Evandro Menezes3701df52017-09-28 17:24:40 +0000726
Chijun Sima21a8b602018-08-03 05:08:17 +0000727 if (DTU) {
728 assert(PredBB->getInstList().size() == 1 &&
729 isa<UnreachableInst>(PredBB->getTerminator()) &&
730 "The successor list of PredBB isn't empty before "
731 "applying corresponding DTU updates.");
Chijun Sima70e97162019-02-22 13:48:38 +0000732 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +0000733 DTU->deleteBB(PredBB);
734 // Recalculation of DomTree is needed when updating a forward DomTree and
735 // the Entry BB is replaced.
736 if (ReplaceEntryBB && DTU->hasDomTree()) {
737 // The entry block was removed and there is no external interface for
738 // the dominator tree to be notified of this change. In this corner-case
739 // we recalculate the entire tree.
740 DTU->recalculate(*(DestBB->getParent()));
Balaram Makam9ee942f2017-10-26 15:04:53 +0000741 }
Evandro Menezes3701df52017-09-28 17:24:40 +0000742 }
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000743
Chijun Sima21a8b602018-08-03 05:08:17 +0000744 else {
745 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000746 }
Chris Lattner99d68092008-11-27 07:43:12 +0000747}
Devang Patelcaf44852009-02-10 07:00:59 +0000748
Sanjay Patel38a02002019-07-25 13:11:21 +0000749/// Return true if we can choose one of these values to use in place of the
750/// other. Note that we will always choose the non-undef value to keep.
Duncan Sandse773c082013-07-11 08:28:20 +0000751static bool CanMergeValues(Value *First, Value *Second) {
752 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
753}
754
Sanjay Patel38a02002019-07-25 13:11:21 +0000755/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
756/// branch to Succ, into Succ.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000757///
758/// Assumption: Succ is the single successor for BB.
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000759static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
760 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
761
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000762 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
763 << Succ->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000764 // Shortcut, if there is only a single predecessor it must be BB and merging
765 // is always safe
766 if (Succ->getSinglePredecessor()) return true;
767
768 // Make a list of the predecessors of BB
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000769 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000770
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000771 // Look at all the phi nodes in Succ, to see if they present a conflict when
772 // merging these blocks
773 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
774 PHINode *PN = cast<PHINode>(I);
775
776 // If the incoming value from BB is again a PHINode in
777 // BB which has the same incoming value for *PI as PN does, we can
778 // merge the phi nodes and then the blocks can still be merged
779 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
780 if (BBPN && BBPN->getParent() == BB) {
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000781 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
782 BasicBlock *IBB = PN->getIncomingBlock(PI);
783 if (BBPreds.count(IBB) &&
Duncan Sandse773c082013-07-11 08:28:20 +0000784 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
785 PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000786 LLVM_DEBUG(dbgs()
787 << "Can't fold, phi node " << PN->getName() << " in "
788 << Succ->getName() << " is conflicting with "
789 << BBPN->getName() << " with regard to common predecessor "
790 << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000791 return false;
792 }
793 }
794 } else {
795 Value* Val = PN->getIncomingValueForBlock(BB);
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000796 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000797 // See if the incoming value for the common predecessor is equal to the
798 // one for BB, in which case this phi node will not prevent the merging
799 // of the block.
Benjamin Kramerb5188f12011-12-06 16:14:29 +0000800 BasicBlock *IBB = PN->getIncomingBlock(PI);
Duncan Sandse773c082013-07-11 08:28:20 +0000801 if (BBPreds.count(IBB) &&
802 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
804 << " in " << Succ->getName()
805 << " is conflicting with regard to common "
806 << "predecessor " << IBB->getName() << "\n");
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000807 return false;
808 }
809 }
810 }
811 }
812
813 return true;
814}
815
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000816using PredBlockVector = SmallVector<BasicBlock *, 16>;
817using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
Duncan Sandse773c082013-07-11 08:28:20 +0000818
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000819/// Determines the value to use as the phi node input for a block.
Duncan Sandse773c082013-07-11 08:28:20 +0000820///
821/// Select between \p OldVal any value that we know flows from \p BB
822/// to a particular phi on the basis of which one (if either) is not
823/// undef. Update IncomingValues based on the selected value.
824///
825/// \param OldVal The value we are considering selecting.
826/// \param BB The block that the value flows in from.
827/// \param IncomingValues A map from block-to-value for other phi inputs
828/// that we have examined.
829///
830/// \returns the selected value.
831static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
832 IncomingValueMap &IncomingValues) {
833 if (!isa<UndefValue>(OldVal)) {
834 assert((!IncomingValues.count(BB) ||
835 IncomingValues.find(BB)->second == OldVal) &&
836 "Expected OldVal to match incoming value from BB!");
837
838 IncomingValues.insert(std::make_pair(BB, OldVal));
839 return OldVal;
840 }
841
842 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
843 if (It != IncomingValues.end()) return It->second;
844
845 return OldVal;
846}
847
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000848/// Create a map from block to value for the operands of a
Duncan Sandse773c082013-07-11 08:28:20 +0000849/// given phi.
850///
851/// Create a map from block to value for each non-undef value flowing
852/// into \p PN.
853///
854/// \param PN The phi we are collecting the map for.
855/// \param IncomingValues [out] The map from block to value for this phi.
856static void gatherIncomingValuesToPhi(PHINode *PN,
857 IncomingValueMap &IncomingValues) {
858 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
859 BasicBlock *BB = PN->getIncomingBlock(i);
860 Value *V = PN->getIncomingValue(i);
861
862 if (!isa<UndefValue>(V))
863 IncomingValues.insert(std::make_pair(BB, V));
864 }
865}
866
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000867/// Replace the incoming undef values to a phi with the values
Duncan Sandse773c082013-07-11 08:28:20 +0000868/// from a block-to-value map.
869///
870/// \param PN The phi we are replacing the undefs in.
871/// \param IncomingValues A map from block to value.
872static void replaceUndefValuesInPhi(PHINode *PN,
873 const IncomingValueMap &IncomingValues) {
874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
875 Value *V = PN->getIncomingValue(i);
876
877 if (!isa<UndefValue>(V)) continue;
878
879 BasicBlock *BB = PN->getIncomingBlock(i);
880 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
881 if (It == IncomingValues.end()) continue;
882
883 PN->setIncomingValue(i, It->second);
884 }
885}
886
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000887/// Replace a value flowing from a block to a phi with
Duncan Sandse773c082013-07-11 08:28:20 +0000888/// potentially multiple instances of that value flowing from the
889/// block's predecessors to the phi.
890///
891/// \param BB The block with the value flowing into the phi.
892/// \param BBPreds The predecessors of BB.
893/// \param PN The phi that we are updating.
894static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
895 const PredBlockVector &BBPreds,
896 PHINode *PN) {
897 Value *OldVal = PN->removeIncomingValue(BB, false);
898 assert(OldVal && "No entry in PHI for Pred BB!");
899
900 IncomingValueMap IncomingValues;
901
902 // We are merging two blocks - BB, and the block containing PN - and
903 // as a result we need to redirect edges from the predecessors of BB
904 // to go to the block containing PN, and update PN
905 // accordingly. Since we allow merging blocks in the case where the
906 // predecessor and successor blocks both share some predecessors,
907 // and where some of those common predecessors might have undef
908 // values flowing into PN, we want to rewrite those values to be
909 // consistent with the non-undef values.
910
911 gatherIncomingValuesToPhi(PN, IncomingValues);
912
913 // If this incoming value is one of the PHI nodes in BB, the new entries
914 // in the PHI node are the entries from the old PHI.
915 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
916 PHINode *OldValPN = cast<PHINode>(OldVal);
917 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
918 // Note that, since we are merging phi nodes and BB and Succ might
919 // have common predecessors, we could end up with a phi node with
920 // identical incoming branches. This will be cleaned up later (and
921 // will trigger asserts if we try to clean it up now, without also
922 // simplifying the corresponding conditional branch).
923 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
924 Value *PredVal = OldValPN->getIncomingValue(i);
925 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
926 IncomingValues);
927
928 // And add a new incoming value for this predecessor for the
929 // newly retargeted branch.
930 PN->addIncoming(Selected, PredBB);
931 }
932 } else {
933 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
934 // Update existing incoming values in PN for this
935 // predecessor of BB.
936 BasicBlock *PredBB = BBPreds[i];
937 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
938 IncomingValues);
939
940 // And add a new incoming value for this predecessor for the
941 // newly retargeted branch.
942 PN->addIncoming(Selected, PredBB);
943 }
944 }
945
946 replaceUndefValuesInPhi(PN, IncomingValues);
947}
948
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +0000949bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
Chijun Sima21a8b602018-08-03 05:08:17 +0000950 DomTreeUpdater *DTU) {
Dan Gohman4a63fad2010-08-14 00:29:42 +0000951 assert(BB != &BB->getParent()->getEntryBlock() &&
952 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
953
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000954 // We can't eliminate infinite loops.
955 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
956 if (BB == Succ) return false;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +0000957
Reid Klecknerbca59d22016-05-02 19:43:22 +0000958 // Check to see if merging these blocks would cause conflicts for any of the
959 // phi nodes in BB or Succ. If not, we can safely merge.
960 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattnercbd18fc2009-11-10 05:59:26 +0000961
Reid Klecknerbca59d22016-05-02 19:43:22 +0000962 // Check for cases where Succ has multiple predecessors and a PHI node in BB
963 // has uses which will not disappear when the PHI nodes are merged. It is
964 // possible to handle such cases, but difficult: it requires checking whether
965 // BB dominates Succ, which is non-trivial to calculate in the case where
966 // Succ has multiple predecessors. Also, it requires checking whether
967 // constructing the necessary self-referential PHI node doesn't introduce any
968 // conflicts; this isn't too difficult, but the previous code for doing this
969 // was incorrect.
970 //
971 // Note that if this check finds a live use, BB dominates Succ, so BB is
972 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
973 // folding the branch isn't profitable in that case anyway.
974 if (!Succ->getSinglePredecessor()) {
975 BasicBlock::iterator BBI = BB->begin();
976 while (isa<PHINode>(*BBI)) {
977 for (Use &U : BBI->uses()) {
978 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
979 if (PN->getIncomingBlock(U) != BB)
Hans Wennborgb7599322016-05-02 17:22:54 +0000980 return false;
Reid Klecknerbca59d22016-05-02 19:43:22 +0000981 } else {
982 return false;
Hans Wennborgb7599322016-05-02 17:22:54 +0000983 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000984 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000985 ++BBI;
Hans Wennborgb7599322016-05-02 17:22:54 +0000986 }
Hans Wennborgb7599322016-05-02 17:22:54 +0000987 }
Reid Klecknerbca59d22016-05-02 19:43:22 +0000988
Craig Topper784929d2019-02-08 20:48:56 +0000989 // We cannot fold the block if it's a branch to an already present callbr
990 // successor because that creates duplicate successors.
991 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
992 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
993 if (Succ == CBI->getDefaultDest())
994 return false;
995 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
996 if (Succ == CBI->getIndirectDest(i))
997 return false;
998 }
999 }
1000
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001001 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Reid Klecknerbca59d22016-05-02 19:43:22 +00001002
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001003 SmallVector<DominatorTree::UpdateType, 32> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +00001004 if (DTU) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001005 Updates.push_back({DominatorTree::Delete, BB, Succ});
1006 // All predecessors of BB will be moved to Succ.
1007 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1008 Updates.push_back({DominatorTree::Delete, *I, BB});
1009 // This predecessor of BB may already have Succ as a successor.
1010 if (llvm::find(successors(*I), Succ) == succ_end(*I))
1011 Updates.push_back({DominatorTree::Insert, *I, Succ});
1012 }
1013 }
1014
Reid Klecknerbca59d22016-05-02 19:43:22 +00001015 if (isa<PHINode>(Succ->begin())) {
1016 // If there is more than one pred of succ, and there are PHI nodes in
1017 // the successor, then we need to add incoming edges for the PHI nodes
1018 //
1019 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1020
1021 // Loop over all of the PHI nodes in the successor of BB.
1022 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1023 PHINode *PN = cast<PHINode>(I);
1024
1025 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1026 }
1027 }
1028
1029 if (Succ->getSinglePredecessor()) {
1030 // BB is the only predecessor of Succ, so Succ will end up with exactly
1031 // the same predecessors BB had.
1032
1033 // Copy over any phi, debug or lifetime instruction.
1034 BB->getTerminator()->eraseFromParent();
1035 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1036 BB->getInstList());
1037 } else {
1038 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1039 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1040 assert(PN->use_empty() && "There shouldn't be any uses here!");
1041 PN->eraseFromParent();
1042 }
1043 }
1044
Florian Hahn77382be2016-11-18 13:12:07 +00001045 // If the unconditional branch we replaced contains llvm.loop metadata, we
1046 // add the metadata to the branch instructions in the predecessors.
1047 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1048 Instruction *TI = BB->getTerminator();
Daniel Jasper0a51ec22017-09-30 11:57:19 +00001049 if (TI)
Florian Hahn77382be2016-11-18 13:12:07 +00001050 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1051 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1052 BasicBlock *Pred = *PI;
1053 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1054 }
1055
Reid Klecknerbca59d22016-05-02 19:43:22 +00001056 // Everything that jumped to BB now goes to Succ.
1057 BB->replaceAllUsesWith(Succ);
1058 if (!Succ->hasName()) Succ->takeName(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001059
Chijun Sima21a8b602018-08-03 05:08:17 +00001060 // Clear the successor list of BB to match updates applying to DTU later.
1061 if (BB->getTerminator())
1062 BB->getInstList().pop_back();
1063 new UnreachableInst(BB->getContext(), BB);
1064 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1065 "applying corresponding DTU updates.");
1066
1067 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00001068 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +00001069 DTU->deleteBB(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001070 } else {
1071 BB->eraseFromParent(); // Delete the old basic block.
1072 }
Reid Klecknerbca59d22016-05-02 19:43:22 +00001073 return true;
Chris Lattnercbd18fc2009-11-10 05:59:26 +00001074}
1075
Jim Grosbachd831ef42009-12-02 17:06:45 +00001076bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
Jim Grosbachd831ef42009-12-02 17:06:45 +00001077 // This implementation doesn't currently consider undef operands
Nick Lewyckyfa44dc62011-06-28 03:57:31 +00001078 // specially. Theoretically, two phis which are identical except for
Jim Grosbachd831ef42009-12-02 17:06:45 +00001079 // one having an undef where the other doesn't could be collapsed.
1080
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001081 struct PHIDenseMapInfo {
1082 static PHINode *getEmptyKey() {
1083 return DenseMapInfo<PHINode *>::getEmptyKey();
1084 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001085
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001086 static PHINode *getTombstoneKey() {
1087 return DenseMapInfo<PHINode *>::getTombstoneKey();
1088 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001089
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001090 static unsigned getHashValue(PHINode *PN) {
1091 // Compute a hash value on the operands. Instcombine will likely have
1092 // sorted them, which helps expose duplicates, but we have to check all
1093 // the operands to be safe in case instcombine hasn't run.
1094 return static_cast<unsigned>(hash_combine(
1095 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1096 hash_combine_range(PN->block_begin(), PN->block_end())));
1097 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001098
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001099 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1100 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1101 RHS == getEmptyKey() || RHS == getTombstoneKey())
1102 return LHS == RHS;
1103 return LHS->isIdenticalTo(RHS);
1104 }
1105 };
Jim Grosbachd831ef42009-12-02 17:06:45 +00001106
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001107 // Set of unique PHINodes.
1108 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
Jim Grosbachd831ef42009-12-02 17:06:45 +00001109
1110 // Examine each PHI.
Benjamin Kramer2b2cdd72015-06-18 16:01:00 +00001111 bool Changed = false;
1112 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1113 auto Inserted = PHISet.insert(PN);
1114 if (!Inserted.second) {
1115 // A duplicate. Replace this PHI with its duplicate.
1116 PN->replaceAllUsesWith(*Inserted.first);
1117 PN->eraseFromParent();
1118 Changed = true;
Benjamin Kramerf175e042015-09-02 19:52:23 +00001119
1120 // The RAUW can change PHIs that we already visited. Start over from the
1121 // beginning.
1122 PHISet.clear();
1123 I = BB->begin();
Jim Grosbachd831ef42009-12-02 17:06:45 +00001124 }
1125 }
1126
1127 return Changed;
1128}
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001129
1130/// enforceKnownAlignment - If the specified pointer points to an object that
1131/// we control, modify the object's alignment to PrefAlign. This isn't
1132/// often possible though. If alignment is important, a more reliable approach
1133/// is to simply align all global variables and allocation instructions to
1134/// their preferred alignment from the beginning.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001135static unsigned enforceKnownAlignment(Value *V, unsigned Alignment,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001136 unsigned PrefAlign,
1137 const DataLayout &DL) {
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001138 assert(PrefAlign > Alignment);
James Y Knightac03dca2016-01-15 16:33:06 +00001139
Eli Friedman19ace4c2011-06-15 21:08:25 +00001140 V = V->stripPointerCasts();
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001141
Eli Friedman19ace4c2011-06-15 21:08:25 +00001142 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001143 // TODO: ideally, computeKnownBits ought to have used
1144 // AllocaInst::getAlignment() in its computation already, making
1145 // the below max redundant. But, as it turns out,
1146 // stripPointerCasts recurses through infinite layers of bitcasts,
1147 // while computeKnownBits is not allowed to traverse more than 6
1148 // levels.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001149 Alignment = std::max(AI->getAlignment(), Alignment);
1150 if (PrefAlign <= Alignment)
1151 return Alignment;
James Y Knightac03dca2016-01-15 16:33:06 +00001152
Lang Hamesde7ab802011-10-10 23:42:08 +00001153 // If the preferred alignment is greater than the natural stack alignment
1154 // then don't round up. This avoids dynamic stack realignment.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001155 if (DL.exceedsNaturalStackAlignment(Align(PrefAlign)))
1156 return Alignment;
Guillaume Chateletab11b912019-09-30 13:34:44 +00001157 AI->setAlignment(MaybeAlign(PrefAlign));
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001158 return PrefAlign;
1159 }
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001160
Rafael Espindola99e05cf2014-05-13 18:45:48 +00001161 if (auto *GO = dyn_cast<GlobalObject>(V)) {
James Y Knightac03dca2016-01-15 16:33:06 +00001162 // TODO: as above, this shouldn't be necessary.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001163 Alignment = std::max(GO->getAlignment(), Alignment);
1164 if (PrefAlign <= Alignment)
1165 return Alignment;
James Y Knightac03dca2016-01-15 16:33:06 +00001166
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001167 // If there is a large requested alignment and we can, bump up the alignment
Reid Kleckner486fa392015-07-14 00:11:08 +00001168 // of the global. If the memory we set aside for the global may not be the
1169 // memory used by the final program then it is impossible for us to reliably
1170 // enforce the preferred alignment.
James Y Knightac03dca2016-01-15 16:33:06 +00001171 if (!GO->canIncreaseAlignment())
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001172 return Alignment;
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001173
James Y Knightac03dca2016-01-15 16:33:06 +00001174 GO->setAlignment(PrefAlign);
1175 return PrefAlign;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001176 }
1177
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001178 return Alignment;
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001179}
1180
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001181unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182 const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001183 const Instruction *CxtI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001184 AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001185 const DominatorTree *DT) {
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001186 assert(V->getType()->isPointerTy() &&
1187 "getOrEnforceKnownAlignment expects a pointer!");
Matt Arsenault87dc6072013-08-01 22:42:18 +00001188
Craig Topper8205a1a2017-05-24 16:53:07 +00001189 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
Craig Topper8df66c62017-05-12 17:20:30 +00001190 unsigned TrailZ = Known.countMinTrailingZeros();
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001191
Matt Arsenaultf64212b2013-07-23 22:20:57 +00001192 // Avoid trouble with ridiculously large TrailZ values, such as
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001193 // those computed from a null pointer.
1194 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001195
Craig Topper8205a1a2017-05-24 16:53:07 +00001196 unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001197
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001198 // LLVM doesn't support alignments larger than this currently.
1199 Align = std::min(Align, +Value::MaximumAlignment);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001200
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001201 if (PrefAlign > Align)
Matt Arsenault87dc6072013-08-01 22:42:18 +00001202 Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
Jakub Staszak8e1a6e72013-07-22 23:16:36 +00001203
Chris Lattner6fcd32e2010-12-25 20:37:57 +00001204 // We don't need to make any adjustment.
1205 return Align;
1206}
1207
Devang Patel8c0b16b2011-03-17 21:58:19 +00001208///===---------------------------------------------------------------------===//
1209/// Dbg Intrinsic utilities
1210///
1211
Adrian Prantl29b9de72013-04-26 17:48:33 +00001212/// See if there is a dbg.value intrinsic for DIVar before I.
Adrian Prantla5b2a642016-02-17 20:02:25 +00001213static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1214 Instruction *I) {
Adrian Prantl29b9de72013-04-26 17:48:33 +00001215 // Since we can't guarantee that the original dbg.declare instrinsic
1216 // is removed by LowerDbgDeclare(), we need to make sure that we are
1217 // not inserting the same dbg.value intrinsic over and over.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001218 BasicBlock::InstListType::iterator PrevI(I);
Adrian Prantl29b9de72013-04-26 17:48:33 +00001219 if (PrevI != I->getParent()->getInstList().begin()) {
1220 --PrevI;
1221 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1222 if (DVI->getValue() == I->getOperand(0) &&
Adrian Prantla5b2a642016-02-17 20:02:25 +00001223 DVI->getVariable() == DIVar &&
1224 DVI->getExpression() == DIExpr)
Adrian Prantl29b9de72013-04-26 17:48:33 +00001225 return true;
1226 }
1227 return false;
1228}
1229
Keith Walkerba159892016-09-22 14:13:25 +00001230/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
Chandler Carruth2abb65a2017-06-26 03:31:31 +00001231static bool PhiHasDebugValue(DILocalVariable *DIVar,
Keith Walkerba159892016-09-22 14:13:25 +00001232 DIExpression *DIExpr,
1233 PHINode *APN) {
1234 // Since we can't guarantee that the original dbg.declare instrinsic
1235 // is removed by LowerDbgDeclare(), we need to make sure that we are
1236 // not inserting the same dbg.value intrinsic over and over.
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001237 SmallVector<DbgValueInst *, 1> DbgValues;
1238 findDbgValues(DbgValues, APN);
1239 for (auto *DVI : DbgValues) {
1240 assert(DVI->getValue() == APN);
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001241 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1242 return true;
1243 }
1244 return false;
Keith Walkerba159892016-09-22 14:13:25 +00001245}
1246
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001247/// Check if the alloc size of \p ValTy is large enough to cover the variable
1248/// (or fragment of the variable) described by \p DII.
1249///
1250/// This is primarily intended as a helper for the different
1251/// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1252/// converted describes an alloca'd variable, so we need to use the
1253/// alloc size of the value when doing the comparison. E.g. an i1 value will be
1254/// identified as covering an n-bit fragment, if the store size of i1 is at
1255/// least n bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001256static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001257 const DataLayout &DL = DII->getModule()->getDataLayout();
1258 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1259 if (auto FragmentSize = DII->getFragmentSizeInBits())
1260 return ValueSize >= *FragmentSize;
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001261 // We can't always calculate the size of the DI variable (e.g. if it is a
1262 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1263 // intead.
1264 if (DII->isAddressOfVariable())
1265 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1266 if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1267 return ValueSize >= *FragmentSize;
1268 // Could not determine size of variable. Conservatively return false.
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001269 return false;
1270}
1271
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001272/// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1273/// to a dbg.value. Because no machine insts can come from debug intrinsics,
1274/// only the scope and inlinedAt is significant. Zero line numbers are used in
1275/// case this DebugLoc leaks into any adjacent instructions.
1276static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1277 // Original dbg.declare must have a location.
1278 DebugLoc DeclareLoc = DII->getDebugLoc();
1279 MDNode *Scope = DeclareLoc.getScope();
1280 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1281 // Produce an unknown location with the correct scope / inlinedAt fields.
1282 return DebugLoc::get(0, 0, Scope, InlinedAt);
1283}
1284
Adrian Prantld00333a2013-04-26 18:10:50 +00001285/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001286/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001287void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel8c0b16b2011-03-17 21:58:19 +00001288 StoreInst *SI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001289 assert(DII->isAddressOfVariable());
1290 auto *DIVar = DII->getVariable();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001291 assert(DIVar && "Missing variable");
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001292 auto *DIExpr = DII->getExpression();
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001293 Value *DV = SI->getValueOperand();
Devang Patel8c0b16b2011-03-17 21:58:19 +00001294
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001295 DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1296
Brian Gesiak1c44ed82019-04-02 14:57:56 +00001297 if (!valueCoversEntireFragment(DV->getType(), DII)) {
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001298 // FIXME: If storing to a part of the variable described by the dbg.declare,
1299 // then we want to insert a dbg.value for the corresponding fragment.
1300 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1301 << *DII << '\n');
1302 // For now, when there is a store to parts of the variable (but we do not
1303 // know which part) we insert an dbg.value instrinsic to indicate that we
1304 // know nothing about the variable's content.
1305 DV = UndefValue::get(DV->getType());
1306 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001307 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
Bjorn Pettersson428caf92018-06-15 13:48:55 +00001308 return;
1309 }
1310
David Blaikie441cfee2017-05-15 21:34:01 +00001311 if (!LdStHasDebugValue(DIVar, DIExpr, SI))
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001312 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
Devang Patel8c0b16b2011-03-17 21:58:19 +00001313}
1314
Adrian Prantld00333a2013-04-26 18:10:50 +00001315/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001316/// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001317void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Devang Patel2c7ee272011-03-18 23:45:43 +00001318 LoadInst *LI, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001319 auto *DIVar = DII->getVariable();
1320 auto *DIExpr = DII->getExpression();
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +00001321 assert(DIVar && "Missing variable");
Devang Patel2c7ee272011-03-18 23:45:43 +00001322
Adrian Prantla5b2a642016-02-17 20:02:25 +00001323 if (LdStHasDebugValue(DIVar, DIExpr, LI))
Keith Walkerba159892016-09-22 14:13:25 +00001324 return;
Adrian Prantl29b9de72013-04-26 17:48:33 +00001325
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001326 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1327 // FIXME: If only referring to a part of the variable described by the
1328 // dbg.declare, then we want to insert a dbg.value for the corresponding
1329 // fragment.
1330 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1331 << *DII << '\n');
1332 return;
1333 }
1334
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001335 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1336
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001337 // We are now tracking the loaded value instead of the address. In the
1338 // future if multi-location support is added to the IR, it might be
1339 // preferable to keep tracking both the loaded value and the original
1340 // address in case the alloca can not be elided.
1341 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001342 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
Keno Fischer00cbf9a2015-12-19 02:02:44 +00001343 DbgValue->insertAfter(LI);
Keith Walkerba159892016-09-22 14:13:25 +00001344}
1345
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001346/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1347/// llvm.dbg.declare or llvm.dbg.addr intrinsic.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001348void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
Keith Walkerba159892016-09-22 14:13:25 +00001349 PHINode *APN, DIBuilder &Builder) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001350 auto *DIVar = DII->getVariable();
1351 auto *DIExpr = DII->getExpression();
Keith Walkerba159892016-09-22 14:13:25 +00001352 assert(DIVar && "Missing variable");
1353
1354 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1355 return;
1356
Bjorn Pettersson550517b2018-06-26 06:17:00 +00001357 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1358 // FIXME: If only referring to a part of the variable described by the
1359 // dbg.declare, then we want to insert a dbg.value for the corresponding
1360 // fragment.
1361 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1362 << *DII << '\n');
1363 return;
1364 }
1365
Reid Kleckner64818222016-09-27 18:45:31 +00001366 BasicBlock *BB = APN->getParent();
Keith Walkerba159892016-09-22 14:13:25 +00001367 auto InsertionPt = BB->getFirstInsertionPt();
Reid Kleckner64818222016-09-27 18:45:31 +00001368
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001369 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1370
Reid Kleckner64818222016-09-27 18:45:31 +00001371 // The block may be a catchswitch block, which does not have a valid
1372 // insertion point.
1373 // FIXME: Insert dbg.value markers in the successors when appropriate.
1374 if (InsertionPt != BB->end())
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001375 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
Keith Walkerc9412522016-09-19 09:49:30 +00001376}
1377
Adrian Prantl232897f2014-04-25 23:00:25 +00001378/// Determine whether this alloca is either a VLA or an array.
1379static bool isArray(AllocaInst *AI) {
1380 return AI->isArrayAllocation() ||
Alexey Lapshincbf1f3b2019-09-04 14:19:49 +00001381 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1382}
1383
1384/// Determine whether this alloca is a structure.
1385static bool isStructure(AllocaInst *AI) {
1386 return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
Adrian Prantl232897f2014-04-25 23:00:25 +00001387}
1388
Devang Patelaad34d82011-03-17 22:18:16 +00001389/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1390/// of llvm.dbg.value intrinsics.
1391bool llvm::LowerDbgDeclare(Function &F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001392 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Devang Patelaad34d82011-03-17 22:18:16 +00001393 SmallVector<DbgDeclareInst *, 4> Dbgs;
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001394 for (auto &FI : F)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001395 for (Instruction &BI : FI)
1396 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Devang Patelaad34d82011-03-17 22:18:16 +00001397 Dbgs.push_back(DDI);
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001398
Devang Patelaad34d82011-03-17 22:18:16 +00001399 if (Dbgs.empty())
1400 return false;
1401
Adrian Prantl79c8e8f2014-03-27 23:30:04 +00001402 for (auto &I : Dbgs) {
1403 DbgDeclareInst *DDI = I;
Adrian Prantl8e10fdb2013-11-18 23:04:38 +00001404 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1405 // If this is an alloca for a scalar variable, insert a dbg.value
1406 // at each load and store to the alloca and erase the dbg.declare.
Adrian Prantl32da8892014-04-25 20:49:25 +00001407 // The dbg.values allow tracking a variable even if it is not
1408 // stored on the stack, while the dbg.declare can only describe
1409 // the stack slot (and at a lexical-scope granularity). Later
1410 // passes will attempt to elide the stack slot.
Alexey Lapshincbf1f3b2019-09-04 14:19:49 +00001411 if (!AI || isArray(AI) || isStructure(AI))
Adrian Prantl5b477be2018-03-09 00:45:04 +00001412 continue;
1413
1414 // A volatile load/store means that the alloca can't be elided anyway.
1415 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1416 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1417 return LI->isVolatile();
1418 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1419 return SI->isVolatile();
1420 return false;
1421 }))
1422 continue;
1423
1424 for (auto &AIUse : AI->uses()) {
1425 User *U = AIUse.getUser();
1426 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1427 if (AIUse.getOperandNo() == 1)
1428 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1429 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1430 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1431 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
Vedant Kumarb572f642018-07-26 20:56:53 +00001432 // This is a call by-value or some other instruction that takes a
1433 // pointer to the variable. Insert a *value* intrinsic that describes
1434 // the variable by dereferencing the alloca.
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001435 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
Vedant Kumarb572f642018-07-26 20:56:53 +00001436 auto *DerefExpr =
1437 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
Jeremy Morsea2b780b2019-05-10 10:03:41 +00001438 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr, NewLoc,
1439 CI);
Keno Fischer1dd319f2016-01-14 19:12:27 +00001440 }
Devang Patelaad34d82011-03-17 22:18:16 +00001441 }
Adrian Prantl5b477be2018-03-09 00:45:04 +00001442 DDI->eraseFromParent();
Devang Patelaad34d82011-03-17 22:18:16 +00001443 }
1444 return true;
1445}
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001446
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001447/// Propagate dbg.value intrinsics through the newly inserted PHIs.
1448void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1449 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1450 assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1451 if (InsertedPHIs.size() == 0)
1452 return;
1453
1454 // Map existing PHI nodes to their dbg.values.
1455 ValueToValueMapTy DbgValueMap;
1456 for (auto &I : *BB) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001457 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001458 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1459 DbgValueMap.insert({Loc, DbgII});
1460 }
1461 }
1462 if (DbgValueMap.size() == 0)
1463 return;
1464
1465 // Then iterate through the new PHIs and look to see if they use one of the
1466 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1467 // propagate the info through the new PHI.
1468 LLVMContext &C = BB->getContext();
1469 for (auto PHI : InsertedPHIs) {
Matt Davis523c6562018-02-23 17:38:27 +00001470 BasicBlock *Parent = PHI->getParent();
1471 // Avoid inserting an intrinsic into an EH block.
1472 if (Parent->getFirstNonPHI()->isEHPad())
1473 continue;
1474 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001475 for (auto VI : PHI->operand_values()) {
1476 auto V = DbgValueMap.find(VI);
1477 if (V != DbgValueMap.end()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001478 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001479 Instruction *NewDbgII = DbgII->clone();
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001480 NewDbgII->setOperand(0, PhiMAV);
Vedant Kumar6394df92018-01-25 23:48:29 +00001481 auto InsertionPt = Parent->getFirstInsertionPt();
1482 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1483 NewDbgII->insertBefore(&*InsertionPt);
Vedant Kumar6bfc8692018-01-25 21:37:05 +00001484 }
1485 }
1486 }
1487}
1488
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001489/// Finds all intrinsics declaring local variables as living in the memory that
1490/// 'V' points to. This may include a mix of dbg.declare and
1491/// dbg.addr intrinsics.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001492TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001493 // This function is hot. Check whether the value has any metadata to avoid a
1494 // DenseMap lookup.
1495 if (!V->isUsedByMetadata())
1496 return {};
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001497 auto *L = LocalAsMetadata::getIfExists(V);
1498 if (!L)
1499 return {};
1500 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1501 if (!MDV)
1502 return {};
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001503
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001504 TinyPtrVector<DbgVariableIntrinsic *> Declares;
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001505 for (User *U : MDV->users()) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001506 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001507 if (DII->isAddressOfVariable())
1508 Declares.push_back(DII);
1509 }
1510
1511 return Declares;
Cameron Zwarich843bc7d2011-05-24 03:10:43 +00001512}
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001513
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001514void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001515 // This function is hot. Check whether the value has any metadata to avoid a
1516 // DenseMap lookup.
1517 if (!V->isUsedByMetadata())
1518 return;
Keith Walkerba159892016-09-22 14:13:25 +00001519 if (auto *L = LocalAsMetadata::getIfExists(V))
1520 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1521 for (User *U : MDV->users())
1522 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Adrian Prantlfa9e84e2017-03-16 20:11:54 +00001523 DbgValues.push_back(DVI);
Keith Walkerba159892016-09-22 14:13:25 +00001524}
1525
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001526void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001527 Value *V) {
Vedant Kumarde46f652018-06-26 18:44:52 +00001528 // This function is hot. Check whether the value has any metadata to avoid a
1529 // DenseMap lookup.
1530 if (!V->isUsedByMetadata())
1531 return;
Reid Kleckner29a5c032017-11-14 21:49:06 +00001532 if (auto *L = LocalAsMetadata::getIfExists(V))
1533 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1534 for (User *U : MDV->users())
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001535 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
Reid Kleckner29a5c032017-11-14 21:49:06 +00001536 DbgUsers.push_back(DII);
1537}
1538
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001539bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1540 Instruction *InsertBefore, DIBuilder &Builder,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001541 uint8_t DIExprFlags, int Offset) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001542 auto DbgAddrs = FindDbgAddrUses(Address);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001543 for (DbgVariableIntrinsic *DII : DbgAddrs) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001544 DebugLoc Loc = DII->getDebugLoc();
1545 auto *DIVar = DII->getVariable();
1546 auto *DIExpr = DII->getExpression();
1547 assert(DIVar && "Missing variable");
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001548 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
Vedant Kumard37e0782018-07-13 22:39:31 +00001549 // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001550 // llvm.dbg.declare.
1551 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1552 if (DII == InsertBefore)
Vedant Kumard37e0782018-07-13 22:39:31 +00001553 InsertBefore = InsertBefore->getNextNode();
Reid Kleckner0fe506b2017-09-21 19:52:03 +00001554 DII->eraseFromParent();
1555 }
1556 return !DbgAddrs.empty();
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001557}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00001558
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001559bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001560 DIBuilder &Builder, uint8_t DIExprFlags,
1561 int Offset) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001562 return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
Petar Jovanovice85bbf52019-05-20 10:35:57 +00001563 DIExprFlags, Offset);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +00001564}
1565
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001566static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1567 DIBuilder &Builder, int Offset) {
1568 DebugLoc Loc = DVI->getDebugLoc();
1569 auto *DIVar = DVI->getVariable();
1570 auto *DIExpr = DVI->getExpression();
1571 assert(DIVar && "Missing variable");
1572
1573 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1574 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1575 // it and give up.
1576 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1577 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1578 return;
1579
Petr Hosekf6cd6ff2019-07-22 18:52:42 +00001580 // Insert the offset before the first deref.
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001581 // We could just change the offset argument of dbg.value, but it's unsigned...
Petr Hosek8b161ba2019-07-24 00:16:23 +00001582 if (Offset)
1583 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001584
Adrian Prantlabe04752017-07-28 20:21:02 +00001585 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +00001586 DVI->eraseFromParent();
1587}
1588
1589void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1590 DIBuilder &Builder, int Offset) {
1591 if (auto *L = LocalAsMetadata::getIfExists(AI))
1592 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1593 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1594 Use &U = *UI++;
1595 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1596 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1597 }
1598}
1599
Vedant Kumar6379a622018-07-06 17:32:39 +00001600/// Wrap \p V in a ValueAsMetadata instance.
1601static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1602 return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1603}
1604
1605bool llvm::salvageDebugInfo(Instruction &I) {
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001606 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001607 findDbgUsers(DbgUsers, &I);
1608 if (DbgUsers.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001609 return false;
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001610
Jeremy Morse84ca7062019-02-05 11:11:28 +00001611 return salvageDebugInfoForDbgValues(I, DbgUsers);
1612}
1613
1614bool llvm::salvageDebugInfoForDbgValues(
1615 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001616 auto &Ctx = I.getContext();
1617 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
Adrian Prantl47ea6472017-03-16 21:14:09 +00001618
Jeremy Morse84ca7062019-02-05 11:11:28 +00001619 for (auto *DII : DbgUsers) {
1620 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1621 // are implicitly pointing out the value as a DWARF memory location
1622 // description.
1623 bool StackValue = isa<DbgValueInst>(DII);
1624
1625 DIExpression *DIExpr =
1626 salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1627
1628 // salvageDebugInfoImpl should fail on examining the first element of
1629 // DbgUsers, or none of them.
1630 if (!DIExpr)
1631 return false;
1632
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001633 DII->setOperand(0, wrapMD(I.getOperand(0)));
Vedant Kumar6379a622018-07-06 17:32:39 +00001634 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001635 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
Jeremy Morse84ca7062019-02-05 11:11:28 +00001636 }
1637
1638 return true;
1639}
1640
1641DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1642 DIExpression *SrcDIExpr,
1643 bool WithStackValue) {
1644 auto &M = *I.getModule();
1645 auto &DL = M.getDataLayout();
1646
1647 // Apply a vector of opcodes to the source DIExpression.
1648 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1649 DIExpression *DIExpr = SrcDIExpr;
1650 if (!Ops.empty()) {
1651 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1652 }
1653 return DIExpr;
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001654 };
1655
Jeremy Morse84ca7062019-02-05 11:11:28 +00001656 // Apply the given offset to the source DIExpression.
1657 auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001658 SmallVector<uint64_t, 8> Ops;
1659 DIExpression::appendOffset(Ops, Offset);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001660 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001661 };
1662
Jeremy Morse84ca7062019-02-05 11:11:28 +00001663 // initializer-list helper for applying operators to the source DIExpression.
1664 auto applyOps =
1665 [&](std::initializer_list<uint64_t> Opcodes) -> DIExpression * {
Vedant Kumar04386d82018-02-09 19:19:55 +00001666 SmallVector<uint64_t, 8> Ops(Opcodes);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001667 return doSalvage(Ops);
Vedant Kumar04386d82018-02-09 19:19:55 +00001668 };
1669
Vedant Kumar388fac52018-02-13 03:34:23 +00001670 if (auto *CI = dyn_cast<CastInst>(&I)) {
Wolfgang Pieb4fe42212019-04-15 17:36:29 +00001671 // No-op casts and zexts are irrelevant for debug info.
1672 if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
1673 return SrcDIExpr;
Bob Haarman032f87b2019-05-21 11:53:41 +00001674 return nullptr;
1675 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001676 unsigned BitWidth =
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001677 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
Jeremy Morse84ca7062019-02-05 11:11:28 +00001678 // Rewrite a constant GEP into a DIExpression.
Vedant Kumarb2ec02b2018-01-05 23:27:02 +00001679 APInt Offset(BitWidth, 0);
Jeremy Morse84ca7062019-02-05 11:11:28 +00001680 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1681 return applyOffset(Offset.getSExtValue());
1682 } else {
1683 return nullptr;
1684 }
Adrian Prantl182f9fe2017-11-06 22:49:39 +00001685 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
Vedant Kumar044b5882018-02-15 19:13:03 +00001686 // Rewrite binary operations with constant integer operands.
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001687 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1688 if (!ConstInt || ConstInt->getBitWidth() > 64)
Jeremy Morse84ca7062019-02-05 11:11:28 +00001689 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001690
1691 uint64_t Val = ConstInt->getSExtValue();
Jeremy Morse84ca7062019-02-05 11:11:28 +00001692 switch (BI->getOpcode()) {
1693 case Instruction::Add:
1694 return applyOffset(Val);
1695 case Instruction::Sub:
1696 return applyOffset(-int64_t(Val));
1697 case Instruction::Mul:
1698 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1699 case Instruction::SDiv:
1700 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1701 case Instruction::SRem:
1702 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1703 case Instruction::Or:
1704 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1705 case Instruction::And:
1706 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1707 case Instruction::Xor:
1708 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1709 case Instruction::Shl:
1710 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1711 case Instruction::LShr:
1712 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1713 case Instruction::AShr:
1714 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1715 default:
1716 // TODO: Salvage constants from each kind of binop we know about.
1717 return nullptr;
Vedant Kumar96b7dc02018-02-13 01:09:46 +00001718 }
Jeremy Morseb33a5c72019-02-12 10:54:30 +00001719 // *Not* to do: we should not attempt to salvage load instructions,
1720 // because the validity and lifetime of a dbg.value containing
1721 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
Adrian Prantl47ea6472017-03-16 21:14:09 +00001722 }
Jeremy Morse84ca7062019-02-05 11:11:28 +00001723 return nullptr;
Adrian Prantl47ea6472017-03-16 21:14:09 +00001724}
1725
Vedant Kumar6379a622018-07-06 17:32:39 +00001726/// A replacement for a dbg.value expression.
1727using DbgValReplacement = Optional<DIExpression *>;
1728
1729/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1730/// possibly moving/deleting users to prevent use-before-def. Returns true if
1731/// changes are made.
1732static bool rewriteDebugUsers(
1733 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001734 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
Vedant Kumar6379a622018-07-06 17:32:39 +00001735 // Find debug users of From.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001736 SmallVector<DbgVariableIntrinsic *, 1> Users;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001737 findDbgUsers(Users, &From);
1738 if (Users.empty())
Vedant Kumar6379a622018-07-06 17:32:39 +00001739 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001740
Vedant Kumar6379a622018-07-06 17:32:39 +00001741 // Prevent use-before-def of To.
1742 bool Changed = false;
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001743 SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
Vedant Kumar6379a622018-07-06 17:32:39 +00001744 if (isa<Instruction>(&To)) {
1745 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1746
1747 for (auto *DII : Users) {
1748 // It's common to see a debug user between From and DomPoint. Move it
1749 // after DomPoint to preserve the variable update without any reordering.
1750 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1751 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
1752 DII->moveAfter(&DomPoint);
1753 Changed = true;
1754
1755 // Users which otherwise aren't dominated by the replacement value must
1756 // be salvaged or deleted.
1757 } else if (!DT.dominates(&DomPoint, DII)) {
1758 DeleteOrSalvage.insert(DII);
1759 }
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001760 }
Vedant Kumar6379a622018-07-06 17:32:39 +00001761 }
1762
1763 // Update debug users without use-before-def risk.
1764 for (auto *DII : Users) {
1765 if (DeleteOrSalvage.count(DII))
1766 continue;
1767
1768 LLVMContext &Ctx = DII->getContext();
1769 DbgValReplacement DVR = RewriteExpr(*DII);
1770 if (!DVR)
1771 continue;
1772
1773 DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1774 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1775 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
1776 Changed = true;
1777 }
1778
1779 if (!DeleteOrSalvage.empty()) {
1780 // Try to salvage the remaining debug users.
1781 Changed |= salvageDebugInfo(From);
1782
1783 // Delete the debug users which weren't salvaged.
1784 for (auto *DII : DeleteOrSalvage) {
1785 if (DII->getVariableLocation() == &From) {
1786 LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
1787 DII->eraseFromParent();
1788 Changed = true;
1789 }
1790 }
1791 }
1792
1793 return Changed;
Vedant Kumarc85ca4c2018-06-26 18:44:53 +00001794}
1795
Vedant Kumar6379a622018-07-06 17:32:39 +00001796/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1797/// losslessly preserve the bits and semantics of the value. This predicate is
1798/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1799///
1800/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1801/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1802/// and also does not allow lossless pointer <-> integer conversions.
1803static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1804 Type *ToTy) {
1805 // Trivially compatible types.
1806 if (FromTy == ToTy)
1807 return true;
1808
1809 // Handle compatible pointer <-> integer conversions.
1810 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1811 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1812 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1813 !DL.isNonIntegralPointerType(ToTy);
1814 return SameSize && LosslessConversion;
1815 }
1816
1817 // TODO: This is not exhaustive.
1818 return false;
1819}
1820
1821bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1822 Instruction &DomPoint, DominatorTree &DT) {
1823 // Exit early if From has no debug users.
1824 if (!From.isUsedByMetadata())
1825 return false;
1826
1827 assert(&From != &To && "Can't replace something with itself");
1828
1829 Type *FromTy = From.getType();
1830 Type *ToTy = To.getType();
1831
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001832 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001833 return DII.getExpression();
1834 };
1835
1836 // Handle no-op conversions.
1837 Module &M = *From.getModule();
1838 const DataLayout &DL = M.getDataLayout();
1839 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1840 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1841
1842 // Handle integer-to-integer widening and narrowing.
1843 // FIXME: Use DW_OP_convert when it's available everywhere.
1844 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1845 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1846 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1847 assert(FromBits != ToBits && "Unexpected no-op conversion");
1848
1849 // When the width of the result grows, assume that a debugger will only
1850 // access the low `FromBits` bits when inspecting the source variable.
1851 if (FromBits < ToBits)
1852 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1853
1854 // The width of the result has shrunk. Use sign/zero extension to describe
1855 // the source variable's high bits.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00001856 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
Vedant Kumar6379a622018-07-06 17:32:39 +00001857 DILocalVariable *Var = DII.getVariable();
1858
1859 // Without knowing signedness, sign/zero extension isn't possible.
1860 auto Signedness = Var->getSignedness();
1861 if (!Signedness)
1862 return None;
1863
1864 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
Markus Lavinb86ce212019-03-19 13:16:28 +00001865 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1866 SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_LLVM_convert, ToBits, TK,
1867 dwarf::DW_OP_LLVM_convert, FromBits, TK});
1868 return DIExpression::appendToStack(DII.getExpression(), Ops);
Vedant Kumar6379a622018-07-06 17:32:39 +00001869 };
1870 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1871 }
1872
1873 // TODO: Floating-point conversions, vectors.
1874 return false;
Vedant Kumar6fa24b02018-06-20 16:50:25 +00001875}
1876
David Majnemer35c46d32016-01-24 05:26:18 +00001877unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1878 unsigned NumDeadInst = 0;
1879 // Delete the instructions backwards, as it has a reduced likelihood of
1880 // having to update as many def-use and use-def chains.
1881 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001882 while (EndInst != &BB->front()) {
David Majnemer35c46d32016-01-24 05:26:18 +00001883 // Delete the next to last instruction.
1884 Instruction *Inst = &*--EndInst->getIterator();
1885 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1886 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1887 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1888 EndInst = Inst;
1889 continue;
1890 }
1891 if (!isa<DbgInfoIntrinsic>(Inst))
1892 ++NumDeadInst;
1893 Inst->eraseFromParent();
1894 }
1895 return NumDeadInst;
1896}
1897
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001898unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001899 bool PreserveLCSSA, DomTreeUpdater *DTU,
1900 MemorySSAUpdater *MSSAU) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001901 BasicBlock *BB = I->getParent();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001902 std::vector <DominatorTree::UpdateType> Updates;
1903
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001904 if (MSSAU)
1905 MSSAU->changeToUnreachable(I);
1906
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001907 // Loop over all of the successors, removing BB's entry from any PHI
1908 // nodes.
Chijun Sima21a8b602018-08-03 05:08:17 +00001909 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001910 Updates.reserve(BB->getTerminator()->getNumSuccessors());
1911 for (BasicBlock *Successor : successors(BB)) {
Michael Zolotukhin5020c992016-11-18 21:01:12 +00001912 Successor->removePredecessor(BB, PreserveLCSSA);
Chijun Sima21a8b602018-08-03 05:08:17 +00001913 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001914 Updates.push_back({DominatorTree::Delete, BB, Successor});
1915 }
David Majnemere14e7bc2016-06-25 08:19:55 +00001916 // Insert a call to llvm.trap right before this. This turns the undefined
1917 // behavior into a hard fail instead of falling through into random code.
1918 if (UseLLVMTrap) {
1919 Function *TrapFn =
1920 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1921 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1922 CallTrap->setDebugLoc(I->getDebugLoc());
1923 }
Anastasis Grammenos52d52832018-08-07 20:21:56 +00001924 auto *UI = new UnreachableInst(I->getContext(), I);
1925 UI->setDebugLoc(I->getDebugLoc());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001926
1927 // All instructions after this are dead.
David Majnemer88542a02016-01-24 06:26:47 +00001928 unsigned NumInstrsRemoved = 0;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001929 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001930 while (BBI != BBE) {
1931 if (!BBI->use_empty())
1932 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1933 BB->getInstList().erase(BBI++);
David Majnemer88542a02016-01-24 06:26:47 +00001934 ++NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001935 }
Chijun Sima21a8b602018-08-03 05:08:17 +00001936 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001937 DTU->applyUpdatesPermissive(Updates);
David Majnemer88542a02016-01-24 06:26:47 +00001938 return NumInstrsRemoved;
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001939}
1940
Johannes Doerfert3d7bbc62019-08-05 21:35:02 +00001941CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
1942 SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end());
Sanjoy Das8a954a02015-12-08 22:26:08 +00001943 SmallVector<OperandBundleDef, 1> OpBundles;
1944 II->getOperandBundlesAsDefs(OpBundles);
Johannes Doerfert3d7bbc62019-08-05 21:35:02 +00001945 CallInst *NewCall = CallInst::Create(II->getFunctionType(),
1946 II->getCalledValue(), Args, OpBundles);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001947 NewCall->setCallingConv(II->getCallingConv());
1948 NewCall->setAttributes(II->getAttributes());
1949 NewCall->setDebugLoc(II->getDebugLoc());
Michael Kruse5948b7f2018-12-14 18:15:11 +00001950 NewCall->copyMetadata(*II);
Johannes Doerfert3d7bbc62019-08-05 21:35:02 +00001951 return NewCall;
1952}
1953
1954/// changeToCall - Convert the specified invoke into a normal call.
1955void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
1956 CallInst *NewCall = createCallMatchingInvoke(II);
1957 NewCall->takeName(II);
1958 NewCall->insertBefore(II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001959 II->replaceAllUsesWith(NewCall);
1960
1961 // Follow the call by a branch to the normal destination.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001962 BasicBlock *NormalDestBB = II->getNormalDest();
1963 BranchInst::Create(NormalDestBB, II);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001964
1965 // Update PHI nodes in the unwind destination
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00001966 BasicBlock *BB = II->getParent();
1967 BasicBlock *UnwindDestBB = II->getUnwindDest();
1968 UnwindDestBB->removePredecessor(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001969 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00001970 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00001971 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00001972}
1973
Kuba Breckaddfdba32016-11-14 21:41:13 +00001974BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1975 BasicBlock *UnwindEdge) {
1976 BasicBlock *BB = CI->getParent();
1977
1978 // Convert this function call into an invoke instruction. First, split the
1979 // basic block.
1980 BasicBlock *Split =
1981 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1982
1983 // Delete the unconditional branch inserted by splitBasicBlock
1984 BB->getInstList().pop_back();
1985
1986 // Create the new invoke instruction.
1987 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1988 SmallVector<OperandBundleDef, 1> OpBundles;
1989
1990 CI->getOperandBundlesAsDefs(OpBundles);
1991
1992 // Note: we're round tripping operand bundles through memory here, and that
1993 // can potentially be avoided with a cleverer API design that we do not have
1994 // as of this time.
1995
James Y Knightd9e85a02019-02-01 20:43:34 +00001996 InvokeInst *II =
1997 InvokeInst::Create(CI->getFunctionType(), CI->getCalledValue(), Split,
1998 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
Kuba Breckaddfdba32016-11-14 21:41:13 +00001999 II->setDebugLoc(CI->getDebugLoc());
2000 II->setCallingConv(CI->getCallingConv());
2001 II->setAttributes(CI->getAttributes());
2002
2003 // Make sure that anything using the call now uses the invoke! This also
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002004 // updates the CallGraph if present, because it uses a WeakTrackingVH.
Kuba Breckaddfdba32016-11-14 21:41:13 +00002005 CI->replaceAllUsesWith(II);
2006
2007 // Delete the original call
2008 Split->getInstList().pop_front();
2009 return Split;
2010}
2011
David Majnemer7fddecc2015-06-17 20:52:32 +00002012static bool markAliveBlocks(Function &F,
Chijun Sima21a8b602018-08-03 05:08:17 +00002013 SmallPtrSetImpl<BasicBlock *> &Reachable,
2014 DomTreeUpdater *DTU = nullptr) {
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002015 SmallVector<BasicBlock*, 128> Worklist;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002016 BasicBlock *BB = &F.front();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002017 Worklist.push_back(BB);
2018 Reachable.insert(BB);
2019 bool Changed = false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002020 do {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002021 BB = Worklist.pop_back_val();
2022
2023 // Do a quick scan of the basic block, turning any obviously unreachable
2024 // instructions into LLVM unreachable insts. The instruction combining pass
2025 // canonicalizes unreachable insts into stores to null or undef.
David Majnemer9f506252016-06-25 08:34:38 +00002026 for (Instruction &I : *BB) {
Xin Tong074ccf32018-07-18 18:40:45 +00002027 if (auto *CI = dyn_cast<CallInst>(&I)) {
2028 Value *Callee = CI->getCalledValue();
2029 // Handle intrinsic calls.
2030 if (Function *F = dyn_cast<Function>(Callee)) {
2031 auto IntrinsicID = F->getIntrinsicID();
2032 // Assumptions that are known to be false are equivalent to
2033 // unreachable. Also, if the condition is undefined, then we make the
2034 // choice most beneficial to the optimizer, and choose that to also be
2035 // unreachable.
2036 if (IntrinsicID == Intrinsic::assume) {
2037 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2038 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002039 changeToUnreachable(CI, false, false, DTU);
Sanjoy Das54a3a002016-04-21 05:09:12 +00002040 Changed = true;
2041 break;
2042 }
Xin Tong074ccf32018-07-18 18:40:45 +00002043 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2044 // A call to the guard intrinsic bails out of the current
2045 // compilation unit if the predicate passed to it is false. If the
2046 // predicate is a constant false, then we know the guard will bail
2047 // out of the current compile unconditionally, so all code following
2048 // it is dead.
2049 //
2050 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2051 // guards to treat `undef` as `false` since a guard on `undef` can
2052 // still be useful for widening.
2053 if (match(CI->getArgOperand(0), m_Zero()))
2054 if (!isa<UnreachableInst>(CI->getNextNode())) {
2055 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
Chijun Sima21a8b602018-08-03 05:08:17 +00002056 false, DTU);
Xin Tong074ccf32018-07-18 18:40:45 +00002057 Changed = true;
2058 break;
2059 }
2060 }
2061 } else if ((isa<ConstantPointerNull>(Callee) &&
2062 !NullPointerIsDefined(CI->getFunction())) ||
2063 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002064 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
David Majnemer1fea77c2016-06-25 07:37:27 +00002065 Changed = true;
2066 break;
2067 }
Joseph Tremouletfb4d9f72019-04-02 15:48:58 +00002068 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002069 // If we found a call to a no-return function, insert an unreachable
2070 // instruction after it. Make sure there isn't *already* one there
2071 // though.
David Majnemer9f506252016-06-25 08:34:38 +00002072 if (!isa<UnreachableInst>(CI->getNextNode())) {
David Majnemere14e7bc2016-06-25 08:19:55 +00002073 // Don't insert a call to llvm.trap right before the unreachable.
Chijun Sima21a8b602018-08-03 05:08:17 +00002074 changeToUnreachable(CI->getNextNode(), false, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002075 Changed = true;
2076 }
2077 break;
2078 }
Xin Tong074ccf32018-07-18 18:40:45 +00002079 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2080 // Store to undef and store to null are undefined and used to signal
2081 // that they should be changed to unreachable by passes that can't
2082 // modify the CFG.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002083
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002084 // Don't touch volatile stores.
2085 if (SI->isVolatile()) continue;
2086
2087 Value *Ptr = SI->getOperand(1);
2088
2089 if (isa<UndefValue>(Ptr) ||
2090 (isa<ConstantPointerNull>(Ptr) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002091 !NullPointerIsDefined(SI->getFunction(),
2092 SI->getPointerAddressSpace()))) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002093 changeToUnreachable(SI, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002094 Changed = true;
2095 break;
2096 }
2097 }
2098 }
2099
Chandler Carruthedb12a82018-10-15 10:04:59 +00002100 Instruction *Terminator = BB->getTerminator();
David Majnemer2fa86512016-01-05 06:27:50 +00002101 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2102 // Turn invokes that call 'nounwind' functions into ordinary calls.
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002103 Value *Callee = II->getCalledValue();
Manoj Gupta77eeac32018-07-09 22:27:23 +00002104 if ((isa<ConstantPointerNull>(Callee) &&
2105 !NullPointerIsDefined(BB->getParent())) ||
2106 isa<UndefValue>(Callee)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002107 changeToUnreachable(II, true, false, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002108 Changed = true;
David Majnemer7fddecc2015-06-17 20:52:32 +00002109 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002110 if (II->use_empty() && II->onlyReadsMemory()) {
2111 // jump to the normal destination branch.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002112 BasicBlock *NormalDestBB = II->getNormalDest();
2113 BasicBlock *UnwindDestBB = II->getUnwindDest();
2114 BranchInst::Create(NormalDestBB, II);
2115 UnwindDestBB->removePredecessor(II->getParent());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002116 II->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002117 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002118 DTU->applyUpdatesPermissive(
2119 {{DominatorTree::Delete, BB, UnwindDestBB}});
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002120 } else
Chijun Sima21a8b602018-08-03 05:08:17 +00002121 changeToCall(II, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002122 Changed = true;
2123 }
David Majnemer2fa86512016-01-05 06:27:50 +00002124 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2125 // Remove catchpads which cannot be reached.
David Majnemer59eb7332016-01-05 07:42:17 +00002126 struct CatchPadDenseMapInfo {
2127 static CatchPadInst *getEmptyKey() {
2128 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2129 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002130
David Majnemer59eb7332016-01-05 07:42:17 +00002131 static CatchPadInst *getTombstoneKey() {
2132 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2133 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002134
David Majnemer59eb7332016-01-05 07:42:17 +00002135 static unsigned getHashValue(CatchPadInst *CatchPad) {
2136 return static_cast<unsigned>(hash_combine_range(
2137 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2138 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002139
David Majnemer59eb7332016-01-05 07:42:17 +00002140 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2141 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2142 RHS == getEmptyKey() || RHS == getTombstoneKey())
2143 return LHS == RHS;
2144 return LHS->isIdenticalTo(RHS);
2145 }
2146 };
2147
2148 // Set of unique CatchPads.
2149 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2150 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2151 HandlerSet;
2152 detail::DenseSetEmpty Empty;
David Majnemer2fa86512016-01-05 06:27:50 +00002153 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2154 E = CatchSwitch->handler_end();
2155 I != E; ++I) {
2156 BasicBlock *HandlerBB = *I;
David Majnemer59eb7332016-01-05 07:42:17 +00002157 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2158 if (!HandlerSet.insert({CatchPad, Empty}).second) {
David Majnemer2fa86512016-01-05 06:27:50 +00002159 CatchSwitch->removeHandler(I);
2160 --I;
2161 --E;
2162 Changed = true;
2163 }
2164 }
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002165 }
2166
Chijun Sima21a8b602018-08-03 05:08:17 +00002167 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
David Majnemer9f506252016-06-25 08:34:38 +00002168 for (BasicBlock *Successor : successors(BB))
2169 if (Reachable.insert(Successor).second)
2170 Worklist.push_back(Successor);
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002171 } while (!Worklist.empty());
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002172 return Changed;
2173}
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002174
Chijun Sima21a8b602018-08-03 05:08:17 +00002175void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00002176 Instruction *TI = BB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002177
2178 if (auto *II = dyn_cast<InvokeInst>(TI)) {
Chijun Sima21a8b602018-08-03 05:08:17 +00002179 changeToCall(II, DTU);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002180 return;
2181 }
2182
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002183 Instruction *NewTI;
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002184 BasicBlock *UnwindDest;
2185
2186 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2187 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2188 UnwindDest = CRI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00002189 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2190 auto *NewCatchSwitch = CatchSwitchInst::Create(
2191 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2192 CatchSwitch->getName(), CatchSwitch);
2193 for (BasicBlock *PadBB : CatchSwitch->handlers())
2194 NewCatchSwitch->addHandler(PadBB);
2195
2196 NewTI = NewCatchSwitch;
2197 UnwindDest = CatchSwitch->getUnwindDest();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002198 } else {
2199 llvm_unreachable("Could not find unwind successor");
2200 }
2201
2202 NewTI->takeName(TI);
2203 NewTI->setDebugLoc(TI->getDebugLoc());
2204 UnwindDest->removePredecessor(BB);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002205 TI->replaceAllUsesWith(NewTI);
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002206 TI->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002207 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +00002208 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00002209}
2210
Davide Italiano4eb210b2017-07-07 18:54:14 +00002211/// removeUnreachableBlocks - Remove blocks that are not reachable, even
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002212/// if they are in a dead cycle. Return true if a change was made, false
Davide Italiano4eb210b2017-07-07 18:54:14 +00002213/// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
2214/// after modifying the CFG.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002215bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002216 DomTreeUpdater *DTU,
2217 MemorySSAUpdater *MSSAU) {
Florian Hahn167b0522019-10-02 07:37:41 +00002218 SmallPtrSet<BasicBlock *, 16> Reachable;
Chijun Sima21a8b602018-08-03 05:08:17 +00002219 bool Changed = markAliveBlocks(F, Reachable, DTU);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002220
2221 // If there are unreachable blocks in the CFG...
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002222 if (Reachable.size() == F.size())
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002223 return Changed;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002224
2225 assert(Reachable.size() < F.size());
Florian Hahn167b0522019-10-02 07:37:41 +00002226 NumRemoved += F.size() - Reachable.size();
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002227
Alina Sbirleadb101862019-07-12 22:30:30 +00002228 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
Florian Hahn167b0522019-10-02 07:37:41 +00002229 for (BasicBlock &BB : F) {
2230 // Skip reachable basic blocks
2231 if (Reachable.find(&BB) != Reachable.end())
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002232 continue;
Florian Hahn167b0522019-10-02 07:37:41 +00002233 DeadBlockSet.insert(&BB);
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002234 }
2235
2236 if (MSSAU)
2237 MSSAU->removeBlocks(DeadBlockSet);
2238
2239 // Loop over all of the basic blocks that are not reachable, dropping all of
2240 // their internal references. Update DTU and LVI if available.
2241 std::vector<DominatorTree::UpdateType> Updates;
2242 for (auto *BB : DeadBlockSet) {
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002243 for (BasicBlock *Successor : successors(BB)) {
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002244 if (!DeadBlockSet.count(Successor))
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002245 Successor->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +00002246 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002247 Updates.push_back({DominatorTree::Delete, BB, Successor});
2248 }
David Majnemerd9833ea2016-01-10 07:13:04 +00002249 if (LVI)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002250 LVI->eraseBlock(BB);
Peter Collingbourne8d642de2013-08-12 22:38:43 +00002251 BB->dropAllReferences();
Chijun Sima21a8b602018-08-03 05:08:17 +00002252 if (DTU) {
Chandler Carruthc8eaea72018-10-18 00:39:18 +00002253 // Remove the terminator of BB to clear the successor list of BB.
Chijun Sima21a8b602018-08-03 05:08:17 +00002254 if (BB->getTerminator())
2255 BB->getInstList().pop_back();
2256 new UnreachableInst(BB->getContext(), BB);
2257 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2258 "applying corresponding DTU updates.");
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +00002259 }
2260 }
Evgeniy Stepanov2a066af2013-03-22 08:43:04 +00002261
Chijun Sima21a8b602018-08-03 05:08:17 +00002262 if (DTU) {
Chijun Sima70e97162019-02-22 13:48:38 +00002263 DTU->applyUpdatesPermissive(Updates);
Chijun Sima53048432018-08-03 12:45:29 +00002264 bool Deleted = false;
Alina Sbirlea2ab544b2018-08-16 21:58:44 +00002265 for (auto *BB : DeadBlockSet) {
Chijun Sima53048432018-08-03 12:45:29 +00002266 if (DTU->isBBPendingDeletion(BB))
2267 --NumRemoved;
2268 else
2269 Deleted = true;
Chijun Sima21a8b602018-08-03 05:08:17 +00002270 DTU->deleteBB(BB);
Chijun Sima53048432018-08-03 12:45:29 +00002271 }
2272 if (!Deleted)
2273 return false;
Florian Hahn167b0522019-10-02 07:37:41 +00002274 } else {
2275 for (auto *BB : DeadBlockSet)
2276 BB->eraseFromParent();
Chijun Sima21a8b602018-08-03 05:08:17 +00002277 }
Florian Hahn167b0522019-10-02 07:37:41 +00002278
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +00002279 return true;
2280}
Rafael Espindolaea46c322014-08-15 15:46:38 +00002281
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002282void llvm::combineMetadata(Instruction *K, const Instruction *J,
Florian Hahn950576b2018-08-07 15:36:11 +00002283 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002284 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002285 K->dropUnknownNonDebugMetadata(KnownIDs);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002286 K->getAllMetadataOtherThanDebugLoc(Metadata);
David Majnemer6f014d32016-07-25 02:21:19 +00002287 for (const auto &MD : Metadata) {
2288 unsigned Kind = MD.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002289 MDNode *JMD = J->getMetadata(Kind);
David Majnemer6f014d32016-07-25 02:21:19 +00002290 MDNode *KMD = MD.second;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002291
2292 switch (Kind) {
2293 default:
2294 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2295 break;
2296 case LLVMContext::MD_dbg:
2297 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2298 case LLVMContext::MD_tbaa:
2299 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2300 break;
2301 case LLVMContext::MD_alias_scope:
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +00002302 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2303 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002304 case LLVMContext::MD_noalias:
Hal Finkele4c0c162016-04-26 02:06:06 +00002305 case LLVMContext::MD_mem_parallel_loop_access:
Rafael Espindolaea46c322014-08-15 15:46:38 +00002306 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2307 break;
Michael Kruse978ba612018-12-20 04:58:07 +00002308 case LLVMContext::MD_access_group:
2309 K->setMetadata(LLVMContext::MD_access_group,
2310 intersectAccessGroups(K, J));
2311 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002312 case LLVMContext::MD_range:
Florian Hahnfc7654a2018-10-27 16:53:45 +00002313
2314 // If K does move, use most generic range. Otherwise keep the range of
2315 // K.
2316 if (DoesKMove)
2317 // FIXME: If K does move, we should drop the range info and nonnull.
2318 // Currently this function is used with DoesKMove in passes
2319 // doing hoisting/sinking and the current behavior of using the
2320 // most generic range is correct in those cases.
2321 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
Rafael Espindolaea46c322014-08-15 15:46:38 +00002322 break;
2323 case LLVMContext::MD_fpmath:
2324 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2325 break;
2326 case LLVMContext::MD_invariant_load:
2327 // Only set the !invariant.load if it is present in both instructions.
2328 K->setMetadata(Kind, JMD);
2329 break;
Philip Reamesd7c21362014-10-21 21:02:19 +00002330 case LLVMContext::MD_nonnull:
Florian Hahn950576b2018-08-07 15:36:11 +00002331 // If K does move, keep nonull if it is present in both instructions.
2332 if (DoesKMove)
2333 K->setMetadata(Kind, JMD);
Philip Reamesd7c21362014-10-21 21:02:19 +00002334 break;
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002335 case LLVMContext::MD_invariant_group:
2336 // Preserve !invariant.group in K.
2337 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002338 case LLVMContext::MD_align:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002339 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002340 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2341 break;
2342 case LLVMContext::MD_dereferenceable:
2343 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002344 K->setMetadata(Kind,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00002345 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2346 break;
Yonghong Song44b16bd2019-08-03 23:41:26 +00002347 case LLVMContext::MD_preserve_access_index:
2348 // Preserve !preserve.access.index in K.
2349 break;
Rafael Espindolaea46c322014-08-15 15:46:38 +00002350 }
2351 }
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00002352 // Set !invariant.group from J if J has it. If both instructions have it
2353 // then we will just pick it from J - even when they are different.
2354 // Also make sure that K is load or store - f.e. combining bitcast with load
2355 // could produce bitcast with invariant.group metadata, which is invalid.
2356 // FIXME: we should try to preserve both invariant.group md if they are
2357 // different, but right now instruction can only have one invariant.group.
2358 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2359 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2360 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
Rafael Espindolaea46c322014-08-15 15:46:38 +00002361}
Philip Reames7c78ef72015-05-22 23:53:24 +00002362
Florian Hahn406f1ff2018-08-24 11:40:04 +00002363void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2364 bool KDominatesJ) {
Eli Friedman02419a92016-08-08 04:10:22 +00002365 unsigned KnownIDs[] = {
2366 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2367 LLVMContext::MD_noalias, LLVMContext::MD_range,
2368 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2369 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2370 LLVMContext::MD_dereferenceable,
Michael Kruse978ba612018-12-20 04:58:07 +00002371 LLVMContext::MD_dereferenceable_or_null,
Yonghong Song44b16bd2019-08-03 23:41:26 +00002372 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
Florian Hahn406f1ff2018-08-24 11:40:04 +00002373 combineMetadata(K, J, KnownIDs, KDominatesJ);
Eli Friedman02419a92016-08-08 04:10:22 +00002374}
2375
Sanjay Patel86e9f9d2019-07-24 22:11:11 +00002376void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2377 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2378 Source.getAllMetadata(MD);
2379 MDBuilder MDB(Dest.getContext());
2380 Type *NewType = Dest.getType();
2381 const DataLayout &DL = Source.getModule()->getDataLayout();
2382 for (const auto &MDPair : MD) {
2383 unsigned ID = MDPair.first;
2384 MDNode *N = MDPair.second;
2385 // Note, essentially every kind of metadata should be preserved here! This
2386 // routine is supposed to clone a load instruction changing *only its type*.
2387 // The only metadata it makes sense to drop is metadata which is invalidated
2388 // when the pointer type changes. This should essentially never be the case
2389 // in LLVM, but we explicitly switch over only known metadata to be
2390 // conservatively correct. If you are adding metadata to LLVM which pertains
2391 // to loads, you almost certainly want to add it here.
2392 switch (ID) {
2393 case LLVMContext::MD_dbg:
2394 case LLVMContext::MD_tbaa:
2395 case LLVMContext::MD_prof:
2396 case LLVMContext::MD_fpmath:
2397 case LLVMContext::MD_tbaa_struct:
2398 case LLVMContext::MD_invariant_load:
2399 case LLVMContext::MD_alias_scope:
2400 case LLVMContext::MD_noalias:
2401 case LLVMContext::MD_nontemporal:
2402 case LLVMContext::MD_mem_parallel_loop_access:
2403 case LLVMContext::MD_access_group:
2404 // All of these directly apply.
2405 Dest.setMetadata(ID, N);
2406 break;
2407
2408 case LLVMContext::MD_nonnull:
2409 copyNonnullMetadata(Source, N, Dest);
2410 break;
2411
2412 case LLVMContext::MD_align:
2413 case LLVMContext::MD_dereferenceable:
2414 case LLVMContext::MD_dereferenceable_or_null:
2415 // These only directly apply if the new type is also a pointer.
2416 if (NewType->isPointerTy())
2417 Dest.setMetadata(ID, N);
2418 break;
2419
2420 case LLVMContext::MD_range:
2421 copyRangeMetadata(DL, Source, N, Dest);
2422 break;
2423 }
2424 }
2425}
2426
Florian Hahn39bbe172018-08-07 13:27:33 +00002427void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2428 auto *ReplInst = dyn_cast<Instruction>(Repl);
2429 if (!ReplInst)
2430 return;
2431
2432 // Patch the replacement so that it is not more restrictive than the value
2433 // being replaced.
2434 // Note that if 'I' is a load being replaced by some operation,
2435 // for example, by an arithmetic operation, then andIRFlags()
2436 // would just erase all math flags from the original arithmetic
2437 // operation, which is clearly not wanted and not needed.
2438 if (!isa<LoadInst>(I))
2439 ReplInst->andIRFlags(I);
2440
2441 // FIXME: If both the original and replacement value are part of the
2442 // same control-flow region (meaning that the execution of one
2443 // guarantees the execution of the other), then we can combine the
2444 // noalias scopes here and do better than the general conservative
2445 // answer used in combineMetadata().
2446
2447 // In general, GVN unifies expressions over different control-flow
2448 // regions, and so we need a conservative combination of the noalias
2449 // scopes.
2450 static const unsigned KnownIDs[] = {
2451 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2452 LLVMContext::MD_noalias, LLVMContext::MD_range,
2453 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Michael Kruse978ba612018-12-20 04:58:07 +00002454 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
Yonghong Song44b16bd2019-08-03 23:41:26 +00002455 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
Florian Hahn950576b2018-08-07 15:36:11 +00002456 combineMetadata(ReplInst, I, KnownIDs, false);
Florian Hahn39bbe172018-08-07 13:27:33 +00002457}
2458
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002459template <typename RootType, typename DominatesFn>
2460static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2461 const RootType &Root,
2462 const DominatesFn &Dominates) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002463 assert(From->getType() == To->getType());
2464
2465 unsigned Count = 0;
2466 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2467 UI != UE;) {
2468 Use &U = *UI++;
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002469 if (!Dominates(Root, U))
2470 continue;
2471 U.set(To);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002472 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2473 << "' as " << *To << " in " << *U << "\n");
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002474 ++Count;
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00002475 }
2476 return Count;
2477}
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002478
Anna Thomasc07d5542017-05-23 13:36:25 +00002479unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2480 assert(From->getType() == To->getType());
2481 auto *BB = From->getParent();
2482 unsigned Count = 0;
2483
2484 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2485 UI != UE;) {
2486 Use &U = *UI++;
2487 auto *I = cast<Instruction>(U.getUser());
2488 if (I->getParent() == BB)
2489 continue;
2490 U.set(To);
2491 ++Count;
2492 }
2493 return Count;
2494}
2495
Piotr Padlewskid979c1f2017-05-09 19:39:44 +00002496unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2497 DominatorTree &DT,
2498 const BasicBlockEdge &Root) {
2499 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2500 return DT.dominates(Root, U);
2501 };
2502 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2503}
2504
2505unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2506 DominatorTree &DT,
2507 const BasicBlock *BB) {
2508 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2509 auto *I = cast<Instruction>(U.getUser())->getParent();
2510 return DT.properlyDominates(BB, I);
2511 };
2512 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2513}
2514
Chandler Carruth31607342019-02-11 07:42:30 +00002515bool llvm::callsGCLeafFunction(const CallBase *Call,
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002516 const TargetLibraryInfo &TLI) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002517 // Check if the function is specifically marked as a gc leaf function.
Chandler Carruth31607342019-02-11 07:42:30 +00002518 if (Call->hasFnAttr("gc-leaf-function"))
Manuel Jacob3eedd112016-01-05 23:59:08 +00002519 return true;
Chandler Carruth31607342019-02-11 07:42:30 +00002520 if (const Function *F = Call->getCalledFunction()) {
Sanjoy Dasd4c78332016-03-25 20:12:13 +00002521 if (F->hasFnAttribute("gc-leaf-function"))
2522 return true;
2523
2524 if (auto IID = F->getIntrinsicID())
2525 // Most LLVM intrinsics do not take safepoints.
2526 return IID != Intrinsic::experimental_gc_statepoint &&
2527 IID != Intrinsic::experimental_deoptimize;
2528 }
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002529
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002530 // Lib calls can be materialized by some passes, and won't be
2531 // marked as 'gc-leaf-function.' All available Libcalls are
2532 // GC-leaf.
2533 LibFunc LF;
Chandler Carruth31607342019-02-11 07:42:30 +00002534 if (TLI.getLibFunc(ImmutableCallSite(Call), LF)) {
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002535 return TLI.has(LF);
2536 }
2537
Sanjoy Dasc21a05a2015-10-08 23:18:30 +00002538 return false;
2539}
James Molloyf01488e2016-01-15 09:20:19 +00002540
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002541void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2542 LoadInst &NewLI) {
2543 auto *NewTy = NewLI.getType();
2544
2545 // This only directly applies if the new type is also a pointer.
2546 if (NewTy->isPointerTy()) {
2547 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2548 return;
2549 }
2550
2551 // The only other translation we can do is to integral loads with !range
2552 // metadata.
2553 if (!NewTy->isIntegerTy())
2554 return;
2555
2556 MDBuilder MDB(NewLI.getContext());
2557 const Value *Ptr = OldLI.getPointerOperand();
2558 auto *ITy = cast<IntegerType>(NewTy);
2559 auto *NullInt = ConstantExpr::getPtrToInt(
2560 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2561 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2562 NewLI.setMetadata(LLVMContext::MD_range,
2563 MDB.createRange(NonNullInt, NullInt));
2564}
2565
2566void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2567 MDNode *N, LoadInst &NewLI) {
2568 auto *NewTy = NewLI.getType();
2569
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002570 // Give up unless it is converted to a pointer where there is a single very
2571 // valuable mapping we can do reliably.
2572 // FIXME: It would be nice to propagate this in more ways, but the type
2573 // conversions make it hard.
2574 if (!NewTy->isPointerTy())
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002575 return;
2576
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002577 unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002578 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2579 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2580 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002581 }
2582}
2583
Carlos Alberto Encisoba4e4372018-09-19 08:16:56 +00002584void llvm::dropDebugUsers(Instruction &I) {
2585 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2586 findDbgUsers(DbgUsers, &I);
2587 for (auto *DII : DbgUsers)
2588 DII->eraseFromParent();
2589}
2590
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002591void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2592 BasicBlock *BB) {
2593 // Since we are moving the instructions out of its basic block, we do not
2594 // retain their original debug locations (DILocations) and debug intrinsic
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002595 // instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002596 //
2597 // Doing so would degrade the debugging experience and adversely affect the
2598 // accuracy of profiling information.
2599 //
2600 // Currently, when hoisting the instructions, we take the following actions:
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002601 // - Remove their debug intrinsic instructions.
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002602 // - Set their debug locations to the values from the insertion point.
2603 //
2604 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2605 // need to be deleted, is because there will not be any instructions with a
2606 // DILocation in either branch left after performing the transformation. We
2607 // can only insert a dbg.value after the two branches are joined again.
2608 //
2609 // See PR38762, PR39243 for more details.
2610 //
2611 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2612 // encode predicated DIExpressions that yield different results on different
2613 // code paths.
2614 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2615 Instruction *I = &*II;
2616 I->dropUnknownNonDebugMetadata();
2617 if (I->isUsedByMetadata())
2618 dropDebugUsers(*I);
Carlos Alberto Enciso08dc50f2019-02-08 10:57:26 +00002619 if (isa<DbgInfoIntrinsic>(I)) {
Carlos Alberto Enciso9a24e1a2018-10-25 09:58:59 +00002620 // Remove DbgInfo Intrinsics.
2621 II = I->eraseFromParent();
2622 continue;
2623 }
2624 I->setDebugLoc(InsertPt->getDebugLoc());
2625 ++II;
2626 }
2627 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2628 BB->begin(),
2629 BB->getTerminator()->getIterator());
2630}
2631
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002632namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002633
James Molloyf01488e2016-01-15 09:20:19 +00002634/// A potential constituent of a bitreverse or bswap expression. See
2635/// collectBitParts for a fuller explanation.
2636struct BitPart {
2637 BitPart(Value *P, unsigned BW) : Provider(P) {
2638 Provenance.resize(BW);
2639 }
2640
2641 /// The Value that this is a bitreverse/bswap of.
2642 Value *Provider;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002643
James Molloyf01488e2016-01-15 09:20:19 +00002644 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2645 /// in Provider becomes bit B in the result of this expression.
2646 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2647
2648 enum { Unset = -1 };
2649};
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002650
Benjamin Kramerb7d33112016-08-06 11:13:10 +00002651} // end anonymous namespace
James Molloyf01488e2016-01-15 09:20:19 +00002652
2653/// Analyze the specified subexpression and see if it is capable of providing
2654/// pieces of a bswap or bitreverse. The subexpression provides a potential
2655/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2656/// the output of the expression came from a corresponding bit in some other
2657/// value. This function is recursive, and the end result is a mapping of
2658/// bitnumber to bitnumber. It is the caller's responsibility to validate that
2659/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2660///
2661/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2662/// that the expression deposits the low byte of %X into the high byte of the
2663/// result and that all other bits are zero. This expression is accepted and a
2664/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2665/// [0-7].
2666///
2667/// To avoid revisiting values, the BitPart results are memoized into the
2668/// provided map. To avoid unnecessary copying of BitParts, BitParts are
2669/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2670/// store BitParts objects, not pointers. As we need the concept of a nullptr
2671/// BitParts (Value has been analyzed and the analysis failed), we an Optional
2672/// type instead to provide the same functionality.
2673///
2674/// Because we pass around references into \c BPS, we must use a container that
2675/// does not invalidate internal references (std::map instead of DenseMap).
James Molloyf01488e2016-01-15 09:20:19 +00002676static const Optional<BitPart> &
2677collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
David Stuttard411488b2019-05-09 15:02:10 +00002678 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
James Molloyf01488e2016-01-15 09:20:19 +00002679 auto I = BPS.find(V);
2680 if (I != BPS.end())
2681 return I->second;
2682
2683 auto &Result = BPS[V] = None;
2684 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2685
David Stuttard411488b2019-05-09 15:02:10 +00002686 // Prevent stack overflow by limiting the recursion depth
2687 if (Depth == BitPartRecursionMaxDepth) {
2688 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2689 return Result;
2690 }
2691
James Molloyf01488e2016-01-15 09:20:19 +00002692 if (Instruction *I = dyn_cast<Instruction>(V)) {
2693 // If this is an or instruction, it may be an inner node of the bswap.
2694 if (I->getOpcode() == Instruction::Or) {
2695 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002696 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002697 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002698 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002699 if (!A || !B)
2700 return Result;
2701
2702 // Try and merge the two together.
2703 if (!A->Provider || A->Provider != B->Provider)
2704 return Result;
2705
2706 Result = BitPart(A->Provider, BitWidth);
2707 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2708 if (A->Provenance[i] != BitPart::Unset &&
2709 B->Provenance[i] != BitPart::Unset &&
2710 A->Provenance[i] != B->Provenance[i])
2711 return Result = None;
2712
2713 if (A->Provenance[i] == BitPart::Unset)
2714 Result->Provenance[i] = B->Provenance[i];
2715 else
2716 Result->Provenance[i] = A->Provenance[i];
2717 }
2718
2719 return Result;
2720 }
2721
2722 // If this is a logical shift by a constant, recurse then shift the result.
2723 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2724 unsigned BitShift =
2725 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2726 // Ensure the shift amount is defined.
2727 if (BitShift > BitWidth)
2728 return Result;
2729
2730 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002731 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002732 if (!Res)
2733 return Result;
2734 Result = Res;
2735
2736 // Perform the "shift" on BitProvenance.
2737 auto &P = Result->Provenance;
2738 if (I->getOpcode() == Instruction::Shl) {
2739 P.erase(std::prev(P.end(), BitShift), P.end());
2740 P.insert(P.begin(), BitShift, BitPart::Unset);
2741 } else {
2742 P.erase(P.begin(), std::next(P.begin(), BitShift));
2743 P.insert(P.end(), BitShift, BitPart::Unset);
2744 }
2745
2746 return Result;
2747 }
2748
2749 // If this is a logical 'and' with a mask that clears bits, recurse then
2750 // unset the appropriate bits.
2751 if (I->getOpcode() == Instruction::And &&
2752 isa<ConstantInt>(I->getOperand(1))) {
2753 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2754 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2755
2756 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2757 // early exit.
2758 unsigned NumMaskedBits = AndMask.countPopulation();
2759 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2760 return Result;
Chandler Carruth2abb65a2017-06-26 03:31:31 +00002761
James Molloyf01488e2016-01-15 09:20:19 +00002762 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002763 MatchBitReversals, BPS, Depth + 1);
James Molloyf01488e2016-01-15 09:20:19 +00002764 if (!Res)
2765 return Result;
2766 Result = Res;
2767
2768 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2769 // If the AndMask is zero for this bit, clear the bit.
2770 if ((AndMask & Bit) == 0)
2771 Result->Provenance[i] = BitPart::Unset;
Chad Rosiere5819e22016-05-26 14:58:51 +00002772 return Result;
2773 }
James Molloyf01488e2016-01-15 09:20:19 +00002774
Chad Rosiere5819e22016-05-26 14:58:51 +00002775 // If this is a zext instruction zero extend the result.
2776 if (I->getOpcode() == Instruction::ZExt) {
2777 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
David Stuttard411488b2019-05-09 15:02:10 +00002778 MatchBitReversals, BPS, Depth + 1);
Chad Rosiere5819e22016-05-26 14:58:51 +00002779 if (!Res)
2780 return Result;
2781
2782 Result = BitPart(Res->Provider, BitWidth);
2783 auto NarrowBitWidth =
2784 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2785 for (unsigned i = 0; i < NarrowBitWidth; ++i)
2786 Result->Provenance[i] = Res->Provenance[i];
2787 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2788 Result->Provenance[i] = BitPart::Unset;
James Molloyf01488e2016-01-15 09:20:19 +00002789 return Result;
2790 }
2791 }
2792
2793 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2794 // the input value to the bswap/bitreverse.
2795 Result = BitPart(V, BitWidth);
2796 for (unsigned i = 0; i < BitWidth; ++i)
2797 Result->Provenance[i] = i;
2798 return Result;
2799}
2800
2801static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2802 unsigned BitWidth) {
2803 if (From % 8 != To % 8)
2804 return false;
2805 // Convert from bit indices to byte indices and check for a byte reversal.
2806 From >>= 3;
2807 To >>= 3;
2808 BitWidth >>= 3;
2809 return From == BitWidth - To - 1;
2810}
2811
2812static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2813 unsigned BitWidth) {
2814 return From == BitWidth - To - 1;
2815}
2816
Chad Rosiera00df492016-05-25 16:22:14 +00002817bool llvm::recognizeBSwapOrBitReverseIdiom(
James Molloyf01488e2016-01-15 09:20:19 +00002818 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2819 SmallVectorImpl<Instruction *> &InsertedInsts) {
2820 if (Operator::getOpcode(I) != Instruction::Or)
2821 return false;
2822 if (!MatchBSwaps && !MatchBitReversals)
2823 return false;
2824 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2825 if (!ITy || ITy->getBitWidth() > 128)
2826 return false; // Can't do vectors or integers > 128 bits.
2827 unsigned BW = ITy->getBitWidth();
2828
Chad Rosiere5819e22016-05-26 14:58:51 +00002829 unsigned DemandedBW = BW;
2830 IntegerType *DemandedTy = ITy;
2831 if (I->hasOneUse()) {
2832 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2833 DemandedTy = cast<IntegerType>(Trunc->getType());
2834 DemandedBW = DemandedTy->getBitWidth();
2835 }
2836 }
2837
James Molloyf01488e2016-01-15 09:20:19 +00002838 // Try to find all the pieces corresponding to the bswap.
2839 std::map<Value *, Optional<BitPart>> BPS;
David Stuttard411488b2019-05-09 15:02:10 +00002840 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
James Molloyf01488e2016-01-15 09:20:19 +00002841 if (!Res)
2842 return false;
2843 auto &BitProvenance = Res->Provenance;
2844
2845 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2846 // only byteswap values with an even number of bytes.
Chad Rosiere5819e22016-05-26 14:58:51 +00002847 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2848 for (unsigned i = 0; i < DemandedBW; ++i) {
2849 OKForBSwap &=
2850 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002851 OKForBitReverse &=
Chad Rosiere5819e22016-05-26 14:58:51 +00002852 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
James Molloyf01488e2016-01-15 09:20:19 +00002853 }
2854
2855 Intrinsic::ID Intrin;
2856 if (OKForBSwap && MatchBSwaps)
2857 Intrin = Intrinsic::bswap;
2858 else if (OKForBitReverse && MatchBitReversals)
2859 Intrin = Intrinsic::bitreverse;
2860 else
2861 return false;
2862
Chad Rosiere5819e22016-05-26 14:58:51 +00002863 if (ITy != DemandedTy) {
2864 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2865 Value *Provider = Res->Provider;
2866 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2867 // We may need to truncate the provider.
2868 if (DemandedTy != ProviderTy) {
2869 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2870 "trunc", I);
2871 InsertedInsts.push_back(Trunc);
2872 Provider = Trunc;
2873 }
2874 auto *CI = CallInst::Create(F, Provider, "rev", I);
2875 InsertedInsts.push_back(CI);
2876 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2877 InsertedInsts.push_back(ExtInst);
2878 return true;
2879 }
2880
James Molloyf01488e2016-01-15 09:20:19 +00002881 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2882 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2883 return true;
2884}
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002885
2886// CodeGen has special handling for some string functions that may replace
2887// them with target-specific intrinsics. Since that'd skip our interceptors
2888// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2889// we mark affected calls as NoBuiltin, which will disable optimization
2890// in CodeGen.
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002891void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2892 CallInst *CI, const TargetLibraryInfo *TLI) {
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002893 Function *F = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002894 LibFunc Func;
Evgeniy Stepanovd240a882016-07-28 23:45:15 +00002895 if (F && !F->hasLocalLinkage() && F->hasName() &&
2896 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2897 !F->doesNotAccessMemory())
Reid Klecknerb5180542017-03-21 16:57:19 +00002898 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002899}
James Molloya9290632017-05-25 12:51:11 +00002900
2901bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2902 // We can't have a PHI with a metadata type.
2903 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2904 return false;
2905
2906 // Early exit.
2907 if (!isa<Constant>(I->getOperand(OpIdx)))
2908 return true;
2909
2910 switch (I->getOpcode()) {
2911 default:
2912 return true;
2913 case Instruction::Call:
2914 case Instruction::Invoke:
Leo Li93abd7d2017-07-10 20:45:34 +00002915 // Can't handle inline asm. Skip it.
2916 if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
2917 return false;
James Molloya9290632017-05-25 12:51:11 +00002918 // Many arithmetic intrinsics have no issue taking a
2919 // variable, however it's hard to distingish these from
2920 // specials such as @llvm.frameaddress that require a constant.
2921 if (isa<IntrinsicInst>(I))
2922 return false;
2923
2924 // Constant bundle operands may need to retain their constant-ness for
2925 // correctness.
2926 if (ImmutableCallSite(I).isBundleOperand(OpIdx))
2927 return false;
2928 return true;
2929 case Instruction::ShuffleVector:
2930 // Shufflevector masks are constant.
2931 return OpIdx != 2;
Leo Li5499b1b2017-07-06 18:47:05 +00002932 case Instruction::Switch:
James Molloya9290632017-05-25 12:51:11 +00002933 case Instruction::ExtractValue:
James Molloya9290632017-05-25 12:51:11 +00002934 // All operands apart from the first are constant.
2935 return OpIdx == 0;
Leo Li5499b1b2017-07-06 18:47:05 +00002936 case Instruction::InsertValue:
2937 // All operands apart from the first and the second are constant.
2938 return OpIdx < 2;
James Molloya9290632017-05-25 12:51:11 +00002939 case Instruction::Alloca:
Leo Li5499b1b2017-07-06 18:47:05 +00002940 // Static allocas (constant size in the entry block) are handled by
2941 // prologue/epilogue insertion so they're free anyway. We definitely don't
2942 // want to make them non-constant.
Craig Topper781aa182018-05-05 01:57:00 +00002943 return !cast<AllocaInst>(I)->isStaticAlloca();
James Molloya9290632017-05-25 12:51:11 +00002944 case Instruction::GetElementPtr:
2945 if (OpIdx == 0)
2946 return true;
2947 gep_type_iterator It = gep_type_begin(I);
2948 for (auto E = std::next(It, OpIdx); It != E; ++It)
2949 if (It.isStruct())
2950 return false;
2951 return true;
2952 }
2953}
Alexander Potapenko6a63e5a2019-04-15 08:59:56 +00002954
2955using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
2956AllocaInst *llvm::findAllocaForValue(Value *V,
2957 AllocaForValueMapTy &AllocaForValue) {
2958 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2959 return AI;
2960 // See if we've already calculated (or started to calculate) alloca for a
2961 // given value.
2962 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2963 if (I != AllocaForValue.end())
2964 return I->second;
2965 // Store 0 while we're calculating alloca for value V to avoid
2966 // infinite recursion if the value references itself.
2967 AllocaForValue[V] = nullptr;
2968 AllocaInst *Res = nullptr;
2969 if (CastInst *CI = dyn_cast<CastInst>(V))
2970 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
2971 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2972 for (Value *IncValue : PN->incoming_values()) {
2973 // Allow self-referencing phi-nodes.
2974 if (IncValue == PN)
2975 continue;
2976 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
2977 // AI for incoming values should exist and should all be equal.
2978 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2979 return nullptr;
2980 Res = IncValueAI;
2981 }
2982 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2983 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
2984 } else {
2985 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
2986 << *V << "\n");
2987 }
2988 if (Res)
2989 AllocaForValue[V] = Res;
2990 return Res;
2991}