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