LLVM  13.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"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DerivedUser.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/ValueHandle.h"
32 #include "llvm/Support/Debug.h"
36 #include <algorithm>
37 
38 using namespace llvm;
39 
41  "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
42  cl::desc("Deref attributes and metadata infer facts at definition only"));
43 
44 
46  "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
47  cl::desc("Maximum size for the name of non-global values."));
48 
49 //===----------------------------------------------------------------------===//
50 // Value Class
51 //===----------------------------------------------------------------------===//
52 static inline Type *checkType(Type *Ty) {
53  assert(Ty && "Value defined with a null type: Error!");
54  return Ty;
55 }
56 
57 Value::Value(Type *ty, unsigned scid)
58  : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
59  SubclassOptionalData(0), SubclassData(0), NumUserOperands(0),
60  IsUsedByMD(false), HasName(false), HasMetadata(false) {
61  static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
62  // FIXME: Why isn't this in the subclass gunk??
63  // Note, we cannot call isa<CallInst> before the CallInst has been
64  // constructed.
65  if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
66  SubclassID == Instruction::CallBr)
67  assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
68  "invalid CallInst type!");
69  else if (SubclassID != BasicBlockVal &&
70  (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
71  assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
72  "Cannot create non-first-class values except for constants!");
73  static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
74  "Value too big");
75 }
76 
78  // Notify all ValueHandles (if present) that this value is going away.
79  if (HasValueHandle)
81  if (isUsedByMetadata())
83 
84  // Remove associated metadata from context.
85  if (HasMetadata)
86  clearMetadata();
87 
88 #ifndef NDEBUG // Only in -g mode...
89  // Check to make sure that there are no uses of this value that are still
90  // around when the value is destroyed. If there are, then we have a dangling
91  // reference and something is wrong. This code is here to print out where
92  // the value is still being referenced.
93  //
94  // Note that use_empty() cannot be called here, as it eventually downcasts
95  // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
96  // been destructed, so accessing it is UB.
97  //
98  if (!materialized_use_empty()) {
99  dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
100  for (auto *U : users())
101  dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
102  }
103 #endif
104  assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
105 
106  // If this value is named, destroy the name. This should not be in a symtab
107  // at this point.
108  destroyValueName();
109 }
110 
112  switch (getValueID()) {
113 #define HANDLE_VALUE(Name) \
114  case Value::Name##Val: \
115  delete static_cast<Name *>(this); \
116  break;
117 #define HANDLE_MEMORY_VALUE(Name) \
118  case Value::Name##Val: \
119  static_cast<DerivedUser *>(this)->DeleteValue( \
120  static_cast<DerivedUser *>(this)); \
121  break;
122 #define HANDLE_CONSTANT(Name) \
123  case Value::Name##Val: \
124  llvm_unreachable("constants should be destroyed with destroyConstant"); \
125  break;
126 #define HANDLE_INSTRUCTION(Name) /* nothing */
127 #include "llvm/IR/Value.def"
128 
129 #define HANDLE_INST(N, OPC, CLASS) \
130  case Value::InstructionVal + Instruction::OPC: \
131  delete static_cast<CLASS *>(this); \
132  break;
133 #define HANDLE_USER_INST(N, OPC, CLASS)
134 #include "llvm/IR/Instruction.def"
135 
136  default:
137  llvm_unreachable("attempting to delete unknown value kind");
138  }
139 }
140 
141 void Value::destroyValueName() {
143  if (Name) {
145  Name->Destroy(Allocator);
146  }
147  setValueName(nullptr);
148 }
149 
150 bool Value::hasNUses(unsigned N) const {
151  return hasNItems(use_begin(), use_end(), N);
152 }
153 
154 bool Value::hasNUsesOrMore(unsigned N) const {
155  return hasNItemsOrMore(use_begin(), use_end(), N);
156 }
157 
158 bool Value::hasOneUser() const {
159  if (use_empty())
160  return false;
161  if (hasOneUse())
162  return true;
163  return std::equal(++user_begin(), user_end(), user_begin());
164 }
165 
166 static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
167 
169  Use *Result = nullptr;
170  for (Use &U : uses()) {
171  if (!U.getUser()->isDroppable()) {
172  if (Result)
173  return nullptr;
174  Result = &U;
175  }
176  }
177  return Result;
178 }
179 
180 bool Value::hasNUndroppableUses(unsigned int N) const {
182 }
183 
184 bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
186 }
187 
189  llvm::function_ref<bool(const Use *)> ShouldDrop) {
190  SmallVector<Use *, 8> ToBeEdited;
191  for (Use &U : uses())
192  if (U.getUser()->isDroppable() && ShouldDrop(&U))
193  ToBeEdited.push_back(&U);
194  for (Use *U : ToBeEdited)
195  dropDroppableUse(*U);
196 }
197 
199  assert(Usr.isDroppable() && "Expected a droppable user!");
200  for (Use &UsrOp : Usr.operands()) {
201  if (UsrOp.get() == this)
202  dropDroppableUse(UsrOp);
203  }
204 }
205 
207  U.removeFromList();
208  if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
209  unsigned OpNo = U.getOperandNo();
210  if (OpNo == 0)
211  U.set(ConstantInt::getTrue(Assume->getContext()));
212  else {
213  U.set(UndefValue::get(U.get()->getType()));
214  CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
215  BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
216  }
217  return;
218  }
219 
220  llvm_unreachable("unkown droppable use");
221 }
222 
224  // This can be computed either by scanning the instructions in BB, or by
225  // scanning the use list of this Value. Both lists can be very long, but
226  // usually one is quite short.
227  //
228  // Scan both lists simultaneously until one is exhausted. This limits the
229  // search to the shorter list.
230  BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
231  const_user_iterator UI = user_begin(), UE = user_end();
232  for (; BI != BE && UI != UE; ++BI, ++UI) {
233  // Scan basic block: Check if this Value is used by the instruction at BI.
234  if (is_contained(BI->operands(), this))
235  return true;
236  // Scan use list: Check if the use at UI is in BB.
237  const auto *User = dyn_cast<Instruction>(*UI);
238  if (User && User->getParent() == BB)
239  return true;
240  }
241  return false;
242 }
243 
244 unsigned Value::getNumUses() const {
245  return (unsigned)std::distance(use_begin(), use_end());
246 }
247 
248 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
249  ST = nullptr;
250  if (Instruction *I = dyn_cast<Instruction>(V)) {
251  if (BasicBlock *P = I->getParent())
252  if (Function *PP = P->getParent())
253  ST = PP->getValueSymbolTable();
254  } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
255  if (Function *P = BB->getParent())
256  ST = P->getValueSymbolTable();
257  } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
258  if (Module *P = GV->getParent())
259  ST = &P->getValueSymbolTable();
260  } else if (Argument *A = dyn_cast<Argument>(V)) {
261  if (Function *P = A->getParent())
262  ST = P->getValueSymbolTable();
263  } else {
264  assert(isa<Constant>(V) && "Unknown value type!");
265  return true; // no name is setable for this.
266  }
267  return false;
268 }
269 
271  if (!HasName) return nullptr;
272 
273  LLVMContext &Ctx = getContext();
274  auto I = Ctx.pImpl->ValueNames.find(this);
275  assert(I != Ctx.pImpl->ValueNames.end() &&
276  "No name entry found!");
277 
278  return I->second;
279 }
280 
282  LLVMContext &Ctx = getContext();
283 
284  assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
285  "HasName bit out of sync!");
286 
287  if (!VN) {
288  if (HasName)
289  Ctx.pImpl->ValueNames.erase(this);
290  HasName = false;
291  return;
292  }
293 
294  HasName = true;
295  Ctx.pImpl->ValueNames[this] = VN;
296 }
297 
299  // Make sure the empty string is still a C string. For historical reasons,
300  // some clients want to call .data() on the result and expect it to be null
301  // terminated.
302  if (!hasName())
303  return StringRef("", 0);
304  return getValueName()->getKey();
305 }
306 
307 void Value::setNameImpl(const Twine &NewName) {
308  // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
309  if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
310  return;
311 
312  // Fast path for common IRBuilder case of setName("") when there is no name.
313  if (NewName.isTriviallyEmpty() && !hasName())
314  return;
315 
316  SmallString<256> NameData;
317  StringRef NameRef = NewName.toStringRef(NameData);
318  assert(NameRef.find_first_of(0) == StringRef::npos &&
319  "Null bytes are not allowed in names");
320 
321  // Name isn't changing?
322  if (getName() == NameRef)
323  return;
324 
325  // Cap the size of non-GlobalValue names.
326  if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
327  NameRef =
328  NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
329 
330  assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
331 
332  // Get the symbol table to update for this object.
334  if (getSymTab(this, ST))
335  return; // Cannot set a name on this value (e.g. constant).
336 
337  if (!ST) { // No symbol table to update? Just do the change.
338  if (NameRef.empty()) {
339  // Free the name for this value.
340  destroyValueName();
341  return;
342  }
343 
344  // NOTE: Could optimize for the case the name is shrinking to not deallocate
345  // then reallocated.
346  destroyValueName();
347 
348  // Create the new name.
351  getValueName()->setValue(this);
352  return;
353  }
354 
355  // NOTE: Could optimize for the case the name is shrinking to not deallocate
356  // then reallocated.
357  if (hasName()) {
358  // Remove old name.
359  ST->removeValueName(getValueName());
360  destroyValueName();
361 
362  if (NameRef.empty())
363  return;
364  }
365 
366  // Name is changing to something new.
367  setValueName(ST->createValueName(NameRef, this));
368 }
369 
370 void Value::setName(const Twine &NewName) {
371  setNameImpl(NewName);
372  if (Function *F = dyn_cast<Function>(this))
373  F->recalculateIntrinsicID();
374 }
375 
377  ValueSymbolTable *ST = nullptr;
378  // If this value has a name, drop it.
379  if (hasName()) {
380  // Get the symtab this is in.
381  if (getSymTab(this, ST)) {
382  // We can't set a name on this value, but we need to clear V's name if
383  // it has one.
384  if (V->hasName()) V->setName("");
385  return; // Cannot set a name on this value (e.g. constant).
386  }
387 
388  // Remove old name.
389  if (ST)
390  ST->removeValueName(getValueName());
391  destroyValueName();
392  }
393 
394  // Now we know that this has no name.
395 
396  // If V has no name either, we're done.
397  if (!V->hasName()) return;
398 
399  // Get this's symtab if we didn't before.
400  if (!ST) {
401  if (getSymTab(this, ST)) {
402  // Clear V's name.
403  V->setName("");
404  return; // Cannot set a name on this value (e.g. constant).
405  }
406  }
407 
408  // Get V's ST, this should always succed, because V has a name.
409  ValueSymbolTable *VST;
410  bool Failure = getSymTab(V, VST);
411  assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
412 
413  // If these values are both in the same symtab, we can do this very fast.
414  // This works even if both values have no symtab yet.
415  if (ST == VST) {
416  // Take the name!
418  V->setValueName(nullptr);
419  getValueName()->setValue(this);
420  return;
421  }
422 
423  // Otherwise, things are slightly more complex. Remove V's name from VST and
424  // then reinsert it into ST.
425 
426  if (VST)
427  VST->removeValueName(V->getValueName());
429  V->setValueName(nullptr);
430  getValueName()->setValue(this);
431 
432  if (ST)
433  ST->reinsertValue(this);
434 }
435 
436 #ifndef NDEBUG
437 std::string Value::getNameOrAsOperand() const {
438  if (!getName().empty())
439  return std::string(getName());
440 
441  std::string BBName;
442  raw_string_ostream OS(BBName);
443  printAsOperand(OS, false);
444  return OS.str();
445 }
446 #endif
447 
449 #ifndef NDEBUG
450  const GlobalValue *GV = dyn_cast<GlobalValue>(this);
451  if (!GV)
452  return;
453  const Module *M = GV->getParent();
454  if (!M)
455  return;
456  assert(M->isMaterialized());
457 #endif
458 }
459 
460 #ifndef NDEBUG
462  Constant *C) {
463  if (!Cache.insert(Expr).second)
464  return false;
465 
466  for (auto &O : Expr->operands()) {
467  if (O == C)
468  return true;
469  auto *CE = dyn_cast<ConstantExpr>(O);
470  if (!CE)
471  continue;
472  if (contains(Cache, CE, C))
473  return true;
474  }
475  return false;
476 }
477 
478 static bool contains(Value *Expr, Value *V) {
479  if (Expr == V)
480  return true;
481 
482  auto *C = dyn_cast<Constant>(V);
483  if (!C)
484  return false;
485 
486  auto *CE = dyn_cast<ConstantExpr>(Expr);
487  if (!CE)
488  return false;
489 
491  return contains(Cache, CE, C);
492 }
493 #endif // NDEBUG
494 
495 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
496  assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
497  assert(!contains(New, this) &&
498  "this->replaceAllUsesWith(expr(this)) is NOT valid!");
499  assert(New->getType() == getType() &&
500  "replaceAllUses of value with new value of different type!");
501 
502  // Notify all ValueHandles (if present) that this value is going away.
503  if (HasValueHandle)
505  if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
506  ValueAsMetadata::handleRAUW(this, New);
507 
508  while (!materialized_use_empty()) {
509  Use &U = *UseList;
510  // Must handle Constants specially, we cannot call replaceUsesOfWith on a
511  // constant because they are uniqued.
512  if (auto *C = dyn_cast<Constant>(U.getUser())) {
513  if (!isa<GlobalValue>(C)) {
514  C->handleOperandChange(this, New);
515  continue;
516  }
517  }
518 
519  U.set(New);
520  }
521 
522  if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
523  BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
524 }
525 
527  doRAUW(New, ReplaceMetadataUses::Yes);
528 }
529 
531  doRAUW(New, ReplaceMetadataUses::No);
532 }
533 
534 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
535 // This routine leaves uses within BB.
537  assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
538  assert(!contains(New, this) &&
539  "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
540  assert(New->getType() == getType() &&
541  "replaceUses of value with new value of different type!");
542  assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
543 
544  replaceUsesWithIf(New, [BB](Use &U) {
545  auto *I = dyn_cast<Instruction>(U.getUser());
546  // Don't replace if it's an instruction in the BB basic block.
547  return !I || I->getParent() != BB;
548  });
549 }
550 
551 namespace {
552 // Various metrics for how much to strip off of pointers.
553 enum PointerStripKind {
554  PSK_ZeroIndices,
555  PSK_ZeroIndicesAndAliases,
556  PSK_ZeroIndicesSameRepresentation,
557  PSK_ForAliasAnalysis,
558  PSK_InBoundsConstantIndices,
559  PSK_InBounds
560 };
561 
562 template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
563 
564 template <PointerStripKind StripKind>
565 static const Value *stripPointerCastsAndOffsets(
566  const Value *V,
567  function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
568  if (!V->getType()->isPointerTy())
569  return V;
570 
571  // Even though we don't look through PHI nodes, we could be called on an
572  // instruction in an unreachable block, which may be on a cycle.
574 
575  Visited.insert(V);
576  do {
577  Func(V);
578  if (auto *GEP = dyn_cast<GEPOperator>(V)) {
579  switch (StripKind) {
580  case PSK_ZeroIndices:
581  case PSK_ZeroIndicesAndAliases:
582  case PSK_ZeroIndicesSameRepresentation:
583  case PSK_ForAliasAnalysis:
584  if (!GEP->hasAllZeroIndices())
585  return V;
586  break;
587  case PSK_InBoundsConstantIndices:
588  if (!GEP->hasAllConstantIndices())
589  return V;
591  case PSK_InBounds:
592  if (!GEP->isInBounds())
593  return V;
594  break;
595  }
596  V = GEP->getPointerOperand();
597  } else if (Operator::getOpcode(V) == Instruction::BitCast) {
598  V = cast<Operator>(V)->getOperand(0);
599  if (!V->getType()->isPointerTy())
600  return V;
601  } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
602  Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
603  // TODO: If we know an address space cast will not change the
604  // representation we could look through it here as well.
605  V = cast<Operator>(V)->getOperand(0);
606  } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
607  V = cast<GlobalAlias>(V)->getAliasee();
608  } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
609  cast<PHINode>(V)->getNumIncomingValues() == 1) {
610  V = cast<PHINode>(V)->getIncomingValue(0);
611  } else {
612  if (const auto *Call = dyn_cast<CallBase>(V)) {
613  if (const Value *RV = Call->getReturnedArgOperand()) {
614  V = RV;
615  continue;
616  }
617  // The result of launder.invariant.group must alias it's argument,
618  // but it can't be marked with returned attribute, that's why it needs
619  // special case.
620  if (StripKind == PSK_ForAliasAnalysis &&
621  (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
622  Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
623  V = Call->getArgOperand(0);
624  continue;
625  }
626  }
627  return V;
628  }
629  assert(V->getType()->isPointerTy() && "Unexpected operand type!");
630  } while (Visited.insert(V).second);
631 
632  return V;
633 }
634 } // end anonymous namespace
635 
637  return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
638 }
639 
641  return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
642 }
643 
645  return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
646 }
647 
649  return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
650 }
651 
653  return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this);
654 }
655 
657  const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
658  function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
659  if (!getType()->isPtrOrPtrVectorTy())
660  return this;
661 
662  unsigned BitWidth = Offset.getBitWidth();
663  assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
664  "The offset bit width does not match the DL specification.");
665 
666  // Even though we don't look through PHI nodes, we could be called on an
667  // instruction in an unreachable block, which may be on a cycle.
669  Visited.insert(this);
670  const Value *V = this;
671  do {
672  if (auto *GEP = dyn_cast<GEPOperator>(V)) {
673  // If in-bounds was requested, we do not strip non-in-bounds GEPs.
674  if (!AllowNonInbounds && !GEP->isInBounds())
675  return V;
676 
677  // If one of the values we have visited is an addrspacecast, then
678  // the pointer type of this GEP may be different from the type
679  // of the Ptr parameter which was passed to this function. This
680  // means when we construct GEPOffset, we need to use the size
681  // of GEP's pointer type rather than the size of the original
682  // pointer type.
683  APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
684  if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
685  return V;
686 
687  // Stop traversal if the pointer offset wouldn't fit in the bit-width
688  // provided by the Offset argument. This can happen due to AddrSpaceCast
689  // stripping.
690  if (GEPOffset.getMinSignedBits() > BitWidth)
691  return V;
692 
693  // External Analysis can return a result higher/lower than the value
694  // represents. We need to detect overflow/underflow.
695  APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
696  if (!ExternalAnalysis) {
697  Offset += GEPOffsetST;
698  } else {
699  bool Overflow = false;
700  APInt OldOffset = Offset;
701  Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
702  if (Overflow) {
703  Offset = OldOffset;
704  return V;
705  }
706  }
707  V = GEP->getPointerOperand();
708  } else if (Operator::getOpcode(V) == Instruction::BitCast ||
709  Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
710  V = cast<Operator>(V)->getOperand(0);
711  } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
712  if (!GA->isInterposable())
713  V = GA->getAliasee();
714  } else if (const auto *Call = dyn_cast<CallBase>(V)) {
715  if (const Value *RV = Call->getReturnedArgOperand())
716  V = RV;
717  }
718  assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
719  } while (Visited.insert(V).second);
720 
721  return V;
722 }
723 
724 const Value *
725 Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
726  return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
727 }
728 
729 bool Value::canBeFreed() const {
730  assert(getType()->isPointerTy());
731 
732  // Cases that can simply never be deallocated
733  // *) Constants aren't allocated per se, thus not deallocated either.
734  if (isa<Constant>(this))
735  return false;
736 
737  // Handle byval/byref/sret/inalloca/preallocated arguments. The storage
738  // lifetime is guaranteed to be longer than the callee's lifetime.
739  if (auto *A = dyn_cast<Argument>(this))
740  if (A->hasPointeeInMemoryValueAttr())
741  return false;
742 
743  const Function *F = nullptr;
744  if (auto *I = dyn_cast<Instruction>(this))
745  F = I->getFunction();
746  if (auto *A = dyn_cast<Argument>(this))
747  F = A->getParent();
748 
749  if (!F)
750  return true;
751 
752  // A pointer to an object in a function which neither frees, nor can arrange
753  // for another thread to free on its behalf, can not be freed in the scope
754  // of the function.
755  if (F->doesNotFreeMemory() && F->hasNoSync())
756  return false;
757 
758  // With garbage collection, deallocation typically occurs solely at or after
759  // safepoints. If we're compiling for a collector which uses the
760  // gc.statepoint infrastructure, safepoints aren't explicitly present
761  // in the IR until after lowering from abstract to physical machine model.
762  // The collector could chose to mix explicit deallocation and gc'd objects
763  // which is why we need the explicit opt in on a per collector basis.
764  if (!F->hasGC())
765  return true;
766 
767  const auto &GCName = F->getGC();
768  const StringRef StatepointExampleName("statepoint-example");
769  if (GCName != StatepointExampleName)
770  return true;
771 
772  auto *PT = cast<PointerType>(this->getType());
773  if (PT->getAddressSpace() != 1)
774  // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
775  // GC managed heap. This must match the same check in
776  // RewriteStatepointsForGC (and probably needs better factored.)
777  return true;
778 
779  // It is cheaper to scan for a declaration than to scan for a use in this
780  // function. Note that gc.statepoint is a type overloaded function so the
781  // usual trick of requesting declaration of the intrinsic from the module
782  // doesn't work.
783  for (auto &Fn : *F->getParent())
784  if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
785  return true;
786  return false;
787 }
788 
790  bool &CanBeNull,
791  bool &CanBeFreed) const {
792  assert(getType()->isPointerTy() && "must be pointer");
793 
794  uint64_t DerefBytes = 0;
795  CanBeNull = false;
796  CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
797  if (const Argument *A = dyn_cast<Argument>(this)) {
798  DerefBytes = A->getDereferenceableBytes();
799  if (DerefBytes == 0) {
800  // Handle byval/byref/inalloca/preallocated arguments
801  if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
802  if (ArgMemTy->isSized()) {
803  // FIXME: Why isn't this the type alloc size?
804  DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize();
805  }
806  }
807  }
808 
809  if (DerefBytes == 0) {
810  DerefBytes = A->getDereferenceableOrNullBytes();
811  CanBeNull = true;
812  }
813  } else if (const auto *Call = dyn_cast<CallBase>(this)) {
814  DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
815  if (DerefBytes == 0) {
816  DerefBytes =
817  Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
818  CanBeNull = true;
819  }
820  } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
821  if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
822  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
823  DerefBytes = CI->getLimitedValue();
824  }
825  if (DerefBytes == 0) {
826  if (MDNode *MD =
827  LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
828  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
829  DerefBytes = CI->getLimitedValue();
830  }
831  CanBeNull = true;
832  }
833  } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
834  if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
835  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
836  DerefBytes = CI->getLimitedValue();
837  }
838  if (DerefBytes == 0) {
839  if (MDNode *MD =
840  IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
841  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
842  DerefBytes = CI->getLimitedValue();
843  }
844  CanBeNull = true;
845  }
846  } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
847  if (!AI->isArrayAllocation()) {
848  DerefBytes =
849  DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
850  CanBeNull = false;
851  CanBeFreed = false;
852  }
853  } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
854  if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
855  // TODO: Don't outright reject hasExternalWeakLinkage but set the
856  // CanBeNull flag.
857  DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
858  CanBeNull = false;
859  }
860  }
861  return DerefBytes;
862 }
863 
865  assert(getType()->isPointerTy() && "must be pointer");
866  if (auto *GO = dyn_cast<GlobalObject>(this)) {
867  if (isa<Function>(GO)) {
868  Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
869  switch (DL.getFunctionPtrAlignType()) {
871  return FunctionPtrAlign;
873  return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
874  }
875  llvm_unreachable("Unhandled FunctionPtrAlignType");
876  }
877  const MaybeAlign Alignment(GO->getAlignment());
878  if (!Alignment) {
879  if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
880  Type *ObjectType = GVar->getValueType();
881  if (ObjectType->isSized()) {
882  // If the object is defined in the current Module, we'll be giving
883  // it the preferred alignment. Otherwise, we have to assume that it
884  // may only have the minimum ABI alignment.
885  if (GVar->isStrongDefinitionForLinker())
886  return DL.getPreferredAlign(GVar);
887  else
888  return DL.getABITypeAlign(ObjectType);
889  }
890  }
891  }
892  return Alignment.valueOrOne();
893  } else if (const Argument *A = dyn_cast<Argument>(this)) {
894  const MaybeAlign Alignment = A->getParamAlign();
895  if (!Alignment && A->hasStructRetAttr()) {
896  // An sret parameter has at least the ABI alignment of the return type.
897  Type *EltTy = A->getParamStructRetType();
898  if (EltTy->isSized())
899  return DL.getABITypeAlign(EltTy);
900  }
901  return Alignment.valueOrOne();
902  } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
903  return AI->getAlign();
904  } else if (const auto *Call = dyn_cast<CallBase>(this)) {
905  MaybeAlign Alignment = Call->getRetAlign();
906  if (!Alignment && Call->getCalledFunction())
907  Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
908  return Alignment.valueOrOne();
909  } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
910  if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
911  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
912  return Align(CI->getLimitedValue());
913  }
914  } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
915  if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
916  const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
917  /*OnlyIfReduced=*/true))) {
918  size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
919  // While the actual alignment may be large, elsewhere we have
920  // an arbitrary upper alignmet limit, so let's clamp to it.
921  return Align(TrailingZeros < Value::MaxAlignmentExponent
922  ? uint64_t(1) << TrailingZeros
924  }
925  }
926  return Align(1);
927 }
928 
930  const BasicBlock *PredBB) const {
931  auto *PN = dyn_cast<PHINode>(this);
932  if (PN && PN->getParent() == CurBB)
933  return PN->getIncomingValueForBlock(PredBB);
934  return this;
935 }
936 
937 LLVMContext &Value::getContext() const { return VTy->getContext(); }
938 
940  if (!UseList || !UseList->Next)
941  // No need to reverse 0 or 1 uses.
942  return;
943 
944  Use *Head = UseList;
945  Use *Current = UseList->Next;
946  Head->Next = nullptr;
947  while (Current) {
948  Use *Next = Current->Next;
949  Current->Next = Head;
950  Head->Prev = &Current->Next;
951  Head = Current;
952  Current = Next;
953  }
954  UseList = Head;
955  Head->Prev = &UseList;
956 }
957 
958 bool Value::isSwiftError() const {
959  auto *Arg = dyn_cast<Argument>(this);
960  if (Arg)
961  return Arg->hasSwiftErrorAttr();
962  auto *Alloca = dyn_cast<AllocaInst>(this);
963  if (!Alloca)
964  return false;
965  return Alloca->isSwiftError();
966 }
967 
968 //===----------------------------------------------------------------------===//
969 // ValueHandleBase Class
970 //===----------------------------------------------------------------------===//
971 
972 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
973  assert(List && "Handle list is null?");
974 
975  // Splice ourselves into the list.
976  Next = *List;
977  *List = this;
978  setPrevPtr(List);
979  if (Next) {
980  Next->setPrevPtr(&Next);
981  assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
982  }
983 }
984 
985 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
986  assert(List && "Must insert after existing node");
987 
988  Next = List->Next;
989  setPrevPtr(&List->Next);
990  List->Next = this;
991  if (Next)
992  Next->setPrevPtr(&Next);
993 }
994 
995 void ValueHandleBase::AddToUseList() {
996  assert(getValPtr() && "Null pointer doesn't have a use list!");
997 
999 
1000  if (getValPtr()->HasValueHandle) {
1001  // If this value already has a ValueHandle, then it must be in the
1002  // ValueHandles map already.
1003  ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
1004  assert(Entry && "Value doesn't have any handles?");
1005  AddToExistingUseList(&Entry);
1006  return;
1007  }
1008 
1009  // Ok, it doesn't have any handles yet, so we must insert it into the
1010  // DenseMap. However, doing this insertion could cause the DenseMap to
1011  // reallocate itself, which would invalidate all of the PrevP pointers that
1012  // point into the old table. Handle this by checking for reallocation and
1013  // updating the stale pointers only if needed.
1015  const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1016 
1017  ValueHandleBase *&Entry = Handles[getValPtr()];
1018  assert(!Entry && "Value really did already have handles?");
1019  AddToExistingUseList(&Entry);
1020  getValPtr()->HasValueHandle = true;
1021 
1022  // If reallocation didn't happen or if this was the first insertion, don't
1023  // walk the table.
1024  if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1025  Handles.size() == 1) {
1026  return;
1027  }
1028 
1029  // Okay, reallocation did happen. Fix the Prev Pointers.
1031  E = Handles.end(); I != E; ++I) {
1032  assert(I->second && I->first == I->second->getValPtr() &&
1033  "List invariant broken!");
1034  I->second->setPrevPtr(&I->second);
1035  }
1036 }
1037 
1039  assert(getValPtr() && getValPtr()->HasValueHandle &&
1040  "Pointer doesn't have a use list!");
1041 
1042  // Unlink this from its use list.
1043  ValueHandleBase **PrevPtr = getPrevPtr();
1044  assert(*PrevPtr == this && "List invariant broken");
1045 
1046  *PrevPtr = Next;
1047  if (Next) {
1048  assert(Next->getPrevPtr() == &Next && "List invariant broken");
1049  Next->setPrevPtr(PrevPtr);
1050  return;
1051  }
1052 
1053  // If the Next pointer was null, then it is possible that this was the last
1054  // ValueHandle watching VP. If so, delete its entry from the ValueHandles
1055  // map.
1056  LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1058  if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
1059  Handles.erase(getValPtr());
1060  getValPtr()->HasValueHandle = false;
1061  }
1062 }
1063 
1065  assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1066 
1067  // Get the linked list base, which is guaranteed to exist since the
1068  // HasValueHandle flag is set.
1069  LLVMContextImpl *pImpl = V->getContext().pImpl;
1070  ValueHandleBase *Entry = pImpl->ValueHandles[V];
1071  assert(Entry && "Value bit set but no entries exist");
1072 
1073  // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1074  // and remove themselves from the list without breaking our iteration. This
1075  // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1076  // Note that we deliberately do not the support the case when dropping a value
1077  // handle results in a new value handle being permanently added to the list
1078  // (as might occur in theory for CallbackVH's): the new value handle will not
1079  // be processed and the checking code will mete out righteous punishment if
1080  // the handle is still present once we have finished processing all the other
1081  // value handles (it is fine to momentarily add then remove a value handle).
1082  for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1083  Iterator.RemoveFromUseList();
1084  Iterator.AddToExistingUseListAfter(Entry);
1085  assert(Entry->Next == &Iterator && "Loop invariant broken.");
1086 
1087  switch (Entry->getKind()) {
1088  case Assert:
1089  break;
1090  case Weak:
1091  case WeakTracking:
1092  // WeakTracking and Weak just go to null, which unlinks them
1093  // from the list.
1094  Entry->operator=(nullptr);
1095  break;
1096  case Callback:
1097  // Forward to the subclass's implementation.
1098  static_cast<CallbackVH*>(Entry)->deleted();
1099  break;
1100  }
1101  }
1102 
1103  // All callbacks, weak references, and assertingVHs should be dropped by now.
1104  if (V->HasValueHandle) {
1105 #ifndef NDEBUG // Only in +Asserts mode...
1106  dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1107  << "\n";
1108  if (pImpl->ValueHandles[V]->getKind() == Assert)
1109  llvm_unreachable("An asserting value handle still pointed to this"
1110  " value!");
1111 
1112 #endif
1113  llvm_unreachable("All references to V were not removed?");
1114  }
1115 }
1116 
1118  assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1119  assert(Old != New && "Changing value into itself!");
1120  assert(Old->getType() == New->getType() &&
1121  "replaceAllUses of value with new value of different type!");
1122 
1123  // Get the linked list base, which is guaranteed to exist since the
1124  // HasValueHandle flag is set.
1125  LLVMContextImpl *pImpl = Old->getContext().pImpl;
1126  ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1127 
1128  assert(Entry && "Value bit set but no entries exist");
1129 
1130  // We use a local ValueHandleBase as an iterator so that
1131  // ValueHandles can add and remove themselves from the list without
1132  // breaking our iteration. This is not really an AssertingVH; we
1133  // just have to give ValueHandleBase some kind.
1134  for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1135  Iterator.RemoveFromUseList();
1136  Iterator.AddToExistingUseListAfter(Entry);
1137  assert(Entry->Next == &Iterator && "Loop invariant broken.");
1138 
1139  switch (Entry->getKind()) {
1140  case Assert:
1141  case Weak:
1142  // Asserting and Weak handles do not follow RAUW implicitly.
1143  break;
1144  case WeakTracking:
1145  // Weak goes to the new value, which will unlink it from Old's list.
1146  Entry->operator=(New);
1147  break;
1148  case Callback:
1149  // Forward to the subclass's implementation.
1150  static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1151  break;
1152  }
1153  }
1154 
1155 #ifndef NDEBUG
1156  // If any new weak value handles were added while processing the
1157  // list, then complain about it now.
1158  if (Old->HasValueHandle)
1159  for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1160  switch (Entry->getKind()) {
1161  case WeakTracking:
1162  dbgs() << "After RAUW from " << *Old->getType() << " %"
1163  << Old->getName() << " to " << *New->getType() << " %"
1164  << New->getName() << "\n";
1166  "A weak tracking value handle still pointed to the old value!\n");
1167  default:
1168  break;
1169  }
1170 #endif
1171 }
1172 
1173 // Pin the vtable to this file.
1174 void CallbackVH::anchor() {}
llvm::LLVMContext::pImpl
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:70
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
llvm::Type::isSized
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:272
llvm::Value::const_user_iterator
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:404
llvm::Value::stripPointerCastsAndAliases
const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition: Value.cpp:640
llvm
Definition: AllocatorList.h:23
llvm::Value::isUsedInBasicBlock
bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition: Value.cpp:223
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::Value::dropDroppableUse
static void dropDroppableUse(Use &U)
Remove the droppable use U.
Definition: Value.cpp:206
llvm::StringRef::empty
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:156
llvm::Value::getPointerAlignment
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:864
llvm::StringMapEntry
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMapEntry.h:98
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:112
llvm::StringMapEntry::Create
static StringMapEntry * Create(StringRef key, AllocatorTy &allocator, InitTy &&... initVals)
Create a StringMapEntry for the specified key construct the value using InitiVals.
Definition: StringMapEntry.h:120
llvm::Value::hasOneUse
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:447
llvm::User::operands
op_range operands()
Definition: User.h:242
IntrinsicInst.h
llvm::Type::isPointerTy
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:229
llvm::hasNItems
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:1953
llvm::ValueHandleBase
This is the common base class of value handles.
Definition: ValueHandle.h:29
checkType
static Type * checkType(Type *Ty)
Definition: Value.cpp:52
llvm::Function
Definition: Function.h:61
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
llvm::DataLayout::FunctionPtrAlignType::Independent
@ Independent
The function pointer alignment is independent of the function alignment.
llvm::CallBase::BundleOpInfo::Tag
StringMapEntry< uint32_t > * Tag
The operand bundle tag, interned by LLVMContextImpl::getOrInsertBundleTag.
Definition: InstrTypes.h:2112
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:614
GetElementPtrTypeIterator.h
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:59
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
llvm::Value::replaceUsesWithIf
void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition: Value.h:315
llvm::Value::hasName
bool hasName() const
Definition: Value.h:262
ErrorHandling.h
ManagedStatic.h
llvm::Use::get
Value * get() const
Definition: Use.h:67
llvm::ValueHandleBase::Callback
@ Callback
Definition: ValueHandle.h:37
llvm::ValueAsMetadata::handleDeletion
static void handleDeletion(Value *V)
Definition: Metadata.cpp:386
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:140
llvm::DenseMapBase::erase
bool erase(const KeyT &Val)
Definition: DenseMap.h:302
llvm::ConstantInt::getLimitedValue
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:242
llvm::DenseMapBase::begin
iterator begin()
Definition: DenseMap.h:74
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:46
llvm::Twine::isTriviallyEmpty
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:400
DenseMap.h
Module.h
llvm::MaybeAlign::valueOrOne
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:144
llvm::Value::stripAndAccumulateConstantOffsets
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr) const
Accumulate the constant offset this value has compared to a base pointer.
llvm::Use::getOperandNo
unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition: Use.cpp:33
llvm::ValueHandleBase::getValPtr
Value * getValPtr() const
Definition: ValueHandle.h:99
llvm::ValueHandleBase::WeakTracking
@ WeakTracking
Definition: ValueHandle.h:37
llvm::Value::hasOneUser
bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition: Value.cpp:158
llvm::DenseMapBase::isPointerIntoBucketsArray
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the DenseMap's...
Definition: DenseMap.h:348
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:449
Operator.h
llvm::Value::user_begin
user_iterator user_begin()
Definition: Value.h:410
DerivedUser.h
llvm::LLVMContextImpl::ValueNames
DenseMap< const Value *, ValueName * > ValueNames
Definition: LLVMContextImpl.h:1380
llvm::Value::dropDroppableUses
void dropDroppableUses(llvm::function_ref< bool(const Use *)> ShouldDrop=[](const Use *) { return true;})
Remove every uses that can safely be removed.
Definition: Value.cpp:188
llvm::DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign
@ MultipleOfFunctionAlign
The function pointer alignment is a multiple of the function alignment.
contains
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:461
F
#define F(x, y, z)
Definition: MD5.cpp:56
UseDerefAtPointSemantics
static cl::opt< unsigned > UseDerefAtPointSemantics("use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false), cl::desc("Deref attributes and metadata infer facts at definition only"))
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::lltok::equal
@ equal
Definition: LLToken.h:25
llvm::Value::isSwiftError
bool isSwiftError() const
Return true if this value is a swifterror value.
Definition: Value.cpp:958
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
llvm::StringRef::substr
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:612
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:205
CommandLine.h
llvm::Value::reverseUseList
void reverseUseList()
Reverse the use-list.
Definition: Value.cpp:939
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:77
llvm::Value::HasName
unsigned HasName
Definition: Value.h:119
Constants.h
llvm::LLVMContextImpl::ValueHandles
ValueHandlesTy ValueHandles
Definition: LLVMContextImpl.h:1455
SmallString.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::User
Definition: User.h:44
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::LLVMContextImpl
Definition: LLVMContextImpl.h:1324
llvm::Value::getSingleUndroppableUse
Use * getSingleUndroppableUse()
Return true if there is exactly one use of this value that cannot be dropped.
Definition: Value.cpp:168
InstrTypes.h
llvm::Value::assertModuleIsMaterializedImpl
void assertModuleIsMaterializedImpl() const
Definition: Value.cpp:448
llvm::ConstantExpr::getPtrToInt
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2179
IP
Definition: NVPTXLowerArgs.cpp:166
llvm::Value::uses
iterator_range< use_iterator > uses()
Definition: Value.h:389
false
Definition: StackSlotColoring.cpp:142
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:119
llvm::Value::getValueID
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:541
llvm::Instruction
Definition: Instruction.h:45
LLVMContextImpl.h
llvm::Operator::getOpcode
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:40
llvm::Value::setName
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:370
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1770
llvm::Use::getUser
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:73
llvm::hasNItemsOrMore
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:1978
llvm::CallBase::BundleOpInfo
Used to keep track of an operand bundle.
Definition: InstrTypes.h:2109
llvm::DenseMapBase::getPointerIntoBucketsArray
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition: DenseMap.h:355
Align
uint64_t Align
Definition: ELFObjHandler.cpp:83
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
llvm::MCID::Call
@ Call
Definition: MCInstrDesc.h:154
llvm::Value::use_empty
bool use_empty() const
Definition: Value.h:357
llvm::SmallString< 256 >
llvm::Value::dropDroppableUsesIn
void dropDroppableUsesIn(User &Usr)
Remove every use of this value in User that can safely be removed.
Definition: Value.cpp:198
llvm::ValueHandleBase::ValueIsRAUWd
static void ValueIsRAUWd(Value *Old, Value *New)
Definition: Value.cpp:1117
ValueSymbolTable.h
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:176
llvm::Value::user_end
user_iterator user_end()
Definition: Value.h:418
llvm::Value::stripPointerCastsSameRepresentation
const Value * stripPointerCastsSameRepresentation() const
Strip off pointer casts, all-zero GEPs and address space casts but ensures the representation of the ...
Definition: Value.cpp:644
llvm::Value::Value
Value(Type *Ty, unsigned scid)
Definition: Value.cpp:57
llvm::Value::hasNUndroppableUsesOrMore
bool hasNUndroppableUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition: Value.cpp:184
llvm::Use::set
void set(Value *Val)
Definition: Value.h:869
llvm::cl::opt
Definition: CommandLine.h:1419
llvm::AttributeList::ReturnIndex
@ ReturnIndex
Definition: Attributes.h:378
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:128
llvm::ValueHandleBase::Assert
@ Assert
Definition: ValueHandle.h:37
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::Value::getNameOrAsOperand
std::string getNameOrAsOperand() const
Definition: Value.cpp:437
llvm::Value::getPointerDereferenceableBytes
uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool &CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition: Value.cpp:789
llvm::ValueHandleBase::RemoveFromUseList
void RemoveFromUseList()
Remove this ValueHandle from its current use list.
Definition: Value.cpp:1038
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
llvm::ARM_MB::ST
@ ST
Definition: ARMBaseInfo.h:73
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
llvm::Value::hasNUsesOrMore
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition: Value.cpp:154
llvm::Value::materialized_use_empty
bool materialized_use_empty() const
Definition: Value.h:362
llvm::DenseMap< Value *, ValueHandleBase * >
llvm::StringMapEntryStorage::setValue
void setValue(const ValueTy &V)
Definition: StringMapEntry.h:82
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:440
llvm::ValueHandleBase::Weak
@ Weak
Definition: ValueHandle.h:37
llvm::is_contained
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1570
llvm::Value::getValueName
ValueName * getValueName() const
Definition: Value.cpp:270
llvm::Value::replaceNonMetadataUsesWith
void replaceNonMetadataUsesWith(Value *V)
Change non-metadata uses of this to point to a new Value.
Definition: Value.cpp:530
llvm::StringMapEntry::getKey
StringRef getKey() const
Definition: StringMapEntry.h:102
llvm::Value::MaximumAlignment
static const unsigned MaximumAlignment
Definition: Value.h:794
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::Value::setValueName
void setValueName(ValueName *VN)
Definition: Value.cpp:281
llvm::elfabi::ELFSymbolType::Func
@ Func
llvm::Value::replaceUsesOutsideBlock
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
Definition: Value.cpp:536
llvm::Value::stripPointerCastsForAliasAnalysis
const Value * stripPointerCastsForAliasAnalysis() const
Strip off pointer casts, all-zero GEPs, single-argument phi nodes and invariant group info.
Definition: Value.cpp:652
llvm::Value::use_begin
use_iterator use_begin()
Definition: Value.h:373
llvm::Type::isVoidTy
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::MDNode
Metadata node.
Definition: Metadata.h:897
llvm::Value::clearMetadata
void clearMetadata()
Erase all metadata attached to this Value.
Definition: Metadata.cpp:1285
llvm::User::isDroppable
bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition: User.cpp:109
llvm::Value::printAsOperand
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4691
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:70
llvm::ValueHandleBase::ValueIsDeleted
static void ValueIsDeleted(Value *V)
Definition: Value.cpp:1064
DataLayout.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:136
llvm::Value::getNumUses
unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition: Value.cpp:244
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
llvm::Value::replaceAllUsesWith
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:526
llvm::ms_demangle::IntrinsicFunctionKind::New
@ New
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:937
NonGlobalValueMaxNameSize
static cl::opt< unsigned > NonGlobalValueMaxNameSize("non-global-value-max-name-size", cl::Hidden, cl::init(1024), cl::desc("Maximum size for the name of non-global values."))
llvm::Value::use_end
use_iterator use_end()
Definition: Value.h:381
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
llvm::Type::isPtrOrPtrVectorTy
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:232
LLVM_FALLTHROUGH
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:281
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:298
llvm::Type::getContext
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
llvm::LoadInst
An instruction for reading from memory.
Definition: Instructions.h:174
ValueHandle.h
llvm::Value::stripPointerCasts
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:636
llvm::Value::stripInBoundsOffsets
const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition: Value.cpp:725
llvm::Value::HasMetadata
unsigned HasMetadata
Definition: Value.h:120
Constant.h
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:931
llvm::empty
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:263
llvm::ConstantInt::getTrue
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:52
isUnDroppableUser
static bool isUnDroppableUser(const User *U)
Definition: Value.cpp:166
llvm::MallocAllocator
Definition: AllocatorBase.h:80
llvm::Value::hasNUndroppableUses
bool hasNUndroppableUses(unsigned N) const
Return true if there this value.
Definition: Value.cpp:180
llvm::Value::~Value
~Value()
Value's destructor should be virtual by design, but that would require that Value and all of its subc...
Definition: Value.cpp:77
llvm::DenseMapBase::end
iterator end()
Definition: DenseMap.h:83
llvm::APInt::sextOrTrunc
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition: APInt.cpp:956
llvm::Value::MaxAlignmentExponent
static const unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition: Value.h:793
NodeList::Next
NodeList * Next
Definition: MicrosoftDemangle.cpp:39
llvm::Value::hasNUses
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:150
llvm::BitWidth
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:147
llvm::DenseMapBase::size
unsigned size() const
Definition: DenseMap.h:100
llvm::CallbackVH
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:383
llvm::ValueAsMetadata::handleRAUW
static void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:405
llvm::Value::canBeFreed
bool canBeFreed() const
Return true if the memory object referred to by V can by freed in the scope for which the SSA value d...
Definition: Value.cpp:729
Instructions.h
llvm::Type::isStructTy
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:223
llvm::ValueSymbolTable
This class provides a symbol table of name/value pairs.
Definition: ValueSymbolTable.h:37
llvm::Value::isUsedByMetadata
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
Definition: Value.h:566
llvm::Value::stripInBoundsConstantOffsets
const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition: Value.cpp:648
llvm::Value::DoPHITranslation
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
Definition: Value.cpp:929
Allocator
Basic Register Allocator
Definition: RegAllocBasic.cpp:146
getSymTab
static bool getSymTab(Value *V, ValueSymbolTable *&ST)
Definition: Value.cpp:248
List
const NodeList & List
Definition: RDFGraph.cpp:201
N
#define N
llvm::Value::deleteValue
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:111
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:350
DerivedTypes.h
llvm::SmallPtrSetImpl
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
llvm::Twine::toStringRef
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:455
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
GEP
Hexagon Common GEP
Definition: HexagonCommonGEP.cpp:171
llvm::StringRef::find_first_of
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:413
llvm::Value::takeName
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:376
llvm::AllocaInst
an instruction to allocate memory on the stack
Definition: Instructions.h:61
llvm::cl::desc
Definition: CommandLine.h:411
raw_ostream.h
llvm::StringRef::size
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:160
Value.h
llvm::raw_string_ostream::str
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
Definition: raw_ostream.h:632
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
Debug.h
llvm::Value::users
iterator_range< user_iterator > users()
Definition: Value.h:434
SetVector.h
llvm::BasicBlock::const_iterator
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:91
llvm::Type::isFirstClassType
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:251
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44
llvm::SmallPtrSetImpl::insert
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:364