1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/ValueMapper.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/Operator.h"
25 // Out of line method to get vtable etc for class.
26 void ValueMapTypeRemapper::anchor() {}
27 void ValueMaterializer::anchor() {}
29 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
30 ValueMapTypeRemapper *TypeMapper,
31 ValueMaterializer *Materializer) {
32 ValueToValueMapTy::iterator I = VM.find(V);
34 // If the value already exists in the map, use it.
35 if (I != VM.end() && I->second) return I->second;
37 // If we have a materializer and it can materialize a value, use that.
39 if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
43 // Global values do not need to be seeded into the VM if they
44 // are using the identity mapping.
45 if (isa<GlobalValue>(V))
46 return VM[V] = const_cast<Value*>(V);
48 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
49 // Inline asm may need *type* remapping.
50 FunctionType *NewTy = IA->getFunctionType();
52 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
54 if (NewTy != IA->getFunctionType())
55 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
56 IA->hasSideEffects(), IA->isAlignStack());
59 return VM[V] = const_cast<Value*>(V);
62 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
63 const Metadata *MD = MDV->getMetadata();
64 // If this is a module-level metadata and we know that nothing at the module
65 // level is changing, then use an identity mapping.
66 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
67 return VM[V] = const_cast<Value *>(V);
69 auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
70 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
71 return VM[V] = const_cast<Value *>(V);
73 // FIXME: This assert crashes during bootstrap, but I think it should be
74 // correct. For now, just match behaviour from before the metadata/value
77 // assert(MappedMD && "Referenced metadata value not in value map");
78 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
81 // Okay, this either must be a constant (which may or may not be mappable) or
82 // is something that is not in the mapping table.
83 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
87 if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
89 cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
90 BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
91 Flags, TypeMapper, Materializer));
92 return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
95 // Otherwise, we have some other constant to remap. Start by checking to see
96 // if all operands have an identity remapping.
97 unsigned OpNo = 0, NumOperands = C->getNumOperands();
98 Value *Mapped = nullptr;
99 for (; OpNo != NumOperands; ++OpNo) {
100 Value *Op = C->getOperand(OpNo);
101 Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
102 if (Mapped != C) break;
105 // See if the type mapper wants to remap the type as well.
106 Type *NewTy = C->getType();
108 NewTy = TypeMapper->remapType(NewTy);
110 // If the result type and all operands match up, then just insert an identity
112 if (OpNo == NumOperands && NewTy == C->getType())
115 // Okay, we need to create a new constant. We've already processed some or
116 // all of the operands, set them all up now.
117 SmallVector<Constant*, 8> Ops;
118 Ops.reserve(NumOperands);
119 for (unsigned j = 0; j != OpNo; ++j)
120 Ops.push_back(cast<Constant>(C->getOperand(j)));
122 // If one of the operands mismatch, push it and the other mapped operands.
123 if (OpNo != NumOperands) {
124 Ops.push_back(cast<Constant>(Mapped));
126 // Map the rest of the operands that aren't processed yet.
127 for (++OpNo; OpNo != NumOperands; ++OpNo)
128 Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
129 Flags, TypeMapper, Materializer));
131 Type *NewSrcTy = nullptr;
133 if (auto *GEPO = dyn_cast<GEPOperator>(C))
134 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
136 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
137 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
138 if (isa<ConstantArray>(C))
139 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
140 if (isa<ConstantStruct>(C))
141 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
142 if (isa<ConstantVector>(C))
143 return VM[V] = ConstantVector::get(Ops);
144 // If this is a no-operand constant, it must be because the type was remapped.
145 if (isa<UndefValue>(C))
146 return VM[V] = UndefValue::get(NewTy);
147 if (isa<ConstantAggregateZero>(C))
148 return VM[V] = ConstantAggregateZero::get(NewTy);
149 assert(isa<ConstantPointerNull>(C));
150 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
153 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
155 VM.MD()[Key].reset(Val);
159 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
160 return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
163 static Metadata *MapMetadataImpl(const Metadata *MD,
164 SmallVectorImpl<MDNode *> &DistinctWorklist,
165 ValueToValueMapTy &VM, RemapFlags Flags,
166 ValueMapTypeRemapper *TypeMapper,
167 ValueMaterializer *Materializer);
169 static Metadata *mapMetadataOp(Metadata *Op,
170 SmallVectorImpl<MDNode *> &DistinctWorklist,
171 ValueToValueMapTy &VM, RemapFlags Flags,
172 ValueMapTypeRemapper *TypeMapper,
173 ValueMaterializer *Materializer) {
176 if (Metadata *MappedOp = MapMetadataImpl(Op, DistinctWorklist, VM, Flags,
177 TypeMapper, Materializer))
179 // Use identity map if MappedOp is null and we can ignore missing entries.
180 if (Flags & RF_IgnoreMissingEntries)
183 // FIXME: This assert crashes during bootstrap, but I think it should be
184 // correct. For now, just match behaviour from before the metadata/value
187 // llvm_unreachable("Referenced metadata not in value map!");
191 /// Resolve uniquing cycles involving the given metadata.
192 static void resolveCycles(Metadata *MD) {
193 if (auto *N = dyn_cast_or_null<MDNode>(MD))
194 if (!N->isResolved())
198 /// Remap the operands of an MDNode.
200 /// If \c Node is temporary, uniquing cycles are ignored. If \c Node is
201 /// distinct, uniquing cycles are resolved as they're found.
203 /// \pre \c Node.isDistinct() or \c Node.isTemporary().
204 static bool remapOperands(MDNode &Node,
205 SmallVectorImpl<MDNode *> &DistinctWorklist,
206 ValueToValueMapTy &VM, RemapFlags Flags,
207 ValueMapTypeRemapper *TypeMapper,
208 ValueMaterializer *Materializer) {
209 assert(!Node.isUniqued() && "Expected temporary or distinct node");
210 const bool IsDistinct = Node.isDistinct();
212 bool AnyChanged = false;
213 for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
214 Metadata *Old = Node.getOperand(I);
215 Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
219 Node.replaceOperandWith(I, New);
221 // Resolve uniquing cycles underneath distinct nodes on the fly so they
222 // don't infect later operands.
231 /// Map a distinct MDNode.
233 /// Whether distinct nodes change is independent of their operands. If \a
234 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
235 /// place; effectively, they're moved from one graph to another. Otherwise,
236 /// they're cloned/duplicated, and the new copy's operands are remapped.
237 static Metadata *mapDistinctNode(const MDNode *Node,
238 SmallVectorImpl<MDNode *> &DistinctWorklist,
239 ValueToValueMapTy &VM, RemapFlags Flags,
240 ValueMapTypeRemapper *TypeMapper,
241 ValueMaterializer *Materializer) {
242 assert(Node->isDistinct() && "Expected distinct node");
245 if (Flags & RF_MoveDistinctMDs)
246 NewMD = const_cast<MDNode *>(Node);
248 NewMD = MDNode::replaceWithDistinct(Node->clone());
250 // Remap operands later.
251 DistinctWorklist.push_back(NewMD);
252 return mapToMetadata(VM, Node, NewMD);
255 /// \brief Map a uniqued MDNode.
257 /// Uniqued nodes may not need to be recreated (they may map to themselves).
258 static Metadata *mapUniquedNode(const MDNode *Node,
259 SmallVectorImpl<MDNode *> &DistinctWorklist,
260 ValueToValueMapTy &VM, RemapFlags Flags,
261 ValueMapTypeRemapper *TypeMapper,
262 ValueMaterializer *Materializer) {
263 assert(Node->isUniqued() && "Expected uniqued node");
265 // Create a temporary node and map it upfront in case we have a uniquing
266 // cycle. If necessary, this mapping will get updated by RAUW logic before
268 auto ClonedMD = Node->clone();
269 mapToMetadata(VM, Node, ClonedMD.get());
270 if (!remapOperands(*ClonedMD, DistinctWorklist, VM, Flags, TypeMapper,
272 // No operands changed, so use the original.
273 ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
274 return const_cast<MDNode *>(Node);
277 // Uniquify the cloned node.
278 return MDNode::replaceWithUniqued(std::move(ClonedMD));
281 static Metadata *MapMetadataImpl(const Metadata *MD,
282 SmallVectorImpl<MDNode *> &DistinctWorklist,
283 ValueToValueMapTy &VM, RemapFlags Flags,
284 ValueMapTypeRemapper *TypeMapper,
285 ValueMaterializer *Materializer) {
286 // If the value already exists in the map, use it.
287 if (Metadata *NewMD = VM.MD().lookup(MD).get())
290 if (isa<MDString>(MD))
291 return mapToSelf(VM, MD);
293 if (isa<ConstantAsMetadata>(MD))
294 if ((Flags & RF_NoModuleLevelChanges))
295 return mapToSelf(VM, MD);
297 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
299 MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
300 if (VMD->getValue() == MappedV ||
301 (!MappedV && (Flags & RF_IgnoreMissingEntries)))
302 return mapToSelf(VM, MD);
304 // FIXME: This assert crashes during bootstrap, but I think it should be
305 // correct. For now, just match behaviour from before the metadata/value
308 // assert(MappedV && "Referenced metadata not in value map!");
310 return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
314 // Note: this cast precedes the Flags check so we always get its associated
316 const MDNode *Node = cast<MDNode>(MD);
318 // If this is a module-level metadata and we know that nothing at the
319 // module level is changing, then use an identity mapping.
320 if (Flags & RF_NoModuleLevelChanges)
321 return mapToSelf(VM, MD);
323 // Require resolved nodes whenever metadata might be remapped.
324 assert(Node->isResolved() && "Unexpected unresolved node");
326 if (Node->isDistinct())
327 return mapDistinctNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
330 return mapUniquedNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
334 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
335 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
336 ValueMaterializer *Materializer) {
337 SmallVector<MDNode *, 8> DistinctWorklist;
338 Metadata *NewMD = MapMetadataImpl(MD, DistinctWorklist, VM, Flags, TypeMapper,
341 // When there are no module-level changes, it's possible that the metadata
342 // graph has temporaries. Skip the logic to resolve cycles, since it's
343 // unnecessary (and invalid) in that case.
344 if (Flags & RF_NoModuleLevelChanges)
347 // Resolve cycles involving the entry metadata.
348 resolveCycles(NewMD);
350 // Remap the operands of distinct MDNodes.
351 while (!DistinctWorklist.empty())
352 remapOperands(*DistinctWorklist.pop_back_val(), DistinctWorklist, VM, Flags,
353 TypeMapper, Materializer);
358 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
359 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
360 ValueMaterializer *Materializer) {
361 return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
362 TypeMapper, Materializer));
365 /// RemapInstruction - Convert the instruction operands from referencing the
366 /// current values into those specified by VMap.
368 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
369 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
370 ValueMaterializer *Materializer){
372 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
373 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
374 // If we aren't ignoring missing entries, assert that something happened.
378 assert((Flags & RF_IgnoreMissingEntries) &&
379 "Referenced value not in value map!");
382 // Remap phi nodes' incoming blocks.
383 if (PHINode *PN = dyn_cast<PHINode>(I)) {
384 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
385 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
386 // If we aren't ignoring missing entries, assert that something happened.
388 PN->setIncomingBlock(i, cast<BasicBlock>(V));
390 assert((Flags & RF_IgnoreMissingEntries) &&
391 "Referenced block not in value map!");
395 // Remap attached metadata.
396 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
397 I->getAllMetadata(MDs);
398 for (const auto &MI : MDs) {
399 MDNode *Old = MI.second;
400 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
402 I->setMetadata(MI.first, New);
408 // If the instruction's type is being remapped, do so now.
409 if (auto CS = CallSite(I)) {
410 SmallVector<Type *, 3> Tys;
411 FunctionType *FTy = CS.getFunctionType();
412 Tys.reserve(FTy->getNumParams());
413 for (Type *Ty : FTy->params())
414 Tys.push_back(TypeMapper->remapType(Ty));
415 CS.mutateFunctionType(FunctionType::get(
416 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
419 if (auto *AI = dyn_cast<AllocaInst>(I))
420 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
421 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
422 GEP->setSourceElementType(
423 TypeMapper->remapType(GEP->getSourceElementType()));
424 GEP->setResultElementType(
425 TypeMapper->remapType(GEP->getResultElementType()));
427 I->mutateType(TypeMapper->remapType(I->getType()));