blob: e22922b9fbbea65128e7acc6a8aeb75691556a51 [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"
David Blaikie348de692015-04-23 21:36:23 +000016#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000019#include "llvm/IR/GlobalAlias.h"
20#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Metadata.h"
David Blaikie88208842015-08-21 20:16:51 +000024#include "llvm/IR/Operator.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000025using namespace llvm;
Chris Lattnere4dbb1a2002-11-20 20:47:41 +000026
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000027// Out of line method to get vtable etc for class.
Craig Topper2a6a08b2012-09-26 06:36:36 +000028void ValueMapTypeRemapper::anchor() {}
James Molloyf6f121e2013-05-28 15:17:05 +000029void ValueMaterializer::anchor() {}
Rafael Espindola19b52382015-11-27 20:28:19 +000030void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
31}
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
41 // Explicit move for MSVC.
42 DelayedBasicBlock(DelayedBasicBlock &&X)
43 : OldBB(std::move(X.OldBB)), TempBB(std::move(X.TempBB)) {}
44 DelayedBasicBlock &operator=(DelayedBasicBlock &&X) {
45 OldBB = std::move(X.OldBB);
46 TempBB = std::move(X.TempBB);
47 return *this;
48 }
49
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000050 DelayedBasicBlock(const BlockAddress &Old)
51 : OldBB(Old.getBasicBlock()),
52 TempBB(BasicBlock::Create(Old.getContext())) {}
53};
54
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000055struct WorklistEntry {
56 enum EntryKind {
57 MapGlobalInit,
58 MapAppendingVar,
59 MapGlobalAliasee,
60 RemapFunction
61 };
62 struct GVInitTy {
63 GlobalVariable *GV;
64 Constant *Init;
65 };
66 struct AppendingGVTy {
67 GlobalVariable *GV;
68 Constant *InitPrefix;
69 };
70 struct GlobalAliaseeTy {
71 GlobalAlias *GA;
72 Constant *Aliasee;
73 };
74
75 unsigned Kind : 2;
76 unsigned MCID : 29;
77 unsigned AppendingGVIsOldCtorDtor : 1;
78 unsigned AppendingGVNumNewMembers;
79 union {
80 GVInitTy GVInit;
81 AppendingGVTy AppendingGV;
82 GlobalAliaseeTy GlobalAliasee;
83 Function *RemapF;
84 } Data;
85};
86
87struct MappingContext {
88 ValueToValueMapTy *VM;
89 ValueMaterializer *Materializer = nullptr;
90
91 /// Construct a MappingContext with a value map and materializer.
92 explicit MappingContext(ValueToValueMapTy &VM,
93 ValueMaterializer *Materializer = nullptr)
94 : VM(&VM), Materializer(Materializer) {}
95};
96
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000097class MDNodeMapper;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000098class Mapper {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000099 friend class MDNodeMapper;
100
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000101 RemapFlags Flags;
102 ValueMapTypeRemapper *TypeMapper;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000103 unsigned CurrentMCID = 0;
104 SmallVector<MappingContext, 2> MCs;
105 SmallVector<WorklistEntry, 4> Worklist;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000106 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000107 SmallVector<Constant *, 16> AppendingInits;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000108
109public:
110 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
111 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000112 : Flags(Flags), TypeMapper(TypeMapper),
113 MCs(1, MappingContext(VM, Materializer)) {}
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000114
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000115 /// ValueMapper should explicitly call \a flush() before destruction.
116 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
117
118 bool hasWorkToDo() const { return !Worklist.empty(); }
119
120 unsigned
121 registerAlternateMappingContext(ValueToValueMapTy &VM,
122 ValueMaterializer *Materializer = nullptr) {
123 MCs.push_back(MappingContext(VM, Materializer));
124 return MCs.size() - 1;
125 }
126
127 void addFlags(RemapFlags Flags);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000128
129 Value *mapValue(const Value *V);
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000130 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000131 void remapFunction(Function &F);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000132
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000133 Constant *mapConstant(const Constant *C) {
134 return cast_or_null<Constant>(mapValue(C));
135 }
136
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000137 /// Map metadata.
138 ///
139 /// Find the mapping for MD. Guarantees that the return will be resolved
140 /// (not an MDNode, or MDNode::isResolved() returns true).
141 Metadata *mapMetadata(const Metadata *MD);
142
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000143 // Map LocalAsMetadata, which never gets memoized.
144 //
145 // If the referenced local is not mapped, the principled return is nullptr.
146 // However, optimization passes sometimes move metadata operands *before* the
147 // SSA values they reference. To prevent crashes in \a RemapInstruction(),
148 // return "!{}" when RF_IgnoreMissingLocals is not set.
149 //
150 // \note Adding a mapping for LocalAsMetadata is unsupported. Add a mapping
151 // to the value map for the SSA value in question instead.
152 //
153 // FIXME: Once we have a verifier check for forward references to SSA values
154 // through metadata operands, always return nullptr on unmapped locals.
155 Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
156
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000157 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
158 unsigned MCID);
159 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
160 bool IsOldCtorDtor,
161 ArrayRef<Constant *> NewMembers,
162 unsigned MCID);
163 void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
164 unsigned MCID);
165 void scheduleRemapFunction(Function &F, unsigned MCID);
166
167 void flush();
168
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000169private:
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000170 void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
171 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
172 bool IsOldCtorDtor,
173 ArrayRef<Constant *> NewMembers);
174 void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
175 void remapFunction(Function &F, ValueToValueMapTy &VM);
176
177 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
178 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000179
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000180 Value *mapBlockAddress(const BlockAddress &BA);
181
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000182 /// Map metadata that doesn't require visiting operands.
183 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
184
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000185 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
186 Metadata *mapToSelf(const Metadata *MD);
187};
188
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000189class MDNodeMapper {
190 Mapper &M;
191
192 struct Data {
193 bool HasChangedOps = false;
194 bool HasChangedAddress = false;
195 unsigned ID = ~0u;
196 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000197
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000198 Data() {}
199 Data(Data &&X)
200 : HasChangedOps(std::move(X.HasChangedOps)),
201 HasChangedAddress(std::move(X.HasChangedAddress)),
202 ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
203 Data &operator=(Data &&X) {
204 HasChangedOps = std::move(X.HasChangedOps);
205 HasChangedAddress = std::move(X.HasChangedAddress);
206 ID = std::move(X.ID);
207 Placeholder = std::move(X.Placeholder);
208 return *this;
209 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000210 };
211
212 SmallDenseMap<const Metadata *, Data, 32> Info;
213 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
214 SmallVector<MDNode *, 16> POT;
215
216public:
217 MDNodeMapper(Mapper &M) : M(M) {}
218
219 /// Map a metadata node (and its transitive operands).
220 ///
221 /// This is the only entry point into MDNodeMapper. It works as follows:
222 ///
223 /// 1. \a createPOT(): use a worklist to perform a post-order traversal of
224 /// the transitively referenced unmapped nodes.
225 ///
226 /// 2. \a propagateChangedOperands(): track which nodes will change
227 /// operands, and which will have new addresses in the mapped scheme.
228 /// Propagate the changes through the POT until fixed point, to pick up
229 /// uniquing cycles that need to change.
230 ///
231 /// 3. \a mapDistinctNodes(): map all the distinct nodes without touching
232 /// their operands. If RF_MoveDistinctMetadata, they get mapped to
233 /// themselves; otherwise, they get mapped to clones.
234 ///
235 /// 4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
236 /// creating temporaries for forward references as needed.
237 ///
238 /// 5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
239 Metadata *map(const MDNode &FirstN);
240
241private:
242 /// Return \c true as long as there's work to do.
243 bool hasWork() const { return !Worklist.empty(); }
244
245 /// Get the current node in the worklist.
246 MDNode &getCurrentNode() const { return *Worklist.back().first; }
247
248 /// Push a node onto the worklist.
249 ///
250 /// Adds \c N to \a Worklist and \a Info, unless it's already inserted. If
251 /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
252 /// RF_MoveDistinctMDs.
253 ///
254 /// Returns the data for the node.
255 ///
256 /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
257 /// \post Worklist.back().first == &N.
258 /// \post Worklist.back().second == false.
259 Data &push(const MDNode &N);
260
261 /// Map a node operand, and return true if it changes.
262 ///
263 /// \post getMappedOp(Op) does not return None.
264 bool mapOperand(const Metadata *Op);
265
266 /// Get a previously mapped node.
267 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
268
269 /// Try to pop a node off the worklist and store it in POT.
270 ///
271 /// Returns \c true if it popped; \c false if its operands need to be
272 /// visited.
273 ///
274 /// \post If Worklist.back().second == false: Worklist.back().second == true.
275 /// \post Else: Worklist.back() has been popped off and added to \a POT.
276 bool tryToPop();
277
278 /// Get a forward reference to a node to use as an operand.
279 ///
280 /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
281 /// node and returns it.
282 Metadata &getFwdReference(const Data &D, MDNode &Op);
283
284 /// Create a post-order traversal from the given node.
285 ///
286 /// This traverses the metadata graph deeply enough to map \c FirstN. It
287 /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
288 /// metadata that has already been mapped will not be part of the POT.
289 ///
290 /// \post \a POT is a post-order traversal ending with \c FirstN.
291 bool createPOT(const MDNode &FirstN);
292
293 /// Propagate changed operands through post-order traversal.
294 ///
295 /// Until fixed point, iteratively update:
296 ///
297 /// - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
298 /// - \a Data::HasChangedAddress based on Data::HasChangedOps.
299 ///
300 /// This algorithm never changes \a Data::HasChangedAddress for distinct
301 /// nodes.
302 ///
303 /// \post \a POT is a post-order traversal ending with \c FirstN.
304 void propagateChangedOperands();
305
306 /// Map all distinct nodes in POT.
307 ///
308 /// \post \a getMappedOp() returns the correct node for every distinct node.
309 void mapDistinctNodes();
310
311 /// Map all uniqued nodes in POT with the correct operands.
312 ///
313 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
314 /// \post \a getMappedOp() returns the correct node for every node.
315 /// \post \a MDNode::operands() is correct for every uniqued node.
316 /// \post \a MDNode::isResolved() returns true for every node.
317 void mapUniquedNodes();
318
319 /// Re-map the operands for distinct nodes in POT.
320 ///
321 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
322 /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
323 /// \post \a MDNode::operands() is correct for every distinct node.
324 void remapDistinctOperands();
325
326 /// Remap a node's operands.
327 ///
328 /// Iterate through operands and update them in place using \a getMappedOp()
329 /// and \a getFwdReference().
330 ///
331 /// \pre N.isDistinct() or N.isTemporary().
332 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
333 /// \pre If \c N is distinct, all uniqued nodes are already mapped.
334 void remapOperands(const Data &D, MDNode &N);
335};
336
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000337} // end namespace
338
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000339Value *Mapper::mapValue(const Value *V) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000340 ValueToValueMapTy::iterator I = getVM().find(V);
341
Chris Lattner43f8d162011-01-08 08:15:20 +0000342 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000343 if (I != getVM().end() && I->second)
344 return I->second;
345
James Molloyf6f121e2013-05-28 15:17:05 +0000346 // If we have a materializer and it can materialize a value, use that.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000347 if (auto *Materializer = getMaterializer()) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000348 if (Value *NewV =
349 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000350 getVM()[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000351 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000352 Materializer->materializeInitFor(
353 NewGV, cast<GlobalValue>(const_cast<Value *>(V)));
Rafael Espindola19b52382015-11-27 20:28:19 +0000354 return NewV;
355 }
James Molloyf6f121e2013-05-28 15:17:05 +0000356 }
357
Dan Gohmanca26f792010-08-26 15:41:53 +0000358 // Global values do not need to be seeded into the VM if they
359 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000360 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000361 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000362 return nullptr;
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000363 return getVM()[V] = const_cast<Value *>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000364 }
365
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000366 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
367 // Inline asm may need *type* remapping.
368 FunctionType *NewTy = IA->getFunctionType();
369 if (TypeMapper) {
370 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
371
372 if (NewTy != IA->getFunctionType())
373 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
374 IA->hasSideEffects(), IA->isAlignStack());
375 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000376
377 return getVM()[V] = const_cast<Value *>(V);
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000378 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000379
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000380 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
381 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000382
383 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
384 // Look through to grab the local value.
385 if (Value *LV = mapValue(LAM->getValue())) {
386 if (V == LAM->getValue())
387 return const_cast<Value *>(V);
388 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
389 }
390
391 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
392 // ensures metadata operands only reference defined SSA values.
393 return (Flags & RF_IgnoreMissingLocals)
394 ? nullptr
395 : MetadataAsValue::get(V->getContext(),
396 MDTuple::get(V->getContext(), None));
397 }
398
Chris Lattner43f8d162011-01-08 08:15:20 +0000399 // If this is a module-level metadata and we know that nothing at the module
400 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000401 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000402 return getVM()[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000403
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000404 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000405 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000406 if (MD == MappedMD)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000407 return getVM()[V] = const_cast<Value *>(V);
408 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000409 }
410
Chris Lattner43f8d162011-01-08 08:15:20 +0000411 // Okay, this either must be a constant (which may or may not be mappable) or
412 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000413 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000414 if (!C)
415 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000416
417 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
418 return mapBlockAddress(*BA);
419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420 // Otherwise, we have some other constant to remap. Start by checking to see
421 // if all operands have an identity remapping.
422 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000423 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 for (; OpNo != NumOperands; ++OpNo) {
425 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000426 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000427 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000428 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000429
430 // See if the type mapper wants to remap the type as well.
431 Type *NewTy = C->getType();
432 if (TypeMapper)
433 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000434
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000435 // If the result type and all operands match up, then just insert an identity
436 // mapping.
437 if (OpNo == NumOperands && NewTy == C->getType())
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000438 return getVM()[V] = C;
439
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000440 // Okay, we need to create a new constant. We've already processed some or
441 // all of the operands, set them all up now.
442 SmallVector<Constant*, 8> Ops;
443 Ops.reserve(NumOperands);
444 for (unsigned j = 0; j != OpNo; ++j)
445 Ops.push_back(cast<Constant>(C->getOperand(j)));
446
447 // If one of the operands mismatch, push it and the other mapped operands.
448 if (OpNo != NumOperands) {
449 Ops.push_back(cast<Constant>(Mapped));
450
451 // Map the rest of the operands that aren't processed yet.
452 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000453 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000454 }
David Blaikie88208842015-08-21 20:16:51 +0000455 Type *NewSrcTy = nullptr;
456 if (TypeMapper)
457 if (auto *GEPO = dyn_cast<GEPOperator>(C))
458 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
459
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000460 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000461 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000462 if (isa<ConstantArray>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000463 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000464 if (isa<ConstantStruct>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000465 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 if (isa<ConstantVector>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000467 return getVM()[V] = ConstantVector::get(Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000468 // If this is a no-operand constant, it must be because the type was remapped.
469 if (isa<UndefValue>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000470 return getVM()[V] = UndefValue::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000471 if (isa<ConstantAggregateZero>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000472 return getVM()[V] = ConstantAggregateZero::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000473 assert(isa<ConstantPointerNull>(C));
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000474 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000475}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000476
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000477Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
478 Function *F = cast<Function>(mapValue(BA.getFunction()));
479
480 // F may not have materialized its initializer. In that case, create a
481 // dummy basic block for now, and replace it once we've materialized all
482 // the initializers.
483 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000484 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000485 DelayedBBs.push_back(DelayedBasicBlock(BA));
486 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000487 } else {
488 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000489 }
490
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000491 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000492}
493
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000494Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000495 getVM().MD()[Key].reset(Val);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000496 return Val;
497}
498
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000499Metadata *Mapper::mapToSelf(const Metadata *MD) {
500 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000501}
502
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000503bool MDNodeMapper::mapOperand(const Metadata *Op) {
504 if (!Op)
505 return false;
506
507 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Simon Atanasyane12bef72016-04-16 11:49:40 +0000508#ifndef NDEBUG
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000509 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
510 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
511 M.getVM().getMappedMD(Op)) &&
512 "Expected Value to be memoized");
513 else
514 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
515 "Expected result to be memoized");
Simon Atanasyane12bef72016-04-16 11:49:40 +0000516#endif
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000517 return *MappedOp != Op;
518 }
519
520 return push(*cast<MDNode>(Op)).HasChangedAddress;
521}
522
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000523static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
524 Value *MappedV) {
525 if (CMD.getValue() == MappedV)
526 return const_cast<ConstantAsMetadata *>(&CMD);
527 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
528}
529
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000530Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000531 if (!Op)
532 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000533
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000534 if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000535 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000536
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000537 if (isa<MDString>(Op))
538 return const_cast<Metadata *>(Op);
539
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000540 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
541 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
542
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000543 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000544}
545
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000546Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
547 auto Where = Info.find(&Op);
548 assert(Where != Info.end() && "Expected a valid reference");
549
550 auto &OpD = Where->second;
551 assert(OpD.ID > D.ID && "Expected a forward reference");
552
553 if (!OpD.HasChangedAddress)
554 return Op;
555
556 // Lazily construct a temporary node.
557 if (!OpD.Placeholder)
558 OpD.Placeholder = Op.clone();
559
560 return *OpD.Placeholder;
561}
562
563void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
564 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
565 Metadata *Old = N.getOperand(I);
566 Metadata *New;
567 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
568 New = *MappedOp;
569 } else {
570 assert(!N.isDistinct() &&
571 "Expected all nodes to be pre-mapped for distinct operands");
572 MDNode &OldN = *cast<MDNode>(Old);
573 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
574 New = &getFwdReference(D, OldN);
575 }
576
577 if (Old != New)
578 N.replaceOperandWith(I, New);
579 }
580}
581
582MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
583 auto Insertion = Info.insert(std::make_pair(&N, Data()));
584 auto &D = Insertion.first->second;
585 if (!Insertion.second)
586 return D;
587
588 // Add to the worklist; check for distinct nodes that are required to be
589 // copied.
590 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
591 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
592 return D;
593}
594
595bool MDNodeMapper::tryToPop() {
596 if (!Worklist.back().second) {
597 Worklist.back().second = true;
598 return false;
599 }
600
601 MDNode *N = Worklist.pop_back_val().first;
602 Info[N].ID = POT.size();
603 POT.push_back(N);
604 return true;
605}
606
607bool MDNodeMapper::createPOT(const MDNode &FirstN) {
608 bool AnyChanges = false;
609
610 // Do a traversal of the unmapped subgraph, tracking whether operands change.
611 // In some cases, these changes will propagate naturally, but
612 // propagateChangedOperands() catches the general case.
613 AnyChanges |= push(FirstN).HasChangedAddress;
614 while (hasWork()) {
615 if (tryToPop())
616 continue;
617
618 MDNode &N = getCurrentNode();
619 bool LocalChanges = false;
620 for (const Metadata *Op : N.operands())
621 LocalChanges |= mapOperand(Op);
622
623 if (!LocalChanges)
624 continue;
625
626 AnyChanges = true;
627 auto &D = Info[&N];
628 D.HasChangedOps = true;
629
630 // Uniqued nodes change address when operands change.
631 if (!N.isDistinct())
632 D.HasChangedAddress = true;
633 }
634 return AnyChanges;
635}
636
637void MDNodeMapper::propagateChangedOperands() {
638 bool AnyChangedAddresses;
639 do {
640 AnyChangedAddresses = false;
641 for (MDNode *N : POT) {
642 auto &NI = Info[N];
643 if (NI.HasChangedOps)
644 continue;
645
646 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
647 auto Where = Info.find(Op);
648 return Where != Info.end() && Where->second.HasChangedAddress;
649 }))
650 continue;
651
652 NI.HasChangedOps = true;
653 if (!N->isDistinct()) {
654 NI.HasChangedAddress = true;
655 AnyChangedAddresses = true;
656 }
657 }
658 } while (AnyChangedAddresses);
659}
660
661void MDNodeMapper::mapDistinctNodes() {
662 // Map all the distinct nodes in POT.
663 for (MDNode *N : POT) {
664 if (!N->isDistinct())
665 continue;
666
667 if (M.Flags & RF_MoveDistinctMDs)
668 M.mapToSelf(N);
669 else
670 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
671 }
672}
673
674void MDNodeMapper::mapUniquedNodes() {
675 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000676 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000677 for (auto *N : POT) {
678 if (N->isDistinct())
679 continue;
680
681 auto &D = Info[N];
682 assert(D.HasChangedAddress == D.HasChangedOps &&
683 "Uniqued nodes should change address iff ops change");
684 if (!D.HasChangedAddress) {
685 M.mapToSelf(N);
686 continue;
687 }
688
689 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
690 remapOperands(D, *ClonedN);
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000691 CyclicNodes.push_back(MDNode::replaceWithUniqued(std::move(ClonedN)));
692 M.mapToMetadata(N, CyclicNodes.back());
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000693 }
694
695 // Resolve cycles.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000696 for (auto *N : CyclicNodes)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000697 if (!N->isResolved())
698 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000699}
700
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000701void MDNodeMapper::remapDistinctOperands() {
702 for (auto *N : POT) {
703 if (!N->isDistinct())
704 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000705
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000706 auto &D = Info[N];
707 if (!D.HasChangedOps)
708 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000709
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000710 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
711 "Distinct nodes should change address iff they cannot be moved");
712 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000713 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000714}
715
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000716Metadata *MDNodeMapper::map(const MDNode &FirstN) {
717 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
718 "MDNodeMapper::map assumes module-level changes");
719 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000720
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000721 // Require resolved nodes whenever metadata might be remapped.
722 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000723
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000724 // Return early if nothing at all changed.
725 if (!createPOT(FirstN)) {
726 for (const MDNode *N : POT)
727 M.mapToSelf(N);
728 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000729 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000730
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000731 propagateChangedOperands();
732 mapDistinctNodes();
733 mapUniquedNodes();
734 remapDistinctOperands();
735
736 // Return the original node, remapped.
737 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000738}
739
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000740namespace {
741
742struct MapMetadataDisabler {
743 ValueToValueMapTy &VM;
744
745 MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
746 VM.disableMapMetadata();
747 }
748 ~MapMetadataDisabler() { VM.enableMapMetadata(); }
749};
750
751} // end namespace
752
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000753Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000754 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000755 if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000756 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757
758 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000759 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000760
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000761 // This is a module-level metadata. If nothing at the module level is
762 // changing, use an identity mapping.
763 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +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 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000767 // Disallow recursion into metadata mapping through mapValue.
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000768 MapMetadataDisabler MMD(getVM());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000769
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000770 // Don't memoize ConstantAsMetadata. Instead of lasting until the
771 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
772 // reference is destructed. These aren't super common, so the extra
773 // indirection isn't that expensive.
774 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000775 }
776
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000777 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000778
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000779 return None;
780}
781
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000782Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
783 // Lookup the mapping for the value itself, and return the appropriate
784 // metadata.
785 if (Value *V = mapValue(LAM.getValue())) {
786 if (V == LAM.getValue())
787 return const_cast<LocalAsMetadata *>(&LAM);
788 return ValueAsMetadata::get(V);
789 }
790
791 // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
792 // metadata operands only reference defined SSA values.
793 return (Flags & RF_IgnoreMissingLocals)
794 ? nullptr
795 : MDTuple::get(LAM.getContext(), None);
796}
797
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000798Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000799 assert(MD && "Expected valid metadata");
800 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
801
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000802 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
803 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000804
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000805 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000806}
807
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000808void Mapper::flush() {
809 // Flush out the worklist of global values.
810 while (!Worklist.empty()) {
811 WorklistEntry E = Worklist.pop_back_val();
812 CurrentMCID = E.MCID;
813 switch (E.Kind) {
814 case WorklistEntry::MapGlobalInit:
815 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
816 break;
817 case WorklistEntry::MapAppendingVar: {
818 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
819 mapAppendingVariable(*E.Data.AppendingGV.GV,
820 E.Data.AppendingGV.InitPrefix,
821 E.AppendingGVIsOldCtorDtor,
822 makeArrayRef(AppendingInits).slice(PrefixSize));
823 AppendingInits.resize(PrefixSize);
824 break;
825 }
826 case WorklistEntry::MapGlobalAliasee:
827 E.Data.GlobalAliasee.GA->setAliasee(
828 mapConstant(E.Data.GlobalAliasee.Aliasee));
829 break;
830 case WorklistEntry::RemapFunction:
831 remapFunction(*E.Data.RemapF);
832 break;
833 }
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000834 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000835 CurrentMCID = 0;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000836
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000837 // Finish logic for block addresses now that all global values have been
838 // handled.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000839 while (!DelayedBBs.empty()) {
840 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
841 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
842 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
843 }
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000844}
845
846void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000847 // Remap operands.
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000848 for (Use &Op : I->operands()) {
849 Value *V = mapValue(Op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000850 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000851 if (V)
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000852 Op = V;
Chris Lattner43f8d162011-01-08 08:15:20 +0000853 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000854 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000855 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000856 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000857
Jay Foad61ea0e42011-06-23 09:09:15 +0000858 // Remap phi nodes' incoming blocks.
859 if (PHINode *PN = dyn_cast<PHINode>(I)) {
860 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smithadcebdf2016-04-08 19:17:13 +0000861 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad61ea0e42011-06-23 09:09:15 +0000862 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000863 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000864 PN->setIncomingBlock(i, cast<BasicBlock>(V));
865 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000866 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000867 "Referenced block not in value map!");
868 }
869 }
870
Devang Patelc0174042011-08-04 20:02:18 +0000871 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000872 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000873 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000874 for (const auto &MI : MDs) {
875 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000876 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000877 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000878 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000879 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000880
David Blaikie348de692015-04-23 21:36:23 +0000881 if (!TypeMapper)
882 return;
883
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000884 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000885 if (auto CS = CallSite(I)) {
886 SmallVector<Type *, 3> Tys;
887 FunctionType *FTy = CS.getFunctionType();
888 Tys.reserve(FTy->getNumParams());
889 for (Type *Ty : FTy->params())
890 Tys.push_back(TypeMapper->remapType(Ty));
891 CS.mutateFunctionType(FunctionType::get(
892 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000893 return;
894 }
895 if (auto *AI = dyn_cast<AllocaInst>(I))
896 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000897 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000898 GEP->setSourceElementType(
899 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000900 GEP->setResultElementType(
901 TypeMapper->remapType(GEP->getResultElementType()));
902 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000903 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000904}
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000905
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.
913 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
914 F.getAllMetadata(MDs);
915 for (const auto &I : MDs)
916 F.setMetadata(I.first, cast_or_null<MDNode>(mapMetadata(I.second)));
917
918 // Remap the argument types.
919 if (TypeMapper)
920 for (Argument &A : F.args())
921 A.mutateType(TypeMapper->remapType(A.getType()));
922
923 // Remap the instructions.
924 for (BasicBlock &BB : F)
925 for (Instruction &I : BB)
926 remapInstruction(&I);
927}
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000928
929void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
930 bool IsOldCtorDtor,
931 ArrayRef<Constant *> NewMembers) {
932 SmallVector<Constant *, 16> Elements;
933 if (InitPrefix) {
934 unsigned NumElements =
935 cast<ArrayType>(InitPrefix->getType())->getNumElements();
936 for (unsigned I = 0; I != NumElements; ++I)
937 Elements.push_back(InitPrefix->getAggregateElement(I));
938 }
939
940 PointerType *VoidPtrTy;
941 Type *EltTy;
942 if (IsOldCtorDtor) {
943 // FIXME: This upgrade is done during linking to support the C API. See
944 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
945 VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
946 auto &ST = *cast<StructType>(NewMembers.front()->getType());
947 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
948 EltTy = StructType::get(GV.getContext(), Tys, false);
949 }
950
951 for (auto *V : NewMembers) {
952 Constant *NewV;
953 if (IsOldCtorDtor) {
954 auto *S = cast<ConstantStruct>(V);
955 auto *E1 = mapValue(S->getOperand(0));
956 auto *E2 = mapValue(S->getOperand(1));
957 Value *Null = Constant::getNullValue(VoidPtrTy);
958 NewV =
959 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
960 } else {
961 NewV = cast_or_null<Constant>(mapValue(V));
962 }
963 Elements.push_back(NewV);
964 }
965
966 GV.setInitializer(ConstantArray::get(
967 cast<ArrayType>(GV.getType()->getElementType()), Elements));
968}
969
970void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
971 unsigned MCID) {
972 assert(MCID < MCs.size() && "Invalid mapping context");
973
974 WorklistEntry WE;
975 WE.Kind = WorklistEntry::MapGlobalInit;
976 WE.MCID = MCID;
977 WE.Data.GVInit.GV = &GV;
978 WE.Data.GVInit.Init = &Init;
979 Worklist.push_back(WE);
980}
981
982void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
983 Constant *InitPrefix,
984 bool IsOldCtorDtor,
985 ArrayRef<Constant *> NewMembers,
986 unsigned MCID) {
987 assert(MCID < MCs.size() && "Invalid mapping context");
988
989 WorklistEntry WE;
990 WE.Kind = WorklistEntry::MapAppendingVar;
991 WE.MCID = MCID;
992 WE.Data.AppendingGV.GV = &GV;
993 WE.Data.AppendingGV.InitPrefix = InitPrefix;
994 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
995 WE.AppendingGVNumNewMembers = NewMembers.size();
996 Worklist.push_back(WE);
997 AppendingInits.append(NewMembers.begin(), NewMembers.end());
998}
999
1000void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1001 unsigned MCID) {
1002 assert(MCID < MCs.size() && "Invalid mapping context");
1003
1004 WorklistEntry WE;
1005 WE.Kind = WorklistEntry::MapGlobalAliasee;
1006 WE.MCID = MCID;
1007 WE.Data.GlobalAliasee.GA = &GA;
1008 WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1009 Worklist.push_back(WE);
1010}
1011
1012void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1013 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}