LLVM 23.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 compile units.
92 if (isa<DICompileUnit>(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 // Clone types that are local to subprograms being cloned.
108 // Avoid cloning other types.
109 auto *Type = dyn_cast<DIType>(MD);
110 if (!Type)
111 return false;
112
113 // No need to clone types if subprograms are not cloned.
114 if (SPClonedWithinModule == nullptr)
115 return true;
116
117 // Scopeless types may be derived from local types (e.g. pointers to local
118 // types). They may need cloning.
120 DTy && !DTy->getScope())
121 return false;
122
123 auto *LScope = dyn_cast_or_null<DILocalScope>(Type->getScope());
124 if (!LScope)
125 return true;
126
127 if (ShouldKeep(LScope->getSubprogram()))
128 return true;
129
130 return false;
131 };
132}
133
134/// See comments in Cloning.h.
136 const Twine &NameSuffix, Function *F,
137 ClonedCodeInfo *CodeInfo, bool MapAtoms) {
138 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
139 if (BB->hasName())
140 NewBB->setName(BB->getName() + NameSuffix);
141
142 bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
143
144 // Loop over all instructions, and copy them over.
145 for (const Instruction &I : *BB) {
146 Instruction *NewInst = I.clone();
147 if (I.hasName())
148 NewInst->setName(I.getName() + NameSuffix);
149
150 NewInst->insertBefore(*NewBB, NewBB->end());
151 NewInst->cloneDebugInfoFrom(&I);
152
153 VMap[&I] = NewInst; // Add instruction map to value.
154
155 if (MapAtoms) {
156 if (const DebugLoc &DL = NewInst->getDebugLoc())
157 mapAtomInstance(DL.get(), VMap);
158 }
159
160 if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
161 hasCalls = true;
162 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
163 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_callsite);
164 }
165 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
166 if (!AI->isStaticAlloca()) {
167 hasDynamicAllocas = true;
168 }
169 }
170 }
171
172 if (CodeInfo) {
173 CodeInfo->ContainsCalls |= hasCalls;
174 CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
175 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
176 }
177 return NewBB;
178}
179
181 const Function *OldFunc,
182 ValueToValueMapTy &VMap,
183 bool ModuleLevelChanges,
184 ValueMapTypeRemapper *TypeMapper,
185 ValueMaterializer *Materializer) {
186 // Copy all attributes other than those stored in Function's AttributeList
187 // which holds e.g. parameters and return value attributes.
188 AttributeList NewAttrs = NewFunc->getAttributes();
189 NewFunc->copyAttributesFrom(OldFunc);
190 NewFunc->setAttributes(NewAttrs);
191
192 const RemapFlags FuncGlobalRefFlags =
193 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
194
195 // Fix up the personality function that got copied over.
196 if (OldFunc->hasPersonalityFn())
197 NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
198 FuncGlobalRefFlags, TypeMapper,
199 Materializer));
200
201 if (OldFunc->hasPrefixData()) {
202 NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
203 FuncGlobalRefFlags, TypeMapper,
204 Materializer));
205 }
206
207 if (OldFunc->hasPrologueData()) {
208 NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
209 FuncGlobalRefFlags, TypeMapper,
210 Materializer));
211 }
212
213 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
214 AttributeList OldAttrs = OldFunc->getAttributes();
215
216 // Clone any argument attributes that are present in the VMap.
217 for (const Argument &OldArg : OldFunc->args()) {
218 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
219 // Remap the parameter indices.
220 NewArgAttrs[NewArg->getArgNo()] =
221 OldAttrs.getParamAttrs(OldArg.getArgNo());
222 }
223 }
224
225 NewFunc->setAttributes(
226 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
227 OldAttrs.getRetAttrs(), NewArgAttrs));
228}
229
231 ValueToValueMapTy &VMap,
232 RemapFlags RemapFlag,
233 ValueMapTypeRemapper *TypeMapper,
234 ValueMaterializer *Materializer,
235 const MetadataPredicate *IdentityMD) {
237 OldFunc.getAllMetadata(MDs);
238 for (const auto &[Kind, MD] : MDs) {
239 NewFunc.addMetadata(Kind, *MapMetadata(MD, VMap, RemapFlag, TypeMapper,
240 Materializer, IdentityMD));
241 }
242}
243
244void llvm::CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc,
245 ValueToValueMapTy &VMap, RemapFlags RemapFlag,
247 const char *NameSuffix,
248 ClonedCodeInfo *CodeInfo,
249 ValueMapTypeRemapper *TypeMapper,
250 ValueMaterializer *Materializer,
251 const MetadataPredicate *IdentityMD) {
252 if (OldFunc.isDeclaration())
253 return;
254
255 // Loop over all of the basic blocks in the function, cloning them as
256 // appropriate. Note that we save BE this way in order to handle cloning of
257 // recursive functions into themselves.
258 for (const BasicBlock &BB : OldFunc) {
259 // Create a new basic block and copy instructions into it!
260 BasicBlock *CBB =
261 CloneBasicBlock(&BB, VMap, NameSuffix, &NewFunc, CodeInfo);
262
263 // Add basic block mapping.
264 VMap[&BB] = CBB;
265
266 // It is only legal to clone a function if a block address within that
267 // function is never referenced outside of the function. Given that, we
268 // want to map block addresses from the old function to block addresses in
269 // the clone. (This is different from the generic ValueMapper
270 // implementation, which generates an invalid blockaddress when
271 // cloning a function.)
272 if (BB.hasAddressTaken()) {
273 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(&OldFunc),
274 const_cast<BasicBlock *>(&BB));
275 VMap[OldBBAddr] = BlockAddress::get(&NewFunc, CBB);
276 }
277
278 // Note return instructions for the caller.
280 Returns.push_back(RI);
281 }
282
283 // Loop over all of the instructions in the new function, fixing up operand
284 // references as we go. This uses VMap to do all the hard work.
286 BB = cast<BasicBlock>(VMap[&OldFunc.front()])->getIterator(),
287 BE = NewFunc.end();
288 BB != BE; ++BB)
289 // Loop over all instructions, fixing each one as we find it, and any
290 // attached debug-info records.
291 for (Instruction &II : *BB) {
292 RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer,
293 IdentityMD);
294 RemapDbgRecordRange(II.getModule(), II.getDbgRecordRange(), VMap,
295 RemapFlag, TypeMapper, Materializer, IdentityMD);
296 }
297}
298
299// Clone OldFunc into NewFunc, transforming the old arguments into references to
300// VMap values.
301void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
302 ValueToValueMapTy &VMap,
305 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
306 ValueMapTypeRemapper *TypeMapper,
307 ValueMaterializer *Materializer) {
308 assert(NameSuffix && "NameSuffix cannot be null!");
309
310#ifndef NDEBUG
311 for (const Argument &I : OldFunc->args())
312 assert(VMap.count(&I) && "No mapping from source argument specified!");
313#endif
314
315 bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
316
317 CloneFunctionAttributesInto(NewFunc, OldFunc, VMap, ModuleLevelChanges,
318 TypeMapper, Materializer);
319
320 // Everything else beyond this point deals with function instructions,
321 // so if we are dealing with a function declaration, we're done.
322 if (OldFunc->isDeclaration())
323 return;
324
326 assert((NewFunc->getParent() == nullptr ||
327 NewFunc->getParent() == OldFunc->getParent()) &&
328 "Expected NewFunc to have the same parent, or no parent");
329 } else {
330 assert((NewFunc->getParent() == nullptr ||
331 NewFunc->getParent() != OldFunc->getParent()) &&
332 "Expected NewFunc to have different parents, or no parent");
333
335 assert(NewFunc->getParent() &&
336 "Need parent of new function to maintain debug info invariants");
337 }
338 }
339
340 MetadataPredicate IdentityMD = createIdentityMDPredicate(*OldFunc, Changes);
341
342 // Cloning is always a Module level operation, since Metadata needs to be
343 // cloned.
344 const RemapFlags RemapFlag = RF_None;
345
346 CloneFunctionMetadataInto(*NewFunc, *OldFunc, VMap, RemapFlag, TypeMapper,
347 Materializer, &IdentityMD);
348
349 CloneFunctionBodyInto(*NewFunc, *OldFunc, VMap, RemapFlag, Returns,
350 NameSuffix, CodeInfo, TypeMapper, Materializer,
351 &IdentityMD);
352
353 // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
354 // same module, the compile unit will already be listed (or not). When
355 // cloning a module, CloneModule() will handle creating the named metadata.
357 return;
358
359 // Update !llvm.dbg.cu with compile units added to the new module if this
360 // function is being cloned in isolation.
361 //
362 // FIXME: This is making global / module-level changes, which doesn't seem
363 // like the right encapsulation Consider dropping the requirement to update
364 // !llvm.dbg.cu (either obsoleting the node, or restricting it to
365 // non-discardable compile units) instead of discovering compile units by
366 // visiting the metadata attached to global values, which would allow this
367 // code to be deleted. Alternatively, perhaps give responsibility for this
368 // update to CloneFunctionInto's callers.
369 Module *NewModule = NewFunc->getParent();
370 NamedMDNode *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
371 // Avoid multiple insertions of the same DICompileUnit to NMD.
373
374 // Collect and clone all the compile units referenced from the instructions in
375 // the function (e.g. as instructions' scope).
376 DebugInfoFinder DIFinder;
377 collectDebugInfoFromInstructions(*OldFunc, DIFinder);
378 for (DICompileUnit *Unit : DIFinder.compile_units()) {
379 MDNode *MappedUnit =
380 MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
381 if (Visited.insert(MappedUnit).second)
382 NMD->addOperand(MappedUnit);
383 }
384}
385
386/// Return a copy of the specified function and add it to that function's
387/// module. Also, any references specified in the VMap are changed to refer to
388/// their mapped value instead of the original one. If any of the arguments to
389/// the function are in the VMap, the arguments are deleted from the resultant
390/// function. The VMap is updated to include mappings from all of the
391/// instructions and basicblocks in the function from their old to new values.
392///
394 ClonedCodeInfo *CodeInfo) {
395 std::vector<Type *> ArgTypes;
396
397 // The user might be deleting arguments to the function by specifying them in
398 // the VMap. If so, we need to not add the arguments to the arg ty vector
399 //
400 for (const Argument &I : F->args())
401 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
402 ArgTypes.push_back(I.getType());
403
404 // Create a new function type...
405 FunctionType *FTy =
406 FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
407 F->getFunctionType()->isVarArg());
408
409 // Create the new function...
410 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
411 F->getName(), F->getParent());
412
413 // Loop over the arguments, copying the names of the mapped arguments over...
414 Function::arg_iterator DestI = NewF->arg_begin();
415 for (const Argument &I : F->args())
416 if (VMap.count(&I) == 0) { // Is this argument preserved?
417 DestI->setName(I.getName()); // Copy the name over...
418 VMap[&I] = &*DestI++; // Add mapping to VMap
419 }
420
421 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
423 Returns, "", CodeInfo);
424
425 return NewF;
426}
427
428namespace {
429/// This is a private class used to implement CloneAndPruneFunctionInto.
430struct PruningFunctionCloner {
431 Function *NewFunc;
432 const Function *OldFunc;
433 ValueToValueMapTy &VMap;
434 bool ModuleLevelChanges;
435 const char *NameSuffix;
436 ClonedCodeInfo *CodeInfo;
437 bool HostFuncIsStrictFP;
438
439 Instruction *cloneInstruction(BasicBlock::const_iterator II);
440
441public:
442 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
443 ValueToValueMapTy &valueMap, bool moduleLevelChanges,
444 const char *nameSuffix, ClonedCodeInfo *codeInfo)
445 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
446 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
447 CodeInfo(codeInfo) {
448 HostFuncIsStrictFP =
449 newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
450 }
451
452 /// The specified block is found to be reachable, clone it and
453 /// anything that it can reach.
454 void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
455 std::vector<const BasicBlock *> &ToClone);
456};
457} // namespace
458
460PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
461 const Instruction &OldInst = *II;
462 Instruction *NewInst = nullptr;
463 if (HostFuncIsStrictFP) {
465 if (CIID != Intrinsic::not_intrinsic) {
466 // Instead of cloning the instruction, a call to constrained intrinsic
467 // should be created.
468 // Assume the first arguments of constrained intrinsics are the same as
469 // the operands of original instruction.
470
471 // Determine overloaded types of the intrinsic.
474 getIntrinsicInfoTableEntries(CIID, Descriptor);
475 for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
476 Intrinsic::IITDescriptor Operand = Descriptor[I];
477 switch (Operand.Kind) {
479 if (Operand.getArgumentKind() !=
480 Intrinsic::IITDescriptor::AK_MatchType) {
481 if (I == 0)
482 TParams.push_back(OldInst.getType());
483 else
484 TParams.push_back(OldInst.getOperand(I - 1)->getType());
485 }
486 break;
488 ++I;
489 break;
490 default:
491 break;
492 }
493 }
494
495 // Create intrinsic call.
496 LLVMContext &Ctx = NewFunc->getContext();
498 CIID, TParams);
499 SmallVector<Value *, 4> Args;
500 unsigned NumOperands = OldInst.getNumOperands();
501 if (isa<CallInst>(OldInst))
502 --NumOperands;
503 for (unsigned I = 0; I < NumOperands; ++I) {
504 Value *Op = OldInst.getOperand(I);
505 Args.push_back(Op);
506 }
507 if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
508 FCmpInst::Predicate Pred = CmpI->getPredicate();
509 StringRef PredName = FCmpInst::getPredicateName(Pred);
510 Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
511 }
512
513 // The last arguments of a constrained intrinsic are metadata that
514 // represent rounding mode (absents in some intrinsics) and exception
515 // behavior. The inlined function uses default settings.
517 Args.push_back(
518 MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
519 Args.push_back(
520 MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
521
522 NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
523 }
524 }
525 if (!NewInst)
526 NewInst = II->clone();
527 return NewInst;
528}
529
530/// The specified block is found to be reachable, clone it and
531/// anything that it can reach.
532void PruningFunctionCloner::CloneBlock(
533 const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
534 std::vector<const BasicBlock *> &ToClone) {
535 WeakTrackingVH &BBEntry = VMap[BB];
536
537 // Have we already cloned this block?
538 if (BBEntry)
539 return;
540
541 // Nope, clone it now.
542 BasicBlock *NewBB;
543 Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
544 BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
545
546 // It is only legal to clone a function if a block address within that
547 // function is never referenced outside of the function. Given that, we
548 // want to map block addresses from the old function to block addresses in
549 // the clone. (This is different from the generic ValueMapper
550 // implementation, which generates an invalid blockaddress when
551 // cloning a function.)
552 //
553 // Note that we don't need to fix the mapping for unreachable blocks;
554 // the default mapping there is safe.
555 if (BB->hasAddressTaken()) {
556 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
557 const_cast<BasicBlock *>(BB));
558 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
559 }
560
561 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
562 bool hasMemProfMetadata = false;
563
564 // Keep a cursor pointing at the last place we cloned debug-info records from.
565 BasicBlock::const_iterator DbgCursor = StartingInst;
566 auto CloneDbgRecordsToHere =
567 [&DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
568 // Clone debug-info records onto this instruction. Iterate through any
569 // source-instructions we've cloned and then subsequently optimised
570 // away, so that their debug-info doesn't go missing.
571 for (; DbgCursor != II; ++DbgCursor)
572 NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
573 NewInst->cloneDebugInfoFrom(&*II);
574 DbgCursor = std::next(II);
575 };
576
577 // Loop over all instructions, and copy them over, DCE'ing as we go. This
578 // loop doesn't include the terminator.
579 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
580 ++II) {
581
582 // Don't clone fake_use as it may suppress many optimizations
583 // due to inlining, especially SROA.
584 if (auto *IntrInst = dyn_cast<IntrinsicInst>(II))
585 if (IntrInst->getIntrinsicID() == Intrinsic::fake_use)
586 continue;
587
588 Instruction *NewInst = cloneInstruction(II);
589 NewInst->insertInto(NewBB, NewBB->end());
590
591 if (HostFuncIsStrictFP) {
592 // All function calls in the inlined function must get 'strictfp'
593 // attribute to prevent undesirable optimizations.
594 if (auto *Call = dyn_cast<CallInst>(NewInst))
595 Call->addFnAttr(Attribute::StrictFP);
596 }
597
598 // Eagerly remap operands to the newly cloned instruction, except for PHI
599 // nodes for which we defer processing until we update the CFG.
600 if (!isa<PHINode>(NewInst)) {
601 RemapInstruction(NewInst, VMap,
602 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
603
604 // Eagerly constant fold the newly cloned instruction. If successful, add
605 // a mapping to the new value. Non-constant operands may be incomplete at
606 // this stage, thus instruction simplification is performed after
607 // processing phi-nodes.
609 NewInst, BB->getDataLayout())) {
610 if (isInstructionTriviallyDead(NewInst)) {
611 VMap[&*II] = V;
612 NewInst->eraseFromParent();
613 continue;
614 }
615 }
616 }
617
618 if (II->hasName())
619 NewInst->setName(II->getName() + NameSuffix);
620 VMap[&*II] = NewInst; // Add instruction map to value.
621 if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
622 hasCalls = true;
623 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
624 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_callsite);
625 }
626
627 CloneDbgRecordsToHere(NewInst, II);
628
629 if (CodeInfo) {
630 CodeInfo->OrigVMap[&*II] = NewInst;
631 if (auto *CB = dyn_cast<CallBase>(&*II))
632 if (CB->hasOperandBundles())
633 CodeInfo->OperandBundleCallSites.push_back(NewInst);
634 }
635
636 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
637 if (isa<ConstantInt>(AI->getArraySize()))
638 hasStaticAllocas = true;
639 else
640 hasDynamicAllocas = true;
641 }
642 }
643
644 // Finally, clone over the terminator.
645 const Instruction *OldTI = BB->getTerminator();
646 bool TerminatorDone = false;
647 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
648 if (BI->isConditional()) {
649 // If the condition was a known constant in the callee...
650 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
651 // Or is a known constant in the caller...
652 if (!Cond) {
653 Value *V = VMap.lookup(BI->getCondition());
655 }
656
657 // Constant fold to uncond branch!
658 if (Cond) {
659 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
660 auto *NewBI = BranchInst::Create(Dest, NewBB);
661 NewBI->setDebugLoc(BI->getDebugLoc());
662 VMap[OldTI] = NewBI;
663 ToClone.push_back(Dest);
664 TerminatorDone = true;
665 }
666 }
667 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
668 // If switching on a value known constant in the caller.
669 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
670 if (!Cond) { // Or known constant after constant prop in the callee...
671 Value *V = VMap.lookup(SI->getCondition());
673 }
674 if (Cond) { // Constant fold to uncond branch!
675 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
676 BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
677 auto *NewBI = BranchInst::Create(Dest, NewBB);
678 NewBI->setDebugLoc(SI->getDebugLoc());
679 VMap[OldTI] = NewBI;
680 ToClone.push_back(Dest);
681 TerminatorDone = true;
682 }
683 }
684
685 if (!TerminatorDone) {
686 Instruction *NewInst = OldTI->clone();
687 if (OldTI->hasName())
688 NewInst->setName(OldTI->getName() + NameSuffix);
689 NewInst->insertInto(NewBB, NewBB->end());
690
691 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
692
693 VMap[OldTI] = NewInst; // Add instruction map to value.
694
695 if (CodeInfo) {
696 CodeInfo->OrigVMap[OldTI] = NewInst;
697 if (auto *CB = dyn_cast<CallBase>(OldTI))
698 if (CB->hasOperandBundles())
699 CodeInfo->OperandBundleCallSites.push_back(NewInst);
700 }
701
702 // Recursively clone any reachable successor blocks.
703 append_range(ToClone, successors(BB->getTerminator()));
704 } else {
705 // If we didn't create a new terminator, clone DbgVariableRecords from the
706 // old terminator onto the new terminator.
707 Instruction *NewInst = NewBB->getTerminator();
708 assert(NewInst);
709
710 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
711 }
712
713 if (CodeInfo) {
714 CodeInfo->ContainsCalls |= hasCalls;
715 CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
716 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
717 CodeInfo->ContainsDynamicAllocas |=
718 hasStaticAllocas && BB != &BB->getParent()->front();
719 }
720}
721
722/// This works like CloneAndPruneFunctionInto, except that it does not clone the
723/// entire function. Instead it starts at an instruction provided by the caller
724/// and copies (and prunes) only the code reachable from that instruction.
726 const Instruction *StartingInst,
727 ValueToValueMapTy &VMap,
728 bool ModuleLevelChanges,
730 const char *NameSuffix,
731 ClonedCodeInfo *CodeInfo) {
732 assert(NameSuffix && "NameSuffix cannot be null!");
733
734 ValueMapTypeRemapper *TypeMapper = nullptr;
735 ValueMaterializer *Materializer = nullptr;
736
737#ifndef NDEBUG
738 // If the cloning starts at the beginning of the function, verify that
739 // the function arguments are mapped.
740 if (!StartingInst)
741 for (const Argument &II : OldFunc->args())
742 assert(VMap.count(&II) && "No mapping from source argument specified!");
743#endif
744
745 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
746 NameSuffix, CodeInfo);
747 const BasicBlock *StartingBB;
748 if (StartingInst)
749 StartingBB = StartingInst->getParent();
750 else {
751 StartingBB = &OldFunc->getEntryBlock();
752 StartingInst = &StartingBB->front();
753 }
754
755 // Clone the entry block, and anything recursively reachable from it.
756 std::vector<const BasicBlock *> CloneWorklist;
757 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
758 while (!CloneWorklist.empty()) {
759 const BasicBlock *BB = CloneWorklist.back();
760 CloneWorklist.pop_back();
761 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
762 }
763
764 // Loop over all of the basic blocks in the old function. If the block was
765 // reachable, we have cloned it and the old block is now in the value map:
766 // insert it into the new function in the right order. If not, ignore it.
767 //
768 // Defer PHI resolution until rest of function is resolved.
770 for (const BasicBlock &BI : *OldFunc) {
771 Value *V = VMap.lookup(&BI);
773 if (!NewBB)
774 continue; // Dead block.
775
776 // Move the new block to preserve the order in the original function.
777 NewBB->moveBefore(NewFunc->end());
778
779 // Handle PHI nodes specially, as we have to remove references to dead
780 // blocks.
781 for (const PHINode &PN : BI.phis()) {
782 // PHI nodes may have been remapped to non-PHI nodes by the caller or
783 // during the cloning process.
784 if (isa<PHINode>(VMap[&PN]))
785 PHIToResolve.push_back(&PN);
786 else
787 break;
788 }
789
790 // Finally, remap the terminator instructions, as those can't be remapped
791 // until all BBs are mapped.
792 RemapInstruction(NewBB->getTerminator(), VMap,
793 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
794 TypeMapper, Materializer);
795 }
796
797 // Defer PHI resolution until rest of function is resolved, PHI resolution
798 // requires the CFG to be up-to-date.
799 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
800 const PHINode *OPN = PHIToResolve[phino];
801 unsigned NumPreds = OPN->getNumIncomingValues();
802 const BasicBlock *OldBB = OPN->getParent();
803 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
804
805 // Map operands for blocks that are live and remove operands for blocks
806 // that are dead.
807 for (; phino != PHIToResolve.size() &&
808 PHIToResolve[phino]->getParent() == OldBB;
809 ++phino) {
810 OPN = PHIToResolve[phino];
811 PHINode *PN = cast<PHINode>(VMap[OPN]);
812 for (int64_t pred = NumPreds - 1; pred >= 0; --pred) {
813 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
814 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
815 Value *InVal =
816 MapValue(PN->getIncomingValue(pred), VMap,
817 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
818 assert(InVal && "Unknown input value?");
819 PN->setIncomingValue(pred, InVal);
820 PN->setIncomingBlock(pred, MappedBlock);
821 continue;
822 }
823 PN->removeIncomingValue(pred, false);
824 }
825 }
826
827 // The loop above has removed PHI entries for those blocks that are dead
828 // and has updated others. However, if a block is live (i.e. copied over)
829 // but its terminator has been changed to not go to this block, then our
830 // phi nodes will have invalid entries. Update the PHI nodes in this
831 // case.
832 PHINode *PN = cast<PHINode>(NewBB->begin());
833 NumPreds = pred_size(NewBB);
834 if (NumPreds != PN->getNumIncomingValues()) {
835 assert(NumPreds < PN->getNumIncomingValues());
836 // Count how many times each predecessor comes to this block.
838 for (BasicBlock *Pred : predecessors(NewBB))
839 ++PredCount[Pred];
840
841 BasicBlock::iterator I = NewBB->begin();
843 SeenPredCount.reserve(PredCount.size());
844 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
845 SeenPredCount.clear();
847 [&](unsigned Idx) {
848 BasicBlock *IncomingBlock = PN->getIncomingBlock(Idx);
849 auto It = PredCount.find(IncomingBlock);
850 if (It == PredCount.end())
851 return true;
852 unsigned &SeenCount = SeenPredCount[IncomingBlock];
853 if (SeenCount < It->second) {
854 SeenCount++;
855 return false;
856 }
857 return true;
858 },
859 false);
860 }
861 }
862
863 // If the loops above have made these phi nodes have 0 or 1 operand,
864 // replace them with poison or the input value. We must do this for
865 // correctness, because 0-operand phis are not valid.
866 PN = cast<PHINode>(NewBB->begin());
867 if (PN->getNumIncomingValues() == 0) {
868 BasicBlock::iterator I = NewBB->begin();
869 BasicBlock::const_iterator OldI = OldBB->begin();
870 while ((PN = dyn_cast<PHINode>(I++))) {
871 Value *NV = PoisonValue::get(PN->getType());
872 PN->replaceAllUsesWith(NV);
873 assert(VMap[&*OldI] == PN && "VMap mismatch");
874 VMap[&*OldI] = NV;
875 PN->eraseFromParent();
876 ++OldI;
877 }
878 }
879 }
880
881 // Drop all incompatible return attributes that cannot be applied to NewFunc
882 // during cloning, so as to allow instruction simplification to reason on the
883 // old state of the function. The original attributes are restored later.
884 AttributeList Attrs = NewFunc->getAttributes();
885 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
886 OldFunc->getReturnType(), Attrs.getRetAttrs());
887 NewFunc->removeRetAttrs(IncompatibleAttrs);
888
889 // As phi-nodes have been now remapped, allow incremental simplification of
890 // newly-cloned instructions.
891 const DataLayout &DL = NewFunc->getDataLayout();
892 for (const BasicBlock &BB : *OldFunc) {
893 for (const Instruction &I : BB) {
894 auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
895 if (!NewI)
896 continue;
897
898 if (Value *V = simplifyInstruction(NewI, DL)) {
899 NewI->replaceAllUsesWith(V);
900
901 if (isInstructionTriviallyDead(NewI)) {
902 NewI->eraseFromParent();
903 } else {
904 // Did not erase it? Restore the new instruction into VMap previously
905 // dropped by `ValueIsRAUWd`.
906 VMap[&I] = NewI;
907 }
908 }
909 }
910 }
911
912 // Restore attributes.
913 NewFunc->setAttributes(Attrs);
914
915 // Remap debug records operands now that all values have been mapped.
916 // Doing this now (late) preserves use-before-defs in debug records. If
917 // we didn't do this, ValueAsMetadata(use-before-def) operands would be
918 // replaced by empty metadata. This would signal later cleanup passes to
919 // remove the debug records, potentially causing incorrect locations.
920 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
921 for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
922 for (Instruction &I : BB) {
923 RemapDbgRecordRange(I.getModule(), I.getDbgRecordRange(), VMap,
924 ModuleLevelChanges ? RF_None
926 TypeMapper, Materializer);
927 }
928 }
929
930 // Simplify conditional branches and switches with a constant operand. We try
931 // to prune these out when cloning, but if the simplification required
932 // looking through PHI nodes, those are only available after forming the full
933 // basic block. That may leave some here, and we still want to prune the dead
934 // code as early as possible.
935 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
937
938 // Some blocks may have become unreachable as a result. Find and delete them.
939 {
940 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
942 Worklist.push_back(&*Begin);
943 while (!Worklist.empty()) {
944 BasicBlock *BB = Worklist.pop_back_val();
945 if (ReachableBlocks.insert(BB).second)
946 append_range(Worklist, successors(BB));
947 }
948
949 SmallVector<BasicBlock *, 16> UnreachableBlocks;
950 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
951 if (!ReachableBlocks.contains(&BB))
952 UnreachableBlocks.push_back(&BB);
953 DeleteDeadBlocks(UnreachableBlocks);
954 }
955
956 // Now that the inlined function body has been fully constructed, go through
957 // and zap unconditional fall-through branches. This happens all the time when
958 // specializing code: code specialization turns conditional branches into
959 // uncond branches, and this code folds them.
960 Function::iterator I = Begin;
961 while (I != NewFunc->end()) {
962 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
963 if (!BI || BI->isConditional()) {
964 ++I;
965 continue;
966 }
967
968 BasicBlock *Dest = BI->getSuccessor(0);
969 if (!Dest->getSinglePredecessor() || Dest->hasAddressTaken()) {
970 ++I;
971 continue;
972 }
973
974 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
975 // above should have zapped all of them..
976 assert(!isa<PHINode>(Dest->begin()));
977
978 // We know all single-entry PHI nodes in the inlined function have been
979 // removed, so we just need to splice the blocks.
980 BI->eraseFromParent();
981
982 // Make all PHI nodes that referred to Dest now refer to I as their source.
983 Dest->replaceAllUsesWith(&*I);
984
985 // Move all the instructions in the succ to the pred.
986 I->splice(I->end(), Dest);
987
988 // Remove the dest block.
989 Dest->eraseFromParent();
990
991 // Do not increment I, iteratively merge all things this block branches to.
992 }
993
994 // Make a final pass over the basic blocks from the old function to gather
995 // any return instructions which survived folding. We have to do this here
996 // because we can iteratively remove and merge returns above.
997 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
998 E = NewFunc->end();
999 I != E; ++I)
1000 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
1001 Returns.push_back(RI);
1002}
1003
1004/// This works exactly like CloneFunctionInto,
1005/// except that it does some simple constant prop and DCE on the fly. The
1006/// effect of this is to copy significantly less code in cases where (for
1007/// example) a function call with constant arguments is inlined, and those
1008/// constant arguments cause a significant amount of code in the callee to be
1009/// dead. Since this doesn't produce an exact copy of the input, it can't be
1010/// used for things like CloneFunction or CloneModule.
1012 Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
1013 bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
1014 const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
1015 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
1016 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
1017}
1018
1019/// Remaps instructions in \p Blocks using the mapping in \p VMap.
1021 ValueToValueMapTy &VMap) {
1022 // Rewrite the code to refer to itself.
1023 for (BasicBlock *BB : Blocks) {
1024 for (Instruction &Inst : *BB) {
1025 RemapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange(), VMap,
1027 RemapInstruction(&Inst, VMap,
1029 }
1030 }
1031}
1032
1033/// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
1034/// Blocks.
1035///
1036/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
1037/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
1039 Loop *OrigLoop, ValueToValueMapTy &VMap,
1040 const Twine &NameSuffix, LoopInfo *LI,
1041 DominatorTree *DT,
1043 Function *F = OrigLoop->getHeader()->getParent();
1044 Loop *ParentLoop = OrigLoop->getParentLoop();
1046
1047 Loop *NewLoop = LI->AllocateLoop();
1048 LMap[OrigLoop] = NewLoop;
1049 if (ParentLoop)
1050 ParentLoop->addChildLoop(NewLoop);
1051 else
1052 LI->addTopLevelLoop(NewLoop);
1053
1054 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
1055 assert(OrigPH && "No preheader");
1056 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
1057 // To rename the loop PHIs.
1058 VMap[OrigPH] = NewPH;
1059 Blocks.push_back(NewPH);
1060
1061 // Update LoopInfo.
1062 if (ParentLoop)
1063 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
1064
1065 // Update DominatorTree.
1066 DT->addNewBlock(NewPH, LoopDomBB);
1067
1068 for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
1069 Loop *&NewLoop = LMap[CurLoop];
1070 if (!NewLoop) {
1071 NewLoop = LI->AllocateLoop();
1072
1073 // Establish the parent/child relationship.
1074 Loop *OrigParent = CurLoop->getParentLoop();
1075 assert(OrigParent && "Could not find the original parent loop");
1076 Loop *NewParentLoop = LMap[OrigParent];
1077 assert(NewParentLoop && "Could not find the new parent loop");
1078
1079 NewParentLoop->addChildLoop(NewLoop);
1080 }
1081 }
1082
1083 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1084 Loop *CurLoop = LI->getLoopFor(BB);
1085 Loop *&NewLoop = LMap[CurLoop];
1086 assert(NewLoop && "Expecting new loop to be allocated");
1087
1088 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
1089 VMap[BB] = NewBB;
1090
1091 // Update LoopInfo.
1092 NewLoop->addBasicBlockToLoop(NewBB, *LI);
1093
1094 // Add DominatorTree node. After seeing all blocks, update to correct
1095 // IDom.
1096 DT->addNewBlock(NewBB, NewPH);
1097
1098 Blocks.push_back(NewBB);
1099 }
1100
1101 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1102 // Update loop headers.
1103 Loop *CurLoop = LI->getLoopFor(BB);
1104 if (BB == CurLoop->getHeader())
1105 LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1106
1107 // Update DominatorTree.
1108 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
1110 cast<BasicBlock>(VMap[IDomBB]));
1111 }
1112
1113 // Move them physically from the end of the block list.
1114 F->splice(Before->getIterator(), F, NewPH->getIterator());
1115 F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1116 F->end());
1117
1118 return NewLoop;
1119}
1120
1121/// Duplicate non-Phi instructions from the beginning of block up to
1122/// StopAt instruction into a split block between BB and its predecessor.
1124 BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1125 ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1126
1127 assert(count(successors(PredBB), BB) == 1 &&
1128 "There must be a single edge between PredBB and BB!");
1129 // We are going to have to map operands from the original BB block to the new
1130 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1131 // account for entry from PredBB.
1132 BasicBlock::iterator BI = BB->begin();
1133 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1134 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1135
1136 BasicBlock *NewBB = SplitEdge(PredBB, BB);
1137 NewBB->setName(PredBB->getName() + ".split");
1138 Instruction *NewTerm = NewBB->getTerminator();
1139
1140 // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1141 // in the update set here.
1142 DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1143 {DominatorTree::Insert, PredBB, NewBB},
1144 {DominatorTree::Insert, NewBB, BB}});
1145
1146 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1147 // mapping and using it to remap operands in the cloned instructions.
1148 // Stop once we see the terminator too. This covers the case where BB's
1149 // terminator gets replaced and StopAt == BB's terminator.
1150 for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
1151 Instruction *New = BI->clone();
1152 New->setName(BI->getName());
1153 New->insertBefore(NewTerm->getIterator());
1154 New->cloneDebugInfoFrom(&*BI);
1155 ValueMapping[&*BI] = New;
1156
1157 // Remap operands to patch up intra-block references.
1158 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1159 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1160 auto I = ValueMapping.find(Inst);
1161 if (I != ValueMapping.end())
1162 New->setOperand(i, I->second);
1163 }
1164
1165 // Remap debug variable operands.
1166 remapDebugVariable(ValueMapping, New);
1167 }
1168
1169 return NewBB;
1170}
1171
1173 DenseMap<MDNode *, MDNode *> &ClonedScopes,
1174 StringRef Ext, LLVMContext &Context) {
1175 MDBuilder MDB(Context);
1176
1177 for (MDNode *ScopeList : NoAliasDeclScopes) {
1178 for (const MDOperand &MDOp : ScopeList->operands()) {
1179 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1180 AliasScopeNode SNANode(MD);
1181
1182 std::string Name;
1183 auto ScopeName = SNANode.getName();
1184 if (!ScopeName.empty())
1185 Name = (Twine(ScopeName) + ":" + Ext).str();
1186 else
1187 Name = std::string(Ext);
1188
1189 MDNode *NewScope = MDB.createAnonymousAliasScope(
1190 const_cast<MDNode *>(SNANode.getDomain()), Name);
1191 ClonedScopes.insert(std::make_pair(MD, NewScope));
1192 }
1193 }
1194 }
1195}
1196
1198 const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1199 LLVMContext &Context) {
1200 auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1201 bool NeedsReplacement = false;
1202 SmallVector<Metadata *, 8> NewScopeList;
1203 for (const MDOperand &MDOp : ScopeList->operands()) {
1204 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1205 if (auto *NewMD = ClonedScopes.lookup(MD)) {
1206 NewScopeList.push_back(NewMD);
1207 NeedsReplacement = true;
1208 continue;
1209 }
1210 NewScopeList.push_back(MD);
1211 }
1212 }
1213 if (NeedsReplacement)
1214 return MDNode::get(Context, NewScopeList);
1215 return nullptr;
1216 };
1217
1218 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1219 if (MDNode *NewScopeList = CloneScopeList(Decl->getScopeList()))
1220 Decl->setScopeList(NewScopeList);
1221
1222 auto replaceWhenNeeded = [&](unsigned MD_ID) {
1223 if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1224 if (MDNode *NewScopeList = CloneScopeList(CSNoAlias))
1225 I->setMetadata(MD_ID, NewScopeList);
1226 };
1227 replaceWhenNeeded(LLVMContext::MD_noalias);
1228 replaceWhenNeeded(LLVMContext::MD_alias_scope);
1229}
1230
1232 ArrayRef<BasicBlock *> NewBlocks,
1233 LLVMContext &Context, StringRef Ext) {
1234 if (NoAliasDeclScopes.empty())
1235 return;
1236
1237 DenseMap<MDNode *, MDNode *> ClonedScopes;
1238 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1239 << NoAliasDeclScopes.size() << " node(s)\n");
1240
1241 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1242 // Identify instructions using metadata that needs adaptation
1243 for (BasicBlock *NewBlock : NewBlocks)
1244 for (Instruction &I : *NewBlock)
1245 adaptNoAliasScopes(&I, ClonedScopes, Context);
1246}
1247
1249 Instruction *IStart, Instruction *IEnd,
1250 LLVMContext &Context, StringRef Ext) {
1251 if (NoAliasDeclScopes.empty())
1252 return;
1253
1254 DenseMap<MDNode *, MDNode *> ClonedScopes;
1255 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1256 << NoAliasDeclScopes.size() << " node(s)\n");
1257
1258 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1259 // Identify instructions using metadata that needs adaptation
1260 assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1261 auto ItStart = IStart->getIterator();
1262 auto ItEnd = IEnd->getIterator();
1263 ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1264 for (auto &I : llvm::make_range(ItStart, ItEnd))
1265 adaptNoAliasScopes(&I, ClonedScopes, Context);
1266}
1267
1269 ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1270 for (BasicBlock *BB : BBs)
1271 for (Instruction &I : *BB)
1272 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1273 NoAliasDeclScopes.push_back(Decl->getScopeList());
1274}
1275
1278 SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1279 for (Instruction &I : make_range(Start, End))
1280 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1281 NoAliasDeclScopes.push_back(Decl->getScopeList());
1282}
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...
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:1596
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1607
StringRef getName() const
Definition Metadata.h:1612
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:483
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:470
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:696
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:493
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:397
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:149
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
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
unsigned size() const
Definition DenseMap.h:110
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:114
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:168
const BasicBlock & getEntryBlock() const
Definition Function.h:809
BasicBlockListType::iterator iterator
Definition Function.h:70
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:362
const BasicBlock & front() const
Definition Function.h:860
iterator_range< arg_iterator > args()
Definition Function.h:892
bool hasPrefixData() const
Check whether this function has prefix data.
Definition Function.h:914
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
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:354
arg_iterator arg_begin()
Definition Function.h:868
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
size_t arg_size() const
Definition Function.h:901
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:707
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
Constant * getPrefixData() const
Get the prefix data associated with this function.
iterator end()
Definition Function.h:855
bool hasPrologueData() const
Check whether this function has prologue data.
Definition Function.h:923
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:844
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:329
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:195
Metadata node.
Definition Metadata.h:1080
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
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:308
A tuple of MDNodes.
Definition Metadata.h:1760
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
LLVM_ABI void addOperand(MDNode *M)
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
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
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
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:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
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.
Definition Types.h:26
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:2208
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:3486
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:406
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
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:2012
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)
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:207