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