LLVM  4.0.0
ValueMapper.cpp
Go to the documentation of this file.
1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/IR/Operator.h"
27 using namespace llvm;
28 
29 // Out of line method to get vtable etc for class.
30 void ValueMapTypeRemapper::anchor() {}
31 void ValueMaterializer::anchor() {}
32 
33 namespace {
34 
35 /// A basic block used in a BlockAddress whose function body is not yet
36 /// materialized.
37 struct DelayedBasicBlock {
38  BasicBlock *OldBB;
39  std::unique_ptr<BasicBlock> TempBB;
40 
41  DelayedBasicBlock(const BlockAddress &Old)
42  : OldBB(Old.getBasicBlock()),
43  TempBB(BasicBlock::Create(Old.getContext())) {}
44 };
45 
46 struct WorklistEntry {
47  enum EntryKind {
48  MapGlobalInit,
49  MapAppendingVar,
50  MapGlobalAliasee,
52  };
53  struct GVInitTy {
54  GlobalVariable *GV;
55  Constant *Init;
56  };
57  struct AppendingGVTy {
58  GlobalVariable *GV;
59  Constant *InitPrefix;
60  };
61  struct GlobalAliaseeTy {
62  GlobalAlias *GA;
63  Constant *Aliasee;
64  };
65 
66  unsigned Kind : 2;
67  unsigned MCID : 29;
68  unsigned AppendingGVIsOldCtorDtor : 1;
69  unsigned AppendingGVNumNewMembers;
70  union {
71  GVInitTy GVInit;
72  AppendingGVTy AppendingGV;
73  GlobalAliaseeTy GlobalAliasee;
74  Function *RemapF;
75  } Data;
76 };
77 
78 struct MappingContext {
80  ValueMaterializer *Materializer = nullptr;
81 
82  /// Construct a MappingContext with a value map and materializer.
83  explicit MappingContext(ValueToValueMapTy &VM,
84  ValueMaterializer *Materializer = nullptr)
85  : VM(&VM), Materializer(Materializer) {}
86 };
87 
88 class MDNodeMapper;
89 class Mapper {
90  friend class MDNodeMapper;
91 
92 #ifndef NDEBUG
93  DenseSet<GlobalValue *> AlreadyScheduled;
94 #endif
95 
97  ValueMapTypeRemapper *TypeMapper;
98  unsigned CurrentMCID = 0;
102  SmallVector<Constant *, 16> AppendingInits;
103 
104 public:
105  Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
106  ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
107  : Flags(Flags), TypeMapper(TypeMapper),
108  MCs(1, MappingContext(VM, Materializer)) {}
109 
110  /// ValueMapper should explicitly call \a flush() before destruction.
111  ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
112 
113  bool hasWorkToDo() const { return !Worklist.empty(); }
114 
115  unsigned
116  registerAlternateMappingContext(ValueToValueMapTy &VM,
117  ValueMaterializer *Materializer = nullptr) {
118  MCs.push_back(MappingContext(VM, Materializer));
119  return MCs.size() - 1;
120  }
121 
122  void addFlags(RemapFlags Flags);
123 
124  Value *mapValue(const Value *V);
126  void remapFunction(Function &F);
127 
128  Constant *mapConstant(const Constant *C) {
129  return cast_or_null<Constant>(mapValue(C));
130  }
131 
132  /// Map metadata.
133  ///
134  /// Find the mapping for MD. Guarantees that the return will be resolved
135  /// (not an MDNode, or MDNode::isResolved() returns true).
136  Metadata *mapMetadata(const Metadata *MD);
137 
138  void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
139  unsigned MCID);
140  void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
141  bool IsOldCtorDtor,
142  ArrayRef<Constant *> NewMembers,
143  unsigned MCID);
144  void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
145  unsigned MCID);
146  void scheduleRemapFunction(Function &F, unsigned MCID);
147 
148  void flush();
149 
150 private:
151  void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
152  void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
153  bool IsOldCtorDtor,
154  ArrayRef<Constant *> NewMembers);
155  void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
156  void remapFunction(Function &F, ValueToValueMapTy &VM);
157 
158  ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
159  ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
160 
161  Value *mapBlockAddress(const BlockAddress &BA);
162 
163  /// Map metadata that doesn't require visiting operands.
164  Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
165 
166  Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
167  Metadata *mapToSelf(const Metadata *MD);
168 };
169 
170 class MDNodeMapper {
171  Mapper &M;
172 
173  /// Data about a node in \a UniquedGraph.
174  struct Data {
175  bool HasChanged = false;
176  unsigned ID = ~0u;
177  TempMDNode Placeholder;
178  };
179 
180  /// A graph of uniqued nodes.
181  struct UniquedGraph {
182  SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
183  SmallVector<MDNode *, 16> POT; // Post-order traversal.
184 
185  /// Propagate changed operands through the post-order traversal.
186  ///
187  /// Iteratively update \a Data::HasChanged for each node based on \a
188  /// Data::HasChanged of its operands, until fixed point.
189  void propagateChanges();
190 
191  /// Get a forward reference to a node to use as an operand.
192  Metadata &getFwdReference(MDNode &Op);
193  };
194 
195  /// Worklist of distinct nodes whose operands need to be remapped.
196  SmallVector<MDNode *, 16> DistinctWorklist;
197 
198  // Storage for a UniquedGraph.
200  SmallVector<MDNode *, 16> POTStorage;
201 
202 public:
203  MDNodeMapper(Mapper &M) : M(M) {}
204 
205  /// Map a metadata node (and its transitive operands).
206  ///
207  /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
208  /// algorithm handles distinct nodes and uniqued node subgraphs using
209  /// different strategies.
210  ///
211  /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
212  /// using \a mapDistinctNode(). Their mapping can always be computed
213  /// immediately without visiting operands, even if their operands change.
214  ///
215  /// The mapping for uniqued nodes depends on whether their operands change.
216  /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
217  /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
218  /// added to \a DistinctWorklist with \a mapDistinctNode().
219  ///
220  /// After mapping \c N itself, this function remaps the operands of the
221  /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
222  /// N has been mapped.
223  Metadata *map(const MDNode &N);
224 
225 private:
226  /// Map a top-level uniqued node and the uniqued subgraph underneath it.
227  ///
228  /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
229  /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
230  /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
231  /// operands uses the identity mapping.
232  ///
233  /// The algorithm works as follows:
234  ///
235  /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
236  /// save the post-order traversal in the given \a UniquedGraph, tracking
237  /// nodes' operands change.
238  ///
239  /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
240  /// through the \a UniquedGraph until fixed point, following the rule
241  /// that if a node changes, any node that references must also change.
242  ///
243  /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
244  /// (referencing new operands) where necessary.
245  Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
246 
247  /// Try to map the operand of an \a MDNode.
248  ///
249  /// If \c Op is already mapped, return the mapping. If it's not an \a
250  /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
251  /// return the result of \a mapDistinctNode().
252  ///
253  /// \return None if \c Op is an unmapped uniqued \a MDNode.
254  /// \post getMappedOp(Op) only returns None if this returns None.
255  Optional<Metadata *> tryToMapOperand(const Metadata *Op);
256 
257  /// Map a distinct node.
258  ///
259  /// Return the mapping for the distinct node \c N, saving the result in \a
260  /// DistinctWorklist for later remapping.
261  ///
262  /// \pre \c N is not yet mapped.
263  /// \pre \c N.isDistinct().
264  MDNode *mapDistinctNode(const MDNode &N);
265 
266  /// Get a previously mapped node.
267  Optional<Metadata *> getMappedOp(const Metadata *Op) const;
268 
269  /// Create a post-order traversal of an unmapped uniqued node subgraph.
270  ///
271  /// This traverses the metadata graph deeply enough to map \c FirstN. It
272  /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
273  /// metadata that has already been mapped will not be part of the POT.
274  ///
275  /// Each node that has a changed operand from outside the graph (e.g., a
276  /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
277  /// is marked with \a Data::HasChanged.
278  ///
279  /// \return \c true if any nodes in \c G have \a Data::HasChanged.
280  /// \post \c G.POT is a post-order traversal ending with \c FirstN.
281  /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
282  /// to change because of operands outside the graph.
283  bool createPOT(UniquedGraph &G, const MDNode &FirstN);
284 
285  /// Visit the operands of a uniqued node in the POT.
286  ///
287  /// Visit the operands in the range from \c I to \c E, returning the first
288  /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
289  /// where to continue the loop through the operands.
290  ///
291  /// This sets \c HasChanged if any of the visited operands change.
292  MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
293  MDNode::op_iterator E, bool &HasChanged);
294 
295  /// Map all the nodes in the given uniqued graph.
296  ///
297  /// This visits all the nodes in \c G in post-order, using the identity
298  /// mapping or creating a new node depending on \a Data::HasChanged.
299  ///
300  /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
301  /// their operands outside of \c G.
302  /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
303  /// operands have changed.
304  /// \post \a getMappedOp() returns the mapped node for every node in \c G.
305  void mapNodesInPOT(UniquedGraph &G);
306 
307  /// Remap a node's operands using the given functor.
308  ///
309  /// Iterate through the operands of \c N and update them in place using \c
310  /// mapOperand.
311  ///
312  /// \pre N.isDistinct() or N.isTemporary().
313  template <class OperandMapper>
314  void remapOperands(MDNode &N, OperandMapper mapOperand);
315 };
316 
317 } // end namespace
318 
319 Value *Mapper::mapValue(const Value *V) {
320  ValueToValueMapTy::iterator I = getVM().find(V);
321 
322  // If the value already exists in the map, use it.
323  if (I != getVM().end()) {
324  assert(I->second && "Unexpected null mapping");
325  return I->second;
326  }
327 
328  // If we have a materializer and it can materialize a value, use that.
329  if (auto *Materializer = getMaterializer()) {
330  if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
331  getVM()[V] = NewV;
332  return NewV;
333  }
334  }
335 
336  // Global values do not need to be seeded into the VM if they
337  // are using the identity mapping.
338  if (isa<GlobalValue>(V)) {
340  return nullptr;
341  return getVM()[V] = const_cast<Value *>(V);
342  }
343 
344  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
345  // Inline asm may need *type* remapping.
346  FunctionType *NewTy = IA->getFunctionType();
347  if (TypeMapper) {
348  NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
349 
350  if (NewTy != IA->getFunctionType())
351  V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
352  IA->hasSideEffects(), IA->isAlignStack());
353  }
354 
355  return getVM()[V] = const_cast<Value *>(V);
356  }
357 
358  if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
359  const Metadata *MD = MDV->getMetadata();
360 
361  if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
362  // Look through to grab the local value.
363  if (Value *LV = mapValue(LAM->getValue())) {
364  if (V == LAM->getValue())
365  return const_cast<Value *>(V);
367  }
368 
369  // FIXME: always return nullptr once Verifier::verifyDominatesUse()
370  // ensures metadata operands only reference defined SSA values.
371  return (Flags & RF_IgnoreMissingLocals)
372  ? nullptr
374  MDTuple::get(V->getContext(), None));
375  }
376 
377  // If this is a module-level metadata and we know that nothing at the module
378  // level is changing, then use an identity mapping.
380  return getVM()[V] = const_cast<Value *>(V);
381 
382  // Map the metadata and turn it into a value.
383  auto *MappedMD = mapMetadata(MD);
384  if (MD == MappedMD)
385  return getVM()[V] = const_cast<Value *>(V);
386  return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
387  }
388 
389  // Okay, this either must be a constant (which may or may not be mappable) or
390  // is something that is not in the mapping table.
391  Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
392  if (!C)
393  return nullptr;
394 
395  if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
396  return mapBlockAddress(*BA);
397 
398  auto mapValueOrNull = [this](Value *V) {
399  auto Mapped = mapValue(V);
400  assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
401  "Unexpected null mapping for constant operand without "
402  "NullMapMissingGlobalValues flag");
403  return Mapped;
404  };
405 
406  // Otherwise, we have some other constant to remap. Start by checking to see
407  // if all operands have an identity remapping.
408  unsigned OpNo = 0, NumOperands = C->getNumOperands();
409  Value *Mapped = nullptr;
410  for (; OpNo != NumOperands; ++OpNo) {
411  Value *Op = C->getOperand(OpNo);
412  Mapped = mapValueOrNull(Op);
413  if (!Mapped)
414  return nullptr;
415  if (Mapped != Op)
416  break;
417  }
418 
419  // See if the type mapper wants to remap the type as well.
420  Type *NewTy = C->getType();
421  if (TypeMapper)
422  NewTy = TypeMapper->remapType(NewTy);
423 
424  // If the result type and all operands match up, then just insert an identity
425  // mapping.
426  if (OpNo == NumOperands && NewTy == C->getType())
427  return getVM()[V] = C;
428 
429  // Okay, we need to create a new constant. We've already processed some or
430  // all of the operands, set them all up now.
432  Ops.reserve(NumOperands);
433  for (unsigned j = 0; j != OpNo; ++j)
434  Ops.push_back(cast<Constant>(C->getOperand(j)));
435 
436  // If one of the operands mismatch, push it and the other mapped operands.
437  if (OpNo != NumOperands) {
438  Ops.push_back(cast<Constant>(Mapped));
439 
440  // Map the rest of the operands that aren't processed yet.
441  for (++OpNo; OpNo != NumOperands; ++OpNo) {
442  Mapped = mapValueOrNull(C->getOperand(OpNo));
443  if (!Mapped)
444  return nullptr;
445  Ops.push_back(cast<Constant>(Mapped));
446  }
447  }
448  Type *NewSrcTy = nullptr;
449  if (TypeMapper)
450  if (auto *GEPO = dyn_cast<GEPOperator>(C))
451  NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
452 
453  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
454  return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
455  if (isa<ConstantArray>(C))
456  return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
457  if (isa<ConstantStruct>(C))
458  return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
459  if (isa<ConstantVector>(C))
460  return getVM()[V] = ConstantVector::get(Ops);
461  // If this is a no-operand constant, it must be because the type was remapped.
462  if (isa<UndefValue>(C))
463  return getVM()[V] = UndefValue::get(NewTy);
464  if (isa<ConstantAggregateZero>(C))
465  return getVM()[V] = ConstantAggregateZero::get(NewTy);
466  assert(isa<ConstantPointerNull>(C));
467  return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
468 }
469 
470 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
471  Function *F = cast<Function>(mapValue(BA.getFunction()));
472 
473  // F may not have materialized its initializer. In that case, create a
474  // dummy basic block for now, and replace it once we've materialized all
475  // the initializers.
476  BasicBlock *BB;
477  if (F->empty()) {
478  DelayedBBs.push_back(DelayedBasicBlock(BA));
479  BB = DelayedBBs.back().TempBB.get();
480  } else {
481  BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
482  }
483 
484  return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
485 }
486 
487 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
488  getVM().MD()[Key].reset(Val);
489  return Val;
490 }
491 
492 Metadata *Mapper::mapToSelf(const Metadata *MD) {
493  return mapToMetadata(MD, const_cast<Metadata *>(MD));
494 }
495 
496 Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
497  if (!Op)
498  return nullptr;
499 
500  if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
501 #ifndef NDEBUG
502  if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
503  assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
504  M.getVM().getMappedMD(Op)) &&
505  "Expected Value to be memoized");
506  else
507  assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
508  "Expected result to be memoized");
509 #endif
510  return *MappedOp;
511  }
512 
513  const MDNode &N = *cast<MDNode>(Op);
514  if (N.isDistinct())
515  return mapDistinctNode(N);
516  return None;
517 }
518 
519 MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
520  assert(N.isDistinct() && "Expected a distinct node");
521  assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
522  DistinctWorklist.push_back(cast<MDNode>(
523  (M.Flags & RF_MoveDistinctMDs)
524  ? M.mapToSelf(&N)
525  : M.mapToMetadata(&N, MDNode::replaceWithDistinct(N.clone()))));
526  return DistinctWorklist.back();
527 }
528 
530  Value *MappedV) {
531  if (CMD.getValue() == MappedV)
532  return const_cast<ConstantAsMetadata *>(&CMD);
533  return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
534 }
535 
536 Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
537  if (!Op)
538  return nullptr;
539 
540  if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
541  return *MappedOp;
542 
543  if (isa<MDString>(Op))
544  return const_cast<Metadata *>(Op);
545 
546  if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
547  return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
548 
549  return None;
550 }
551 
552 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
553  auto Where = Info.find(&Op);
554  assert(Where != Info.end() && "Expected a valid reference");
555 
556  auto &OpD = Where->second;
557  if (!OpD.HasChanged)
558  return Op;
559 
560  // Lazily construct a temporary node.
561  if (!OpD.Placeholder)
562  OpD.Placeholder = Op.clone();
563 
564  return *OpD.Placeholder;
565 }
566 
567 template <class OperandMapper>
568 void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
569  assert(!N.isUniqued() && "Expected distinct or temporary nodes");
570  for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
571  Metadata *Old = N.getOperand(I);
572  Metadata *New = mapOperand(Old);
573 
574  if (Old != New)
575  N.replaceOperandWith(I, New);
576  }
577 }
578 
579 namespace {
580 /// An entry in the worklist for the post-order traversal.
581 struct POTWorklistEntry {
582  MDNode *N; ///< Current node.
583  MDNode::op_iterator Op; ///< Current operand of \c N.
584 
585  /// Keep a flag of whether operands have changed in the worklist to avoid
586  /// hitting the map in \a UniquedGraph.
587  bool HasChanged = false;
588 
589  POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
590 };
591 } // end namespace
592 
593 bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
594  assert(G.Info.empty() && "Expected a fresh traversal");
595  assert(FirstN.isUniqued() && "Expected uniqued node in POT");
596 
597  // Construct a post-order traversal of the uniqued subgraph under FirstN.
598  bool AnyChanges = false;
600  Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
601  (void)G.Info[&FirstN];
602  while (!Worklist.empty()) {
603  // Start or continue the traversal through the this node's operands.
604  auto &WE = Worklist.back();
605  if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
606  // Push a new node to traverse first.
607  Worklist.push_back(POTWorklistEntry(*N));
608  continue;
609  }
610 
611  // Push the node onto the POT.
612  assert(WE.N->isUniqued() && "Expected only uniqued nodes");
613  assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
614  auto &D = G.Info[WE.N];
615  AnyChanges |= D.HasChanged = WE.HasChanged;
616  D.ID = G.POT.size();
617  G.POT.push_back(WE.N);
618 
619  // Pop the node off the worklist.
620  Worklist.pop_back();
621  }
622  return AnyChanges;
623 }
624 
625 MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
626  MDNode::op_iterator E, bool &HasChanged) {
627  while (I != E) {
628  Metadata *Op = *I++; // Increment even on early return.
629  if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
630  // Check if the operand changes.
631  HasChanged |= Op != *MappedOp;
632  continue;
633  }
634 
635  // A uniqued metadata node.
636  MDNode &OpN = *cast<MDNode>(Op);
637  assert(OpN.isUniqued() &&
638  "Only uniqued operands cannot be mapped immediately");
639  if (G.Info.insert(std::make_pair(&OpN, Data())).second)
640  return &OpN; // This is a new one. Return it.
641  }
642  return nullptr;
643 }
644 
645 void MDNodeMapper::UniquedGraph::propagateChanges() {
646  bool AnyChanges;
647  do {
648  AnyChanges = false;
649  for (MDNode *N : POT) {
650  auto &D = Info[N];
651  if (D.HasChanged)
652  continue;
653 
654  if (none_of(N->operands(), [&](const Metadata *Op) {
655  auto Where = Info.find(Op);
656  return Where != Info.end() && Where->second.HasChanged;
657  }))
658  continue;
659 
660  AnyChanges = D.HasChanged = true;
661  }
662  } while (AnyChanges);
663 }
664 
665 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
666  // Construct uniqued nodes, building forward references as necessary.
667  SmallVector<MDNode *, 16> CyclicNodes;
668  for (auto *N : G.POT) {
669  auto &D = G.Info[N];
670  if (!D.HasChanged) {
671  // The node hasn't changed.
672  M.mapToSelf(N);
673  continue;
674  }
675 
676  // Remember whether this node had a placeholder.
677  bool HadPlaceholder(D.Placeholder);
678 
679  // Clone the uniqued node and remap the operands.
680  TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
681  remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
682  if (Optional<Metadata *> MappedOp = getMappedOp(Old))
683  return *MappedOp;
684  assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
685  return &G.getFwdReference(*cast<MDNode>(Old));
686  });
687 
688  auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
689  M.mapToMetadata(N, NewN);
690 
691  // Nodes that were referenced out of order in the POT are involved in a
692  // uniquing cycle.
693  if (HadPlaceholder)
694  CyclicNodes.push_back(NewN);
695  }
696 
697  // Resolve cycles.
698  for (auto *N : CyclicNodes)
699  if (!N->isResolved())
700  N->resolveCycles();
701 }
702 
703 Metadata *MDNodeMapper::map(const MDNode &N) {
704  assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
705  assert(!(M.Flags & RF_NoModuleLevelChanges) &&
706  "MDNodeMapper::map assumes module-level changes");
707 
708  // Require resolved nodes whenever metadata might be remapped.
709  assert(N.isResolved() && "Unexpected unresolved node");
710 
711  Metadata *MappedN =
712  N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
713  while (!DistinctWorklist.empty())
714  remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
715  if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
716  return *MappedOp;
717  return mapTopLevelUniquedNode(*cast<MDNode>(Old));
718  });
719  return MappedN;
720 }
721 
722 Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
723  assert(FirstN.isUniqued() && "Expected uniqued node");
724 
725  // Create a post-order traversal of uniqued nodes under FirstN.
726  UniquedGraph G;
727  if (!createPOT(G, FirstN)) {
728  // Return early if no nodes have changed.
729  for (const MDNode *N : G.POT)
730  M.mapToSelf(N);
731  return &const_cast<MDNode &>(FirstN);
732  }
733 
734  // Update graph with all nodes that have changed.
735  G.propagateChanges();
736 
737  // Map all the nodes in the graph.
738  mapNodesInPOT(G);
739 
740  // Return the original node, remapped.
741  return *getMappedOp(&FirstN);
742 }
743 
744 namespace {
745 
746 struct MapMetadataDisabler {
747  ValueToValueMapTy &VM;
748 
749  MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
750  VM.disableMapMetadata();
751  }
752  ~MapMetadataDisabler() { VM.enableMapMetadata(); }
753 };
754 
755 } // end namespace
756 
757 Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
758  // If the value already exists in the map, use it.
759  if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
760  return *NewMD;
761 
762  if (isa<MDString>(MD))
763  return const_cast<Metadata *>(MD);
764 
765  // This is a module-level metadata. If nothing at the module level is
766  // changing, use an identity mapping.
767  if ((Flags & RF_NoModuleLevelChanges))
768  return const_cast<Metadata *>(MD);
769 
770  if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
771  // Disallow recursion into metadata mapping through mapValue.
772  MapMetadataDisabler MMD(getVM());
773 
774  // Don't memoize ConstantAsMetadata. Instead of lasting until the
775  // LLVMContext is destroyed, they can be deleted when the GlobalValue they
776  // reference is destructed. These aren't super common, so the extra
777  // indirection isn't that expensive.
778  return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
779  }
780 
781  assert(isa<MDNode>(MD) && "Expected a metadata node");
782 
783  return None;
784 }
785 
786 Metadata *Mapper::mapMetadata(const Metadata *MD) {
787  assert(MD && "Expected valid metadata");
788  assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
789 
790  if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
791  return *NewMD;
792 
793  return MDNodeMapper(*this).map(*cast<MDNode>(MD));
794 }
795 
796 void Mapper::flush() {
797  // Flush out the worklist of global values.
798  while (!Worklist.empty()) {
799  WorklistEntry E = Worklist.pop_back_val();
800  CurrentMCID = E.MCID;
801  switch (E.Kind) {
802  case WorklistEntry::MapGlobalInit:
803  E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
804  break;
805  case WorklistEntry::MapAppendingVar: {
806  unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
807  mapAppendingVariable(*E.Data.AppendingGV.GV,
808  E.Data.AppendingGV.InitPrefix,
809  E.AppendingGVIsOldCtorDtor,
810  makeArrayRef(AppendingInits).slice(PrefixSize));
811  AppendingInits.resize(PrefixSize);
812  break;
813  }
814  case WorklistEntry::MapGlobalAliasee:
815  E.Data.GlobalAliasee.GA->setAliasee(
816  mapConstant(E.Data.GlobalAliasee.Aliasee));
817  break;
819  remapFunction(*E.Data.RemapF);
820  break;
821  }
822  }
823  CurrentMCID = 0;
824 
825  // Finish logic for block addresses now that all global values have been
826  // handled.
827  while (!DelayedBBs.empty()) {
828  DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
829  BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
830  DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
831  }
832 }
833 
835  // Remap operands.
836  for (Use &Op : I->operands()) {
837  Value *V = mapValue(Op);
838  // If we aren't ignoring missing entries, assert that something happened.
839  if (V)
840  Op = V;
841  else
842  assert((Flags & RF_IgnoreMissingLocals) &&
843  "Referenced value not in value map!");
844  }
845 
846  // Remap phi nodes' incoming blocks.
847  if (PHINode *PN = dyn_cast<PHINode>(I)) {
848  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
849  Value *V = mapValue(PN->getIncomingBlock(i));
850  // If we aren't ignoring missing entries, assert that something happened.
851  if (V)
852  PN->setIncomingBlock(i, cast<BasicBlock>(V));
853  else
854  assert((Flags & RF_IgnoreMissingLocals) &&
855  "Referenced block not in value map!");
856  }
857  }
858 
859  // Remap attached metadata.
861  I->getAllMetadata(MDs);
862  for (const auto &MI : MDs) {
863  MDNode *Old = MI.second;
864  MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
865  if (New != Old)
866  I->setMetadata(MI.first, New);
867  }
868 
869  if (!TypeMapper)
870  return;
871 
872  // If the instruction's type is being remapped, do so now.
873  if (auto CS = CallSite(I)) {
875  FunctionType *FTy = CS.getFunctionType();
876  Tys.reserve(FTy->getNumParams());
877  for (Type *Ty : FTy->params())
878  Tys.push_back(TypeMapper->remapType(Ty));
879  CS.mutateFunctionType(FunctionType::get(
880  TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
881  return;
882  }
883  if (auto *AI = dyn_cast<AllocaInst>(I))
884  AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
885  if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
886  GEP->setSourceElementType(
887  TypeMapper->remapType(GEP->getSourceElementType()));
888  GEP->setResultElementType(
889  TypeMapper->remapType(GEP->getResultElementType()));
890  }
891  I->mutateType(TypeMapper->remapType(I->getType()));
892 }
893 
894 void Mapper::remapFunction(Function &F) {
895  // Remap the operands.
896  for (Use &Op : F.operands())
897  if (Op)
898  Op = mapValue(Op);
899 
900  // Remap the metadata attachments.
902  F.getAllMetadata(MDs);
903  F.clearMetadata();
904  for (const auto &I : MDs)
905  F.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
906 
907  // Remap the argument types.
908  if (TypeMapper)
909  for (Argument &A : F.args())
910  A.mutateType(TypeMapper->remapType(A.getType()));
911 
912  // Remap the instructions.
913  for (BasicBlock &BB : F)
914  for (Instruction &I : BB)
915  remapInstruction(&I);
916 }
917 
918 void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
919  bool IsOldCtorDtor,
920  ArrayRef<Constant *> NewMembers) {
922  if (InitPrefix) {
923  unsigned NumElements =
924  cast<ArrayType>(InitPrefix->getType())->getNumElements();
925  for (unsigned I = 0; I != NumElements; ++I)
926  Elements.push_back(InitPrefix->getAggregateElement(I));
927  }
928 
929  PointerType *VoidPtrTy;
930  Type *EltTy;
931  if (IsOldCtorDtor) {
932  // FIXME: This upgrade is done during linking to support the C API. See
933  // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
934  VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
935  auto &ST = *cast<StructType>(NewMembers.front()->getType());
936  Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
937  EltTy = StructType::get(GV.getContext(), Tys, false);
938  }
939 
940  for (auto *V : NewMembers) {
941  Constant *NewV;
942  if (IsOldCtorDtor) {
943  auto *S = cast<ConstantStruct>(V);
944  auto *E1 = mapValue(S->getOperand(0));
945  auto *E2 = mapValue(S->getOperand(1));
946  Value *Null = Constant::getNullValue(VoidPtrTy);
947  NewV =
948  ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
949  } else {
950  NewV = cast_or_null<Constant>(mapValue(V));
951  }
952  Elements.push_back(NewV);
953  }
954 
956  cast<ArrayType>(GV.getType()->getElementType()), Elements));
957 }
958 
959 void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
960  unsigned MCID) {
961  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
962  assert(MCID < MCs.size() && "Invalid mapping context");
963 
964  WorklistEntry WE;
965  WE.Kind = WorklistEntry::MapGlobalInit;
966  WE.MCID = MCID;
967  WE.Data.GVInit.GV = &GV;
968  WE.Data.GVInit.Init = &Init;
969  Worklist.push_back(WE);
970 }
971 
972 void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
973  Constant *InitPrefix,
974  bool IsOldCtorDtor,
975  ArrayRef<Constant *> NewMembers,
976  unsigned MCID) {
977  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
978  assert(MCID < MCs.size() && "Invalid mapping context");
979 
980  WorklistEntry WE;
981  WE.Kind = WorklistEntry::MapAppendingVar;
982  WE.MCID = MCID;
983  WE.Data.AppendingGV.GV = &GV;
984  WE.Data.AppendingGV.InitPrefix = InitPrefix;
985  WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
986  WE.AppendingGVNumNewMembers = NewMembers.size();
987  Worklist.push_back(WE);
988  AppendingInits.append(NewMembers.begin(), NewMembers.end());
989 }
990 
991 void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
992  unsigned MCID) {
993  assert(AlreadyScheduled.insert(&GA).second && "Should not reschedule");
994  assert(MCID < MCs.size() && "Invalid mapping context");
995 
996  WorklistEntry WE;
997  WE.Kind = WorklistEntry::MapGlobalAliasee;
998  WE.MCID = MCID;
999  WE.Data.GlobalAliasee.GA = &GA;
1000  WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1001  Worklist.push_back(WE);
1002 }
1003 
1004 void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1005  assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1006  assert(MCID < MCs.size() && "Invalid mapping context");
1007 
1008  WorklistEntry WE;
1009  WE.Kind = WorklistEntry::RemapFunction;
1010  WE.MCID = MCID;
1011  WE.Data.RemapF = &F;
1012  Worklist.push_back(WE);
1013 }
1014 
1015 void Mapper::addFlags(RemapFlags Flags) {
1016  assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1017  this->Flags = this->Flags | Flags;
1018 }
1019 
1020 static Mapper *getAsMapper(void *pImpl) {
1021  return reinterpret_cast<Mapper *>(pImpl);
1022 }
1023 
1024 namespace {
1025 
1026 class FlushingMapper {
1027  Mapper &M;
1028 
1029 public:
1030  explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1031  assert(!M.hasWorkToDo() && "Expected to be flushed");
1032  }
1033  ~FlushingMapper() { M.flush(); }
1034  Mapper *operator->() const { return &M; }
1035 };
1036 
1037 } // end namespace
1038 
1039 ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1040  ValueMapTypeRemapper *TypeMapper,
1041  ValueMaterializer *Materializer)
1042  : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1043 
1045 
1046 unsigned
1048  ValueMaterializer *Materializer) {
1049  return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1050 }
1051 
1053  FlushingMapper(pImpl)->addFlags(Flags);
1054 }
1055 
1057  return FlushingMapper(pImpl)->mapValue(&V);
1058 }
1059 
1061  return cast_or_null<Constant>(mapValue(C));
1062 }
1063 
1065  return FlushingMapper(pImpl)->mapMetadata(&MD);
1066 }
1067 
1069  return cast_or_null<MDNode>(mapMetadata(N));
1070 }
1071 
1073  FlushingMapper(pImpl)->remapInstruction(&I);
1074 }
1075 
1077  FlushingMapper(pImpl)->remapFunction(F);
1078 }
1079 
1081  Constant &Init,
1082  unsigned MCID) {
1083  getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1084 }
1085 
1087  Constant *InitPrefix,
1088  bool IsOldCtorDtor,
1089  ArrayRef<Constant *> NewMembers,
1090  unsigned MCID) {
1091  getAsMapper(pImpl)->scheduleMapAppendingVariable(
1092  GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1093 }
1094 
1096  unsigned MCID) {
1097  getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1098 }
1099 
1101  getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1102 }
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1364
const NoneType None
Definition: None.h:23
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:241
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:679
LLVM Argument representation.
Definition: Argument.h:34
const Instruction & back() const
Definition: BasicBlock.h:242
static void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
Definition: LoopUnroll.cpp:56
size_t i
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:137
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:819
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:144
void RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Remap the operands, metadata, arguments, and instructions of a function.
Definition: ValueMapper.h:256
Implements a dense probed hash-table based set.
Definition: DenseSet.h:202
unsigned getNumOperands() const
Definition: User.h:167
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1040
Any global values not in value map are mapped to null instead of mapping to self. ...
Definition: ValueMapper.h:88
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1254
iterator end() const
Definition: ArrayRef.h:130
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:128
This file contains the declarations for metadata subclasses.
Metadata node.
Definition: Metadata.h:830
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Get all metadata attached to this Instruction.
Definition: Instruction.h:191
Hexagon Common GEP
Type * getElementType() const
Definition: DerivedTypes.h:462
void reserve(size_type N)
Definition: SmallVector.h:377
static Mapper * getAsMapper(void *pImpl)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:195
static std::enable_if< std::is_base_of< MDNode, T >::value, T * >::type replaceWithDistinct(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a distinct one.
Definition: Metadata.h:956
The address of a basic block.
Definition: Constants.h:822
struct fuzzer::@269 Flags
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:440
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:323
void remapInstruction(Instruction &I)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
Constant * mapConstant(const Constant &C)
static GCRegistry::Add< StatepointGC > D("statepoint-example","an example strategy for statepoint")
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:994
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:750
Windows NT (Windows on ARM)
void resolveCycles()
Resolve cycles.
Definition: Metadata.cpp:581
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:873
Class to represent function types.
Definition: DerivedTypes.h:102
Metadata * mapMetadata(const Metadata &MD)
Instruct the remapper to move distinct metadata instead of duplicating it when there are module-level...
Definition: ValueMapper.h:84
#define F(x, y, z)
Definition: MD5.cpp:51
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:291
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
void enableMapMetadata()
Definition: ValueMap.h:122
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:141
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:62
Class to represent pointers.
Definition: DerivedTypes.h:443
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:74
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:40
static std::enable_if< std::is_base_of< MDNode, T >::value, T * >::type replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
Definition: Metadata.h:946
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1323
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static ConstantAsMetadata * wrapConstantAsMetadata(const ConstantAsMetadata &CMD, Value *MappedV)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1356
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1099
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:888
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
iterator begin() const
Definition: ArrayRef.h:129
Value * getOperand(unsigned i) const
Definition: User.h:145
op_range operands()
Definition: User.h:213
void disableMapMetadata()
Definition: ValueMap.h:123
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:949
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:265
TempMDNode clone() const
Create a (temporary) clone of this.
Definition: Metadata.cpp:482
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1337
RemapFlags
These are flags that the value mapping APIs allow.
Definition: ValueMapper.h:56
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:654
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1183
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1034
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:330
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:346
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:309
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1342
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
IteratorT end() const
BasicBlock * getBasicBlock() const
Definition: Constants.h:851
void remapFunction(Function &F)
void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
bool empty() const
Definition: Function.h:541
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:28
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
Definition: ValueMapper.h:80
bool isDistinct() const
Definition: Metadata.h:908
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:259
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
op_range operands() const
Definition: Metadata.h:1032
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:27
Constant * getValue() const
Definition: Metadata.h:400
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition: Value.h:558
bool isVarArg() const
Definition: DerivedTypes.h:122
const unsigned Kind
Value * mapValue(const Value &V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Function * getFunction() const
Definition: Constants.h:850
bool isUniqued() const
Definition: Metadata.h:907
LLVM Value Representation.
Definition: Value.h:71
unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
IRTranslator LLVM IR MI
bool isResolved() const
Check if node is fully resolved.
Definition: Metadata.h:905
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
Root of the metadata hierarchy.
Definition: Metadata.h:55
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:167
iterator_range< arg_iterator > args()
Definition: Function.h:568
MDNode * mapMDNode(const MDNode &N)