00a8984845dd4e6a7a3eabc906a056977002ce95
[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) {
171   VM.MD()[Key].reset(Val);
172   return Val;
173 }
174
175 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
176   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
177 }
178
179 static Metadata *MapMetadataImpl(const Metadata *MD,
180                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
181                                  ValueToValueMapTy &VM, RemapFlags Flags,
182                                  ValueMapTypeRemapper *TypeMapper,
183                                  ValueMaterializer *Materializer);
184
185 static Metadata *mapMetadataOp(Metadata *Op,
186                                SmallVectorImpl<MDNode *> &DistinctWorklist,
187                                ValueToValueMapTy &VM, RemapFlags Flags,
188                                ValueMapTypeRemapper *TypeMapper,
189                                ValueMaterializer *Materializer) {
190   if (!Op)
191     return nullptr;
192   if (Metadata *MappedOp = MapMetadataImpl(Op, DistinctWorklist, VM, Flags,
193                                            TypeMapper, Materializer))
194     return MappedOp;
195   // Use identity map if MappedOp is null and we can ignore missing entries.
196   if (Flags & RF_IgnoreMissingEntries)
197     return Op;
198
199   // FIXME: This assert crashes during bootstrap, but I think it should be
200   // correct.  For now, just match behaviour from before the metadata/value
201   // split.
202   //
203   //    assert((Flags & RF_NullMapMissingGlobalValues) &&
204   //           "Referenced metadata not in value map!");
205   return nullptr;
206 }
207
208 /// Resolve uniquing cycles involving the given metadata.
209 static void resolveCycles(Metadata *MD) {
210   if (auto *N = dyn_cast_or_null<MDNode>(MD))
211     if (!N->isResolved())
212       N->resolveCycles();
213 }
214
215 /// Remap the operands of an MDNode.
216 ///
217 /// If \c Node is temporary, uniquing cycles are ignored.  If \c Node is
218 /// distinct, uniquing cycles are resolved as they're found.
219 ///
220 /// \pre \c Node.isDistinct() or \c Node.isTemporary().
221 static bool remapOperands(MDNode &Node,
222                           SmallVectorImpl<MDNode *> &DistinctWorklist,
223                           ValueToValueMapTy &VM, RemapFlags Flags,
224                           ValueMapTypeRemapper *TypeMapper,
225                           ValueMaterializer *Materializer) {
226   assert(!Node.isUniqued() && "Expected temporary or distinct node");
227   const bool IsDistinct = Node.isDistinct();
228
229   bool AnyChanged = false;
230   for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
231     Metadata *Old = Node.getOperand(I);
232     Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
233                                   Materializer);
234     if (Old != New) {
235       AnyChanged = true;
236       Node.replaceOperandWith(I, New);
237
238       // Resolve uniquing cycles underneath distinct nodes on the fly so they
239       // don't infect later operands.
240       if (IsDistinct)
241         resolveCycles(New);
242     }
243   }
244
245   return AnyChanged;
246 }
247
248 /// Map a distinct MDNode.
249 ///
250 /// Whether distinct nodes change is independent of their operands.  If \a
251 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
252 /// place; effectively, they're moved from one graph to another.  Otherwise,
253 /// they're cloned/duplicated, and the new copy's operands are remapped.
254 static Metadata *mapDistinctNode(const MDNode *Node,
255                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
256                                  ValueToValueMapTy &VM, RemapFlags Flags,
257                                  ValueMapTypeRemapper *TypeMapper,
258                                  ValueMaterializer *Materializer) {
259   assert(Node->isDistinct() && "Expected distinct node");
260
261   MDNode *NewMD;
262   if (Flags & RF_MoveDistinctMDs)
263     NewMD = const_cast<MDNode *>(Node);
264   else
265     NewMD = MDNode::replaceWithDistinct(Node->clone());
266
267   // Remap operands later.
268   DistinctWorklist.push_back(NewMD);
269   return mapToMetadata(VM, Node, NewMD);
270 }
271
272 /// \brief Map a uniqued MDNode.
273 ///
274 /// Uniqued nodes may not need to be recreated (they may map to themselves).
275 static Metadata *mapUniquedNode(const MDNode *Node,
276                                 SmallVectorImpl<MDNode *> &DistinctWorklist,
277                                 ValueToValueMapTy &VM, RemapFlags Flags,
278                                 ValueMapTypeRemapper *TypeMapper,
279                                 ValueMaterializer *Materializer) {
280   assert(Node->isUniqued() && "Expected uniqued node");
281
282   // Create a temporary node and map it upfront in case we have a uniquing
283   // cycle.  If necessary, this mapping will get updated by RAUW logic before
284   // returning.
285   auto ClonedMD = Node->clone();
286   mapToMetadata(VM, Node, ClonedMD.get());
287   if (!remapOperands(*ClonedMD, DistinctWorklist, VM, Flags, TypeMapper,
288                      Materializer)) {
289     // No operands changed, so use the original.
290     ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
291     return const_cast<MDNode *>(Node);
292   }
293
294   // Uniquify the cloned node.
295   return MDNode::replaceWithUniqued(std::move(ClonedMD));
296 }
297
298 static Metadata *MapMetadataImpl(const Metadata *MD,
299                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
300                                  ValueToValueMapTy &VM, RemapFlags Flags,
301                                  ValueMapTypeRemapper *TypeMapper,
302                                  ValueMaterializer *Materializer) {
303   // If the value already exists in the map, use it.
304   if (Metadata *NewMD = VM.MD().lookup(MD).get())
305     return NewMD;
306
307   if (isa<MDString>(MD))
308     return mapToSelf(VM, MD);
309
310   if (isa<ConstantAsMetadata>(MD))
311     if ((Flags & RF_NoModuleLevelChanges))
312       return mapToSelf(VM, MD);
313
314   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
315     Value *MappedV =
316         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
317     if (VMD->getValue() == MappedV ||
318         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
319       return mapToSelf(VM, MD);
320
321     // FIXME: This assert crashes during bootstrap, but I think it should be
322     // correct.  For now, just match behaviour from before the metadata/value
323     // split.
324     //
325     //    assert((MappedV || (Flags & RF_NullMapMissingGlobalValues)) &&
326     //           "Referenced metadata not in value map!");
327     if (MappedV)
328       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
329     return nullptr;
330   }
331
332   // Note: this cast precedes the Flags check so we always get its associated
333   // assertion.
334   const MDNode *Node = cast<MDNode>(MD);
335
336   // If this is a module-level metadata and we know that nothing at the
337   // module level is changing, then use an identity mapping.
338   if (Flags & RF_NoModuleLevelChanges)
339     return mapToSelf(VM, MD);
340
341   // Require resolved nodes whenever metadata might be remapped.
342   assert(Node->isResolved() && "Unexpected unresolved node");
343
344   if (Node->isDistinct())
345     return mapDistinctNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
346                            Materializer);
347
348   return mapUniquedNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
349                         Materializer);
350 }
351
352 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
353                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
354                             ValueMaterializer *Materializer) {
355   SmallVector<MDNode *, 8> DistinctWorklist;
356   Metadata *NewMD = MapMetadataImpl(MD, DistinctWorklist, VM, Flags, TypeMapper,
357                                     Materializer);
358
359   // When there are no module-level changes, it's possible that the metadata
360   // graph has temporaries.  Skip the logic to resolve cycles, since it's
361   // unnecessary (and invalid) in that case.
362   if (Flags & RF_NoModuleLevelChanges)
363     return NewMD;
364
365   // Resolve cycles involving the entry metadata.
366   resolveCycles(NewMD);
367
368   // Remap the operands of distinct MDNodes.
369   while (!DistinctWorklist.empty())
370     remapOperands(*DistinctWorklist.pop_back_val(), DistinctWorklist, VM, Flags,
371                   TypeMapper, Materializer);
372
373   return NewMD;
374 }
375
376 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
377                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
378                           ValueMaterializer *Materializer) {
379   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
380                                   TypeMapper, Materializer));
381 }
382
383 /// RemapInstruction - Convert the instruction operands from referencing the
384 /// current values into those specified by VMap.
385 ///
386 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
387                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
388                             ValueMaterializer *Materializer){
389   // Remap operands.
390   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
391     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
392     // If we aren't ignoring missing entries, assert that something happened.
393     if (V)
394       *op = V;
395     else
396       assert((Flags & RF_IgnoreMissingEntries) &&
397              "Referenced value not in value map!");
398   }
399
400   // Remap phi nodes' incoming blocks.
401   if (PHINode *PN = dyn_cast<PHINode>(I)) {
402     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
403       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
404       // If we aren't ignoring missing entries, assert that something happened.
405       if (V)
406         PN->setIncomingBlock(i, cast<BasicBlock>(V));
407       else
408         assert((Flags & RF_IgnoreMissingEntries) &&
409                "Referenced block not in value map!");
410     }
411   }
412
413   // Remap attached metadata.
414   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
415   I->getAllMetadata(MDs);
416   for (const auto &MI : MDs) {
417     MDNode *Old = MI.second;
418     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
419     if (New != Old)
420       I->setMetadata(MI.first, New);
421   }
422   
423   if (!TypeMapper)
424     return;
425
426   // If the instruction's type is being remapped, do so now.
427   if (auto CS = CallSite(I)) {
428     SmallVector<Type *, 3> Tys;
429     FunctionType *FTy = CS.getFunctionType();
430     Tys.reserve(FTy->getNumParams());
431     for (Type *Ty : FTy->params())
432       Tys.push_back(TypeMapper->remapType(Ty));
433     CS.mutateFunctionType(FunctionType::get(
434         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
435     return;
436   }
437   if (auto *AI = dyn_cast<AllocaInst>(I))
438     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
439   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
440     GEP->setSourceElementType(
441         TypeMapper->remapType(GEP->getSourceElementType()));
442     GEP->setResultElementType(
443         TypeMapper->remapType(GEP->getResultElementType()));
444   }
445   I->mutateType(TypeMapper->remapType(I->getType()));
446 }