Linker: Fix references to uniqued nodes after r243883
[oota-llvm.git] / lib / Transforms / Utils / ValueMapper.cpp
1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
12 //
13 //===----------------------------------------------------------------------===//
14
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 using namespace llvm;
23
24 // Out of line method to get vtable etc for class.
25 void ValueMapTypeRemapper::anchor() {}
26 void ValueMaterializer::anchor() {}
27
28 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
29                       ValueMapTypeRemapper *TypeMapper,
30                       ValueMaterializer *Materializer) {
31   ValueToValueMapTy::iterator I = VM.find(V);
32   
33   // If the value already exists in the map, use it.
34   if (I != VM.end() && I->second) return I->second;
35   
36   // If we have a materializer and it can materialize a value, use that.
37   if (Materializer) {
38     if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
39       return VM[V] = NewV;
40   }
41
42   // Global values do not need to be seeded into the VM if they
43   // are using the identity mapping.
44   if (isa<GlobalValue>(V))
45     return VM[V] = const_cast<Value*>(V);
46   
47   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
48     // Inline asm may need *type* remapping.
49     FunctionType *NewTy = IA->getFunctionType();
50     if (TypeMapper) {
51       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
52
53       if (NewTy != IA->getFunctionType())
54         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
55                            IA->hasSideEffects(), IA->isAlignStack());
56     }
57     
58     return VM[V] = const_cast<Value*>(V);
59   }
60
61   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
62     const Metadata *MD = MDV->getMetadata();
63     // If this is a module-level metadata and we know that nothing at the module
64     // level is changing, then use an identity mapping.
65     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
66       return VM[V] = const_cast<Value *>(V);
67
68     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
69     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
70       return VM[V] = const_cast<Value *>(V);
71
72     // FIXME: This assert crashes during bootstrap, but I think it should be
73     // correct.  For now, just match behaviour from before the metadata/value
74     // split.
75     //
76     //    assert(MappedMD && "Referenced metadata value not in value map");
77     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
78   }
79
80   // Okay, this either must be a constant (which may or may not be mappable) or
81   // is something that is not in the mapping table.
82   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
83   if (!C)
84     return nullptr;
85   
86   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
87     Function *F = 
88       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
89     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
90                                                        Flags, TypeMapper, Materializer));
91     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
92   }
93   
94   // Otherwise, we have some other constant to remap.  Start by checking to see
95   // if all operands have an identity remapping.
96   unsigned OpNo = 0, NumOperands = C->getNumOperands();
97   Value *Mapped = nullptr;
98   for (; OpNo != NumOperands; ++OpNo) {
99     Value *Op = C->getOperand(OpNo);
100     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
101     if (Mapped != C) break;
102   }
103   
104   // See if the type mapper wants to remap the type as well.
105   Type *NewTy = C->getType();
106   if (TypeMapper)
107     NewTy = TypeMapper->remapType(NewTy);
108
109   // If the result type and all operands match up, then just insert an identity
110   // mapping.
111   if (OpNo == NumOperands && NewTy == C->getType())
112     return VM[V] = C;
113   
114   // Okay, we need to create a new constant.  We've already processed some or
115   // all of the operands, set them all up now.
116   SmallVector<Constant*, 8> Ops;
117   Ops.reserve(NumOperands);
118   for (unsigned j = 0; j != OpNo; ++j)
119     Ops.push_back(cast<Constant>(C->getOperand(j)));
120   
121   // If one of the operands mismatch, push it and the other mapped operands.
122   if (OpNo != NumOperands) {
123     Ops.push_back(cast<Constant>(Mapped));
124   
125     // Map the rest of the operands that aren't processed yet.
126     for (++OpNo; OpNo != NumOperands; ++OpNo)
127       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
128                              Flags, TypeMapper, Materializer));
129   }
130   
131   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
132     return VM[V] = CE->getWithOperands(Ops, NewTy);
133   if (isa<ConstantArray>(C))
134     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
135   if (isa<ConstantStruct>(C))
136     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
137   if (isa<ConstantVector>(C))
138     return VM[V] = ConstantVector::get(Ops);
139   // If this is a no-operand constant, it must be because the type was remapped.
140   if (isa<UndefValue>(C))
141     return VM[V] = UndefValue::get(NewTy);
142   if (isa<ConstantAggregateZero>(C))
143     return VM[V] = ConstantAggregateZero::get(NewTy);
144   assert(isa<ConstantPointerNull>(C));
145   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
146 }
147
148 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
149                      Metadata *Val) {
150   VM.MD()[Key].reset(Val);
151   return Val;
152 }
153
154 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
155   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
156 }
157
158 static Metadata *MapMetadataImpl(const Metadata *MD,
159                                  SmallVectorImpl<MDNode *> &Cycles,
160                                  ValueToValueMapTy &VM, RemapFlags Flags,
161                                  ValueMapTypeRemapper *TypeMapper,
162                                  ValueMaterializer *Materializer);
163
164 static Metadata *mapMetadataOp(Metadata *Op, SmallVectorImpl<MDNode *> &Cycles,
165                                ValueToValueMapTy &VM, RemapFlags Flags,
166                                ValueMapTypeRemapper *TypeMapper,
167                                ValueMaterializer *Materializer) {
168   if (!Op)
169     return nullptr;
170   if (Metadata *MappedOp =
171           MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer))
172     return MappedOp;
173   // Use identity map if MappedOp is null and we can ignore missing entries.
174   if (Flags & RF_IgnoreMissingEntries)
175     return Op;
176
177   // FIXME: This assert crashes during bootstrap, but I think it should be
178   // correct.  For now, just match behaviour from before the metadata/value
179   // split.
180   //
181   //    llvm_unreachable("Referenced metadata not in value map!");
182   return nullptr;
183 }
184
185 /// \brief Remap nodes.
186 ///
187 /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
188 /// Assumes that \c NewNode is already a clone of \c OldNode.
189 ///
190 /// \pre \c NewNode is a clone of \c OldNode.
191 static bool remap(const MDNode *OldNode, MDNode *NewNode,
192                   SmallVectorImpl<MDNode *> &Cycles, ValueToValueMapTy &VM,
193                   RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
194                   ValueMaterializer *Materializer) {
195   assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
196          "Expected nodes to match");
197   assert(OldNode->isResolved() && "Expected resolved node");
198   assert(!NewNode->isUniqued() && "Expected non-uniqued node");
199
200   // Map the node upfront so it's available for cyclic references.
201   mapToMetadata(VM, OldNode, NewNode);
202   bool AnyChanged = false;
203   for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
204     Metadata *Old = OldNode->getOperand(I);
205     assert(NewNode->getOperand(I) == Old &&
206            "Expected old operands to already be in place");
207
208     Metadata *New =
209         mapMetadataOp(Old, Cycles, VM, Flags, TypeMapper, Materializer);
210     if (Old != New) {
211       AnyChanged = true;
212       NewNode->replaceOperandWith(I, New);
213     }
214   }
215
216   return AnyChanged;
217 }
218
219 /// Map a distinct MDNode.
220 ///
221 /// Whether distinct nodes change is independent of their operands.  If \a
222 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
223 /// place; effectively, they're moved from one graph to another.  Otherwise,
224 /// they're cloned/duplicated, and the new copy's operands are remapped.
225 static Metadata *mapDistinctNode(const MDNode *Node,
226                                  SmallVectorImpl<MDNode *> &Cycles,
227                                  ValueToValueMapTy &VM, RemapFlags Flags,
228                                  ValueMapTypeRemapper *TypeMapper,
229                                  ValueMaterializer *Materializer) {
230   assert(Node->isDistinct() && "Expected distinct node");
231
232   MDNode *NewMD;
233   if (Flags & RF_MoveDistinctMDs)
234     NewMD = const_cast<MDNode *>(Node);
235   else
236     NewMD = MDNode::replaceWithDistinct(Node->clone());
237
238   // Remap the operands.  If any change, track those that could be involved in
239   // uniquing cycles.
240   if (remap(Node, NewMD, Cycles, VM, Flags, TypeMapper, Materializer))
241     for (Metadata *Op : NewMD->operands())
242       if (auto *Node = dyn_cast_or_null<MDNode>(Op))
243         if (!Node->isResolved())
244           Cycles.push_back(Node);
245
246   return NewMD;
247 }
248
249 /// \brief Map a uniqued MDNode.
250 ///
251 /// Uniqued nodes may not need to be recreated (they may map to themselves).
252 static Metadata *mapUniquedNode(const MDNode *Node,
253                                 SmallVectorImpl<MDNode *> &Cycles,
254                                 ValueToValueMapTy &VM, RemapFlags Flags,
255                                 ValueMapTypeRemapper *TypeMapper,
256                                 ValueMaterializer *Materializer) {
257   assert(Node->isUniqued() && "Expected uniqued node");
258
259   // Create a temporary node upfront in case we have a metadata cycle.
260   auto ClonedMD = Node->clone();
261   if (!remap(Node, ClonedMD.get(), Cycles, VM, Flags, TypeMapper, Materializer)) {
262     // No operands changed, so use the identity mapping.
263     ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
264     return mapToSelf(VM, Node);
265   }
266
267   // At least one operand has changed, so uniquify the cloned node.
268   return mapToMetadata(VM, Node,
269                        MDNode::replaceWithUniqued(std::move(ClonedMD)));
270 }
271
272 static Metadata *MapMetadataImpl(const Metadata *MD,
273                                  SmallVectorImpl<MDNode *> &Cycles,
274                                  ValueToValueMapTy &VM, RemapFlags Flags,
275                                  ValueMapTypeRemapper *TypeMapper,
276                                  ValueMaterializer *Materializer) {
277   // If the value already exists in the map, use it.
278   if (Metadata *NewMD = VM.MD().lookup(MD).get())
279     return NewMD;
280
281   if (isa<MDString>(MD))
282     return mapToSelf(VM, MD);
283
284   if (isa<ConstantAsMetadata>(MD))
285     if ((Flags & RF_NoModuleLevelChanges))
286       return mapToSelf(VM, MD);
287
288   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
289     Value *MappedV =
290         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
291     if (VMD->getValue() == MappedV ||
292         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
293       return mapToSelf(VM, MD);
294
295     // FIXME: This assert crashes during bootstrap, but I think it should be
296     // correct.  For now, just match behaviour from before the metadata/value
297     // split.
298     //
299     //    assert(MappedV && "Referenced metadata not in value map!");
300     if (MappedV)
301       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
302     return nullptr;
303   }
304
305   // Note: this cast precedes the Flags check so we always get its associated
306   // assertion.
307   const MDNode *Node = cast<MDNode>(MD);
308
309   // If this is a module-level metadata and we know that nothing at the
310   // module level is changing, then use an identity mapping.
311   if (Flags & RF_NoModuleLevelChanges)
312     return mapToSelf(VM, MD);
313
314   // Require resolved nodes whenever metadata might be remapped.
315   assert(Node->isResolved() && "Unexpected unresolved node");
316
317   if (Node->isDistinct())
318     return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
319
320   return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
321 }
322
323 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
324                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
325                             ValueMaterializer *Materializer) {
326   SmallVector<MDNode *, 8> Cycles;
327   Metadata *NewMD =
328       MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer);
329
330   if ((Flags & RF_NoModuleLevelChanges) ||
331       (MD == NewMD && !(Flags & RF_MoveDistinctMDs))) {
332     assert(Cycles.empty() && "Unresolved cycles without remapping anything?");
333     return NewMD;
334   }
335
336   if (auto *N = dyn_cast<MDNode>(NewMD))
337     if (!N->isResolved())
338       N->resolveCycles();
339
340   // Resolve cycles underneath MD.
341   for (MDNode *N : Cycles)
342     if (!N->isResolved())
343       N->resolveCycles();
344
345   return NewMD;
346 }
347
348 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
349                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
350                           ValueMaterializer *Materializer) {
351   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
352                                   TypeMapper, Materializer));
353 }
354
355 /// RemapInstruction - Convert the instruction operands from referencing the
356 /// current values into those specified by VMap.
357 ///
358 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
359                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
360                             ValueMaterializer *Materializer){
361   // Remap operands.
362   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
363     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
364     // If we aren't ignoring missing entries, assert that something happened.
365     if (V)
366       *op = V;
367     else
368       assert((Flags & RF_IgnoreMissingEntries) &&
369              "Referenced value not in value map!");
370   }
371
372   // Remap phi nodes' incoming blocks.
373   if (PHINode *PN = dyn_cast<PHINode>(I)) {
374     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
375       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
376       // If we aren't ignoring missing entries, assert that something happened.
377       if (V)
378         PN->setIncomingBlock(i, cast<BasicBlock>(V));
379       else
380         assert((Flags & RF_IgnoreMissingEntries) &&
381                "Referenced block not in value map!");
382     }
383   }
384
385   // Remap attached metadata.
386   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
387   I->getAllMetadata(MDs);
388   for (const auto &MI : MDs) {
389     MDNode *Old = MI.second;
390     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
391     if (New != Old)
392       I->setMetadata(MI.first, New);
393   }
394   
395   if (!TypeMapper)
396     return;
397
398   // If the instruction's type is being remapped, do so now.
399   if (auto CS = CallSite(I)) {
400     SmallVector<Type *, 3> Tys;
401     FunctionType *FTy = CS.getFunctionType();
402     Tys.reserve(FTy->getNumParams());
403     for (Type *Ty : FTy->params())
404       Tys.push_back(TypeMapper->remapType(Ty));
405     CS.mutateFunctionType(FunctionType::get(
406         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
407     return;
408   }
409   if (auto *AI = dyn_cast<AllocaInst>(I))
410     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
411   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
412     GEP->setSourceElementType(
413         TypeMapper->remapType(GEP->getSourceElementType()));
414     GEP->setResultElementType(
415         TypeMapper->remapType(GEP->getResultElementType()));
416   }
417   I->mutateType(TypeMapper->remapType(I->getType()));
418 }