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