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/DenseSet.h"
18#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AssumeBundleQueries.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/DomTreeUpdater.h"
27#include "llvm/Analysis/InstructionSimplify.h"
28#include "llvm/Analysis/MemoryBuiltins.h"
29#include "llvm/Analysis/MemorySSAUpdater.h"
30#include "llvm/Analysis/TargetLibraryInfo.h"
31#include "llvm/Analysis/ValueTracking.h"
32#include "llvm/Analysis/VectorUtils.h"
33#include "llvm/BinaryFormat/Dwarf.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CFG.h"
38#include "llvm/IR/Constant.h"
39#include "llvm/IR/ConstantRange.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DIBuilder.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
44#include "llvm/IR/DebugInfoMetadata.h"
45#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/DerivedTypes.h"
47#include "llvm/IR/Dominators.h"
48#include "llvm/IR/EHPersonalities.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/GetElementPtrTypeIterator.h"
51#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
55#include "llvm/IR/IntrinsicInst.h"
56#include "llvm/IR/Intrinsics.h"
57#include "llvm/IR/IntrinsicsWebAssembly.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/MDBuilder.h"
60#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/PatternMatch.h"
64#include "llvm/IR/ProfDataUtils.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/Use.h"
67#include "llvm/IR/User.h"
68#include "llvm/IR/Value.h"
69#include "llvm/IR/ValueHandle.h"
70#include "llvm/Support/Casting.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/Compiler.h"
73#include "llvm/Support/Debug.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/KnownBits.h"
76#include "llvm/Support/raw_ostream.h"
77#include "llvm/Transforms/Utils/BasicBlockUtils.h"
78#include "llvm/Transforms/Utils/ValueMapper.h"
79#include <algorithm>
80#include <cassert>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <optional>
85#include <utility>
86
87using namespace llvm;
88using namespace llvm::PatternMatch;
89
90#define DEBUG_TYPE "local"
91
92STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
93STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
94
95static cl::opt<bool> PHICSEDebugHash(
96 "phicse-debug-hash",
97#ifdef EXPENSIVE_CHECKS
98 cl::init(true),
99#else
100 cl::init(Val: false),
101#endif
102 cl::Hidden,
103 cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
104 "function is well-behaved w.r.t. its isEqual predicate"));
105
106static cl::opt<unsigned> PHICSENumPHISmallSize(
107 "phicse-num-phi-smallsize", cl::init(Val: 32), cl::Hidden,
108 cl::desc(
109 "When the basic block contains not more than this number of PHI nodes, "
110 "perform a (faster!) exhaustive search instead of set-driven one."));
111
112static cl::opt<unsigned> MaxPhiEntriesIncreaseAfterRemovingEmptyBlock(
113 "max-phi-entries-increase-after-removing-empty-block", cl::init(Val: 1000),
114 cl::Hidden,
115 cl::desc("Stop removing an empty block if removing it will introduce more "
116 "than this number of phi entries in its successor"));
117
118// Max recursion depth for collectBitParts used when detecting bswap and
119// bitreverse idioms.
120static const unsigned BitPartRecursionMaxDepth = 48;
121
122//===----------------------------------------------------------------------===//
123// Local constant propagation.
124//
125
126/// ConstantFoldTerminator - If a terminator instruction is predicated on a
127/// constant value, convert it into an unconditional branch to the constant
128/// destination. This is a nontrivial operation because the successors of this
129/// basic block must have their PHI nodes updated.
130/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
131/// conditions and indirectbr addresses this might make dead if
132/// DeleteDeadConditions is true.
133bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
134 const TargetLibraryInfo *TLI,
135 DomTreeUpdater *DTU) {
136 Instruction *T = BB->getTerminator();
137 IRBuilder<> Builder(T);
138
139 // Branch - See if we are conditional jumping on constant
140 if (auto *BI = dyn_cast<CondBrInst>(Val: T)) {
141 BasicBlock *Dest1 = BI->getSuccessor(i: 0);
142 BasicBlock *Dest2 = BI->getSuccessor(i: 1);
143
144 if (Dest2 == Dest1) { // Conditional branch to same location?
145 // This branch matches something like this:
146 // br bool %cond, label %Dest, label %Dest
147 // and changes it into: br label %Dest
148
149 // Let the basic block know that we are letting go of one copy of it.
150 assert(BI->getParent() && "Terminator not inserted in block!");
151 Dest1->removePredecessor(Pred: BI->getParent());
152
153 // Replace the conditional branch with an unconditional one.
154 UncondBrInst *NewBI = Builder.CreateBr(Dest: Dest1);
155
156 // Transfer the metadata to the new branch instruction.
157 NewBI->copyMetadata(SrcInst: *BI, WL: {LLVMContext::MD_loop, LLVMContext::MD_dbg,
158 LLVMContext::MD_annotation});
159
160 Value *Cond = BI->getCondition();
161 BI->eraseFromParent();
162 if (DeleteDeadConditions)
163 RecursivelyDeleteTriviallyDeadInstructions(V: Cond, TLI);
164 return true;
165 }
166
167 if (auto *Cond = dyn_cast<ConstantInt>(Val: BI->getCondition())) {
168 // Are we branching on constant?
169 // YES. Change to unconditional branch...
170 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
171 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
172
173 // Let the basic block know that we are letting go of it. Based on this,
174 // it will adjust it's PHI nodes.
175 OldDest->removePredecessor(Pred: BB);
176
177 // Replace the conditional branch with an unconditional one.
178 UncondBrInst *NewBI = Builder.CreateBr(Dest: Destination);
179
180 // Transfer the metadata to the new branch instruction.
181 NewBI->copyMetadata(SrcInst: *BI, WL: {LLVMContext::MD_loop, LLVMContext::MD_dbg,
182 LLVMContext::MD_annotation});
183
184 BI->eraseFromParent();
185 if (DTU)
186 DTU->applyUpdates(Updates: {{DominatorTree::Delete, BB, OldDest}});
187 return true;
188 }
189
190 return false;
191 }
192
193 if (auto *SI = dyn_cast<SwitchInst>(Val: T)) {
194 // If we are switching on a constant, we can convert the switch to an
195 // unconditional branch.
196 auto *CI = dyn_cast<ConstantInt>(Val: SI->getCondition());
197 BasicBlock *DefaultDest = SI->getDefaultDest();
198 BasicBlock *TheOnlyDest = DefaultDest;
199
200 // If the default is unreachable, ignore it when searching for TheOnlyDest.
201 if (SI->defaultDestUnreachable() && SI->getNumCases() > 0)
202 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
203
204 bool Changed = false;
205
206 // Figure out which case it goes to.
207 for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {
208 // Found case matching a constant operand?
209 if (It->getCaseValue() == CI) {
210 TheOnlyDest = It->getCaseSuccessor();
211 break;
212 }
213
214 // Check to see if this branch is going to the same place as the default
215 // dest. If so, eliminate it as an explicit compare.
216 if (It->getCaseSuccessor() == DefaultDest) {
217 MDNode *MD = getValidBranchWeightMDNode(I: *SI);
218 unsigned NCases = SI->getNumCases();
219 // Fold the case metadata into the default if there will be any branches
220 // left, unless the metadata doesn't match the switch.
221 if (NCases > 1 && MD) {
222 // Collect branch weights into a vector.
223 SmallVector<uint64_t, 8> Weights;
224 extractFromBranchWeightMD64(ProfileData: MD, Weights);
225
226 // Merge weight of this case to the default weight.
227 unsigned Idx = It->getCaseIndex();
228
229 // Check for and prevent uint64_t overflow by reducing branch weights.
230 if (Weights[0] > UINT64_MAX - Weights[Idx + 1])
231 fitWeights(Weights);
232
233 Weights[0] += Weights[Idx + 1];
234 // Remove weight for this case.
235 std::swap(a&: Weights[Idx + 1], b&: Weights.back());
236 Weights.pop_back();
237 setFittedBranchWeights(I&: *SI, Weights, IsExpected: hasBranchWeightOrigin(ProfileData: MD));
238 }
239 // Remove this entry.
240 BasicBlock *ParentBB = SI->getParent();
241 DefaultDest->removePredecessor(Pred: ParentBB);
242 It = SI->removeCase(I: It);
243 End = SI->case_end();
244
245 // Removing this case may have made the condition constant. In that
246 // case, update CI and restart iteration through the cases.
247 if (auto *NewCI = dyn_cast<ConstantInt>(Val: SI->getCondition())) {
248 CI = NewCI;
249 It = SI->case_begin();
250 }
251
252 Changed = true;
253 continue;
254 }
255
256 // Otherwise, check to see if the switch only branches to one destination.
257 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
258 // destinations.
259 if (It->getCaseSuccessor() != TheOnlyDest)
260 TheOnlyDest = nullptr;
261
262 // Increment this iterator as we haven't removed the case.
263 ++It;
264 }
265
266 if (CI && !TheOnlyDest) {
267 // Branching on a constant, but not any of the cases, go to the default
268 // successor.
269 TheOnlyDest = SI->getDefaultDest();
270 }
271
272 // If we found a single destination that we can fold the switch into, do so
273 // now.
274 if (TheOnlyDest) {
275 // Insert the new branch.
276 Builder.CreateBr(Dest: TheOnlyDest);
277 BasicBlock *BB = SI->getParent();
278
279 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
280
281 // Remove entries from PHI nodes which we no longer branch to...
282 BasicBlock *SuccToKeep = TheOnlyDest;
283 for (BasicBlock *Succ : successors(I: SI)) {
284 if (DTU && Succ != TheOnlyDest)
285 RemovedSuccessors.insert(Ptr: Succ);
286 // Found case matching a constant operand?
287 if (Succ == SuccToKeep) {
288 SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
289 } else {
290 Succ->removePredecessor(Pred: BB);
291 }
292 }
293
294 // Delete the old switch.
295 Value *Cond = SI->getCondition();
296 SI->eraseFromParent();
297 if (DeleteDeadConditions)
298 RecursivelyDeleteTriviallyDeadInstructions(V: Cond, TLI);
299 if (DTU) {
300 std::vector<DominatorTree::UpdateType> Updates;
301 Updates.reserve(n: RemovedSuccessors.size());
302 for (auto *RemovedSuccessor : RemovedSuccessors)
303 Updates.push_back(x: {DominatorTree::Delete, BB, RemovedSuccessor});
304 DTU->applyUpdates(Updates);
305 }
306 return true;
307 }
308
309 if (SI->getNumCases() == 1) {
310 // Otherwise, we can fold this switch into a conditional branch
311 // instruction if it has only one non-default destination.
312 auto FirstCase = *SI->case_begin();
313 Value *Cond = Builder.CreateICmpEQ(LHS: SI->getCondition(),
314 RHS: FirstCase.getCaseValue(), Name: "cond");
315
316 // Insert the new branch.
317 CondBrInst *NewBr = Builder.CreateCondBr(
318 Cond, True: FirstCase.getCaseSuccessor(), False: SI->getDefaultDest());
319 SmallVector<uint32_t> Weights;
320 if (extractBranchWeights(I: *SI, Weights) && Weights.size() == 2) {
321 uint32_t DefWeight = Weights[0];
322 uint32_t CaseWeight = Weights[1];
323 // The TrueWeight should be the weight for the single case of SI.
324 NewBr->setMetadata(KindID: LLVMContext::MD_prof,
325 Node: MDBuilder(BB->getContext())
326 .createBranchWeights(TrueWeight: CaseWeight, FalseWeight: DefWeight));
327 }
328
329 // Update make.implicit metadata to the newly-created conditional branch.
330 MDNode *MakeImplicitMD = SI->getMetadata(KindID: LLVMContext::MD_make_implicit);
331 if (MakeImplicitMD)
332 NewBr->setMetadata(KindID: LLVMContext::MD_make_implicit, Node: MakeImplicitMD);
333
334 // Delete the old switch.
335 SI->eraseFromParent();
336 return true;
337 }
338 return Changed;
339 }
340
341 if (auto *IBI = dyn_cast<IndirectBrInst>(Val: T)) {
342 // indirectbr blockaddress(@F, @BB) -> br label @BB
343 if (auto *BA =
344 dyn_cast<BlockAddress>(Val: IBI->getAddress()->stripPointerCasts())) {
345 BasicBlock *TheOnlyDest = BA->getBasicBlock();
346 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
347
348 // Insert the new branch.
349 Builder.CreateBr(Dest: TheOnlyDest);
350
351 BasicBlock *SuccToKeep = TheOnlyDest;
352 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
353 BasicBlock *DestBB = IBI->getDestination(i);
354 if (DTU && DestBB != TheOnlyDest)
355 RemovedSuccessors.insert(Ptr: DestBB);
356 if (IBI->getDestination(i) == SuccToKeep) {
357 SuccToKeep = nullptr;
358 } else {
359 DestBB->removePredecessor(Pred: BB);
360 }
361 }
362 Value *Address = IBI->getAddress();
363 IBI->eraseFromParent();
364 if (DeleteDeadConditions)
365 // Delete pointer cast instructions.
366 RecursivelyDeleteTriviallyDeadInstructions(V: Address, TLI);
367
368 // Also zap the blockaddress constant if there are no users remaining,
369 // otherwise the destination is still marked as having its address taken.
370 if (BA->use_empty())
371 BA->destroyConstant();
372
373 // If we didn't find our destination in the IBI successor list, then we
374 // have undefined behavior. Replace the unconditional branch with an
375 // 'unreachable' instruction.
376 if (SuccToKeep) {
377 BB->getTerminator()->eraseFromParent();
378 new UnreachableInst(BB->getContext(), BB);
379 }
380
381 if (DTU) {
382 std::vector<DominatorTree::UpdateType> Updates;
383 Updates.reserve(n: RemovedSuccessors.size());
384 for (auto *RemovedSuccessor : RemovedSuccessors)
385 Updates.push_back(x: {DominatorTree::Delete, BB, RemovedSuccessor});
386 DTU->applyUpdates(Updates);
387 }
388 return true;
389 }
390 }
391
392 return false;
393}
394
395//===----------------------------------------------------------------------===//
396// Local dead code elimination.
397//
398
399/// isInstructionTriviallyDead - Return true if the result produced by the
400/// instruction is not used, and the instruction has no side effects.
401///
402bool llvm::isInstructionTriviallyDead(Instruction *I,
403 const TargetLibraryInfo *TLI) {
404 if (!I->use_empty())
405 return false;
406 return wouldInstructionBeTriviallyDead(I, TLI);
407}
408
409bool llvm::wouldInstructionBeTriviallyDead(const Instruction *I,
410 const TargetLibraryInfo *TLI) {
411 if (I->isTerminator())
412 return false;
413
414 // We don't want the landingpad-like instructions removed by anything this
415 // general.
416 if (I->isEHPad())
417 return false;
418
419 if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(Val: I)) {
420 if (DLI->getLabel())
421 return false;
422 return true;
423 }
424
425 if (auto *CB = dyn_cast<CallBase>(Val: I))
426 if (isRemovableAlloc(V: CB, TLI))
427 return true;
428
429 if (!I->willReturn()) {
430 auto *II = dyn_cast<IntrinsicInst>(Val: I);
431 if (!II)
432 return false;
433
434 switch (II->getIntrinsicID()) {
435 case Intrinsic::experimental_guard: {
436 // Guards on true are operationally no-ops. In the future we can
437 // consider more sophisticated tradeoffs for guards considering potential
438 // for check widening, but for now we keep things simple.
439 auto *Cond = dyn_cast<ConstantInt>(Val: II->getArgOperand(i: 0));
440 return Cond && Cond->isOne();
441 }
442 // TODO: These intrinsics are not safe to remove, because this may remove
443 // a well-defined trap.
444 case Intrinsic::wasm_trunc_signed:
445 case Intrinsic::wasm_trunc_unsigned:
446 case Intrinsic::ptrauth_auth:
447 case Intrinsic::ptrauth_resign:
448 case Intrinsic::ptrauth_resign_load_relative:
449 return true;
450 default:
451 return false;
452 }
453 }
454
455 if (!I->mayHaveSideEffects())
456 return true;
457
458 // Special case intrinsics that "may have side effects" but can be deleted
459 // when dead.
460 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
461 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
462 if (II->getIntrinsicID() == Intrinsic::stacksave ||
463 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
464 return true;
465
466 // Intrinsics declare sideeffects to prevent them from moving, but they are
467 // nops without users.
468 if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
469 II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
470 return true;
471
472 if (II->isLifetimeStartOrEnd()) {
473 auto *Arg = II->getArgOperand(i: 0);
474 if (isa<PoisonValue>(Val: Arg))
475 return true;
476
477 // If the only uses of the alloca are lifetime intrinsics, then the
478 // intrinsics are dead.
479 return llvm::all_of(Range: Arg->uses(), P: [](Use &Use) {
480 return isa<LifetimeIntrinsic>(Val: Use.getUser());
481 });
482 }
483
484 // Assumptions are dead if their condition is trivially true.
485 if (II->getIntrinsicID() == Intrinsic::assume &&
486 isAssumeWithEmptyBundle(Assume: cast<AssumeInst>(Val: *II))) {
487 if (ConstantInt *Cond = dyn_cast<ConstantInt>(Val: II->getArgOperand(i: 0)))
488 return !Cond->isZero();
489
490 return false;
491 }
492
493 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(Val: I)) {
494 std::optional<fp::ExceptionBehavior> ExBehavior =
495 FPI->getExceptionBehavior();
496 return *ExBehavior != fp::ebStrict;
497 }
498 }
499
500 if (auto *Call = dyn_cast<CallBase>(Val: I)) {
501 if (Value *FreedOp = getFreedOperand(CB: Call, TLI))
502 if (Constant *C = dyn_cast<Constant>(Val: FreedOp))
503 return C->isNullValue() || isa<UndefValue>(Val: C);
504 if (isMathLibCallNoop(Call, TLI))
505 return true;
506 }
507
508 // Non-volatile atomic loads from constants can be removed.
509 if (auto *LI = dyn_cast<LoadInst>(Val: I))
510 if (auto *GV = dyn_cast<GlobalVariable>(
511 Val: LI->getPointerOperand()->stripPointerCasts()))
512 if (!LI->isVolatile() && GV->isConstant())
513 return true;
514
515 return false;
516}
517
518/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
519/// trivially dead instruction, delete it. If that makes any of its operands
520/// trivially dead, delete them too, recursively. Return true if any
521/// instructions were deleted.
522bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
523 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
524 std::function<void(Value *)> AboutToDeleteCallback) {
525 Instruction *I = dyn_cast<Instruction>(Val: V);
526 if (!I || !isInstructionTriviallyDead(I, TLI))
527 return false;
528
529 SmallVector<WeakTrackingVH, 16> DeadInsts;
530 DeadInsts.push_back(Elt: I);
531 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
532 AboutToDeleteCallback);
533
534 return true;
535}
536
537bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
538 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
539 MemorySSAUpdater *MSSAU,
540 std::function<void(Value *)> AboutToDeleteCallback) {
541 unsigned S = 0, E = DeadInsts.size(), Alive = 0;
542 for (; S != E; ++S) {
543 auto *I = dyn_cast_or_null<Instruction>(Val&: DeadInsts[S]);
544 if (!I || !isInstructionTriviallyDead(I)) {
545 DeadInsts[S] = nullptr;
546 ++Alive;
547 }
548 }
549 if (Alive == E)
550 return false;
551 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
552 AboutToDeleteCallback);
553 return true;
554}
555
556void llvm::RecursivelyDeleteTriviallyDeadInstructions(
557 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
558 MemorySSAUpdater *MSSAU,
559 std::function<void(Value *)> AboutToDeleteCallback) {
560 // Process the dead instruction list until empty.
561 while (!DeadInsts.empty()) {
562 Value *V = DeadInsts.pop_back_val();
563 Instruction *I = cast_or_null<Instruction>(Val: V);
564 if (!I)
565 continue;
566 assert(isInstructionTriviallyDead(I, TLI) &&
567 "Live instruction found in dead worklist!");
568 assert(I->use_empty() && "Instructions with uses are not dead.");
569
570 // Don't lose the debug info while deleting the instructions.
571 salvageDebugInfo(I&: *I);
572
573 if (AboutToDeleteCallback)
574 AboutToDeleteCallback(I);
575
576 // Null out all of the instruction's operands to see if any operand becomes
577 // dead as we go.
578 for (Use &OpU : I->operands()) {
579 Value *OpV = OpU.get();
580 OpU.set(nullptr);
581
582 if (!OpV->use_empty())
583 continue;
584
585 // If the operand is an instruction that became dead as we nulled out the
586 // operand, and if it is 'trivially' dead, delete it in a future loop
587 // iteration.
588 if (Instruction *OpI = dyn_cast<Instruction>(Val: OpV))
589 if (isInstructionTriviallyDead(I: OpI, TLI))
590 DeadInsts.push_back(Elt: OpI);
591 }
592 if (MSSAU)
593 MSSAU->removeMemoryAccess(I);
594
595 I->eraseFromParent();
596 }
597}
598
599/// areAllUsesEqual - Check whether the uses of a value are all the same.
600/// This is similar to Instruction::hasOneUse() except this will also return
601/// true when there are no uses or multiple uses that all refer to the same
602/// value.
603static bool areAllUsesEqual(Instruction *I) {
604 Value::user_iterator UI = I->user_begin();
605 Value::user_iterator UE = I->user_end();
606 if (UI == UE)
607 return true;
608
609 User *TheUse = *UI;
610 for (++UI; UI != UE; ++UI) {
611 if (*UI != TheUse)
612 return false;
613 }
614 return true;
615}
616
617/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
618/// dead PHI node, due to being a def-use chain of single-use nodes that
619/// either forms a cycle or is terminated by a trivially dead instruction,
620/// delete it. If that makes any of its operands trivially dead, delete them
621/// too, recursively. Return true if a change was made.
622bool llvm::RecursivelyDeleteDeadPHINode(
623 PHINode *PN, const TargetLibraryInfo *TLI, llvm::MemorySSAUpdater *MSSAU,
624 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs) {
625 SmallPtrSet<Instruction*, 4> Visited;
626 SmallVector<PHINode *, 8> VisitedPHIs;
627
628 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
629 I = cast<Instruction>(Val: *I->user_begin())) {
630 if (I->use_empty())
631 return RecursivelyDeleteTriviallyDeadInstructions(V: I, TLI, MSSAU);
632
633 // If we find an instruction more than once, we're on a cycle that
634 // won't prove fruitful.
635 if (!Visited.insert(Ptr: I).second) {
636 // Break the cycle and delete the instruction and its operands.
637 I->replaceAllUsesWith(V: PoisonValue::get(T: I->getType()));
638 (void)RecursivelyDeleteTriviallyDeadInstructions(V: I, TLI, MSSAU);
639 return true;
640 }
641
642 if (PHINode *CurPN = dyn_cast<PHINode>(Val: I)) {
643 if (KnownNonDeadPHIs && KnownNonDeadPHIs->contains(Ptr: CurPN))
644 break;
645 VisitedPHIs.push_back(Elt: CurPN);
646 }
647 }
648
649 if (KnownNonDeadPHIs)
650 for (PHINode *VisitedPN : VisitedPHIs)
651 KnownNonDeadPHIs->insert(Ptr: VisitedPN);
652
653 return false;
654}
655
656static bool
657simplifyAndDCEInstruction(Instruction *I,
658 SmallSetVector<Instruction *, 16> &WorkList,
659 const DataLayout &DL,
660 const TargetLibraryInfo *TLI) {
661 if (isInstructionTriviallyDead(I, TLI)) {
662 salvageDebugInfo(I&: *I);
663
664 // Null out all of the instruction's operands to see if any operand becomes
665 // dead as we go.
666 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
667 Value *OpV = I->getOperand(i);
668 I->setOperand(i, Val: nullptr);
669
670 if (!OpV->use_empty() || I == OpV)
671 continue;
672
673 // If the operand is an instruction that became dead as we nulled out the
674 // operand, and if it is 'trivially' dead, delete it in a future loop
675 // iteration.
676 if (Instruction *OpI = dyn_cast<Instruction>(Val: OpV))
677 if (isInstructionTriviallyDead(I: OpI, TLI))
678 WorkList.insert(X: OpI);
679 }
680
681 I->eraseFromParent();
682
683 return true;
684 }
685
686 if (Value *SimpleV = simplifyInstruction(I, Q: DL)) {
687 // Add the users to the worklist. CAREFUL: an instruction can use itself,
688 // in the case of a phi node.
689 for (User *U : I->users()) {
690 if (U != I) {
691 WorkList.insert(X: cast<Instruction>(Val: U));
692 }
693 }
694
695 // Replace the instruction with its simplified value.
696 bool Changed = false;
697 if (!I->use_empty()) {
698 I->replaceAllUsesWith(V: SimpleV);
699 Changed = true;
700 }
701 if (isInstructionTriviallyDead(I, TLI)) {
702 I->eraseFromParent();
703 Changed = true;
704 }
705 return Changed;
706 }
707 return false;
708}
709
710/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
711/// simplify any instructions in it and recursively delete dead instructions.
712///
713/// This returns true if it changed the code, note that it can delete
714/// instructions in other blocks as well in this block.
715bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
716 const TargetLibraryInfo *TLI) {
717 bool MadeChange = false;
718 const DataLayout &DL = BB->getDataLayout();
719
720#ifndef NDEBUG
721 // In debug builds, ensure that the terminator of the block is never replaced
722 // or deleted by these simplifications. The idea of simplification is that it
723 // cannot introduce new instructions, and there is no way to replace the
724 // terminator of a block without introducing a new instruction.
725 AssertingVH<Instruction> TerminatorVH(&BB->back());
726#endif
727
728 SmallSetVector<Instruction *, 16> WorkList;
729 // Iterate over the original function, only adding insts to the worklist
730 // if they actually need to be revisited. This avoids having to pre-init
731 // the worklist with the entire function's worth of instructions.
732 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(x: BB->end());
733 BI != E;) {
734 assert(!BI->isTerminator());
735 Instruction *I = &*BI;
736 ++BI;
737
738 // We're visiting this instruction now, so make sure it's not in the
739 // worklist from an earlier visit.
740 if (!WorkList.count(key: I))
741 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
742 }
743
744 while (!WorkList.empty()) {
745 Instruction *I = WorkList.pop_back_val();
746 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
747 }
748 return MadeChange;
749}
750
751//===----------------------------------------------------------------------===//
752// Control Flow Graph Restructuring.
753//
754
755void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
756 DomTreeUpdater *DTU) {
757
758 // If BB has single-entry PHI nodes, fold them.
759 while (PHINode *PN = dyn_cast<PHINode>(Val: DestBB->begin())) {
760 Value *NewVal = PN->getIncomingValue(i: 0);
761 // Replace self referencing PHI with poison, it must be dead.
762 if (NewVal == PN) NewVal = PoisonValue::get(T: PN->getType());
763 PN->replaceAllUsesWith(V: NewVal);
764 PN->eraseFromParent();
765 }
766
767 BasicBlock *PredBB = DestBB->getSinglePredecessor();
768 assert(PredBB && "Block doesn't have a single predecessor!");
769
770 bool ReplaceEntryBB = PredBB->isEntryBlock();
771
772 // DTU updates: Collect all the edges that enter
773 // PredBB. These dominator edges will be redirected to DestBB.
774 SmallVector<DominatorTree::UpdateType, 32> Updates;
775
776 if (DTU) {
777 // To avoid processing the same predecessor more than once.
778 SmallPtrSet<BasicBlock *, 2> SeenPreds;
779 Updates.reserve(N: Updates.size() + 2 * pred_size(BB: PredBB) + 1);
780 for (BasicBlock *PredOfPredBB : predecessors(BB: PredBB))
781 // This predecessor of PredBB may already have DestBB as a successor.
782 if (PredOfPredBB != PredBB)
783 if (SeenPreds.insert(Ptr: PredOfPredBB).second)
784 Updates.push_back(Elt: {DominatorTree::Insert, PredOfPredBB, DestBB});
785 SeenPreds.clear();
786 for (BasicBlock *PredOfPredBB : predecessors(BB: PredBB))
787 if (SeenPreds.insert(Ptr: PredOfPredBB).second)
788 Updates.push_back(Elt: {DominatorTree::Delete, PredOfPredBB, PredBB});
789 Updates.push_back(Elt: {DominatorTree::Delete, PredBB, DestBB});
790 }
791
792 // Zap anything that took the address of DestBB. Not doing this will give the
793 // address an invalid value.
794 if (DestBB->hasAddressTaken()) {
795 BlockAddress *BA = BlockAddress::get(BB: DestBB);
796 Constant *Replacement =
797 ConstantInt::get(Ty: Type::getInt32Ty(C&: BA->getContext()), V: 1);
798 BA->replaceAllUsesWith(V: ConstantExpr::getIntToPtr(C: Replacement,
799 Ty: BA->getType()));
800 BA->destroyConstant();
801 }
802
803 // Anything that branched to PredBB now branches to DestBB.
804 PredBB->replaceAllUsesWith(V: DestBB);
805
806 // Splice all the instructions from PredBB to DestBB.
807 PredBB->getTerminator()->eraseFromParent();
808 DestBB->splice(ToIt: DestBB->begin(), FromBB: PredBB);
809 new UnreachableInst(PredBB->getContext(), PredBB);
810
811 // If the PredBB is the entry block of the function, move DestBB up to
812 // become the entry block after we erase PredBB.
813 if (ReplaceEntryBB)
814 DestBB->moveAfter(MovePos: PredBB);
815
816 if (DTU) {
817 assert(PredBB->size() == 1 &&
818 isa<UnreachableInst>(PredBB->getTerminator()) &&
819 "The successor list of PredBB isn't empty before "
820 "applying corresponding DTU updates.");
821 DTU->applyUpdatesPermissive(Updates);
822 DTU->deleteBB(DelBB: PredBB);
823 // Recalculation of DomTree is needed when updating a forward DomTree and
824 // the Entry BB is replaced.
825 if (ReplaceEntryBB && DTU->hasDomTree()) {
826 // The entry block was removed and there is no external interface for
827 // the dominator tree to be notified of this change. In this corner-case
828 // we recalculate the entire tree.
829 DTU->recalculate(F&: *(DestBB->getParent()));
830 }
831 }
832
833 else {
834 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
835 }
836}
837
838/// Return true if we can choose one of these values to use in place of the
839/// other. Note that we will always choose the non-undef value to keep.
840static bool CanMergeValues(Value *First, Value *Second) {
841 return First == Second || isa<UndefValue>(Val: First) || isa<UndefValue>(Val: Second);
842}
843
844/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
845/// branch to Succ, into Succ.
846///
847/// Assumption: Succ is the single successor for BB.
848static bool
849CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ,
850 const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
851 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
852
853 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
854 << Succ->getName() << "\n");
855 // Shortcut, if there is only a single predecessor it must be BB and merging
856 // is always safe
857 if (Succ->getSinglePredecessor())
858 return true;
859
860 // Look at all the phi nodes in Succ, to see if they present a conflict when
861 // merging these blocks
862 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(Val: I); ++I) {
863 PHINode *PN = cast<PHINode>(Val&: I);
864
865 // If the incoming value from BB is again a PHINode in
866 // BB which has the same incoming value for *PI as PN does, we can
867 // merge the phi nodes and then the blocks can still be merged
868 PHINode *BBPN = dyn_cast<PHINode>(Val: PN->getIncomingValueForBlock(BB));
869 if (BBPN && BBPN->getParent() == BB) {
870 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
871 BasicBlock *IBB = PN->getIncomingBlock(i: PI);
872 if (BBPreds.count(Ptr: IBB) &&
873 !CanMergeValues(First: BBPN->getIncomingValueForBlock(BB: IBB),
874 Second: PN->getIncomingValue(i: PI))) {
875 LLVM_DEBUG(dbgs()
876 << "Can't fold, phi node " << PN->getName() << " in "
877 << Succ->getName() << " is conflicting with "
878 << BBPN->getName() << " with regard to common predecessor "
879 << IBB->getName() << "\n");
880 return false;
881 }
882 }
883 } else {
884 Value* Val = PN->getIncomingValueForBlock(BB);
885 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
886 // See if the incoming value for the common predecessor is equal to the
887 // one for BB, in which case this phi node will not prevent the merging
888 // of the block.
889 BasicBlock *IBB = PN->getIncomingBlock(i: PI);
890 if (BBPreds.count(Ptr: IBB) &&
891 !CanMergeValues(First: Val, Second: PN->getIncomingValue(i: PI))) {
892 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
893 << " in " << Succ->getName()
894 << " is conflicting with regard to common "
895 << "predecessor " << IBB->getName() << "\n");
896 return false;
897 }
898 }
899 }
900 }
901
902 return true;
903}
904
905using PredBlockVector = SmallVector<BasicBlock *, 16>;
906using IncomingValueMap = SmallDenseMap<BasicBlock *, Value *, 16>;
907
908/// Determines the value to use as the phi node input for a block.
909///
910/// Select between \p OldVal any value that we know flows from \p BB
911/// to a particular phi on the basis of which one (if either) is not
912/// undef. Update IncomingValues based on the selected value.
913///
914/// \param OldVal The value we are considering selecting.
915/// \param BB The block that the value flows in from.
916/// \param IncomingValues A map from block-to-value for other phi inputs
917/// that we have examined.
918///
919/// \returns the selected value.
920static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
921 IncomingValueMap &IncomingValues) {
922 IncomingValueMap::const_iterator It = IncomingValues.find(Val: BB);
923 if (!isa<UndefValue>(Val: OldVal)) {
924 assert((It != IncomingValues.end() &&
925 (!(It->second) || It->second == OldVal)) &&
926 "Expected OldVal to match incoming value from BB!");
927
928 IncomingValues.insert_or_assign(Key: BB, Val&: OldVal);
929 return OldVal;
930 }
931
932 if (It != IncomingValues.end() && It->second)
933 return It->second;
934
935 return OldVal;
936}
937
938/// Create a map from block to value for the operands of a
939/// given phi.
940///
941/// This function initializes the map with UndefValue for all predecessors
942/// in BBPreds, and then updates the map with concrete non-undef values
943/// found in the PHI node.
944///
945/// \param PN The phi we are collecting the map for.
946/// \param BBPreds The list of all predecessor blocks to initialize with Undef.
947/// \param IncomingValues [out] The map from block to value for this phi.
948static void gatherIncomingValuesToPhi(PHINode *PN,
949 const PredBlockVector &BBPreds,
950 IncomingValueMap &IncomingValues) {
951 for (BasicBlock *Pred : BBPreds)
952 IncomingValues[Pred] = nullptr;
953
954 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
955 Value *V = PN->getIncomingValue(i);
956 if (isa<UndefValue>(Val: V))
957 continue;
958
959 BasicBlock *BB = PN->getIncomingBlock(i);
960 auto It = IncomingValues.find(Val: BB);
961 if (It != IncomingValues.end())
962 It->second = V;
963 }
964}
965
966/// Replace the incoming undef values to a phi with the values
967/// from a block-to-value map.
968///
969/// \param PN The phi we are replacing the undefs in.
970/// \param IncomingValues A map from block to value.
971static void replaceUndefValuesInPhi(PHINode *PN,
972 const IncomingValueMap &IncomingValues) {
973 SmallVector<unsigned> TrueUndefOps;
974 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
975 Value *V = PN->getIncomingValue(i);
976
977 if (!isa<UndefValue>(Val: V)) continue;
978
979 BasicBlock *BB = PN->getIncomingBlock(i);
980 IncomingValueMap::const_iterator It = IncomingValues.find(Val: BB);
981 if (It == IncomingValues.end())
982 continue;
983
984 // Keep track of undef/poison incoming values. Those must match, so we fix
985 // them up below if needed.
986 // Note: this is conservatively correct, but we could try harder and group
987 // the undef values per incoming basic block.
988 if (!It->second) {
989 TrueUndefOps.push_back(Elt: i);
990 continue;
991 }
992
993 // There is a defined value for this incoming block, so map this undef
994 // incoming value to the defined value.
995 PN->setIncomingValue(i, V: It->second);
996 }
997
998 // If there are both undef and poison values incoming, then convert those
999 // values to undef. It is invalid to have different values for the same
1000 // incoming block.
1001 unsigned PoisonCount = count_if(Range&: TrueUndefOps, P: [&](unsigned i) {
1002 return isa<PoisonValue>(Val: PN->getIncomingValue(i));
1003 });
1004 if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1005 for (unsigned i : TrueUndefOps)
1006 PN->setIncomingValue(i, V: UndefValue::get(T: PN->getType()));
1007 }
1008}
1009
1010// Only when they shares a single common predecessor, return true.
1011// Only handles cases when BB can't be merged while its predecessors can be
1012// redirected.
1013static bool
1014CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ,
1015 const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1016 BasicBlock *&CommonPred) {
1017
1018 // There must be phis in BB, otherwise BB will be merged into Succ directly
1019 if (BB->phis().empty() || Succ->phis().empty())
1020 return false;
1021
1022 // BB must have predecessors not shared that can be redirected to Succ
1023 if (!BB->hasNPredecessorsOrMore(N: 2))
1024 return false;
1025
1026 if (any_of(Range: BBPreds, P: [](const BasicBlock *Pred) {
1027 return isa<IndirectBrInst>(Val: Pred->getTerminator());
1028 }))
1029 return false;
1030
1031 // Get the single common predecessor of both BB and Succ. Return false
1032 // when there are more than one common predecessors.
1033 for (BasicBlock *SuccPred : predecessors(BB: Succ)) {
1034 if (BBPreds.count(Ptr: SuccPred)) {
1035 if (CommonPred)
1036 return false;
1037 CommonPred = SuccPred;
1038 }
1039 }
1040
1041 return true;
1042}
1043
1044/// Check whether removing \p BB will make the phis in its \p Succ have too
1045/// many incoming entries. This function does not check whether \p BB is
1046/// foldable or not.
1047static bool introduceTooManyPhiEntries(BasicBlock *BB, BasicBlock *Succ) {
1048 // If BB only has one predecessor, then removing it will not introduce more
1049 // incoming edges for phis.
1050 if (BB->hasNPredecessors(N: 1))
1051 return false;
1052 unsigned NumPreds = pred_size(BB);
1053 unsigned NumChangedPhi = 0;
1054 for (auto &Phi : Succ->phis()) {
1055 // If the incoming value is a phi and the phi is defined in BB,
1056 // then removing BB will not increase the total phi entries of the ir.
1057 if (auto *IncomingPhi = dyn_cast<PHINode>(Val: Phi.getIncomingValueForBlock(BB)))
1058 if (IncomingPhi->getParent() == BB)
1059 continue;
1060 // Otherwise, we need to add entries to the phi
1061 NumChangedPhi++;
1062 }
1063 // For every phi that needs to be changed, (NumPreds - 1) new entries will be
1064 // added. If the total increase in phi entries exceeds
1065 // MaxPhiEntriesIncreaseAfterRemovingEmptyBlock, it will be considered as
1066 // introducing too many new phi entries.
1067 return (NumPreds - 1) * NumChangedPhi >
1068 MaxPhiEntriesIncreaseAfterRemovingEmptyBlock;
1069}
1070
1071/// Replace a value flowing from a block to a phi with
1072/// potentially multiple instances of that value flowing from the
1073/// block's predecessors to the phi.
1074///
1075/// \param BB The block with the value flowing into the phi.
1076/// \param BBPreds The predecessors of BB.
1077/// \param PN The phi that we are updating.
1078/// \param CommonPred The common predecessor of BB and PN's BasicBlock
1079static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
1080 const PredBlockVector &BBPreds,
1081 PHINode *PN,
1082 BasicBlock *CommonPred) {
1083 Value *OldVal = PN->removeIncomingValue(BB, DeletePHIIfEmpty: false);
1084 assert(OldVal && "No entry in PHI for Pred BB!");
1085
1086 // Map BBPreds to defined values or nullptr (representing undefined values).
1087 IncomingValueMap IncomingValues;
1088
1089 // We are merging two blocks - BB, and the block containing PN - and
1090 // as a result we need to redirect edges from the predecessors of BB
1091 // to go to the block containing PN, and update PN
1092 // accordingly. Since we allow merging blocks in the case where the
1093 // predecessor and successor blocks both share some predecessors,
1094 // and where some of those common predecessors might have undef
1095 // values flowing into PN, we want to rewrite those values to be
1096 // consistent with the non-undef values.
1097
1098 gatherIncomingValuesToPhi(PN, BBPreds, IncomingValues);
1099
1100 // If this incoming value is one of the PHI nodes in BB, the new entries
1101 // in the PHI node are the entries from the old PHI.
1102 if (isa<PHINode>(Val: OldVal) && cast<PHINode>(Val: OldVal)->getParent() == BB) {
1103 PHINode *OldValPN = cast<PHINode>(Val: OldVal);
1104 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1105 // Note that, since we are merging phi nodes and BB and Succ might
1106 // have common predecessors, we could end up with a phi node with
1107 // identical incoming branches. This will be cleaned up later (and
1108 // will trigger asserts if we try to clean it up now, without also
1109 // simplifying the corresponding conditional branch).
1110 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1111
1112 if (PredBB == CommonPred)
1113 continue;
1114
1115 Value *PredVal = OldValPN->getIncomingValue(i);
1116 Value *Selected =
1117 selectIncomingValueForBlock(OldVal: PredVal, BB: PredBB, IncomingValues);
1118
1119 // And add a new incoming value for this predecessor for the
1120 // newly retargeted branch.
1121 PN->addIncoming(V: Selected, BB: PredBB);
1122 }
1123 if (CommonPred)
1124 PN->addIncoming(V: OldValPN->getIncomingValueForBlock(BB: CommonPred), BB);
1125
1126 } else {
1127 for (BasicBlock *PredBB : BBPreds) {
1128 // Update existing incoming values in PN for this
1129 // predecessor of BB.
1130 if (PredBB == CommonPred)
1131 continue;
1132
1133 Value *Selected =
1134 selectIncomingValueForBlock(OldVal, BB: PredBB, IncomingValues);
1135
1136 // And add a new incoming value for this predecessor for the
1137 // newly retargeted branch.
1138 PN->addIncoming(V: Selected, BB: PredBB);
1139 }
1140 if (CommonPred)
1141 PN->addIncoming(V: OldVal, BB);
1142 }
1143
1144 replaceUndefValuesInPhi(PN, IncomingValues);
1145}
1146
1147bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1148 DomTreeUpdater *DTU) {
1149 assert(BB != &BB->getParent()->getEntryBlock() &&
1150 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1151
1152 // We can't simplify infinite loops.
1153 BasicBlock *Succ = cast<UncondBrInst>(Val: BB->getTerminator())->getSuccessor(i: 0);
1154 if (BB == Succ)
1155 return false;
1156
1157 SmallPtrSet<BasicBlock *, 16> BBPreds(llvm::from_range, predecessors(BB));
1158
1159 // The single common predecessor of BB and Succ when BB cannot be killed
1160 BasicBlock *CommonPred = nullptr;
1161
1162 bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
1163
1164 // Even if we can not fold BB into Succ, we may be able to redirect the
1165 // predecessors of BB to Succ.
1166 bool BBPhisMergeable = BBKillable || CanRedirectPredsOfEmptyBBToSucc(
1167 BB, Succ, BBPreds, CommonPred);
1168
1169 if ((!BBKillable && !BBPhisMergeable) || introduceTooManyPhiEntries(BB, Succ))
1170 return false;
1171
1172 // Check to see if merging these blocks/phis would cause conflicts for any of
1173 // the phi nodes in BB or Succ. If not, we can safely merge.
1174
1175 // Check for cases where Succ has multiple predecessors and a PHI node in BB
1176 // has uses which will not disappear when the PHI nodes are merged. It is
1177 // possible to handle such cases, but difficult: it requires checking whether
1178 // BB dominates Succ, which is non-trivial to calculate in the case where
1179 // Succ has multiple predecessors. Also, it requires checking whether
1180 // constructing the necessary self-referential PHI node doesn't introduce any
1181 // conflicts; this isn't too difficult, but the previous code for doing this
1182 // was incorrect.
1183 //
1184 // Note that if this check finds a live use, BB dominates Succ, so BB is
1185 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1186 // folding the branch isn't profitable in that case anyway.
1187 if (!Succ->getSinglePredecessor()) {
1188 BasicBlock::iterator BBI = BB->begin();
1189 while (isa<PHINode>(Val: *BBI)) {
1190 for (Use &U : BBI->uses()) {
1191 if (PHINode* PN = dyn_cast<PHINode>(Val: U.getUser())) {
1192 if (PN->getIncomingBlock(U) != BB)
1193 return false;
1194 } else {
1195 return false;
1196 }
1197 }
1198 ++BBI;
1199 }
1200 }
1201
1202 if (BBPhisMergeable && CommonPred)
1203 LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()
1204 << " and " << Succ->getName() << " : "
1205 << CommonPred->getName() << "\n");
1206
1207 // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1208 // metadata.
1209 //
1210 // FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1211 // current status (that loop metadata is implemented as metadata attached to
1212 // the branch instruction in the loop latch block). To quote from review
1213 // comments, "the current representation of loop metadata (using a loop latch
1214 // terminator attachment) is known to be fundamentally broken. Loop latches
1215 // are not uniquely associated with loops (both in that a latch can be part of
1216 // multiple loops and a loop may have multiple latches). Loop headers are. The
1217 // solution to this problem is also known: Add support for basic block
1218 // metadata, and attach loop metadata to the loop header."
1219 //
1220 // Why bail out:
1221 // In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1222 // the latch for inner-loop (see reason below), so bail out to prerserve
1223 // inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1224 // to this inner-loop.
1225 // - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1226 // loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1227 // then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1228 // one self-looping basic block, which is contradictory with the assumption.
1229 //
1230 // To illustrate how inner-loop metadata is dropped:
1231 //
1232 // CFG Before
1233 //
1234 // BB is while.cond.exit, attached with loop metdata md2.
1235 // BB->Pred is for.body, attached with loop metadata md1.
1236 //
1237 // entry
1238 // |
1239 // v
1240 // ---> while.cond -------------> while.end
1241 // | |
1242 // | v
1243 // | while.body
1244 // | |
1245 // | v
1246 // | for.body <---- (md1)
1247 // | | |______|
1248 // | v
1249 // | while.cond.exit (md2)
1250 // | |
1251 // |_______|
1252 //
1253 // CFG After
1254 //
1255 // while.cond1 is the merge of while.cond.exit and while.cond above.
1256 // for.body is attached with md2, and md1 is dropped.
1257 // If LoopSimplify runs later (as a part of loop pass), it could create
1258 // dedicated exits for inner-loop (essentially adding `while.cond.exit`
1259 // back), but won't it won't see 'md1' nor restore it for the inner-loop.
1260 //
1261 // entry
1262 // |
1263 // v
1264 // ---> while.cond1 -------------> while.end
1265 // | |
1266 // | v
1267 // | while.body
1268 // | |
1269 // | v
1270 // | for.body <---- (md2)
1271 // |_______| |______|
1272 if (Instruction *TI = BB->getTerminatorOrNull())
1273 if (TI->hasNonDebugLocLoopMetadata())
1274 for (BasicBlock *Pred : predecessors(BB))
1275 if (Instruction *PredTI = Pred->getTerminatorOrNull())
1276 if (PredTI->hasNonDebugLocLoopMetadata())
1277 return false;
1278
1279 if (BBKillable)
1280 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1281 else if (BBPhisMergeable)
1282 LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);
1283
1284 SmallVector<DominatorTree::UpdateType, 32> Updates;
1285
1286 if (DTU) {
1287 // To avoid processing the same predecessor more than once.
1288 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1289 // All predecessors of BB (except the common predecessor) will be moved to
1290 // Succ.
1291 Updates.reserve(N: Updates.size() + 2 * pred_size(BB) + 1);
1292 SmallPtrSet<BasicBlock *, 16> SuccPreds(llvm::from_range,
1293 predecessors(BB: Succ));
1294 for (auto *PredOfBB : predecessors(BB)) {
1295 // Do not modify those common predecessors of BB and Succ
1296 if (!SuccPreds.contains(Ptr: PredOfBB))
1297 if (SeenPreds.insert(Ptr: PredOfBB).second)
1298 Updates.push_back(Elt: {DominatorTree::Insert, PredOfBB, Succ});
1299 }
1300
1301 SeenPreds.clear();
1302
1303 for (auto *PredOfBB : predecessors(BB))
1304 // When BB cannot be killed, do not remove the edge between BB and
1305 // CommonPred.
1306 if (SeenPreds.insert(Ptr: PredOfBB).second && PredOfBB != CommonPred)
1307 Updates.push_back(Elt: {DominatorTree::Delete, PredOfBB, BB});
1308
1309 if (BBKillable)
1310 Updates.push_back(Elt: {DominatorTree::Delete, BB, Succ});
1311 }
1312
1313 if (isa<PHINode>(Val: Succ->begin())) {
1314 // If there is more than one pred of succ, and there are PHI nodes in
1315 // the successor, then we need to add incoming edges for the PHI nodes
1316 //
1317 const PredBlockVector BBPreds(predecessors(BB));
1318
1319 // Loop over all of the PHI nodes in the successor of BB.
1320 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(Val: I); ++I) {
1321 PHINode *PN = cast<PHINode>(Val&: I);
1322 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
1323 }
1324 }
1325
1326 if (Succ->getSinglePredecessor()) {
1327 // BB is the only predecessor of Succ, so Succ will end up with exactly
1328 // the same predecessors BB had.
1329 // Copy over any phi, debug or lifetime instruction.
1330 BB->getTerminator()->eraseFromParent();
1331 Succ->splice(ToIt: Succ->getFirstNonPHIIt(), FromBB: BB);
1332 } else {
1333 while (PHINode *PN = dyn_cast<PHINode>(Val: &BB->front())) {
1334 // We explicitly check for such uses for merging phis.
1335 assert(PN->use_empty() && "There shouldn't be any uses here!");
1336 PN->eraseFromParent();
1337 }
1338 }
1339
1340 // If the unconditional branch we replaced contains non-debug llvm.loop
1341 // metadata, we add the metadata to the branch instructions in the
1342 // predecessors.
1343 if (Instruction *TI = BB->getTerminatorOrNull())
1344 if (TI->hasNonDebugLocLoopMetadata()) {
1345 MDNode *LoopMD = TI->getMetadata(KindID: LLVMContext::MD_loop);
1346 for (BasicBlock *Pred : predecessors(BB))
1347 Pred->getTerminator()->setMetadata(KindID: LLVMContext::MD_loop, Node: LoopMD);
1348 }
1349
1350 if (BBKillable) {
1351 // Everything that jumped to BB now goes to Succ.
1352 BB->replaceAllUsesWith(V: Succ);
1353
1354 if (!Succ->hasName())
1355 Succ->takeName(V: BB);
1356
1357 // Clear the successor list of BB to match updates applying to DTU later.
1358 if (BB->hasTerminator())
1359 BB->back().eraseFromParent();
1360
1361 new UnreachableInst(BB->getContext(), BB);
1362 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1363 "applying corresponding DTU updates.");
1364 } else if (BBPhisMergeable) {
1365 // Everything except CommonPred that jumped to BB now goes to Succ.
1366 BB->replaceUsesWithIf(New: Succ, ShouldReplace: [BBPreds, CommonPred](Use &U) -> bool {
1367 if (Instruction *UseInst = dyn_cast<Instruction>(Val: U.getUser()))
1368 return UseInst->getParent() != CommonPred &&
1369 BBPreds.contains(Ptr: UseInst->getParent());
1370 return false;
1371 });
1372 }
1373
1374 if (DTU)
1375 DTU->applyUpdates(Updates);
1376
1377 if (BBKillable)
1378 DeleteDeadBlock(BB, DTU);
1379
1380 return true;
1381}
1382
1383static bool
1384EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,
1385 SmallPtrSetImpl<PHINode *> &ToRemove) {
1386 // This implementation doesn't currently consider undef operands
1387 // specially. Theoretically, two phis which are identical except for
1388 // one having an undef where the other doesn't could be collapsed.
1389
1390 bool Changed = false;
1391
1392 // Examine each PHI.
1393 // Note that increment of I must *NOT* be in the iteration_expression, since
1394 // we don't want to immediately advance when we restart from the beginning.
1395 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(Val&: I);) {
1396 ++I;
1397 // Is there an identical PHI node in this basic block?
1398 // Note that we only look in the upper square's triangle,
1399 // we already checked that the lower triangle PHI's aren't identical.
1400 for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(Val&: J); ++J) {
1401 if (ToRemove.contains(Ptr: DuplicatePN))
1402 continue;
1403 if (!DuplicatePN->isIdenticalToWhenDefined(I: PN))
1404 continue;
1405 // A duplicate. Replace this PHI with the base PHI.
1406 ++NumPHICSEs;
1407 DuplicatePN->replaceAllUsesWith(V: PN);
1408 ToRemove.insert(Ptr: DuplicatePN);
1409 Changed = true;
1410
1411 // The RAUW can change PHIs that we already visited.
1412 I = BB->begin();
1413 break; // Start over from the beginning.
1414 }
1415 }
1416 return Changed;
1417}
1418
1419static bool
1420EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,
1421 SmallPtrSetImpl<PHINode *> &ToRemove) {
1422 // This implementation doesn't currently consider undef operands
1423 // specially. Theoretically, two phis which are identical except for
1424 // one having an undef where the other doesn't could be collapsed.
1425
1426 struct PHIDenseMapInfo {
1427 // WARNING: this logic must be kept in sync with
1428 // Instruction::isIdenticalToWhenDefined()!
1429 static unsigned getHashValueImpl(PHINode *PN) {
1430 // Compute a hash value on the operands. Instcombine will likely have
1431 // sorted them, which helps expose duplicates, but we have to check all
1432 // the operands to be safe in case instcombine hasn't run.
1433 return static_cast<unsigned>(
1434 hash_combine(args: hash_combine_range(R: PN->operand_values()),
1435 args: hash_combine_range(R: PN->blocks())));
1436 }
1437
1438 static unsigned getHashValue(PHINode *PN) {
1439#ifndef NDEBUG
1440 // If -phicse-debug-hash was specified, return a constant -- this
1441 // will force all hashing to collide, so we'll exhaustively search
1442 // the table for a match, and the assertion in isEqual will fire if
1443 // there's a bug causing equal keys to hash differently.
1444 if (PHICSEDebugHash)
1445 return 0;
1446#endif
1447 return getHashValueImpl(PN);
1448 }
1449
1450 static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1451 return LHS->isIdenticalTo(I: RHS);
1452 }
1453
1454 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1455 // These comparisons are nontrivial, so assert that equality implies
1456 // hash equality (DenseMap demands this as an invariant).
1457 bool Result = isEqualImpl(LHS, RHS);
1458 assert(!Result || getHashValueImpl(LHS) == getHashValueImpl(RHS));
1459 return Result;
1460 }
1461 };
1462
1463 // Set of unique PHINodes.
1464 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1465 PHISet.reserve(Size: 4 * PHICSENumPHISmallSize);
1466
1467 // Examine each PHI.
1468 bool Changed = false;
1469 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(Val: I++);) {
1470 if (ToRemove.contains(Ptr: PN))
1471 continue;
1472 auto Inserted = PHISet.insert(V: PN);
1473 if (!Inserted.second) {
1474 // A duplicate. Replace this PHI with its duplicate.
1475 ++NumPHICSEs;
1476 PN->replaceAllUsesWith(V: *Inserted.first);
1477 ToRemove.insert(Ptr: PN);
1478 Changed = true;
1479
1480 // The RAUW can change PHIs that we already visited. Start over from the
1481 // beginning.
1482 PHISet.clear();
1483 I = BB->begin();
1484 }
1485 }
1486
1487 return Changed;
1488}
1489
1490bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB,
1491 SmallPtrSetImpl<PHINode *> &ToRemove) {
1492 if (
1493#ifndef NDEBUG
1494 !PHICSEDebugHash &&
1495#endif
1496 hasNItemsOrLess(C: BB->phis(), N: PHICSENumPHISmallSize))
1497 return EliminateDuplicatePHINodesNaiveImpl(BB, ToRemove);
1498 return EliminateDuplicatePHINodesSetBasedImpl(BB, ToRemove);
1499}
1500
1501bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1502 SmallPtrSet<PHINode *, 8> ToRemove;
1503 bool Changed = EliminateDuplicatePHINodes(BB, ToRemove);
1504 for (PHINode *PN : ToRemove)
1505 PN->eraseFromParent();
1506 return Changed;
1507}
1508
1509Align llvm::tryEnforceAlignment(Value *V, Align PrefAlign,
1510 const DataLayout &DL) {
1511 V = V->stripPointerCasts();
1512
1513 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
1514 // TODO: Ideally, this function would not be called if PrefAlign is smaller
1515 // than the current alignment, as the known bits calculation should have
1516 // already taken it into account. However, this is not always the case,
1517 // as computeKnownBits() has a depth limit, while stripPointerCasts()
1518 // doesn't.
1519 Align CurrentAlign = AI->getAlign();
1520 if (PrefAlign <= CurrentAlign)
1521 return CurrentAlign;
1522
1523 // If the preferred alignment is greater than the natural stack alignment
1524 // then don't round up. This avoids dynamic stack realignment.
1525 MaybeAlign StackAlign = DL.getStackAlignment();
1526 if (StackAlign && PrefAlign > *StackAlign)
1527 return CurrentAlign;
1528 AI->setAlignment(PrefAlign);
1529 return PrefAlign;
1530 }
1531
1532 if (auto *GV = dyn_cast<GlobalVariable>(Val: V)) {
1533 // TODO: as above, this shouldn't be necessary.
1534 Align CurrentAlign = GV->getPointerAlignment(DL);
1535 if (PrefAlign <= CurrentAlign)
1536 return CurrentAlign;
1537
1538 // If there is a large requested alignment and we can, bump up the alignment
1539 // of the global. If the memory we set aside for the global may not be the
1540 // memory used by the final program then it is impossible for us to reliably
1541 // enforce the preferred alignment.
1542 if (!GV->canIncreaseAlignment())
1543 return CurrentAlign;
1544
1545 if (GV->isThreadLocal()) {
1546 unsigned MaxTLSAlign = GV->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1547 if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))
1548 PrefAlign = Align(MaxTLSAlign);
1549 }
1550
1551 GV->setAlignment(PrefAlign);
1552 return PrefAlign;
1553 }
1554
1555 return Align(1);
1556}
1557
1558Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
1559 const DataLayout &DL,
1560 const Instruction *CxtI,
1561 AssumptionCache *AC,
1562 const DominatorTree *DT) {
1563 assert(V->getType()->isPointerTy() &&
1564 "getOrEnforceKnownAlignment expects a pointer!");
1565
1566 KnownBits Known = computeKnownBits(V, DL, AC, CxtI, DT);
1567 unsigned TrailZ = Known.countMinTrailingZeros();
1568
1569 // Avoid trouble with ridiculously large TrailZ values, such as
1570 // those computed from a null pointer.
1571 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1572 TrailZ = std::min(a: TrailZ, b: +Value::MaxAlignmentExponent);
1573
1574 Align Alignment = Align(1ull << std::min(a: Known.getBitWidth() - 1, b: TrailZ));
1575
1576 if (PrefAlign && *PrefAlign > Alignment)
1577 Alignment = std::max(a: Alignment, b: tryEnforceAlignment(V, PrefAlign: *PrefAlign, DL));
1578
1579 // We don't need to make any adjustment.
1580 return Alignment;
1581}
1582
1583///===---------------------------------------------------------------------===//
1584/// Dbg Intrinsic utilities
1585///
1586
1587/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1588static bool PhiHasDebugValue(DILocalVariable *DIVar,
1589 DIExpression *DIExpr,
1590 PHINode *APN) {
1591 // Since we can't guarantee that the original dbg.declare intrinsic
1592 // is removed by LowerDbgDeclare(), we need to make sure that we are
1593 // not inserting the same dbg.value intrinsic over and over.
1594 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
1595 findDbgValues(V: APN, DbgVariableRecords);
1596 for (DbgVariableRecord *DVR : DbgVariableRecords) {
1597 assert(is_contained(DVR->location_ops(), APN));
1598 if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1599 return true;
1600 }
1601 return false;
1602}
1603
1604/// Check if the alloc size of \p ValTy is large enough to cover the variable
1605/// (or fragment of the variable) described by \p DII.
1606///
1607/// This is primarily intended as a helper for the different
1608/// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
1609/// describes an alloca'd variable, so we need to use the alloc size of the
1610/// value when doing the comparison. E.g. an i1 value will be identified as
1611/// covering an n-bit fragment, if the store size of i1 is at least n bits.
1612static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR) {
1613 const DataLayout &DL = DVR->getModule()->getDataLayout();
1614 TypeSize ValueSize = DL.getTypeAllocSizeInBits(Ty: ValTy);
1615 if (std::optional<uint64_t> FragmentSize =
1616 DVR->getExpression()->getActiveBits(Var: DVR->getVariable()))
1617 return TypeSize::isKnownGE(LHS: ValueSize, RHS: TypeSize::getFixed(ExactSize: *FragmentSize));
1618
1619 // We can't always calculate the size of the DI variable (e.g. if it is a
1620 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1621 // instead.
1622 if (DVR->isAddressOfVariable()) {
1623 // DVR should have exactly 1 location when it is an address.
1624 assert(DVR->getNumVariableLocationOps() == 1 &&
1625 "address of variable must have exactly 1 location operand.");
1626 if (auto *AI =
1627 dyn_cast_or_null<AllocaInst>(Val: DVR->getVariableLocationOp(OpIdx: 0))) {
1628 if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1629 return TypeSize::isKnownGE(LHS: ValueSize, RHS: *FragmentSize);
1630 }
1631 }
1632 }
1633 // Could not determine size of variable. Conservatively return false.
1634 return false;
1635}
1636
1637static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV,
1638 DILocalVariable *DIVar,
1639 DIExpression *DIExpr,
1640 const DebugLoc &NewLoc,
1641 BasicBlock::iterator Instr) {
1642 ValueAsMetadata *DVAM = ValueAsMetadata::get(V: DV);
1643 DbgVariableRecord *DVRec =
1644 new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1645 Instr->getParent()->insertDbgRecordBefore(DR: DVRec, Here: Instr);
1646}
1647
1648static DIExpression *dropInitialDeref(const DIExpression *DIExpr) {
1649 int NumEltDropped = DIExpr->getElements()[0] == dwarf::DW_OP_LLVM_arg ? 3 : 1;
1650 return DIExpression::get(Context&: DIExpr->getContext(),
1651 Elements: DIExpr->getElements().drop_front(N: NumEltDropped));
1652}
1653
1654void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
1655 StoreInst *SI, DIBuilder &Builder) {
1656 assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
1657 auto *DIVar = DVR->getVariable();
1658 assert(DIVar && "Missing variable");
1659 auto *DIExpr = DVR->getExpression();
1660 Value *DV = SI->getValueOperand();
1661
1662 if (isa<UndefValue>(Val: DV) && !isa<PoisonValue>(Val: DV))
1663 return;
1664
1665 DebugLoc NewLoc = getDebugValueLoc(DVR);
1666
1667 // If the alloca describes the variable itself, i.e. the expression in the
1668 // dbg.declare doesn't start with a dereference, we can perform the
1669 // conversion if the value covers the entire fragment of DII.
1670 // If the alloca describes the *address* of DIVar, i.e. DIExpr is
1671 // *just* a DW_OP_deref, we use DV as is for the dbg.value.
1672 // We conservatively ignore other dereferences, because the following two are
1673 // not equivalent:
1674 // dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1675 // dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1676 // The former is adding 2 to the address of the variable, whereas the latter
1677 // is adding 2 to the value of the variable. As such, we insist on just a
1678 // deref expression.
1679 bool CanConvert =
1680 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1681 valueCoversEntireFragment(ValTy: DV->getType(), DVR));
1682 if (CanConvert) {
1683 insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1684 Instr: SI->getIterator());
1685 return;
1686 }
1687
1688 // FIXME: If storing to a part of the variable described by the dbg.declare,
1689 // then we want to insert a dbg.value for the corresponding fragment.
1690 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR
1691 << '\n');
1692
1693 // For now, when there is a store to parts of the variable (but we do not
1694 // know which part) we insert an dbg.value intrinsic to indicate that we
1695 // know nothing about the variable's content.
1696 DV = PoisonValue::get(T: DV->getType());
1697 ValueAsMetadata *DVAM = ValueAsMetadata::get(V: DV);
1698 DbgVariableRecord *NewDVR =
1699 new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1700 SI->getParent()->insertDbgRecordBefore(DR: NewDVR, Here: SI->getIterator());
1701}
1702
1703void llvm::InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
1704 DIBuilder &Builder) {
1705 auto *DIVar = DVR->getVariable();
1706 assert(DIVar && "Missing variable");
1707 auto *DIExpr = DVR->getExpression();
1708 DIExpr = dropInitialDeref(DIExpr);
1709 Value *DV = SI->getValueOperand();
1710
1711 DebugLoc NewLoc = getDebugValueLoc(DVR);
1712
1713 insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1714 Instr: SI->getIterator());
1715}
1716
1717void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, LoadInst *LI,
1718 DIBuilder &Builder) {
1719 auto *DIVar = DVR->getVariable();
1720 auto *DIExpr = DVR->getExpression();
1721 assert(DIVar && "Missing variable");
1722
1723 if (!valueCoversEntireFragment(ValTy: LI->getType(), DVR)) {
1724 // FIXME: If only referring to a part of the variable described by the
1725 // dbg.declare, then we want to insert a DbgVariableRecord for the
1726 // corresponding fragment.
1727 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1728 << *DVR << '\n');
1729 return;
1730 }
1731
1732 DebugLoc NewLoc = getDebugValueLoc(DVR);
1733
1734 // We are now tracking the loaded value instead of the address. In the
1735 // future if multi-location support is added to the IR, it might be
1736 // preferable to keep tracking both the loaded value and the original
1737 // address in case the alloca can not be elided.
1738
1739 // Create a DbgVariableRecord directly and insert.
1740 ValueAsMetadata *LIVAM = ValueAsMetadata::get(V: LI);
1741 DbgVariableRecord *DV =
1742 new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
1743 LI->getParent()->insertDbgRecordAfter(DR: DV, I: LI);
1744}
1745
1746/// Determine whether this debug variable is a not a basic type.
1747/// We strip through DIDerivedType modifiers (typedefs, const, etc.)
1748/// to find the underlying type to decide if it seems perhaps worthwhile to
1749/// do LowerDbgDeclare.
1750static bool isCompositeType(DbgVariableRecord *DVR) {
1751 DIType *Ty = DVR->getVariable()->getType();
1752 if (Ty == nullptr)
1753 return true;
1754 // Strip through modifier types to find the underlying type.
1755 while (auto *DTy = dyn_cast<DIDerivedType>(Val: Ty)) {
1756 switch (DTy->getTag()) {
1757 case dwarf::DW_TAG_pointer_type:
1758 case dwarf::DW_TAG_reference_type:
1759 case dwarf::DW_TAG_rvalue_reference_type:
1760 case dwarf::DW_TAG_ptr_to_member_type:
1761 case dwarf::DW_TAG_LLVM_ptrauth_type:
1762 return false;
1763 case dwarf::DW_TAG_typedef:
1764 case dwarf::DW_TAG_const_type:
1765 case dwarf::DW_TAG_volatile_type:
1766 case dwarf::DW_TAG_restrict_type:
1767 case dwarf::DW_TAG_atomic_type:
1768 case dwarf::DW_TAG_immutable_type:
1769 Ty = DTy->getBaseType();
1770 continue;
1771 default:
1772 break;
1773 }
1774 break;
1775 }
1776 return !isa<DIBasicType>(Val: Ty);
1777}
1778
1779void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, PHINode *APN,
1780 DIBuilder &Builder) {
1781 auto *DIVar = DVR->getVariable();
1782 auto *DIExpr = DVR->getExpression();
1783 assert(DIVar && "Missing variable");
1784
1785 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1786 return;
1787
1788 if (!valueCoversEntireFragment(ValTy: APN->getType(), DVR)) {
1789 // FIXME: If only referring to a part of the variable described by the
1790 // dbg.declare, then we want to insert a DbgVariableRecord for the
1791 // corresponding fragment.
1792 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1793 << *DVR << '\n');
1794 return;
1795 }
1796
1797 BasicBlock *BB = APN->getParent();
1798 auto InsertionPt = BB->getFirstInsertionPt();
1799
1800 DebugLoc NewLoc = getDebugValueLoc(DVR);
1801
1802 // The block may be a catchswitch block, which does not have a valid
1803 // insertion point.
1804 // FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
1805 if (InsertionPt != BB->end()) {
1806 insertDbgValueOrDbgVariableRecord(Builder, DV: APN, DIVar, DIExpr, NewLoc,
1807 Instr: InsertionPt);
1808 }
1809}
1810
1811/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1812/// of llvm.dbg.value intrinsics.
1813bool llvm::LowerDbgDeclare(Function &F) {
1814 bool Changed = false;
1815 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1816 SmallVector<DbgDeclareInst *, 4> Dbgs;
1817 SmallVector<DbgVariableRecord *> DVRs;
1818 for (auto &FI : F) {
1819 for (Instruction &BI : FI) {
1820 if (auto *DDI = dyn_cast<DbgDeclareInst>(Val: &BI))
1821 Dbgs.push_back(Elt: DDI);
1822 for (DbgVariableRecord &DVR : filterDbgVars(R: BI.getDbgRecordRange())) {
1823 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
1824 DVRs.push_back(Elt: &DVR);
1825 }
1826 }
1827 }
1828
1829 if (Dbgs.empty() && DVRs.empty())
1830 return Changed;
1831
1832 auto LowerOne = [&](DbgVariableRecord *DDI) {
1833 AllocaInst *AI =
1834 dyn_cast_or_null<AllocaInst>(Val: DDI->getVariableLocationOp(OpIdx: 0));
1835 // If this is an alloca for a scalar variable, insert a dbg.value
1836 // at each load and store to the alloca and erase the dbg.declare.
1837 // The dbg.values allow tracking a variable even if it is not
1838 // stored on the stack, while the dbg.declare can only describe
1839 // the stack slot (and at a lexical-scope granularity). Later
1840 // passes will attempt to elide the stack slot.
1841 // Skip VLAs (dynamic allocas) and composite types (arrays/structs) since
1842 // they can't be represented as a single dbg.value.
1843 if (!AI || !isa<Constant>(Val: AI->getArraySize()) || isCompositeType(DVR: DDI))
1844 return;
1845
1846 // A volatile load/store means that the alloca can't be elided anyway.
1847 // Just look at direct uses however, and ignore any other instructions.
1848 if (llvm::any_of(Range: AI->users(), P: [](User *U) -> bool {
1849 if (LoadInst *LI = dyn_cast<LoadInst>(Val: U))
1850 return LI->isVolatile();
1851 if (StoreInst *SI = dyn_cast<StoreInst>(Val: U))
1852 return SI->isVolatile();
1853 return false;
1854 }))
1855 return;
1856
1857 SmallVector<const Value *, 8> WorkList;
1858 WorkList.push_back(Elt: AI);
1859 while (!WorkList.empty()) {
1860 const Value *V = WorkList.pop_back_val();
1861 for (const auto &AIUse : V->uses()) {
1862 User *U = AIUse.getUser();
1863 if (StoreInst *SI = dyn_cast<StoreInst>(Val: U)) {
1864 if (AIUse.getOperandNo() == 1)
1865 ConvertDebugDeclareToDebugValue(DVR: DDI, SI, Builder&: DIB);
1866 } else if (LoadInst *LI = dyn_cast<LoadInst>(Val: U)) {
1867 ConvertDebugDeclareToDebugValue(DVR: DDI, LI, Builder&: DIB);
1868 } else if (CallInst *CI = dyn_cast<CallInst>(Val: U)) {
1869 // This is a call by-value or some other instruction that takes a
1870 // pointer to the variable. Insert a *value* intrinsic that describes
1871 // the variable by dereferencing the alloca.
1872 if (!CI->isLifetimeStartOrEnd()) {
1873 DebugLoc NewLoc = getDebugValueLoc(DVR: DDI);
1874 auto *DerefExpr =
1875 DIExpression::append(Expr: DDI->getExpression(), Ops: dwarf::DW_OP_deref);
1876 insertDbgValueOrDbgVariableRecord(Builder&: DIB, DV: AI, DIVar: DDI->getVariable(),
1877 DIExpr: DerefExpr, NewLoc,
1878 Instr: CI->getIterator());
1879 }
1880 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(Val: U)) {
1881 if (BI->getType()->isPointerTy())
1882 WorkList.push_back(Elt: BI);
1883 }
1884 }
1885 }
1886 DDI->eraseFromParent();
1887 Changed = true;
1888 };
1889
1890 for_each(Range&: DVRs, F: LowerOne);
1891
1892 if (Changed)
1893 for (BasicBlock &BB : F)
1894 RemoveRedundantDbgInstrs(BB: &BB);
1895
1896 return Changed;
1897}
1898
1899/// Propagate dbg.value records through the newly inserted PHIs.
1900void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1901 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1902 assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");
1903 if (InsertedPHIs.size() == 0)
1904 return;
1905
1906 // Map existing PHI nodes to their DbgVariableRecords.
1907 DenseMap<Value *, DbgVariableRecord *> DbgValueMap;
1908 for (auto &I : *BB) {
1909 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) {
1910 for (Value *V : DVR.location_ops())
1911 if (auto *Loc = dyn_cast_or_null<PHINode>(Val: V))
1912 DbgValueMap.insert(KV: {Loc, &DVR});
1913 }
1914 }
1915 if (DbgValueMap.size() == 0)
1916 return;
1917
1918 // Map a pair of the destination BB and old DbgVariableRecord to the new
1919 // DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
1920 // more than one of the inserted PHIs in the same destination BB, we can
1921 // update the same DbgVariableRecord with all the new PHIs instead of creating
1922 // one copy for each.
1923 MapVector<std::pair<BasicBlock *, DbgVariableRecord *>, DbgVariableRecord *>
1924 NewDbgValueMap;
1925 // Then iterate through the new PHIs and look to see if they use one of the
1926 // previously mapped PHIs. If so, create a new DbgVariableRecord that will
1927 // propagate the info through the new PHI. If we use more than one new PHI in
1928 // a single destination BB with the same old dbg.value, merge the updates so
1929 // that we get a single new DbgVariableRecord with all the new PHIs.
1930 for (auto PHI : InsertedPHIs) {
1931 BasicBlock *Parent = PHI->getParent();
1932 // Avoid inserting a debug-info record into an EH block.
1933 if (Parent->getFirstNonPHIIt()->isEHPad())
1934 continue;
1935 for (auto VI : PHI->operand_values()) {
1936 auto V = DbgValueMap.find(Val: VI);
1937 if (V != DbgValueMap.end()) {
1938 DbgVariableRecord *DbgII = cast<DbgVariableRecord>(Val: V->second);
1939 auto NewDI = NewDbgValueMap.find(Key: {Parent, DbgII});
1940 if (NewDI == NewDbgValueMap.end()) {
1941 DbgVariableRecord *NewDbgII = DbgII->clone();
1942 NewDI = NewDbgValueMap.insert(KV: {{Parent, DbgII}, NewDbgII}).first;
1943 }
1944 DbgVariableRecord *NewDbgII = NewDI->second;
1945 // If PHI contains VI as an operand more than once, we may
1946 // replaced it in NewDbgII; confirm that it is present.
1947 if (is_contained(Range: NewDbgII->location_ops(), Element: VI))
1948 NewDbgII->replaceVariableLocationOp(OldValue: VI, NewValue: PHI);
1949 }
1950 }
1951 }
1952 // Insert the new DbgVariableRecords into their destination blocks.
1953 for (auto DI : NewDbgValueMap) {
1954 BasicBlock *Parent = DI.first.first;
1955 DbgVariableRecord *NewDbgII = DI.second;
1956 auto InsertionPt = Parent->getFirstInsertionPt();
1957 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1958
1959 Parent->insertDbgRecordBefore(DR: NewDbgII, Here: InsertionPt);
1960 }
1961}
1962
1963bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1964 DIBuilder &Builder, uint8_t DIExprFlags,
1965 int Offset) {
1966 TinyPtrVector<DbgVariableRecord *> DVRDeclares = findDVRDeclares(V: Address);
1967
1968 auto ReplaceOne = [&](DbgVariableRecord *DII) {
1969 assert(DII->getVariable() && "Missing variable");
1970 auto *DIExpr = DII->getExpression();
1971 DIExpr = DIExpression::prepend(Expr: DIExpr, Flags: DIExprFlags, Offset);
1972 DII->setExpression(DIExpr);
1973 DII->replaceVariableLocationOp(OldValue: Address, NewValue: NewAddress);
1974 };
1975
1976 for_each(Range&: DVRDeclares, F: ReplaceOne);
1977
1978 return !DVRDeclares.empty();
1979}
1980
1981static void updateOneDbgValueForAlloca(const DebugLoc &Loc,
1982 DILocalVariable *DIVar,
1983 DIExpression *DIExpr, Value *NewAddress,
1984 DbgVariableRecord *DVR,
1985 DIBuilder &Builder, int Offset) {
1986 assert(DIVar && "Missing variable");
1987
1988 // This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
1989 // should do with the alloca pointer is dereference it. Otherwise we don't
1990 // know how to handle it and give up.
1991 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1992 DIExpr->getElement(I: 0) != dwarf::DW_OP_deref)
1993 return;
1994
1995 // Insert the offset before the first deref.
1996 if (Offset)
1997 DIExpr = DIExpression::prepend(Expr: DIExpr, Flags: 0, Offset);
1998
1999 DVR->setExpression(DIExpr);
2000 DVR->replaceVariableLocationOp(OpIdx: 0u, NewValue: NewAddress);
2001}
2002
2003void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
2004 DIBuilder &Builder, int Offset) {
2005 SmallVector<DbgVariableRecord *, 1> DPUsers;
2006 findDbgValues(V: AI, DbgVariableRecords&: DPUsers);
2007
2008 // Replace any DbgVariableRecords that use this alloca.
2009 for (DbgVariableRecord *DVR : DPUsers)
2010 updateOneDbgValueForAlloca(Loc: DVR->getDebugLoc(), DIVar: DVR->getVariable(),
2011 DIExpr: DVR->getExpression(), NewAddress: NewAllocaAddress, DVR,
2012 Builder, Offset);
2013}
2014
2015void llvm::salvageDebugInfo(Instruction &I) {
2016 SmallVector<DbgVariableRecord *, 1> DbgRecords;
2017 findDbgUsers(V: &I, DbgVariableRecords&: DbgRecords);
2018 salvageDebugInfoForDbgValues(I, DbgRecords);
2019}
2020
2021/// Salvage the address of \p Assign, which the caller has checked is \p I. An
2022/// address we cannot salvage stays as it is rather than stopping the caller,
2023/// which counts the record as processed either way and goes on to salvage its
2024/// variable location.
2025static void salvageDbgAssignAddress(Instruction &I, DbgVariableRecord &Assign) {
2026 assert(Assign.isDbgAssign() && Assign.getAddress() == &I &&
2027 "dbg.assign must use salvaged instruction as its address");
2028 assert(!Assign.getAddressExpression()->getFragmentInfo().has_value() &&
2029 "address-expression shouldn't have fragment info");
2030
2031 // The address component of a dbg.assign cannot be variadic.
2032 uint64_t CurrentLocOps = 0;
2033 SmallVector<Value *, 4> AdditionalValues;
2034 SmallVector<uint64_t, 16> Ops;
2035 Value *NewAddress =
2036 salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2037
2038 // Keep an address we cannot salvage. If I is deleted, its remaining metadata
2039 // use is replaced with poison.
2040 if (!NewAddress)
2041 return;
2042
2043 DIExpression *SalvagedExpr = DIExpression::appendOpsToArg(
2044 Expr: Assign.getAddressExpression(), Ops, ArgNo: 0, /*StackValue=*/false);
2045 assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2046 "address-expression shouldn't have fragment info");
2047
2048 SalvagedExpr = SalvagedExpr->foldConstantMath();
2049
2050 // Salvage succeeds if no additional values are required.
2051 if (AdditionalValues.empty()) {
2052 Assign.setAddress(NewAddress);
2053 Assign.setAddressExpression(SalvagedExpr);
2054 } else {
2055 Assign.setKillAddress();
2056 }
2057}
2058
2059/// Rewrite \p DVR's variable location in terms of \p I's operands. Return false
2060/// and leave the record alone when the instruction cannot be salvaged. Return
2061/// true once it can, including when the location ends up killed.
2062static bool salvageDbgVariableLocation(Instruction &I, DbgVariableRecord &DVR) {
2063 // These are arbitrary chosen limits on the maximum number of values and the
2064 // maximum size of a debug expression we can salvage up to, used for
2065 // performance reasons.
2066 const unsigned MaxDebugArgs = 16;
2067 const unsigned MaxExpressionSize = 128;
2068
2069 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
2070 // are implicitly pointing out the value as a DWARF memory location
2071 // description.
2072 const bool StackValue = !DVR.isAddressOfVariable();
2073 auto LocationOps = DVR.location_ops();
2074 assert(is_contained(LocationOps, &I) &&
2075 "DbgVariableRecord must use salvaged instruction as its location");
2076 SmallVector<Value *, 4> AdditionalValues;
2077 // 'I' may appear more than once in DVR's location ops, and each use of 'I'
2078 // must be updated in the DIExpression and potentially have additional
2079 // values added; thus we call salvageDebugInfoImpl for each 'I' instance in
2080 // LocationOps.
2081 Value *Replacement = nullptr;
2082 DIExpression *SalvagedExpr = DVR.getExpression();
2083 auto LocIt = find(Range&: LocationOps, Val: &I);
2084 while (SalvagedExpr && LocIt != LocationOps.end()) {
2085 SmallVector<uint64_t, 16> Ops;
2086 unsigned LocationIndex = std::distance(first: LocationOps.begin(), last: LocIt);
2087 uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2088 Replacement = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2089 if (!Replacement)
2090 break;
2091 SalvagedExpr = DIExpression::appendOpsToArg(Expr: SalvagedExpr, Ops,
2092 ArgNo: LocationIndex, StackValue);
2093 LocIt = std::find(first: ++LocIt, last: LocationOps.end(), val: &I);
2094 }
2095 // The failure conditions in salvageDebugInfoImpl do not depend on
2096 // CurrentLocOps, so failure can only occur on the first occurrence.
2097 if (!Replacement)
2098 return false;
2099
2100 SalvagedExpr = SalvagedExpr->foldConstantMath();
2101 DVR.replaceVariableLocationOp(OldValue: &I, NewValue: Replacement);
2102 const bool FitsExpressionLimit =
2103 SalvagedExpr->getNumElements() <= MaxExpressionSize;
2104 if (AdditionalValues.empty() && FitsExpressionLimit) {
2105 DVR.setExpression(SalvagedExpr);
2106 } else if (!DVR.isAddressOfVariable() && FitsExpressionLimit &&
2107 DVR.getNumVariableLocationOps() + AdditionalValues.size() <=
2108 MaxDebugArgs) {
2109 DVR.addVariableLocationOps(NewValues: AdditionalValues, NewExpr: SalvagedExpr);
2110 } else {
2111 // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
2112 // currently only valid for stack value expressions.
2113 // Also do not salvage if the resulting DIArgList would contain an
2114 // unreasonably large number of values.
2115 DVR.setKillLocation();
2116 }
2117 LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');
2118 return true;
2119}
2120
2121void llvm::salvageDebugInfoForDbgValues(
2122 Instruction &I, ArrayRef<DbgVariableRecord *> DbgRecords) {
2123 bool ProcessedAnyUse = false;
2124
2125 for (auto *DVR : DbgRecords) {
2126 // replaceVariableLocationOp also updates a matching dbg.assign address, so
2127 // salvage the address before changing the variable location.
2128 if (DVR->isDbgAssign()) {
2129 if (DVR->getAddress() == &I) {
2130 salvageDbgAssignAddress(I, Assign&: *DVR);
2131 ProcessedAnyUse = true;
2132 }
2133 if (DVR->getValue() != &I)
2134 continue;
2135 }
2136 if (!salvageDbgVariableLocation(I, DVR&: *DVR))
2137 break;
2138 ProcessedAnyUse = true;
2139 }
2140
2141 if (ProcessedAnyUse)
2142 return;
2143
2144 for (auto *DVR : DbgRecords)
2145 DVR->setKillLocation();
2146}
2147
2148Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
2149 uint64_t CurrentLocOps,
2150 SmallVectorImpl<uint64_t> &Opcodes,
2151 SmallVectorImpl<Value *> &AdditionalValues) {
2152 unsigned BitWidth = DL.getIndexSizeInBits(AS: GEP->getPointerAddressSpace());
2153 // Rewrite a GEP into a DIExpression.
2154 SmallMapVector<Value *, APInt, 4> VariableOffsets;
2155 APInt ConstantOffset(BitWidth, 0);
2156 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
2157 return nullptr;
2158 if (!VariableOffsets.empty() && !CurrentLocOps) {
2159 Opcodes.insert(I: Opcodes.begin(), IL: {dwarf::DW_OP_LLVM_arg, 0});
2160 CurrentLocOps = 1;
2161 }
2162 for (const auto &Offset : VariableOffsets) {
2163 AdditionalValues.push_back(Elt: Offset.first);
2164 assert(Offset.second.isStrictlyPositive() &&
2165 "Expected strictly positive multiplier for offset.");
2166 Opcodes.append(IL: {dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2167 Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2168 dwarf::DW_OP_plus});
2169 }
2170 DIExpression::appendOffset(Ops&: Opcodes, Offset: ConstantOffset.getSExtValue());
2171 return GEP->getOperand(i_nocapture: 0);
2172}
2173
2174uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
2175 switch (Opcode) {
2176 case Instruction::Add:
2177 return dwarf::DW_OP_plus;
2178 case Instruction::Sub:
2179 return dwarf::DW_OP_minus;
2180 case Instruction::Mul:
2181 return dwarf::DW_OP_mul;
2182 case Instruction::SDiv:
2183 return dwarf::DW_OP_div;
2184 case Instruction::SRem:
2185 return dwarf::DW_OP_mod;
2186 case Instruction::Or:
2187 return dwarf::DW_OP_or;
2188 case Instruction::And:
2189 return dwarf::DW_OP_and;
2190 case Instruction::Xor:
2191 return dwarf::DW_OP_xor;
2192 case Instruction::Shl:
2193 return dwarf::DW_OP_shl;
2194 case Instruction::LShr:
2195 return dwarf::DW_OP_shr;
2196 case Instruction::AShr:
2197 return dwarf::DW_OP_shra;
2198 default:
2199 // TODO: Salvage from each kind of binop we know about.
2200 return 0;
2201 }
2202}
2203
2204static void handleSSAValueOperands(uint64_t CurrentLocOps,
2205 SmallVectorImpl<uint64_t> &Opcodes,
2206 SmallVectorImpl<Value *> &AdditionalValues,
2207 Instruction *I) {
2208 if (!CurrentLocOps) {
2209 Opcodes.append(IL: {dwarf::DW_OP_LLVM_arg, 0});
2210 CurrentLocOps = 1;
2211 }
2212 Opcodes.append(IL: {dwarf::DW_OP_LLVM_arg, CurrentLocOps});
2213 AdditionalValues.push_back(Elt: I->getOperand(i: 1));
2214}
2215
2216Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
2217 SmallVectorImpl<uint64_t> &Opcodes,
2218 SmallVectorImpl<Value *> &AdditionalValues) {
2219 // Handle binary operations with constant integer operands as a special case.
2220 auto *ConstInt = dyn_cast<ConstantInt>(Val: BI->getOperand(i_nocapture: 1));
2221 // Values wider than 64 bits cannot be represented within a DIExpression.
2222 if (ConstInt && ConstInt->getBitWidth() > 64)
2223 return nullptr;
2224
2225 Instruction::BinaryOps BinOpcode = BI->getOpcode();
2226 // Push any Constant Int operand onto the expression stack.
2227 if (ConstInt) {
2228 uint64_t Val = ConstInt->getSExtValue();
2229 // Add or Sub Instructions with a constant operand can potentially be
2230 // simplified.
2231 if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2232 uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2233 DIExpression::appendOffset(Ops&: Opcodes, Offset);
2234 return BI->getOperand(i_nocapture: 0);
2235 }
2236 Opcodes.append(IL: {dwarf::DW_OP_constu, Val});
2237 } else {
2238 handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, I: BI);
2239 }
2240
2241 // Add salvaged binary operator to expression stack, if it has a valid
2242 // representation in a DIExpression.
2243 uint64_t DwarfBinOp = getDwarfOpForBinOp(Opcode: BinOpcode);
2244 if (!DwarfBinOp)
2245 return nullptr;
2246 Opcodes.push_back(Elt: DwarfBinOp);
2247 return BI->getOperand(i_nocapture: 0);
2248}
2249
2250uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred) {
2251 // The signedness of the operation is implicit in the typed stack, signed and
2252 // unsigned instructions map to the same DWARF opcode.
2253 switch (Pred) {
2254 case CmpInst::ICMP_EQ:
2255 return dwarf::DW_OP_eq;
2256 case CmpInst::ICMP_NE:
2257 return dwarf::DW_OP_ne;
2258 case CmpInst::ICMP_UGT:
2259 case CmpInst::ICMP_SGT:
2260 return dwarf::DW_OP_gt;
2261 case CmpInst::ICMP_UGE:
2262 case CmpInst::ICMP_SGE:
2263 return dwarf::DW_OP_ge;
2264 case CmpInst::ICMP_ULT:
2265 case CmpInst::ICMP_SLT:
2266 return dwarf::DW_OP_lt;
2267 case CmpInst::ICMP_ULE:
2268 case CmpInst::ICMP_SLE:
2269 return dwarf::DW_OP_le;
2270 default:
2271 return 0;
2272 }
2273}
2274
2275Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps,
2276 SmallVectorImpl<uint64_t> &Opcodes,
2277 SmallVectorImpl<Value *> &AdditionalValues) {
2278 // Handle icmp operations with constant integer operands as a special case.
2279 auto *ConstInt = dyn_cast<ConstantInt>(Val: Icmp->getOperand(i_nocapture: 1));
2280 // Values wider than 64 bits cannot be represented within a DIExpression.
2281 if (ConstInt && ConstInt->getBitWidth() > 64)
2282 return nullptr;
2283 // Push any Constant Int operand onto the expression stack.
2284 if (ConstInt) {
2285 if (Icmp->isSigned())
2286 Opcodes.push_back(Elt: dwarf::DW_OP_consts);
2287 else
2288 Opcodes.push_back(Elt: dwarf::DW_OP_constu);
2289 uint64_t Val = ConstInt->getSExtValue();
2290 Opcodes.push_back(Elt: Val);
2291 } else {
2292 handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, I: Icmp);
2293 }
2294
2295 // Add salvaged binary operator to expression stack, if it has a valid
2296 // representation in a DIExpression.
2297 uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Pred: Icmp->getPredicate());
2298 if (!DwarfIcmpOp)
2299 return nullptr;
2300 Opcodes.push_back(Elt: DwarfIcmpOp);
2301 return Icmp->getOperand(i_nocapture: 0);
2302}
2303
2304Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
2305 SmallVectorImpl<uint64_t> &Ops,
2306 SmallVectorImpl<Value *> &AdditionalValues) {
2307 auto &M = *I.getModule();
2308 auto &DL = M.getDataLayout();
2309
2310 if (auto *CI = dyn_cast<CastInst>(Val: &I)) {
2311 Value *FromValue = CI->getOperand(i_nocapture: 0);
2312 // No-op casts are irrelevant for debug info.
2313 if (CI->isNoopCast(DL)) {
2314 return FromValue;
2315 }
2316
2317 Type *Type = CI->getType();
2318 if (Type->isPointerTy())
2319 Type = DL.getIntPtrType(Type);
2320 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
2321 if (Type->isVectorTy() ||
2322 !(isa<TruncInst>(Val: &I) || isa<SExtInst>(Val: &I) || isa<ZExtInst>(Val: &I) ||
2323 isa<IntToPtrInst>(Val: &I) || isa<PtrToIntInst>(Val: &I)))
2324 return nullptr;
2325
2326 llvm::Type *FromType = FromValue->getType();
2327 if (FromType->isPointerTy())
2328 FromType = DL.getIntPtrType(FromType);
2329
2330 unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2331 unsigned ToTypeBitSize = Type->getScalarSizeInBits();
2332
2333 auto ExtOps = DIExpression::getExtOps(FromSize: FromTypeBitSize, ToSize: ToTypeBitSize,
2334 Signed: isa<SExtInst>(Val: &I));
2335 Ops.append(in_start: ExtOps.begin(), in_end: ExtOps.end());
2336 return FromValue;
2337 }
2338
2339 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: &I))
2340 return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Opcodes&: Ops, AdditionalValues);
2341 if (auto *BI = dyn_cast<BinaryOperator>(Val: &I))
2342 return getSalvageOpsForBinOp(BI, CurrentLocOps, Opcodes&: Ops, AdditionalValues);
2343 if (auto *IC = dyn_cast<ICmpInst>(Val: &I))
2344 return getSalvageOpsForIcmpOp(Icmp: IC, CurrentLocOps, Opcodes&: Ops, AdditionalValues);
2345
2346 // *Not* to do: we should not attempt to salvage load instructions,
2347 // because the validity and lifetime of a dbg.value containing
2348 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
2349 return nullptr;
2350}
2351
2352/// A replacement for a dbg.value expression.
2353using DbgValReplacement = std::optional<DIExpression *>;
2354
2355/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2356/// possibly moving/undefing users to prevent use-before-def. Returns true if
2357/// changes are made.
2358static bool rewriteDebugUsers(
2359 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
2360 function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
2361 // Find debug users of From.
2362 SmallVector<DbgVariableRecord *, 1> DPUsers;
2363 findDbgUsers(V: &From, DbgVariableRecords&: DPUsers);
2364 if (DPUsers.empty())
2365 return false;
2366
2367 // Prevent use-before-def of To.
2368 bool Changed = false;
2369
2370 SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
2371 if (isa<Instruction>(Val: &To)) {
2372 bool DomPointAfterFrom = From.getNextNode() == &DomPoint;
2373
2374 // DbgVariableRecord implementation of the above.
2375 for (auto *DVR : DPUsers) {
2376 Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
2377 Instruction *NextNonDebug = MarkedInstr;
2378
2379 // It's common to see a debug user between From and DomPoint. Move it
2380 // after DomPoint to preserve the variable update without any reordering.
2381 if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2382 LLVM_DEBUG(dbgs() << "MOVE: " << *DVR << '\n');
2383 DVR->removeFromParent();
2384 DomPoint.getParent()->insertDbgRecordAfter(DR: DVR, I: &DomPoint);
2385 Changed = true;
2386
2387 // Users which otherwise aren't dominated by the replacement value must
2388 // be salvaged or deleted.
2389 } else if (!DT.dominates(Def: &DomPoint, User: MarkedInstr)) {
2390 UndefOrSalvageDVR.insert(Ptr: DVR);
2391 }
2392 }
2393 }
2394
2395 // Update debug users without use-before-def risk.
2396 for (auto *DVR : DPUsers) {
2397 if (UndefOrSalvageDVR.count(Ptr: DVR))
2398 continue;
2399
2400 DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
2401 if (!DVRepl)
2402 continue;
2403
2404 DVR->replaceVariableLocationOp(OldValue: &From, NewValue: &To);
2405 DVR->setExpression(*DVRepl);
2406 LLVM_DEBUG(dbgs() << "REWRITE: " << DVR << '\n');
2407 Changed = true;
2408 }
2409
2410 if (!UndefOrSalvageDVR.empty()) {
2411 // Try to salvage the remaining debug users.
2412 salvageDebugInfo(I&: From);
2413 Changed = true;
2414 }
2415
2416 return Changed;
2417}
2418
2419/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2420/// losslessly preserve the bits and semantics of the value. This predicate is
2421/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2422///
2423/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2424/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2425/// and also does not allow lossless pointer <-> integer conversions.
2426static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
2427 Type *ToTy) {
2428 // Trivially compatible types.
2429 if (FromTy == ToTy)
2430 return true;
2431
2432 // Handle compatible pointer <-> integer conversions.
2433 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2434 bool SameSize = DL.getTypeSizeInBits(Ty: FromTy) == DL.getTypeSizeInBits(Ty: ToTy);
2435 bool LosslessConversion = !DL.isNonIntegralPointerType(Ty: FromTy) &&
2436 !DL.isNonIntegralPointerType(Ty: ToTy);
2437 return SameSize && LosslessConversion;
2438 }
2439
2440 // TODO: This is not exhaustive.
2441 return false;
2442}
2443
2444bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
2445 Instruction &DomPoint, DominatorTree &DT) {
2446 // Exit early if From has no debug users.
2447 if (!From.isUsedByMetadata())
2448 return false;
2449
2450 assert(&From != &To && "Can't replace something with itself");
2451
2452 Type *FromTy = From.getType();
2453 Type *ToTy = To.getType();
2454
2455 auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2456 return DVR.getExpression();
2457 };
2458
2459 // Handle no-op conversions.
2460 Module &M = *From.getModule();
2461 const DataLayout &DL = M.getDataLayout();
2462 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2463 return rewriteDebugUsers(From, To, DomPoint, DT, RewriteDVRExpr: IdentityDVR);
2464
2465 // Handle integer-to-integer widening and narrowing.
2466 // FIXME: Use DW_OP_convert when it's available everywhere.
2467 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2468 uint64_t FromBits = FromTy->getIntegerBitWidth();
2469 uint64_t ToBits = ToTy->getIntegerBitWidth();
2470 assert(FromBits != ToBits && "Unexpected no-op conversion");
2471
2472 // When the width of the result grows, assume that a debugger will only
2473 // access the low `FromBits` bits when inspecting the source variable.
2474 if (FromBits < ToBits)
2475 return rewriteDebugUsers(From, To, DomPoint, DT, RewriteDVRExpr: IdentityDVR);
2476
2477 // The width of the result has shrunk. Use sign/zero extension to describe
2478 // the source variable's high bits.
2479 auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2480 DILocalVariable *Var = DVR.getVariable();
2481
2482 // Without knowing signedness, sign/zero extension isn't possible.
2483 auto Signedness = Var->getSignedness();
2484 if (!Signedness)
2485 return std::nullopt;
2486
2487 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2488 return DIExpression::appendExt(Expr: DVR.getExpression(), FromSize: ToBits, ToSize: FromBits,
2489 Signed);
2490 };
2491 return rewriteDebugUsers(From, To, DomPoint, DT, RewriteDVRExpr: SignOrZeroExtDVR);
2492 }
2493
2494 // TODO: Floating-point conversions, vectors.
2495 return false;
2496}
2497
2498bool llvm::handleUnreachableTerminator(
2499 Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {
2500 bool Changed = false;
2501 // RemoveDIs: erase debug-info on this instruction manually.
2502 I->dropDbgRecords();
2503 for (Use &U : I->operands()) {
2504 Value *Op = U.get();
2505 if (isa<Instruction>(Val: Op) && !Op->getType()->isTokenTy()) {
2506 U.set(PoisonValue::get(T: Op->getType()));
2507 PoisonedValues.push_back(Elt: Op);
2508 Changed = true;
2509 }
2510 }
2511
2512 return Changed;
2513}
2514
2515unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
2516 unsigned NumDeadInst = 0;
2517 // Delete the instructions backwards, as it has a reduced likelihood of
2518 // having to update as many def-use and use-def chains.
2519 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2520 SmallVector<Value *> Uses;
2521 handleUnreachableTerminator(I: EndInst, PoisonedValues&: Uses);
2522
2523 while (EndInst != &BB->front()) {
2524 // Delete the next to last instruction.
2525 Instruction *Inst = &*--EndInst->getIterator();
2526 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2527 Inst->replaceAllUsesWith(V: PoisonValue::get(T: Inst->getType()));
2528 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2529 // EHPads can't have DbgVariableRecords attached to them, but it might be
2530 // possible for things with token type.
2531 Inst->dropDbgRecords();
2532 EndInst = Inst;
2533 continue;
2534 }
2535 ++NumDeadInst;
2536 // RemoveDIs: erasing debug-info must be done manually.
2537 Inst->dropDbgRecords();
2538 Inst->eraseFromParent();
2539 }
2540 return NumDeadInst;
2541}
2542
2543unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2544 DomTreeUpdater *DTU,
2545 MemorySSAUpdater *MSSAU) {
2546 BasicBlock *BB = I->getParent();
2547
2548 if (MSSAU)
2549 MSSAU->changeToUnreachable(I);
2550
2551 SmallPtrSet<BasicBlock *, 8> UniqueSuccessors;
2552
2553 // Loop over all of the successors, removing BB's entry from any PHI
2554 // nodes.
2555 for (BasicBlock *Successor : successors(BB)) {
2556 Successor->removePredecessor(Pred: BB, KeepOneInputPHIs: PreserveLCSSA);
2557 if (DTU)
2558 UniqueSuccessors.insert(Ptr: Successor);
2559 }
2560 auto *UI = new UnreachableInst(I->getContext(), I->getIterator());
2561 UI->setDebugLoc(I->getDebugLoc());
2562
2563 // All instructions after this are dead.
2564 unsigned NumInstrsRemoved = 0;
2565 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2566 while (BBI != BBE) {
2567 if (!BBI->use_empty())
2568 BBI->replaceAllUsesWith(V: PoisonValue::get(T: BBI->getType()));
2569 BBI++->eraseFromParent();
2570 ++NumInstrsRemoved;
2571 }
2572 if (DTU) {
2573 SmallVector<DominatorTree::UpdateType, 8> Updates;
2574 Updates.reserve(N: UniqueSuccessors.size());
2575 for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2576 Updates.push_back(Elt: {DominatorTree::Delete, BB, UniqueSuccessor});
2577 DTU->applyUpdates(Updates);
2578 }
2579 BB->flushTerminatorDbgRecords();
2580 return NumInstrsRemoved;
2581}
2582
2583CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2584 SmallVector<Value *, 8> Args(II->args());
2585 SmallVector<OperandBundleDef, 1> OpBundles;
2586 II->getOperandBundlesAsDefs(Defs&: OpBundles);
2587 CallInst *NewCall = CallInst::Create(Ty: II->getFunctionType(),
2588 Func: II->getCalledOperand(), Args, Bundles: OpBundles);
2589 NewCall->setCallingConv(II->getCallingConv());
2590 NewCall->setAttributes(II->getAttributes());
2591 NewCall->copyMetadata(SrcInst: *II);
2592
2593 // If the invoke had profile metadata, try converting them for CallInst.
2594 uint64_t TotalWeight;
2595 if (NewCall->extractProfTotalWeight(TotalVal&: TotalWeight)) {
2596 // Set the total weight if it fits into i32, otherwise reset.
2597 MDBuilder MDB(NewCall->getContext());
2598 auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2599 ? nullptr
2600 : MDB.createBranchWeights(Weights: {uint32_t(TotalWeight)});
2601 NewCall->setMetadata(KindID: LLVMContext::MD_prof, Node: NewWeights);
2602 }
2603
2604 return NewCall;
2605}
2606
2607// changeToCall - Convert the specified invoke into a normal call.
2608CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2609 CallInst *NewCall = createCallMatchingInvoke(II);
2610 NewCall->takeName(V: II);
2611 NewCall->insertBefore(InsertPos: II->getIterator());
2612 II->replaceAllUsesWith(V: NewCall);
2613
2614 // Follow the call by a branch to the normal destination.
2615 BasicBlock *NormalDestBB = II->getNormalDest();
2616 auto *BI = UncondBrInst::Create(Target: NormalDestBB, InsertBefore: II->getIterator());
2617 // Although it takes place after the call itself, the new branch is still
2618 // performing part of the control-flow functionality of the invoke, so we use
2619 // II's DebugLoc.
2620 BI->setDebugLoc(II->getDebugLoc());
2621
2622 // Update PHI nodes in the unwind destination
2623 BasicBlock *BB = II->getParent();
2624 BasicBlock *UnwindDestBB = II->getUnwindDest();
2625 UnwindDestBB->removePredecessor(Pred: BB);
2626 II->eraseFromParent();
2627 if (DTU)
2628 DTU->applyUpdates(Updates: {{DominatorTree::Delete, BB, UnwindDestBB}});
2629 return NewCall;
2630}
2631
2632BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2633 BasicBlock *UnwindEdge,
2634 DomTreeUpdater *DTU) {
2635 BasicBlock *BB = CI->getParent();
2636
2637 // Convert this function call into an invoke instruction. First, split the
2638 // basic block.
2639 BasicBlock *Split = SplitBlock(Old: BB, SplitPt: CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2640 BBName: CI->getName() + ".noexc");
2641
2642 // Delete the unconditional branch inserted by SplitBlock
2643 BB->back().eraseFromParent();
2644
2645 // Create the new invoke instruction.
2646 SmallVector<Value *, 8> InvokeArgs(CI->args());
2647 SmallVector<OperandBundleDef, 1> OpBundles;
2648
2649 CI->getOperandBundlesAsDefs(Defs&: OpBundles);
2650
2651 // Note: we're round tripping operand bundles through memory here, and that
2652 // can potentially be avoided with a cleverer API design that we do not have
2653 // as of this time.
2654
2655 InvokeInst *II =
2656 InvokeInst::Create(Ty: CI->getFunctionType(), Func: CI->getCalledOperand(), IfNormal: Split,
2657 IfException: UnwindEdge, Args: InvokeArgs, Bundles: OpBundles, NameStr: CI->getName(), InsertBefore: BB);
2658 II->setDebugLoc(CI->getDebugLoc());
2659 II->setCallingConv(CI->getCallingConv());
2660 II->setAttributes(CI->getAttributes());
2661 II->setMetadata(KindID: LLVMContext::MD_prof, Node: CI->getMetadata(KindID: LLVMContext::MD_prof));
2662
2663 if (DTU)
2664 DTU->applyUpdates(Updates: {{DominatorTree::Insert, BB, UnwindEdge}});
2665
2666 // Make sure that anything using the call now uses the invoke! This also
2667 // updates the CallGraph if present, because it uses a WeakTrackingVH.
2668 CI->replaceAllUsesWith(V: II);
2669
2670 // Delete the original call
2671 Split->front().eraseFromParent();
2672 return Split;
2673}
2674
2675static bool markAliveBlocks(Function &F, SmallVectorImpl<bool> &Reachable,
2676 DomTreeUpdater *DTU, bool FoldInstsToUnreachable) {
2677 SmallVector<BasicBlock*, 128> Worklist;
2678 BasicBlock *BB = &F.front();
2679 Worklist.push_back(Elt: BB);
2680 Reachable[BB->getNumber()] = true;
2681 bool Changed = false;
2682 do {
2683 BB = Worklist.pop_back_val();
2684
2685 // Do a scan of the basic block, turning any obviously unreachable
2686 // instructions into LLVM unreachable insts. The instruction combining pass
2687 // canonicalizes unreachable insts into stores to null or undef.
2688 // Note that it traverses the whole instruction list, so it may incur
2689 // significant performance overhead.
2690 if (FoldInstsToUnreachable) {
2691 for (Instruction &I : *BB) {
2692 if (auto *CI = dyn_cast<CallInst>(Val: &I)) {
2693 Value *Callee = CI->getCalledOperand();
2694 // Handle intrinsic calls.
2695 if (Function *F = dyn_cast<Function>(Val: Callee)) {
2696 auto IntrinsicID = F->getIntrinsicID();
2697 // Assumptions that are known to be false are equivalent to
2698 // unreachable. Also, if the condition is undefined, then we make
2699 // the choice most beneficial to the optimizer, and choose that to
2700 // also be unreachable.
2701 if (IntrinsicID == Intrinsic::assume) {
2702 if (match(V: CI->getArgOperand(i: 0),
2703 P: m_CombineOr(Ps: m_Zero(), Ps: m_Undef()))) {
2704 // Don't insert a call to llvm.trap right before the
2705 // unreachable.
2706 changeToUnreachable(I: CI, PreserveLCSSA: false, DTU);
2707 Changed = true;
2708 break;
2709 }
2710 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2711 // A call to the guard intrinsic bails out of the current
2712 // compilation unit if the predicate passed to it is false. If the
2713 // predicate is a constant false, then we know the guard will bail
2714 // out of the current compile unconditionally, so all code
2715 // following it is dead.
2716 //
2717 // Note: unlike in llvm.assume, it is not "obviously profitable"
2718 // for guards to treat `undef` as `false` since a guard on `undef`
2719 // can still be useful for widening.
2720 if (match(V: CI->getArgOperand(i: 0), P: m_Zero()))
2721 if (!isa<UnreachableInst>(Val: CI->getNextNode())) {
2722 changeToUnreachable(I: CI->getNextNode(), PreserveLCSSA: false, DTU);
2723 Changed = true;
2724 break;
2725 }
2726 }
2727 } else if ((isa<ConstantPointerNull>(Val: Callee) &&
2728 !NullPointerIsDefined(F: CI->getFunction(),
2729 AS: cast<PointerType>(Val: Callee->getType())
2730 ->getAddressSpace())) ||
2731 isa<UndefValue>(Val: Callee)) {
2732 changeToUnreachable(I: CI, PreserveLCSSA: false, DTU);
2733 Changed = true;
2734 break;
2735 }
2736 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2737 // If we found a call to a no-return function, insert an unreachable
2738 // instruction after it. Make sure there isn't *already* one there
2739 // though.
2740 if (!isa<UnreachableInst>(Val: CI->getNextNode())) {
2741 // Don't insert a call to llvm.trap right before the unreachable.
2742 changeToUnreachable(I: CI->getNextNode(), PreserveLCSSA: false, DTU);
2743 Changed = true;
2744 }
2745 break;
2746 }
2747 } else if (auto *SI = dyn_cast<StoreInst>(Val: &I)) {
2748 // Store to undef and store to null are undefined and used to signal
2749 // that they should be changed to unreachable by passes that can't
2750 // modify the CFG.
2751
2752 // Don't touch volatile stores.
2753 if (SI->isVolatile())
2754 continue;
2755
2756 Value *Ptr = SI->getOperand(i_nocapture: 1);
2757
2758 if (isa<UndefValue>(Val: Ptr) ||
2759 (isa<ConstantPointerNull>(Val: Ptr) &&
2760 !NullPointerIsDefined(F: SI->getFunction(),
2761 AS: SI->getPointerAddressSpace()))) {
2762 changeToUnreachable(I: SI, PreserveLCSSA: false, DTU);
2763 Changed = true;
2764 break;
2765 }
2766 }
2767 }
2768
2769 Instruction *Terminator = BB->getTerminator();
2770 if (auto *II = dyn_cast<InvokeInst>(Val: Terminator)) {
2771 // Turn invokes that call 'nounwind' functions into ordinary calls.
2772 Value *Callee = II->getCalledOperand();
2773 if ((isa<ConstantPointerNull>(Val: Callee) &&
2774 !NullPointerIsDefined(F: BB->getParent())) ||
2775 isa<UndefValue>(Val: Callee)) {
2776 changeToUnreachable(I: II, PreserveLCSSA: false, DTU);
2777 Changed = true;
2778 } else {
2779 if (II->doesNotReturn() &&
2780 !isa<UnreachableInst>(Val: II->getNormalDest()->front())) {
2781 // If we found an invoke of a no-return function,
2782 // create a new empty basic block with an `unreachable` terminator,
2783 // and set it as the normal destination for the invoke,
2784 // unless that is already the case.
2785 // Note that the original normal destination could have other uses.
2786 BasicBlock *OrigNormalDest = II->getNormalDest();
2787 OrigNormalDest->removePredecessor(Pred: II->getParent());
2788 LLVMContext &Ctx = II->getContext();
2789 BasicBlock *UnreachableNormalDest = BasicBlock::Create(
2790 Context&: Ctx, Name: OrigNormalDest->getName() + ".unreachable",
2791 Parent: II->getFunction(), InsertBefore: OrigNormalDest);
2792 Reachable.resize(N: II->getFunction()->getMaxBlockNumber());
2793 auto *UI = new UnreachableInst(Ctx, UnreachableNormalDest);
2794 UI->setDebugLoc(DebugLoc::getTemporary());
2795 II->setNormalDest(UnreachableNormalDest);
2796 if (DTU)
2797 DTU->applyUpdates(
2798 Updates: {{DominatorTree::Delete, BB, OrigNormalDest},
2799 {DominatorTree::Insert, BB, UnreachableNormalDest}});
2800 Changed = true;
2801 }
2802 if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F: &F)) {
2803 if (II->use_empty() && !II->mayHaveSideEffects()) {
2804 // jump to the normal destination branch.
2805 BasicBlock *NormalDestBB = II->getNormalDest();
2806 BasicBlock *UnwindDestBB = II->getUnwindDest();
2807 UncondBrInst::Create(Target: NormalDestBB, InsertBefore: II->getIterator());
2808 UnwindDestBB->removePredecessor(Pred: II->getParent());
2809 II->eraseFromParent();
2810 if (DTU)
2811 DTU->applyUpdates(Updates: {{DominatorTree::Delete, BB, UnwindDestBB}});
2812 } else
2813 changeToCall(II, DTU);
2814 Changed = true;
2815 }
2816 }
2817 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val: Terminator)) {
2818 // Remove catchpads which cannot be reached.
2819 struct CatchPadDenseMapInfo {
2820 static unsigned getHashValue(CatchPadInst *CatchPad) {
2821 return static_cast<unsigned>(hash_combine_range(
2822 first: CatchPad->value_op_begin(), last: CatchPad->value_op_end()));
2823 }
2824
2825 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2826 return LHS->isIdenticalTo(I: RHS);
2827 }
2828 };
2829
2830 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
2831 // Set of unique CatchPads.
2832 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2833 CatchPadDenseMapInfo,
2834 detail::DenseSetPair<CatchPadInst *>>
2835 HandlerSet;
2836 detail::DenseSetEmpty Empty;
2837 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2838 E = CatchSwitch->handler_end();
2839 I != E; ++I) {
2840 BasicBlock *HandlerBB = *I;
2841 if (DTU)
2842 ++NumPerSuccessorCases[HandlerBB];
2843 auto *CatchPad = cast<CatchPadInst>(Val: HandlerBB->getFirstNonPHIIt());
2844 if (!HandlerSet.insert(KV: {CatchPad, Empty}).second) {
2845 if (DTU)
2846 --NumPerSuccessorCases[HandlerBB];
2847 CatchSwitch->removeHandler(HI: I);
2848 --I;
2849 --E;
2850 Changed = true;
2851 }
2852 }
2853 if (DTU) {
2854 std::vector<DominatorTree::UpdateType> Updates;
2855 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
2856 if (I.second == 0)
2857 Updates.push_back(x: {DominatorTree::Delete, BB, I.first});
2858 DTU->applyUpdates(Updates);
2859 }
2860 }
2861
2862 Changed |= ConstantFoldTerminator(BB, DeleteDeadConditions: true, TLI: nullptr, DTU);
2863 }
2864 for (BasicBlock *Successor : successors(BB)) {
2865 if (!Reachable[Successor->getNumber()]) {
2866 Worklist.push_back(Elt: Successor);
2867 Reachable[Successor->getNumber()] = true;
2868 }
2869 }
2870 } while (!Worklist.empty());
2871 return Changed;
2872}
2873
2874Instruction *llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2875 Instruction *TI = BB->getTerminator();
2876
2877 if (auto *II = dyn_cast<InvokeInst>(Val: TI))
2878 return changeToCall(II, DTU);
2879
2880 Instruction *NewTI;
2881 BasicBlock *UnwindDest;
2882
2883 if (auto *CRI = dyn_cast<CleanupReturnInst>(Val: TI)) {
2884 NewTI = CleanupReturnInst::Create(CleanupPad: CRI->getCleanupPad(), UnwindBB: nullptr, InsertBefore: CRI->getIterator());
2885 UnwindDest = CRI->getUnwindDest();
2886 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val: TI)) {
2887 auto *NewCatchSwitch = CatchSwitchInst::Create(
2888 ParentPad: CatchSwitch->getParentPad(), UnwindDest: nullptr, NumHandlers: CatchSwitch->getNumHandlers(),
2889 NameStr: CatchSwitch->getName(), InsertBefore: CatchSwitch->getIterator());
2890 for (BasicBlock *PadBB : CatchSwitch->handlers())
2891 NewCatchSwitch->addHandler(Dest: PadBB);
2892
2893 NewTI = NewCatchSwitch;
2894 UnwindDest = CatchSwitch->getUnwindDest();
2895 } else {
2896 llvm_unreachable("Could not find unwind successor");
2897 }
2898
2899 NewTI->takeName(V: TI);
2900 NewTI->setDebugLoc(TI->getDebugLoc());
2901 UnwindDest->removePredecessor(Pred: BB);
2902 TI->replaceAllUsesWith(V: NewTI);
2903 TI->eraseFromParent();
2904 if (DTU)
2905 DTU->applyUpdates(Updates: {{DominatorTree::Delete, BB, UnwindDest}});
2906 return NewTI;
2907}
2908
2909/// removeUnreachableBlocks - Remove blocks that are not reachable, even
2910/// if they are in a dead cycle. Return true if a change was made, false
2911/// otherwise.
2912bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2913 MemorySSAUpdater *MSSAU,
2914 bool FoldInstsToUnreachable) {
2915 SmallVector<bool, 16> Reachable(F.getMaxBlockNumber());
2916 bool Changed = markAliveBlocks(F, Reachable, DTU, FoldInstsToUnreachable);
2917
2918 // Are there any blocks left to actually delete?
2919 SmallSetVector<BasicBlock *, 8> BlocksToRemove;
2920 for (BasicBlock &BB : F) {
2921 // Skip reachable basic blocks
2922 if (Reachable[BB.getNumber()])
2923 continue;
2924 // Skip already-deleted blocks
2925 if (DTU && DTU->isBBPendingDeletion(DelBB: &BB))
2926 continue;
2927 BlocksToRemove.insert(X: &BB);
2928 }
2929
2930 if (BlocksToRemove.empty())
2931 return Changed;
2932
2933 Changed = true;
2934 NumRemoved += BlocksToRemove.size();
2935
2936 if (MSSAU)
2937 MSSAU->removeBlocks(DeadBlocks: BlocksToRemove);
2938
2939 DeleteDeadBlocks(BBs: BlocksToRemove.takeVector(), DTU);
2940
2941 return Changed;
2942}
2943
2944/// If AAOnly is set, only intersect alias analysis metadata and preserve other
2945/// known metadata. Unknown metadata is always dropped.
2946static void combineMetadata(Instruction *K, const Instruction *J,
2947 bool DoesKMove, bool AAOnly = false) {
2948 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2949 K->getAllMetadataOtherThanDebugLoc(MDs&: Metadata);
2950 for (const auto &MD : Metadata) {
2951 unsigned Kind = MD.first;
2952 MDNode *JMD = J->getMetadata(KindID: Kind);
2953 MDNode *KMD = MD.second;
2954
2955 // TODO: Assert that this switch is exhaustive for fixed MD kinds.
2956 switch (Kind) {
2957 default:
2958 K->setMetadata(KindID: Kind, Node: nullptr); // Remove unknown metadata
2959 break;
2960 case LLVMContext::MD_dbg:
2961 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2962 case LLVMContext::MD_DIAssignID:
2963 if (!AAOnly)
2964 K->mergeDIAssignID(SourceInstructions: J);
2965 break;
2966 case LLVMContext::MD_tbaa:
2967 if (DoesKMove)
2968 K->setMetadata(KindID: Kind, Node: MDNode::getMostGenericTBAA(A: JMD, B: KMD));
2969 break;
2970 case LLVMContext::MD_alias_scope:
2971 if (DoesKMove)
2972 K->setMetadata(KindID: Kind, Node: MDNode::getMostGenericAliasScope(A: JMD, B: KMD));
2973 break;
2974 case LLVMContext::MD_noalias:
2975 case LLVMContext::MD_mem_parallel_loop_access:
2976 if (DoesKMove)
2977 K->setMetadata(KindID: Kind, Node: MDNode::intersect(A: JMD, B: KMD));
2978 break;
2979 case LLVMContext::MD_access_group:
2980 if (DoesKMove)
2981 K->setMetadata(KindID: LLVMContext::MD_access_group,
2982 Node: intersectAccessGroups(Inst1: K, Inst2: J));
2983 break;
2984 case LLVMContext::MD_range:
2985 if (!AAOnly && (DoesKMove || !K->hasMetadata(KindID: LLVMContext::MD_noundef)))
2986 K->setMetadata(KindID: Kind, Node: MDNode::getMostGenericRange(A: JMD, B: KMD));
2987 break;
2988 case LLVMContext::MD_nofpclass:
2989 if (!AAOnly && (DoesKMove || !K->hasMetadata(KindID: LLVMContext::MD_noundef)))
2990 K->setMetadata(KindID: Kind, Node: MDNode::getMostGenericNoFPClass(A: JMD, B: KMD));
2991 break;
2992 case LLVMContext::MD_fpmath:
2993 if (!AAOnly)
2994 K->setMetadata(KindID: Kind, Node: MDNode::getMostGenericFPMath(A: JMD, B: KMD));
2995 break;
2996 case LLVMContext::MD_invariant_load:
2997 case LLVMContext::MD_invariant_group:
2998 // If K moves, only keep the invariant metadata if it is present on
2999 // both instructions; otherwise the invariant would be asserted on a
3000 // path (J's) that never promised it. If K does not move, K stays on
3001 // its original path, so its existing metadata remains valid.
3002 if (DoesKMove)
3003 K->setMetadata(KindID: Kind, Node: JMD);
3004 break;
3005 case LLVMContext::MD_nonnull:
3006 if (!AAOnly && (DoesKMove || !K->hasMetadata(KindID: LLVMContext::MD_noundef)))
3007 K->setMetadata(KindID: Kind, Node: JMD);
3008 break;
3009 // Keep empty cases for prof, mmra, memprof, and callsite to prevent them
3010 // from being removed as unknown metadata. The actual merging is handled
3011 // separately below.
3012 case LLVMContext::MD_prof:
3013 case LLVMContext::MD_mmra:
3014 case LLVMContext::MD_memprof:
3015 case LLVMContext::MD_callsite:
3016 break;
3017 case LLVMContext::MD_callee_type:
3018 if (!AAOnly) {
3019 K->setMetadata(KindID: LLVMContext::MD_callee_type,
3020 Node: MDNode::getMergedCalleeTypeMetadata(A: KMD, B: JMD));
3021 }
3022 break;
3023 case LLVMContext::MD_align:
3024 if (!AAOnly && (DoesKMove || !K->hasMetadata(KindID: LLVMContext::MD_noundef)))
3025 K->setMetadata(
3026 KindID: Kind, Node: MDNode::getMostGenericAlignmentOrDereferenceable(A: JMD, B: KMD));
3027 break;
3028 case LLVMContext::MD_dereferenceable:
3029 case LLVMContext::MD_dereferenceable_or_null:
3030 if (!AAOnly && DoesKMove)
3031 K->setMetadata(KindID: Kind,
3032 Node: MDNode::getMostGenericAlignmentOrDereferenceable(A: JMD, B: KMD));
3033 break;
3034 case LLVMContext::MD_preserve_access_index:
3035 // Preserve !preserve.access.index in K.
3036 break;
3037 case LLVMContext::MD_noundef:
3038 // If K does move, keep noundef if it is present in both instructions.
3039 if (!AAOnly && DoesKMove)
3040 K->setMetadata(KindID: Kind, Node: JMD);
3041 break;
3042 case LLVMContext::MD_nontemporal:
3043 // Preserve !nontemporal if it is present on both instructions.
3044 if (!AAOnly)
3045 K->setMetadata(KindID: Kind, Node: JMD);
3046 break;
3047 case LLVMContext::MD_mem_cache_hint:
3048 // Preserve !mem.cache_hint only if it is present and equivalent on both
3049 // instructions.
3050 if (!AAOnly && KMD != JMD)
3051 K->setMetadata(KindID: Kind, Node: nullptr);
3052 break;
3053 case LLVMContext::MD_noalias_addrspace:
3054 if (DoesKMove)
3055 K->setMetadata(KindID: Kind,
3056 Node: MDNode::getMostGenericNoaliasAddrspace(A: JMD, B: KMD));
3057 break;
3058 case LLVMContext::MD_nosanitize:
3059 // Preserve !nosanitize if both K and J have it.
3060 K->setMetadata(KindID: Kind, Node: JMD);
3061 break;
3062 case LLVMContext::MD_captures:
3063 K->setMetadata(
3064 KindID: Kind, Node: MDNode::fromCaptureComponents(
3065 Ctx&: K->getContext(), CC: MDNode::toCaptureComponents(MD: JMD) |
3066 MDNode::toCaptureComponents(MD: KMD)));
3067 break;
3068 case LLVMContext::MD_alloc_token:
3069 if (!AAOnly && KMD != JMD)
3070 K->setMetadata(KindID: Kind, Node: MDNode::getMergedAllocTokenMetadata(A: KMD, B: JMD));
3071 break;
3072 }
3073 }
3074
3075 // Merge MMRAs.
3076 // This is handled separately because we also want to handle cases where K
3077 // doesn't have tags but J does.
3078 auto JMMRA = J->getMetadata(KindID: LLVMContext::MD_mmra);
3079 auto KMMRA = K->getMetadata(KindID: LLVMContext::MD_mmra);
3080 if (JMMRA || KMMRA) {
3081 K->setMetadata(KindID: LLVMContext::MD_mmra,
3082 Node: MMRAMetadata::combine(Ctx&: K->getContext(), A: JMMRA, B: KMMRA));
3083 }
3084
3085 // Merge memprof metadata.
3086 // Handle separately to support cases where only one instruction has the
3087 // metadata.
3088 auto *JMemProf = J->getMetadata(KindID: LLVMContext::MD_memprof);
3089 auto *KMemProf = K->getMetadata(KindID: LLVMContext::MD_memprof);
3090 if (!AAOnly && (JMemProf || KMemProf)) {
3091 K->setMetadata(KindID: LLVMContext::MD_memprof,
3092 Node: MDNode::getMergedMemProfMetadata(A: KMemProf, B: JMemProf));
3093 }
3094
3095 // Merge callsite metadata.
3096 // Handle separately to support cases where only one instruction has the
3097 // metadata.
3098 auto *JCallSite = J->getMetadata(KindID: LLVMContext::MD_callsite);
3099 auto *KCallSite = K->getMetadata(KindID: LLVMContext::MD_callsite);
3100 if (!AAOnly && (JCallSite || KCallSite)) {
3101 K->setMetadata(KindID: LLVMContext::MD_callsite,
3102 Node: MDNode::getMergedCallsiteMetadata(A: KCallSite, B: JCallSite));
3103 }
3104
3105 // Merge prof metadata.
3106 // Handle separately to support cases where only one instruction has the
3107 // metadata.
3108 auto *JProf = J->getMetadata(KindID: LLVMContext::MD_prof);
3109 auto *KProf = K->getMetadata(KindID: LLVMContext::MD_prof);
3110 if (!AAOnly && (JProf || KProf)) {
3111 K->setMetadata(KindID: LLVMContext::MD_prof,
3112 Node: MDNode::getMergedProfMetadata(A: KProf, B: JProf, AInstr: K, BInstr: J));
3113 }
3114}
3115
3116void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
3117 bool DoesKMove) {
3118 combineMetadata(K, J, DoesKMove);
3119}
3120
3121void llvm::combineAAMetadata(Instruction *K, const Instruction *J) {
3122 combineMetadata(K, J, /*DoesKMove=*/true, /*AAOnly=*/true);
3123}
3124
3125void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
3126 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
3127 Source.getAllMetadata(MDs&: MD);
3128 MDBuilder MDB(Dest.getContext());
3129 Type *NewType = Dest.getType();
3130 const DataLayout &DL = Source.getDataLayout();
3131 for (const auto &MDPair : MD) {
3132 unsigned ID = MDPair.first;
3133 MDNode *N = MDPair.second;
3134 // Note, essentially every kind of metadata should be preserved here! This
3135 // routine is supposed to clone a load instruction changing *only its type*.
3136 // The only metadata it makes sense to drop is metadata which is invalidated
3137 // when the pointer type changes. This should essentially never be the case
3138 // in LLVM, but we explicitly switch over only known metadata to be
3139 // conservatively correct. If you are adding metadata to LLVM which pertains
3140 // to loads, you almost certainly want to add it here.
3141 switch (ID) {
3142 case LLVMContext::MD_dbg:
3143 case LLVMContext::MD_tbaa:
3144 case LLVMContext::MD_prof:
3145 case LLVMContext::MD_fpmath:
3146 case LLVMContext::MD_tbaa_struct:
3147 case LLVMContext::MD_invariant_load:
3148 case LLVMContext::MD_alias_scope:
3149 case LLVMContext::MD_noalias:
3150 case LLVMContext::MD_nontemporal:
3151 case LLVMContext::MD_mem_cache_hint:
3152 case LLVMContext::MD_mem_parallel_loop_access:
3153 case LLVMContext::MD_access_group:
3154 case LLVMContext::MD_noundef:
3155 case LLVMContext::MD_noalias_addrspace:
3156 case LLVMContext::MD_invariant_group:
3157 // All of these directly apply.
3158 Dest.setMetadata(KindID: ID, Node: N);
3159 break;
3160
3161 case LLVMContext::MD_nonnull:
3162 copyNonnullMetadata(OldLI: Source, N, NewLI&: Dest);
3163 break;
3164
3165 case LLVMContext::MD_align:
3166 case LLVMContext::MD_dereferenceable:
3167 case LLVMContext::MD_dereferenceable_or_null:
3168 // These only directly apply if the new type is also a pointer.
3169 if (NewType->isPointerTy())
3170 Dest.setMetadata(KindID: ID, Node: N);
3171 break;
3172
3173 case LLVMContext::MD_range:
3174 copyRangeMetadata(DL, OldLI: Source, N, NewLI&: Dest);
3175 break;
3176
3177 case LLVMContext::MD_nofpclass:
3178 // This only applies if the floating-point type interpretation. This
3179 // should handle degenerate cases like casting between a scalar and single
3180 // element vector.
3181 if (NewType->getScalarType() == Source.getType()->getScalarType())
3182 Dest.setMetadata(KindID: ID, Node: N);
3183 break;
3184 }
3185 }
3186}
3187
3188void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
3189 auto *ReplInst = dyn_cast<Instruction>(Val: Repl);
3190 if (!ReplInst)
3191 return;
3192
3193 // Patch the replacement so that it is not more restrictive than the value
3194 // being replaced.
3195 WithOverflowInst *UnusedWO;
3196 // When replacing the result of a llvm.*.with.overflow intrinsic with a
3197 // overflowing binary operator, nuw/nsw flags may no longer hold.
3198 if (isa<OverflowingBinaryOperator>(Val: ReplInst) &&
3199 match(V: I, P: m_ExtractValue<0>(V: m_WithOverflowInst(I&: UnusedWO))))
3200 ReplInst->dropPoisonGeneratingFlags();
3201 // Note that if 'I' is a load being replaced by some operation,
3202 // for example, by an arithmetic operation, then andIRFlags()
3203 // would just erase all math flags from the original arithmetic
3204 // operation, which is clearly not wanted and not needed.
3205 else if (!isa<LoadInst>(Val: I))
3206 ReplInst->andIRFlags(V: I);
3207
3208 // Handle attributes.
3209 if (auto *CB1 = dyn_cast<CallBase>(Val: ReplInst)) {
3210 if (auto *CB2 = dyn_cast<CallBase>(Val: I)) {
3211 bool Success = CB1->tryIntersectAttributes(Other: CB2);
3212 assert(Success && "We should not be trying to sink callbases "
3213 "with non-intersectable attributes");
3214 // For NDEBUG Compile.
3215 (void)Success;
3216 }
3217 }
3218
3219 // FIXME: If both the original and replacement value are part of the
3220 // same control-flow region (meaning that the execution of one
3221 // guarantees the execution of the other), then we can combine the
3222 // noalias scopes here and do better than the general conservative
3223 // answer used in combineMetadata().
3224
3225 // In general, GVN unifies expressions over different control-flow
3226 // regions, and so we need a conservative combination of the noalias
3227 // scopes.
3228 combineMetadataForCSE(K: ReplInst, J: I, DoesKMove: false);
3229}
3230
3231template <typename ShouldReplaceFn>
3232static unsigned replaceDominatedUsesWith(Value *From, Value *To,
3233 const ShouldReplaceFn &ShouldReplace) {
3234 assert(From->getType() == To->getType());
3235
3236 unsigned Count = 0;
3237 for (Use &U : llvm::make_early_inc_range(Range: From->uses())) {
3238 auto *II = dyn_cast<IntrinsicInst>(Val: U.getUser());
3239 if (II && II->getIntrinsicID() == Intrinsic::fake_use)
3240 continue;
3241 if (!ShouldReplace(U))
3242 continue;
3243 LLVM_DEBUG(dbgs() << "Replace dominated use of '";
3244 From->printAsOperand(dbgs());
3245 dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");
3246 U.set(To);
3247 ++Count;
3248 }
3249 return Count;
3250}
3251
3252unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
3253 assert(From->getType() == To->getType());
3254 auto *BB = From->getParent();
3255 unsigned Count = 0;
3256
3257 for (Use &U : llvm::make_early_inc_range(Range: From->uses())) {
3258 auto *I = cast<Instruction>(Val: U.getUser());
3259 if (I->getParent() == BB)
3260 continue;
3261 U.set(To);
3262 ++Count;
3263 }
3264 return Count;
3265}
3266
3267unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
3268 DominatorTree &DT,
3269 const BasicBlockEdge &Root) {
3270 auto Dominates = [&](const Use &U) { return DT.dominates(BBE: Root, U); };
3271 return ::replaceDominatedUsesWith(From, To, ShouldReplace: Dominates);
3272}
3273
3274unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
3275 DominatorTree &DT,
3276 const BasicBlock *BB) {
3277 auto Dominates = [&](const Use &U) { return DT.dominates(BB, U); };
3278 return ::replaceDominatedUsesWith(From, To, ShouldReplace: Dominates);
3279}
3280
3281unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
3282 DominatorTree &DT,
3283 const Instruction *I) {
3284 auto Dominates = [&](const Use &U) { return DT.dominates(Def: I, U); };
3285 return ::replaceDominatedUsesWith(From, To, ShouldReplace: Dominates);
3286}
3287
3288unsigned llvm::replaceDominatedUsesWithIf(
3289 Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,
3290 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3291 auto DominatesAndShouldReplace = [&](const Use &U) {
3292 return DT.dominates(BBE: Root, U) && ShouldReplace(U, To);
3293 };
3294 return ::replaceDominatedUsesWith(From, To, ShouldReplace: DominatesAndShouldReplace);
3295}
3296
3297unsigned llvm::replaceDominatedUsesWithIf(
3298 Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
3299 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3300 auto DominatesAndShouldReplace = [&](const Use &U) {
3301 return DT.dominates(BB, U) && ShouldReplace(U, To);
3302 };
3303 return ::replaceDominatedUsesWith(From, To, ShouldReplace: DominatesAndShouldReplace);
3304}
3305
3306unsigned llvm::replaceDominatedUsesWithIf(
3307 Value *From, Value *To, DominatorTree &DT, const Instruction *I,
3308 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3309 auto DominatesAndShouldReplace = [&](const Use &U) {
3310 return DT.dominates(Def: I, U) && ShouldReplace(U, To);
3311 };
3312 return ::replaceDominatedUsesWith(From, To, ShouldReplace: DominatesAndShouldReplace);
3313}
3314
3315bool llvm::callsGCLeafFunction(const CallBase *Call,
3316 const TargetLibraryInfo &TLI) {
3317 // Check if the function is specifically marked as a gc leaf function.
3318 if (Call->hasFnAttr(Kind: "gc-leaf-function"))
3319 return true;
3320 if (const Function *F = Call->getCalledFunction()) {
3321 if (F->hasFnAttribute(Kind: "gc-leaf-function"))
3322 return true;
3323
3324 if (auto IID = F->getIntrinsicID()) {
3325 // Most LLVM intrinsics do not take safepoints.
3326 return IID != Intrinsic::experimental_gc_statepoint &&
3327 IID != Intrinsic::experimental_deoptimize &&
3328 IID != Intrinsic::memcpy_element_unordered_atomic &&
3329 IID != Intrinsic::memmove_element_unordered_atomic;
3330 }
3331 }
3332
3333 // Lib calls can be materialized by some passes, and won't be
3334 // marked as 'gc-leaf-function.' All available Libcalls are
3335 // GC-leaf.
3336 return TLI.has(F: TLI.getLibFunc(CB: *Call));
3337}
3338
3339void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
3340 LoadInst &NewLI) {
3341 auto *NewTy = NewLI.getType();
3342
3343 // This only directly applies if the new type is also a pointer.
3344 if (NewTy->isPointerTy()) {
3345 NewLI.setMetadata(KindID: LLVMContext::MD_nonnull, Node: N);
3346 return;
3347 }
3348
3349 // The only other translation we can do is to integral loads with !range
3350 // metadata.
3351 if (!NewTy->isIntegerTy())
3352 return;
3353
3354 MDBuilder MDB(NewLI.getContext());
3355 const Value *Ptr = OldLI.getPointerOperand();
3356 auto *ITy = cast<IntegerType>(Val: NewTy);
3357 auto *NullInt = ConstantExpr::getPtrToInt(
3358 C: ConstantPointerNull::get(T: cast<PointerType>(Val: Ptr->getType())), Ty: ITy);
3359 auto *NonNullInt = ConstantExpr::getAdd(C1: NullInt, C2: ConstantInt::get(Ty: ITy, V: 1));
3360 NewLI.setMetadata(KindID: LLVMContext::MD_range,
3361 Node: MDB.createRange(Lo: NonNullInt, Hi: NullInt));
3362}
3363
3364void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
3365 MDNode *N, LoadInst &NewLI) {
3366 auto *NewTy = NewLI.getType();
3367 // Simply copy the metadata if the type did not change.
3368 if (NewTy == OldLI.getType()) {
3369 NewLI.setMetadata(KindID: LLVMContext::MD_range, Node: N);
3370 return;
3371 }
3372
3373 // Give up unless it is converted to a pointer where there is a single very
3374 // valuable mapping we can do reliably.
3375 // FIXME: It would be nice to propagate this in more ways, but the type
3376 // conversions make it hard.
3377 if (!NewTy->isPointerTy())
3378 return;
3379
3380 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
3381 if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
3382 !getConstantRangeFromMetadata(RangeMD: *N).contains(Val: APInt(BitWidth, 0))) {
3383 MDNode *NN = MDNode::get(Context&: OldLI.getContext(), MDs: {});
3384 NewLI.setMetadata(KindID: LLVMContext::MD_nonnull, Node: NN);
3385 }
3386}
3387
3388void llvm::dropDebugUsers(Instruction &I) {
3389 SmallVector<DbgVariableRecord *, 1> DPUsers;
3390 findDbgUsers(V: &I, DbgVariableRecords&: DPUsers);
3391 for (auto *DVR : DPUsers)
3392 DVR->eraseFromParent();
3393}
3394
3395void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
3396 BasicBlock *BB) {
3397 // Since we are moving the instructions out of its basic block, we do not
3398 // retain their original debug locations (DILocations) and debug intrinsic
3399 // instructions.
3400 //
3401 // Doing so would degrade the debugging experience.
3402 //
3403 // FIXME: Issue #152767: debug info should also be the same as the
3404 // original branch, **if** the user explicitly indicated that (for sampling
3405 // PGO)
3406 //
3407 // Currently, when hoisting the instructions, we take the following actions:
3408 // - Remove their debug intrinsic instructions.
3409 // - Set their debug locations to the values from the insertion point.
3410 //
3411 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
3412 // need to be deleted, is because there will not be any instructions with a
3413 // DILocation in either branch left after performing the transformation. We
3414 // can only insert a dbg.value after the two branches are joined again.
3415 //
3416 // See PR38762, PR39243 for more details.
3417 //
3418 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
3419 // encode predicated DIExpressions that yield different results on different
3420 // code paths.
3421
3422 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
3423 Instruction *I = &*II;
3424 I->dropUBImplyingAttrsAndMetadata();
3425 if (I->isUsedByMetadata())
3426 dropDebugUsers(I&: *I);
3427 // RemoveDIs: drop debug-info too as the following code does.
3428 I->dropDbgRecords();
3429 if (I->isDebugOrPseudoInst()) {
3430 // Remove DbgInfo and pseudo probe Intrinsics.
3431 II = I->eraseFromParent();
3432 continue;
3433 }
3434 I->setDebugLoc(InsertPt->getDebugLoc());
3435 ++II;
3436 }
3437 DomBlock->splice(ToIt: InsertPt->getIterator(), FromBB: BB, FromBeginIt: BB->begin(),
3438 FromEndIt: BB->getTerminator()->getIterator());
3439}
3440
3441DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,
3442 Type &Ty) {
3443 // Create integer constant expression.
3444 auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {
3445 const APInt &API = cast<ConstantInt>(Val: &CV)->getValue();
3446 std::optional<int64_t> InitIntOpt;
3447 if (API.getBitWidth() == 1)
3448 InitIntOpt = API.tryZExtValue();
3449 else
3450 InitIntOpt = API.trySExtValue();
3451 return InitIntOpt ? DIB.createConstantValueExpression(
3452 Val: static_cast<uint64_t>(*InitIntOpt))
3453 : nullptr;
3454 };
3455
3456 if (isa<ConstantInt>(Val: C))
3457 return createIntegerExpression(C);
3458
3459 auto *FP = dyn_cast<ConstantFP>(Val: &C);
3460 if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3461 const APFloat &APF = FP->getValueAPF();
3462 APInt const &API = APF.bitcastToAPInt();
3463 if (uint64_t Temp = API.getZExtValue())
3464 return DIB.createConstantValueExpression(Val: Temp);
3465 return DIB.createConstantValueExpression(Val: *API.getRawData());
3466 }
3467
3468 if (!Ty.isPointerTy())
3469 return nullptr;
3470
3471 if (isa<ConstantPointerNull>(Val: C))
3472 return DIB.createConstantValueExpression(Val: 0);
3473
3474 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: &C))
3475 if (CE->getOpcode() == Instruction::IntToPtr) {
3476 const Value *V = CE->getOperand(i_nocapture: 0);
3477 if (auto CI = dyn_cast_or_null<ConstantInt>(Val: V))
3478 return createIntegerExpression(*CI);
3479 }
3480 return nullptr;
3481}
3482
3483void llvm::remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst) {
3484 auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {
3485 for (auto *Op : Set) {
3486 auto I = Mapping.find(Op);
3487 if (I != Mapping.end())
3488 DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);
3489 }
3490 };
3491 auto RemapAssignAddress = [&Mapping](auto *DA) {
3492 auto I = Mapping.find(DA->getAddress());
3493 if (I != Mapping.end())
3494 DA->setAddress(I->second);
3495 };
3496 for (DbgVariableRecord &DVR : filterDbgVars(R: Inst->getDbgRecordRange())) {
3497 RemapDebugOperands(&DVR, DVR.location_ops());
3498 if (DVR.isDbgAssign())
3499 RemapAssignAddress(&DVR);
3500 }
3501}
3502
3503namespace {
3504
3505/// A potential constituent of a bitreverse or bswap expression. See
3506/// collectBitParts for a fuller explanation.
3507struct BitPart {
3508 BitPart(Value *P, unsigned BW) : Provider(P) {
3509 Provenance.resize(N: BW);
3510 }
3511
3512 /// The Value that this is a bitreverse/bswap of.
3513 Value *Provider;
3514
3515 /// The "provenance" of each bit. Provenance[A] = B means that bit A
3516 /// in Provider becomes bit B in the result of this expression.
3517 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
3518
3519 enum { Unset = -1 };
3520};
3521
3522} // end anonymous namespace
3523
3524/// Analyze the specified subexpression and see if it is capable of providing
3525/// pieces of a bswap or bitreverse. The subexpression provides a potential
3526/// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
3527/// the output of the expression came from a corresponding bit in some other
3528/// value. This function is recursive, and the end result is a mapping of
3529/// bitnumber to bitnumber. It is the caller's responsibility to validate that
3530/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
3531///
3532/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
3533/// that the expression deposits the low byte of %X into the high byte of the
3534/// result and that all other bits are zero. This expression is accepted and a
3535/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
3536/// [0-7].
3537///
3538/// For vector types, all analysis is performed at the per-element level. No
3539/// cross-element analysis is supported (shuffle/insertion/reduction), and all
3540/// constant masks must be splatted across all elements.
3541///
3542/// To avoid revisiting values, the BitPart results are memoized into the
3543/// provided map. To avoid unnecessary copying of BitParts, BitParts are
3544/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
3545/// store BitParts objects, not pointers. As we need the concept of a nullptr
3546/// BitParts (Value has been analyzed and the analysis failed), we an Optional
3547/// type instead to provide the same functionality.
3548///
3549/// Because we pass around references into \c BPS, we must use a container that
3550/// does not invalidate internal references (std::map instead of DenseMap).
3551static const std::optional<BitPart> &
3552collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
3553 std::map<Value *, std::optional<BitPart>> &BPS, int Depth,
3554 bool &FoundRoot) {
3555 auto [I, Inserted] = BPS.try_emplace(k: V);
3556 if (!Inserted)
3557 return I->second;
3558
3559 auto &Result = I->second;
3560 auto BitWidth = V->getType()->getScalarSizeInBits();
3561
3562 // Can't do integer/elements > 128 bits.
3563 if (BitWidth > 128)
3564 return Result;
3565
3566 // Prevent stack overflow by limiting the recursion depth
3567 if (Depth == BitPartRecursionMaxDepth) {
3568 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
3569 return Result;
3570 }
3571
3572 if (auto *I = dyn_cast<Instruction>(Val: V)) {
3573 Value *X, *Y;
3574 const APInt *C;
3575
3576 // If this is an or instruction, it may be an inner node of the bswap.
3577 if (match(V, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3578 // Check we have both sources and they are from the same provider.
3579 const auto &A = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3580 Depth: Depth + 1, FoundRoot);
3581 if (!A || !A->Provider)
3582 return Result;
3583
3584 const auto &B = collectBitParts(V: Y, MatchBSwaps, MatchBitReversals, BPS,
3585 Depth: Depth + 1, FoundRoot);
3586 if (!B || A->Provider != B->Provider)
3587 return Result;
3588
3589 // Try and merge the two together.
3590 Result = BitPart(A->Provider, BitWidth);
3591 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
3592 if (A->Provenance[BitIdx] != BitPart::Unset &&
3593 B->Provenance[BitIdx] != BitPart::Unset &&
3594 A->Provenance[BitIdx] != B->Provenance[BitIdx])
3595 return Result = std::nullopt;
3596
3597 if (A->Provenance[BitIdx] == BitPart::Unset)
3598 Result->Provenance[BitIdx] = B->Provenance[BitIdx];
3599 else
3600 Result->Provenance[BitIdx] = A->Provenance[BitIdx];
3601 }
3602
3603 return Result;
3604 }
3605
3606 // If this is a logical shift by a constant, recurse then shift the result.
3607 if (match(V, P: m_LogicalShift(L: m_Value(V&: X), R: m_APInt(Res&: C)))) {
3608 const APInt &BitShift = *C;
3609
3610 // Ensure the shift amount is defined.
3611 if (BitShift.uge(RHS: BitWidth))
3612 return Result;
3613
3614 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3615 if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3616 return Result;
3617
3618 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3619 Depth: Depth + 1, FoundRoot);
3620 if (!Res)
3621 return Result;
3622 Result = Res;
3623
3624 // Perform the "shift" on BitProvenance.
3625 auto &P = Result->Provenance;
3626 if (I->getOpcode() == Instruction::Shl) {
3627 P.erase(CS: std::prev(x: P.end(), n: BitShift.getZExtValue()), CE: P.end());
3628 P.insert(I: P.begin(), NumToInsert: BitShift.getZExtValue(), Elt: BitPart::Unset);
3629 } else {
3630 P.erase(CS: P.begin(), CE: std::next(x: P.begin(), n: BitShift.getZExtValue()));
3631 P.insert(I: P.end(), NumToInsert: BitShift.getZExtValue(), Elt: BitPart::Unset);
3632 }
3633
3634 return Result;
3635 }
3636
3637 // If this is a logical 'and' with a mask that clears bits, recurse then
3638 // unset the appropriate bits.
3639 if (match(V, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C)))) {
3640 const APInt &AndMask = *C;
3641
3642 // Check that the mask allows a multiple of 8 bits for a bswap, for an
3643 // early exit.
3644 unsigned NumMaskedBits = AndMask.popcount();
3645 if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3646 return Result;
3647
3648 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3649 Depth: Depth + 1, FoundRoot);
3650 if (!Res)
3651 return Result;
3652 Result = Res;
3653
3654 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3655 // If the AndMask is zero for this bit, clear the bit.
3656 if (AndMask[BitIdx] == 0)
3657 Result->Provenance[BitIdx] = BitPart::Unset;
3658 return Result;
3659 }
3660
3661 // If this is a zext instruction zero extend the result.
3662 if (match(V, P: m_ZExt(Op: m_Value(V&: X)))) {
3663 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3664 Depth: Depth + 1, FoundRoot);
3665 if (!Res)
3666 return Result;
3667
3668 Result = BitPart(Res->Provider, BitWidth);
3669 auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3670 for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3671 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3672 for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3673 Result->Provenance[BitIdx] = BitPart::Unset;
3674 return Result;
3675 }
3676
3677 // If this is a truncate instruction, extract the lower bits.
3678 if (match(V, P: m_Trunc(Op: m_Value(V&: X)))) {
3679 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3680 Depth: Depth + 1, FoundRoot);
3681 if (!Res)
3682 return Result;
3683
3684 Result = BitPart(Res->Provider, BitWidth);
3685 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3686 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3687 return Result;
3688 }
3689
3690 // BITREVERSE - most likely due to us previous matching a partial
3691 // bitreverse.
3692 if (match(V, P: m_BitReverse(Op0: m_Value(V&: X)))) {
3693 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3694 Depth: Depth + 1, FoundRoot);
3695 if (!Res)
3696 return Result;
3697
3698 Result = BitPart(Res->Provider, BitWidth);
3699 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3700 Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3701 return Result;
3702 }
3703
3704 // BSWAP - most likely due to us previous matching a partial bswap.
3705 if (match(V, P: m_BSwap(Op0: m_Value(V&: X)))) {
3706 const auto &Res = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3707 Depth: Depth + 1, FoundRoot);
3708 if (!Res)
3709 return Result;
3710
3711 unsigned ByteWidth = BitWidth / 8;
3712 Result = BitPart(Res->Provider, BitWidth);
3713 for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3714 unsigned ByteBitOfs = ByteIdx * 8;
3715 for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3716 Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3717 Res->Provenance[ByteBitOfs + BitIdx];
3718 }
3719 return Result;
3720 }
3721
3722 // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3723 // amount (modulo).
3724 // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3725 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3726 if (match(V, P: m_FShl(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_APInt(Res&: C))) ||
3727 match(V, P: m_FShr(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_APInt(Res&: C)))) {
3728 // We can treat fshr as a fshl by flipping the modulo amount.
3729 unsigned ModAmt = C->urem(RHS: BitWidth);
3730 if (cast<IntrinsicInst>(Val: I)->getIntrinsicID() == Intrinsic::fshr)
3731 ModAmt = BitWidth - ModAmt;
3732
3733 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3734 if (!MatchBitReversals && (ModAmt % 8) != 0)
3735 return Result;
3736
3737 // Check we have both sources and they are from the same provider.
3738 const auto &LHS = collectBitParts(V: X, MatchBSwaps, MatchBitReversals, BPS,
3739 Depth: Depth + 1, FoundRoot);
3740 if (!LHS || !LHS->Provider)
3741 return Result;
3742
3743 const auto &RHS = collectBitParts(V: Y, MatchBSwaps, MatchBitReversals, BPS,
3744 Depth: Depth + 1, FoundRoot);
3745 if (!RHS || LHS->Provider != RHS->Provider)
3746 return Result;
3747
3748 unsigned StartBitRHS = BitWidth - ModAmt;
3749 Result = BitPart(LHS->Provider, BitWidth);
3750 for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3751 Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
3752 for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3753 Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
3754 return Result;
3755 }
3756 }
3757
3758 // If we've already found a root input value then we're never going to merge
3759 // these back together.
3760 if (FoundRoot)
3761 return Result;
3762
3763 // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
3764 // be the root input value to the bswap/bitreverse.
3765 FoundRoot = true;
3766 Result = BitPart(V, BitWidth);
3767 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3768 Result->Provenance[BitIdx] = BitIdx;
3769 return Result;
3770}
3771
3772static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
3773 unsigned BitWidth) {
3774 if (From % 8 != To % 8)
3775 return false;
3776 // Convert from bit indices to byte indices and check for a byte reversal.
3777 From >>= 3;
3778 To >>= 3;
3779 BitWidth >>= 3;
3780 return From == BitWidth - To - 1;
3781}
3782
3783static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
3784 unsigned BitWidth) {
3785 return From == BitWidth - To - 1;
3786}
3787
3788bool llvm::recognizeBSwapOrBitReverseIdiom(
3789 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
3790 SmallVectorImpl<Instruction *> &InsertedInsts) {
3791 if (!match(V: I, P: m_Or(L: m_Value(), R: m_Value())) &&
3792 !match(V: I, P: m_FShl(Op0: m_Value(), Op1: m_Value(), Op2: m_Value())) &&
3793 !match(V: I, P: m_FShr(Op0: m_Value(), Op1: m_Value(), Op2: m_Value())) &&
3794 !match(V: I, P: m_BSwap(Op0: m_Value())))
3795 return false;
3796 if (!MatchBSwaps && !MatchBitReversals)
3797 return false;
3798 Type *ITy = I->getType();
3799 if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() == 1 ||
3800 ITy->getScalarSizeInBits() > 128)
3801 return false; // Can't do integer/elements > 128 bits.
3802
3803 // Try to find all the pieces corresponding to the bswap.
3804 bool FoundRoot = false;
3805 std::map<Value *, std::optional<BitPart>> BPS;
3806 const auto &Res =
3807 collectBitParts(V: I, MatchBSwaps, MatchBitReversals, BPS, Depth: 0, FoundRoot);
3808 if (!Res)
3809 return false;
3810 ArrayRef<int8_t> BitProvenance = Res->Provenance;
3811 assert(all_of(BitProvenance,
3812 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
3813 "Illegal bit provenance index");
3814
3815 // If the upper bits are zero, then attempt to perform as a truncated op.
3816 Type *DemandedTy = ITy;
3817 if (BitProvenance.back() == BitPart::Unset) {
3818 while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
3819 BitProvenance = BitProvenance.drop_back();
3820 if (BitProvenance.empty())
3821 return false; // TODO - handle null value?
3822 DemandedTy = Type::getIntNTy(C&: I->getContext(), N: BitProvenance.size());
3823 if (auto *IVecTy = dyn_cast<VectorType>(Val: ITy))
3824 DemandedTy = VectorType::get(ElementType: DemandedTy, Other: IVecTy);
3825 }
3826
3827 // Check BitProvenance hasn't found a source larger than the result type.
3828 unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
3829 if (DemandedBW > ITy->getScalarSizeInBits())
3830 return false;
3831
3832 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
3833 // only byteswap values with an even number of bytes.
3834 APInt DemandedMask = APInt::getAllOnes(numBits: DemandedBW);
3835 bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
3836 bool OKForBitReverse = MatchBitReversals;
3837 for (unsigned BitIdx = 0;
3838 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
3839 if (BitProvenance[BitIdx] == BitPart::Unset) {
3840 DemandedMask.clearBit(BitPosition: BitIdx);
3841 continue;
3842 }
3843 OKForBSwap &= bitTransformIsCorrectForBSwap(From: BitProvenance[BitIdx], To: BitIdx,
3844 BitWidth: DemandedBW);
3845 OKForBitReverse &= bitTransformIsCorrectForBitReverse(From: BitProvenance[BitIdx],
3846 To: BitIdx, BitWidth: DemandedBW);
3847 }
3848
3849 Intrinsic::ID Intrin;
3850 if (OKForBSwap)
3851 Intrin = Intrinsic::bswap;
3852 else if (OKForBitReverse)
3853 Intrin = Intrinsic::bitreverse;
3854 else
3855 return false;
3856
3857 Function *F =
3858 Intrinsic::getOrInsertDeclaration(M: I->getModule(), id: Intrin, OverloadTys: DemandedTy);
3859 Value *Provider = Res->Provider;
3860
3861 // We may need to truncate the provider.
3862 if (DemandedTy != Provider->getType()) {
3863 auto *Trunc =
3864 CastInst::CreateIntegerCast(S: Provider, Ty: DemandedTy, isSigned: false, Name: "trunc", InsertBefore: I->getIterator());
3865 InsertedInsts.push_back(Elt: Trunc);
3866 Provider = Trunc;
3867 }
3868
3869 Instruction *Result = CallInst::Create(Func: F, Args: Provider, NameStr: "rev", InsertBefore: I->getIterator());
3870 InsertedInsts.push_back(Elt: Result);
3871
3872 if (!DemandedMask.isAllOnes()) {
3873 auto *Mask = ConstantInt::get(Ty: DemandedTy, V: DemandedMask);
3874 Result = BinaryOperator::Create(Op: Instruction::And, S1: Result, S2: Mask, Name: "mask", InsertBefore: I->getIterator());
3875 InsertedInsts.push_back(Elt: Result);
3876 }
3877
3878 // We may need to zeroextend back to the result type.
3879 if (ITy != Result->getType()) {
3880 auto *ExtInst = CastInst::CreateIntegerCast(S: Result, Ty: ITy, isSigned: false, Name: "zext", InsertBefore: I->getIterator());
3881 InsertedInsts.push_back(Elt: ExtInst);
3882 }
3883
3884 return true;
3885}
3886
3887// CodeGen has special handling for some string functions that may replace
3888// them with target-specific intrinsics. Since that'd skip our interceptors
3889// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
3890// we mark affected calls as NoBuiltin, which will disable optimization
3891// in CodeGen.
3892void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
3893 CallInst *CI, const TargetLibraryInfo *TLI) {
3894 Function *F = CI->getCalledFunction();
3895 if (F && !F->hasLocalLinkage() && F->hasName() &&
3896 TLI->hasOptimizedCodeGen(F: TLI->getLibFunc(funcName: F->getName())) &&
3897 !F->doesNotAccessMemory())
3898 CI->addFnAttr(Kind: Attribute::NoBuiltin);
3899}
3900
3901bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
3902 const auto *Op = I->getOperand(i: OpIdx);
3903 // We can't have a PHI with a metadata or token type.
3904 if (Op->getType()->isMetadataTy() || Op->getType()->isTokenLikeTy())
3905 return false;
3906
3907 // swifterror pointers can only be used by a load, store, or as a swifterror
3908 // argument; swifterror pointers are not allowed to be used in select or phi
3909 // instructions.
3910 if (Op->isSwiftError())
3911 return false;
3912
3913 // Cannot replace alloca argument with phi/select.
3914 if (I->isLifetimeStartOrEnd())
3915 return false;
3916
3917 // Early exit.
3918 if (!isa<Constant, InlineAsm>(Val: Op))
3919 return true;
3920
3921 switch (I->getOpcode()) {
3922 default:
3923 return true;
3924 case Instruction::Call:
3925 case Instruction::Invoke: {
3926 const auto &CB = cast<CallBase>(Val: *I);
3927
3928 // Can't handle inline asm. Skip it.
3929 if (CB.isInlineAsm())
3930 return false;
3931
3932 // Constant bundle operands may need to retain their constant-ness for
3933 // correctness.
3934 if (CB.isBundleOperand(Idx: OpIdx))
3935 return false;
3936
3937 if (OpIdx < CB.arg_size()) {
3938 // Some variadic intrinsics require constants in the variadic arguments,
3939 // which currently aren't markable as immarg.
3940 if (isa<IntrinsicInst>(Val: CB) &&
3941 OpIdx >= CB.getFunctionType()->getNumParams()) {
3942 // This is known to be OK for stackmap.
3943 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
3944 }
3945
3946 // gcroot is a special case, since it requires a constant argument which
3947 // isn't also required to be a simple ConstantInt.
3948 if (CB.getIntrinsicID() == Intrinsic::gcroot)
3949 return false;
3950
3951 // threadlocal_address is a special case as it requires its only
3952 // argument to be a thread local global.
3953 if (CB.getIntrinsicID() == Intrinsic::threadlocal_address)
3954 return false;
3955
3956 // Some intrinsic operands are required to be immediates.
3957 return !CB.paramHasAttr(ArgNo: OpIdx, Kind: Attribute::ImmArg);
3958 }
3959
3960 // It is never allowed to replace the call argument to an intrinsic, but it
3961 // may be possible for a call.
3962 return !isa<IntrinsicInst>(Val: CB);
3963 }
3964 case Instruction::ShuffleVector:
3965 // Shufflevector masks are constant.
3966 return OpIdx != 2;
3967 case Instruction::Switch:
3968 case Instruction::ExtractValue:
3969 // All operands apart from the first are constant.
3970 return OpIdx == 0;
3971 case Instruction::InsertValue:
3972 // All operands apart from the first and the second are constant.
3973 return OpIdx < 2;
3974 case Instruction::Alloca:
3975 // Static allocas (constant size in the entry block) are handled by
3976 // prologue/epilogue insertion so they're free anyway. We definitely don't
3977 // want to make them non-constant.
3978 return !cast<AllocaInst>(Val: I)->isStaticAlloca();
3979 case Instruction::GetElementPtr:
3980 if (OpIdx == 0)
3981 return true;
3982 gep_type_iterator It = gep_type_begin(GEP: I);
3983 for (auto E = std::next(x: It, n: OpIdx); It != E; ++It)
3984 if (It.isStruct())
3985 return false;
3986 return true;
3987 }
3988}
3989
3990Value *llvm::invertCondition(Value *Condition) {
3991 // First: Check if it's a constant
3992 if (Constant *C = dyn_cast<Constant>(Val: Condition))
3993 return ConstantExpr::getNot(C);
3994
3995 // Second: If the condition is already inverted, return the original value
3996 Value *NotCondition;
3997 if (match(V: Condition, P: m_Not(V: m_Value(V&: NotCondition))))
3998 return NotCondition;
3999
4000 BasicBlock *Parent = nullptr;
4001 Instruction *Inst = dyn_cast<Instruction>(Val: Condition);
4002 if (Inst)
4003 Parent = Inst->getParent();
4004 else if (Argument *Arg = dyn_cast<Argument>(Val: Condition))
4005 Parent = &Arg->getParent()->getEntryBlock();
4006 assert(Parent && "Unsupported condition to invert");
4007
4008 // Third: Check all the users for an invert
4009 for (User *U : Condition->users())
4010 if (Instruction *I = dyn_cast<Instruction>(Val: U))
4011 if (I->getParent() == Parent && match(V: I, P: m_Not(V: m_Specific(V: Condition))))
4012 return I;
4013
4014 // Last option: Create a new instruction
4015 auto *Inverted =
4016 BinaryOperator::CreateNot(Op: Condition, Name: Condition->getName() + ".inv");
4017 if (Inst && !isa<PHINode>(Val: Inst))
4018 Inverted->insertAfter(InsertPos: Inst->getIterator());
4019 else
4020 Inverted->insertBefore(InsertPos: Parent->getFirstInsertionPt());
4021 return Inverted;
4022}
4023
4024bool llvm::inferAttributesFromOthers(Function &F) {
4025 // Note: We explicitly check for attributes rather than using cover functions
4026 // because some of the cover functions include the logic being implemented.
4027
4028 bool Changed = false;
4029 // readnone + not convergent implies nosync
4030 if (!F.hasFnAttribute(Kind: Attribute::NoSync) &&
4031 F.doesNotAccessMemory() && !F.isConvergent()) {
4032 F.setNoSync();
4033 Changed = true;
4034 }
4035
4036 // readonly implies nofree
4037 if (!F.hasFnAttribute(Kind: Attribute::NoFree) && F.onlyReadsMemory()) {
4038 F.setDoesNotFreeMemory();
4039 Changed = true;
4040 }
4041
4042 // willreturn implies mustprogress
4043 if (!F.hasFnAttribute(Kind: Attribute::MustProgress) && F.willReturn()) {
4044 F.setMustProgress();
4045 Changed = true;
4046 }
4047
4048 // TODO: There are a bunch of cases of restrictive memory effects we
4049 // can infer by inspecting arguments of argmemonly-ish functions.
4050
4051 return Changed;
4052}
4053
4054void OverflowTracking::mergeFlags(Instruction &I) {
4055#ifndef NDEBUG
4056 if (Opcode)
4057 assert(Opcode == I.getOpcode() &&
4058 "can only use mergeFlags on instructions with matching opcodes");
4059 else
4060 Opcode = I.getOpcode();
4061#endif
4062 if (isa<OverflowingBinaryOperator>(Val: &I)) {
4063 HasNUW &= I.hasNoUnsignedWrap();
4064 HasNSW &= I.hasNoSignedWrap();
4065 }
4066 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
4067 IsDisjoint &= DisjointOp->isDisjoint();
4068}
4069
4070void OverflowTracking::applyFlags(Instruction &I) {
4071 I.dropPoisonGeneratingFlags();
4072 if (I.getOpcode() == Instruction::Add ||
4073 (I.getOpcode() == Instruction::Mul && AllKnownNonZero)) {
4074 if (HasNUW)
4075 I.setHasNoUnsignedWrap();
4076 if (HasNSW && (AllKnownNonNegative || HasNUW))
4077 I.setHasNoSignedWrap();
4078 }
4079 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
4080 DisjointOp->setIsDisjoint(IsDisjoint);
4081}
4082