Utils: Thread distinct-ness through the cloneMD*() functions, NFC
[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/Constants.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Metadata.h"
21 using namespace llvm;
22
23 // Out of line method to get vtable etc for class.
24 void ValueMapTypeRemapper::anchor() {}
25 void ValueMaterializer::anchor() {}
26
27 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
28                       ValueMapTypeRemapper *TypeMapper,
29                       ValueMaterializer *Materializer) {
30   ValueToValueMapTy::iterator I = VM.find(V);
31   
32   // If the value already exists in the map, use it.
33   if (I != VM.end() && I->second) return I->second;
34   
35   // If we have a materializer and it can materialize a value, use that.
36   if (Materializer) {
37     if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
38       return VM[V] = NewV;
39   }
40
41   // Global values do not need to be seeded into the VM if they
42   // are using the identity mapping.
43   if (isa<GlobalValue>(V))
44     return VM[V] = const_cast<Value*>(V);
45   
46   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
47     // Inline asm may need *type* remapping.
48     FunctionType *NewTy = IA->getFunctionType();
49     if (TypeMapper) {
50       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
51
52       if (NewTy != IA->getFunctionType())
53         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
54                            IA->hasSideEffects(), IA->isAlignStack());
55     }
56     
57     return VM[V] = const_cast<Value*>(V);
58   }
59
60   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
61     const Metadata *MD = MDV->getMetadata();
62     // If this is a module-level metadata and we know that nothing at the module
63     // level is changing, then use an identity mapping.
64     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
65       return VM[V] = const_cast<Value *>(V);
66
67     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
68     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
69       return VM[V] = const_cast<Value *>(V);
70
71     // FIXME: This assert crashes during bootstrap, but I think it should be
72     // correct.  For now, just match behaviour from before the metadata/value
73     // split.
74     //
75     //    assert(MappedMD && "Referenced metadata value not in value map");
76     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
77   }
78
79   // Okay, this either must be a constant (which may or may not be mappable) or
80   // is something that is not in the mapping table.
81   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
82   if (!C)
83     return nullptr;
84   
85   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
86     Function *F = 
87       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
88     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
89                                                        Flags, TypeMapper, Materializer));
90     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
91   }
92   
93   // Otherwise, we have some other constant to remap.  Start by checking to see
94   // if all operands have an identity remapping.
95   unsigned OpNo = 0, NumOperands = C->getNumOperands();
96   Value *Mapped = nullptr;
97   for (; OpNo != NumOperands; ++OpNo) {
98     Value *Op = C->getOperand(OpNo);
99     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
100     if (Mapped != C) break;
101   }
102   
103   // See if the type mapper wants to remap the type as well.
104   Type *NewTy = C->getType();
105   if (TypeMapper)
106     NewTy = TypeMapper->remapType(NewTy);
107
108   // If the result type and all operands match up, then just insert an identity
109   // mapping.
110   if (OpNo == NumOperands && NewTy == C->getType())
111     return VM[V] = C;
112   
113   // Okay, we need to create a new constant.  We've already processed some or
114   // all of the operands, set them all up now.
115   SmallVector<Constant*, 8> Ops;
116   Ops.reserve(NumOperands);
117   for (unsigned j = 0; j != OpNo; ++j)
118     Ops.push_back(cast<Constant>(C->getOperand(j)));
119   
120   // If one of the operands mismatch, push it and the other mapped operands.
121   if (OpNo != NumOperands) {
122     Ops.push_back(cast<Constant>(Mapped));
123   
124     // Map the rest of the operands that aren't processed yet.
125     for (++OpNo; OpNo != NumOperands; ++OpNo)
126       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
127                              Flags, TypeMapper, Materializer));
128   }
129   
130   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
131     return VM[V] = CE->getWithOperands(Ops, NewTy);
132   if (isa<ConstantArray>(C))
133     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
134   if (isa<ConstantStruct>(C))
135     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
136   if (isa<ConstantVector>(C))
137     return VM[V] = ConstantVector::get(Ops);
138   // If this is a no-operand constant, it must be because the type was remapped.
139   if (isa<UndefValue>(C))
140     return VM[V] = UndefValue::get(NewTy);
141   if (isa<ConstantAggregateZero>(C))
142     return VM[V] = ConstantAggregateZero::get(NewTy);
143   assert(isa<ConstantPointerNull>(C));
144   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
145 }
146
147 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
148                      Metadata *Val) {
149   VM.MD()[Key].reset(Val);
150   return Val;
151 }
152
153 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
154   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
155 }
156
157 static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
158                                  RemapFlags Flags,
159                                  ValueMapTypeRemapper *TypeMapper,
160                                  ValueMaterializer *Materializer);
161
162 static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
163                                  RemapFlags Flags,
164                                  ValueMapTypeRemapper *TypeMapper,
165                                  ValueMaterializer *Materializer) {
166   if (!Op)
167     return nullptr;
168   if (Metadata *MappedOp =
169           MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
170     return MappedOp;
171   // Use identity map if MappedOp is null and we can ignore missing entries.
172   if (Flags & RF_IgnoreMissingEntries)
173     return Op;
174
175   // FIXME: This assert crashes during bootstrap, but I think it should be
176   // correct.  For now, just match behaviour from before the metadata/value
177   // split.
178   //
179   //    llvm_unreachable("Referenced metadata not in value map!");
180   return nullptr;
181 }
182
183 static Metadata *cloneMDTuple(const MDTuple *Node, ValueToValueMapTy &VM,
184                               RemapFlags Flags,
185                               ValueMapTypeRemapper *TypeMapper,
186                               ValueMaterializer *Materializer,
187                               bool IsDistinct) {
188   SmallVector<Metadata *, 4> Elts;
189   Elts.reserve(Node->getNumOperands());
190   for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
191     Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,
192                                  Materializer));
193
194   return (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Node->getContext(),
195                                                             Elts);
196 }
197
198 static Metadata *cloneMDLocation(const MDLocation *Node, ValueToValueMapTy &VM,
199                                  RemapFlags Flags,
200                                  ValueMapTypeRemapper *TypeMapper,
201                                  ValueMaterializer *Materializer,
202                                  bool IsDistinct) {
203   return (IsDistinct ? MDLocation::getDistinct : MDLocation::get)(
204       Node->getContext(), Node->getLine(), Node->getColumn(),
205       mapMetadataOp(Node->getScope(), VM, Flags, TypeMapper, Materializer),
206       mapMetadataOp(Node->getInlinedAt(), VM, Flags, TypeMapper, Materializer));
207 }
208
209 static Metadata *cloneMDNode(const UniquableMDNode *Node, ValueToValueMapTy &VM,
210                              RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
211                              ValueMaterializer *Materializer, bool IsDistinct) {
212   switch (Node->getMetadataID()) {
213   default:
214     llvm_unreachable("Invalid UniquableMDNode subclass");
215 #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
216   case Metadata::CLASS##Kind:                                                  \
217     return clone##CLASS(cast<CLASS>(Node), VM, Flags, TypeMapper,              \
218                         Materializer, IsDistinct);                             \
219     break;
220 #include "llvm/IR/Metadata.def"
221   }
222 }
223
224 /// \brief Map a distinct MDNode.
225 ///
226 /// Distinct nodes are not uniqued, so they must always recreated.
227 static Metadata *mapDistinctNode(const UniquableMDNode *Node,
228                                  ValueToValueMapTy &VM, RemapFlags Flags,
229                                  ValueMapTypeRemapper *TypeMapper,
230                                  ValueMaterializer *Materializer) {
231   assert(Node->isDistinct() && "Expected distinct node");
232
233   // Create the node first so it's available for cyclical references.
234   SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands());
235   MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);
236   mapToMetadata(VM, Node, NewMD);
237
238   // Fix the operands.
239   for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
240     NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,
241                                                TypeMapper, Materializer));
242
243   return NewMD;
244 }
245
246 /// \brief Check whether a uniqued node needs to be remapped.
247 ///
248 /// Check whether a uniqued node needs to be remapped (due to any operands
249 /// changing).
250 static bool shouldRemapUniquedNode(const UniquableMDNode *Node,
251                                    ValueToValueMapTy &VM, RemapFlags Flags,
252                                    ValueMapTypeRemapper *TypeMapper,
253                                    ValueMaterializer *Materializer) {
254   // Check all operands to see if any need to be remapped.
255   for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
256     Metadata *Op = Node->getOperand(I);
257     if (Op != mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer))
258       return true;
259   }
260   return false;
261 }
262
263 /// \brief Map a uniqued MDNode.
264 ///
265 /// Uniqued nodes may not need to be recreated (they may map to themselves).
266 static Metadata *mapUniquedNode(const UniquableMDNode *Node,
267                                  ValueToValueMapTy &VM, RemapFlags Flags,
268                                  ValueMapTypeRemapper *TypeMapper,
269                                  ValueMaterializer *Materializer) {
270   assert(!Node->isDistinct() && "Expected uniqued node");
271
272   // Create a dummy node in case we have a metadata cycle.
273   MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
274   mapToMetadata(VM, Node, Dummy);
275
276   // Check all operands to see if any need to be remapped.
277   if (!shouldRemapUniquedNode(Node, VM, Flags, TypeMapper, Materializer)) {
278     // Use an identity mapping.
279     mapToSelf(VM, Node);
280     MDNode::deleteTemporary(Dummy);
281     return const_cast<Metadata *>(static_cast<const Metadata *>(Node));
282   }
283
284   // At least one operand needs remapping.
285   Metadata *NewMD = cloneMDNode(Node, VM, Flags, TypeMapper, Materializer,
286                                 /* IsDistinct */ false);
287   Dummy->replaceAllUsesWith(NewMD);
288   MDNode::deleteTemporary(Dummy);
289   return mapToMetadata(VM, Node, NewMD);
290 }
291
292 static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
293                                  RemapFlags Flags,
294                                  ValueMapTypeRemapper *TypeMapper,
295                                  ValueMaterializer *Materializer) {
296   // If the value already exists in the map, use it.
297   if (Metadata *NewMD = VM.MD().lookup(MD).get())
298     return NewMD;
299
300   if (isa<MDString>(MD))
301     return mapToSelf(VM, MD);
302
303   if (isa<ConstantAsMetadata>(MD))
304     if ((Flags & RF_NoModuleLevelChanges))
305       return mapToSelf(VM, MD);
306
307   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
308     Value *MappedV =
309         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
310     if (VMD->getValue() == MappedV ||
311         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
312       return mapToSelf(VM, MD);
313
314     // FIXME: This assert crashes during bootstrap, but I think it should be
315     // correct.  For now, just match behaviour from before the metadata/value
316     // split.
317     //
318     //    assert(MappedV && "Referenced metadata not in value map!");
319     if (MappedV)
320       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
321     return nullptr;
322   }
323
324   const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
325   assert(Node->isResolved() && "Unexpected unresolved node");
326
327   // If this is a module-level metadata and we know that nothing at the
328   // module level is changing, then use an identity mapping.
329   if (Flags & RF_NoModuleLevelChanges)
330     return mapToSelf(VM, MD);
331
332   if (Node->isDistinct())
333     return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);
334
335   return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
336 }
337
338 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
339                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
340                             ValueMaterializer *Materializer) {
341   Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
342   if (NewMD && NewMD != MD)
343     if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
344       N->resolveCycles();
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 (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
389            MI = MDs.begin(),
390            ME = MDs.end();
391        MI != ME; ++MI) {
392     MDNode *Old = MI->second;
393     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
394     if (New != Old)
395       I->setMetadata(MI->first, New);
396   }
397   
398   // If the instruction's type is being remapped, do so now.
399   if (TypeMapper)
400     I->mutateType(TypeMapper->remapType(I->getType()));
401 }