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