1 //===- Local.cpp - Functions to perform local transformations -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions perform various local transformations to the
10 // program.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/Analysis/AssumeBundleQueries.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/DomTreeUpdater.h"
31 #include "llvm/Analysis/EHPersonalities.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/LazyValueInfo.h"
34 #include "llvm/Analysis/MemoryBuiltins.h"
35 #include "llvm/Analysis/MemorySSAUpdater.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/BinaryFormat/Dwarf.h"
40 #include "llvm/IR/Argument.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/ConstantRange.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DIBuilder.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalObject.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
79 #include "llvm/Transforms/Utils/ValueMapper.h"
80 #include <algorithm>
81 #include <cassert>
82 #include <climits>
83 #include <cstdint>
84 #include <iterator>
85 #include <map>
86 #include <utility>
87
88 using namespace llvm;
89 using namespace llvm::PatternMatch;
90
91 #define DEBUG_TYPE "local"
92
93 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
94
95 // Max recursion depth for collectBitParts used when detecting bswap and
96 // bitreverse idioms
97 static const unsigned BitPartRecursionMaxDepth = 64;
98
99 //===----------------------------------------------------------------------===//
100 // Local constant propagation.
101 //
102
103 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
104 /// constant value, convert it into an unconditional branch to the constant
105 /// destination. This is a nontrivial operation because the successors of this
106 /// basic block must have their PHI nodes updated.
107 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
108 /// conditions and indirectbr addresses this might make dead if
109 /// DeleteDeadConditions is true.
ConstantFoldTerminator(BasicBlock * BB,bool DeleteDeadConditions,const TargetLibraryInfo * TLI,DomTreeUpdater * DTU)110 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
111 const TargetLibraryInfo *TLI,
112 DomTreeUpdater *DTU) {
113 Instruction *T = BB->getTerminator();
114 IRBuilder<> Builder(T);
115
116 // Branch - See if we are conditional jumping on constant
117 if (auto *BI = dyn_cast<BranchInst>(T)) {
118 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
119 BasicBlock *Dest1 = BI->getSuccessor(0);
120 BasicBlock *Dest2 = BI->getSuccessor(1);
121
122 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
123 // Are we branching on constant?
124 // YES. Change to unconditional branch...
125 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
126 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
127
128 // Let the basic block know that we are letting go of it. Based on this,
129 // it will adjust it's PHI nodes.
130 OldDest->removePredecessor(BB);
131
132 // Replace the conditional branch with an unconditional one.
133 Builder.CreateBr(Destination);
134 BI->eraseFromParent();
135 if (DTU)
136 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
137 return true;
138 }
139
140 if (Dest2 == Dest1) { // Conditional branch to same location?
141 // This branch matches something like this:
142 // br bool %cond, label %Dest, label %Dest
143 // and changes it into: br label %Dest
144
145 // Let the basic block know that we are letting go of one copy of it.
146 assert(BI->getParent() && "Terminator not inserted in block!");
147 Dest1->removePredecessor(BI->getParent());
148
149 // Replace the conditional branch with an unconditional one.
150 Builder.CreateBr(Dest1);
151 Value *Cond = BI->getCondition();
152 BI->eraseFromParent();
153 if (DeleteDeadConditions)
154 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
155 return true;
156 }
157 return false;
158 }
159
160 if (auto *SI = dyn_cast<SwitchInst>(T)) {
161 // If we are switching on a constant, we can convert the switch to an
162 // unconditional branch.
163 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
164 BasicBlock *DefaultDest = SI->getDefaultDest();
165 BasicBlock *TheOnlyDest = DefaultDest;
166
167 // If the default is unreachable, ignore it when searching for TheOnlyDest.
168 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
169 SI->getNumCases() > 0) {
170 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
171 }
172
173 // Figure out which case it goes to.
174 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
175 // Found case matching a constant operand?
176 if (i->getCaseValue() == CI) {
177 TheOnlyDest = i->getCaseSuccessor();
178 break;
179 }
180
181 // Check to see if this branch is going to the same place as the default
182 // dest. If so, eliminate it as an explicit compare.
183 if (i->getCaseSuccessor() == DefaultDest) {
184 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
185 unsigned NCases = SI->getNumCases();
186 // Fold the case metadata into the default if there will be any branches
187 // left, unless the metadata doesn't match the switch.
188 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
189 // Collect branch weights into a vector.
190 SmallVector<uint32_t, 8> Weights;
191 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
192 ++MD_i) {
193 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
194 Weights.push_back(CI->getValue().getZExtValue());
195 }
196 // Merge weight of this case to the default weight.
197 unsigned idx = i->getCaseIndex();
198 Weights[0] += Weights[idx+1];
199 // Remove weight for this case.
200 std::swap(Weights[idx+1], Weights.back());
201 Weights.pop_back();
202 SI->setMetadata(LLVMContext::MD_prof,
203 MDBuilder(BB->getContext()).
204 createBranchWeights(Weights));
205 }
206 // Remove this entry.
207 BasicBlock *ParentBB = SI->getParent();
208 DefaultDest->removePredecessor(ParentBB);
209 i = SI->removeCase(i);
210 e = SI->case_end();
211 if (DTU)
212 DTU->applyUpdatesPermissive(
213 {{DominatorTree::Delete, ParentBB, DefaultDest}});
214 continue;
215 }
216
217 // Otherwise, check to see if the switch only branches to one destination.
218 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
219 // destinations.
220 if (i->getCaseSuccessor() != TheOnlyDest)
221 TheOnlyDest = nullptr;
222
223 // Increment this iterator as we haven't removed the case.
224 ++i;
225 }
226
227 if (CI && !TheOnlyDest) {
228 // Branching on a constant, but not any of the cases, go to the default
229 // successor.
230 TheOnlyDest = SI->getDefaultDest();
231 }
232
233 // If we found a single destination that we can fold the switch into, do so
234 // now.
235 if (TheOnlyDest) {
236 // Insert the new branch.
237 Builder.CreateBr(TheOnlyDest);
238 BasicBlock *BB = SI->getParent();
239 std::vector <DominatorTree::UpdateType> Updates;
240 if (DTU)
241 Updates.reserve(SI->getNumSuccessors() - 1);
242
243 // Remove entries from PHI nodes which we no longer branch to...
244 for (BasicBlock *Succ : successors(SI)) {
245 // Found case matching a constant operand?
246 if (Succ == TheOnlyDest) {
247 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
248 } else {
249 Succ->removePredecessor(BB);
250 if (DTU)
251 Updates.push_back({DominatorTree::Delete, BB, Succ});
252 }
253 }
254
255 // Delete the old switch.
256 Value *Cond = SI->getCondition();
257 SI->eraseFromParent();
258 if (DeleteDeadConditions)
259 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
260 if (DTU)
261 DTU->applyUpdatesPermissive(Updates);
262 return true;
263 }
264
265 if (SI->getNumCases() == 1) {
266 // Otherwise, we can fold this switch into a conditional branch
267 // instruction if it has only one non-default destination.
268 auto FirstCase = *SI->case_begin();
269 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
270 FirstCase.getCaseValue(), "cond");
271
272 // Insert the new branch.
273 BranchInst *NewBr = Builder.CreateCondBr(Cond,
274 FirstCase.getCaseSuccessor(),
275 SI->getDefaultDest());
276 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
277 if (MD && MD->getNumOperands() == 3) {
278 ConstantInt *SICase =
279 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
280 ConstantInt *SIDef =
281 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
282 assert(SICase && SIDef);
283 // The TrueWeight should be the weight for the single case of SI.
284 NewBr->setMetadata(LLVMContext::MD_prof,
285 MDBuilder(BB->getContext()).
286 createBranchWeights(SICase->getValue().getZExtValue(),
287 SIDef->getValue().getZExtValue()));
288 }
289
290 // Update make.implicit metadata to the newly-created conditional branch.
291 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
292 if (MakeImplicitMD)
293 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
294
295 // Delete the old switch.
296 SI->eraseFromParent();
297 return true;
298 }
299 return false;
300 }
301
302 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
303 // indirectbr blockaddress(@F, @BB) -> br label @BB
304 if (auto *BA =
305 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
306 BasicBlock *TheOnlyDest = BA->getBasicBlock();
307 std::vector <DominatorTree::UpdateType> Updates;
308 if (DTU)
309 Updates.reserve(IBI->getNumDestinations() - 1);
310
311 // Insert the new branch.
312 Builder.CreateBr(TheOnlyDest);
313
314 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
315 if (IBI->getDestination(i) == TheOnlyDest) {
316 TheOnlyDest = nullptr;
317 } else {
318 BasicBlock *ParentBB = IBI->getParent();
319 BasicBlock *DestBB = IBI->getDestination(i);
320 DestBB->removePredecessor(ParentBB);
321 if (DTU)
322 Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
323 }
324 }
325 Value *Address = IBI->getAddress();
326 IBI->eraseFromParent();
327 if (DeleteDeadConditions)
328 // Delete pointer cast instructions.
329 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
330
331 // Also zap the blockaddress constant if there are no users remaining,
332 // otherwise the destination is still marked as having its address taken.
333 if (BA->use_empty())
334 BA->destroyConstant();
335
336 // If we didn't find our destination in the IBI successor list, then we
337 // have undefined behavior. Replace the unconditional branch with an
338 // 'unreachable' instruction.
339 if (TheOnlyDest) {
340 BB->getTerminator()->eraseFromParent();
341 new UnreachableInst(BB->getContext(), BB);
342 }
343
344 if (DTU)
345 DTU->applyUpdatesPermissive(Updates);
346 return true;
347 }
348 }
349
350 return false;
351 }
352
353 //===----------------------------------------------------------------------===//
354 // Local dead code elimination.
355 //
356
357 /// isInstructionTriviallyDead - Return true if the result produced by the
358 /// instruction is not used, and the instruction has no side effects.
359 ///
isInstructionTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)360 bool llvm::isInstructionTriviallyDead(Instruction *I,
361 const TargetLibraryInfo *TLI) {
362 if (!I->use_empty())
363 return false;
364 return wouldInstructionBeTriviallyDead(I, TLI);
365 }
366
wouldInstructionBeTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)367 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
368 const TargetLibraryInfo *TLI) {
369 if (I->isTerminator())
370 return false;
371
372 // We don't want the landingpad-like instructions removed by anything this
373 // general.
374 if (I->isEHPad())
375 return false;
376
377 // We don't want debug info removed by anything this general, unless
378 // debug info is empty.
379 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
380 if (DDI->getAddress())
381 return false;
382 return true;
383 }
384 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
385 if (DVI->getValue())
386 return false;
387 return true;
388 }
389 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
390 if (DLI->getLabel())
391 return false;
392 return true;
393 }
394
395 if (!I->mayHaveSideEffects())
396 return true;
397
398 // Special case intrinsics that "may have side effects" but can be deleted
399 // when dead.
400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
401 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
402 if (II->getIntrinsicID() == Intrinsic::stacksave ||
403 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
404 return true;
405
406 if (II->isLifetimeStartOrEnd()) {
407 auto *Arg = II->getArgOperand(1);
408 // Lifetime intrinsics are dead when their right-hand is undef.
409 if (isa<UndefValue>(Arg))
410 return true;
411 // If the right-hand is an alloc, global, or argument and the only uses
412 // are lifetime intrinsics then the intrinsics are dead.
413 if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
414 return llvm::all_of(Arg->uses(), [](Use &Use) {
415 if (IntrinsicInst *IntrinsicUse =
416 dyn_cast<IntrinsicInst>(Use.getUser()))
417 return IntrinsicUse->isLifetimeStartOrEnd();
418 return false;
419 });
420 return false;
421 }
422
423 // Assumptions are dead if their condition is trivially true. Guards on
424 // true are operationally no-ops. In the future we can consider more
425 // sophisticated tradeoffs for guards considering potential for check
426 // widening, but for now we keep things simple.
427 if ((II->getIntrinsicID() == Intrinsic::assume &&
428 isAssumeWithEmptyBundle(*II)) ||
429 II->getIntrinsicID() == Intrinsic::experimental_guard) {
430 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
431 return !Cond->isZero();
432
433 return false;
434 }
435 }
436
437 if (isAllocLikeFn(I, TLI))
438 return true;
439
440 if (CallInst *CI = isFreeCall(I, TLI))
441 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
442 return C->isNullValue() || isa<UndefValue>(C);
443
444 if (auto *Call = dyn_cast<CallBase>(I))
445 if (isMathLibCallNoop(Call, TLI))
446 return true;
447
448 return false;
449 }
450
451 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
452 /// trivially dead instruction, delete it. If that makes any of its operands
453 /// trivially dead, delete them too, recursively. Return true if any
454 /// instructions were deleted.
RecursivelyDeleteTriviallyDeadInstructions(Value * V,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)455 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
456 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
457 std::function<void(Value *)> AboutToDeleteCallback) {
458 Instruction *I = dyn_cast<Instruction>(V);
459 if (!I || !isInstructionTriviallyDead(I, TLI))
460 return false;
461
462 SmallVector<WeakTrackingVH, 16> DeadInsts;
463 DeadInsts.push_back(I);
464 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
465 AboutToDeleteCallback);
466
467 return true;
468 }
469
RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)470 bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
471 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
472 MemorySSAUpdater *MSSAU,
473 std::function<void(Value *)> AboutToDeleteCallback) {
474 unsigned S = 0, E = DeadInsts.size(), Alive = 0;
475 for (; S != E; ++S) {
476 auto *I = cast<Instruction>(DeadInsts[S]);
477 if (!isInstructionTriviallyDead(I)) {
478 DeadInsts[S] = nullptr;
479 ++Alive;
480 }
481 }
482 if (Alive == E)
483 return false;
484 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
485 AboutToDeleteCallback);
486 return true;
487 }
488
RecursivelyDeleteTriviallyDeadInstructions(SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU,std::function<void (Value *)> AboutToDeleteCallback)489 void llvm::RecursivelyDeleteTriviallyDeadInstructions(
490 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
491 MemorySSAUpdater *MSSAU,
492 std::function<void(Value *)> AboutToDeleteCallback) {
493 // Process the dead instruction list until empty.
494 while (!DeadInsts.empty()) {
495 Value *V = DeadInsts.pop_back_val();
496 Instruction *I = cast_or_null<Instruction>(V);
497 if (!I)
498 continue;
499 assert(isInstructionTriviallyDead(I, TLI) &&
500 "Live instruction found in dead worklist!");
501 assert(I->use_empty() && "Instructions with uses are not dead.");
502
503 // Don't lose the debug info while deleting the instructions.
504 salvageDebugInfo(*I);
505
506 if (AboutToDeleteCallback)
507 AboutToDeleteCallback(I);
508
509 // Null out all of the instruction's operands to see if any operand becomes
510 // dead as we go.
511 for (Use &OpU : I->operands()) {
512 Value *OpV = OpU.get();
513 OpU.set(nullptr);
514
515 if (!OpV->use_empty())
516 continue;
517
518 // If the operand is an instruction that became dead as we nulled out the
519 // operand, and if it is 'trivially' dead, delete it in a future loop
520 // iteration.
521 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
522 if (isInstructionTriviallyDead(OpI, TLI))
523 DeadInsts.push_back(OpI);
524 }
525 if (MSSAU)
526 MSSAU->removeMemoryAccess(I);
527
528 I->eraseFromParent();
529 }
530 }
531
replaceDbgUsesWithUndef(Instruction * I)532 bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
533 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
534 findDbgUsers(DbgUsers, I);
535 for (auto *DII : DbgUsers) {
536 Value *Undef = UndefValue::get(I->getType());
537 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
538 ValueAsMetadata::get(Undef)));
539 }
540 return !DbgUsers.empty();
541 }
542
543 /// areAllUsesEqual - Check whether the uses of a value are all the same.
544 /// This is similar to Instruction::hasOneUse() except this will also return
545 /// true when there are no uses or multiple uses that all refer to the same
546 /// value.
areAllUsesEqual(Instruction * I)547 static bool areAllUsesEqual(Instruction *I) {
548 Value::user_iterator UI = I->user_begin();
549 Value::user_iterator UE = I->user_end();
550 if (UI == UE)
551 return true;
552
553 User *TheUse = *UI;
554 for (++UI; UI != UE; ++UI) {
555 if (*UI != TheUse)
556 return false;
557 }
558 return true;
559 }
560
561 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
562 /// dead PHI node, due to being a def-use chain of single-use nodes that
563 /// either forms a cycle or is terminated by a trivially dead instruction,
564 /// delete it. If that makes any of its operands trivially dead, delete them
565 /// too, recursively. Return true if a change was made.
RecursivelyDeleteDeadPHINode(PHINode * PN,const TargetLibraryInfo * TLI,llvm::MemorySSAUpdater * MSSAU)566 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
567 const TargetLibraryInfo *TLI,
568 llvm::MemorySSAUpdater *MSSAU) {
569 SmallPtrSet<Instruction*, 4> Visited;
570 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
571 I = cast<Instruction>(*I->user_begin())) {
572 if (I->use_empty())
573 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
574
575 // If we find an instruction more than once, we're on a cycle that
576 // won't prove fruitful.
577 if (!Visited.insert(I).second) {
578 // Break the cycle and delete the instruction and its operands.
579 I->replaceAllUsesWith(UndefValue::get(I->getType()));
580 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
581 return true;
582 }
583 }
584 return false;
585 }
586
587 static bool
simplifyAndDCEInstruction(Instruction * I,SmallSetVector<Instruction *,16> & WorkList,const DataLayout & DL,const TargetLibraryInfo * TLI)588 simplifyAndDCEInstruction(Instruction *I,
589 SmallSetVector<Instruction *, 16> &WorkList,
590 const DataLayout &DL,
591 const TargetLibraryInfo *TLI) {
592 if (isInstructionTriviallyDead(I, TLI)) {
593 salvageDebugInfo(*I);
594
595 // Null out all of the instruction's operands to see if any operand becomes
596 // dead as we go.
597 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
598 Value *OpV = I->getOperand(i);
599 I->setOperand(i, nullptr);
600
601 if (!OpV->use_empty() || I == OpV)
602 continue;
603
604 // If the operand is an instruction that became dead as we nulled out the
605 // operand, and if it is 'trivially' dead, delete it in a future loop
606 // iteration.
607 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
608 if (isInstructionTriviallyDead(OpI, TLI))
609 WorkList.insert(OpI);
610 }
611
612 I->eraseFromParent();
613
614 return true;
615 }
616
617 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
618 // Add the users to the worklist. CAREFUL: an instruction can use itself,
619 // in the case of a phi node.
620 for (User *U : I->users()) {
621 if (U != I) {
622 WorkList.insert(cast<Instruction>(U));
623 }
624 }
625
626 // Replace the instruction with its simplified value.
627 bool Changed = false;
628 if (!I->use_empty()) {
629 I->replaceAllUsesWith(SimpleV);
630 Changed = true;
631 }
632 if (isInstructionTriviallyDead(I, TLI)) {
633 I->eraseFromParent();
634 Changed = true;
635 }
636 return Changed;
637 }
638 return false;
639 }
640
641 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
642 /// simplify any instructions in it and recursively delete dead instructions.
643 ///
644 /// This returns true if it changed the code, note that it can delete
645 /// instructions in other blocks as well in this block.
SimplifyInstructionsInBlock(BasicBlock * BB,const TargetLibraryInfo * TLI)646 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
647 const TargetLibraryInfo *TLI) {
648 bool MadeChange = false;
649 const DataLayout &DL = BB->getModule()->getDataLayout();
650
651 #ifndef NDEBUG
652 // In debug builds, ensure that the terminator of the block is never replaced
653 // or deleted by these simplifications. The idea of simplification is that it
654 // cannot introduce new instructions, and there is no way to replace the
655 // terminator of a block without introducing a new instruction.
656 AssertingVH<Instruction> TerminatorVH(&BB->back());
657 #endif
658
659 SmallSetVector<Instruction *, 16> WorkList;
660 // Iterate over the original function, only adding insts to the worklist
661 // if they actually need to be revisited. This avoids having to pre-init
662 // the worklist with the entire function's worth of instructions.
663 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
664 BI != E;) {
665 assert(!BI->isTerminator());
666 Instruction *I = &*BI;
667 ++BI;
668
669 // We're visiting this instruction now, so make sure it's not in the
670 // worklist from an earlier visit.
671 if (!WorkList.count(I))
672 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
673 }
674
675 while (!WorkList.empty()) {
676 Instruction *I = WorkList.pop_back_val();
677 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
678 }
679 return MadeChange;
680 }
681
682 //===----------------------------------------------------------------------===//
683 // Control Flow Graph Restructuring.
684 //
685
RemovePredecessorAndSimplify(BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)686 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
687 DomTreeUpdater *DTU) {
688 // This only adjusts blocks with PHI nodes.
689 if (!isa<PHINode>(BB->begin()))
690 return;
691
692 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
693 // them down. This will leave us with single entry phi nodes and other phis
694 // that can be removed.
695 BB->removePredecessor(Pred, true);
696
697 WeakTrackingVH PhiIt = &BB->front();
698 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
699 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
700 Value *OldPhiIt = PhiIt;
701
702 if (!recursivelySimplifyInstruction(PN))
703 continue;
704
705 // If recursive simplification ended up deleting the next PHI node we would
706 // iterate to, then our iterator is invalid, restart scanning from the top
707 // of the block.
708 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
709 }
710 if (DTU)
711 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
712 }
713
MergeBasicBlockIntoOnlyPred(BasicBlock * DestBB,DomTreeUpdater * DTU)714 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
715 DomTreeUpdater *DTU) {
716
717 // If BB has single-entry PHI nodes, fold them.
718 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
719 Value *NewVal = PN->getIncomingValue(0);
720 // Replace self referencing PHI with undef, it must be dead.
721 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
722 PN->replaceAllUsesWith(NewVal);
723 PN->eraseFromParent();
724 }
725
726 BasicBlock *PredBB = DestBB->getSinglePredecessor();
727 assert(PredBB && "Block doesn't have a single predecessor!");
728
729 bool ReplaceEntryBB = false;
730 if (PredBB == &DestBB->getParent()->getEntryBlock())
731 ReplaceEntryBB = true;
732
733 // DTU updates: Collect all the edges that enter
734 // PredBB. These dominator edges will be redirected to DestBB.
735 SmallVector<DominatorTree::UpdateType, 32> Updates;
736
737 if (DTU) {
738 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
739 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
740 Updates.push_back({DominatorTree::Delete, *I, PredBB});
741 // This predecessor of PredBB may already have DestBB as a successor.
742 if (llvm::find(successors(*I), DestBB) == succ_end(*I))
743 Updates.push_back({DominatorTree::Insert, *I, DestBB});
744 }
745 }
746
747 // Zap anything that took the address of DestBB. Not doing this will give the
748 // address an invalid value.
749 if (DestBB->hasAddressTaken()) {
750 BlockAddress *BA = BlockAddress::get(DestBB);
751 Constant *Replacement =
752 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
753 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
754 BA->getType()));
755 BA->destroyConstant();
756 }
757
758 // Anything that branched to PredBB now branches to DestBB.
759 PredBB->replaceAllUsesWith(DestBB);
760
761 // Splice all the instructions from PredBB to DestBB.
762 PredBB->getTerminator()->eraseFromParent();
763 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
764 new UnreachableInst(PredBB->getContext(), PredBB);
765
766 // If the PredBB is the entry block of the function, move DestBB up to
767 // become the entry block after we erase PredBB.
768 if (ReplaceEntryBB)
769 DestBB->moveAfter(PredBB);
770
771 if (DTU) {
772 assert(PredBB->getInstList().size() == 1 &&
773 isa<UnreachableInst>(PredBB->getTerminator()) &&
774 "The successor list of PredBB isn't empty before "
775 "applying corresponding DTU updates.");
776 DTU->applyUpdatesPermissive(Updates);
777 DTU->deleteBB(PredBB);
778 // Recalculation of DomTree is needed when updating a forward DomTree and
779 // the Entry BB is replaced.
780 if (ReplaceEntryBB && DTU->hasDomTree()) {
781 // The entry block was removed and there is no external interface for
782 // the dominator tree to be notified of this change. In this corner-case
783 // we recalculate the entire tree.
784 DTU->recalculate(*(DestBB->getParent()));
785 }
786 }
787
788 else {
789 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
790 }
791 }
792
793 /// Return true if we can choose one of these values to use in place of the
794 /// other. Note that we will always choose the non-undef value to keep.
CanMergeValues(Value * First,Value * Second)795 static bool CanMergeValues(Value *First, Value *Second) {
796 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
797 }
798
799 /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
800 /// branch to Succ, into Succ.
801 ///
802 /// Assumption: Succ is the single successor for BB.
CanPropagatePredecessorsForPHIs(BasicBlock * BB,BasicBlock * Succ)803 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
804 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
805
806 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
807 << Succ->getName() << "\n");
808 // Shortcut, if there is only a single predecessor it must be BB and merging
809 // is always safe
810 if (Succ->getSinglePredecessor()) return true;
811
812 // Make a list of the predecessors of BB
813 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
814
815 // Look at all the phi nodes in Succ, to see if they present a conflict when
816 // merging these blocks
817 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
818 PHINode *PN = cast<PHINode>(I);
819
820 // If the incoming value from BB is again a PHINode in
821 // BB which has the same incoming value for *PI as PN does, we can
822 // merge the phi nodes and then the blocks can still be merged
823 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
824 if (BBPN && BBPN->getParent() == BB) {
825 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
826 BasicBlock *IBB = PN->getIncomingBlock(PI);
827 if (BBPreds.count(IBB) &&
828 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
829 PN->getIncomingValue(PI))) {
830 LLVM_DEBUG(dbgs()
831 << "Can't fold, phi node " << PN->getName() << " in "
832 << Succ->getName() << " is conflicting with "
833 << BBPN->getName() << " with regard to common predecessor "
834 << IBB->getName() << "\n");
835 return false;
836 }
837 }
838 } else {
839 Value* Val = PN->getIncomingValueForBlock(BB);
840 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
841 // See if the incoming value for the common predecessor is equal to the
842 // one for BB, in which case this phi node will not prevent the merging
843 // of the block.
844 BasicBlock *IBB = PN->getIncomingBlock(PI);
845 if (BBPreds.count(IBB) &&
846 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
847 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
848 << " in " << Succ->getName()
849 << " is conflicting with regard to common "
850 << "predecessor " << IBB->getName() << "\n");
851 return false;
852 }
853 }
854 }
855 }
856
857 return true;
858 }
859
860 using PredBlockVector = SmallVector<BasicBlock *, 16>;
861 using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
862
863 /// Determines the value to use as the phi node input for a block.
864 ///
865 /// Select between \p OldVal any value that we know flows from \p BB
866 /// to a particular phi on the basis of which one (if either) is not
867 /// undef. Update IncomingValues based on the selected value.
868 ///
869 /// \param OldVal The value we are considering selecting.
870 /// \param BB The block that the value flows in from.
871 /// \param IncomingValues A map from block-to-value for other phi inputs
872 /// that we have examined.
873 ///
874 /// \returns the selected value.
selectIncomingValueForBlock(Value * OldVal,BasicBlock * BB,IncomingValueMap & IncomingValues)875 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
876 IncomingValueMap &IncomingValues) {
877 if (!isa<UndefValue>(OldVal)) {
878 assert((!IncomingValues.count(BB) ||
879 IncomingValues.find(BB)->second == OldVal) &&
880 "Expected OldVal to match incoming value from BB!");
881
882 IncomingValues.insert(std::make_pair(BB, OldVal));
883 return OldVal;
884 }
885
886 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
887 if (It != IncomingValues.end()) return It->second;
888
889 return OldVal;
890 }
891
892 /// Create a map from block to value for the operands of a
893 /// given phi.
894 ///
895 /// Create a map from block to value for each non-undef value flowing
896 /// into \p PN.
897 ///
898 /// \param PN The phi we are collecting the map for.
899 /// \param IncomingValues [out] The map from block to value for this phi.
gatherIncomingValuesToPhi(PHINode * PN,IncomingValueMap & IncomingValues)900 static void gatherIncomingValuesToPhi(PHINode *PN,
901 IncomingValueMap &IncomingValues) {
902 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
903 BasicBlock *BB = PN->getIncomingBlock(i);
904 Value *V = PN->getIncomingValue(i);
905
906 if (!isa<UndefValue>(V))
907 IncomingValues.insert(std::make_pair(BB, V));
908 }
909 }
910
911 /// Replace the incoming undef values to a phi with the values
912 /// from a block-to-value map.
913 ///
914 /// \param PN The phi we are replacing the undefs in.
915 /// \param IncomingValues A map from block to value.
replaceUndefValuesInPhi(PHINode * PN,const IncomingValueMap & IncomingValues)916 static void replaceUndefValuesInPhi(PHINode *PN,
917 const IncomingValueMap &IncomingValues) {
918 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
919 Value *V = PN->getIncomingValue(i);
920
921 if (!isa<UndefValue>(V)) continue;
922
923 BasicBlock *BB = PN->getIncomingBlock(i);
924 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
925 if (It == IncomingValues.end()) continue;
926
927 PN->setIncomingValue(i, It->second);
928 }
929 }
930
931 /// Replace a value flowing from a block to a phi with
932 /// potentially multiple instances of that value flowing from the
933 /// block's predecessors to the phi.
934 ///
935 /// \param BB The block with the value flowing into the phi.
936 /// \param BBPreds The predecessors of BB.
937 /// \param PN The phi that we are updating.
redirectValuesFromPredecessorsToPhi(BasicBlock * BB,const PredBlockVector & BBPreds,PHINode * PN)938 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
939 const PredBlockVector &BBPreds,
940 PHINode *PN) {
941 Value *OldVal = PN->removeIncomingValue(BB, false);
942 assert(OldVal && "No entry in PHI for Pred BB!");
943
944 IncomingValueMap IncomingValues;
945
946 // We are merging two blocks - BB, and the block containing PN - and
947 // as a result we need to redirect edges from the predecessors of BB
948 // to go to the block containing PN, and update PN
949 // accordingly. Since we allow merging blocks in the case where the
950 // predecessor and successor blocks both share some predecessors,
951 // and where some of those common predecessors might have undef
952 // values flowing into PN, we want to rewrite those values to be
953 // consistent with the non-undef values.
954
955 gatherIncomingValuesToPhi(PN, IncomingValues);
956
957 // If this incoming value is one of the PHI nodes in BB, the new entries
958 // in the PHI node are the entries from the old PHI.
959 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
960 PHINode *OldValPN = cast<PHINode>(OldVal);
961 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
962 // Note that, since we are merging phi nodes and BB and Succ might
963 // have common predecessors, we could end up with a phi node with
964 // identical incoming branches. This will be cleaned up later (and
965 // will trigger asserts if we try to clean it up now, without also
966 // simplifying the corresponding conditional branch).
967 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
968 Value *PredVal = OldValPN->getIncomingValue(i);
969 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
970 IncomingValues);
971
972 // And add a new incoming value for this predecessor for the
973 // newly retargeted branch.
974 PN->addIncoming(Selected, PredBB);
975 }
976 } else {
977 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
978 // Update existing incoming values in PN for this
979 // predecessor of BB.
980 BasicBlock *PredBB = BBPreds[i];
981 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
982 IncomingValues);
983
984 // And add a new incoming value for this predecessor for the
985 // newly retargeted branch.
986 PN->addIncoming(Selected, PredBB);
987 }
988 }
989
990 replaceUndefValuesInPhi(PN, IncomingValues);
991 }
992
TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock * BB,DomTreeUpdater * DTU)993 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
994 DomTreeUpdater *DTU) {
995 assert(BB != &BB->getParent()->getEntryBlock() &&
996 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
997
998 // We can't eliminate infinite loops.
999 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
1000 if (BB == Succ) return false;
1001
1002 // Check to see if merging these blocks would cause conflicts for any of the
1003 // phi nodes in BB or Succ. If not, we can safely merge.
1004 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
1005
1006 // Check for cases where Succ has multiple predecessors and a PHI node in BB
1007 // has uses which will not disappear when the PHI nodes are merged. It is
1008 // possible to handle such cases, but difficult: it requires checking whether
1009 // BB dominates Succ, which is non-trivial to calculate in the case where
1010 // Succ has multiple predecessors. Also, it requires checking whether
1011 // constructing the necessary self-referential PHI node doesn't introduce any
1012 // conflicts; this isn't too difficult, but the previous code for doing this
1013 // was incorrect.
1014 //
1015 // Note that if this check finds a live use, BB dominates Succ, so BB is
1016 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1017 // folding the branch isn't profitable in that case anyway.
1018 if (!Succ->getSinglePredecessor()) {
1019 BasicBlock::iterator BBI = BB->begin();
1020 while (isa<PHINode>(*BBI)) {
1021 for (Use &U : BBI->uses()) {
1022 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1023 if (PN->getIncomingBlock(U) != BB)
1024 return false;
1025 } else {
1026 return false;
1027 }
1028 }
1029 ++BBI;
1030 }
1031 }
1032
1033 // We cannot fold the block if it's a branch to an already present callbr
1034 // successor because that creates duplicate successors.
1035 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1036 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
1037 if (Succ == CBI->getDefaultDest())
1038 return false;
1039 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
1040 if (Succ == CBI->getIndirectDest(i))
1041 return false;
1042 }
1043 }
1044
1045 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1046
1047 SmallVector<DominatorTree::UpdateType, 32> Updates;
1048 if (DTU) {
1049 Updates.push_back({DominatorTree::Delete, BB, Succ});
1050 // All predecessors of BB will be moved to Succ.
1051 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1052 Updates.push_back({DominatorTree::Delete, *I, BB});
1053 // This predecessor of BB may already have Succ as a successor.
1054 if (llvm::find(successors(*I), Succ) == succ_end(*I))
1055 Updates.push_back({DominatorTree::Insert, *I, Succ});
1056 }
1057 }
1058
1059 if (isa<PHINode>(Succ->begin())) {
1060 // If there is more than one pred of succ, and there are PHI nodes in
1061 // the successor, then we need to add incoming edges for the PHI nodes
1062 //
1063 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1064
1065 // Loop over all of the PHI nodes in the successor of BB.
1066 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1067 PHINode *PN = cast<PHINode>(I);
1068
1069 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1070 }
1071 }
1072
1073 if (Succ->getSinglePredecessor()) {
1074 // BB is the only predecessor of Succ, so Succ will end up with exactly
1075 // the same predecessors BB had.
1076
1077 // Copy over any phi, debug or lifetime instruction.
1078 BB->getTerminator()->eraseFromParent();
1079 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1080 BB->getInstList());
1081 } else {
1082 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1083 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1084 assert(PN->use_empty() && "There shouldn't be any uses here!");
1085 PN->eraseFromParent();
1086 }
1087 }
1088
1089 // If the unconditional branch we replaced contains llvm.loop metadata, we
1090 // add the metadata to the branch instructions in the predecessors.
1091 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1092 Instruction *TI = BB->getTerminator();
1093 if (TI)
1094 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1095 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1096 BasicBlock *Pred = *PI;
1097 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1098 }
1099
1100 // Everything that jumped to BB now goes to Succ.
1101 BB->replaceAllUsesWith(Succ);
1102 if (!Succ->hasName()) Succ->takeName(BB);
1103
1104 // Clear the successor list of BB to match updates applying to DTU later.
1105 if (BB->getTerminator())
1106 BB->getInstList().pop_back();
1107 new UnreachableInst(BB->getContext(), BB);
1108 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1109 "applying corresponding DTU updates.");
1110
1111 if (DTU) {
1112 DTU->applyUpdatesPermissive(Updates);
1113 DTU->deleteBB(BB);
1114 } else {
1115 BB->eraseFromParent(); // Delete the old basic block.
1116 }
1117 return true;
1118 }
1119
EliminateDuplicatePHINodes(BasicBlock * BB)1120 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1121 // This implementation doesn't currently consider undef operands
1122 // specially. Theoretically, two phis which are identical except for
1123 // one having an undef where the other doesn't could be collapsed.
1124
1125 struct PHIDenseMapInfo {
1126 static PHINode *getEmptyKey() {
1127 return DenseMapInfo<PHINode *>::getEmptyKey();
1128 }
1129
1130 static PHINode *getTombstoneKey() {
1131 return DenseMapInfo<PHINode *>::getTombstoneKey();
1132 }
1133
1134 static unsigned getHashValue(PHINode *PN) {
1135 // Compute a hash value on the operands. Instcombine will likely have
1136 // sorted them, which helps expose duplicates, but we have to check all
1137 // the operands to be safe in case instcombine hasn't run.
1138 return static_cast<unsigned>(hash_combine(
1139 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1140 hash_combine_range(PN->block_begin(), PN->block_end())));
1141 }
1142
1143 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1144 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1145 RHS == getEmptyKey() || RHS == getTombstoneKey())
1146 return LHS == RHS;
1147 return LHS->isIdenticalTo(RHS);
1148 }
1149 };
1150
1151 // Set of unique PHINodes.
1152 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1153
1154 // Examine each PHI.
1155 bool Changed = false;
1156 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1157 auto Inserted = PHISet.insert(PN);
1158 if (!Inserted.second) {
1159 // A duplicate. Replace this PHI with its duplicate.
1160 PN->replaceAllUsesWith(*Inserted.first);
1161 PN->eraseFromParent();
1162 Changed = true;
1163
1164 // The RAUW can change PHIs that we already visited. Start over from the
1165 // beginning.
1166 PHISet.clear();
1167 I = BB->begin();
1168 }
1169 }
1170
1171 return Changed;
1172 }
1173
1174 /// enforceKnownAlignment - If the specified pointer points to an object that
1175 /// we control, modify the object's alignment to PrefAlign. This isn't
1176 /// often possible though. If alignment is important, a more reliable approach
1177 /// is to simply align all global variables and allocation instructions to
1178 /// their preferred alignment from the beginning.
enforceKnownAlignment(Value * V,Align Alignment,Align PrefAlign,const DataLayout & DL)1179 static Align enforceKnownAlignment(Value *V, Align Alignment, Align PrefAlign,
1180 const DataLayout &DL) {
1181 assert(PrefAlign > Alignment);
1182
1183 V = V->stripPointerCasts();
1184
1185 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1186 // TODO: ideally, computeKnownBits ought to have used
1187 // AllocaInst::getAlignment() in its computation already, making
1188 // the below max redundant. But, as it turns out,
1189 // stripPointerCasts recurses through infinite layers of bitcasts,
1190 // while computeKnownBits is not allowed to traverse more than 6
1191 // levels.
1192 Alignment = std::max(AI->getAlign(), Alignment);
1193 if (PrefAlign <= Alignment)
1194 return Alignment;
1195
1196 // If the preferred alignment is greater than the natural stack alignment
1197 // then don't round up. This avoids dynamic stack realignment.
1198 if (DL.exceedsNaturalStackAlignment(PrefAlign))
1199 return Alignment;
1200 AI->setAlignment(PrefAlign);
1201 return PrefAlign;
1202 }
1203
1204 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1205 // TODO: as above, this shouldn't be necessary.
1206 Alignment = max(GO->getAlign(), Alignment);
1207 if (PrefAlign <= Alignment)
1208 return Alignment;
1209
1210 // If there is a large requested alignment and we can, bump up the alignment
1211 // of the global. If the memory we set aside for the global may not be the
1212 // memory used by the final program then it is impossible for us to reliably
1213 // enforce the preferred alignment.
1214 if (!GO->canIncreaseAlignment())
1215 return Alignment;
1216
1217 GO->setAlignment(PrefAlign);
1218 return PrefAlign;
1219 }
1220
1221 return Alignment;
1222 }
1223
getOrEnforceKnownAlignment(Value * V,MaybeAlign PrefAlign,const DataLayout & DL,const Instruction * CxtI,AssumptionCache * AC,const DominatorTree * DT)1224 Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
1225 const DataLayout &DL,
1226 const Instruction *CxtI,
1227 AssumptionCache *AC,
1228 const DominatorTree *DT) {
1229 assert(V->getType()->isPointerTy() &&
1230 "getOrEnforceKnownAlignment expects a pointer!");
1231 unsigned BitWidth = DL.getPointerAddrSizeInBits(V->getType());
1232
1233 KnownBits Known(BitWidth);
1234 computeKnownBits(V, Known, DL, 0, AC, CxtI, DT);
1235 unsigned TrailZ = Known.countMinTrailingZeros();
1236
1237 // Avoid trouble with ridiculously large TrailZ values, such as
1238 // those computed from a null pointer.
1239 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1240 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1241
1242 Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1243
1244 if (PrefAlign && *PrefAlign > Alignment)
1245 Alignment = enforceKnownAlignment(V, Alignment, *PrefAlign, DL);
1246
1247 // We don't need to make any adjustment.
1248 return Alignment;
1249 }
1250
1251 ///===---------------------------------------------------------------------===//
1252 /// Dbg Intrinsic utilities
1253 ///
1254
1255 /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
PhiHasDebugValue(DILocalVariable * DIVar,DIExpression * DIExpr,PHINode * APN)1256 static bool PhiHasDebugValue(DILocalVariable *DIVar,
1257 DIExpression *DIExpr,
1258 PHINode *APN) {
1259 // Since we can't guarantee that the original dbg.declare instrinsic
1260 // is removed by LowerDbgDeclare(), we need to make sure that we are
1261 // not inserting the same dbg.value intrinsic over and over.
1262 SmallVector<DbgValueInst *, 1> DbgValues;
1263 findDbgValues(DbgValues, APN);
1264 for (auto *DVI : DbgValues) {
1265 assert(DVI->getValue() == APN);
1266 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1267 return true;
1268 }
1269 return false;
1270 }
1271
1272 /// Check if the alloc size of \p ValTy is large enough to cover the variable
1273 /// (or fragment of the variable) described by \p DII.
1274 ///
1275 /// This is primarily intended as a helper for the different
1276 /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1277 /// converted describes an alloca'd variable, so we need to use the
1278 /// alloc size of the value when doing the comparison. E.g. an i1 value will be
1279 /// identified as covering an n-bit fragment, if the store size of i1 is at
1280 /// least n bits.
valueCoversEntireFragment(Type * ValTy,DbgVariableIntrinsic * DII)1281 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1282 const DataLayout &DL = DII->getModule()->getDataLayout();
1283 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1284 if (auto FragmentSize = DII->getFragmentSizeInBits())
1285 return ValueSize >= *FragmentSize;
1286 // We can't always calculate the size of the DI variable (e.g. if it is a
1287 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1288 // intead.
1289 if (DII->isAddressOfVariable())
1290 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1291 if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1292 return ValueSize >= *FragmentSize;
1293 // Could not determine size of variable. Conservatively return false.
1294 return false;
1295 }
1296
1297 /// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1298 /// to a dbg.value. Because no machine insts can come from debug intrinsics,
1299 /// only the scope and inlinedAt is significant. Zero line numbers are used in
1300 /// case this DebugLoc leaks into any adjacent instructions.
getDebugValueLoc(DbgVariableIntrinsic * DII,Instruction * Src)1301 static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1302 // Original dbg.declare must have a location.
1303 DebugLoc DeclareLoc = DII->getDebugLoc();
1304 MDNode *Scope = DeclareLoc.getScope();
1305 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1306 // Produce an unknown location with the correct scope / inlinedAt fields.
1307 return DebugLoc::get(0, 0, Scope, InlinedAt);
1308 }
1309
1310 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1311 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,StoreInst * SI,DIBuilder & Builder)1312 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1313 StoreInst *SI, DIBuilder &Builder) {
1314 assert(DII->isAddressOfVariable());
1315 auto *DIVar = DII->getVariable();
1316 assert(DIVar && "Missing variable");
1317 auto *DIExpr = DII->getExpression();
1318 Value *DV = SI->getValueOperand();
1319
1320 DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1321
1322 if (!valueCoversEntireFragment(DV->getType(), DII)) {
1323 // FIXME: If storing to a part of the variable described by the dbg.declare,
1324 // then we want to insert a dbg.value for the corresponding fragment.
1325 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1326 << *DII << '\n');
1327 // For now, when there is a store to parts of the variable (but we do not
1328 // know which part) we insert an dbg.value instrinsic to indicate that we
1329 // know nothing about the variable's content.
1330 DV = UndefValue::get(DV->getType());
1331 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1332 return;
1333 }
1334
1335 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1336 }
1337
1338 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1339 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,LoadInst * LI,DIBuilder & Builder)1340 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1341 LoadInst *LI, DIBuilder &Builder) {
1342 auto *DIVar = DII->getVariable();
1343 auto *DIExpr = DII->getExpression();
1344 assert(DIVar && "Missing variable");
1345
1346 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1347 // FIXME: If only referring to a part of the variable described by the
1348 // dbg.declare, then we want to insert a dbg.value for the corresponding
1349 // fragment.
1350 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1351 << *DII << '\n');
1352 return;
1353 }
1354
1355 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1356
1357 // We are now tracking the loaded value instead of the address. In the
1358 // future if multi-location support is added to the IR, it might be
1359 // preferable to keep tracking both the loaded value and the original
1360 // address in case the alloca can not be elided.
1361 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1362 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
1363 DbgValue->insertAfter(LI);
1364 }
1365
1366 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1367 /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,PHINode * APN,DIBuilder & Builder)1368 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1369 PHINode *APN, DIBuilder &Builder) {
1370 auto *DIVar = DII->getVariable();
1371 auto *DIExpr = DII->getExpression();
1372 assert(DIVar && "Missing variable");
1373
1374 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1375 return;
1376
1377 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1378 // FIXME: If only referring to a part of the variable described by the
1379 // dbg.declare, then we want to insert a dbg.value for the corresponding
1380 // fragment.
1381 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1382 << *DII << '\n');
1383 return;
1384 }
1385
1386 BasicBlock *BB = APN->getParent();
1387 auto InsertionPt = BB->getFirstInsertionPt();
1388
1389 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1390
1391 // The block may be a catchswitch block, which does not have a valid
1392 // insertion point.
1393 // FIXME: Insert dbg.value markers in the successors when appropriate.
1394 if (InsertionPt != BB->end())
1395 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1396 }
1397
1398 /// Determine whether this alloca is either a VLA or an array.
isArray(AllocaInst * AI)1399 static bool isArray(AllocaInst *AI) {
1400 return AI->isArrayAllocation() ||
1401 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1402 }
1403
1404 /// Determine whether this alloca is a structure.
isStructure(AllocaInst * AI)1405 static bool isStructure(AllocaInst *AI) {
1406 return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1407 }
1408
1409 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1410 /// of llvm.dbg.value intrinsics.
LowerDbgDeclare(Function & F)1411 bool llvm::LowerDbgDeclare(Function &F) {
1412 bool Changed = false;
1413 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1414 SmallVector<DbgDeclareInst *, 4> Dbgs;
1415 for (auto &FI : F)
1416 for (Instruction &BI : FI)
1417 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1418 Dbgs.push_back(DDI);
1419
1420 if (Dbgs.empty())
1421 return Changed;
1422
1423 for (auto &I : Dbgs) {
1424 DbgDeclareInst *DDI = I;
1425 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1426 // If this is an alloca for a scalar variable, insert a dbg.value
1427 // at each load and store to the alloca and erase the dbg.declare.
1428 // The dbg.values allow tracking a variable even if it is not
1429 // stored on the stack, while the dbg.declare can only describe
1430 // the stack slot (and at a lexical-scope granularity). Later
1431 // passes will attempt to elide the stack slot.
1432 if (!AI || isArray(AI) || isStructure(AI))
1433 continue;
1434
1435 // A volatile load/store means that the alloca can't be elided anyway.
1436 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1437 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1438 return LI->isVolatile();
1439 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1440 return SI->isVolatile();
1441 return false;
1442 }))
1443 continue;
1444
1445 SmallVector<const Value *, 8> WorkList;
1446 WorkList.push_back(AI);
1447 while (!WorkList.empty()) {
1448 const Value *V = WorkList.pop_back_val();
1449 for (auto &AIUse : V->uses()) {
1450 User *U = AIUse.getUser();
1451 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1452 if (AIUse.getOperandNo() == 1)
1453 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1454 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1455 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1456 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1457 // This is a call by-value or some other instruction that takes a
1458 // pointer to the variable. Insert a *value* intrinsic that describes
1459 // the variable by dereferencing the alloca.
1460 if (!CI->isLifetimeStartOrEnd()) {
1461 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
1462 auto *DerefExpr =
1463 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1464 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1465 NewLoc, CI);
1466 }
1467 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1468 if (BI->getType()->isPointerTy())
1469 WorkList.push_back(BI);
1470 }
1471 }
1472 }
1473 DDI->eraseFromParent();
1474 Changed = true;
1475 }
1476
1477 if (Changed)
1478 for (BasicBlock &BB : F)
1479 RemoveRedundantDbgInstrs(&BB);
1480
1481 return Changed;
1482 }
1483
1484 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
insertDebugValuesForPHIs(BasicBlock * BB,SmallVectorImpl<PHINode * > & InsertedPHIs)1485 void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1486 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1487 assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1488 if (InsertedPHIs.size() == 0)
1489 return;
1490
1491 // Map existing PHI nodes to their dbg.values.
1492 ValueToValueMapTy DbgValueMap;
1493 for (auto &I : *BB) {
1494 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
1495 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1496 DbgValueMap.insert({Loc, DbgII});
1497 }
1498 }
1499 if (DbgValueMap.size() == 0)
1500 return;
1501
1502 // Then iterate through the new PHIs and look to see if they use one of the
1503 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1504 // propagate the info through the new PHI.
1505 LLVMContext &C = BB->getContext();
1506 for (auto PHI : InsertedPHIs) {
1507 BasicBlock *Parent = PHI->getParent();
1508 // Avoid inserting an intrinsic into an EH block.
1509 if (Parent->getFirstNonPHI()->isEHPad())
1510 continue;
1511 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
1512 for (auto VI : PHI->operand_values()) {
1513 auto V = DbgValueMap.find(VI);
1514 if (V != DbgValueMap.end()) {
1515 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1516 Instruction *NewDbgII = DbgII->clone();
1517 NewDbgII->setOperand(0, PhiMAV);
1518 auto InsertionPt = Parent->getFirstInsertionPt();
1519 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1520 NewDbgII->insertBefore(&*InsertionPt);
1521 }
1522 }
1523 }
1524 }
1525
1526 /// Finds all intrinsics declaring local variables as living in the memory that
1527 /// 'V' points to. This may include a mix of dbg.declare and
1528 /// dbg.addr intrinsics.
FindDbgAddrUses(Value * V)1529 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
1530 // This function is hot. Check whether the value has any metadata to avoid a
1531 // DenseMap lookup.
1532 if (!V->isUsedByMetadata())
1533 return {};
1534 auto *L = LocalAsMetadata::getIfExists(V);
1535 if (!L)
1536 return {};
1537 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1538 if (!MDV)
1539 return {};
1540
1541 TinyPtrVector<DbgVariableIntrinsic *> Declares;
1542 for (User *U : MDV->users()) {
1543 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
1544 if (DII->isAddressOfVariable())
1545 Declares.push_back(DII);
1546 }
1547
1548 return Declares;
1549 }
1550
FindDbgDeclareUses(Value * V)1551 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
1552 TinyPtrVector<DbgDeclareInst *> DDIs;
1553 for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
1554 if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
1555 DDIs.push_back(DDI);
1556 return DDIs;
1557 }
1558
findDbgValues(SmallVectorImpl<DbgValueInst * > & DbgValues,Value * V)1559 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
1560 // This function is hot. Check whether the value has any metadata to avoid a
1561 // DenseMap lookup.
1562 if (!V->isUsedByMetadata())
1563 return;
1564 if (auto *L = LocalAsMetadata::getIfExists(V))
1565 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1566 for (User *U : MDV->users())
1567 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1568 DbgValues.push_back(DVI);
1569 }
1570
findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic * > & DbgUsers,Value * V)1571 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
1572 Value *V) {
1573 // This function is hot. Check whether the value has any metadata to avoid a
1574 // DenseMap lookup.
1575 if (!V->isUsedByMetadata())
1576 return;
1577 if (auto *L = LocalAsMetadata::getIfExists(V))
1578 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1579 for (User *U : MDV->users())
1580 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
1581 DbgUsers.push_back(DII);
1582 }
1583
replaceDbgDeclare(Value * Address,Value * NewAddress,DIBuilder & Builder,uint8_t DIExprFlags,int Offset)1584 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1585 DIBuilder &Builder, uint8_t DIExprFlags,
1586 int Offset) {
1587 auto DbgAddrs = FindDbgAddrUses(Address);
1588 for (DbgVariableIntrinsic *DII : DbgAddrs) {
1589 DebugLoc Loc = DII->getDebugLoc();
1590 auto *DIVar = DII->getVariable();
1591 auto *DIExpr = DII->getExpression();
1592 assert(DIVar && "Missing variable");
1593 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1594 // Insert llvm.dbg.declare immediately before DII, and remove old
1595 // llvm.dbg.declare.
1596 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII);
1597 DII->eraseFromParent();
1598 }
1599 return !DbgAddrs.empty();
1600 }
1601
replaceOneDbgValueForAlloca(DbgValueInst * DVI,Value * NewAddress,DIBuilder & Builder,int Offset)1602 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1603 DIBuilder &Builder, int Offset) {
1604 DebugLoc Loc = DVI->getDebugLoc();
1605 auto *DIVar = DVI->getVariable();
1606 auto *DIExpr = DVI->getExpression();
1607 assert(DIVar && "Missing variable");
1608
1609 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1610 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1611 // it and give up.
1612 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1613 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1614 return;
1615
1616 // Insert the offset before the first deref.
1617 // We could just change the offset argument of dbg.value, but it's unsigned...
1618 if (Offset)
1619 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1620
1621 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1622 DVI->eraseFromParent();
1623 }
1624
replaceDbgValueForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,int Offset)1625 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1626 DIBuilder &Builder, int Offset) {
1627 if (auto *L = LocalAsMetadata::getIfExists(AI))
1628 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1629 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1630 Use &U = *UI++;
1631 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1632 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1633 }
1634 }
1635
1636 /// Wrap \p V in a ValueAsMetadata instance.
wrapValueInMetadata(LLVMContext & C,Value * V)1637 static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1638 return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1639 }
1640
1641 /// Where possible to salvage debug information for \p I do so
1642 /// and return True. If not possible mark undef and return False.
salvageDebugInfo(Instruction & I)1643 void llvm::salvageDebugInfo(Instruction &I) {
1644 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
1645 findDbgUsers(DbgUsers, &I);
1646 salvageDebugInfoForDbgValues(I, DbgUsers);
1647 }
1648
salvageDebugInfoForDbgValues(Instruction & I,ArrayRef<DbgVariableIntrinsic * > DbgUsers)1649 void llvm::salvageDebugInfoForDbgValues(
1650 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
1651 auto &Ctx = I.getContext();
1652 bool Salvaged = false;
1653 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
1654
1655 for (auto *DII : DbgUsers) {
1656 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1657 // are implicitly pointing out the value as a DWARF memory location
1658 // description.
1659 bool StackValue = isa<DbgValueInst>(DII);
1660
1661 DIExpression *DIExpr =
1662 salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1663
1664 // salvageDebugInfoImpl should fail on examining the first element of
1665 // DbgUsers, or none of them.
1666 if (!DIExpr)
1667 break;
1668
1669 DII->setOperand(0, wrapMD(I.getOperand(0)));
1670 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
1671 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
1672 Salvaged = true;
1673 }
1674
1675 if (Salvaged)
1676 return;
1677
1678 for (auto *DII : DbgUsers) {
1679 Value *Undef = UndefValue::get(I.getType());
1680 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
1681 ValueAsMetadata::get(Undef)));
1682 }
1683 }
1684
salvageDebugInfoImpl(Instruction & I,DIExpression * SrcDIExpr,bool WithStackValue)1685 DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1686 DIExpression *SrcDIExpr,
1687 bool WithStackValue) {
1688 auto &M = *I.getModule();
1689 auto &DL = M.getDataLayout();
1690
1691 // Apply a vector of opcodes to the source DIExpression.
1692 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1693 DIExpression *DIExpr = SrcDIExpr;
1694 if (!Ops.empty()) {
1695 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1696 }
1697 return DIExpr;
1698 };
1699
1700 // Apply the given offset to the source DIExpression.
1701 auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
1702 SmallVector<uint64_t, 8> Ops;
1703 DIExpression::appendOffset(Ops, Offset);
1704 return doSalvage(Ops);
1705 };
1706
1707 // initializer-list helper for applying operators to the source DIExpression.
1708 auto applyOps = [&](ArrayRef<uint64_t> Opcodes) -> DIExpression * {
1709 SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end());
1710 return doSalvage(Ops);
1711 };
1712
1713 if (auto *CI = dyn_cast<CastInst>(&I)) {
1714 // No-op casts are irrelevant for debug info.
1715 if (CI->isNoopCast(DL))
1716 return SrcDIExpr;
1717
1718 Type *Type = CI->getType();
1719 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
1720 if (Type->isVectorTy() ||
1721 !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I)))
1722 return nullptr;
1723
1724 Value *FromValue = CI->getOperand(0);
1725 unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1726 unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1727
1728 return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1729 isa<SExtInst>(&I)));
1730 }
1731
1732 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1733 unsigned BitWidth =
1734 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
1735 // Rewrite a constant GEP into a DIExpression.
1736 APInt Offset(BitWidth, 0);
1737 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1738 return applyOffset(Offset.getSExtValue());
1739 } else {
1740 return nullptr;
1741 }
1742 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1743 // Rewrite binary operations with constant integer operands.
1744 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1745 if (!ConstInt || ConstInt->getBitWidth() > 64)
1746 return nullptr;
1747
1748 uint64_t Val = ConstInt->getSExtValue();
1749 switch (BI->getOpcode()) {
1750 case Instruction::Add:
1751 return applyOffset(Val);
1752 case Instruction::Sub:
1753 return applyOffset(-int64_t(Val));
1754 case Instruction::Mul:
1755 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1756 case Instruction::SDiv:
1757 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1758 case Instruction::SRem:
1759 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1760 case Instruction::Or:
1761 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1762 case Instruction::And:
1763 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1764 case Instruction::Xor:
1765 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1766 case Instruction::Shl:
1767 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1768 case Instruction::LShr:
1769 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1770 case Instruction::AShr:
1771 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1772 default:
1773 // TODO: Salvage constants from each kind of binop we know about.
1774 return nullptr;
1775 }
1776 // *Not* to do: we should not attempt to salvage load instructions,
1777 // because the validity and lifetime of a dbg.value containing
1778 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1779 }
1780 return nullptr;
1781 }
1782
1783 /// A replacement for a dbg.value expression.
1784 using DbgValReplacement = Optional<DIExpression *>;
1785
1786 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1787 /// possibly moving/undefing users to prevent use-before-def. Returns true if
1788 /// changes are made.
rewriteDebugUsers(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT,function_ref<DbgValReplacement (DbgVariableIntrinsic & DII)> RewriteExpr)1789 static bool rewriteDebugUsers(
1790 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1791 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1792 // Find debug users of From.
1793 SmallVector<DbgVariableIntrinsic *, 1> Users;
1794 findDbgUsers(Users, &From);
1795 if (Users.empty())
1796 return false;
1797
1798 // Prevent use-before-def of To.
1799 bool Changed = false;
1800 SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1801 if (isa<Instruction>(&To)) {
1802 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1803
1804 for (auto *DII : Users) {
1805 // It's common to see a debug user between From and DomPoint. Move it
1806 // after DomPoint to preserve the variable update without any reordering.
1807 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1808 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
1809 DII->moveAfter(&DomPoint);
1810 Changed = true;
1811
1812 // Users which otherwise aren't dominated by the replacement value must
1813 // be salvaged or deleted.
1814 } else if (!DT.dominates(&DomPoint, DII)) {
1815 UndefOrSalvage.insert(DII);
1816 }
1817 }
1818 }
1819
1820 // Update debug users without use-before-def risk.
1821 for (auto *DII : Users) {
1822 if (UndefOrSalvage.count(DII))
1823 continue;
1824
1825 LLVMContext &Ctx = DII->getContext();
1826 DbgValReplacement DVR = RewriteExpr(*DII);
1827 if (!DVR)
1828 continue;
1829
1830 DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1831 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1832 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
1833 Changed = true;
1834 }
1835
1836 if (!UndefOrSalvage.empty()) {
1837 // Try to salvage the remaining debug users.
1838 salvageDebugInfo(From);
1839 Changed = true;
1840 }
1841
1842 return Changed;
1843 }
1844
1845 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1846 /// losslessly preserve the bits and semantics of the value. This predicate is
1847 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1848 ///
1849 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1850 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1851 /// and also does not allow lossless pointer <-> integer conversions.
isBitCastSemanticsPreserving(const DataLayout & DL,Type * FromTy,Type * ToTy)1852 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1853 Type *ToTy) {
1854 // Trivially compatible types.
1855 if (FromTy == ToTy)
1856 return true;
1857
1858 // Handle compatible pointer <-> integer conversions.
1859 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1860 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1861 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1862 !DL.isNonIntegralPointerType(ToTy);
1863 return SameSize && LosslessConversion;
1864 }
1865
1866 // TODO: This is not exhaustive.
1867 return false;
1868 }
1869
replaceAllDbgUsesWith(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT)1870 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1871 Instruction &DomPoint, DominatorTree &DT) {
1872 // Exit early if From has no debug users.
1873 if (!From.isUsedByMetadata())
1874 return false;
1875
1876 assert(&From != &To && "Can't replace something with itself");
1877
1878 Type *FromTy = From.getType();
1879 Type *ToTy = To.getType();
1880
1881 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1882 return DII.getExpression();
1883 };
1884
1885 // Handle no-op conversions.
1886 Module &M = *From.getModule();
1887 const DataLayout &DL = M.getDataLayout();
1888 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1889 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1890
1891 // Handle integer-to-integer widening and narrowing.
1892 // FIXME: Use DW_OP_convert when it's available everywhere.
1893 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1894 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1895 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1896 assert(FromBits != ToBits && "Unexpected no-op conversion");
1897
1898 // When the width of the result grows, assume that a debugger will only
1899 // access the low `FromBits` bits when inspecting the source variable.
1900 if (FromBits < ToBits)
1901 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1902
1903 // The width of the result has shrunk. Use sign/zero extension to describe
1904 // the source variable's high bits.
1905 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1906 DILocalVariable *Var = DII.getVariable();
1907
1908 // Without knowing signedness, sign/zero extension isn't possible.
1909 auto Signedness = Var->getSignedness();
1910 if (!Signedness)
1911 return None;
1912
1913 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
1914 return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
1915 Signed);
1916 };
1917 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1918 }
1919
1920 // TODO: Floating-point conversions, vectors.
1921 return false;
1922 }
1923
removeAllNonTerminatorAndEHPadInstructions(BasicBlock * BB)1924 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1925 unsigned NumDeadInst = 0;
1926 // Delete the instructions backwards, as it has a reduced likelihood of
1927 // having to update as many def-use and use-def chains.
1928 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1929 while (EndInst != &BB->front()) {
1930 // Delete the next to last instruction.
1931 Instruction *Inst = &*--EndInst->getIterator();
1932 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1933 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1934 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1935 EndInst = Inst;
1936 continue;
1937 }
1938 if (!isa<DbgInfoIntrinsic>(Inst))
1939 ++NumDeadInst;
1940 Inst->eraseFromParent();
1941 }
1942 return NumDeadInst;
1943 }
1944
changeToUnreachable(Instruction * I,bool UseLLVMTrap,bool PreserveLCSSA,DomTreeUpdater * DTU,MemorySSAUpdater * MSSAU)1945 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1946 bool PreserveLCSSA, DomTreeUpdater *DTU,
1947 MemorySSAUpdater *MSSAU) {
1948 BasicBlock *BB = I->getParent();
1949 std::vector <DominatorTree::UpdateType> Updates;
1950
1951 if (MSSAU)
1952 MSSAU->changeToUnreachable(I);
1953
1954 // Loop over all of the successors, removing BB's entry from any PHI
1955 // nodes.
1956 if (DTU)
1957 Updates.reserve(BB->getTerminator()->getNumSuccessors());
1958 for (BasicBlock *Successor : successors(BB)) {
1959 Successor->removePredecessor(BB, PreserveLCSSA);
1960 if (DTU)
1961 Updates.push_back({DominatorTree::Delete, BB, Successor});
1962 }
1963 // Insert a call to llvm.trap right before this. This turns the undefined
1964 // behavior into a hard fail instead of falling through into random code.
1965 if (UseLLVMTrap) {
1966 Function *TrapFn =
1967 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1968 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1969 CallTrap->setDebugLoc(I->getDebugLoc());
1970 }
1971 auto *UI = new UnreachableInst(I->getContext(), I);
1972 UI->setDebugLoc(I->getDebugLoc());
1973
1974 // All instructions after this are dead.
1975 unsigned NumInstrsRemoved = 0;
1976 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1977 while (BBI != BBE) {
1978 if (!BBI->use_empty())
1979 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1980 BB->getInstList().erase(BBI++);
1981 ++NumInstrsRemoved;
1982 }
1983 if (DTU)
1984 DTU->applyUpdatesPermissive(Updates);
1985 return NumInstrsRemoved;
1986 }
1987
createCallMatchingInvoke(InvokeInst * II)1988 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
1989 SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end());
1990 SmallVector<OperandBundleDef, 1> OpBundles;
1991 II->getOperandBundlesAsDefs(OpBundles);
1992 CallInst *NewCall = CallInst::Create(II->getFunctionType(),
1993 II->getCalledOperand(), Args, OpBundles);
1994 NewCall->setCallingConv(II->getCallingConv());
1995 NewCall->setAttributes(II->getAttributes());
1996 NewCall->setDebugLoc(II->getDebugLoc());
1997 NewCall->copyMetadata(*II);
1998
1999 // If the invoke had profile metadata, try converting them for CallInst.
2000 uint64_t TotalWeight;
2001 if (NewCall->extractProfTotalWeight(TotalWeight)) {
2002 // Set the total weight if it fits into i32, otherwise reset.
2003 MDBuilder MDB(NewCall->getContext());
2004 auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2005 ? nullptr
2006 : MDB.createBranchWeights({uint32_t(TotalWeight)});
2007 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2008 }
2009
2010 return NewCall;
2011 }
2012
2013 /// changeToCall - Convert the specified invoke into a normal call.
changeToCall(InvokeInst * II,DomTreeUpdater * DTU)2014 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2015 CallInst *NewCall = createCallMatchingInvoke(II);
2016 NewCall->takeName(II);
2017 NewCall->insertBefore(II);
2018 II->replaceAllUsesWith(NewCall);
2019
2020 // Follow the call by a branch to the normal destination.
2021 BasicBlock *NormalDestBB = II->getNormalDest();
2022 BranchInst::Create(NormalDestBB, II);
2023
2024 // Update PHI nodes in the unwind destination
2025 BasicBlock *BB = II->getParent();
2026 BasicBlock *UnwindDestBB = II->getUnwindDest();
2027 UnwindDestBB->removePredecessor(BB);
2028 II->eraseFromParent();
2029 if (DTU)
2030 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
2031 }
2032
changeToInvokeAndSplitBasicBlock(CallInst * CI,BasicBlock * UnwindEdge)2033 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2034 BasicBlock *UnwindEdge) {
2035 BasicBlock *BB = CI->getParent();
2036
2037 // Convert this function call into an invoke instruction. First, split the
2038 // basic block.
2039 BasicBlock *Split =
2040 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
2041
2042 // Delete the unconditional branch inserted by splitBasicBlock
2043 BB->getInstList().pop_back();
2044
2045 // Create the new invoke instruction.
2046 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
2047 SmallVector<OperandBundleDef, 1> OpBundles;
2048
2049 CI->getOperandBundlesAsDefs(OpBundles);
2050
2051 // Note: we're round tripping operand bundles through memory here, and that
2052 // can potentially be avoided with a cleverer API design that we do not have
2053 // as of this time.
2054
2055 InvokeInst *II =
2056 InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2057 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2058 II->setDebugLoc(CI->getDebugLoc());
2059 II->setCallingConv(CI->getCallingConv());
2060 II->setAttributes(CI->getAttributes());
2061
2062 // Make sure that anything using the call now uses the invoke! This also
2063 // updates the CallGraph if present, because it uses a WeakTrackingVH.
2064 CI->replaceAllUsesWith(II);
2065
2066 // Delete the original call
2067 Split->getInstList().pop_front();
2068 return Split;
2069 }
2070
markAliveBlocks(Function & F,SmallPtrSetImpl<BasicBlock * > & Reachable,DomTreeUpdater * DTU=nullptr)2071 static bool markAliveBlocks(Function &F,
2072 SmallPtrSetImpl<BasicBlock *> &Reachable,
2073 DomTreeUpdater *DTU = nullptr) {
2074 SmallVector<BasicBlock*, 128> Worklist;
2075 BasicBlock *BB = &F.front();
2076 Worklist.push_back(BB);
2077 Reachable.insert(BB);
2078 bool Changed = false;
2079 do {
2080 BB = Worklist.pop_back_val();
2081
2082 // Do a quick scan of the basic block, turning any obviously unreachable
2083 // instructions into LLVM unreachable insts. The instruction combining pass
2084 // canonicalizes unreachable insts into stores to null or undef.
2085 for (Instruction &I : *BB) {
2086 if (auto *CI = dyn_cast<CallInst>(&I)) {
2087 Value *Callee = CI->getCalledOperand();
2088 // Handle intrinsic calls.
2089 if (Function *F = dyn_cast<Function>(Callee)) {
2090 auto IntrinsicID = F->getIntrinsicID();
2091 // Assumptions that are known to be false are equivalent to
2092 // unreachable. Also, if the condition is undefined, then we make the
2093 // choice most beneficial to the optimizer, and choose that to also be
2094 // unreachable.
2095 if (IntrinsicID == Intrinsic::assume) {
2096 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2097 // Don't insert a call to llvm.trap right before the unreachable.
2098 changeToUnreachable(CI, false, false, DTU);
2099 Changed = true;
2100 break;
2101 }
2102 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2103 // A call to the guard intrinsic bails out of the current
2104 // compilation unit if the predicate passed to it is false. If the
2105 // predicate is a constant false, then we know the guard will bail
2106 // out of the current compile unconditionally, so all code following
2107 // it is dead.
2108 //
2109 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2110 // guards to treat `undef` as `false` since a guard on `undef` can
2111 // still be useful for widening.
2112 if (match(CI->getArgOperand(0), m_Zero()))
2113 if (!isa<UnreachableInst>(CI->getNextNode())) {
2114 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2115 false, DTU);
2116 Changed = true;
2117 break;
2118 }
2119 }
2120 } else if ((isa<ConstantPointerNull>(Callee) &&
2121 !NullPointerIsDefined(CI->getFunction())) ||
2122 isa<UndefValue>(Callee)) {
2123 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
2124 Changed = true;
2125 break;
2126 }
2127 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2128 // If we found a call to a no-return function, insert an unreachable
2129 // instruction after it. Make sure there isn't *already* one there
2130 // though.
2131 if (!isa<UnreachableInst>(CI->getNextNode())) {
2132 // Don't insert a call to llvm.trap right before the unreachable.
2133 changeToUnreachable(CI->getNextNode(), false, false, DTU);
2134 Changed = true;
2135 }
2136 break;
2137 }
2138 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2139 // Store to undef and store to null are undefined and used to signal
2140 // that they should be changed to unreachable by passes that can't
2141 // modify the CFG.
2142
2143 // Don't touch volatile stores.
2144 if (SI->isVolatile()) continue;
2145
2146 Value *Ptr = SI->getOperand(1);
2147
2148 if (isa<UndefValue>(Ptr) ||
2149 (isa<ConstantPointerNull>(Ptr) &&
2150 !NullPointerIsDefined(SI->getFunction(),
2151 SI->getPointerAddressSpace()))) {
2152 changeToUnreachable(SI, true, false, DTU);
2153 Changed = true;
2154 break;
2155 }
2156 }
2157 }
2158
2159 Instruction *Terminator = BB->getTerminator();
2160 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2161 // Turn invokes that call 'nounwind' functions into ordinary calls.
2162 Value *Callee = II->getCalledOperand();
2163 if ((isa<ConstantPointerNull>(Callee) &&
2164 !NullPointerIsDefined(BB->getParent())) ||
2165 isa<UndefValue>(Callee)) {
2166 changeToUnreachable(II, true, false, DTU);
2167 Changed = true;
2168 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2169 if (II->use_empty() && II->onlyReadsMemory()) {
2170 // jump to the normal destination branch.
2171 BasicBlock *NormalDestBB = II->getNormalDest();
2172 BasicBlock *UnwindDestBB = II->getUnwindDest();
2173 BranchInst::Create(NormalDestBB, II);
2174 UnwindDestBB->removePredecessor(II->getParent());
2175 II->eraseFromParent();
2176 if (DTU)
2177 DTU->applyUpdatesPermissive(
2178 {{DominatorTree::Delete, BB, UnwindDestBB}});
2179 } else
2180 changeToCall(II, DTU);
2181 Changed = true;
2182 }
2183 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2184 // Remove catchpads which cannot be reached.
2185 struct CatchPadDenseMapInfo {
2186 static CatchPadInst *getEmptyKey() {
2187 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2188 }
2189
2190 static CatchPadInst *getTombstoneKey() {
2191 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2192 }
2193
2194 static unsigned getHashValue(CatchPadInst *CatchPad) {
2195 return static_cast<unsigned>(hash_combine_range(
2196 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2197 }
2198
2199 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2200 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2201 RHS == getEmptyKey() || RHS == getTombstoneKey())
2202 return LHS == RHS;
2203 return LHS->isIdenticalTo(RHS);
2204 }
2205 };
2206
2207 // Set of unique CatchPads.
2208 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2209 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2210 HandlerSet;
2211 detail::DenseSetEmpty Empty;
2212 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2213 E = CatchSwitch->handler_end();
2214 I != E; ++I) {
2215 BasicBlock *HandlerBB = *I;
2216 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2217 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2218 CatchSwitch->removeHandler(I);
2219 --I;
2220 --E;
2221 Changed = true;
2222 }
2223 }
2224 }
2225
2226 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2227 for (BasicBlock *Successor : successors(BB))
2228 if (Reachable.insert(Successor).second)
2229 Worklist.push_back(Successor);
2230 } while (!Worklist.empty());
2231 return Changed;
2232 }
2233
removeUnwindEdge(BasicBlock * BB,DomTreeUpdater * DTU)2234 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2235 Instruction *TI = BB->getTerminator();
2236
2237 if (auto *II = dyn_cast<InvokeInst>(TI)) {
2238 changeToCall(II, DTU);
2239 return;
2240 }
2241
2242 Instruction *NewTI;
2243 BasicBlock *UnwindDest;
2244
2245 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2246 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2247 UnwindDest = CRI->getUnwindDest();
2248 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2249 auto *NewCatchSwitch = CatchSwitchInst::Create(
2250 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2251 CatchSwitch->getName(), CatchSwitch);
2252 for (BasicBlock *PadBB : CatchSwitch->handlers())
2253 NewCatchSwitch->addHandler(PadBB);
2254
2255 NewTI = NewCatchSwitch;
2256 UnwindDest = CatchSwitch->getUnwindDest();
2257 } else {
2258 llvm_unreachable("Could not find unwind successor");
2259 }
2260
2261 NewTI->takeName(TI);
2262 NewTI->setDebugLoc(TI->getDebugLoc());
2263 UnwindDest->removePredecessor(BB);
2264 TI->replaceAllUsesWith(NewTI);
2265 TI->eraseFromParent();
2266 if (DTU)
2267 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
2268 }
2269
2270 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2271 /// if they are in a dead cycle. Return true if a change was made, false
2272 /// otherwise.
removeUnreachableBlocks(Function & F,DomTreeUpdater * DTU,MemorySSAUpdater * MSSAU)2273 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2274 MemorySSAUpdater *MSSAU) {
2275 SmallPtrSet<BasicBlock *, 16> Reachable;
2276 bool Changed = markAliveBlocks(F, Reachable, DTU);
2277
2278 // If there are unreachable blocks in the CFG...
2279 if (Reachable.size() == F.size())
2280 return Changed;
2281
2282 assert(Reachable.size() < F.size());
2283 NumRemoved += F.size() - Reachable.size();
2284
2285 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
2286 for (BasicBlock &BB : F) {
2287 // Skip reachable basic blocks
2288 if (Reachable.count(&BB))
2289 continue;
2290 DeadBlockSet.insert(&BB);
2291 }
2292
2293 if (MSSAU)
2294 MSSAU->removeBlocks(DeadBlockSet);
2295
2296 // Loop over all of the basic blocks that are not reachable, dropping all of
2297 // their internal references. Update DTU if available.
2298 std::vector<DominatorTree::UpdateType> Updates;
2299 for (auto *BB : DeadBlockSet) {
2300 for (BasicBlock *Successor : successors(BB)) {
2301 if (!DeadBlockSet.count(Successor))
2302 Successor->removePredecessor(BB);
2303 if (DTU)
2304 Updates.push_back({DominatorTree::Delete, BB, Successor});
2305 }
2306 BB->dropAllReferences();
2307 if (DTU) {
2308 Instruction *TI = BB->getTerminator();
2309 assert(TI && "Basic block should have a terminator");
2310 // Terminators like invoke can have users. We have to replace their users,
2311 // before removing them.
2312 if (!TI->use_empty())
2313 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
2314 TI->eraseFromParent();
2315 new UnreachableInst(BB->getContext(), BB);
2316 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2317 "applying corresponding DTU updates.");
2318 }
2319 }
2320
2321 if (DTU) {
2322 DTU->applyUpdatesPermissive(Updates);
2323 bool Deleted = false;
2324 for (auto *BB : DeadBlockSet) {
2325 if (DTU->isBBPendingDeletion(BB))
2326 --NumRemoved;
2327 else
2328 Deleted = true;
2329 DTU->deleteBB(BB);
2330 }
2331 if (!Deleted)
2332 return false;
2333 } else {
2334 for (auto *BB : DeadBlockSet)
2335 BB->eraseFromParent();
2336 }
2337
2338 return true;
2339 }
2340
combineMetadata(Instruction * K,const Instruction * J,ArrayRef<unsigned> KnownIDs,bool DoesKMove)2341 void llvm::combineMetadata(Instruction *K, const Instruction *J,
2342 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2343 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2344 K->dropUnknownNonDebugMetadata(KnownIDs);
2345 K->getAllMetadataOtherThanDebugLoc(Metadata);
2346 for (const auto &MD : Metadata) {
2347 unsigned Kind = MD.first;
2348 MDNode *JMD = J->getMetadata(Kind);
2349 MDNode *KMD = MD.second;
2350
2351 switch (Kind) {
2352 default:
2353 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2354 break;
2355 case LLVMContext::MD_dbg:
2356 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2357 case LLVMContext::MD_tbaa:
2358 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2359 break;
2360 case LLVMContext::MD_alias_scope:
2361 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2362 break;
2363 case LLVMContext::MD_noalias:
2364 case LLVMContext::MD_mem_parallel_loop_access:
2365 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2366 break;
2367 case LLVMContext::MD_access_group:
2368 K->setMetadata(LLVMContext::MD_access_group,
2369 intersectAccessGroups(K, J));
2370 break;
2371 case LLVMContext::MD_range:
2372
2373 // If K does move, use most generic range. Otherwise keep the range of
2374 // K.
2375 if (DoesKMove)
2376 // FIXME: If K does move, we should drop the range info and nonnull.
2377 // Currently this function is used with DoesKMove in passes
2378 // doing hoisting/sinking and the current behavior of using the
2379 // most generic range is correct in those cases.
2380 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2381 break;
2382 case LLVMContext::MD_fpmath:
2383 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2384 break;
2385 case LLVMContext::MD_invariant_load:
2386 // Only set the !invariant.load if it is present in both instructions.
2387 K->setMetadata(Kind, JMD);
2388 break;
2389 case LLVMContext::MD_nonnull:
2390 // If K does move, keep nonull if it is present in both instructions.
2391 if (DoesKMove)
2392 K->setMetadata(Kind, JMD);
2393 break;
2394 case LLVMContext::MD_invariant_group:
2395 // Preserve !invariant.group in K.
2396 break;
2397 case LLVMContext::MD_align:
2398 K->setMetadata(Kind,
2399 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2400 break;
2401 case LLVMContext::MD_dereferenceable:
2402 case LLVMContext::MD_dereferenceable_or_null:
2403 K->setMetadata(Kind,
2404 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2405 break;
2406 case LLVMContext::MD_preserve_access_index:
2407 // Preserve !preserve.access.index in K.
2408 break;
2409 }
2410 }
2411 // Set !invariant.group from J if J has it. If both instructions have it
2412 // then we will just pick it from J - even when they are different.
2413 // Also make sure that K is load or store - f.e. combining bitcast with load
2414 // could produce bitcast with invariant.group metadata, which is invalid.
2415 // FIXME: we should try to preserve both invariant.group md if they are
2416 // different, but right now instruction can only have one invariant.group.
2417 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2418 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2419 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2420 }
2421
combineMetadataForCSE(Instruction * K,const Instruction * J,bool KDominatesJ)2422 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2423 bool KDominatesJ) {
2424 unsigned KnownIDs[] = {
2425 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2426 LLVMContext::MD_noalias, LLVMContext::MD_range,
2427 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2428 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2429 LLVMContext::MD_dereferenceable,
2430 LLVMContext::MD_dereferenceable_or_null,
2431 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2432 combineMetadata(K, J, KnownIDs, KDominatesJ);
2433 }
2434
copyMetadataForLoad(LoadInst & Dest,const LoadInst & Source)2435 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2436 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2437 Source.getAllMetadata(MD);
2438 MDBuilder MDB(Dest.getContext());
2439 Type *NewType = Dest.getType();
2440 const DataLayout &DL = Source.getModule()->getDataLayout();
2441 for (const auto &MDPair : MD) {
2442 unsigned ID = MDPair.first;
2443 MDNode *N = MDPair.second;
2444 // Note, essentially every kind of metadata should be preserved here! This
2445 // routine is supposed to clone a load instruction changing *only its type*.
2446 // The only metadata it makes sense to drop is metadata which is invalidated
2447 // when the pointer type changes. This should essentially never be the case
2448 // in LLVM, but we explicitly switch over only known metadata to be
2449 // conservatively correct. If you are adding metadata to LLVM which pertains
2450 // to loads, you almost certainly want to add it here.
2451 switch (ID) {
2452 case LLVMContext::MD_dbg:
2453 case LLVMContext::MD_tbaa:
2454 case LLVMContext::MD_prof:
2455 case LLVMContext::MD_fpmath:
2456 case LLVMContext::MD_tbaa_struct:
2457 case LLVMContext::MD_invariant_load:
2458 case LLVMContext::MD_alias_scope:
2459 case LLVMContext::MD_noalias:
2460 case LLVMContext::MD_nontemporal:
2461 case LLVMContext::MD_mem_parallel_loop_access:
2462 case LLVMContext::MD_access_group:
2463 // All of these directly apply.
2464 Dest.setMetadata(ID, N);
2465 break;
2466
2467 case LLVMContext::MD_nonnull:
2468 copyNonnullMetadata(Source, N, Dest);
2469 break;
2470
2471 case LLVMContext::MD_align:
2472 case LLVMContext::MD_dereferenceable:
2473 case LLVMContext::MD_dereferenceable_or_null:
2474 // These only directly apply if the new type is also a pointer.
2475 if (NewType->isPointerTy())
2476 Dest.setMetadata(ID, N);
2477 break;
2478
2479 case LLVMContext::MD_range:
2480 copyRangeMetadata(DL, Source, N, Dest);
2481 break;
2482 }
2483 }
2484 }
2485
patchReplacementInstruction(Instruction * I,Value * Repl)2486 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2487 auto *ReplInst = dyn_cast<Instruction>(Repl);
2488 if (!ReplInst)
2489 return;
2490
2491 // Patch the replacement so that it is not more restrictive than the value
2492 // being replaced.
2493 // Note that if 'I' is a load being replaced by some operation,
2494 // for example, by an arithmetic operation, then andIRFlags()
2495 // would just erase all math flags from the original arithmetic
2496 // operation, which is clearly not wanted and not needed.
2497 if (!isa<LoadInst>(I))
2498 ReplInst->andIRFlags(I);
2499
2500 // FIXME: If both the original and replacement value are part of the
2501 // same control-flow region (meaning that the execution of one
2502 // guarantees the execution of the other), then we can combine the
2503 // noalias scopes here and do better than the general conservative
2504 // answer used in combineMetadata().
2505
2506 // In general, GVN unifies expressions over different control-flow
2507 // regions, and so we need a conservative combination of the noalias
2508 // scopes.
2509 static const unsigned KnownIDs[] = {
2510 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2511 LLVMContext::MD_noalias, LLVMContext::MD_range,
2512 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2513 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2514 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2515 combineMetadata(ReplInst, I, KnownIDs, false);
2516 }
2517
2518 template <typename RootType, typename DominatesFn>
replaceDominatedUsesWith(Value * From,Value * To,const RootType & Root,const DominatesFn & Dominates)2519 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2520 const RootType &Root,
2521 const DominatesFn &Dominates) {
2522 assert(From->getType() == To->getType());
2523
2524 unsigned Count = 0;
2525 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2526 UI != UE;) {
2527 Use &U = *UI++;
2528 if (!Dominates(Root, U))
2529 continue;
2530 U.set(To);
2531 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2532 << "' as " << *To << " in " << *U << "\n");
2533 ++Count;
2534 }
2535 return Count;
2536 }
2537
replaceNonLocalUsesWith(Instruction * From,Value * To)2538 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2539 assert(From->getType() == To->getType());
2540 auto *BB = From->getParent();
2541 unsigned Count = 0;
2542
2543 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2544 UI != UE;) {
2545 Use &U = *UI++;
2546 auto *I = cast<Instruction>(U.getUser());
2547 if (I->getParent() == BB)
2548 continue;
2549 U.set(To);
2550 ++Count;
2551 }
2552 return Count;
2553 }
2554
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlockEdge & Root)2555 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2556 DominatorTree &DT,
2557 const BasicBlockEdge &Root) {
2558 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2559 return DT.dominates(Root, U);
2560 };
2561 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2562 }
2563
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlock * BB)2564 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2565 DominatorTree &DT,
2566 const BasicBlock *BB) {
2567 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2568 auto *I = cast<Instruction>(U.getUser())->getParent();
2569 return DT.properlyDominates(BB, I);
2570 };
2571 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2572 }
2573
callsGCLeafFunction(const CallBase * Call,const TargetLibraryInfo & TLI)2574 bool llvm::callsGCLeafFunction(const CallBase *Call,
2575 const TargetLibraryInfo &TLI) {
2576 // Check if the function is specifically marked as a gc leaf function.
2577 if (Call->hasFnAttr("gc-leaf-function"))
2578 return true;
2579 if (const Function *F = Call->getCalledFunction()) {
2580 if (F->hasFnAttribute("gc-leaf-function"))
2581 return true;
2582
2583 if (auto IID = F->getIntrinsicID())
2584 // Most LLVM intrinsics do not take safepoints.
2585 return IID != Intrinsic::experimental_gc_statepoint &&
2586 IID != Intrinsic::experimental_deoptimize;
2587 }
2588
2589 // Lib calls can be materialized by some passes, and won't be
2590 // marked as 'gc-leaf-function.' All available Libcalls are
2591 // GC-leaf.
2592 LibFunc LF;
2593 if (TLI.getLibFunc(*Call, LF)) {
2594 return TLI.has(LF);
2595 }
2596
2597 return false;
2598 }
2599
copyNonnullMetadata(const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)2600 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2601 LoadInst &NewLI) {
2602 auto *NewTy = NewLI.getType();
2603
2604 // This only directly applies if the new type is also a pointer.
2605 if (NewTy->isPointerTy()) {
2606 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2607 return;
2608 }
2609
2610 // The only other translation we can do is to integral loads with !range
2611 // metadata.
2612 if (!NewTy->isIntegerTy())
2613 return;
2614
2615 MDBuilder MDB(NewLI.getContext());
2616 const Value *Ptr = OldLI.getPointerOperand();
2617 auto *ITy = cast<IntegerType>(NewTy);
2618 auto *NullInt = ConstantExpr::getPtrToInt(
2619 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2620 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2621 NewLI.setMetadata(LLVMContext::MD_range,
2622 MDB.createRange(NonNullInt, NullInt));
2623 }
2624
copyRangeMetadata(const DataLayout & DL,const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)2625 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2626 MDNode *N, LoadInst &NewLI) {
2627 auto *NewTy = NewLI.getType();
2628
2629 // Give up unless it is converted to a pointer where there is a single very
2630 // valuable mapping we can do reliably.
2631 // FIXME: It would be nice to propagate this in more ways, but the type
2632 // conversions make it hard.
2633 if (!NewTy->isPointerTy())
2634 return;
2635
2636 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2637 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2638 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2639 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2640 }
2641 }
2642
dropDebugUsers(Instruction & I)2643 void llvm::dropDebugUsers(Instruction &I) {
2644 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2645 findDbgUsers(DbgUsers, &I);
2646 for (auto *DII : DbgUsers)
2647 DII->eraseFromParent();
2648 }
2649
hoistAllInstructionsInto(BasicBlock * DomBlock,Instruction * InsertPt,BasicBlock * BB)2650 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2651 BasicBlock *BB) {
2652 // Since we are moving the instructions out of its basic block, we do not
2653 // retain their original debug locations (DILocations) and debug intrinsic
2654 // instructions.
2655 //
2656 // Doing so would degrade the debugging experience and adversely affect the
2657 // accuracy of profiling information.
2658 //
2659 // Currently, when hoisting the instructions, we take the following actions:
2660 // - Remove their debug intrinsic instructions.
2661 // - Set their debug locations to the values from the insertion point.
2662 //
2663 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2664 // need to be deleted, is because there will not be any instructions with a
2665 // DILocation in either branch left after performing the transformation. We
2666 // can only insert a dbg.value after the two branches are joined again.
2667 //
2668 // See PR38762, PR39243 for more details.
2669 //
2670 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2671 // encode predicated DIExpressions that yield different results on different
2672 // code paths.
2673 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2674 Instruction *I = &*II;
2675 I->dropUnknownNonDebugMetadata();
2676 if (I->isUsedByMetadata())
2677 dropDebugUsers(*I);
2678 if (isa<DbgInfoIntrinsic>(I)) {
2679 // Remove DbgInfo Intrinsics.
2680 II = I->eraseFromParent();
2681 continue;
2682 }
2683 I->setDebugLoc(InsertPt->getDebugLoc());
2684 ++II;
2685 }
2686 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2687 BB->begin(),
2688 BB->getTerminator()->getIterator());
2689 }
2690
2691 namespace {
2692
2693 /// A potential constituent of a bitreverse or bswap expression. See
2694 /// collectBitParts for a fuller explanation.
2695 struct BitPart {
BitPart__anon6243f5c70b11::BitPart2696 BitPart(Value *P, unsigned BW) : Provider(P) {
2697 Provenance.resize(BW);
2698 }
2699
2700 /// The Value that this is a bitreverse/bswap of.
2701 Value *Provider;
2702
2703 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2704 /// in Provider becomes bit B in the result of this expression.
2705 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2706
2707 enum { Unset = -1 };
2708 };
2709
2710 } // end anonymous namespace
2711
2712 /// Analyze the specified subexpression and see if it is capable of providing
2713 /// pieces of a bswap or bitreverse. The subexpression provides a potential
2714 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2715 /// the output of the expression came from a corresponding bit in some other
2716 /// value. This function is recursive, and the end result is a mapping of
2717 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
2718 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2719 ///
2720 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2721 /// that the expression deposits the low byte of %X into the high byte of the
2722 /// result and that all other bits are zero. This expression is accepted and a
2723 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2724 /// [0-7].
2725 ///
2726 /// To avoid revisiting values, the BitPart results are memoized into the
2727 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
2728 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2729 /// store BitParts objects, not pointers. As we need the concept of a nullptr
2730 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
2731 /// type instead to provide the same functionality.
2732 ///
2733 /// Because we pass around references into \c BPS, we must use a container that
2734 /// does not invalidate internal references (std::map instead of DenseMap).
2735 static const Optional<BitPart> &
collectBitParts(Value * V,bool MatchBSwaps,bool MatchBitReversals,std::map<Value *,Optional<BitPart>> & BPS,int Depth)2736 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2737 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
2738 auto I = BPS.find(V);
2739 if (I != BPS.end())
2740 return I->second;
2741
2742 auto &Result = BPS[V] = None;
2743 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2744
2745 // Prevent stack overflow by limiting the recursion depth
2746 if (Depth == BitPartRecursionMaxDepth) {
2747 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2748 return Result;
2749 }
2750
2751 if (Instruction *I = dyn_cast<Instruction>(V)) {
2752 // If this is an or instruction, it may be an inner node of the bswap.
2753 if (I->getOpcode() == Instruction::Or) {
2754 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
2755 MatchBitReversals, BPS, Depth + 1);
2756 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
2757 MatchBitReversals, BPS, Depth + 1);
2758 if (!A || !B)
2759 return Result;
2760
2761 // Try and merge the two together.
2762 if (!A->Provider || A->Provider != B->Provider)
2763 return Result;
2764
2765 Result = BitPart(A->Provider, BitWidth);
2766 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2767 if (A->Provenance[i] != BitPart::Unset &&
2768 B->Provenance[i] != BitPart::Unset &&
2769 A->Provenance[i] != B->Provenance[i])
2770 return Result = None;
2771
2772 if (A->Provenance[i] == BitPart::Unset)
2773 Result->Provenance[i] = B->Provenance[i];
2774 else
2775 Result->Provenance[i] = A->Provenance[i];
2776 }
2777
2778 return Result;
2779 }
2780
2781 // If this is a logical shift by a constant, recurse then shift the result.
2782 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2783 unsigned BitShift =
2784 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2785 // Ensure the shift amount is defined.
2786 if (BitShift > BitWidth)
2787 return Result;
2788
2789 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2790 MatchBitReversals, BPS, Depth + 1);
2791 if (!Res)
2792 return Result;
2793 Result = Res;
2794
2795 // Perform the "shift" on BitProvenance.
2796 auto &P = Result->Provenance;
2797 if (I->getOpcode() == Instruction::Shl) {
2798 P.erase(std::prev(P.end(), BitShift), P.end());
2799 P.insert(P.begin(), BitShift, BitPart::Unset);
2800 } else {
2801 P.erase(P.begin(), std::next(P.begin(), BitShift));
2802 P.insert(P.end(), BitShift, BitPart::Unset);
2803 }
2804
2805 return Result;
2806 }
2807
2808 // If this is a logical 'and' with a mask that clears bits, recurse then
2809 // unset the appropriate bits.
2810 if (I->getOpcode() == Instruction::And &&
2811 isa<ConstantInt>(I->getOperand(1))) {
2812 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2813 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2814
2815 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2816 // early exit.
2817 unsigned NumMaskedBits = AndMask.countPopulation();
2818 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2819 return Result;
2820
2821 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2822 MatchBitReversals, BPS, Depth + 1);
2823 if (!Res)
2824 return Result;
2825 Result = Res;
2826
2827 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2828 // If the AndMask is zero for this bit, clear the bit.
2829 if ((AndMask & Bit) == 0)
2830 Result->Provenance[i] = BitPart::Unset;
2831 return Result;
2832 }
2833
2834 // If this is a zext instruction zero extend the result.
2835 if (I->getOpcode() == Instruction::ZExt) {
2836 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2837 MatchBitReversals, BPS, Depth + 1);
2838 if (!Res)
2839 return Result;
2840
2841 Result = BitPart(Res->Provider, BitWidth);
2842 auto NarrowBitWidth =
2843 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2844 for (unsigned i = 0; i < NarrowBitWidth; ++i)
2845 Result->Provenance[i] = Res->Provenance[i];
2846 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2847 Result->Provenance[i] = BitPart::Unset;
2848 return Result;
2849 }
2850 }
2851
2852 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2853 // the input value to the bswap/bitreverse.
2854 Result = BitPart(V, BitWidth);
2855 for (unsigned i = 0; i < BitWidth; ++i)
2856 Result->Provenance[i] = i;
2857 return Result;
2858 }
2859
bitTransformIsCorrectForBSwap(unsigned From,unsigned To,unsigned BitWidth)2860 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2861 unsigned BitWidth) {
2862 if (From % 8 != To % 8)
2863 return false;
2864 // Convert from bit indices to byte indices and check for a byte reversal.
2865 From >>= 3;
2866 To >>= 3;
2867 BitWidth >>= 3;
2868 return From == BitWidth - To - 1;
2869 }
2870
bitTransformIsCorrectForBitReverse(unsigned From,unsigned To,unsigned BitWidth)2871 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2872 unsigned BitWidth) {
2873 return From == BitWidth - To - 1;
2874 }
2875
recognizeBSwapOrBitReverseIdiom(Instruction * I,bool MatchBSwaps,bool MatchBitReversals,SmallVectorImpl<Instruction * > & InsertedInsts)2876 bool llvm::recognizeBSwapOrBitReverseIdiom(
2877 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2878 SmallVectorImpl<Instruction *> &InsertedInsts) {
2879 if (Operator::getOpcode(I) != Instruction::Or)
2880 return false;
2881 if (!MatchBSwaps && !MatchBitReversals)
2882 return false;
2883 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2884 if (!ITy || ITy->getBitWidth() > 128)
2885 return false; // Can't do vectors or integers > 128 bits.
2886 unsigned BW = ITy->getBitWidth();
2887
2888 unsigned DemandedBW = BW;
2889 IntegerType *DemandedTy = ITy;
2890 if (I->hasOneUse()) {
2891 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2892 DemandedTy = cast<IntegerType>(Trunc->getType());
2893 DemandedBW = DemandedTy->getBitWidth();
2894 }
2895 }
2896
2897 // Try to find all the pieces corresponding to the bswap.
2898 std::map<Value *, Optional<BitPart>> BPS;
2899 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
2900 if (!Res)
2901 return false;
2902 auto &BitProvenance = Res->Provenance;
2903
2904 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2905 // only byteswap values with an even number of bytes.
2906 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2907 for (unsigned i = 0; i < DemandedBW; ++i) {
2908 OKForBSwap &=
2909 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2910 OKForBitReverse &=
2911 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2912 }
2913
2914 Intrinsic::ID Intrin;
2915 if (OKForBSwap && MatchBSwaps)
2916 Intrin = Intrinsic::bswap;
2917 else if (OKForBitReverse && MatchBitReversals)
2918 Intrin = Intrinsic::bitreverse;
2919 else
2920 return false;
2921
2922 if (ITy != DemandedTy) {
2923 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2924 Value *Provider = Res->Provider;
2925 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2926 // We may need to truncate the provider.
2927 if (DemandedTy != ProviderTy) {
2928 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2929 "trunc", I);
2930 InsertedInsts.push_back(Trunc);
2931 Provider = Trunc;
2932 }
2933 auto *CI = CallInst::Create(F, Provider, "rev", I);
2934 InsertedInsts.push_back(CI);
2935 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2936 InsertedInsts.push_back(ExtInst);
2937 return true;
2938 }
2939
2940 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2941 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2942 return true;
2943 }
2944
2945 // CodeGen has special handling for some string functions that may replace
2946 // them with target-specific intrinsics. Since that'd skip our interceptors
2947 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2948 // we mark affected calls as NoBuiltin, which will disable optimization
2949 // in CodeGen.
maybeMarkSanitizerLibraryCallNoBuiltin(CallInst * CI,const TargetLibraryInfo * TLI)2950 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2951 CallInst *CI, const TargetLibraryInfo *TLI) {
2952 Function *F = CI->getCalledFunction();
2953 LibFunc Func;
2954 if (F && !F->hasLocalLinkage() && F->hasName() &&
2955 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2956 !F->doesNotAccessMemory())
2957 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
2958 }
2959
canReplaceOperandWithVariable(const Instruction * I,unsigned OpIdx)2960 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2961 // We can't have a PHI with a metadata type.
2962 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2963 return false;
2964
2965 // Early exit.
2966 if (!isa<Constant>(I->getOperand(OpIdx)))
2967 return true;
2968
2969 switch (I->getOpcode()) {
2970 default:
2971 return true;
2972 case Instruction::Call:
2973 case Instruction::Invoke: {
2974 const auto &CB = cast<CallBase>(*I);
2975
2976 // Can't handle inline asm. Skip it.
2977 if (CB.isInlineAsm())
2978 return false;
2979
2980 // Constant bundle operands may need to retain their constant-ness for
2981 // correctness.
2982 if (CB.isBundleOperand(OpIdx))
2983 return false;
2984
2985 if (OpIdx < CB.getNumArgOperands()) {
2986 // Some variadic intrinsics require constants in the variadic arguments,
2987 // which currently aren't markable as immarg.
2988 if (isa<IntrinsicInst>(CB) &&
2989 OpIdx >= CB.getFunctionType()->getNumParams()) {
2990 // This is known to be OK for stackmap.
2991 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
2992 }
2993
2994 // gcroot is a special case, since it requires a constant argument which
2995 // isn't also required to be a simple ConstantInt.
2996 if (CB.getIntrinsicID() == Intrinsic::gcroot)
2997 return false;
2998
2999 // Some intrinsic operands are required to be immediates.
3000 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
3001 }
3002
3003 // It is never allowed to replace the call argument to an intrinsic, but it
3004 // may be possible for a call.
3005 return !isa<IntrinsicInst>(CB);
3006 }
3007 case Instruction::ShuffleVector:
3008 // Shufflevector masks are constant.
3009 return OpIdx != 2;
3010 case Instruction::Switch:
3011 case Instruction::ExtractValue:
3012 // All operands apart from the first are constant.
3013 return OpIdx == 0;
3014 case Instruction::InsertValue:
3015 // All operands apart from the first and the second are constant.
3016 return OpIdx < 2;
3017 case Instruction::Alloca:
3018 // Static allocas (constant size in the entry block) are handled by
3019 // prologue/epilogue insertion so they're free anyway. We definitely don't
3020 // want to make them non-constant.
3021 return !cast<AllocaInst>(I)->isStaticAlloca();
3022 case Instruction::GetElementPtr:
3023 if (OpIdx == 0)
3024 return true;
3025 gep_type_iterator It = gep_type_begin(I);
3026 for (auto E = std::next(It, OpIdx); It != E; ++It)
3027 if (It.isStruct())
3028 return false;
3029 return true;
3030 }
3031 }
3032
3033 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
findAllocaForValue(Value * V,AllocaForValueMapTy & AllocaForValue)3034 AllocaInst *llvm::findAllocaForValue(Value *V,
3035 AllocaForValueMapTy &AllocaForValue) {
3036 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3037 return AI;
3038 // See if we've already calculated (or started to calculate) alloca for a
3039 // given value.
3040 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3041 if (I != AllocaForValue.end())
3042 return I->second;
3043 // Store 0 while we're calculating alloca for value V to avoid
3044 // infinite recursion if the value references itself.
3045 AllocaForValue[V] = nullptr;
3046 AllocaInst *Res = nullptr;
3047 if (CastInst *CI = dyn_cast<CastInst>(V))
3048 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
3049 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3050 for (Value *IncValue : PN->incoming_values()) {
3051 // Allow self-referencing phi-nodes.
3052 if (IncValue == PN)
3053 continue;
3054 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
3055 // AI for incoming values should exist and should all be equal.
3056 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3057 return nullptr;
3058 Res = IncValueAI;
3059 }
3060 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3061 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
3062 } else {
3063 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
3064 << *V << "\n");
3065 }
3066 if (Res)
3067 AllocaForValue[V] = Res;
3068 return Res;
3069 }
3070
invertCondition(Value * Condition)3071 Value *llvm::invertCondition(Value *Condition) {
3072 // First: Check if it's a constant
3073 if (Constant *C = dyn_cast<Constant>(Condition))
3074 return ConstantExpr::getNot(C);
3075
3076 // Second: If the condition is already inverted, return the original value
3077 Value *NotCondition;
3078 if (match(Condition, m_Not(m_Value(NotCondition))))
3079 return NotCondition;
3080
3081 BasicBlock *Parent = nullptr;
3082 Instruction *Inst = dyn_cast<Instruction>(Condition);
3083 if (Inst)
3084 Parent = Inst->getParent();
3085 else if (Argument *Arg = dyn_cast<Argument>(Condition))
3086 Parent = &Arg->getParent()->getEntryBlock();
3087 assert(Parent && "Unsupported condition to invert");
3088
3089 // Third: Check all the users for an invert
3090 for (User *U : Condition->users())
3091 if (Instruction *I = dyn_cast<Instruction>(U))
3092 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
3093 return I;
3094
3095 // Last option: Create a new instruction
3096 auto *Inverted =
3097 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
3098 if (Inst && !isa<PHINode>(Inst))
3099 Inverted->insertAfter(Inst);
3100 else
3101 Inverted->insertBefore(&*Parent->getFirstInsertionPt());
3102 return Inverted;
3103 }
3104