LLVM 22.0.0git
CloneFunction.cpp
Go to the documentation of this file.
1//===- CloneFunction.cpp - Clone a function into another function ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the CloneFunctionInto interface, which is used as the
10// low-level function cloner. This is used by the CloneFunction and function
11// inliner to do the dirty work of copying the body of a function around.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/Statistic.h"
22#include "llvm/IR/CFG.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
33#include "llvm/IR/Module.h"
38#include <cstdint>
39#include <map>
40#include <optional>
41using namespace llvm;
42
43#define DEBUG_TYPE "clone-function"
44
45STATISTIC(RemappedAtomMax, "Highest global NextAtomGroup (after mapping)");
46
48 uint64_t CurGroup = DL->getAtomGroup();
49 if (!CurGroup)
50 return;
51
52 // Try inserting a new entry. If there's already a mapping for this atom
53 // then there's nothing to do.
54 auto [It, Inserted] = VMap.AtomMap.insert({{DL.getInlinedAt(), CurGroup}, 0});
55 if (!Inserted)
56 return;
57
58 // Map entry to a new atom group.
59 uint64_t NewGroup = DL->getContext().incNextDILocationAtomGroup();
60 assert(NewGroup > CurGroup && "Next should always be greater than current");
61 It->second = NewGroup;
62
63 RemappedAtomMax = std::max<uint64_t>(NewGroup, RemappedAtomMax);
64}
65
67 DebugInfoFinder &DIFinder) {
68 const Module *M = F.getParent();
69 if (!M)
70 return;
71 // Inspect instructions to process e.g. DILexicalBlocks of inlined functions
72 for (const Instruction &I : instructions(F))
73 DIFinder.processInstruction(*M, I);
74}
75
76// Create a predicate that matches the metadata that should be identity mapped
77// during function cloning.
81 return [](const Metadata *MD) { return false; };
82
83 DISubprogram *SPClonedWithinModule = F.getSubprogram();
84
85 // Don't clone inlined subprograms.
86 auto ShouldKeep = [SPClonedWithinModule](const DISubprogram *SP) -> bool {
87 return SP != SPClonedWithinModule;
88 };
89
90 return [=](const Metadata *MD) {
91 // Avoid cloning types, compile units, and (other) subprograms.
92 if (isa<DICompileUnit>(MD) || isa<DIType>(MD))
93 return true;
94
95 if (auto *SP = dyn_cast<DISubprogram>(MD))
96 return ShouldKeep(SP);
97
98 // If a subprogram isn't going to be cloned skip its lexical blocks as well.
99 if (auto *LScope = dyn_cast<DILocalScope>(MD))
100 return ShouldKeep(LScope->getSubprogram());
101
102 // Avoid cloning local variables of subprograms that won't be cloned.
103 if (auto *DV = dyn_cast<DILocalVariable>(MD))
104 if (auto *S = dyn_cast_or_null<DILocalScope>(DV->getScope()))
105 return ShouldKeep(S->getSubprogram());
106
107 return false;
108 };
109}
110
111/// See comments in Cloning.h.
113 const Twine &NameSuffix, Function *F,
114 ClonedCodeInfo *CodeInfo, bool MapAtoms) {
115 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
116 if (BB->hasName())
117 NewBB->setName(BB->getName() + NameSuffix);
118
119 bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
120
121 // Loop over all instructions, and copy them over.
122 for (const Instruction &I : *BB) {
123 Instruction *NewInst = I.clone();
124 if (I.hasName())
125 NewInst->setName(I.getName() + NameSuffix);
126
127 NewInst->insertBefore(*NewBB, NewBB->end());
128 NewInst->cloneDebugInfoFrom(&I);
129
130 VMap[&I] = NewInst; // Add instruction map to value.
131
132 if (MapAtoms) {
133 if (const DebugLoc &DL = NewInst->getDebugLoc())
134 mapAtomInstance(DL.get(), VMap);
135 }
136
137 if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
138 hasCalls = true;
139 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
140 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_callsite);
141 }
142 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
143 if (!AI->isStaticAlloca()) {
144 hasDynamicAllocas = true;
145 }
146 }
147 }
148
149 if (CodeInfo) {
150 CodeInfo->ContainsCalls |= hasCalls;
151 CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
152 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
153 }
154 return NewBB;
155}
156
158 const Function *OldFunc,
159 ValueToValueMapTy &VMap,
160 bool ModuleLevelChanges,
161 ValueMapTypeRemapper *TypeMapper,
162 ValueMaterializer *Materializer) {
163 // Copy all attributes other than those stored in Function's AttributeList
164 // which holds e.g. parameters and return value attributes.
165 AttributeList NewAttrs = NewFunc->getAttributes();
166 NewFunc->copyAttributesFrom(OldFunc);
167 NewFunc->setAttributes(NewAttrs);
168
169 const RemapFlags FuncGlobalRefFlags =
170 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
171
172 // Fix up the personality function that got copied over.
173 if (OldFunc->hasPersonalityFn())
174 NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
175 FuncGlobalRefFlags, TypeMapper,
176 Materializer));
177
178 if (OldFunc->hasPrefixData()) {
179 NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
180 FuncGlobalRefFlags, TypeMapper,
181 Materializer));
182 }
183
184 if (OldFunc->hasPrologueData()) {
185 NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
186 FuncGlobalRefFlags, TypeMapper,
187 Materializer));
188 }
189
190 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
191 AttributeList OldAttrs = OldFunc->getAttributes();
192
193 // Clone any argument attributes that are present in the VMap.
194 for (const Argument &OldArg : OldFunc->args()) {
195 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
196 // Remap the parameter indices.
197 NewArgAttrs[NewArg->getArgNo()] =
198 OldAttrs.getParamAttrs(OldArg.getArgNo());
199 }
200 }
201
202 NewFunc->setAttributes(
203 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
204 OldAttrs.getRetAttrs(), NewArgAttrs));
205}
206
208 ValueToValueMapTy &VMap,
209 RemapFlags RemapFlag,
210 ValueMapTypeRemapper *TypeMapper,
211 ValueMaterializer *Materializer,
212 const MetadataPredicate *IdentityMD) {
214 OldFunc.getAllMetadata(MDs);
215 for (const auto &[Kind, MD] : MDs) {
216 NewFunc.addMetadata(Kind, *MapMetadata(MD, VMap, RemapFlag, TypeMapper,
217 Materializer, IdentityMD));
218 }
219}
220
221void llvm::CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc,
222 ValueToValueMapTy &VMap, RemapFlags RemapFlag,
224 const char *NameSuffix,
225 ClonedCodeInfo *CodeInfo,
226 ValueMapTypeRemapper *TypeMapper,
227 ValueMaterializer *Materializer,
228 const MetadataPredicate *IdentityMD) {
229 if (OldFunc.isDeclaration())
230 return;
231
232 // Loop over all of the basic blocks in the function, cloning them as
233 // appropriate. Note that we save BE this way in order to handle cloning of
234 // recursive functions into themselves.
235 for (const BasicBlock &BB : OldFunc) {
236 // Create a new basic block and copy instructions into it!
237 BasicBlock *CBB =
238 CloneBasicBlock(&BB, VMap, NameSuffix, &NewFunc, CodeInfo);
239
240 // Add basic block mapping.
241 VMap[&BB] = CBB;
242
243 // It is only legal to clone a function if a block address within that
244 // function is never referenced outside of the function. Given that, we
245 // want to map block addresses from the old function to block addresses in
246 // the clone. (This is different from the generic ValueMapper
247 // implementation, which generates an invalid blockaddress when
248 // cloning a function.)
249 if (BB.hasAddressTaken()) {
250 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(&OldFunc),
251 const_cast<BasicBlock *>(&BB));
252 VMap[OldBBAddr] = BlockAddress::get(&NewFunc, CBB);
253 }
254
255 // Note return instructions for the caller.
257 Returns.push_back(RI);
258 }
259
260 // Loop over all of the instructions in the new function, fixing up operand
261 // references as we go. This uses VMap to do all the hard work.
263 BB = cast<BasicBlock>(VMap[&OldFunc.front()])->getIterator(),
264 BE = NewFunc.end();
265 BB != BE; ++BB)
266 // Loop over all instructions, fixing each one as we find it, and any
267 // attached debug-info records.
268 for (Instruction &II : *BB) {
269 RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer,
270 IdentityMD);
271 RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,
272 RemapFlag, TypeMapper, Materializer, IdentityMD);
273 }
274}
275
276// Clone OldFunc into NewFunc, transforming the old arguments into references to
277// VMap values.
278void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
279 ValueToValueMapTy &VMap,
282 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
283 ValueMapTypeRemapper *TypeMapper,
284 ValueMaterializer *Materializer) {
285 assert(NameSuffix && "NameSuffix cannot be null!");
286
287#ifndef NDEBUG
288 for (const Argument &I : OldFunc->args())
289 assert(VMap.count(&I) && "No mapping from source argument specified!");
290#endif
291
292 bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
293
294 CloneFunctionAttributesInto(NewFunc, OldFunc, VMap, ModuleLevelChanges,
295 TypeMapper, Materializer);
296
297 // Everything else beyond this point deals with function instructions,
298 // so if we are dealing with a function declaration, we're done.
299 if (OldFunc->isDeclaration())
300 return;
301
303 assert((NewFunc->getParent() == nullptr ||
304 NewFunc->getParent() == OldFunc->getParent()) &&
305 "Expected NewFunc to have the same parent, or no parent");
306 } else {
307 assert((NewFunc->getParent() == nullptr ||
308 NewFunc->getParent() != OldFunc->getParent()) &&
309 "Expected NewFunc to have different parents, or no parent");
310
312 assert(NewFunc->getParent() &&
313 "Need parent of new function to maintain debug info invariants");
314 }
315 }
316
317 MetadataPredicate IdentityMD = createIdentityMDPredicate(*OldFunc, Changes);
318
319 // Cloning is always a Module level operation, since Metadata needs to be
320 // cloned.
321 const RemapFlags RemapFlag = RF_None;
322
323 CloneFunctionMetadataInto(*NewFunc, *OldFunc, VMap, RemapFlag, TypeMapper,
324 Materializer, &IdentityMD);
325
326 CloneFunctionBodyInto(*NewFunc, *OldFunc, VMap, RemapFlag, Returns,
327 NameSuffix, CodeInfo, TypeMapper, Materializer,
328 &IdentityMD);
329
330 // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
331 // same module, the compile unit will already be listed (or not). When
332 // cloning a module, CloneModule() will handle creating the named metadata.
334 return;
335
336 // Update !llvm.dbg.cu with compile units added to the new module if this
337 // function is being cloned in isolation.
338 //
339 // FIXME: This is making global / module-level changes, which doesn't seem
340 // like the right encapsulation Consider dropping the requirement to update
341 // !llvm.dbg.cu (either obsoleting the node, or restricting it to
342 // non-discardable compile units) instead of discovering compile units by
343 // visiting the metadata attached to global values, which would allow this
344 // code to be deleted. Alternatively, perhaps give responsibility for this
345 // update to CloneFunctionInto's callers.
346 Module *NewModule = NewFunc->getParent();
347 NamedMDNode *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
348 // Avoid multiple insertions of the same DICompileUnit to NMD.
350
351 // Collect and clone all the compile units referenced from the instructions in
352 // the function (e.g. as instructions' scope).
353 DebugInfoFinder DIFinder;
354 collectDebugInfoFromInstructions(*OldFunc, DIFinder);
355 for (DICompileUnit *Unit : DIFinder.compile_units()) {
356 MDNode *MappedUnit =
357 MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
358 if (Visited.insert(MappedUnit).second)
359 NMD->addOperand(MappedUnit);
360 }
361}
362
363/// Return a copy of the specified function and add it to that function's
364/// module. Also, any references specified in the VMap are changed to refer to
365/// their mapped value instead of the original one. If any of the arguments to
366/// the function are in the VMap, the arguments are deleted from the resultant
367/// function. The VMap is updated to include mappings from all of the
368/// instructions and basicblocks in the function from their old to new values.
369///
371 ClonedCodeInfo *CodeInfo) {
372 std::vector<Type *> ArgTypes;
373
374 // The user might be deleting arguments to the function by specifying them in
375 // the VMap. If so, we need to not add the arguments to the arg ty vector
376 //
377 for (const Argument &I : F->args())
378 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
379 ArgTypes.push_back(I.getType());
380
381 // Create a new function type...
382 FunctionType *FTy =
383 FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
384 F->getFunctionType()->isVarArg());
385
386 // Create the new function...
387 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
388 F->getName(), F->getParent());
389
390 // Loop over the arguments, copying the names of the mapped arguments over...
391 Function::arg_iterator DestI = NewF->arg_begin();
392 for (const Argument &I : F->args())
393 if (VMap.count(&I) == 0) { // Is this argument preserved?
394 DestI->setName(I.getName()); // Copy the name over...
395 VMap[&I] = &*DestI++; // Add mapping to VMap
396 }
397
398 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
400 Returns, "", CodeInfo);
401
402 return NewF;
403}
404
405namespace {
406/// This is a private class used to implement CloneAndPruneFunctionInto.
407struct PruningFunctionCloner {
408 Function *NewFunc;
409 const Function *OldFunc;
410 ValueToValueMapTy &VMap;
411 bool ModuleLevelChanges;
412 const char *NameSuffix;
413 ClonedCodeInfo *CodeInfo;
414 bool HostFuncIsStrictFP;
415
416 Instruction *cloneInstruction(BasicBlock::const_iterator II);
417
418public:
419 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
420 ValueToValueMapTy &valueMap, bool moduleLevelChanges,
421 const char *nameSuffix, ClonedCodeInfo *codeInfo)
422 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
423 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
424 CodeInfo(codeInfo) {
425 HostFuncIsStrictFP =
426 newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
427 }
428
429 /// The specified block is found to be reachable, clone it and
430 /// anything that it can reach.
431 void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
432 std::vector<const BasicBlock *> &ToClone);
433};
434} // namespace
435
437PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
438 const Instruction &OldInst = *II;
439 Instruction *NewInst = nullptr;
440 if (HostFuncIsStrictFP) {
442 if (CIID != Intrinsic::not_intrinsic) {
443 // Instead of cloning the instruction, a call to constrained intrinsic
444 // should be created.
445 // Assume the first arguments of constrained intrinsics are the same as
446 // the operands of original instruction.
447
448 // Determine overloaded types of the intrinsic.
451 getIntrinsicInfoTableEntries(CIID, Descriptor);
452 for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
453 Intrinsic::IITDescriptor Operand = Descriptor[I];
454 switch (Operand.Kind) {
456 if (Operand.getArgumentKind() !=
457 Intrinsic::IITDescriptor::AK_MatchType) {
458 if (I == 0)
459 TParams.push_back(OldInst.getType());
460 else
461 TParams.push_back(OldInst.getOperand(I - 1)->getType());
462 }
463 break;
465 ++I;
466 break;
467 default:
468 break;
469 }
470 }
471
472 // Create intrinsic call.
473 LLVMContext &Ctx = NewFunc->getContext();
475 CIID, TParams);
477 unsigned NumOperands = OldInst.getNumOperands();
478 if (isa<CallInst>(OldInst))
479 --NumOperands;
480 for (unsigned I = 0; I < NumOperands; ++I) {
481 Value *Op = OldInst.getOperand(I);
482 Args.push_back(Op);
483 }
484 if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
485 FCmpInst::Predicate Pred = CmpI->getPredicate();
486 StringRef PredName = FCmpInst::getPredicateName(Pred);
487 Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
488 }
489
490 // The last arguments of a constrained intrinsic are metadata that
491 // represent rounding mode (absents in some intrinsics) and exception
492 // behavior. The inlined function uses default settings.
494 Args.push_back(
495 MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
496 Args.push_back(
497 MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
498
499 NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
500 }
501 }
502 if (!NewInst)
503 NewInst = II->clone();
504 return NewInst;
505}
506
507/// The specified block is found to be reachable, clone it and
508/// anything that it can reach.
509void PruningFunctionCloner::CloneBlock(
510 const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
511 std::vector<const BasicBlock *> &ToClone) {
512 WeakTrackingVH &BBEntry = VMap[BB];
513
514 // Have we already cloned this block?
515 if (BBEntry)
516 return;
517
518 // Nope, clone it now.
519 BasicBlock *NewBB;
520 Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
521 BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
522
523 // It is only legal to clone a function if a block address within that
524 // function is never referenced outside of the function. Given that, we
525 // want to map block addresses from the old function to block addresses in
526 // the clone. (This is different from the generic ValueMapper
527 // implementation, which generates an invalid blockaddress when
528 // cloning a function.)
529 //
530 // Note that we don't need to fix the mapping for unreachable blocks;
531 // the default mapping there is safe.
532 if (BB->hasAddressTaken()) {
533 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
534 const_cast<BasicBlock *>(BB));
535 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
536 }
537
538 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
539 bool hasMemProfMetadata = false;
540
541 // Keep a cursor pointing at the last place we cloned debug-info records from.
542 BasicBlock::const_iterator DbgCursor = StartingInst;
543 auto CloneDbgRecordsToHere =
544 [&DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
545 // Clone debug-info records onto this instruction. Iterate through any
546 // source-instructions we've cloned and then subsequently optimised
547 // away, so that their debug-info doesn't go missing.
548 for (; DbgCursor != II; ++DbgCursor)
549 NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
550 NewInst->cloneDebugInfoFrom(&*II);
551 DbgCursor = std::next(II);
552 };
553
554 // Loop over all instructions, and copy them over, DCE'ing as we go. This
555 // loop doesn't include the terminator.
556 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
557 ++II) {
558
559 // Don't clone fake_use as it may suppress many optimizations
560 // due to inlining, especially SROA.
561 if (auto *IntrInst = dyn_cast<IntrinsicInst>(II))
562 if (IntrInst->getIntrinsicID() == Intrinsic::fake_use)
563 continue;
564
565 Instruction *NewInst = cloneInstruction(II);
566 NewInst->insertInto(NewBB, NewBB->end());
567
568 if (HostFuncIsStrictFP) {
569 // All function calls in the inlined function must get 'strictfp'
570 // attribute to prevent undesirable optimizations.
571 if (auto *Call = dyn_cast<CallInst>(NewInst))
572 Call->addFnAttr(Attribute::StrictFP);
573 }
574
575 // Eagerly remap operands to the newly cloned instruction, except for PHI
576 // nodes for which we defer processing until we update the CFG.
577 if (!isa<PHINode>(NewInst)) {
578 RemapInstruction(NewInst, VMap,
579 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
580
581 // Eagerly constant fold the newly cloned instruction. If successful, add
582 // a mapping to the new value. Non-constant operands may be incomplete at
583 // this stage, thus instruction simplification is performed after
584 // processing phi-nodes.
586 NewInst, BB->getDataLayout())) {
587 if (isInstructionTriviallyDead(NewInst)) {
588 VMap[&*II] = V;
589 NewInst->eraseFromParent();
590 continue;
591 }
592 }
593 }
594
595 if (II->hasName())
596 NewInst->setName(II->getName() + NameSuffix);
597 VMap[&*II] = NewInst; // Add instruction map to value.
598 if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
599 hasCalls = true;
600 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
601 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_callsite);
602 }
603
604 CloneDbgRecordsToHere(NewInst, II);
605
606 if (CodeInfo) {
607 CodeInfo->OrigVMap[&*II] = NewInst;
608 if (auto *CB = dyn_cast<CallBase>(&*II))
609 if (CB->hasOperandBundles())
610 CodeInfo->OperandBundleCallSites.push_back(NewInst);
611 }
612
613 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
614 if (isa<ConstantInt>(AI->getArraySize()))
615 hasStaticAllocas = true;
616 else
617 hasDynamicAllocas = true;
618 }
619 }
620
621 // Finally, clone over the terminator.
622 const Instruction *OldTI = BB->getTerminator();
623 bool TerminatorDone = false;
624 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
625 if (BI->isConditional()) {
626 // If the condition was a known constant in the callee...
627 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
628 // Or is a known constant in the caller...
629 if (!Cond) {
630 Value *V = VMap.lookup(BI->getCondition());
632 }
633
634 // Constant fold to uncond branch!
635 if (Cond) {
636 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
637 auto *NewBI = BranchInst::Create(Dest, NewBB);
638 NewBI->setDebugLoc(BI->getDebugLoc());
639 VMap[OldTI] = NewBI;
640 ToClone.push_back(Dest);
641 TerminatorDone = true;
642 }
643 }
644 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
645 // If switching on a value known constant in the caller.
646 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
647 if (!Cond) { // Or known constant after constant prop in the callee...
648 Value *V = VMap.lookup(SI->getCondition());
650 }
651 if (Cond) { // Constant fold to uncond branch!
652 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
653 BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
654 auto *NewBI = BranchInst::Create(Dest, NewBB);
655 NewBI->setDebugLoc(SI->getDebugLoc());
656 VMap[OldTI] = NewBI;
657 ToClone.push_back(Dest);
658 TerminatorDone = true;
659 }
660 }
661
662 if (!TerminatorDone) {
663 Instruction *NewInst = OldTI->clone();
664 if (OldTI->hasName())
665 NewInst->setName(OldTI->getName() + NameSuffix);
666 NewInst->insertInto(NewBB, NewBB->end());
667
668 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
669
670 VMap[OldTI] = NewInst; // Add instruction map to value.
671
672 if (CodeInfo) {
673 CodeInfo->OrigVMap[OldTI] = NewInst;
674 if (auto *CB = dyn_cast<CallBase>(OldTI))
675 if (CB->hasOperandBundles())
676 CodeInfo->OperandBundleCallSites.push_back(NewInst);
677 }
678
679 // Recursively clone any reachable successor blocks.
680 append_range(ToClone, successors(BB->getTerminator()));
681 } else {
682 // If we didn't create a new terminator, clone DbgVariableRecords from the
683 // old terminator onto the new terminator.
684 Instruction *NewInst = NewBB->getTerminator();
685 assert(NewInst);
686
687 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
688 }
689
690 if (CodeInfo) {
691 CodeInfo->ContainsCalls |= hasCalls;
692 CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
693 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
694 CodeInfo->ContainsDynamicAllocas |=
695 hasStaticAllocas && BB != &BB->getParent()->front();
696 }
697}
698
699/// This works like CloneAndPruneFunctionInto, except that it does not clone the
700/// entire function. Instead it starts at an instruction provided by the caller
701/// and copies (and prunes) only the code reachable from that instruction.
703 const Instruction *StartingInst,
704 ValueToValueMapTy &VMap,
705 bool ModuleLevelChanges,
707 const char *NameSuffix,
708 ClonedCodeInfo *CodeInfo) {
709 assert(NameSuffix && "NameSuffix cannot be null!");
710
711 ValueMapTypeRemapper *TypeMapper = nullptr;
712 ValueMaterializer *Materializer = nullptr;
713
714#ifndef NDEBUG
715 // If the cloning starts at the beginning of the function, verify that
716 // the function arguments are mapped.
717 if (!StartingInst)
718 for (const Argument &II : OldFunc->args())
719 assert(VMap.count(&II) && "No mapping from source argument specified!");
720#endif
721
722 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
723 NameSuffix, CodeInfo);
724 const BasicBlock *StartingBB;
725 if (StartingInst)
726 StartingBB = StartingInst->getParent();
727 else {
728 StartingBB = &OldFunc->getEntryBlock();
729 StartingInst = &StartingBB->front();
730 }
731
732 // Clone the entry block, and anything recursively reachable from it.
733 std::vector<const BasicBlock *> CloneWorklist;
734 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
735 while (!CloneWorklist.empty()) {
736 const BasicBlock *BB = CloneWorklist.back();
737 CloneWorklist.pop_back();
738 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
739 }
740
741 // Loop over all of the basic blocks in the old function. If the block was
742 // reachable, we have cloned it and the old block is now in the value map:
743 // insert it into the new function in the right order. If not, ignore it.
744 //
745 // Defer PHI resolution until rest of function is resolved.
747 for (const BasicBlock &BI : *OldFunc) {
748 Value *V = VMap.lookup(&BI);
750 if (!NewBB)
751 continue; // Dead block.
752
753 // Move the new block to preserve the order in the original function.
754 NewBB->moveBefore(NewFunc->end());
755
756 // Handle PHI nodes specially, as we have to remove references to dead
757 // blocks.
758 for (const PHINode &PN : BI.phis()) {
759 // PHI nodes may have been remapped to non-PHI nodes by the caller or
760 // during the cloning process.
761 if (isa<PHINode>(VMap[&PN]))
762 PHIToResolve.push_back(&PN);
763 else
764 break;
765 }
766
767 // Finally, remap the terminator instructions, as those can't be remapped
768 // until all BBs are mapped.
769 RemapInstruction(NewBB->getTerminator(), VMap,
770 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
771 TypeMapper, Materializer);
772 }
773
774 // Defer PHI resolution until rest of function is resolved, PHI resolution
775 // requires the CFG to be up-to-date.
776 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
777 const PHINode *OPN = PHIToResolve[phino];
778 unsigned NumPreds = OPN->getNumIncomingValues();
779 const BasicBlock *OldBB = OPN->getParent();
780 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
781
782 // Map operands for blocks that are live and remove operands for blocks
783 // that are dead.
784 for (; phino != PHIToResolve.size() &&
785 PHIToResolve[phino]->getParent() == OldBB;
786 ++phino) {
787 OPN = PHIToResolve[phino];
788 PHINode *PN = cast<PHINode>(VMap[OPN]);
789 for (int64_t pred = NumPreds - 1; pred >= 0; --pred) {
790 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
791 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
792 Value *InVal =
793 MapValue(PN->getIncomingValue(pred), VMap,
794 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
795 assert(InVal && "Unknown input value?");
796 PN->setIncomingValue(pred, InVal);
797 PN->setIncomingBlock(pred, MappedBlock);
798 continue;
799 }
800 PN->removeIncomingValue(pred, false);
801 }
802 }
803
804 // The loop above has removed PHI entries for those blocks that are dead
805 // and has updated others. However, if a block is live (i.e. copied over)
806 // but its terminator has been changed to not go to this block, then our
807 // phi nodes will have invalid entries. Update the PHI nodes in this
808 // case.
809 PHINode *PN = cast<PHINode>(NewBB->begin());
810 NumPreds = pred_size(NewBB);
811 if (NumPreds != PN->getNumIncomingValues()) {
812 assert(NumPreds < PN->getNumIncomingValues());
813 // Count how many times each predecessor comes to this block.
814 std::map<BasicBlock *, unsigned> PredCount;
815 for (BasicBlock *Pred : predecessors(NewBB))
816 --PredCount[Pred];
817
818 // Figure out how many entries to remove from each PHI.
819 for (BasicBlock *Pred : PN->blocks())
820 ++PredCount[Pred];
821
822 // At this point, the excess predecessor entries are positive in the
823 // map. Loop over all of the PHIs and remove excess predecessor
824 // entries.
825 BasicBlock::iterator I = NewBB->begin();
826 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
827 for (const auto &[Pred, Count] : PredCount) {
828 for ([[maybe_unused]] unsigned _ : llvm::seq<unsigned>(Count))
829 PN->removeIncomingValue(Pred, false);
830 }
831 }
832 }
833
834 // If the loops above have made these phi nodes have 0 or 1 operand,
835 // replace them with poison or the input value. We must do this for
836 // correctness, because 0-operand phis are not valid.
837 PN = cast<PHINode>(NewBB->begin());
838 if (PN->getNumIncomingValues() == 0) {
839 BasicBlock::iterator I = NewBB->begin();
840 BasicBlock::const_iterator OldI = OldBB->begin();
841 while ((PN = dyn_cast<PHINode>(I++))) {
842 Value *NV = PoisonValue::get(PN->getType());
843 PN->replaceAllUsesWith(NV);
844 assert(VMap[&*OldI] == PN && "VMap mismatch");
845 VMap[&*OldI] = NV;
846 PN->eraseFromParent();
847 ++OldI;
848 }
849 }
850 }
851
852 // Drop all incompatible return attributes that cannot be applied to NewFunc
853 // during cloning, so as to allow instruction simplification to reason on the
854 // old state of the function. The original attributes are restored later.
855 AttributeList Attrs = NewFunc->getAttributes();
856 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
857 OldFunc->getReturnType(), Attrs.getRetAttrs());
858 NewFunc->removeRetAttrs(IncompatibleAttrs);
859
860 // As phi-nodes have been now remapped, allow incremental simplification of
861 // newly-cloned instructions.
862 const DataLayout &DL = NewFunc->getDataLayout();
863 for (const BasicBlock &BB : *OldFunc) {
864 for (const Instruction &I : BB) {
865 auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
866 if (!NewI)
867 continue;
868
869 if (Value *V = simplifyInstruction(NewI, DL)) {
870 NewI->replaceAllUsesWith(V);
871
872 if (isInstructionTriviallyDead(NewI)) {
873 NewI->eraseFromParent();
874 } else {
875 // Did not erase it? Restore the new instruction into VMap previously
876 // dropped by `ValueIsRAUWd`.
877 VMap[&I] = NewI;
878 }
879 }
880 }
881 }
882
883 // Restore attributes.
884 NewFunc->setAttributes(Attrs);
885
886 // Remap debug records operands now that all values have been mapped.
887 // Doing this now (late) preserves use-before-defs in debug records. If
888 // we didn't do this, ValueAsMetadata(use-before-def) operands would be
889 // replaced by empty metadata. This would signal later cleanup passes to
890 // remove the debug records, potentially causing incorrect locations.
891 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
892 for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
893 for (Instruction &I : BB) {
894 RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,
895 ModuleLevelChanges ? RF_None
897 TypeMapper, Materializer);
898 }
899 }
900
901 // Simplify conditional branches and switches with a constant operand. We try
902 // to prune these out when cloning, but if the simplification required
903 // looking through PHI nodes, those are only available after forming the full
904 // basic block. That may leave some here, and we still want to prune the dead
905 // code as early as possible.
906 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
908
909 // Some blocks may have become unreachable as a result. Find and delete them.
910 {
911 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
913 Worklist.push_back(&*Begin);
914 while (!Worklist.empty()) {
915 BasicBlock *BB = Worklist.pop_back_val();
916 if (ReachableBlocks.insert(BB).second)
917 append_range(Worklist, successors(BB));
918 }
919
920 SmallVector<BasicBlock *, 16> UnreachableBlocks;
921 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
922 if (!ReachableBlocks.contains(&BB))
923 UnreachableBlocks.push_back(&BB);
924 DeleteDeadBlocks(UnreachableBlocks);
925 }
926
927 // Now that the inlined function body has been fully constructed, go through
928 // and zap unconditional fall-through branches. This happens all the time when
929 // specializing code: code specialization turns conditional branches into
930 // uncond branches, and this code folds them.
931 Function::iterator I = Begin;
932 while (I != NewFunc->end()) {
933 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
934 if (!BI || BI->isConditional()) {
935 ++I;
936 continue;
937 }
938
939 BasicBlock *Dest = BI->getSuccessor(0);
940 if (!Dest->getSinglePredecessor() || Dest->hasAddressTaken()) {
941 ++I;
942 continue;
943 }
944
945 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
946 // above should have zapped all of them..
947 assert(!isa<PHINode>(Dest->begin()));
948
949 // We know all single-entry PHI nodes in the inlined function have been
950 // removed, so we just need to splice the blocks.
951 BI->eraseFromParent();
952
953 // Make all PHI nodes that referred to Dest now refer to I as their source.
954 Dest->replaceAllUsesWith(&*I);
955
956 // Move all the instructions in the succ to the pred.
957 I->splice(I->end(), Dest);
958
959 // Remove the dest block.
960 Dest->eraseFromParent();
961
962 // Do not increment I, iteratively merge all things this block branches to.
963 }
964
965 // Make a final pass over the basic blocks from the old function to gather
966 // any return instructions which survived folding. We have to do this here
967 // because we can iteratively remove and merge returns above.
968 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
969 E = NewFunc->end();
970 I != E; ++I)
971 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
972 Returns.push_back(RI);
973}
974
975/// This works exactly like CloneFunctionInto,
976/// except that it does some simple constant prop and DCE on the fly. The
977/// effect of this is to copy significantly less code in cases where (for
978/// example) a function call with constant arguments is inlined, and those
979/// constant arguments cause a significant amount of code in the callee to be
980/// dead. Since this doesn't produce an exact copy of the input, it can't be
981/// used for things like CloneFunction or CloneModule.
983 Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
984 bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
985 const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
986 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
987 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
988}
989
990/// Remaps instructions in \p Blocks using the mapping in \p VMap.
992 ValueToValueMapTy &VMap) {
993 // Rewrite the code to refer to itself.
994 for (BasicBlock *BB : Blocks) {
995 for (Instruction &Inst : *BB) {
996 RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,
998 RemapInstruction(&Inst, VMap,
1000 }
1001 }
1002}
1003
1004/// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
1005/// Blocks.
1006///
1007/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
1008/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
1010 Loop *OrigLoop, ValueToValueMapTy &VMap,
1011 const Twine &NameSuffix, LoopInfo *LI,
1012 DominatorTree *DT,
1014 Function *F = OrigLoop->getHeader()->getParent();
1015 Loop *ParentLoop = OrigLoop->getParentLoop();
1017
1018 Loop *NewLoop = LI->AllocateLoop();
1019 LMap[OrigLoop] = NewLoop;
1020 if (ParentLoop)
1021 ParentLoop->addChildLoop(NewLoop);
1022 else
1023 LI->addTopLevelLoop(NewLoop);
1024
1025 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
1026 assert(OrigPH && "No preheader");
1027 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
1028 // To rename the loop PHIs.
1029 VMap[OrigPH] = NewPH;
1030 Blocks.push_back(NewPH);
1031
1032 // Update LoopInfo.
1033 if (ParentLoop)
1034 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
1035
1036 // Update DominatorTree.
1037 DT->addNewBlock(NewPH, LoopDomBB);
1038
1039 for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
1040 Loop *&NewLoop = LMap[CurLoop];
1041 if (!NewLoop) {
1042 NewLoop = LI->AllocateLoop();
1043
1044 // Establish the parent/child relationship.
1045 Loop *OrigParent = CurLoop->getParentLoop();
1046 assert(OrigParent && "Could not find the original parent loop");
1047 Loop *NewParentLoop = LMap[OrigParent];
1048 assert(NewParentLoop && "Could not find the new parent loop");
1049
1050 NewParentLoop->addChildLoop(NewLoop);
1051 }
1052 }
1053
1054 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1055 Loop *CurLoop = LI->getLoopFor(BB);
1056 Loop *&NewLoop = LMap[CurLoop];
1057 assert(NewLoop && "Expecting new loop to be allocated");
1058
1059 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
1060 VMap[BB] = NewBB;
1061
1062 // Update LoopInfo.
1063 NewLoop->addBasicBlockToLoop(NewBB, *LI);
1064
1065 // Add DominatorTree node. After seeing all blocks, update to correct
1066 // IDom.
1067 DT->addNewBlock(NewBB, NewPH);
1068
1069 Blocks.push_back(NewBB);
1070 }
1071
1072 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1073 // Update loop headers.
1074 Loop *CurLoop = LI->getLoopFor(BB);
1075 if (BB == CurLoop->getHeader())
1076 LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1077
1078 // Update DominatorTree.
1079 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
1081 cast<BasicBlock>(VMap[IDomBB]));
1082 }
1083
1084 // Move them physically from the end of the block list.
1085 F->splice(Before->getIterator(), F, NewPH->getIterator());
1086 F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1087 F->end());
1088
1089 return NewLoop;
1090}
1091
1092/// Duplicate non-Phi instructions from the beginning of block up to
1093/// StopAt instruction into a split block between BB and its predecessor.
1095 BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1096 ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1097
1098 assert(count(successors(PredBB), BB) == 1 &&
1099 "There must be a single edge between PredBB and BB!");
1100 // We are going to have to map operands from the original BB block to the new
1101 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1102 // account for entry from PredBB.
1103 BasicBlock::iterator BI = BB->begin();
1104 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1105 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1106
1107 BasicBlock *NewBB = SplitEdge(PredBB, BB);
1108 NewBB->setName(PredBB->getName() + ".split");
1109 Instruction *NewTerm = NewBB->getTerminator();
1110
1111 // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1112 // in the update set here.
1113 DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1114 {DominatorTree::Insert, PredBB, NewBB},
1115 {DominatorTree::Insert, NewBB, BB}});
1116
1117 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1118 // mapping and using it to remap operands in the cloned instructions.
1119 // Stop once we see the terminator too. This covers the case where BB's
1120 // terminator gets replaced and StopAt == BB's terminator.
1121 for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
1122 Instruction *New = BI->clone();
1123 New->setName(BI->getName());
1124 New->insertBefore(NewTerm->getIterator());
1125 New->cloneDebugInfoFrom(&*BI);
1126 ValueMapping[&*BI] = New;
1127
1128 // Remap operands to patch up intra-block references.
1129 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1130 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1131 auto I = ValueMapping.find(Inst);
1132 if (I != ValueMapping.end())
1133 New->setOperand(i, I->second);
1134 }
1135
1136 // Remap debug variable operands.
1137 remapDebugVariable(ValueMapping, New);
1138 }
1139
1140 return NewBB;
1141}
1142
1144 DenseMap<MDNode *, MDNode *> &ClonedScopes,
1145 StringRef Ext, LLVMContext &Context) {
1146 MDBuilder MDB(Context);
1147
1148 for (MDNode *ScopeList : NoAliasDeclScopes) {
1149 for (const MDOperand &MDOp : ScopeList->operands()) {
1150 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1151 AliasScopeNode SNANode(MD);
1152
1153 std::string Name;
1154 auto ScopeName = SNANode.getName();
1155 if (!ScopeName.empty())
1156 Name = (Twine(ScopeName) + ":" + Ext).str();
1157 else
1158 Name = std::string(Ext);
1159
1160 MDNode *NewScope = MDB.createAnonymousAliasScope(
1161 const_cast<MDNode *>(SNANode.getDomain()), Name);
1162 ClonedScopes.insert(std::make_pair(MD, NewScope));
1163 }
1164 }
1165 }
1166}
1167
1169 const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1170 LLVMContext &Context) {
1171 auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1172 bool NeedsReplacement = false;
1173 SmallVector<Metadata *, 8> NewScopeList;
1174 for (const MDOperand &MDOp : ScopeList->operands()) {
1175 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1176 if (auto *NewMD = ClonedScopes.lookup(MD)) {
1177 NewScopeList.push_back(NewMD);
1178 NeedsReplacement = true;
1179 continue;
1180 }
1181 NewScopeList.push_back(MD);
1182 }
1183 }
1184 if (NeedsReplacement)
1185 return MDNode::get(Context, NewScopeList);
1186 return nullptr;
1187 };
1188
1189 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1190 if (MDNode *NewScopeList = CloneScopeList(Decl->getScopeList()))
1191 Decl->setScopeList(NewScopeList);
1192
1193 auto replaceWhenNeeded = [&](unsigned MD_ID) {
1194 if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1195 if (MDNode *NewScopeList = CloneScopeList(CSNoAlias))
1196 I->setMetadata(MD_ID, NewScopeList);
1197 };
1198 replaceWhenNeeded(LLVMContext::MD_noalias);
1199 replaceWhenNeeded(LLVMContext::MD_alias_scope);
1200}
1201
1203 ArrayRef<BasicBlock *> NewBlocks,
1204 LLVMContext &Context, StringRef Ext) {
1205 if (NoAliasDeclScopes.empty())
1206 return;
1207
1208 DenseMap<MDNode *, MDNode *> ClonedScopes;
1209 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1210 << NoAliasDeclScopes.size() << " node(s)\n");
1211
1212 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1213 // Identify instructions using metadata that needs adaptation
1214 for (BasicBlock *NewBlock : NewBlocks)
1215 for (Instruction &I : *NewBlock)
1216 adaptNoAliasScopes(&I, ClonedScopes, Context);
1217}
1218
1220 Instruction *IStart, Instruction *IEnd,
1221 LLVMContext &Context, StringRef Ext) {
1222 if (NoAliasDeclScopes.empty())
1223 return;
1224
1225 DenseMap<MDNode *, MDNode *> ClonedScopes;
1226 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1227 << NoAliasDeclScopes.size() << " node(s)\n");
1228
1229 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1230 // Identify instructions using metadata that needs adaptation
1231 assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1232 auto ItStart = IStart->getIterator();
1233 auto ItEnd = IEnd->getIterator();
1234 ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1235 for (auto &I : llvm::make_range(ItStart, ItEnd))
1236 adaptNoAliasScopes(&I, ClonedScopes, Context);
1237}
1238
1240 ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1241 for (BasicBlock *BB : BBs)
1242 for (Instruction &I : *BB)
1243 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1244 NoAliasDeclScopes.push_back(Decl->getScopeList());
1245}
1246
1249 SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1250 for (Instruction &I : make_range(Start, End))
1251 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1252 NoAliasDeclScopes.push_back(Decl->getScopeList());
1253}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static MetadataPredicate createIdentityMDPredicate(const Function &F, CloneFunctionChangeType Changes)
static void collectDebugInfoFromInstructions(const Function &F, DebugInfoFinder &DIFinder)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define _
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition Metadata.h:1593
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1604
StringRef getName() const
Definition Metadata.h:1609
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:690
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:482
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:386
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is an important base class in LLVM.
Definition Constant.h:43
Subprogram description. Uses SubclassData1.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Utility to find all debug info in a module.
Definition DebugInfo.h:105
LLVM_ABI void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
iterator_range< compile_unit_iterator > compile_units() const
Definition DebugInfo.h:145
A debug info location.
Definition DebugLoc.h:123
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
const BasicBlock & getEntryBlock() const
Definition Function.h:807
BasicBlockListType::iterator iterator
Definition Function.h:69
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:363
const BasicBlock & front() const
Definition Function.h:858
iterator_range< arg_iterator > args()
Definition Function.h:890
bool hasPrefixData() const
Check whether this function has prefix data.
Definition Function.h:912
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:903
Constant * getPrologueData() const
Get the prologue data associated with this function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setPersonalityFn(Constant *Fn)
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:352
arg_iterator arg_begin()
Definition Function.h:866
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
size_t arg_size() const
Definition Function.h:899
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:708
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
Constant * getPrefixData() const
Get the prefix data associated with this function.
iterator end()
Definition Function.h:853
bool hasPrologueData() const
Check whether this function has prologue data.
Definition Function.h:921
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:859
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:328
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:181
Metadata node.
Definition Metadata.h:1078
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
Tracking metadata reference owned by Metadata.
Definition Metadata.h:900
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:303
A tuple of MDNodes.
Definition Metadata.h:1757
iterator_range< op_iterator > operands()
Definition Metadata.h:1853
LLVM_ABI void addOperand(MDNode *M)
iterator_range< const_block_iterator > blocks() const
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Return a value (possibly void), from a function.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
CaseHandleImpl< const SwitchInst, const ConstantInt, const BasicBlock > ConstCaseHandle
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Value * getOperand(unsigned i) const
Definition User.h:232
unsigned getNumOperands() const
Definition User.h:254
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition ValueMapper.h:45
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition ValueMap.h:156
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition ValueMap.h:123
This is a class that can be implemented by clients to materialize Values on demand.
Definition ValueMapper.h:58
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
bool hasName() const
Definition Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI void CloneFunctionAttributesInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc's attributes into NewFunc, transforming values based on the mappings in VMap.
std::function< bool(const Metadata *)> MetadataPredicate
Definition ValueMapper.h:41
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:134
static cl::opt< unsigned long > StopAt("sbvec-stop-at", cl::init(StopAtDisabled), cl::Hidden, cl::desc("Vectorize if the invocation count is < than this. 0 " "disables vectorization."))
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2148
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition Local.cpp:3456
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
LLVM_ABI void CloneFunctionMetadataInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Clone OldFunc's metadata into NewFunc.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
LLVM_ABI Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
RemapFlags
These are flags that the value mapping APIs allow.
Definition ValueMapper.h:74
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_None
Definition ValueMapper.h:75
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI void cloneNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, DenseMap< MDNode *, MDNode * > &ClonedScopes, StringRef Ext, LLVMContext &Context)
Duplicate the specified list of noalias decl scopes.
LLVM_ABI Intrinsic::ID getConstrainedIntrinsicID(const Instruction &Instr)
Returns constrained intrinsic id to represent the given instruction in strictfp function.
Definition FPEnv.cpp:92
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Clone OldFunc's body into NewFunc.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1966
LLVM_ABI void adaptNoAliasScopes(llvm::Instruction *I, const DenseMap< MDNode *, MDNode * > &ClonedScopes, LLVMContext &Context)
Adapt the metadata for the specified instruction according to the provided mapping.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
DWARFExpression::Operation Op
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
CloneFunctionChangeType
Definition Cloning.h:155
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Look up or compute a value in the value map.
auto predecessors(const MachineBasicBlock *BB)
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Lookup or compute a mapping for a piece of metadata.
This struct can be used to capture information about code being cloned, while it is being cloned.
Definition Cloning.h:67
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
Definition Cloning.h:78
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
Definition Cloning.h:69
bool ContainsMemProfMetadata
This is set to true if there is memprof related metadata (memprof or callsite metadata) in the cloned...
Definition Cloning.h:73
DenseMap< const Value *, const Value * > OrigVMap
Like VMap, but maps only unsimplified instructions.
Definition Cloning.h:88
std::vector< WeakTrackingVH > OperandBundleCallSites
All cloned call sites that have operand bundles attached are appended to this vector.
Definition Cloning.h:83
enum llvm::Intrinsic::IITDescriptor::IITDescriptorKind Kind
ArgKind getArgumentKind() const
Definition Intrinsics.h:209