LLVM  mainline
ValueMapper.cpp
Go to the documentation of this file.
00001 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the MapValue function, which is shared by various parts of
00011 // the lib/Transforms/Utils library.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/ValueMapper.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/Function.h"
00018 #include "llvm/IR/InlineAsm.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/IR/Metadata.h"
00021 using namespace llvm;
00022 
00023 // Out of line method to get vtable etc for class.
00024 void ValueMapTypeRemapper::anchor() {}
00025 void ValueMaterializer::anchor() {}
00026 
00027 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
00028                       ValueMapTypeRemapper *TypeMapper,
00029                       ValueMaterializer *Materializer) {
00030   ValueToValueMapTy::iterator I = VM.find(V);
00031   
00032   // If the value already exists in the map, use it.
00033   if (I != VM.end() && I->second) return I->second;
00034   
00035   // If we have a materializer and it can materialize a value, use that.
00036   if (Materializer) {
00037     if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
00038       return VM[V] = NewV;
00039   }
00040 
00041   // Global values do not need to be seeded into the VM if they
00042   // are using the identity mapping.
00043   if (isa<GlobalValue>(V))
00044     return VM[V] = const_cast<Value*>(V);
00045   
00046   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00047     // Inline asm may need *type* remapping.
00048     FunctionType *NewTy = IA->getFunctionType();
00049     if (TypeMapper) {
00050       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
00051 
00052       if (NewTy != IA->getFunctionType())
00053         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
00054                            IA->hasSideEffects(), IA->isAlignStack());
00055     }
00056     
00057     return VM[V] = const_cast<Value*>(V);
00058   }
00059 
00060   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
00061     const Metadata *MD = MDV->getMetadata();
00062     // If this is a module-level metadata and we know that nothing at the module
00063     // level is changing, then use an identity mapping.
00064     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
00065       return VM[V] = const_cast<Value *>(V);
00066 
00067     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
00068     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
00069       return VM[V] = const_cast<Value *>(V);
00070 
00071     // FIXME: This assert crashes during bootstrap, but I think it should be
00072     // correct.  For now, just match behaviour from before the metadata/value
00073     // split.
00074     //
00075     //    assert(MappedMD && "Referenced metadata value not in value map");
00076     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
00077   }
00078 
00079   // Okay, this either must be a constant (which may or may not be mappable) or
00080   // is something that is not in the mapping table.
00081   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
00082   if (!C)
00083     return nullptr;
00084   
00085   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
00086     Function *F = 
00087       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
00088     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
00089                                                        Flags, TypeMapper, Materializer));
00090     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
00091   }
00092   
00093   // Otherwise, we have some other constant to remap.  Start by checking to see
00094   // if all operands have an identity remapping.
00095   unsigned OpNo = 0, NumOperands = C->getNumOperands();
00096   Value *Mapped = nullptr;
00097   for (; OpNo != NumOperands; ++OpNo) {
00098     Value *Op = C->getOperand(OpNo);
00099     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
00100     if (Mapped != C) break;
00101   }
00102   
00103   // See if the type mapper wants to remap the type as well.
00104   Type *NewTy = C->getType();
00105   if (TypeMapper)
00106     NewTy = TypeMapper->remapType(NewTy);
00107 
00108   // If the result type and all operands match up, then just insert an identity
00109   // mapping.
00110   if (OpNo == NumOperands && NewTy == C->getType())
00111     return VM[V] = C;
00112   
00113   // Okay, we need to create a new constant.  We've already processed some or
00114   // all of the operands, set them all up now.
00115   SmallVector<Constant*, 8> Ops;
00116   Ops.reserve(NumOperands);
00117   for (unsigned j = 0; j != OpNo; ++j)
00118     Ops.push_back(cast<Constant>(C->getOperand(j)));
00119   
00120   // If one of the operands mismatch, push it and the other mapped operands.
00121   if (OpNo != NumOperands) {
00122     Ops.push_back(cast<Constant>(Mapped));
00123   
00124     // Map the rest of the operands that aren't processed yet.
00125     for (++OpNo; OpNo != NumOperands; ++OpNo)
00126       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
00127                              Flags, TypeMapper, Materializer));
00128   }
00129   
00130   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00131     return VM[V] = CE->getWithOperands(Ops, NewTy);
00132   if (isa<ConstantArray>(C))
00133     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
00134   if (isa<ConstantStruct>(C))
00135     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
00136   if (isa<ConstantVector>(C))
00137     return VM[V] = ConstantVector::get(Ops);
00138   // If this is a no-operand constant, it must be because the type was remapped.
00139   if (isa<UndefValue>(C))
00140     return VM[V] = UndefValue::get(NewTy);
00141   if (isa<ConstantAggregateZero>(C))
00142     return VM[V] = ConstantAggregateZero::get(NewTy);
00143   assert(isa<ConstantPointerNull>(C));
00144   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
00145 }
00146 
00147 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
00148                      Metadata *Val) {
00149   VM.MD()[Key].reset(Val);
00150   return Val;
00151 }
00152 
00153 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
00154   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
00155 }
00156 
00157 static Metadata *MapMetadataImpl(const Metadata *MD,
00158                                  SmallVectorImpl<MDNode *> &Cycles,
00159                                  ValueToValueMapTy &VM, RemapFlags Flags,
00160                                  ValueMapTypeRemapper *TypeMapper,
00161                                  ValueMaterializer *Materializer);
00162 
00163 static Metadata *mapMetadataOp(Metadata *Op, SmallVectorImpl<MDNode *> &Cycles,
00164                                ValueToValueMapTy &VM, RemapFlags Flags,
00165                                ValueMapTypeRemapper *TypeMapper,
00166                                ValueMaterializer *Materializer) {
00167   if (!Op)
00168     return nullptr;
00169   if (Metadata *MappedOp =
00170           MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer))
00171     return MappedOp;
00172   // Use identity map if MappedOp is null and we can ignore missing entries.
00173   if (Flags & RF_IgnoreMissingEntries)
00174     return Op;
00175 
00176   // FIXME: This assert crashes during bootstrap, but I think it should be
00177   // correct.  For now, just match behaviour from before the metadata/value
00178   // split.
00179   //
00180   //    llvm_unreachable("Referenced metadata not in value map!");
00181   return nullptr;
00182 }
00183 
00184 /// \brief Remap nodes.
00185 ///
00186 /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
00187 /// Assumes that \c NewNode is already a clone of \c OldNode.
00188 ///
00189 /// \pre \c NewNode is a clone of \c OldNode.
00190 static bool remap(const MDNode *OldNode, MDNode *NewNode,
00191                   SmallVectorImpl<MDNode *> &Cycles, ValueToValueMapTy &VM,
00192                   RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00193                   ValueMaterializer *Materializer) {
00194   assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
00195          "Expected nodes to match");
00196   assert(OldNode->isResolved() && "Expected resolved node");
00197   assert(!NewNode->isUniqued() && "Expected non-uniqued node");
00198 
00199   // Map the node upfront so it's available for cyclic references.
00200   mapToMetadata(VM, OldNode, NewNode);
00201   bool AnyChanged = false;
00202   for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
00203     Metadata *Old = OldNode->getOperand(I);
00204     assert(NewNode->getOperand(I) == Old &&
00205            "Expected old operands to already be in place");
00206 
00207     Metadata *New = mapMetadataOp(OldNode->getOperand(I), Cycles, VM, Flags,
00208                                   TypeMapper, Materializer);
00209     if (Old != New) {
00210       AnyChanged = true;
00211       NewNode->replaceOperandWith(I, New);
00212     }
00213   }
00214 
00215   return AnyChanged;
00216 }
00217 
00218 /// \brief Map a distinct MDNode.
00219 ///
00220 /// Distinct nodes are not uniqued, so they must always recreated.
00221 static Metadata *mapDistinctNode(const MDNode *Node,
00222                                  SmallVectorImpl<MDNode *> &Cycles,
00223                                  ValueToValueMapTy &VM, RemapFlags Flags,
00224                                  ValueMapTypeRemapper *TypeMapper,
00225                                  ValueMaterializer *Materializer) {
00226   assert(Node->isDistinct() && "Expected distinct node");
00227 
00228   MDNode *NewMD = MDNode::replaceWithDistinct(Node->clone());
00229   remap(Node, NewMD, Cycles, VM, Flags, TypeMapper, Materializer);
00230 
00231   // Track any cycles beneath this node.
00232   for (Metadata *Op : NewMD->operands())
00233     if (auto *Node = dyn_cast_or_null<MDNode>(Op))
00234       if (!Node->isResolved())
00235         Cycles.push_back(Node);
00236 
00237   return NewMD;
00238 }
00239 
00240 /// \brief Map a uniqued MDNode.
00241 ///
00242 /// Uniqued nodes may not need to be recreated (they may map to themselves).
00243 static Metadata *mapUniquedNode(const MDNode *Node,
00244                                 SmallVectorImpl<MDNode *> &Cycles,
00245                                 ValueToValueMapTy &VM, RemapFlags Flags,
00246                                 ValueMapTypeRemapper *TypeMapper,
00247                                 ValueMaterializer *Materializer) {
00248   assert(Node->isUniqued() && "Expected uniqued node");
00249 
00250   // Create a temporary node upfront in case we have a metadata cycle.
00251   auto ClonedMD = Node->clone();
00252   if (!remap(Node, ClonedMD.get(), Cycles, VM, Flags, TypeMapper, Materializer))
00253     // No operands changed, so use the identity mapping.
00254     return mapToSelf(VM, Node);
00255 
00256   // At least one operand has changed, so uniquify the cloned node.
00257   return mapToMetadata(VM, Node,
00258                        MDNode::replaceWithUniqued(std::move(ClonedMD)));
00259 }
00260 
00261 static Metadata *MapMetadataImpl(const Metadata *MD,
00262                                  SmallVectorImpl<MDNode *> &Cycles,
00263                                  ValueToValueMapTy &VM, RemapFlags Flags,
00264                                  ValueMapTypeRemapper *TypeMapper,
00265                                  ValueMaterializer *Materializer) {
00266   // If the value already exists in the map, use it.
00267   if (Metadata *NewMD = VM.MD().lookup(MD).get())
00268     return NewMD;
00269 
00270   if (isa<MDString>(MD))
00271     return mapToSelf(VM, MD);
00272 
00273   if (isa<ConstantAsMetadata>(MD))
00274     if ((Flags & RF_NoModuleLevelChanges))
00275       return mapToSelf(VM, MD);
00276 
00277   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
00278     Value *MappedV =
00279         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
00280     if (VMD->getValue() == MappedV ||
00281         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
00282       return mapToSelf(VM, MD);
00283 
00284     // FIXME: This assert crashes during bootstrap, but I think it should be
00285     // correct.  For now, just match behaviour from before the metadata/value
00286     // split.
00287     //
00288     //    assert(MappedV && "Referenced metadata not in value map!");
00289     if (MappedV)
00290       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
00291     return nullptr;
00292   }
00293 
00294   // Note: this cast precedes the Flags check so we always get its associated
00295   // assertion.
00296   const MDNode *Node = cast<MDNode>(MD);
00297 
00298   // If this is a module-level metadata and we know that nothing at the
00299   // module level is changing, then use an identity mapping.
00300   if (Flags & RF_NoModuleLevelChanges)
00301     return mapToSelf(VM, MD);
00302 
00303   // Require resolved nodes whenever metadata might be remapped.
00304   assert(Node->isResolved() && "Unexpected unresolved node");
00305 
00306   if (Node->isDistinct())
00307     return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
00308 
00309   return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
00310 }
00311 
00312 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
00313                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00314                             ValueMaterializer *Materializer) {
00315   SmallVector<MDNode *, 8> Cycles;
00316   Metadata *NewMD =
00317       MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer);
00318 
00319   // Resolve cycles underneath MD.
00320   if (NewMD && NewMD != MD) {
00321     if (auto *N = dyn_cast<MDNode>(NewMD))
00322       if (!N->isResolved())
00323         N->resolveCycles();
00324 
00325     for (MDNode *N : Cycles)
00326       if (!N->isResolved())
00327         N->resolveCycles();
00328   } else {
00329     // Shouldn't get unresolved cycles if nothing was remapped.
00330     assert(Cycles.empty() && "Expected no unresolved cycles");
00331   }
00332 
00333   return NewMD;
00334 }
00335 
00336 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
00337                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00338                           ValueMaterializer *Materializer) {
00339   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
00340                                   TypeMapper, Materializer));
00341 }
00342 
00343 /// RemapInstruction - Convert the instruction operands from referencing the
00344 /// current values into those specified by VMap.
00345 ///
00346 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
00347                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00348                             ValueMaterializer *Materializer){
00349   // Remap operands.
00350   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
00351     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
00352     // If we aren't ignoring missing entries, assert that something happened.
00353     if (V)
00354       *op = V;
00355     else
00356       assert((Flags & RF_IgnoreMissingEntries) &&
00357              "Referenced value not in value map!");
00358   }
00359 
00360   // Remap phi nodes' incoming blocks.
00361   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00362     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00363       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
00364       // If we aren't ignoring missing entries, assert that something happened.
00365       if (V)
00366         PN->setIncomingBlock(i, cast<BasicBlock>(V));
00367       else
00368         assert((Flags & RF_IgnoreMissingEntries) &&
00369                "Referenced block not in value map!");
00370     }
00371   }
00372 
00373   // Remap attached metadata.
00374   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00375   I->getAllMetadata(MDs);
00376   for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
00377            MI = MDs.begin(),
00378            ME = MDs.end();
00379        MI != ME; ++MI) {
00380     MDNode *Old = MI->second;
00381     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
00382     if (New != Old)
00383       I->setMetadata(MI->first, New);
00384   }
00385   
00386   // If the instruction's type is being remapped, do so now.
00387   if (TypeMapper)
00388     I->mutateType(TypeMapper->remapType(I->getType()));
00389 }