LLVM  14.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/GlobalAlias.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Debug.h"
42 #include <cassert>
43 #include <limits>
44 #include <memory>
45 #include <utility>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "value-mapper"
50 
51 // Out of line method to get vtable etc for class.
52 void ValueMapTypeRemapper::anchor() {}
53 void ValueMaterializer::anchor() {}
54 
55 namespace {
56 
57 /// A basic block used in a BlockAddress whose function body is not yet
58 /// materialized.
59 struct DelayedBasicBlock {
60  BasicBlock *OldBB;
61  std::unique_ptr<BasicBlock> TempBB;
62 
63  DelayedBasicBlock(const BlockAddress &Old)
64  : OldBB(Old.getBasicBlock()),
65  TempBB(BasicBlock::Create(Old.getContext())) {}
66 };
67 
68 struct WorklistEntry {
69  enum EntryKind {
70  MapGlobalInit,
71  MapAppendingVar,
72  MapAliasOrIFunc,
74  };
75  struct GVInitTy {
76  GlobalVariable *GV;
77  Constant *Init;
78  };
79  struct AppendingGVTy {
80  GlobalVariable *GV;
81  Constant *InitPrefix;
82  };
83  struct AliasOrIFuncTy {
84  GlobalValue *GV;
86  };
87 
88  unsigned Kind : 2;
89  unsigned MCID : 29;
90  unsigned AppendingGVIsOldCtorDtor : 1;
91  unsigned AppendingGVNumNewMembers;
92  union {
93  GVInitTy GVInit;
94  AppendingGVTy AppendingGV;
95  AliasOrIFuncTy AliasOrIFunc;
96  Function *RemapF;
97  } Data;
98 };
99 
100 struct MappingContext {
101  ValueToValueMapTy *VM;
102  ValueMaterializer *Materializer = nullptr;
103 
104  /// Construct a MappingContext with a value map and materializer.
105  explicit MappingContext(ValueToValueMapTy &VM,
106  ValueMaterializer *Materializer = nullptr)
107  : VM(&VM), Materializer(Materializer) {}
108 };
109 
110 class Mapper {
111  friend class MDNodeMapper;
112 
113 #ifndef NDEBUG
114  DenseSet<GlobalValue *> AlreadyScheduled;
115 #endif
116 
117  RemapFlags Flags;
118  ValueMapTypeRemapper *TypeMapper;
119  unsigned CurrentMCID = 0;
123  SmallVector<Constant *, 16> AppendingInits;
124 
125 public:
126  Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
127  ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
128  : Flags(Flags), TypeMapper(TypeMapper),
129  MCs(1, MappingContext(VM, Materializer)) {}
130 
131  /// ValueMapper should explicitly call \a flush() before destruction.
132  ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
133 
134  bool hasWorkToDo() const { return !Worklist.empty(); }
135 
136  unsigned
137  registerAlternateMappingContext(ValueToValueMapTy &VM,
138  ValueMaterializer *Materializer = nullptr) {
139  MCs.push_back(MappingContext(VM, Materializer));
140  return MCs.size() - 1;
141  }
142 
143  void addFlags(RemapFlags Flags);
144 
145  void remapGlobalObjectMetadata(GlobalObject &GO);
146 
147  Value *mapValue(const Value *V);
148  void remapInstruction(Instruction *I);
149  void remapFunction(Function &F);
150 
151  Constant *mapConstant(const Constant *C) {
152  return cast_or_null<Constant>(mapValue(C));
153  }
154 
155  /// Map metadata.
156  ///
157  /// Find the mapping for MD. Guarantees that the return will be resolved
158  /// (not an MDNode, or MDNode::isResolved() returns true).
159  Metadata *mapMetadata(const Metadata *MD);
160 
161  void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
162  unsigned MCID);
163  void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
164  bool IsOldCtorDtor,
165  ArrayRef<Constant *> NewMembers,
166  unsigned MCID);
167  void scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
168  unsigned MCID);
169  void scheduleRemapFunction(Function &F, unsigned MCID);
170 
171  void flush();
172 
173 private:
174  void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
175  bool IsOldCtorDtor,
176  ArrayRef<Constant *> NewMembers);
177 
178  ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
179  ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
180 
181  Value *mapBlockAddress(const BlockAddress &BA);
182 
183  /// Map metadata that doesn't require visiting operands.
184  Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
185 
186  Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
187  Metadata *mapToSelf(const Metadata *MD);
188 };
189 
190 class MDNodeMapper {
191  Mapper &M;
192 
193  /// Data about a node in \a UniquedGraph.
194  struct Data {
195  bool HasChanged = false;
197  TempMDNode Placeholder;
198  };
199 
200  /// A graph of uniqued nodes.
201  struct UniquedGraph {
203  SmallVector<MDNode *, 16> POT; // Post-order traversal.
204 
205  /// Propagate changed operands through the post-order traversal.
206  ///
207  /// Iteratively update \a Data::HasChanged for each node based on \a
208  /// Data::HasChanged of its operands, until fixed point.
209  void propagateChanges();
210 
211  /// Get a forward reference to a node to use as an operand.
212  Metadata &getFwdReference(MDNode &Op);
213  };
214 
215  /// Worklist of distinct nodes whose operands need to be remapped.
216  SmallVector<MDNode *, 16> DistinctWorklist;
217 
218  // Storage for a UniquedGraph.
220  SmallVector<MDNode *, 16> POTStorage;
221 
222 public:
223  MDNodeMapper(Mapper &M) : M(M) {}
224 
225  /// Map a metadata node (and its transitive operands).
226  ///
227  /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
228  /// algorithm handles distinct nodes and uniqued node subgraphs using
229  /// different strategies.
230  ///
231  /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
232  /// using \a mapDistinctNode(). Their mapping can always be computed
233  /// immediately without visiting operands, even if their operands change.
234  ///
235  /// The mapping for uniqued nodes depends on whether their operands change.
236  /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
237  /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
238  /// added to \a DistinctWorklist with \a mapDistinctNode().
239  ///
240  /// After mapping \c N itself, this function remaps the operands of the
241  /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
242  /// N has been mapped.
243  Metadata *map(const MDNode &N);
244 
245 private:
246  /// Map a top-level uniqued node and the uniqued subgraph underneath it.
247  ///
248  /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
249  /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
250  /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
251  /// operands uses the identity mapping.
252  ///
253  /// The algorithm works as follows:
254  ///
255  /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
256  /// save the post-order traversal in the given \a UniquedGraph, tracking
257  /// nodes' operands change.
258  ///
259  /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
260  /// through the \a UniquedGraph until fixed point, following the rule
261  /// that if a node changes, any node that references must also change.
262  ///
263  /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
264  /// (referencing new operands) where necessary.
265  Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
266 
267  /// Try to map the operand of an \a MDNode.
268  ///
269  /// If \c Op is already mapped, return the mapping. If it's not an \a
270  /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
271  /// return the result of \a mapDistinctNode().
272  ///
273  /// \return None if \c Op is an unmapped uniqued \a MDNode.
274  /// \post getMappedOp(Op) only returns None if this returns None.
275  Optional<Metadata *> tryToMapOperand(const Metadata *Op);
276 
277  /// Map a distinct node.
278  ///
279  /// Return the mapping for the distinct node \c N, saving the result in \a
280  /// DistinctWorklist for later remapping.
281  ///
282  /// \pre \c N is not yet mapped.
283  /// \pre \c N.isDistinct().
284  MDNode *mapDistinctNode(const MDNode &N);
285 
286  /// Get a previously mapped node.
288 
289  /// Create a post-order traversal of an unmapped uniqued node subgraph.
290  ///
291  /// This traverses the metadata graph deeply enough to map \c FirstN. It
292  /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
293  /// metadata that has already been mapped will not be part of the POT.
294  ///
295  /// Each node that has a changed operand from outside the graph (e.g., a
296  /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
297  /// is marked with \a Data::HasChanged.
298  ///
299  /// \return \c true if any nodes in \c G have \a Data::HasChanged.
300  /// \post \c G.POT is a post-order traversal ending with \c FirstN.
301  /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
302  /// to change because of operands outside the graph.
303  bool createPOT(UniquedGraph &G, const MDNode &FirstN);
304 
305  /// Visit the operands of a uniqued node in the POT.
306  ///
307  /// Visit the operands in the range from \c I to \c E, returning the first
308  /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
309  /// where to continue the loop through the operands.
310  ///
311  /// This sets \c HasChanged if any of the visited operands change.
312  MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
313  MDNode::op_iterator E, bool &HasChanged);
314 
315  /// Map all the nodes in the given uniqued graph.
316  ///
317  /// This visits all the nodes in \c G in post-order, using the identity
318  /// mapping or creating a new node depending on \a Data::HasChanged.
319  ///
320  /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
321  /// their operands outside of \c G.
322  /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
323  /// operands have changed.
324  /// \post \a getMappedOp() returns the mapped node for every node in \c G.
325  void mapNodesInPOT(UniquedGraph &G);
326 
327  /// Remap a node's operands using the given functor.
328  ///
329  /// Iterate through the operands of \c N and update them in place using \c
330  /// mapOperand.
331  ///
332  /// \pre N.isDistinct() or N.isTemporary().
333  template <class OperandMapper>
334  void remapOperands(MDNode &N, OperandMapper mapOperand);
335 };
336 
337 } // end anonymous namespace
338 
339 Value *Mapper::mapValue(const Value *V) {
340  ValueToValueMapTy::iterator I = getVM().find(V);
341 
342  // If the value already exists in the map, use it.
343  if (I != getVM().end()) {
344  assert(I->second && "Unexpected null mapping");
345  return I->second;
346  }
347 
348  // If we have a materializer and it can materialize a value, use that.
349  if (auto *Materializer = getMaterializer()) {
350  if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
351  getVM()[V] = NewV;
352  return NewV;
353  }
354  }
355 
356  // Global values do not need to be seeded into the VM if they
357  // are using the identity mapping.
358  if (isa<GlobalValue>(V)) {
359  if (Flags & RF_NullMapMissingGlobalValues)
360  return nullptr;
361  return getVM()[V] = const_cast<Value *>(V);
362  }
363 
364  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
365  // Inline asm may need *type* remapping.
366  FunctionType *NewTy = IA->getFunctionType();
367  if (TypeMapper) {
368  NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
369 
370  if (NewTy != IA->getFunctionType())
371  V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
372  IA->hasSideEffects(), IA->isAlignStack(),
373  IA->getDialect(), IA->canThrow());
374  }
375 
376  return getVM()[V] = const_cast<Value *>(V);
377  }
378 
379  if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
380  const Metadata *MD = MDV->getMetadata();
381 
382  if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
383  // Look through to grab the local value.
384  if (Value *LV = mapValue(LAM->getValue())) {
385  if (V == LAM->getValue())
386  return const_cast<Value *>(V);
388  }
389 
390  // FIXME: always return nullptr once Verifier::verifyDominatesUse()
391  // ensures metadata operands only reference defined SSA values.
392  return (Flags & RF_IgnoreMissingLocals)
393  ? nullptr
395  MDTuple::get(V->getContext(), None));
396  }
397  if (auto *AL = dyn_cast<DIArgList>(MD)) {
399  for (auto *VAM : AL->getArgs()) {
400  // Map both Local and Constant VAMs here; they will both ultimately
401  // be mapped via mapValue (apart from constants when we have no
402  // module level changes, which have an identity mapping).
403  if ((Flags & RF_NoModuleLevelChanges) && isa<ConstantAsMetadata>(VAM)) {
404  MappedArgs.push_back(VAM);
405  } else if (Value *LV = mapValue(VAM->getValue())) {
406  MappedArgs.push_back(
407  LV == VAM->getValue() ? VAM : ValueAsMetadata::get(LV));
408  } else {
409  // If we cannot map the value, set the argument as undef.
410  MappedArgs.push_back(ValueAsMetadata::get(
411  UndefValue::get(VAM->getValue()->getType())));
412  }
413  }
414  return MetadataAsValue::get(V->getContext(),
415  DIArgList::get(V->getContext(), MappedArgs));
416  }
417 
418  // If this is a module-level metadata and we know that nothing at the module
419  // level is changing, then use an identity mapping.
420  if (Flags & RF_NoModuleLevelChanges)
421  return getVM()[V] = const_cast<Value *>(V);
422 
423  // Map the metadata and turn it into a value.
424  auto *MappedMD = mapMetadata(MD);
425  if (MD == MappedMD)
426  return getVM()[V] = const_cast<Value *>(V);
427  return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
428  }
429 
430  // Okay, this either must be a constant (which may or may not be mappable) or
431  // is something that is not in the mapping table.
432  Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
433  if (!C)
434  return nullptr;
435 
436  if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
437  return mapBlockAddress(*BA);
438 
439  if (const auto *E = dyn_cast<DSOLocalEquivalent>(C)) {
440  auto *Val = mapValue(E->getGlobalValue());
441  GlobalValue *GV = dyn_cast<GlobalValue>(Val);
442  if (GV)
443  return getVM()[E] = DSOLocalEquivalent::get(GV);
444 
445  auto *Func = cast<Function>(Val->stripPointerCastsAndAliases());
446  Type *NewTy = E->getType();
447  if (TypeMapper)
448  NewTy = TypeMapper->remapType(NewTy);
449  return getVM()[E] = llvm::ConstantExpr::getBitCast(
450  DSOLocalEquivalent::get(Func), NewTy);
451  }
452 
453  auto mapValueOrNull = [this](Value *V) {
454  auto Mapped = mapValue(V);
455  assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
456  "Unexpected null mapping for constant operand without "
457  "NullMapMissingGlobalValues flag");
458  return Mapped;
459  };
460 
461  // Otherwise, we have some other constant to remap. Start by checking to see
462  // if all operands have an identity remapping.
463  unsigned OpNo = 0, NumOperands = C->getNumOperands();
464  Value *Mapped = nullptr;
465  for (; OpNo != NumOperands; ++OpNo) {
466  Value *Op = C->getOperand(OpNo);
467  Mapped = mapValueOrNull(Op);
468  if (!Mapped)
469  return nullptr;
470  if (Mapped != Op)
471  break;
472  }
473 
474  // See if the type mapper wants to remap the type as well.
475  Type *NewTy = C->getType();
476  if (TypeMapper)
477  NewTy = TypeMapper->remapType(NewTy);
478 
479  // If the result type and all operands match up, then just insert an identity
480  // mapping.
481  if (OpNo == NumOperands && NewTy == C->getType())
482  return getVM()[V] = C;
483 
484  // Okay, we need to create a new constant. We've already processed some or
485  // all of the operands, set them all up now.
487  Ops.reserve(NumOperands);
488  for (unsigned j = 0; j != OpNo; ++j)
489  Ops.push_back(cast<Constant>(C->getOperand(j)));
490 
491  // If one of the operands mismatch, push it and the other mapped operands.
492  if (OpNo != NumOperands) {
493  Ops.push_back(cast<Constant>(Mapped));
494 
495  // Map the rest of the operands that aren't processed yet.
496  for (++OpNo; OpNo != NumOperands; ++OpNo) {
497  Mapped = mapValueOrNull(C->getOperand(OpNo));
498  if (!Mapped)
499  return nullptr;
500  Ops.push_back(cast<Constant>(Mapped));
501  }
502  }
503  Type *NewSrcTy = nullptr;
504  if (TypeMapper)
505  if (auto *GEPO = dyn_cast<GEPOperator>(C))
506  NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
507 
508  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
509  return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
510  if (isa<ConstantArray>(C))
511  return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
512  if (isa<ConstantStruct>(C))
513  return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
514  if (isa<ConstantVector>(C))
515  return getVM()[V] = ConstantVector::get(Ops);
516  // If this is a no-operand constant, it must be because the type was remapped.
517  if (isa<UndefValue>(C))
518  return getVM()[V] = UndefValue::get(NewTy);
519  if (isa<ConstantAggregateZero>(C))
520  return getVM()[V] = ConstantAggregateZero::get(NewTy);
521  assert(isa<ConstantPointerNull>(C));
522  return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
523 }
524 
525 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
526  Function *F = cast<Function>(mapValue(BA.getFunction()));
527 
528  // F may not have materialized its initializer. In that case, create a
529  // dummy basic block for now, and replace it once we've materialized all
530  // the initializers.
531  BasicBlock *BB;
532  if (F->empty()) {
533  DelayedBBs.push_back(DelayedBasicBlock(BA));
534  BB = DelayedBBs.back().TempBB.get();
535  } else {
536  BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
537  }
538 
539  return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
540 }
541 
542 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
543  getVM().MD()[Key].reset(Val);
544  return Val;
545 }
546 
547 Metadata *Mapper::mapToSelf(const Metadata *MD) {
548  return mapToMetadata(MD, const_cast<Metadata *>(MD));
549 }
550 
551 Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
552  if (!Op)
553  return nullptr;
554 
555  if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
556 #ifndef NDEBUG
557  if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
558  assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
559  M.getVM().getMappedMD(Op)) &&
560  "Expected Value to be memoized");
561  else
562  assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
563  "Expected result to be memoized");
564 #endif
565  return *MappedOp;
566  }
567 
568  const MDNode &N = *cast<MDNode>(Op);
569  if (N.isDistinct())
570  return mapDistinctNode(N);
571  return None;
572 }
573 
574 MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
575  assert(N.isDistinct() && "Expected a distinct node");
576  assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
577  Metadata *NewM = nullptr;
578 
579  if (M.Flags & RF_ReuseAndMutateDistinctMDs) {
580  NewM = M.mapToSelf(&N);
581  } else {
582  NewM = MDNode::replaceWithDistinct(N.clone());
583  LLVM_DEBUG(dbgs() << "\nMap " << N << "\n"
584  << "To " << *NewM << "\n\n");
585  M.mapToMetadata(&N, NewM);
586  }
587  DistinctWorklist.push_back(cast<MDNode>(NewM));
588 
589  return DistinctWorklist.back();
590 }
591 
593  Value *MappedV) {
594  if (CMD.getValue() == MappedV)
595  return const_cast<ConstantAsMetadata *>(&CMD);
596  return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
597 }
598 
600  if (!Op)
601  return nullptr;
602 
603  if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
604  return *MappedOp;
605 
606  if (isa<MDString>(Op))
607  return const_cast<Metadata *>(Op);
608 
609  if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
610  return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
611 
612  return None;
613 }
614 
615 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
616  auto Where = Info.find(&Op);
617  assert(Where != Info.end() && "Expected a valid reference");
618 
619  auto &OpD = Where->second;
620  if (!OpD.HasChanged)
621  return Op;
622 
623  // Lazily construct a temporary node.
624  if (!OpD.Placeholder)
625  OpD.Placeholder = Op.clone();
626 
627  return *OpD.Placeholder;
628 }
629 
630 template <class OperandMapper>
631 void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
632  assert(!N.isUniqued() && "Expected distinct or temporary nodes");
633  for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
634  Metadata *Old = N.getOperand(I);
635  Metadata *New = mapOperand(Old);
636  if (Old != New)
637  LLVM_DEBUG(dbgs() << "Replacing Op " << Old << " with " << New << " in "
638  << N << "\n");
639 
640  if (Old != New)
641  N.replaceOperandWith(I, New);
642  }
643 }
644 
645 namespace {
646 
647 /// An entry in the worklist for the post-order traversal.
648 struct POTWorklistEntry {
649  MDNode *N; ///< Current node.
650  MDNode::op_iterator Op; ///< Current operand of \c N.
651 
652  /// Keep a flag of whether operands have changed in the worklist to avoid
653  /// hitting the map in \a UniquedGraph.
654  bool HasChanged = false;
655 
656  POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
657 };
658 
659 } // end anonymous namespace
660 
661 bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
662  assert(G.Info.empty() && "Expected a fresh traversal");
663  assert(FirstN.isUniqued() && "Expected uniqued node in POT");
664 
665  // Construct a post-order traversal of the uniqued subgraph under FirstN.
666  bool AnyChanges = false;
668  Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
669  (void)G.Info[&FirstN];
670  while (!Worklist.empty()) {
671  // Start or continue the traversal through the this node's operands.
672  auto &WE = Worklist.back();
673  if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
674  // Push a new node to traverse first.
675  Worklist.push_back(POTWorklistEntry(*N));
676  continue;
677  }
678 
679  // Push the node onto the POT.
680  assert(WE.N->isUniqued() && "Expected only uniqued nodes");
681  assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
682  auto &D = G.Info[WE.N];
683  AnyChanges |= D.HasChanged = WE.HasChanged;
684  D.ID = G.POT.size();
685  G.POT.push_back(WE.N);
686 
687  // Pop the node off the worklist.
688  Worklist.pop_back();
689  }
690  return AnyChanges;
691 }
692 
693 MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
694  MDNode::op_iterator E, bool &HasChanged) {
695  while (I != E) {
696  Metadata *Op = *I++; // Increment even on early return.
697  if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
698  // Check if the operand changes.
699  HasChanged |= Op != *MappedOp;
700  continue;
701  }
702 
703  // A uniqued metadata node.
704  MDNode &OpN = *cast<MDNode>(Op);
705  assert(OpN.isUniqued() &&
706  "Only uniqued operands cannot be mapped immediately");
707  if (G.Info.insert(std::make_pair(&OpN, Data())).second)
708  return &OpN; // This is a new one. Return it.
709  }
710  return nullptr;
711 }
712 
713 void MDNodeMapper::UniquedGraph::propagateChanges() {
714  bool AnyChanges;
715  do {
716  AnyChanges = false;
717  for (MDNode *N : POT) {
718  auto &D = Info[N];
719  if (D.HasChanged)
720  continue;
721 
722  if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
723  auto Where = Info.find(Op);
724  return Where != Info.end() && Where->second.HasChanged;
725  }))
726  continue;
727 
728  AnyChanges = D.HasChanged = true;
729  }
730  } while (AnyChanges);
731 }
732 
733 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
734  // Construct uniqued nodes, building forward references as necessary.
735  SmallVector<MDNode *, 16> CyclicNodes;
736  for (auto *N : G.POT) {
737  auto &D = G.Info[N];
738  if (!D.HasChanged) {
739  // The node hasn't changed.
740  M.mapToSelf(N);
741  continue;
742  }
743 
744  // Remember whether this node had a placeholder.
745  bool HadPlaceholder(D.Placeholder);
746 
747  // Clone the uniqued node and remap the operands.
748  TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
749  remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
750  if (Optional<Metadata *> MappedOp = getMappedOp(Old))
751  return *MappedOp;
752  (void)D;
753  assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
754  return &G.getFwdReference(*cast<MDNode>(Old));
755  });
756 
757  auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
758  if (N && NewN && N != NewN) {
759  LLVM_DEBUG(dbgs() << "\nMap " << *N << "\n"
760  << "To " << *NewN << "\n\n");
761  }
762 
763  M.mapToMetadata(N, NewN);
764 
765  // Nodes that were referenced out of order in the POT are involved in a
766  // uniquing cycle.
767  if (HadPlaceholder)
768  CyclicNodes.push_back(NewN);
769  }
770 
771  // Resolve cycles.
772  for (auto *N : CyclicNodes)
773  if (!N->isResolved())
774  N->resolveCycles();
775 }
776 
777 Metadata *MDNodeMapper::map(const MDNode &N) {
778  assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
779  assert(!(M.Flags & RF_NoModuleLevelChanges) &&
780  "MDNodeMapper::map assumes module-level changes");
781 
782  // Require resolved nodes whenever metadata might be remapped.
783  assert(N.isResolved() && "Unexpected unresolved node");
784 
785  Metadata *MappedN =
786  N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
787  while (!DistinctWorklist.empty())
788  remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
789  if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
790  return *MappedOp;
791  return mapTopLevelUniquedNode(*cast<MDNode>(Old));
792  });
793  return MappedN;
794 }
795 
796 Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
797  assert(FirstN.isUniqued() && "Expected uniqued node");
798 
799  // Create a post-order traversal of uniqued nodes under FirstN.
800  UniquedGraph G;
801  if (!createPOT(G, FirstN)) {
802  // Return early if no nodes have changed.
803  for (const MDNode *N : G.POT)
804  M.mapToSelf(N);
805  return &const_cast<MDNode &>(FirstN);
806  }
807 
808  // Update graph with all nodes that have changed.
809  G.propagateChanges();
810 
811  // Map all the nodes in the graph.
812  mapNodesInPOT(G);
813 
814  // Return the original node, remapped.
815  return *getMappedOp(&FirstN);
816 }
817 
818 Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
819  // If the value already exists in the map, use it.
820  if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
821  return *NewMD;
822 
823  if (isa<MDString>(MD))
824  return const_cast<Metadata *>(MD);
825 
826  // This is a module-level metadata. If nothing at the module level is
827  // changing, use an identity mapping.
828  if ((Flags & RF_NoModuleLevelChanges))
829  return const_cast<Metadata *>(MD);
830 
831  if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
832  // Don't memoize ConstantAsMetadata. Instead of lasting until the
833  // LLVMContext is destroyed, they can be deleted when the GlobalValue they
834  // reference is destructed. These aren't super common, so the extra
835  // indirection isn't that expensive.
836  return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
837  }
838 
839  assert(isa<MDNode>(MD) && "Expected a metadata node");
840 
841  return None;
842 }
843 
844 Metadata *Mapper::mapMetadata(const Metadata *MD) {
845  assert(MD && "Expected valid metadata");
846  assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
847 
848  if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
849  return *NewMD;
850 
851  return MDNodeMapper(*this).map(*cast<MDNode>(MD));
852 }
853 
854 void Mapper::flush() {
855  // Flush out the worklist of global values.
856  while (!Worklist.empty()) {
857  WorklistEntry E = Worklist.pop_back_val();
858  CurrentMCID = E.MCID;
859  switch (E.Kind) {
860  case WorklistEntry::MapGlobalInit:
861  E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
862  remapGlobalObjectMetadata(*E.Data.GVInit.GV);
863  break;
864  case WorklistEntry::MapAppendingVar: {
865  unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
866  // mapAppendingVariable call can change AppendingInits if initalizer for
867  // the variable depends on another appending global, because of that inits
868  // need to be extracted and updated before the call.
870  drop_begin(AppendingInits, PrefixSize));
871  AppendingInits.resize(PrefixSize);
872  mapAppendingVariable(*E.Data.AppendingGV.GV,
873  E.Data.AppendingGV.InitPrefix,
874  E.AppendingGVIsOldCtorDtor, makeArrayRef(NewInits));
875  break;
876  }
877  case WorklistEntry::MapAliasOrIFunc: {
878  GlobalValue *GV = E.Data.AliasOrIFunc.GV;
879  Constant *Target = mapConstant(E.Data.AliasOrIFunc.Target);
880  if (auto *GA = dyn_cast<GlobalAlias>(GV))
881  GA->setAliasee(Target);
882  else if (auto *GI = dyn_cast<GlobalIFunc>(GV))
883  GI->setResolver(Target);
884  else
885  llvm_unreachable("Not alias or ifunc");
886  break;
887  }
889  remapFunction(*E.Data.RemapF);
890  break;
891  }
892  }
893  CurrentMCID = 0;
894 
895  // Finish logic for block addresses now that all global values have been
896  // handled.
897  while (!DelayedBBs.empty()) {
898  DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
899  BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
900  DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
901  }
902 }
903 
904 void Mapper::remapInstruction(Instruction *I) {
905  // Remap operands.
906  for (Use &Op : I->operands()) {
907  Value *V = mapValue(Op);
908  // If we aren't ignoring missing entries, assert that something happened.
909  if (V)
910  Op = V;
911  else
912  assert((Flags & RF_IgnoreMissingLocals) &&
913  "Referenced value not in value map!");
914  }
915 
916  // Remap phi nodes' incoming blocks.
917  if (PHINode *PN = dyn_cast<PHINode>(I)) {
918  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
919  Value *V = mapValue(PN->getIncomingBlock(i));
920  // If we aren't ignoring missing entries, assert that something happened.
921  if (V)
922  PN->setIncomingBlock(i, cast<BasicBlock>(V));
923  else
924  assert((Flags & RF_IgnoreMissingLocals) &&
925  "Referenced block not in value map!");
926  }
927  }
928 
929  // Remap attached metadata.
931  I->getAllMetadata(MDs);
932  for (const auto &MI : MDs) {
933  MDNode *Old = MI.second;
934  MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
935  if (New != Old)
936  I->setMetadata(MI.first, New);
937  }
938 
939  if (!TypeMapper)
940  return;
941 
942  // If the instruction's type is being remapped, do so now.
943  if (auto *CB = dyn_cast<CallBase>(I)) {
945  FunctionType *FTy = CB->getFunctionType();
946  Tys.reserve(FTy->getNumParams());
947  for (Type *Ty : FTy->params())
948  Tys.push_back(TypeMapper->remapType(Ty));
949  CB->mutateFunctionType(FunctionType::get(
950  TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
951 
952  LLVMContext &C = CB->getContext();
954  for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
955  for (int AttrIdx = Attribute::FirstTypeAttr;
956  AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
957  Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
958  if (Type *Ty =
959  Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
960  Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
961  TypeMapper->remapType(Ty));
962  break;
963  }
964  }
965  }
966  CB->setAttributes(Attrs);
967  return;
968  }
969  if (auto *AI = dyn_cast<AllocaInst>(I))
970  AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
971  if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
972  GEP->setSourceElementType(
973  TypeMapper->remapType(GEP->getSourceElementType()));
974  GEP->setResultElementType(
975  TypeMapper->remapType(GEP->getResultElementType()));
976  }
977  I->mutateType(TypeMapper->remapType(I->getType()));
978 }
979 
980 void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
982  GO.getAllMetadata(MDs);
983  GO.clearMetadata();
984  for (const auto &I : MDs)
985  GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
986 }
987 
988 void Mapper::remapFunction(Function &F) {
989  // Remap the operands.
990  for (Use &Op : F.operands())
991  if (Op)
992  Op = mapValue(Op);
993 
994  // Remap the metadata attachments.
995  remapGlobalObjectMetadata(F);
996 
997  // Remap the argument types.
998  if (TypeMapper)
999  for (Argument &A : F.args())
1000  A.mutateType(TypeMapper->remapType(A.getType()));
1001 
1002  // Remap the instructions.
1003  for (BasicBlock &BB : F)
1004  for (Instruction &I : BB)
1005  remapInstruction(&I);
1006 }
1007 
1008 void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1009  bool IsOldCtorDtor,
1010  ArrayRef<Constant *> NewMembers) {
1011  SmallVector<Constant *, 16> Elements;
1012  if (InitPrefix) {
1013  unsigned NumElements =
1014  cast<ArrayType>(InitPrefix->getType())->getNumElements();
1015  for (unsigned I = 0; I != NumElements; ++I)
1016  Elements.push_back(InitPrefix->getAggregateElement(I));
1017  }
1018 
1019  PointerType *VoidPtrTy;
1020  Type *EltTy;
1021  if (IsOldCtorDtor) {
1022  // FIXME: This upgrade is done during linking to support the C API. See
1023  // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
1024  VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
1025  auto &ST = *cast<StructType>(NewMembers.front()->getType());
1026  Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1027  EltTy = StructType::get(GV.getContext(), Tys, false);
1028  }
1029 
1030  for (auto *V : NewMembers) {
1031  Constant *NewV;
1032  if (IsOldCtorDtor) {
1033  auto *S = cast<ConstantStruct>(V);
1034  auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
1035  auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
1036  Constant *Null = Constant::getNullValue(VoidPtrTy);
1037  NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
1038  } else {
1039  NewV = cast_or_null<Constant>(mapValue(V));
1040  }
1041  Elements.push_back(NewV);
1042  }
1043 
1044  GV.setInitializer(
1045  ConstantArray::get(cast<ArrayType>(GV.getValueType()), Elements));
1046 }
1047 
1048 void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1049  unsigned MCID) {
1050  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1051  assert(MCID < MCs.size() && "Invalid mapping context");
1052 
1053  WorklistEntry WE;
1054  WE.Kind = WorklistEntry::MapGlobalInit;
1055  WE.MCID = MCID;
1056  WE.Data.GVInit.GV = &GV;
1057  WE.Data.GVInit.Init = &Init;
1058  Worklist.push_back(WE);
1059 }
1060 
1061 void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1062  Constant *InitPrefix,
1063  bool IsOldCtorDtor,
1064  ArrayRef<Constant *> NewMembers,
1065  unsigned MCID) {
1066  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1067  assert(MCID < MCs.size() && "Invalid mapping context");
1068 
1069  WorklistEntry WE;
1070  WE.Kind = WorklistEntry::MapAppendingVar;
1071  WE.MCID = MCID;
1072  WE.Data.AppendingGV.GV = &GV;
1073  WE.Data.AppendingGV.InitPrefix = InitPrefix;
1074  WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1075  WE.AppendingGVNumNewMembers = NewMembers.size();
1076  Worklist.push_back(WE);
1077  AppendingInits.append(NewMembers.begin(), NewMembers.end());
1078 }
1079 
1080 void Mapper::scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
1081  unsigned MCID) {
1082  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1083  assert((isa<GlobalAlias>(GV) || isa<GlobalIFunc>(GV)) &&
1084  "Should be alias or ifunc");
1085  assert(MCID < MCs.size() && "Invalid mapping context");
1086 
1087  WorklistEntry WE;
1088  WE.Kind = WorklistEntry::MapAliasOrIFunc;
1089  WE.MCID = MCID;
1090  WE.Data.AliasOrIFunc.GV = &GV;
1091  WE.Data.AliasOrIFunc.Target = &Target;
1092  Worklist.push_back(WE);
1093 }
1094 
1095 void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1096  assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1097  assert(MCID < MCs.size() && "Invalid mapping context");
1098 
1099  WorklistEntry WE;
1100  WE.Kind = WorklistEntry::RemapFunction;
1101  WE.MCID = MCID;
1102  WE.Data.RemapF = &F;
1103  Worklist.push_back(WE);
1104 }
1105 
1106 void Mapper::addFlags(RemapFlags Flags) {
1107  assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1108  this->Flags = this->Flags | Flags;
1109 }
1110 
1111 static Mapper *getAsMapper(void *pImpl) {
1112  return reinterpret_cast<Mapper *>(pImpl);
1113 }
1114 
1115 namespace {
1116 
1117 class FlushingMapper {
1118  Mapper &M;
1119 
1120 public:
1121  explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1122  assert(!M.hasWorkToDo() && "Expected to be flushed");
1123  }
1124 
1125  ~FlushingMapper() { M.flush(); }
1126 
1127  Mapper *operator->() const { return &M; }
1128 };
1129 
1130 } // end anonymous namespace
1131 
1133  ValueMapTypeRemapper *TypeMapper,
1134  ValueMaterializer *Materializer)
1135  : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1136 
1138 
1139 unsigned
1141  ValueMaterializer *Materializer) {
1142  return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1143 }
1144 
1146  FlushingMapper(pImpl)->addFlags(Flags);
1147 }
1148 
1150  return FlushingMapper(pImpl)->mapValue(&V);
1151 }
1152 
1154  return cast_or_null<Constant>(mapValue(C));
1155 }
1156 
1158  return FlushingMapper(pImpl)->mapMetadata(&MD);
1159 }
1160 
1162  return cast_or_null<MDNode>(mapMetadata(N));
1163 }
1164 
1166  FlushingMapper(pImpl)->remapInstruction(&I);
1167 }
1168 
1170  FlushingMapper(pImpl)->remapFunction(F);
1171 }
1172 
1174  Constant &Init,
1175  unsigned MCID) {
1176  getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1177 }
1178 
1180  Constant *InitPrefix,
1181  bool IsOldCtorDtor,
1182  ArrayRef<Constant *> NewMembers,
1183  unsigned MCID) {
1184  getAsMapper(pImpl)->scheduleMapAppendingVariable(
1185  GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1186 }
1187 
1189  unsigned MCID) {
1190  getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GA, Aliasee, MCID);
1191 }
1192 
1194  unsigned MCID) {
1195  getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GI, Resolver, MCID);
1196 }
1197 
1199  getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1200 }
i
i
Definition: README.txt:29
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
Attrs
Function Attrs
Definition: README_ALTIVEC.txt:215
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
GlobalIFunc.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::ValueMapper::scheduleMapAppendingVariable
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
Definition: ValueMapper.cpp:1179
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::AArch64CC::AL
@ AL
Definition: AArch64BaseInfo.h:269
llvm::none_of
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:1595
llvm::drop_begin
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:266
Optional.h
ValueMapper.h
llvm::StructType::get
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:408
Metadata.h
DebugInfoMetadata.h
while
while(!ItemsToConvert.empty())
Definition: NVPTXLowerArgs.cpp:201
llvm::RF_NullMapMissingGlobalValues
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
Definition: ValueMapper.h:99
llvm::Function
Definition: Function.h:62
llvm::ConstantStruct::get
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1352
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:137
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
InlineAsm.h
llvm::GlobalVariable
Definition: GlobalVariable.h:40
llvm::SmallDenseMap
Definition: DenseMap.h:880
llvm::ConstantExpr::getBitCast
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2233
llvm::FunctionType::get
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:363
llvm::BlockAddress::getBasicBlock
BasicBlock * getBasicBlock() const
Definition: Constants.h:877
llvm::GlobalAlias
Definition: GlobalAlias.h:28
llvm::ValueMapper::ValueMapper
ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Definition: ValueMapper.cpp:1132
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DenseMap.h
llvm::AttributeList
Definition: Attributes.h:398
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::ValueMapper::mapMDNode
MDNode * mapMDNode(const MDNode &N)
Definition: ValueMapper.cpp:1161
llvm::AMDGPU::Exp::Target
Target
Definition: SIDefines.h:742
llvm::Optional
Definition: APInt.h:33
GlobalObject.h
Operator.h
llvm::ValueMapper::scheduleMapGlobalInitializer
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
Definition: ValueMapper.cpp:1173
llvm::ValueMapTypeRemapper
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:36
llvm::FunctionType::getNumParams
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
llvm::ValueAsMetadata::get
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:368
STLExtras.h
llvm::SmallVectorImpl::pop_back_val
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:635
llvm::detail::DenseSetImpl< ValueT, DenseMap< ValueT, detail::DenseSetEmpty, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::insert
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
llvm::Type::getInt8Ty
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:239
llvm::ValueMapper::mapMetadata
Metadata * mapMetadata(const Metadata &MD)
Definition: ValueMapper.cpp:1157
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
llvm::ValueMapper::registerAlternateMappingContext
unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
Definition: ValueMapper.cpp:1140
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
new
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM ID Predecessors according to mbb< bb27, 0x8b0a7c0 > Note ADDri is not a two address instruction its result reg1037 is an operand of the PHI node in bb76 and its operand reg1039 is the result of the PHI node We should treat it as a two address code and make sure the ADDri is scheduled after any node that reads reg1039 Use info(i.e. register scavenger) to assign it a free register to allow reuse the collector could move the objects and invalidate the derived pointer This is bad enough in the first but safe points can crop up unpredictably **array_addr i32 n y store obj * new
Definition: README.txt:125
llvm::MDNode::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1233
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::FunctionType::isVarArg
bool isVarArg() const
Definition: DerivedTypes.h:123
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::ConstantAsMetadata::getValue
Constant * getValue() const
Definition: Metadata.h:427
wrapConstantAsMetadata
static ConstantAsMetadata * wrapConstantAsMetadata(const ConstantAsMetadata &CMD, Value *MappedV)
Definition: ValueMapper.cpp:592
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::Resolver
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2013
llvm::RF_ReuseAndMutateDistinctMDs
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
Definition: ValueMapper.h:95
Instruction.h
llvm::ValueMapper::scheduleRemapFunction
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
Definition: ValueMapper.cpp:1198
llvm::pdb::PDB_LocType::Null
@ Null
Constants.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::SmallVectorImpl::append
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:648
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::ARM_PROC::A
@ A
Definition: ARMBaseInfo.h:34
llvm::RemapFlags
RemapFlags
These are flags that the value mapping APIs allow.
Definition: ValueMapper.h:65
llvm::GlobalObject
Definition: GlobalObject.h:28
llvm::AMDGPU::PALMD::Key
Key
PAL metadata keys.
Definition: AMDGPUMetadata.h:481
DenseSet.h
getMappedOp
static unsigned getMappedOp(unsigned PseudoOp)
Definition: ARCExpandPseudos.cpp:49
llvm::Instruction
Definition: Instruction.h:45
llvm::ValueMapper::~ValueMapper
~ValueMapper()
Definition: ValueMapper.cpp:1137
llvm::ValueMapper::mapValue
Value * mapValue(const Value &V)
Definition: ValueMapper.cpp:1149
llvm::GlobalObject::addMetadata
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1268
llvm::SmallVectorImpl::resize
void resize(size_type N)
Definition: SmallVector.h:606
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1796
llvm::FunctionType::params
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:130
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
llvm::Metadata
Root of the metadata hierarchy.
Definition: Metadata.h:62
llvm::RF_NoModuleLevelChanges
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:71
llvm::None
const NoneType None
Definition: None.h:23
llvm::lltok::Kind
Kind
Definition: LLToken.h:18
llvm::InlineAsm::get
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:42
Type.h
llvm::Function::getAttributes
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:316
getAsMapper
static Mapper * getAsMapper(void *pImpl)
Definition: ValueMapper.cpp:1111
llvm::InlineAsm
Definition: InlineAsm.h:31
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::DenseSet
Implements a dense probed hash-table based set.
Definition: DenseSet.h:268
llvm::ValueMapper::remapFunction
void remapFunction(Function &F)
Definition: ValueMapper.cpp:1169
BasicBlock.h
llvm::Function::getAttributeAtIndex
Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const
gets the attribute from the list of attributes.
Definition: Function.cpp:643
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::ValueMapper::remapInstruction
void remapInstruction(Instruction &I)
Definition: ValueMapper.cpp:1165
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
llvm::ARM_MB::ST
@ ST
Definition: ARMBaseInfo.h:73
llvm::RemapFunction
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:267
llvm::ConstantPointerNull::get
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1782
llvm::ValueMapTypeRemapper::remapType
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::MDNode::replaceWithUniqued
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:1027
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::Attribute::AttrKind
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:70
llvm::PointerType
Class to represent pointers.
Definition: DerivedTypes.h:632
ArrayRef.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MDTuple::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1200
llvm::WinEH::EncodingType::CE
@ CE
Windows NT (Windows on ARM)
llvm::MDNode
Metadata node.
Definition: Metadata.h:906
llvm::BlockAddress
The address of a basic block.
Definition: Constants.h:848
llvm::ValueMapper::addFlags
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
Definition: ValueMapper.cpp:1145
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
None.h
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:134
llvm::Constant::getAggregateElement
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:420
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
llvm::MDNode::isUniqued
bool isUniqued() const
Definition: Metadata.h:985
llvm::ms_demangle::IntrinsicFunctionKind::New
@ New
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:991
llvm::ValueMapper::mapConstant
Constant * mapConstant(const Constant &C)
Definition: ValueMapper.cpp:1153
llvm::ValueAsMetadata::getConstant
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:366
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::ConstantVector::get
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1394
llvm::ifs::IFSSymbolType::Func
@ Func
llvm::ValueMap< const Value *, WeakTrackingVH >
llvm::ArrayRef::front
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:166
llvm::Init
Definition: Record.h:275
LAM
LoopAnalysisManager LAM
Definition: PassBuilderBindings.cpp:58
Argument.h
llvm::RF_IgnoreMissingLocals
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:89
llvm::ConstantAsMetadata
Definition: Metadata.h:412
j
return j(j<< 16)
llvm::BlockAddress::getFunction
Function * getFunction() const
Definition: Constants.h:876
Constant.h
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:936
llvm::Constant::getNullValue
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:348
llvm::ValueMapIterator
Definition: ValueMap.h:49
llvm::MetadataAsValue::get
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:106
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:324
llvm::ArrayRef::begin
iterator begin() const
Definition: ArrayRef.h:151
GlobalVariable.h
Casting.h
llvm::Attribute::getValueAsType
Type * getValueAsType() const
Return the attribute's value as a Type.
Definition: Attributes.cpp:308
Function.h
llvm::Type::getPointerTo
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:776
llvm::ConstantArray::get
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1288
GlobalAlias.h
llvm::makeArrayRef
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:474
llvm::MDNode::replaceWithDistinct
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:1037
llvm::ValueMapper::scheduleMapGlobalIFunc
void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
Definition: ValueMapper.cpp:1193
Instructions.h
SmallVector.h
N
#define N
llvm::BlockAddress::get
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1834
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
llvm::PHINode
Definition: Instructions.h:2666
llvm::GlobalObject::getAllMetadata
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1223
DerivedTypes.h
llvm::GlobalValue::getValueType
Type * getValueType() const
Definition: GlobalValue.h:273
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
GEP
Hexagon Common GEP
Definition: HexagonCommonGEP.cpp:172
llvm::ConstantAggregateZero::get
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1675
llvm::SmallVectorImpl::reserve
void reserve(size_type N)
Definition: SmallVector.h:624
llvm::ValueMaterializer
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:49
Value.h
llvm::GlobalIFunc
Definition: GlobalIFunc.h:34
llvm::Function::setAttributes
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:319
llvm::DSOLocalEquivalent::get
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1907
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
Debug.h
llvm::ArrayRef::end
iterator end() const
Definition: ArrayRef.h:152
llvm::MDOperand
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:753
llvm::GlobalVariable::setInitializer
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:419
llvm::FunctionType
Class to represent function types.
Definition: DerivedTypes.h:103
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::GlobalObject::clearMetadata
void clearMetadata()
Erase all metadata attached to this Value.
Definition: Metadata.cpp:1291
llvm::ValueMapper::scheduleMapGlobalAlias
void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
Definition: ValueMapper.cpp:1188