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