blob: f77c10b6dd4730f253f08289bdf4bc1183cd0d1d [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
124 Value *mapValue(const Value *V);
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000125 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000126 void remapFunction(Function &F);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000127
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000128 Constant *mapConstant(const Constant *C) {
129 return cast_or_null<Constant>(mapValue(C));
130 }
131
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000132 /// Map metadata.
133 ///
134 /// Find the mapping for MD. Guarantees that the return will be resolved
135 /// (not an MDNode, or MDNode::isResolved() returns true).
136 Metadata *mapMetadata(const Metadata *MD);
137
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000138 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
139 unsigned MCID);
140 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
141 bool IsOldCtorDtor,
142 ArrayRef<Constant *> NewMembers,
143 unsigned MCID);
144 void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
145 unsigned MCID);
146 void scheduleRemapFunction(Function &F, unsigned MCID);
147
148 void flush();
149
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000150private:
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000151 void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
152 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
153 bool IsOldCtorDtor,
154 ArrayRef<Constant *> NewMembers);
155 void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
156 void remapFunction(Function &F, ValueToValueMapTy &VM);
157
158 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
159 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000160
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000161 Value *mapBlockAddress(const BlockAddress &BA);
162
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000163 /// Map metadata that doesn't require visiting operands.
164 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
165
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000166 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
167 Metadata *mapToSelf(const Metadata *MD);
168};
169
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000170class MDNodeMapper {
171 Mapper &M;
172
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000173 /// Data about a node in \a UniquedGraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000174 struct Data {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000175 bool HasChanged = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000176 unsigned ID = ~0u;
177 TempMDNode Placeholder;
178 };
179
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000180 /// A graph of uniqued nodes.
181 struct UniquedGraph {
182 SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
183 SmallVector<MDNode *, 16> POT; // Post-order traversal.
184
185 /// Propagate changed operands through the post-order traversal.
186 ///
187 /// Iteratively update \a Data::HasChanged for each node based on \a
188 /// Data::HasChanged of its operands, until fixed point.
189 void propagateChanges();
190
191 /// Get a forward reference to a node to use as an operand.
192 Metadata &getFwdReference(MDNode &Op);
193 };
194
195 /// Worklist of distinct nodes whose operands need to be remapped.
196 SmallVector<MDNode *, 16> DistinctWorklist;
197
198 // Storage for a UniquedGraph.
199 SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
200 SmallVector<MDNode *, 16> POTStorage;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000201
202public:
203 MDNodeMapper(Mapper &M) : M(M) {}
204
205 /// Map a metadata node (and its transitive operands).
206 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000207 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
208 /// algorithm handles distinct nodes and uniqued node subgraphs using
209 /// different strategies.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000210 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000211 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
212 /// using \a mapDistinctNode(). Their mapping can always be computed
213 /// immediately without visiting operands, even if their operands change.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000214 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000215 /// The mapping for uniqued nodes depends on whether their operands change.
216 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
217 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
218 /// added to \a DistinctWorklist with \a mapDistinctNode().
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000219 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000220 /// After mapping \c N itself, this function remaps the operands of the
221 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
222 /// N has been mapped.
223 Metadata *map(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000224
225private:
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000226 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
227 ///
228 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
229 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
230 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
231 /// operands uses the identity mapping.
232 ///
233 /// The algorithm works as follows:
234 ///
235 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
236 /// save the post-order traversal in the given \a UniquedGraph, tracking
237 /// nodes' operands change.
238 ///
239 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
240 /// through the \a UniquedGraph until fixed point, following the rule
241 /// that if a node changes, any node that references must also change.
242 ///
243 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
244 /// (referencing new operands) where necessary.
245 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000246
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000247 /// Try to map the operand of an \a MDNode.
248 ///
249 /// If \c Op is already mapped, return the mapping. If it's not an \a
250 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
251 /// return the result of \a mapDistinctNode().
252 ///
253 /// \return None if \c Op is an unmapped uniqued \a MDNode.
254 /// \post getMappedOp(Op) only returns None if this returns None.
255 Optional<Metadata *> tryToMapOperand(const Metadata *Op);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000256
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000257 /// Map a distinct node.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000258 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000259 /// Return the mapping for the distinct node \c N, saving the result in \a
260 /// DistinctWorklist for later remapping.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000261 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000262 /// \pre \c N is not yet mapped.
263 /// \pre \c N.isDistinct().
264 MDNode *mapDistinctNode(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000265
266 /// Get a previously mapped node.
267 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
268
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000269 /// Create a post-order traversal of an unmapped uniqued node subgraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000270 ///
271 /// This traverses the metadata graph deeply enough to map \c FirstN. It
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000272 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000273 /// metadata that has already been mapped will not be part of the POT.
274 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000275 /// Each node that has a changed operand from outside the graph (e.g., a
276 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
277 /// is marked with \a Data::HasChanged.
278 ///
279 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
280 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
281 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
282 /// to change because of operands outside the graph.
283 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000284
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000285 /// Visit the operands of a uniqued node in the POT.
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000286 ///
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000287 /// Visit the operands in the range from \c I to \c E, returning the first
288 /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
289 /// where to continue the loop through the operands.
290 ///
291 /// This sets \c HasChanged if any of the visited operands change.
292 MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
293 MDNode::op_iterator E, bool &HasChanged);
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000294
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000295 /// Map all the nodes in the given uniqued graph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000296 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000297 /// This visits all the nodes in \c G in post-order, using the identity
298 /// mapping or creating a new node depending on \a Data::HasChanged.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000299 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000300 /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
301 /// their operands outside of \c G.
302 /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
303 /// operands have changed.
304 /// \post \a getMappedOp() returns the mapped node for every node in \c G.
305 void mapNodesInPOT(UniquedGraph &G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000306
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000307 /// Remap a node's operands using the given functor.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000308 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000309 /// Iterate through the operands of \c N and update them in place using \c
310 /// mapOperand.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000311 ///
312 /// \pre N.isDistinct() or N.isTemporary().
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000313 template <class OperandMapper>
314 void remapOperands(MDNode &N, OperandMapper mapOperand);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000315};
316
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000317} // end namespace
318
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000319Value *Mapper::mapValue(const Value *V) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000320 ValueToValueMapTy::iterator I = getVM().find(V);
321
Chris Lattner43f8d162011-01-08 08:15:20 +0000322 // If the value already exists in the map, use it.
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000323 if (I != getVM().end()) {
324 assert(I->second && "Unexpected null mapping");
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000325 return I->second;
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000326 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000327
James Molloyf6f121e2013-05-28 15:17:05 +0000328 // If we have a materializer and it can materialize a value, use that.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000329 if (auto *Materializer = getMaterializer()) {
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000330 if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
331 getVM()[V] = NewV;
332 return NewV;
Rafael Espindola19b52382015-11-27 20:28:19 +0000333 }
James Molloyf6f121e2013-05-28 15:17:05 +0000334 }
335
Dan Gohmanca26f792010-08-26 15:41:53 +0000336 // Global values do not need to be seeded into the VM if they
337 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000338 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000339 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000340 return nullptr;
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000341 return getVM()[V] = const_cast<Value *>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000342 }
343
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000344 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
345 // Inline asm may need *type* remapping.
346 FunctionType *NewTy = IA->getFunctionType();
347 if (TypeMapper) {
348 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
349
350 if (NewTy != IA->getFunctionType())
351 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
352 IA->hasSideEffects(), IA->isAlignStack());
353 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000354
355 return getVM()[V] = const_cast<Value *>(V);
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000356 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000357
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000358 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
359 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000360
361 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
362 // Look through to grab the local value.
363 if (Value *LV = mapValue(LAM->getValue())) {
364 if (V == LAM->getValue())
365 return const_cast<Value *>(V);
366 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
367 }
368
369 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
370 // ensures metadata operands only reference defined SSA values.
371 return (Flags & RF_IgnoreMissingLocals)
372 ? nullptr
373 : MetadataAsValue::get(V->getContext(),
374 MDTuple::get(V->getContext(), None));
375 }
376
Chris Lattner43f8d162011-01-08 08:15:20 +0000377 // If this is a module-level metadata and we know that nothing at the module
378 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000379 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000380 return getVM()[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000381
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000382 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000383 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000384 if (MD == MappedMD)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000385 return getVM()[V] = const_cast<Value *>(V);
386 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000387 }
388
Chris Lattner43f8d162011-01-08 08:15:20 +0000389 // Okay, this either must be a constant (which may or may not be mappable) or
390 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000391 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000392 if (!C)
393 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000394
395 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
396 return mapBlockAddress(*BA);
397
Mehdi Aminibcc47412016-05-28 17:26:03 +0000398 auto mapValueOrNull = [this](Value *V) {
399 auto Mapped = mapValue(V);
400 assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
401 "Unexpected null mapping for constant operand without "
402 "NullMapMissingGlobalValues flag");
403 return Mapped;
404 };
405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 // Otherwise, we have some other constant to remap. Start by checking to see
407 // if all operands have an identity remapping.
408 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000409 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 for (; OpNo != NumOperands; ++OpNo) {
411 Value *Op = C->getOperand(OpNo);
Mehdi Aminibcc47412016-05-28 17:26:03 +0000412 Mapped = mapValueOrNull(Op);
413 if (!Mapped)
414 return nullptr;
Mehdi Amini9ee054ae2016-05-27 00:32:12 +0000415 if (Mapped != Op)
416 break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000417 }
Junmo Park95529872016-05-08 23:22:58 +0000418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 // See if the type mapper wants to remap the type as well.
420 Type *NewTy = C->getType();
421 if (TypeMapper)
422 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 // If the result type and all operands match up, then just insert an identity
425 // mapping.
426 if (OpNo == NumOperands && NewTy == C->getType())
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000427 return getVM()[V] = C;
428
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000429 // Okay, we need to create a new constant. We've already processed some or
430 // all of the operands, set them all up now.
431 SmallVector<Constant*, 8> Ops;
432 Ops.reserve(NumOperands);
433 for (unsigned j = 0; j != OpNo; ++j)
434 Ops.push_back(cast<Constant>(C->getOperand(j)));
Junmo Park95529872016-05-08 23:22:58 +0000435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000436 // If one of the operands mismatch, push it and the other mapped operands.
437 if (OpNo != NumOperands) {
438 Ops.push_back(cast<Constant>(Mapped));
Junmo Park95529872016-05-08 23:22:58 +0000439
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000440 // Map the rest of the operands that aren't processed yet.
Mehdi Aminibcc47412016-05-28 17:26:03 +0000441 for (++OpNo; OpNo != NumOperands; ++OpNo) {
442 Mapped = mapValueOrNull(C->getOperand(OpNo));
443 if (!Mapped)
444 return nullptr;
445 Ops.push_back(cast<Constant>(Mapped));
446 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000447 }
David Blaikie88208842015-08-21 20:16:51 +0000448 Type *NewSrcTy = nullptr;
449 if (TypeMapper)
450 if (auto *GEPO = dyn_cast<GEPOperator>(C))
451 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
452
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000454 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000455 if (isa<ConstantArray>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000456 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000457 if (isa<ConstantStruct>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000458 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000459 if (isa<ConstantVector>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000460 return getVM()[V] = ConstantVector::get(Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 // If this is a no-operand constant, it must be because the type was remapped.
462 if (isa<UndefValue>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000463 return getVM()[V] = UndefValue::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000464 if (isa<ConstantAggregateZero>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000465 return getVM()[V] = ConstantAggregateZero::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 assert(isa<ConstantPointerNull>(C));
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000467 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000468}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000469
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000470Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
471 Function *F = cast<Function>(mapValue(BA.getFunction()));
472
473 // F may not have materialized its initializer. In that case, create a
474 // dummy basic block for now, and replace it once we've materialized all
475 // the initializers.
476 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000477 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000478 DelayedBBs.push_back(DelayedBasicBlock(BA));
479 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000480 } else {
481 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000482 }
483
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000484 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000485}
486
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000487Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000488 getVM().MD()[Key].reset(Val);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000489 return Val;
490}
491
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000492Metadata *Mapper::mapToSelf(const Metadata *MD) {
493 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000494}
495
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000496Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000497 if (!Op)
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000498 return nullptr;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000499
500 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Simon Atanasyane12bef72016-04-16 11:49:40 +0000501#ifndef NDEBUG
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000502 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
503 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
504 M.getVM().getMappedMD(Op)) &&
505 "Expected Value to be memoized");
506 else
507 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
508 "Expected result to be memoized");
Simon Atanasyane12bef72016-04-16 11:49:40 +0000509#endif
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000510 return *MappedOp;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000511 }
512
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000513 const MDNode &N = *cast<MDNode>(Op);
514 if (N.isDistinct())
515 return mapDistinctNode(N);
516 return None;
517}
518
519MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
520 assert(N.isDistinct() && "Expected a distinct node");
521 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
522 DistinctWorklist.push_back(cast<MDNode>(
523 (M.Flags & RF_MoveDistinctMDs)
524 ? M.mapToSelf(&N)
525 : M.mapToMetadata(&N, MDNode::replaceWithDistinct(N.clone()))));
526 return DistinctWorklist.back();
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000527}
528
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000529static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
530 Value *MappedV) {
531 if (CMD.getValue() == MappedV)
532 return const_cast<ConstantAsMetadata *>(&CMD);
533 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
534}
535
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000536Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000537 if (!Op)
538 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000539
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000540 if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000541 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000542
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000543 if (isa<MDString>(Op))
544 return const_cast<Metadata *>(Op);
545
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000546 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
547 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
548
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000549 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000550}
551
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000552Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000553 auto Where = Info.find(&Op);
554 assert(Where != Info.end() && "Expected a valid reference");
555
556 auto &OpD = Where->second;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000557 if (!OpD.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000558 return Op;
559
560 // Lazily construct a temporary node.
561 if (!OpD.Placeholder)
562 OpD.Placeholder = Op.clone();
563
564 return *OpD.Placeholder;
565}
566
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000567template <class OperandMapper>
568void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
569 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000570 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
571 Metadata *Old = N.getOperand(I);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000572 Metadata *New = mapOperand(Old);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000573
574 if (Old != New)
575 N.replaceOperandWith(I, New);
576 }
577}
578
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000579namespace {
580/// An entry in the worklist for the post-order traversal.
581struct POTWorklistEntry {
582 MDNode *N; ///< Current node.
583 MDNode::op_iterator Op; ///< Current operand of \c N.
584
585 /// Keep a flag of whether operands have changed in the worklist to avoid
586 /// hitting the map in \a UniquedGraph.
587 bool HasChanged = false;
588
589 POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
590};
591} // end namespace
592
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000593bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
594 assert(G.Info.empty() && "Expected a fresh traversal");
595 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000596
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000597 // Construct a post-order traversal of the uniqued subgraph under FirstN.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000598 bool AnyChanges = false;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000599 SmallVector<POTWorklistEntry, 16> Worklist;
600 Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000601 (void)G.Info[&FirstN];
602 while (!Worklist.empty()) {
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000603 // Start or continue the traversal through the this node's operands.
604 auto &WE = Worklist.back();
605 if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
606 // Push a new node to traverse first.
607 Worklist.push_back(POTWorklistEntry(*N));
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000608 continue;
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000609 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000610
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000611 // Push the node onto the POT.
612 assert(WE.N->isUniqued() && "Expected only uniqued nodes");
613 assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
614 auto &D = G.Info[WE.N];
615 AnyChanges |= D.HasChanged = WE.HasChanged;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000616 D.ID = G.POT.size();
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000617 G.POT.push_back(WE.N);
618
619 // Pop the node off the worklist.
620 Worklist.pop_back();
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000621 }
622 return AnyChanges;
623}
624
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000625MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
626 MDNode::op_iterator E, bool &HasChanged) {
627 while (I != E) {
628 Metadata *Op = *I++; // Increment even on early return.
629 if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
630 // Check if the operand changes.
631 HasChanged |= Op != *MappedOp;
632 continue;
633 }
634
635 // A uniqued metadata node.
636 MDNode &OpN = *cast<MDNode>(Op);
637 assert(OpN.isUniqued() &&
638 "Only uniqued operands cannot be mapped immediately");
639 if (G.Info.insert(std::make_pair(&OpN, Data())).second)
640 return &OpN; // This is a new one. Return it.
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000641 }
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000642 return nullptr;
Duncan P. N. Exon Smith0ab44db2016-04-21 02:34:36 +0000643}
644
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000645void MDNodeMapper::UniquedGraph::propagateChanges() {
646 bool AnyChanges;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000647 do {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000648 AnyChanges = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000649 for (MDNode *N : POT) {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000650 auto &D = Info[N];
651 if (D.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000652 continue;
653
David Majnemer0a16c222016-08-11 21:15:00 +0000654 if (none_of(N->operands(), [&](const Metadata *Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000655 auto Where = Info.find(Op);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000656 return Where != Info.end() && Where->second.HasChanged;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000657 }))
658 continue;
659
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000660 AnyChanges = D.HasChanged = true;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000661 }
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000662 } while (AnyChanges);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000663}
664
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000665void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000666 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000667 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000668 for (auto *N : G.POT) {
669 auto &D = G.Info[N];
670 if (!D.HasChanged) {
671 // The node hasn't changed.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000672 M.mapToSelf(N);
673 continue;
674 }
675
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000676 // Remember whether this node had a placeholder.
677 bool HadPlaceholder(D.Placeholder);
678
679 // Clone the uniqued node and remap the operands.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000680 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000681 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
682 if (Optional<Metadata *> MappedOp = getMappedOp(Old))
683 return *MappedOp;
David L. Jones41cecba2017-01-13 21:02:41 +0000684 (void)D;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000685 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
686 return &G.getFwdReference(*cast<MDNode>(Old));
687 });
688
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000689 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
690 M.mapToMetadata(N, NewN);
691
692 // Nodes that were referenced out of order in the POT are involved in a
693 // uniquing cycle.
694 if (HadPlaceholder)
695 CyclicNodes.push_back(NewN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000696 }
697
698 // Resolve cycles.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000699 for (auto *N : CyclicNodes)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000700 if (!N->isResolved())
701 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000702}
703
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000704Metadata *MDNodeMapper::map(const MDNode &N) {
705 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000706 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
707 "MDNodeMapper::map assumes module-level changes");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000708
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000709 // Require resolved nodes whenever metadata might be remapped.
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000710 assert(N.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000711
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000712 Metadata *MappedN =
713 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
714 while (!DistinctWorklist.empty())
715 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
716 if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
717 return *MappedOp;
718 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
719 });
720 return MappedN;
721}
722
723Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
724 assert(FirstN.isUniqued() && "Expected uniqued node");
725
726 // Create a post-order traversal of uniqued nodes under FirstN.
727 UniquedGraph G;
728 if (!createPOT(G, FirstN)) {
729 // Return early if no nodes have changed.
730 for (const MDNode *N : G.POT)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000731 M.mapToSelf(N);
732 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000733 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000734
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000735 // Update graph with all nodes that have changed.
736 G.propagateChanges();
737
738 // Map all the nodes in the graph.
739 mapNodesInPOT(G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000740
741 // Return the original node, remapped.
742 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000743}
744
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000745namespace {
746
747struct MapMetadataDisabler {
748 ValueToValueMapTy &VM;
749
750 MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
751 VM.disableMapMetadata();
752 }
753 ~MapMetadataDisabler() { VM.enableMapMetadata(); }
754};
755
756} // end namespace
757
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000758Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000759 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000760 if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000761 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000762
763 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000764 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000765
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000766 // This is a module-level metadata. If nothing at the module level is
767 // changing, use an identity mapping.
768 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000769 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000770
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000771 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000772 // Disallow recursion into metadata mapping through mapValue.
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000773 MapMetadataDisabler MMD(getVM());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000774
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000775 // Don't memoize ConstantAsMetadata. Instead of lasting until the
776 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
777 // reference is destructed. These aren't super common, so the extra
778 // indirection isn't that expensive.
779 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000780 }
781
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000782 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000783
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000784 return None;
785}
786
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000787Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000788 assert(MD && "Expected valid metadata");
789 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
790
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000791 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
792 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000793
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000794 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000795}
796
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000797void Mapper::flush() {
798 // Flush out the worklist of global values.
799 while (!Worklist.empty()) {
800 WorklistEntry E = Worklist.pop_back_val();
801 CurrentMCID = E.MCID;
802 switch (E.Kind) {
803 case WorklistEntry::MapGlobalInit:
804 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
805 break;
806 case WorklistEntry::MapAppendingVar: {
807 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
808 mapAppendingVariable(*E.Data.AppendingGV.GV,
809 E.Data.AppendingGV.InitPrefix,
810 E.AppendingGVIsOldCtorDtor,
811 makeArrayRef(AppendingInits).slice(PrefixSize));
812 AppendingInits.resize(PrefixSize);
813 break;
814 }
815 case WorklistEntry::MapGlobalAliasee:
816 E.Data.GlobalAliasee.GA->setAliasee(
817 mapConstant(E.Data.GlobalAliasee.Aliasee));
818 break;
819 case WorklistEntry::RemapFunction:
820 remapFunction(*E.Data.RemapF);
821 break;
822 }
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000823 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000824 CurrentMCID = 0;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000825
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000826 // Finish logic for block addresses now that all global values have been
827 // handled.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000828 while (!DelayedBBs.empty()) {
829 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
830 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
831 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
832 }
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000833}
834
835void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000836 // Remap operands.
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000837 for (Use &Op : I->operands()) {
838 Value *V = mapValue(Op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000839 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000840 if (V)
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000841 Op = V;
Chris Lattner43f8d162011-01-08 08:15:20 +0000842 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000843 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000844 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000845 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000846
Jay Foad61ea0e42011-06-23 09:09:15 +0000847 // Remap phi nodes' incoming blocks.
848 if (PHINode *PN = dyn_cast<PHINode>(I)) {
849 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smithadcebdf2016-04-08 19:17:13 +0000850 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad61ea0e42011-06-23 09:09:15 +0000851 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000852 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000853 PN->setIncomingBlock(i, cast<BasicBlock>(V));
854 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000855 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000856 "Referenced block not in value map!");
857 }
858 }
859
Devang Patelc0174042011-08-04 20:02:18 +0000860 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000861 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000862 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000863 for (const auto &MI : MDs) {
864 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000865 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000866 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000867 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000868 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000869
David Blaikie348de692015-04-23 21:36:23 +0000870 if (!TypeMapper)
871 return;
872
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000873 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000874 if (auto CS = CallSite(I)) {
875 SmallVector<Type *, 3> Tys;
876 FunctionType *FTy = CS.getFunctionType();
877 Tys.reserve(FTy->getNumParams());
878 for (Type *Ty : FTy->params())
879 Tys.push_back(TypeMapper->remapType(Ty));
880 CS.mutateFunctionType(FunctionType::get(
881 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000882 return;
883 }
884 if (auto *AI = dyn_cast<AllocaInst>(I))
885 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000886 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000887 GEP->setSourceElementType(
888 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000889 GEP->setResultElementType(
890 TypeMapper->remapType(GEP->getResultElementType()));
891 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000892 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000893}
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000894
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000895void Mapper::remapFunction(Function &F) {
896 // Remap the operands.
897 for (Use &Op : F.operands())
898 if (Op)
899 Op = mapValue(Op);
900
901 // Remap the metadata attachments.
902 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
903 F.getAllMetadata(MDs);
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000904 F.clearMetadata();
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000905 for (const auto &I : MDs)
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000906 F.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000907
908 // Remap the argument types.
909 if (TypeMapper)
910 for (Argument &A : F.args())
911 A.mutateType(TypeMapper->remapType(A.getType()));
912
913 // Remap the instructions.
914 for (BasicBlock &BB : F)
915 for (Instruction &I : BB)
916 remapInstruction(&I);
917}
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000918
919void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
920 bool IsOldCtorDtor,
921 ArrayRef<Constant *> NewMembers) {
922 SmallVector<Constant *, 16> Elements;
923 if (InitPrefix) {
924 unsigned NumElements =
925 cast<ArrayType>(InitPrefix->getType())->getNumElements();
926 for (unsigned I = 0; I != NumElements; ++I)
927 Elements.push_back(InitPrefix->getAggregateElement(I));
928 }
929
930 PointerType *VoidPtrTy;
931 Type *EltTy;
932 if (IsOldCtorDtor) {
933 // FIXME: This upgrade is done during linking to support the C API. See
934 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
935 VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
936 auto &ST = *cast<StructType>(NewMembers.front()->getType());
937 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
938 EltTy = StructType::get(GV.getContext(), Tys, false);
939 }
940
941 for (auto *V : NewMembers) {
942 Constant *NewV;
943 if (IsOldCtorDtor) {
944 auto *S = cast<ConstantStruct>(V);
945 auto *E1 = mapValue(S->getOperand(0));
946 auto *E2 = mapValue(S->getOperand(1));
947 Value *Null = Constant::getNullValue(VoidPtrTy);
948 NewV =
949 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
950 } else {
951 NewV = cast_or_null<Constant>(mapValue(V));
952 }
953 Elements.push_back(NewV);
954 }
955
956 GV.setInitializer(ConstantArray::get(
957 cast<ArrayType>(GV.getType()->getElementType()), Elements));
958}
959
960void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
961 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000962 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000963 assert(MCID < MCs.size() && "Invalid mapping context");
964
965 WorklistEntry WE;
966 WE.Kind = WorklistEntry::MapGlobalInit;
967 WE.MCID = MCID;
968 WE.Data.GVInit.GV = &GV;
969 WE.Data.GVInit.Init = &Init;
970 Worklist.push_back(WE);
971}
972
973void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
974 Constant *InitPrefix,
975 bool IsOldCtorDtor,
976 ArrayRef<Constant *> NewMembers,
977 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000978 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000979 assert(MCID < MCs.size() && "Invalid mapping context");
980
981 WorklistEntry WE;
982 WE.Kind = WorklistEntry::MapAppendingVar;
983 WE.MCID = MCID;
984 WE.Data.AppendingGV.GV = &GV;
985 WE.Data.AppendingGV.InitPrefix = InitPrefix;
986 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
987 WE.AppendingGVNumNewMembers = NewMembers.size();
988 Worklist.push_back(WE);
989 AppendingInits.append(NewMembers.begin(), NewMembers.end());
990}
991
992void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
993 unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000994 assert(AlreadyScheduled.insert(&GA).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000995 assert(MCID < MCs.size() && "Invalid mapping context");
996
997 WorklistEntry WE;
998 WE.Kind = WorklistEntry::MapGlobalAliasee;
999 WE.MCID = MCID;
1000 WE.Data.GlobalAliasee.GA = &GA;
1001 WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1002 Worklist.push_back(WE);
1003}
1004
1005void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +00001006 assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001007 assert(MCID < MCs.size() && "Invalid mapping context");
1008
1009 WorklistEntry WE;
1010 WE.Kind = WorklistEntry::RemapFunction;
1011 WE.MCID = MCID;
1012 WE.Data.RemapF = &F;
1013 Worklist.push_back(WE);
1014}
1015
1016void Mapper::addFlags(RemapFlags Flags) {
1017 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1018 this->Flags = this->Flags | Flags;
1019}
1020
1021static Mapper *getAsMapper(void *pImpl) {
1022 return reinterpret_cast<Mapper *>(pImpl);
1023}
1024
1025namespace {
1026
1027class FlushingMapper {
1028 Mapper &M;
1029
1030public:
1031 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1032 assert(!M.hasWorkToDo() && "Expected to be flushed");
1033 }
1034 ~FlushingMapper() { M.flush(); }
1035 Mapper *operator->() const { return &M; }
1036};
1037
1038} // end namespace
1039
1040ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1041 ValueMapTypeRemapper *TypeMapper,
1042 ValueMaterializer *Materializer)
1043 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1044
1045ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1046
1047unsigned
1048ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1049 ValueMaterializer *Materializer) {
1050 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1051}
1052
1053void ValueMapper::addFlags(RemapFlags Flags) {
1054 FlushingMapper(pImpl)->addFlags(Flags);
1055}
1056
1057Value *ValueMapper::mapValue(const Value &V) {
1058 return FlushingMapper(pImpl)->mapValue(&V);
1059}
1060
1061Constant *ValueMapper::mapConstant(const Constant &C) {
1062 return cast_or_null<Constant>(mapValue(C));
1063}
1064
1065Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1066 return FlushingMapper(pImpl)->mapMetadata(&MD);
1067}
1068
1069MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1070 return cast_or_null<MDNode>(mapMetadata(N));
1071}
1072
1073void ValueMapper::remapInstruction(Instruction &I) {
1074 FlushingMapper(pImpl)->remapInstruction(&I);
1075}
1076
1077void ValueMapper::remapFunction(Function &F) {
1078 FlushingMapper(pImpl)->remapFunction(F);
1079}
1080
1081void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1082 Constant &Init,
1083 unsigned MCID) {
1084 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1085}
1086
1087void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1088 Constant *InitPrefix,
1089 bool IsOldCtorDtor,
1090 ArrayRef<Constant *> NewMembers,
1091 unsigned MCID) {
1092 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1093 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1094}
1095
1096void ValueMapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1097 unsigned MCID) {
1098 getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1099}
1100
1101void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1102 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1103}