blob: 930972924c3c04d36d622a205b5c6dff4aba14d6 [file] [log] [blame]
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00001//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00009//
10// This file defines the MapValue function, which is shared by various parts of
11// the lib/Transforms/Utils library.
12//
13//===----------------------------------------------------------------------===//
14
Dan Gohmana2095032010-08-24 18:50:07 +000015#include "llvm/Transforms/Utils/ValueMapper.h"
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +000016#include "llvm/ADT/DenseSet.h"
David Blaikie348de692015-04-23 21:36:23 +000017#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +000019#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Function.h"
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000021#include "llvm/IR/GlobalAlias.h"
22#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Metadata.h"
David Blaikie88208842015-08-21 20:16:51 +000026#include "llvm/IR/Operator.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000027using namespace llvm;
Chris Lattnere4dbb1a2002-11-20 20:47:41 +000028
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000029// Out of line method to get vtable etc for class.
Craig Topper2a6a08b2012-09-26 06:36:36 +000030void ValueMapTypeRemapper::anchor() {}
James Molloyf6f121e2013-05-28 15:17:05 +000031void ValueMaterializer::anchor() {}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000032
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000033namespace {
34
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000035/// A basic block used in a BlockAddress whose function body is not yet
36/// materialized.
37struct DelayedBasicBlock {
38 BasicBlock *OldBB;
39 std::unique_ptr<BasicBlock> TempBB;
Duncan P. N. Exon Smitha9978562016-04-03 20:42:21 +000040
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000041 DelayedBasicBlock(const BlockAddress &Old)
42 : OldBB(Old.getBasicBlock()),
43 TempBB(BasicBlock::Create(Old.getContext())) {}
44};
45
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000046struct WorklistEntry {
47 enum EntryKind {
48 MapGlobalInit,
49 MapAppendingVar,
50 MapGlobalAliasee,
51 RemapFunction
52 };
53 struct GVInitTy {
54 GlobalVariable *GV;
55 Constant *Init;
56 };
57 struct AppendingGVTy {
58 GlobalVariable *GV;
59 Constant *InitPrefix;
60 };
61 struct GlobalAliaseeTy {
62 GlobalAlias *GA;
63 Constant *Aliasee;
64 };
65
66 unsigned Kind : 2;
67 unsigned MCID : 29;
68 unsigned AppendingGVIsOldCtorDtor : 1;
69 unsigned AppendingGVNumNewMembers;
70 union {
71 GVInitTy GVInit;
72 AppendingGVTy AppendingGV;
73 GlobalAliaseeTy GlobalAliasee;
74 Function *RemapF;
75 } Data;
76};
77
78struct MappingContext {
79 ValueToValueMapTy *VM;
80 ValueMaterializer *Materializer = nullptr;
81
82 /// Construct a MappingContext with a value map and materializer.
83 explicit MappingContext(ValueToValueMapTy &VM,
84 ValueMaterializer *Materializer = nullptr)
85 : VM(&VM), Materializer(Materializer) {}
86};
87
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000088class MDNodeMapper;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000089class Mapper {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000090 friend class MDNodeMapper;
91
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +000092#ifndef NDEBUG
93 DenseSet<GlobalValue *> AlreadyScheduled;
94#endif
95
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000096 RemapFlags Flags;
97 ValueMapTypeRemapper *TypeMapper;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000098 unsigned CurrentMCID = 0;
99 SmallVector<MappingContext, 2> MCs;
100 SmallVector<WorklistEntry, 4> Worklist;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000101 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000102 SmallVector<Constant *, 16> AppendingInits;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000103
104public:
105 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
106 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000107 : Flags(Flags), TypeMapper(TypeMapper),
108 MCs(1, MappingContext(VM, Materializer)) {}
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000109
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000110 /// ValueMapper should explicitly call \a flush() before destruction.
111 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
112
113 bool hasWorkToDo() const { return !Worklist.empty(); }
114
115 unsigned
116 registerAlternateMappingContext(ValueToValueMapTy &VM,
117 ValueMaterializer *Materializer = nullptr) {
118 MCs.push_back(MappingContext(VM, Materializer));
119 return MCs.size() - 1;
120 }
121
122 void addFlags(RemapFlags Flags);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000123
Evgeniy Stepanov9aff8292017-05-04 23:29:39 +0000124 void remapGlobalObjectMetadata(GlobalObject &GO);
125
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000126 Value *mapValue(const Value *V);
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000127 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000128 void remapFunction(Function &F);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000129
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000130 Constant *mapConstant(const Constant *C) {
131 return cast_or_null<Constant>(mapValue(C));
132 }
133
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000134 /// Map metadata.
135 ///
136 /// Find the mapping for MD. Guarantees that the return will be resolved
137 /// (not an MDNode, or MDNode::isResolved() returns true).
138 Metadata *mapMetadata(const Metadata *MD);
139
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000140 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
141 unsigned MCID);
142 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
143 bool IsOldCtorDtor,
144 ArrayRef<Constant *> NewMembers,
145 unsigned MCID);
146 void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
147 unsigned MCID);
148 void scheduleRemapFunction(Function &F, unsigned MCID);
149
150 void flush();
151
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000152private:
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000153 void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
154 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
155 bool IsOldCtorDtor,
156 ArrayRef<Constant *> NewMembers);
157 void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
158 void remapFunction(Function &F, ValueToValueMapTy &VM);
159
160 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
161 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000162
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000163 Value *mapBlockAddress(const BlockAddress &BA);
164
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000165 /// Map metadata that doesn't require visiting operands.
166 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
167
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000168 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
169 Metadata *mapToSelf(const Metadata *MD);
170};
171
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000172class MDNodeMapper {
173 Mapper &M;
174
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000175 /// Data about a node in \a UniquedGraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000176 struct Data {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000177 bool HasChanged = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000178 unsigned ID = ~0u;
179 TempMDNode Placeholder;
180 };
181
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000182 /// A graph of uniqued nodes.
183 struct UniquedGraph {
184 SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
185 SmallVector<MDNode *, 16> POT; // Post-order traversal.
186
187 /// Propagate changed operands through the post-order traversal.
188 ///
189 /// Iteratively update \a Data::HasChanged for each node based on \a
190 /// Data::HasChanged of its operands, until fixed point.
191 void propagateChanges();
192
193 /// Get a forward reference to a node to use as an operand.
194 Metadata &getFwdReference(MDNode &Op);
195 };
196
197 /// Worklist of distinct nodes whose operands need to be remapped.
198 SmallVector<MDNode *, 16> DistinctWorklist;
199
200 // Storage for a UniquedGraph.
201 SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
202 SmallVector<MDNode *, 16> POTStorage;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000203
204public:
205 MDNodeMapper(Mapper &M) : M(M) {}
206
207 /// Map a metadata node (and its transitive operands).
208 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000209 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
210 /// algorithm handles distinct nodes and uniqued node subgraphs using
211 /// different strategies.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000212 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000213 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
214 /// using \a mapDistinctNode(). Their mapping can always be computed
215 /// immediately without visiting operands, even if their operands change.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000216 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000217 /// The mapping for uniqued nodes depends on whether their operands change.
218 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
219 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
220 /// added to \a DistinctWorklist with \a mapDistinctNode().
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000221 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000222 /// After mapping \c N itself, this function remaps the operands of the
223 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
224 /// N has been mapped.
225 Metadata *map(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000226
227private:
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000228 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
229 ///
230 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
231 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
232 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
233 /// operands uses the identity mapping.
234 ///
235 /// The algorithm works as follows:
236 ///
237 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
238 /// save the post-order traversal in the given \a UniquedGraph, tracking
239 /// nodes' operands change.
240 ///
241 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
242 /// through the \a UniquedGraph until fixed point, following the rule
243 /// that if a node changes, any node that references must also change.
244 ///
245 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
246 /// (referencing new operands) where necessary.
247 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000248
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000249 /// Try to map the operand of an \a MDNode.
250 ///
251 /// If \c Op is already mapped, return the mapping. If it's not an \a
252 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
253 /// return the result of \a mapDistinctNode().
254 ///
255 /// \return None if \c Op is an unmapped uniqued \a MDNode.
256 /// \post getMappedOp(Op) only returns None if this returns None.
257 Optional<Metadata *> tryToMapOperand(const Metadata *Op);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000258
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000259 /// Map a distinct node.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000260 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000261 /// Return the mapping for the distinct node \c N, saving the result in \a
262 /// DistinctWorklist for later remapping.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000263 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000264 /// \pre \c N is not yet mapped.
265 /// \pre \c N.isDistinct().
266 MDNode *mapDistinctNode(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000267
268 /// Get a previously mapped node.
269 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
270
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000271 /// Create a post-order traversal of an unmapped uniqued node subgraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000272 ///
273 /// This traverses the metadata graph deeply enough to map \c FirstN. It
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000274 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000275 /// metadata that has already been mapped will not be part of the POT.
276 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000277 /// Each node that has a changed operand from outside the graph (e.g., a
278 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
279 /// is marked with \a Data::HasChanged.
280 ///
281 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
282 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
283 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
284 /// to change because of operands outside the graph.
285 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000286
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000287 /// Visit the operands of a uniqued node in the POT.
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000288 ///
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000289 /// Visit the operands in the range from \c I to \c E, returning the first
290 /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
291 /// where to continue the loop through the operands.
292 ///
293 /// This sets \c HasChanged if any of the visited operands change.
294 MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
295 MDNode::op_iterator E, bool &HasChanged);
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000296
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000297 /// Map all the nodes in the given uniqued graph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000298 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000299 /// This visits all the nodes in \c G in post-order, using the identity
300 /// mapping or creating a new node depending on \a Data::HasChanged.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000301 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000302 /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
303 /// their operands outside of \c G.
304 /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
305 /// operands have changed.
306 /// \post \a getMappedOp() returns the mapped node for every node in \c G.
307 void mapNodesInPOT(UniquedGraph &G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000308
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000309 /// Remap a node's operands using the given functor.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000310 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000311 /// Iterate through the operands of \c N and update them in place using \c
312 /// mapOperand.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000313 ///
314 /// \pre N.isDistinct() or N.isTemporary().
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000315 template <class OperandMapper>
316 void remapOperands(MDNode &N, OperandMapper mapOperand);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000317};
318
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000319} // end namespace
320
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000321Value *Mapper::mapValue(const Value *V) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000322 ValueToValueMapTy::iterator I = getVM().find(V);
323
Chris Lattner43f8d162011-01-08 08:15:20 +0000324 // If the value already exists in the map, use it.
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000325 if (I != getVM().end()) {
326 assert(I->second && "Unexpected null mapping");
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000327 return I->second;
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000328 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000329
James Molloyf6f121e2013-05-28 15:17:05 +0000330 // If we have a materializer and it can materialize a value, use that.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000331 if (auto *Materializer = getMaterializer()) {
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000332 if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
333 getVM()[V] = NewV;
334 return NewV;
Rafael Espindola19b52382015-11-27 20:28:19 +0000335 }
James Molloyf6f121e2013-05-28 15:17:05 +0000336 }
337
Dan Gohmanca26f792010-08-26 15:41:53 +0000338 // Global values do not need to be seeded into the VM if they
339 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000340 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000341 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000342 return nullptr;
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000343 return getVM()[V] = const_cast<Value *>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000344 }
345
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000346 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
347 // Inline asm may need *type* remapping.
348 FunctionType *NewTy = IA->getFunctionType();
349 if (TypeMapper) {
350 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
351
352 if (NewTy != IA->getFunctionType())
353 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
354 IA->hasSideEffects(), IA->isAlignStack());
355 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000356
357 return getVM()[V] = const_cast<Value *>(V);
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000358 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000359
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000360 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
361 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000362
363 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
364 // Look through to grab the local value.
365 if (Value *LV = mapValue(LAM->getValue())) {
366 if (V == LAM->getValue())
367 return const_cast<Value *>(V);
368 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
369 }
370
371 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
372 // ensures metadata operands only reference defined SSA values.
373 return (Flags & RF_IgnoreMissingLocals)
374 ? nullptr
375 : MetadataAsValue::get(V->getContext(),
376 MDTuple::get(V->getContext(), None));
377 }
378
Chris Lattner43f8d162011-01-08 08:15:20 +0000379 // If this is a module-level metadata and we know that nothing at the module
380 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000381 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000382 return getVM()[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000383
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000384 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000385 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000386 if (MD == MappedMD)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000387 return getVM()[V] = const_cast<Value *>(V);
388 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000389 }
390
Chris Lattner43f8d162011-01-08 08:15:20 +0000391 // Okay, this either must be a constant (which may or may not be mappable) or
392 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000393 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000394 if (!C)
395 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000396
397 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
398 return mapBlockAddress(*BA);
399
Mehdi Aminibcc47412016-05-28 17:26:03 +0000400 auto mapValueOrNull = [this](Value *V) {
401 auto Mapped = mapValue(V);
402 assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
403 "Unexpected null mapping for constant operand without "
404 "NullMapMissingGlobalValues flag");
405 return Mapped;
406 };
407
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000408 // Otherwise, we have some other constant to remap. Start by checking to see
409 // if all operands have an identity remapping.
410 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000411 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 for (; OpNo != NumOperands; ++OpNo) {
413 Value *Op = C->getOperand(OpNo);
Mehdi Aminibcc47412016-05-28 17:26:03 +0000414 Mapped = mapValueOrNull(Op);
415 if (!Mapped)
416 return nullptr;
Mehdi Amini9ee054ae2016-05-27 00:32:12 +0000417 if (Mapped != Op)
418 break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000419 }
Junmo Park95529872016-05-08 23:22:58 +0000420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000421 // See if the type mapper wants to remap the type as well.
422 Type *NewTy = C->getType();
423 if (TypeMapper)
424 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000425
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000426 // If the result type and all operands match up, then just insert an identity
427 // mapping.
428 if (OpNo == NumOperands && NewTy == C->getType())
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000429 return getVM()[V] = C;
430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 // Okay, we need to create a new constant. We've already processed some or
432 // all of the operands, set them all up now.
433 SmallVector<Constant*, 8> Ops;
434 Ops.reserve(NumOperands);
435 for (unsigned j = 0; j != OpNo; ++j)
436 Ops.push_back(cast<Constant>(C->getOperand(j)));
Junmo Park95529872016-05-08 23:22:58 +0000437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000438 // If one of the operands mismatch, push it and the other mapped operands.
439 if (OpNo != NumOperands) {
440 Ops.push_back(cast<Constant>(Mapped));
Junmo Park95529872016-05-08 23:22:58 +0000441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000442 // Map the rest of the operands that aren't processed yet.
Mehdi Aminibcc47412016-05-28 17:26:03 +0000443 for (++OpNo; OpNo != NumOperands; ++OpNo) {
444 Mapped = mapValueOrNull(C->getOperand(OpNo));
445 if (!Mapped)
446 return nullptr;
447 Ops.push_back(cast<Constant>(Mapped));
448 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000449 }
David Blaikie88208842015-08-21 20:16:51 +0000450 Type *NewSrcTy = nullptr;
451 if (TypeMapper)
452 if (auto *GEPO = dyn_cast<GEPOperator>(C))
453 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000455 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000456 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000457 if (isa<ConstantArray>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000458 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000459 if (isa<ConstantStruct>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000460 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 if (isa<ConstantVector>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000462 return getVM()[V] = ConstantVector::get(Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000463 // If this is a no-operand constant, it must be because the type was remapped.
464 if (isa<UndefValue>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000465 return getVM()[V] = UndefValue::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 if (isa<ConstantAggregateZero>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000467 return getVM()[V] = ConstantAggregateZero::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000468 assert(isa<ConstantPointerNull>(C));
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000469 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000470}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000471
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000472Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
473 Function *F = cast<Function>(mapValue(BA.getFunction()));
474
475 // F may not have materialized its initializer. In that case, create a
476 // dummy basic block for now, and replace it once we've materialized all
477 // the initializers.
478 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000479 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000480 DelayedBBs.push_back(DelayedBasicBlock(BA));
481 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000482 } else {
483 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000484 }
485
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000486 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000487}
488
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000489Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000490 getVM().MD()[Key].reset(Val);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000491 return Val;
492}
493
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000494Metadata *Mapper::mapToSelf(const Metadata *MD) {
495 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000496}
497
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000498Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000499 if (!Op)
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000500 return nullptr;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000501
502 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Simon Atanasyane12bef72016-04-16 11:49:40 +0000503#ifndef NDEBUG
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000504 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
505 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
506 M.getVM().getMappedMD(Op)) &&
507 "Expected Value to be memoized");
508 else
509 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
510 "Expected result to be memoized");
Simon Atanasyane12bef72016-04-16 11:49:40 +0000511#endif
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000512 return *MappedOp;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000513 }
514
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000515 const MDNode &N = *cast<MDNode>(Op);
516 if (N.isDistinct())
517 return mapDistinctNode(N);
518 return None;
519}
520
521MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
522 assert(N.isDistinct() && "Expected a distinct node");
523 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
524 DistinctWorklist.push_back(cast<MDNode>(
525 (M.Flags & RF_MoveDistinctMDs)
526 ? M.mapToSelf(&N)
527 : M.mapToMetadata(&N, MDNode::replaceWithDistinct(N.clone()))));
528 return DistinctWorklist.back();
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000529}
530
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000531static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
532 Value *MappedV) {
533 if (CMD.getValue() == MappedV)
534 return const_cast<ConstantAsMetadata *>(&CMD);
535 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
536}
537
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000538Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000539 if (!Op)
540 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000541
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000542 if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000543 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000544
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000545 if (isa<MDString>(Op))
546 return const_cast<Metadata *>(Op);
547
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000548 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
549 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
550
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000551 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000552}
553
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000554Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000555 auto Where = Info.find(&Op);
556 assert(Where != Info.end() && "Expected a valid reference");
557
558 auto &OpD = Where->second;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000559 if (!OpD.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000560 return Op;
561
562 // Lazily construct a temporary node.
563 if (!OpD.Placeholder)
564 OpD.Placeholder = Op.clone();
565
566 return *OpD.Placeholder;
567}
568
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000569template <class OperandMapper>
570void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
571 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000572 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
573 Metadata *Old = N.getOperand(I);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000574 Metadata *New = mapOperand(Old);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000575
576 if (Old != New)
577 N.replaceOperandWith(I, New);
578 }
579}
580
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000581namespace {
582/// An entry in the worklist for the post-order traversal.
583struct POTWorklistEntry {
584 MDNode *N; ///< Current node.
585 MDNode::op_iterator Op; ///< Current operand of \c N.
586
587 /// Keep a flag of whether operands have changed in the worklist to avoid
588 /// hitting the map in \a UniquedGraph.
589 bool HasChanged = false;
590
591 POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
592};
593} // end namespace
594
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000595bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
596 assert(G.Info.empty() && "Expected a fresh traversal");
597 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000598
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000599 // Construct a post-order traversal of the uniqued subgraph under FirstN.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000600 bool AnyChanges = false;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000601 SmallVector<POTWorklistEntry, 16> Worklist;
602 Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000603 (void)G.Info[&FirstN];
604 while (!Worklist.empty()) {
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000605 // Start or continue the traversal through the this node's operands.
606 auto &WE = Worklist.back();
607 if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
608 // Push a new node to traverse first.
609 Worklist.push_back(POTWorklistEntry(*N));
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000610 continue;
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000611 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000612
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000613 // Push the node onto the POT.
614 assert(WE.N->isUniqued() && "Expected only uniqued nodes");
615 assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
616 auto &D = G.Info[WE.N];
617 AnyChanges |= D.HasChanged = WE.HasChanged;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000618 D.ID = G.POT.size();
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000619 G.POT.push_back(WE.N);
620
621 // Pop the node off the worklist.
622 Worklist.pop_back();
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000623 }
624 return AnyChanges;
625}
626
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000627MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
628 MDNode::op_iterator E, bool &HasChanged) {
629 while (I != E) {
630 Metadata *Op = *I++; // Increment even on early return.
631 if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
632 // Check if the operand changes.
633 HasChanged |= Op != *MappedOp;
634 continue;
635 }
636
637 // A uniqued metadata node.
638 MDNode &OpN = *cast<MDNode>(Op);
639 assert(OpN.isUniqued() &&
640 "Only uniqued operands cannot be mapped immediately");
641 if (G.Info.insert(std::make_pair(&OpN, Data())).second)
642 return &OpN; // This is a new one. Return it.
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000643 }
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000644 return nullptr;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000645}
646
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000647void MDNodeMapper::UniquedGraph::propagateChanges() {
648 bool AnyChanges;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000649 do {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000650 AnyChanges = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000651 for (MDNode *N : POT) {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000652 auto &D = Info[N];
653 if (D.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000654 continue;
655
David Majnemer0a16c222016-08-11 21:15:00 +0000656 if (none_of(N->operands(), [&](const Metadata *Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000657 auto Where = Info.find(Op);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000658 return Where != Info.end() && Where->second.HasChanged;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000659 }))
660 continue;
661
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000662 AnyChanges = D.HasChanged = true;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000663 }
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000664 } while (AnyChanges);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000665}
666
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000667void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000668 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000669 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000670 for (auto *N : G.POT) {
671 auto &D = G.Info[N];
672 if (!D.HasChanged) {
673 // The node hasn't changed.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000674 M.mapToSelf(N);
675 continue;
676 }
677
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000678 // Remember whether this node had a placeholder.
679 bool HadPlaceholder(D.Placeholder);
680
681 // Clone the uniqued node and remap the operands.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000682 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000683 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
684 if (Optional<Metadata *> MappedOp = getMappedOp(Old))
685 return *MappedOp;
David L. Jones41cecba2017-01-13 21:02:41 +0000686 (void)D;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000687 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
688 return &G.getFwdReference(*cast<MDNode>(Old));
689 });
690
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000691 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
692 M.mapToMetadata(N, NewN);
693
694 // Nodes that were referenced out of order in the POT are involved in a
695 // uniquing cycle.
696 if (HadPlaceholder)
697 CyclicNodes.push_back(NewN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000698 }
699
700 // Resolve cycles.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000701 for (auto *N : CyclicNodes)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000702 if (!N->isResolved())
703 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000704}
705
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000706Metadata *MDNodeMapper::map(const MDNode &N) {
707 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000708 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
709 "MDNodeMapper::map assumes module-level changes");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000710
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000711 // Require resolved nodes whenever metadata might be remapped.
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000712 assert(N.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000713
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000714 Metadata *MappedN =
715 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
716 while (!DistinctWorklist.empty())
717 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
718 if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
719 return *MappedOp;
720 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
721 });
722 return MappedN;
723}
724
725Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
726 assert(FirstN.isUniqued() && "Expected uniqued node");
727
728 // Create a post-order traversal of uniqued nodes under FirstN.
729 UniquedGraph G;
730 if (!createPOT(G, FirstN)) {
731 // Return early if no nodes have changed.
732 for (const MDNode *N : G.POT)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000733 M.mapToSelf(N);
734 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000735 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000736
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000737 // Update graph with all nodes that have changed.
738 G.propagateChanges();
739
740 // Map all the nodes in the graph.
741 mapNodesInPOT(G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000742
743 // Return the original node, remapped.
744 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000745}
746
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000747namespace {
748
749struct MapMetadataDisabler {
750 ValueToValueMapTy &VM;
751
752 MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
753 VM.disableMapMetadata();
754 }
755 ~MapMetadataDisabler() { VM.enableMapMetadata(); }
756};
757
758} // end namespace
759
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000760Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000761 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000762 if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000763 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000764
765 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000766 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000767
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000768 // This is a module-level metadata. If nothing at the module level is
769 // changing, use an identity mapping.
770 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000771 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000772
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000773 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000774 // Disallow recursion into metadata mapping through mapValue.
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000775 MapMetadataDisabler MMD(getVM());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000776
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000777 // Don't memoize ConstantAsMetadata. Instead of lasting until the
778 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
779 // reference is destructed. These aren't super common, so the extra
780 // indirection isn't that expensive.
781 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000782 }
783
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000784 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000785
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000786 return None;
787}
788
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000789Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000790 assert(MD && "Expected valid metadata");
791 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
792
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000793 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
794 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000795
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000796 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000797}
798
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000799void Mapper::flush() {
800 // Flush out the worklist of global values.
801 while (!Worklist.empty()) {
802 WorklistEntry E = Worklist.pop_back_val();
803 CurrentMCID = E.MCID;
804 switch (E.Kind) {
805 case WorklistEntry::MapGlobalInit:
806 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
Evgeniy Stepanov9aff8292017-05-04 23:29:39 +0000807 remapGlobalObjectMetadata(*E.Data.GVInit.GV);
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000808 break;
809 case WorklistEntry::MapAppendingVar: {
810 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
811 mapAppendingVariable(*E.Data.AppendingGV.GV,
812 E.Data.AppendingGV.InitPrefix,
813 E.AppendingGVIsOldCtorDtor,
814 makeArrayRef(AppendingInits).slice(PrefixSize));
815 AppendingInits.resize(PrefixSize);
816 break;
817 }
818 case WorklistEntry::MapGlobalAliasee:
819 E.Data.GlobalAliasee.GA->setAliasee(
820 mapConstant(E.Data.GlobalAliasee.Aliasee));
821 break;
822 case WorklistEntry::RemapFunction:
823 remapFunction(*E.Data.RemapF);
824 break;
825 }
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000826 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000827 CurrentMCID = 0;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000828
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000829 // Finish logic for block addresses now that all global values have been
830 // handled.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000831 while (!DelayedBBs.empty()) {
832 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
833 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
834 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
835 }
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000836}
837
838void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000839 // Remap operands.
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000840 for (Use &Op : I->operands()) {
841 Value *V = mapValue(Op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000842 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (V)
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000844 Op = V;
Chris Lattner43f8d162011-01-08 08:15:20 +0000845 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000846 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000847 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000848 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000849
Jay Foad61ea0e42011-06-23 09:09:15 +0000850 // Remap phi nodes' incoming blocks.
851 if (PHINode *PN = dyn_cast<PHINode>(I)) {
852 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smithadcebdf2016-04-08 19:17:13 +0000853 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad61ea0e42011-06-23 09:09:15 +0000854 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000855 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000856 PN->setIncomingBlock(i, cast<BasicBlock>(V));
857 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000858 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000859 "Referenced block not in value map!");
860 }
861 }
862
Devang Patelc0174042011-08-04 20:02:18 +0000863 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000864 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000865 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000866 for (const auto &MI : MDs) {
867 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000868 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000869 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000870 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000871 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000872
David Blaikie348de692015-04-23 21:36:23 +0000873 if (!TypeMapper)
874 return;
875
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000876 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000877 if (auto CS = CallSite(I)) {
878 SmallVector<Type *, 3> Tys;
879 FunctionType *FTy = CS.getFunctionType();
880 Tys.reserve(FTy->getNumParams());
881 for (Type *Ty : FTy->params())
882 Tys.push_back(TypeMapper->remapType(Ty));
883 CS.mutateFunctionType(FunctionType::get(
884 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000885 return;
886 }
887 if (auto *AI = dyn_cast<AllocaInst>(I))
888 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000889 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000890 GEP->setSourceElementType(
891 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000892 GEP->setResultElementType(
893 TypeMapper->remapType(GEP->getResultElementType()));
894 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000895 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000896}
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000897
Evgeniy Stepanov9aff8292017-05-04 23:29:39 +0000898void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
899 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
900 GO.getAllMetadata(MDs);
901 GO.clearMetadata();
902 for (const auto &I : MDs)
903 GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
904}
905
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000906void Mapper::remapFunction(Function &F) {
907 // Remap the operands.
908 for (Use &Op : F.operands())
909 if (Op)
910 Op = mapValue(Op);
911
912 // Remap the metadata attachments.
Evgeniy Stepanov9aff8292017-05-04 23:29:39 +0000913 remapGlobalObjectMetadata(F);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000914
915 // Remap the argument types.
916 if (TypeMapper)
917 for (Argument &A : F.args())
918 A.mutateType(TypeMapper->remapType(A.getType()));
919
920 // Remap the instructions.
921 for (BasicBlock &BB : F)
922 for (Instruction &I : BB)
923 remapInstruction(&I);
924}
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000925
926void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
927 bool IsOldCtorDtor,
928 ArrayRef<Constant *> NewMembers) {
929 SmallVector<Constant *, 16> Elements;
930 if (InitPrefix) {
931 unsigned NumElements =
932 cast<ArrayType>(InitPrefix->getType())->getNumElements();
933 for (unsigned I = 0; I != NumElements; ++I)
934 Elements.push_back(InitPrefix->getAggregateElement(I));
935 }
936
937 PointerType *VoidPtrTy;
938 Type *EltTy;
939 if (IsOldCtorDtor) {
940 // FIXME: This upgrade is done during linking to support the C API. See
941 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
942 VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
943 auto &ST = *cast<StructType>(NewMembers.front()->getType());
944 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
945 EltTy = StructType::get(GV.getContext(), Tys, false);
946 }
947
948 for (auto *V : NewMembers) {
949 Constant *NewV;
950 if (IsOldCtorDtor) {
951 auto *S = cast<ConstantStruct>(V);
Serge Gueltone38003f2017-05-09 19:31:13 +0000952 auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
953 auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
954 Constant *Null = Constant::getNullValue(VoidPtrTy);
955 NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000956 } else {
957 NewV = cast_or_null<Constant>(mapValue(V));
958 }
959 Elements.push_back(NewV);
960 }
961
962 GV.setInitializer(ConstantArray::get(
963 cast<ArrayType>(GV.getType()->getElementType()), Elements));
964}
965
966void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
967 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000968 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000969 assert(MCID < MCs.size() && "Invalid mapping context");
970
971 WorklistEntry WE;
972 WE.Kind = WorklistEntry::MapGlobalInit;
973 WE.MCID = MCID;
974 WE.Data.GVInit.GV = &GV;
975 WE.Data.GVInit.Init = &Init;
976 Worklist.push_back(WE);
977}
978
979void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
980 Constant *InitPrefix,
981 bool IsOldCtorDtor,
982 ArrayRef<Constant *> NewMembers,
983 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000984 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000985 assert(MCID < MCs.size() && "Invalid mapping context");
986
987 WorklistEntry WE;
988 WE.Kind = WorklistEntry::MapAppendingVar;
989 WE.MCID = MCID;
990 WE.Data.AppendingGV.GV = &GV;
991 WE.Data.AppendingGV.InitPrefix = InitPrefix;
992 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
993 WE.AppendingGVNumNewMembers = NewMembers.size();
994 Worklist.push_back(WE);
995 AppendingInits.append(NewMembers.begin(), NewMembers.end());
996}
997
998void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
999 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +00001000 assert(AlreadyScheduled.insert(&GA).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001001 assert(MCID < MCs.size() && "Invalid mapping context");
1002
1003 WorklistEntry WE;
1004 WE.Kind = WorklistEntry::MapGlobalAliasee;
1005 WE.MCID = MCID;
1006 WE.Data.GlobalAliasee.GA = &GA;
1007 WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1008 Worklist.push_back(WE);
1009}
1010
1011void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +00001012 assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001013 assert(MCID < MCs.size() && "Invalid mapping context");
1014
1015 WorklistEntry WE;
1016 WE.Kind = WorklistEntry::RemapFunction;
1017 WE.MCID = MCID;
1018 WE.Data.RemapF = &F;
1019 Worklist.push_back(WE);
1020}
1021
1022void Mapper::addFlags(RemapFlags Flags) {
1023 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1024 this->Flags = this->Flags | Flags;
1025}
1026
1027static Mapper *getAsMapper(void *pImpl) {
1028 return reinterpret_cast<Mapper *>(pImpl);
1029}
1030
1031namespace {
1032
1033class FlushingMapper {
1034 Mapper &M;
1035
1036public:
1037 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1038 assert(!M.hasWorkToDo() && "Expected to be flushed");
1039 }
1040 ~FlushingMapper() { M.flush(); }
1041 Mapper *operator->() const { return &M; }
1042};
1043
1044} // end namespace
1045
1046ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1047 ValueMapTypeRemapper *TypeMapper,
1048 ValueMaterializer *Materializer)
1049 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1050
1051ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1052
1053unsigned
1054ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1055 ValueMaterializer *Materializer) {
1056 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1057}
1058
1059void ValueMapper::addFlags(RemapFlags Flags) {
1060 FlushingMapper(pImpl)->addFlags(Flags);
1061}
1062
1063Value *ValueMapper::mapValue(const Value &V) {
1064 return FlushingMapper(pImpl)->mapValue(&V);
1065}
1066
1067Constant *ValueMapper::mapConstant(const Constant &C) {
1068 return cast_or_null<Constant>(mapValue(C));
1069}
1070
1071Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1072 return FlushingMapper(pImpl)->mapMetadata(&MD);
1073}
1074
1075MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1076 return cast_or_null<MDNode>(mapMetadata(N));
1077}
1078
1079void ValueMapper::remapInstruction(Instruction &I) {
1080 FlushingMapper(pImpl)->remapInstruction(&I);
1081}
1082
1083void ValueMapper::remapFunction(Function &F) {
1084 FlushingMapper(pImpl)->remapFunction(F);
1085}
1086
1087void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1088 Constant &Init,
1089 unsigned MCID) {
1090 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1091}
1092
1093void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1094 Constant *InitPrefix,
1095 bool IsOldCtorDtor,
1096 ArrayRef<Constant *> NewMembers,
1097 unsigned MCID) {
1098 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1099 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1100}
1101
1102void ValueMapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1103 unsigned MCID) {
1104 getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1105}
1106
1107void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1108 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1109}