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