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, 158 SmallVectorImpl<UniquableMDNode *> &Cycles, 159 ValueToValueMapTy &VM, RemapFlags Flags, 160 ValueMapTypeRemapper *TypeMapper, 161 ValueMaterializer *Materializer); 162 163 static Metadata *mapMetadataOp(Metadata *Op, 164 SmallVectorImpl<UniquableMDNode *> &Cycles, 165 ValueToValueMapTy &VM, RemapFlags Flags, 166 ValueMapTypeRemapper *TypeMapper, 167 ValueMaterializer *Materializer) { 168 if (!Op) 169 return nullptr; 170 if (Metadata *MappedOp = 171 MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer)) 172 return MappedOp; 173 // Use identity map if MappedOp is null and we can ignore missing entries. 174 if (Flags & RF_IgnoreMissingEntries) 175 return Op; 176 177 // FIXME: This assert crashes during bootstrap, but I think it should be 178 // correct. For now, just match behaviour from before the metadata/value 179 // split. 180 // 181 // llvm_unreachable("Referenced metadata not in value map!"); 182 return nullptr; 183 } 184 185 static Metadata *cloneMDTuple(const MDTuple *Node, 186 SmallVectorImpl<UniquableMDNode *> &Cycles, 187 ValueToValueMapTy &VM, RemapFlags Flags, 188 ValueMapTypeRemapper *TypeMapper, 189 ValueMaterializer *Materializer, 190 bool IsDistinct) { 191 // Distinct MDTuples have their own code path. 192 assert(!IsDistinct && "Unexpected distinct tuple"); 193 (void)IsDistinct; 194 195 SmallVector<Metadata *, 4> Elts; 196 Elts.reserve(Node->getNumOperands()); 197 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) 198 Elts.push_back(mapMetadataOp(Node->getOperand(I), Cycles, VM, Flags, 199 TypeMapper, Materializer)); 200 201 return MDTuple::get(Node->getContext(), Elts); 202 } 203 204 static Metadata *cloneMDLocation(const MDLocation *Node, 205 SmallVectorImpl<UniquableMDNode *> &Cycles, 206 ValueToValueMapTy &VM, RemapFlags Flags, 207 ValueMapTypeRemapper *TypeMapper, 208 ValueMaterializer *Materializer, 209 bool IsDistinct) { 210 return (IsDistinct ? MDLocation::getDistinct : MDLocation::get)( 211 Node->getContext(), Node->getLine(), Node->getColumn(), 212 mapMetadataOp(Node->getScope(), Cycles, VM, Flags, TypeMapper, 213 Materializer), 214 mapMetadataOp(Node->getInlinedAt(), Cycles, VM, Flags, TypeMapper, 215 Materializer)); 216 } 217 218 static Metadata *cloneMDNode(const UniquableMDNode *Node, 219 SmallVectorImpl<UniquableMDNode *> &Cycles, 220 ValueToValueMapTy &VM, RemapFlags Flags, 221 ValueMapTypeRemapper *TypeMapper, 222 ValueMaterializer *Materializer, bool IsDistinct) { 223 switch (Node->getMetadataID()) { 224 default: 225 llvm_unreachable("Invalid UniquableMDNode subclass"); 226 #define HANDLE_UNIQUABLE_LEAF(CLASS) \ 227 case Metadata::CLASS##Kind: \ 228 return clone##CLASS(cast<CLASS>(Node), Cycles, VM, Flags, TypeMapper, \ 229 Materializer, IsDistinct); 230 #include "llvm/IR/Metadata.def" 231 } 232 } 233 234 static void 235 trackCyclesUnderDistinct(const UniquableMDNode *Node, 236 SmallVectorImpl<UniquableMDNode *> &Cycles) { 237 // Track any cycles beneath this node. 238 for (Metadata *Op : Node->operands()) 239 if (auto *N = dyn_cast_or_null<UniquableMDNode>(Op)) 240 if (!N->isResolved()) 241 Cycles.push_back(N); 242 } 243 244 /// \brief Map a distinct MDNode. 245 /// 246 /// Distinct nodes are not uniqued, so they must always recreated. 247 static Metadata *mapDistinctNode(const UniquableMDNode *Node, 248 SmallVectorImpl<UniquableMDNode *> &Cycles, 249 ValueToValueMapTy &VM, RemapFlags Flags, 250 ValueMapTypeRemapper *TypeMapper, 251 ValueMaterializer *Materializer) { 252 assert(Node->isDistinct() && "Expected distinct node"); 253 254 // Optimization for MDTuples. 255 if (isa<MDTuple>(Node)) { 256 // Create the node first so it's available for cyclical references. 257 SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands()); 258 MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps); 259 mapToMetadata(VM, Node, NewMD); 260 261 // Fix the operands. 262 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) 263 NewMD->replaceOperandWith(I, 264 mapMetadataOp(Node->getOperand(I), Cycles, VM, 265 Flags, TypeMapper, Materializer)); 266 267 trackCyclesUnderDistinct(NewMD, Cycles); 268 return NewMD; 269 } 270 271 // In general we need a dummy node, since whether the operands are null can 272 // affect the size of the node. 273 std::unique_ptr<MDNodeFwdDecl> Dummy( 274 MDNode::getTemporary(Node->getContext(), None)); 275 mapToMetadata(VM, Node, Dummy.get()); 276 auto *NewMD = cast<UniquableMDNode>(cloneMDNode(Node, Cycles, VM, Flags, 277 TypeMapper, Materializer, 278 /* IsDistinct */ true)); 279 Dummy->replaceAllUsesWith(NewMD); 280 trackCyclesUnderDistinct(NewMD, Cycles); 281 return mapToMetadata(VM, Node, NewMD); 282 } 283 284 /// \brief Check whether a uniqued node needs to be remapped. 285 /// 286 /// Check whether a uniqued node needs to be remapped (due to any operands 287 /// changing). 288 static bool shouldRemapUniquedNode(const UniquableMDNode *Node, 289 SmallVectorImpl<UniquableMDNode *> &Cycles, 290 ValueToValueMapTy &VM, RemapFlags Flags, 291 ValueMapTypeRemapper *TypeMapper, 292 ValueMaterializer *Materializer) { 293 // Check all operands to see if any need to be remapped. 294 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 295 Metadata *Op = Node->getOperand(I); 296 if (Op != mapMetadataOp(Op, Cycles, VM, Flags, TypeMapper, Materializer)) 297 return true; 298 } 299 return false; 300 } 301 302 /// \brief Map a uniqued MDNode. 303 /// 304 /// Uniqued nodes may not need to be recreated (they may map to themselves). 305 static Metadata *mapUniquedNode(const UniquableMDNode *Node, 306 SmallVectorImpl<UniquableMDNode *> &Cycles, 307 ValueToValueMapTy &VM, RemapFlags Flags, 308 ValueMapTypeRemapper *TypeMapper, 309 ValueMaterializer *Materializer) { 310 assert(!Node->isDistinct() && "Expected uniqued node"); 311 312 // Create a dummy node in case we have a metadata cycle. 313 MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None); 314 mapToMetadata(VM, Node, Dummy); 315 316 // Check all operands to see if any need to be remapped. 317 if (!shouldRemapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, 318 Materializer)) { 319 // Use an identity mapping. 320 mapToSelf(VM, Node); 321 MDNode::deleteTemporary(Dummy); 322 return const_cast<Metadata *>(static_cast<const Metadata *>(Node)); 323 } 324 325 // At least one operand needs remapping. 326 Metadata *NewMD = 327 cloneMDNode(Node, Cycles, VM, Flags, TypeMapper, Materializer, 328 /* IsDistinct */ false); 329 Dummy->replaceAllUsesWith(NewMD); 330 MDNode::deleteTemporary(Dummy); 331 return mapToMetadata(VM, Node, NewMD); 332 } 333 334 static Metadata *MapMetadataImpl(const Metadata *MD, 335 SmallVectorImpl<UniquableMDNode *> &Cycles, 336 ValueToValueMapTy &VM, RemapFlags Flags, 337 ValueMapTypeRemapper *TypeMapper, 338 ValueMaterializer *Materializer) { 339 // If the value already exists in the map, use it. 340 if (Metadata *NewMD = VM.MD().lookup(MD).get()) 341 return NewMD; 342 343 if (isa<MDString>(MD)) 344 return mapToSelf(VM, MD); 345 346 if (isa<ConstantAsMetadata>(MD)) 347 if ((Flags & RF_NoModuleLevelChanges)) 348 return mapToSelf(VM, MD); 349 350 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) { 351 Value *MappedV = 352 MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer); 353 if (VMD->getValue() == MappedV || 354 (!MappedV && (Flags & RF_IgnoreMissingEntries))) 355 return mapToSelf(VM, MD); 356 357 // FIXME: This assert crashes during bootstrap, but I think it should be 358 // correct. For now, just match behaviour from before the metadata/value 359 // split. 360 // 361 // assert(MappedV && "Referenced metadata not in value map!"); 362 if (MappedV) 363 return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV)); 364 return nullptr; 365 } 366 367 const UniquableMDNode *Node = cast<UniquableMDNode>(MD); 368 assert(Node->isResolved() && "Unexpected unresolved node"); 369 370 // If this is a module-level metadata and we know that nothing at the 371 // module level is changing, then use an identity mapping. 372 if (Flags & RF_NoModuleLevelChanges) 373 return mapToSelf(VM, MD); 374 375 if (Node->isDistinct()) 376 return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer); 377 378 return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer); 379 } 380 381 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, 382 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper, 383 ValueMaterializer *Materializer) { 384 SmallVector<UniquableMDNode *, 8> Cycles; 385 Metadata *NewMD = 386 MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer); 387 388 // Resolve cycles underneath MD. 389 if (NewMD && NewMD != MD) { 390 if (auto *N = dyn_cast<UniquableMDNode>(NewMD)) 391 N->resolveCycles(); 392 393 for (UniquableMDNode *N : Cycles) 394 N->resolveCycles(); 395 } else { 396 // Shouldn't get unresolved cycles if nothing was remapped. 397 assert(Cycles.empty() && "Expected no unresolved cycles"); 398 } 399 400 return NewMD; 401 } 402 403 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM, 404 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper, 405 ValueMaterializer *Materializer) { 406 return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags, 407 TypeMapper, Materializer)); 408 } 409 410 /// RemapInstruction - Convert the instruction operands from referencing the 411 /// current values into those specified by VMap. 412 /// 413 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap, 414 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper, 415 ValueMaterializer *Materializer){ 416 // Remap operands. 417 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) { 418 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer); 419 // If we aren't ignoring missing entries, assert that something happened. 420 if (V) 421 *op = V; 422 else 423 assert((Flags & RF_IgnoreMissingEntries) && 424 "Referenced value not in value map!"); 425 } 426 427 // Remap phi nodes' incoming blocks. 428 if (PHINode *PN = dyn_cast<PHINode>(I)) { 429 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 430 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags); 431 // If we aren't ignoring missing entries, assert that something happened. 432 if (V) 433 PN->setIncomingBlock(i, cast<BasicBlock>(V)); 434 else 435 assert((Flags & RF_IgnoreMissingEntries) && 436 "Referenced block not in value map!"); 437 } 438 } 439 440 // Remap attached metadata. 441 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 442 I->getAllMetadata(MDs); 443 for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator 444 MI = MDs.begin(), 445 ME = MDs.end(); 446 MI != ME; ++MI) { 447 MDNode *Old = MI->second; 448 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer); 449 if (New != Old) 450 I->setMetadata(MI->first, New); 451 } 452 453 // If the instruction's type is being remapped, do so now. 454 if (TypeMapper) 455 I->mutateType(TypeMapper->remapType(I->getType())); 456 } 457