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