LLVM 23.0.0git
Value.cpp
Go to the documentation of this file.
1//===-- Value.cpp - Implement the Value class -----------------------------===//
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 file implements the Value, ValueHandle, and User classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Value.h"
14#include "LLVMContextImpl.h"
15#include "llvm/ADT/DenseMap.h"
17#include "llvm/IR/Constant.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/DebugInfo.h"
22#include "llvm/IR/DerivedUser.h"
24#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
30#include "llvm/IR/ValueHandle.h"
35#include <algorithm>
36
37using namespace llvm;
38
40 "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
41 cl::desc("Deref attributes and metadata infer facts at definition only"));
42
43//===----------------------------------------------------------------------===//
44// Value Class
45//===----------------------------------------------------------------------===//
46static inline Type *checkType(Type *Ty) {
47 assert(Ty && "Value defined with a null type: Error!");
48 assert(!isa<TypedPointerType>(Ty->getScalarType()) &&
49 "Cannot have values with typed pointer types");
50 return Ty;
51}
52
53Value::Value(Type *ty, unsigned scid)
54 : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
55 SubclassData(0), NumUserOperands(0), IsUsedByMD(false), HasName(false),
56 VTy(checkType(ty)) {
57 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58 // FIXME: Why isn't this in the subclass gunk??
59 // Note, we cannot call isa<CallInst> before the CallInst has been
60 // constructed.
61 unsigned OpCode = 0;
62 if (SubclassID >= InstructionVal)
63 OpCode = SubclassID - InstructionVal;
64 if (OpCode == Instruction::Call || OpCode == Instruction::Invoke ||
65 OpCode == Instruction::CallBr)
66 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
67 "invalid CallBase type!");
68 else if (SubclassID != BasicBlockVal &&
69 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
70 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
71 "Cannot create non-first-class values except for constants!");
72 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
73 "Value too big");
74}
75
77 // Notify all ValueHandles (if present) that this value is going away.
78 if (HasValueHandle)
79 ValueHandleBase::ValueIsDeleted(this);
80 if (isUsedByMetadata())
81 ValueAsMetadata::handleDeletion(this);
82
83#ifndef NDEBUG // Only in -g mode...
84 // Check to make sure that there are no uses of this value that are still
85 // around when the value is destroyed. If there are, then we have a dangling
86 // reference and something is wrong. This code is here to print out where
87 // the value is still being referenced.
88 //
89 // Note that use_empty() cannot be called here, as it eventually downcasts
90 // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
91 // been destructed, so accessing it is UB.
92 //
93 if (!materialized_use_empty()) {
94 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
95 for (auto *U : users())
96 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
97
98 llvm_unreachable("Uses remain when a value is destroyed!");
99 }
100#endif
101
102 // If this value is named, destroy the name. This should not be in a symtab
103 // at this point.
104 destroyValueName();
105}
106
107void Value::deleteValue() {
108 switch (getValueID()) {
109#define HANDLE_VALUE(Name) \
110 case Value::Name##Val: \
111 delete static_cast<Name *>(this); \
112 break;
113#define HANDLE_MEMORY_VALUE(Name) \
114 case Value::Name##Val: \
115 static_cast<DerivedUser *>(this)->DeleteValue( \
116 static_cast<DerivedUser *>(this)); \
117 break;
118#define HANDLE_CONSTANT(Name) \
119 case Value::Name##Val: \
120 llvm_unreachable("constants should be destroyed with destroyConstant"); \
121 break;
122#define HANDLE_INSTRUCTION(Name) /* nothing */
123#include "llvm/IR/Value.def"
124
125#define HANDLE_INST(N, OPC, CLASS) \
126 case Value::InstructionVal + Instruction::OPC: \
127 delete static_cast<CLASS *>(this); \
128 break;
129#define HANDLE_USER_INST(N, OPC, CLASS)
130#include "llvm/IR/Instruction.def"
131
132 default:
133 llvm_unreachable("attempting to delete unknown value kind");
134 }
135}
136
137void Value::destroyValueName() {
138 ValueName *Name = getValueName();
139 if (Name) {
140 MallocAllocator Allocator;
141 Name->Destroy(Allocator);
142 }
143 setValueName(nullptr);
144}
145
146bool Value::hasNUses(unsigned N) const {
147 if (!UseList)
148 return N == 0;
149
150 // TODO: Disallow for ConstantData and remove !UseList check?
151 return hasNItems(use_begin(), use_end(), N);
152}
153
154bool Value::hasNUsesOrMore(unsigned N) const {
155 // TODO: Disallow for ConstantData and remove !UseList check?
156 if (!UseList)
157 return N == 0;
158
159 return hasNItemsOrMore(use_begin(), use_end(), N);
160}
161
162bool Value::hasOneUser() const {
163 if (use_empty())
164 return false;
165 if (hasOneUse())
166 return true;
167 return std::equal(++user_begin(), user_end(), user_begin());
168}
169
170static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
171
172Use *Value::getSingleUndroppableUse() {
173 Use *Result = nullptr;
174 for (Use &U : uses()) {
175 if (!U.getUser()->isDroppable()) {
176 if (Result)
177 return nullptr;
178 Result = &U;
179 }
180 }
181 return Result;
182}
183
184User *Value::getUniqueUndroppableUser() {
185 User *Result = nullptr;
186 for (auto *U : users()) {
187 if (!U->isDroppable()) {
188 if (Result && Result != U)
189 return nullptr;
190 Result = U;
191 }
192 }
193 return Result;
194}
195
196bool Value::hasNUndroppableUses(unsigned int N) const {
197 return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
198}
199
200bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
201 return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
202}
203
204void Value::dropDroppableUses(
205 llvm::function_ref<bool(const Use *)> ShouldDrop) {
206 SmallVector<Use *, 8> ToBeEdited;
207 for (Use &U : uses())
208 if (U.getUser()->isDroppable() && ShouldDrop(&U))
209 ToBeEdited.push_back(&U);
210 for (Use *U : ToBeEdited)
211 dropDroppableUse(*U);
212}
213
214void Value::dropDroppableUsesIn(User &Usr) {
215 assert(Usr.isDroppable() && "Expected a droppable user!");
216 for (Use &UsrOp : Usr.operands()) {
217 if (UsrOp.get() == this)
218 dropDroppableUse(UsrOp);
219 }
220}
221
222void Value::dropDroppableUse(Use &U) {
223 if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
224 unsigned OpNo = U.getOperandNo();
225 if (OpNo == 0)
226 U.set(ConstantInt::getTrue(Assume->getContext()));
227 else {
228 U.set(PoisonValue::get(U.get()->getType()));
229 CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
230 BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
231 }
232 return;
233 }
234
235 llvm_unreachable("unknown droppable use");
236}
237
238bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
239 assert(hasUseList() && "ConstantData has no use-list");
240
241 // This can be computed either by scanning the instructions in BB, or by
242 // scanning the use list of this Value. Both lists can be very long, but
243 // usually one is quite short.
244 //
245 // Scan both lists simultaneously until one is exhausted. This limits the
246 // search to the shorter list.
247 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
248 const_user_iterator UI = user_begin(), UE = user_end();
249 for (; BI != BE && UI != UE; ++BI, ++UI) {
250 // Scan basic block: Check if this Value is used by the instruction at BI.
251 if (is_contained(BI->operands(), this))
252 return true;
253 // Scan use list: Check if the use at UI is in BB.
254 const auto *User = dyn_cast<Instruction>(*UI);
255 if (User && User->getParent() == BB)
256 return true;
257 }
258 return false;
259}
260
261unsigned Value::getNumUses() const {
262 // TODO: Disallow for ConstantData and remove !UseList check?
263 if (!UseList)
264 return 0;
265 return (unsigned)std::distance(use_begin(), use_end());
266}
267
268static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
269 ST = nullptr;
270 if (Instruction *I = dyn_cast<Instruction>(V)) {
271 if (BasicBlock *P = I->getParent())
272 if (Function *PP = P->getParent())
273 ST = PP->getValueSymbolTable();
274 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
275 if (Function *P = BB->getParent())
276 ST = P->getValueSymbolTable();
277 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
278 if (Module *P = GV->getParent())
279 ST = &P->getValueSymbolTable();
280 } else if (Argument *A = dyn_cast<Argument>(V)) {
281 if (Function *P = A->getParent())
282 ST = P->getValueSymbolTable();
283 } else {
284 assert(isa<Constant>(V) && "Unknown value type!");
285 return true; // no name is setable for this.
286 }
287 return false;
288}
289
290ValueName *Value::getValueName() const {
291 if (!HasName) return nullptr;
292
293 LLVMContext &Ctx = getContext();
294 auto I = Ctx.pImpl->ValueNames.find(this);
295 assert(I != Ctx.pImpl->ValueNames.end() &&
296 "No name entry found!");
297
298 return I->second;
299}
300
301void Value::setValueName(ValueName *VN) {
302 LLVMContext &Ctx = getContext();
303
304 assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
305 "HasName bit out of sync!");
306
307 if (!VN) {
308 if (HasName)
309 Ctx.pImpl->ValueNames.erase(this);
310 HasName = false;
311 return;
312 }
313
314 HasName = true;
315 Ctx.pImpl->ValueNames[this] = VN;
316}
317
318StringRef Value::getName() const {
319 // Make sure the empty string is still a C string. For historical reasons,
320 // some clients want to call .data() on the result and expect it to be null
321 // terminated.
322 if (!hasName())
323 return StringRef("", 0);
324 return getValueName()->getKey();
325}
326
327void Value::setNameImpl(const Twine &NewName) {
328 bool NeedNewName =
329 !getContext().shouldDiscardValueNames() || isa<GlobalValue>(this);
330
331 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
332 // and there is no need to delete the old name.
333 if (!NeedNewName && !hasName())
334 return;
335
336 // Fast path for common IRBuilder case of setName("") when there is no name.
337 if (NewName.isTriviallyEmpty() && !hasName())
338 return;
339
340 SmallString<256> NameData;
341 StringRef NameRef = NeedNewName ? NewName.toStringRef(NameData) : "";
342 assert(!NameRef.contains(0) && "Null bytes are not allowed in names");
343
344 // Name isn't changing?
345 if (getName() == NameRef)
346 return;
347
348 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
349
350 // Get the symbol table to update for this object.
351 ValueSymbolTable *ST;
352 if (getSymTab(this, ST))
353 return; // Cannot set a name on this value (e.g. constant).
354
355 ValueName *NewValueName = nullptr;
356 if (!ST) { // No symbol table to update? Just do the change.
357 if (!NameRef.empty()) {
358 // Create the new name.
359 MallocAllocator Allocator;
360 NewValueName = ValueName::create(NameRef, Allocator);
361 }
362 // NOTE: Could optimize for the case the name is shrinking to not deallocate
363 // then reallocated.
364 destroyValueName();
365
366 if (NewValueName) {
367 assert(NeedNewName);
368 setValueName(NewValueName);
369 getValueName()->setValue(this);
370 }
371 return;
372 }
373
374 if (!NameRef.empty())
375 NewValueName = ST->createValueName(NameRef, this);
376
377 // NOTE: Could optimize for the case the name is shrinking to not deallocate
378 // then reallocated.
379 if (hasName()) {
380 // Remove old name.
381 ST->removeValueName(getValueName());
382 destroyValueName();
383
384 if (NameRef.empty())
385 return;
386 }
387
388 // Name is changing to something new.
389 assert(NeedNewName && NewValueName != nullptr);
390 setValueName(NewValueName);
391}
392
393void Value::setName(const Twine &NewName) {
394 setNameImpl(NewName);
395 if (Function *F = dyn_cast<Function>(this))
396 F->updateAfterNameChange();
397}
398
399void Value::takeName(Value *V) {
400 assert(V != this && "Illegal call to this->takeName(this)!");
401 ValueSymbolTable *ST = nullptr;
402 // If this value has a name, drop it.
403 if (hasName()) {
404 // Get the symtab this is in.
405 if (getSymTab(this, ST)) {
406 // We can't set a name on this value, but we need to clear V's name if
407 // it has one.
408 if (V->hasName()) V->setName("");
409 return; // Cannot set a name on this value (e.g. constant).
410 }
411
412 // Remove old name.
413 if (ST)
414 ST->removeValueName(getValueName());
415 destroyValueName();
416 }
417
418 // Now we know that this has no name.
419
420 // If V has no name either, we're done.
421 if (!V->hasName()) return;
422
423 // Get this's symtab if we didn't before.
424 if (!ST) {
425 if (getSymTab(this, ST)) {
426 // Clear V's name.
427 V->setName("");
428 return; // Cannot set a name on this value (e.g. constant).
429 }
430 }
431
432 // Get V's ST, this should always succeed, because V has a name.
433 ValueSymbolTable *VST;
434 bool Failure = getSymTab(V, VST);
435 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
436
437 // If these values are both in the same symtab, we can do this very fast.
438 // This works even if both values have no symtab yet.
439 if (ST == VST) {
440 // Take the name!
441 setValueName(V->getValueName());
442 V->setValueName(nullptr);
443 getValueName()->setValue(this);
444 return;
445 }
446
447 // Otherwise, things are slightly more complex. Remove V's name from VST and
448 // then reinsert it into ST.
449
450 if (VST)
451 VST->removeValueName(V->getValueName());
452 setValueName(V->getValueName());
453 V->setValueName(nullptr);
454 getValueName()->setValue(this);
455
456 if (ST)
457 ST->reinsertValue(this);
458}
459
460std::string Value::getNameOrAsOperand() const {
461 if (!getName().empty())
462 return std::string(getName());
463
464 std::string BBName;
465 raw_string_ostream OS(BBName);
466 printAsOperand(OS, false);
467 return OS.str();
468}
469
470void Value::assertModuleIsMaterializedImpl() const {
471#ifndef NDEBUG
472 const GlobalValue *GV = dyn_cast<GlobalValue>(this);
473 if (!GV)
474 return;
475 const Module *M = GV->getParent();
476 if (!M)
477 return;
478 assert(M->isMaterialized());
479#endif
480}
481
482#ifndef NDEBUG
483static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
484 Constant *C) {
485 if (!Cache.insert(Expr).second)
486 return false;
487
488 for (auto &O : Expr->operands()) {
489 if (O == C)
490 return true;
491 auto *CE = dyn_cast<ConstantExpr>(O);
492 if (!CE)
493 continue;
494 if (contains(Cache, CE, C))
495 return true;
496 }
497 return false;
498}
499
500static bool contains(Value *Expr, Value *V) {
501 if (Expr == V)
502 return true;
503
504 auto *C = dyn_cast<Constant>(V);
505 if (!C)
506 return false;
507
508 auto *CE = dyn_cast<ConstantExpr>(Expr);
509 if (!CE)
510 return false;
511
512 SmallPtrSet<ConstantExpr *, 4> Cache;
513 return contains(Cache, CE, C);
514}
515#endif // NDEBUG
516
517void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
518 assert(hasUseList() && "Cannot replace constant data");
519 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
520 assert(!contains(New, this) &&
521 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
522 assert(New->getType() == getType() &&
523 "replaceAllUses of value with new value of different type!");
524
525 // Notify all ValueHandles (if present) that this value is going away.
526 if (HasValueHandle)
527 ValueHandleBase::ValueIsRAUWd(this, New);
528 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
529 ValueAsMetadata::handleRAUW(this, New);
530
531 while (!materialized_use_empty()) {
532 Use &U = *UseList;
533 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
534 // constant because they are uniqued.
535 if (auto *C = dyn_cast<Constant>(U.getUser())) {
536 if (!isa<GlobalValue>(C)) {
537 C->handleOperandChange(this, New);
538 continue;
539 }
540 }
541
542 U.set(New);
543 }
544
545 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
546 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
547}
548
549void Value::replaceAllUsesWith(Value *New) {
550 doRAUW(New, ReplaceMetadataUses::Yes);
551}
552
553void Value::replaceNonMetadataUsesWith(Value *New) {
554 doRAUW(New, ReplaceMetadataUses::No);
555}
556
557bool Value::replaceUsesWithIf(Value *New,
558 llvm::function_ref<bool(Use &U)> ShouldReplace) {
559 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
560 assert(New->getType() == getType() &&
561 "replaceUses of value with new value of different type!");
562
563 SmallVector<TrackingVH<Constant>, 8> Consts;
564 SmallPtrSet<Constant *, 8> Visited;
565
566 bool Changed = false;
567 for (Use &U : llvm::make_early_inc_range(uses())) {
568 if (!ShouldReplace(U))
569 continue;
570 Changed = true;
571
572 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
573 // constant because they are uniqued.
574 if (auto *C = dyn_cast<Constant>(U.getUser())) {
575 if (!isa<GlobalValue>(C)) {
576 if (Visited.insert(C).second)
577 Consts.push_back(TrackingVH<Constant>(C));
578 continue;
579 }
580 }
581 U.set(New);
582 }
583
584 while (!Consts.empty()) {
585 // FIXME: handleOperandChange() updates all the uses in a given Constant,
586 // not just the one passed to ShouldReplace
587 Consts.pop_back_val()->handleOperandChange(this, New);
588 }
589
590 return Changed;
591}
592
593/// Replace debug record uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
594/// with New.
595static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
596 SmallVector<DbgVariableRecord *> DPUsers;
597 findDbgUsers(V, DPUsers);
598 for (auto *DVR : DPUsers) {
599 DbgMarker *Marker = DVR->getMarker();
600 if (Marker->getParent() != BB)
601 DVR->replaceVariableLocationOp(V, New);
602 }
603}
604
605// Like replaceAllUsesWith except it does not handle constants or basic blocks.
606// This routine leaves uses within BB.
607void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
608 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
609 assert(!contains(New, this) &&
610 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
611 assert(New->getType() == getType() &&
612 "replaceUses of value with new value of different type!");
613 assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
614
615 replaceDbgUsesOutsideBlock(this, New, BB);
616 replaceUsesWithIf(New, [BB](Use &U) {
617 auto *I = dyn_cast<Instruction>(U.getUser());
618 // Don't replace if it's an instruction in the BB basic block.
619 return !I || I->getParent() != BB;
620 });
621}
622
623namespace {
624// Various metrics for how much to strip off of pointers.
625enum PointerStripKind {
626 PSK_ZeroIndices,
627 PSK_ZeroIndicesAndAliases,
628 PSK_ZeroIndicesSameRepresentation,
629 PSK_ForAliasAnalysis,
630 PSK_InBoundsConstantIndices,
631 PSK_InBounds
632};
633} // end anonymous namespace
634
635template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
636
637template <PointerStripKind StripKind>
639 const Value *V,
640 function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
641 if (!V->getType()->isPointerTy())
642 return V;
643
644 // Even though we don't look through PHI nodes, we could be called on an
645 // instruction in an unreachable block, which may be on a cycle.
646 SmallPtrSet<const Value *, 4> Visited;
647
648 Visited.insert(V);
649 do {
650 Func(V);
651 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
652 switch (StripKind) {
653 case PSK_ZeroIndices:
654 case PSK_ZeroIndicesAndAliases:
655 case PSK_ZeroIndicesSameRepresentation:
656 case PSK_ForAliasAnalysis:
657 if (!GEP->hasAllZeroIndices())
658 return V;
659 break;
660 case PSK_InBoundsConstantIndices:
661 if (!GEP->hasAllConstantIndices())
662 return V;
663 [[fallthrough]];
664 case PSK_InBounds:
665 if (!GEP->isInBounds())
666 return V;
667 break;
668 }
669 V = GEP->getPointerOperand();
670 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
671 Value *NewV = cast<Operator>(V)->getOperand(0);
672 if (!NewV->getType()->isPointerTy())
673 return V;
674 V = NewV;
675 } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
676 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
677 // TODO: If we know an address space cast will not change the
678 // representation we could look through it here as well.
679 V = cast<Operator>(V)->getOperand(0);
680 } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
681 V = cast<GlobalAlias>(V)->getAliasee();
682 } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
683 cast<PHINode>(V)->getNumIncomingValues() == 1) {
684 V = cast<PHINode>(V)->getIncomingValue(0);
685 } else {
686 if (const auto *Call = dyn_cast<CallBase>(V)) {
687 if (const Value *RV = Call->getReturnedArgOperand()) {
688 V = RV;
689 continue;
690 }
691 // The result of launder.invariant.group must alias it's argument,
692 // but it can't be marked with returned attribute, that's why it needs
693 // special case.
694 if (StripKind == PSK_ForAliasAnalysis &&
695 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
696 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
697 V = Call->getArgOperand(0);
698 continue;
699 }
700 }
701 return V;
702 }
703 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
704 } while (Visited.insert(V).second);
705
706 return V;
707}
708
709const Value *Value::stripPointerCasts() const {
711}
712
713const Value *Value::stripPointerCastsAndAliases() const {
715}
716
717const Value *Value::stripPointerCastsSameRepresentation() const {
719}
720
721const Value *Value::stripInBoundsConstantOffsets() const {
723}
724
725const Value *Value::stripPointerCastsForAliasAnalysis() const {
727}
728
729const Value *Value::stripAndAccumulateConstantOffsets(
730 const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
731 bool AllowInvariantGroup,
732 function_ref<bool(Value &, APInt &)> ExternalAnalysis,
733 bool LookThroughIntToPtr) const {
734 if (!getType()->isPtrOrPtrVectorTy())
735 return this;
736
737 unsigned BitWidth = Offset.getBitWidth();
738 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
739 "The offset bit width does not match the DL specification.");
740
741 // Even though we don't look through PHI nodes, we could be called on an
742 // instruction in an unreachable block, which may be on a cycle.
743 SmallPtrSet<const Value *, 4> Visited;
744 Visited.insert(this);
745 const Value *V = this;
746 do {
747 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
748 // If in-bounds was requested, we do not strip non-in-bounds GEPs.
749 if (!AllowNonInbounds && !GEP->isInBounds())
750 return V;
751
752 // If one of the values we have visited is an addrspacecast, then
753 // the pointer type of this GEP may be different from the type
754 // of the Ptr parameter which was passed to this function. This
755 // means when we construct GEPOffset, we need to use the size
756 // of GEP's pointer type rather than the size of the original
757 // pointer type.
758 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
759 if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
760 return V;
761
762 // Stop traversal if the pointer offset wouldn't fit in the bit-width
763 // provided by the Offset argument. This can happen due to AddrSpaceCast
764 // stripping.
765 if (GEPOffset.getSignificantBits() > BitWidth)
766 return V;
767
768 // External Analysis can return a result higher/lower than the value
769 // represents. We need to detect overflow/underflow.
770 APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
771 if (!ExternalAnalysis) {
772 Offset += GEPOffsetST;
773 } else {
774 bool Overflow = false;
775 APInt OldOffset = Offset;
776 Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
777 if (Overflow) {
778 Offset = std::move(OldOffset);
779 return V;
780 }
781 }
782 V = GEP->getPointerOperand();
783 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
784 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
785 V = cast<Operator>(V)->getOperand(0);
786 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
787 if (!GA->isInterposable())
788 V = GA->getAliasee();
789 } else if (const auto *Call = dyn_cast<CallBase>(V)) {
790 if (const Value *RV = Call->getReturnedArgOperand())
791 V = RV;
792 if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup())
793 V = Call->getArgOperand(0);
794 } else if (auto *Int2Ptr = dyn_cast<Operator>(V)) {
795 // Try to accumulate across (inttoptr (add (ptrtoint p), off)).
796 if (!AllowNonInbounds || !LookThroughIntToPtr || !Int2Ptr ||
797 Int2Ptr->getOpcode() != Instruction::IntToPtr ||
798 Int2Ptr->getOperand(0)->getType()->getScalarSizeInBits() != BitWidth)
799 return V;
800
801 auto *Add = dyn_cast<AddOperator>(Int2Ptr->getOperand(0));
802 if (!Add)
803 return V;
804
805 auto *Ptr2Int = dyn_cast<PtrToIntOperator>(Add->getOperand(0));
806 auto *CI = dyn_cast<ConstantInt>(Add->getOperand(1));
807 if (!Ptr2Int || !CI)
808 return V;
809
810 Offset += CI->getValue();
811 V = Ptr2Int->getOperand(0);
812 }
813 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
814 } while (Visited.insert(V).second);
815
816 return V;
817}
818
819const Value *
820Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
822}
823
824bool Value::canBeFreed() const {
826
827 // Cases that can simply never be deallocated
828 // *) Constants aren't allocated per se, thus not deallocated either.
829 if (isa<Constant>(this))
830 return false;
831
832 // Handle byval/byref/sret/inalloca/preallocated arguments. The storage
833 // lifetime is guaranteed to be longer than the callee's lifetime.
834 if (auto *A = dyn_cast<Argument>(this)) {
835 if (A->hasPointeeInMemoryValueAttr())
836 return false;
837 // A pointer to an object in a function which neither frees, nor can arrange
838 // for another thread to free on its behalf, can not be freed in the scope
839 // of the function. Note that this logic is restricted to memory
840 // allocations in existance before the call; a nofree function *is* allowed
841 // to free memory it allocated.
842 const Function *F = A->getParent();
843 if (F->doesNotFreeMemory() && F->hasNoSync())
844 return false;
845 }
846
847 if (auto *ITP = dyn_cast<IntToPtrInst>(this);
848 ITP && ITP->hasMetadata(LLVMContext::MD_nofree))
849 return false;
850
851 const Function *F = nullptr;
852 if (auto *I = dyn_cast<Instruction>(this))
853 F = I->getFunction();
854 if (auto *A = dyn_cast<Argument>(this))
855 F = A->getParent();
856
857 if (!F)
858 return true;
859
860 // With garbage collection, deallocation typically occurs solely at or after
861 // safepoints. If we're compiling for a collector which uses the
862 // gc.statepoint infrastructure, safepoints aren't explicitly present
863 // in the IR until after lowering from abstract to physical machine model.
864 // The collector could chose to mix explicit deallocation and gc'd objects
865 // which is why we need the explicit opt in on a per collector basis.
866 if (!F->hasGC())
867 return true;
868
869 const auto &GCName = F->getGC();
870 if (GCName == "statepoint-example") {
871 auto *PT = cast<PointerType>(this->getType());
872 if (PT->getAddressSpace() != 1)
873 // For the sake of this example GC, we arbitrarily pick addrspace(1) as
874 // our GC managed heap. This must match the same check in
875 // RewriteStatepointsForGC (and probably needs better factored.)
876 return true;
877
878 // It is cheaper to scan for a declaration than to scan for a use in this
879 // function. Note that gc.statepoint is a type overloaded function so the
880 // usual trick of requesting declaration of the intrinsic from the module
881 // doesn't work.
882 for (auto &Fn : *F->getParent())
883 if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
884 return true;
885 return false;
886 }
887 return true;
888}
889
890uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
891 bool &CanBeNull,
892 bool &CanBeFreed) const {
893 assert(getType()->isPointerTy() && "must be pointer");
894
895 uint64_t DerefBytes = 0;
896 CanBeNull = false;
897 CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
898 if (const Argument *A = dyn_cast<Argument>(this)) {
899 DerefBytes = A->getDereferenceableBytes();
900 if (DerefBytes == 0) {
901 // Handle byval/byref/inalloca/preallocated arguments
902 if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
903 if (ArgMemTy->isSized()) {
904 // FIXME: Why isn't this the type alloc size?
905 DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinValue();
906 }
907 }
908 }
909
910 if (DerefBytes == 0) {
911 DerefBytes = A->getDereferenceableOrNullBytes();
912 CanBeNull = true;
913 }
914 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
915 DerefBytes = Call->getRetDereferenceableBytes();
916 if (DerefBytes == 0) {
917 DerefBytes = Call->getRetDereferenceableOrNullBytes();
918 CanBeNull = true;
919 }
920 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
921 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
922 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
923 DerefBytes = CI->getLimitedValue();
924 }
925 if (DerefBytes == 0) {
926 if (MDNode *MD =
927 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
928 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
929 DerefBytes = CI->getLimitedValue();
930 }
931 CanBeNull = true;
932 }
933 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
934 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
935 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
936 DerefBytes = CI->getLimitedValue();
937 }
938 if (DerefBytes == 0) {
939 if (MDNode *MD =
940 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
941 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
942 DerefBytes = CI->getLimitedValue();
943 }
944 CanBeNull = true;
945 }
946 } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
947 if (std::optional<TypeSize> Size = AI->getAllocationSize(DL)) {
948 DerefBytes = Size->getKnownMinValue();
949 CanBeNull = false;
950 CanBeFreed = false;
951 }
952 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
953 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
954 // TODO: Don't outright reject hasExternalWeakLinkage but set the
955 // CanBeNull flag.
956 DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedValue();
957 CanBeNull = false;
958 CanBeFreed = false;
959 }
960 }
961 return DerefBytes;
962}
963
964Align Value::getPointerAlignment(const DataLayout &DL) const {
965 assert(getType()->isPointerTy() && "must be pointer");
966 if (const Function *F = dyn_cast<Function>(this)) {
967 Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
968 switch (DL.getFunctionPtrAlignType()) {
969 case DataLayout::FunctionPtrAlignType::Independent:
970 return FunctionPtrAlign;
971 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
972 return std::max(FunctionPtrAlign, F->getAlign().valueOrOne());
973 }
974 llvm_unreachable("Unhandled FunctionPtrAlignType");
975 } else if (auto *GVar = dyn_cast<GlobalVariable>(this)) {
976 const MaybeAlign Alignment(GVar->getAlign());
977 if (!Alignment) {
978 Type *ObjectType = GVar->getValueType();
979 if (ObjectType->isSized()) {
980 // If the object is defined in the current Module, we'll be giving
981 // it the preferred alignment. Otherwise, we have to assume that it
982 // may only have the minimum ABI alignment.
983 if (GVar->isStrongDefinitionForLinker())
984 return DL.getPreferredAlign(GVar);
985 else
986 return DL.getABITypeAlign(ObjectType);
987 }
988 }
989 return Alignment.valueOrOne();
990 } else if (const Argument *A = dyn_cast<Argument>(this)) {
991 const MaybeAlign Alignment = A->getParamAlign();
992 if (!Alignment && A->hasStructRetAttr()) {
993 // An sret parameter has at least the ABI alignment of the return type.
994 Type *EltTy = A->getParamStructRetType();
995 if (EltTy->isSized())
996 return DL.getABITypeAlign(EltTy);
997 }
998 return Alignment.valueOrOne();
999 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
1000 return AI->getAlign();
1001 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
1002 MaybeAlign Alignment = Call->getRetAlign();
1003 if (!Alignment && Call->getCalledFunction())
1004 Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
1005 return Alignment.valueOrOne();
1006 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
1007 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
1008 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
1009 return Align(CI->getLimitedValue());
1010 }
1011 } else if (auto *CE = dyn_cast<ConstantExpr>(this)) {
1012 // Determine the alignment of inttoptr(C).
1013 if (CE->getOpcode() == Instruction::IntToPtr &&
1014 isa<ConstantInt>(CE->getOperand(0))) {
1015 ConstantInt *IntPtr = cast<ConstantInt>(CE->getOperand(0));
1016 size_t TrailingZeros = IntPtr->getValue().countr_zero();
1017 // While the actual alignment may be large, elsewhere we have
1018 // an arbitrary upper alignmet limit, so let's clamp to it.
1019 return Align(TrailingZeros < Value::MaxAlignmentExponent
1020 ? uint64_t(1) << TrailingZeros
1021 : Value::MaximumAlignment);
1022 }
1023 }
1024 return Align(1);
1025}
1026
1027static std::optional<int64_t>
1028getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
1029 // Skip over the first indices.
1031 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1032 /*skip along*/;
1033
1034 // Compute the offset implied by the rest of the indices.
1035 int64_t Offset = 0;
1036 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1037 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1038 if (!OpC)
1039 return std::nullopt;
1040 if (OpC->isZero())
1041 continue; // No offset.
1042
1043 // Handle struct indices, which add their field offset to the pointer.
1044 if (StructType *STy = GTI.getStructTypeOrNull()) {
1045 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1046 continue;
1047 }
1048
1049 // Otherwise, we have a sequential type like an array or fixed-length
1050 // vector. Multiply the index by the ElementSize.
1051 TypeSize Size = GTI.getSequentialElementStride(DL);
1052 if (Size.isScalable())
1053 return std::nullopt;
1054 Offset += Size.getFixedValue() * OpC->getSExtValue();
1055 }
1056
1057 return Offset;
1058}
1059
1060std::optional<int64_t> Value::getPointerOffsetFrom(const Value *Other,
1061 const DataLayout &DL) const {
1062 const Value *Ptr1 = Other;
1063 const Value *Ptr2 = this;
1064 APInt Offset1(DL.getIndexTypeSizeInBits(Ptr1->getType()), 0);
1065 APInt Offset2(DL.getIndexTypeSizeInBits(Ptr2->getType()), 0);
1066 Ptr1 = Ptr1->stripAndAccumulateConstantOffsets(DL, Offset1, true);
1067 Ptr2 = Ptr2->stripAndAccumulateConstantOffsets(DL, Offset2, true);
1068
1069 // Handle the trivial case first.
1070 if (Ptr1 == Ptr2)
1071 return Offset2.getSExtValue() - Offset1.getSExtValue();
1072
1073 const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
1074 const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
1075
1076 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1077 // base. After that base, they may have some number of common (and
1078 // potentially variable) indices. After that they handle some constant
1079 // offset, which determines their offset from each other. At this point, we
1080 // handle no other case.
1081 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0) ||
1082 GEP1->getSourceElementType() != GEP2->getSourceElementType())
1083 return std::nullopt;
1084
1085 // Skip any common indices and track the GEP types.
1086 unsigned Idx = 1;
1087 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1088 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1089 break;
1090
1091 auto IOffset1 = getOffsetFromIndex(GEP1, Idx, DL);
1092 auto IOffset2 = getOffsetFromIndex(GEP2, Idx, DL);
1093 if (!IOffset1 || !IOffset2)
1094 return std::nullopt;
1095 return *IOffset2 - *IOffset1 + Offset2.getSExtValue() -
1096 Offset1.getSExtValue();
1097}
1098
1099const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
1100 const BasicBlock *PredBB) const {
1101 auto *PN = dyn_cast<PHINode>(this);
1102 if (PN && PN->getParent() == CurBB)
1103 return PN->getIncomingValueForBlock(PredBB);
1104 return this;
1105}
1106
1107void Value::reverseUseList() {
1108 if (!UseList || !UseList->Next)
1109 // No need to reverse 0 or 1 uses.
1110 return;
1111
1112 Use *Head = UseList;
1113 Use *Current = UseList->Next;
1114 Head->Next = nullptr;
1115 while (Current) {
1116 Use *Next = Current->Next;
1117 Current->Next = Head;
1118 Head->Prev = &Current->Next;
1119 Head = Current;
1120 Current = Next;
1121 }
1122 UseList = Head;
1123 Head->Prev = &UseList;
1124}
1125
1126bool Value::isSwiftError() const {
1127 auto *Arg = dyn_cast<Argument>(this);
1128 if (Arg)
1129 return Arg->hasSwiftErrorAttr();
1130 auto *Alloca = dyn_cast<AllocaInst>(this);
1131 if (!Alloca)
1132 return false;
1133 return Alloca->isSwiftError();
1134}
1135
1136//===----------------------------------------------------------------------===//
1137// ValueHandleBase Class
1138//===----------------------------------------------------------------------===//
1139
1140void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
1141 assert(List && "Handle list is null?");
1142
1143 // Splice ourselves into the list.
1144 Next = *List;
1145 *List = this;
1146 setPrevPtr(List);
1147 if (Next) {
1148 Next->setPrevPtr(&Next);
1149 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
1150 }
1151}
1152
1153void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
1154 assert(List && "Must insert after existing node");
1155
1156 Next = List->Next;
1157 setPrevPtr(&List->Next);
1158 List->Next = this;
1159 if (Next)
1160 Next->setPrevPtr(&Next);
1161}
1162
1163void ValueHandleBase::AddToUseList() {
1164 assert(getValPtr() && "Null pointer doesn't have a use list!");
1165
1166 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1167
1168 if (getValPtr()->HasValueHandle) {
1169 // If this value already has a ValueHandle, then it must be in the
1170 // ValueHandles map already.
1171 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
1172 assert(Entry && "Value doesn't have any handles?");
1173 AddToExistingUseList(&Entry);
1174 return;
1175 }
1176
1177 // Ok, it doesn't have any handles yet, so we must insert it into the
1178 // DenseMap. However, doing this insertion could cause the DenseMap to
1179 // reallocate itself, which would invalidate all of the PrevP pointers that
1180 // point into the old table. Handle this by checking for reallocation and
1181 // updating the stale pointers only if needed.
1182 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1183 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1184
1185 ValueHandleBase *&Entry = Handles[getValPtr()];
1186 assert(!Entry && "Value really did already have handles?");
1187 AddToExistingUseList(&Entry);
1188 getValPtr()->HasValueHandle = true;
1189
1190 // If reallocation didn't happen or if this was the first insertion, don't
1191 // walk the table.
1192 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1193 Handles.size() == 1) {
1194 return;
1195 }
1196
1197 // Okay, reallocation did happen. Fix the Prev Pointers.
1198 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
1199 E = Handles.end(); I != E; ++I) {
1200 assert(I->second && I->first == I->second->getValPtr() &&
1201 "List invariant broken!");
1202 I->second->setPrevPtr(&I->second);
1203 }
1204}
1205
1206void ValueHandleBase::RemoveFromUseList() {
1207 assert(getValPtr() && getValPtr()->HasValueHandle &&
1208 "Pointer doesn't have a use list!");
1209
1210 // Unlink this from its use list.
1211 ValueHandleBase **PrevPtr = getPrevPtr();
1212 assert(*PrevPtr == this && "List invariant broken");
1213
1214 *PrevPtr = Next;
1215 if (Next) {
1216 assert(Next->getPrevPtr() == &Next && "List invariant broken");
1217 Next->setPrevPtr(PrevPtr);
1218 return;
1219 }
1220
1221 // If the Next pointer was null, then it is possible that this was the last
1222 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
1223 // map.
1224 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1225 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1226 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
1227 Handles.erase(getValPtr());
1228 getValPtr()->HasValueHandle = false;
1229 }
1230}
1231
1232void ValueHandleBase::ValueIsDeleted(Value *V) {
1233 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1234
1235 // Get the linked list base, which is guaranteed to exist since the
1236 // HasValueHandle flag is set.
1237 LLVMContextImpl *pImpl = V->getContext().pImpl;
1238 ValueHandleBase *Entry = pImpl->ValueHandles[V];
1239 assert(Entry && "Value bit set but no entries exist");
1240
1241 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1242 // and remove themselves from the list without breaking our iteration. This
1243 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1244 // Note that we deliberately do not the support the case when dropping a value
1245 // handle results in a new value handle being permanently added to the list
1246 // (as might occur in theory for CallbackVH's): the new value handle will not
1247 // be processed and the checking code will mete out righteous punishment if
1248 // the handle is still present once we have finished processing all the other
1249 // value handles (it is fine to momentarily add then remove a value handle).
1250 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1251 Iterator.RemoveFromUseList();
1252 Iterator.AddToExistingUseListAfter(Entry);
1253 assert(Entry->Next == &Iterator && "Loop invariant broken.");
1254
1255 switch (Entry->getKind()) {
1256 case Assert:
1257 break;
1258 case Weak:
1259 case WeakTracking:
1260 // WeakTracking and Weak just go to null, which unlinks them
1261 // from the list.
1262 Entry->operator=(nullptr);
1263 break;
1264 case Callback:
1265 // Forward to the subclass's implementation.
1266 static_cast<CallbackVH*>(Entry)->deleted();
1267 break;
1268 }
1269 }
1270
1271 // All callbacks, weak references, and assertingVHs should be dropped by now.
1272 if (V->HasValueHandle) {
1273#ifndef NDEBUG // Only in +Asserts mode...
1274 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1275 << "\n";
1276 if (pImpl->ValueHandles[V]->getKind() == Assert)
1277 llvm_unreachable("An asserting value handle still pointed to this"
1278 " value!");
1279
1280#endif
1281 llvm_unreachable("All references to V were not removed?");
1282 }
1283}
1284
1285void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1286 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1287 assert(Old != New && "Changing value into itself!");
1288 assert(Old->getType() == New->getType() &&
1289 "replaceAllUses of value with new value of different type!");
1290
1291 // Get the linked list base, which is guaranteed to exist since the
1292 // HasValueHandle flag is set.
1293 LLVMContextImpl *pImpl = Old->getContext().pImpl;
1294 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1295
1296 assert(Entry && "Value bit set but no entries exist");
1297
1298 // We use a local ValueHandleBase as an iterator so that
1299 // ValueHandles can add and remove themselves from the list without
1300 // breaking our iteration. This is not really an AssertingVH; we
1301 // just have to give ValueHandleBase some kind.
1302 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1303 Iterator.RemoveFromUseList();
1304 Iterator.AddToExistingUseListAfter(Entry);
1305 assert(Entry->Next == &Iterator && "Loop invariant broken.");
1306
1307 switch (Entry->getKind()) {
1308 case Assert:
1309 case Weak:
1310 // Asserting and Weak handles do not follow RAUW implicitly.
1311 break;
1312 case WeakTracking:
1313 // Weak goes to the new value, which will unlink it from Old's list.
1314 Entry->operator=(New);
1315 break;
1316 case Callback:
1317 // Forward to the subclass's implementation.
1318 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1319 break;
1320 }
1321 }
1322
1323#ifndef NDEBUG
1324 // If any new weak value handles were added while processing the
1325 // list, then complain about it now.
1326 if (Old->HasValueHandle)
1327 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1328 switch (Entry->getKind()) {
1329 case WeakTracking:
1330 dbgs() << "After RAUW from " << *Old->getType() << " %"
1331 << Old->getName() << " to " << *New->getType() << " %"
1332 << New->getName() << "\n";
1334 "A weak tracking value handle still pointed to the old value!\n");
1335 default:
1336 break;
1337 }
1338#endif
1339}
1340
1341// Pin the vtable to this file.
1342void CallbackVH::anchor() {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
iv users
Definition IVUsers.cpp:48
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
const uint64_t BitWidth
#define P(N)
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
Basic Register Allocator
static std::optional< int64_t > getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL)
Definition Value.cpp:1028
static void NoopCallback(const Value *)
Definition Value.cpp:635
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
static cl::opt< bool > UseDerefAtPointSemantics("use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false), cl::desc("Deref attributes and metadata infer facts at definition only"))
static Type * checkType(Type *Ty)
Definition Value.cpp:46
static bool getSymTab(Value *V, ValueSymbolTable *&ST)
Definition Value.cpp:268
static const Value * stripPointerCastsAndOffsets(const Value *V, function_ref< void(const Value *)> Func=NoopCallback< StripKind >)
Definition Value.cpp:638
static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB)
Replace debug record uses of MetadataAsValue(ValueAsMetadata(V)) outside BB with New.
Definition Value.cpp:595
static bool isUnDroppableUser(const User *U)
Definition Value.cpp:170
This file defines the SmallString class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1654
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
LLVM_ABI const BasicBlock * getParent() const
bool erase(const KeyT &Val)
Definition DenseMap.h:330
unsigned size() const
Definition DenseMap.h:110
iterator begin()
Definition DenseMap.h:78
iterator end()
Definition DenseMap.h:81
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the DenseMap's...
Definition DenseMap.h:360
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition DenseMap.h:367
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:82
bool hasExternalWeakLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
Type * getValueType() const
DenseMap< const Value *, ValueName * > ValueNames
ValueHandlesTy ValueHandles
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
static StringMapEntry * create(StringRef key, AllocatorTy &allocator, InitTy &&...initVals)
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
op_range operands()
Definition User.h:267
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition User.cpp:119
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:53
LLVM_ABI ~Value()
Value's destructor should be virtual by design, but that would require that Value and all of its subc...
Definition Value.cpp:76
TypeSize getSequentialElementStride(const DataLayout &DL) const
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:48
initializer< Ty > init(const Ty &Val)
@ Assume
Do not drop type tests (default).
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:139
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
Context & getContext() const
Definition BasicBlock.h:99
This is an optimization pass for GlobalISel generic memory operations.
StringMapEntry< Value * > ValueName
Definition Value.h:56
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:634
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2638
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
Definition STLExtras.h:2613
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:368
generic_gep_type_iterator<> gep_type_iterator
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
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
gep_type_iterator gep_type_begin(const User *GEP)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
#define N
StringMapEntry< uint32_t > * Tag
The operand bundle tag, interned by LLVMContextImpl::getOrInsertBundleTag.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130