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