LLVM 20.0.0git
ArgumentPromotion.cpp
Go to the documentation of this file.
1//===- ArgumentPromotion.cpp - Promote by-reference arguments -------------===//
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 pass promotes "by reference" arguments to be "by value" arguments. In
10// practice, this means looking for internal functions that have pointer
11// arguments. If it can prove, through the use of alias analysis, that an
12// argument is *only* loaded, then it can pass the value into the function
13// instead of the address of the value. This can cause recursive simplification
14// of code and lead to the elimination of allocas (especially in C++ template
15// code like the STL).
16//
17// This pass also handles aggregate arguments that are passed into a function,
18// scalarizing them if the elements of the aggregate are only loaded. Note that
19// by default it refuses to scalarize aggregates which would require passing in
20// more than three operands to the function, because passing thousands of
21// operands for a large array or structure is unprofitable! This limit can be
22// configured or disabled, however.
23//
24// Note that this transformation could also be done for arguments that are only
25// stored to (returning the value instead), but does not currently. This case
26// would be best handled when and if LLVM begins supporting multiple return
27// values from functions.
28//
29//===----------------------------------------------------------------------===//
30
32
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/ScopeExit.h"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/Twine.h"
43#include "llvm/Analysis/Loads.h"
48#include "llvm/IR/Argument.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/CFG.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/Dominators.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/NoFolder.h"
64#include "llvm/IR/PassManager.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/Use.h"
67#include "llvm/IR/User.h"
68#include "llvm/IR/Value.h"
70#include "llvm/Support/Debug.h"
74#include <algorithm>
75#include <cassert>
76#include <cstdint>
77#include <utility>
78#include <vector>
79
80using namespace llvm;
81
82#define DEBUG_TYPE "argpromotion"
83
84STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted");
85STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated");
86
87namespace {
88
89struct ArgPart {
90 Type *Ty;
91 Align Alignment;
92 /// A representative guaranteed-executed load or store instruction for use by
93 /// metadata transfer.
94 Instruction *MustExecInstr;
95};
96
97using OffsetAndArgPart = std::pair<int64_t, ArgPart>;
98
99} // end anonymous namespace
100
102 Value *Ptr, Type *ResElemTy, int64_t Offset) {
103 if (Offset != 0) {
104 APInt APOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), Offset,
105 /*isSigned=*/true);
106 Ptr = IRB.CreatePtrAdd(Ptr, IRB.getInt(APOffset));
107 }
108 return Ptr;
109}
110
111/// DoPromotion - This method actually performs the promotion of the specified
112/// arguments, and returns the new function. At this point, we know that it's
113/// safe to do so.
114static Function *
117 &ArgsToPromote) {
118 // Start by computing a new prototype for the function, which is the same as
119 // the old function, but has modified arguments.
120 FunctionType *FTy = F->getFunctionType();
121 std::vector<Type *> Params;
122
123 // Attribute - Keep track of the parameter attributes for the arguments
124 // that we are *not* promoting. For the ones that we do promote, the parameter
125 // attributes are lost
127 // Mapping from old to new argument indices. -1 for promoted or removed
128 // arguments.
129 SmallVector<unsigned> NewArgIndices;
130 AttributeList PAL = F->getAttributes();
132
133 // First, determine the new argument list
134 unsigned ArgNo = 0, NewArgNo = 0;
135 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
136 ++I, ++ArgNo) {
137 if (!ArgsToPromote.count(&*I)) {
138 // Unchanged argument
139 Params.push_back(I->getType());
140 ArgAttrVec.push_back(PAL.getParamAttrs(ArgNo));
141 NewArgIndices.push_back(NewArgNo++);
142 } else if (I->use_empty()) {
143 // Dead argument (which are always marked as promotable)
144 ++NumArgumentsDead;
145 ORE.emit([&]() {
146 return OptimizationRemark(DEBUG_TYPE, "ArgumentRemoved", F)
147 << "eliminating argument " << ore::NV("ArgName", I->getName())
148 << "(" << ore::NV("ArgIndex", ArgNo) << ")";
149 });
150
151 NewArgIndices.push_back((unsigned)-1);
152 } else {
153 const auto &ArgParts = ArgsToPromote.find(&*I)->second;
154 for (const auto &Pair : ArgParts) {
155 Params.push_back(Pair.second.Ty);
156 ArgAttrVec.push_back(AttributeSet());
157 }
158 ++NumArgumentsPromoted;
159 ORE.emit([&]() {
160 return OptimizationRemark(DEBUG_TYPE, "ArgumentPromoted", F)
161 << "promoting argument " << ore::NV("ArgName", I->getName())
162 << "(" << ore::NV("ArgIndex", ArgNo) << ")"
163 << " to pass by value";
164 });
165
166 NewArgIndices.push_back((unsigned)-1);
167 NewArgNo += ArgParts.size();
168 }
169 }
170
171 Type *RetTy = FTy->getReturnType();
172
173 // Construct the new function type using the new arguments.
174 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
175
176 // Create the new function body and insert it into the module.
177 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace(),
178 F->getName());
180 NF->copyMetadata(F, 0);
181 NF->setIsNewDbgInfoFormat(F->IsNewDbgInfoFormat);
182
183 // The new function will have the !dbg metadata copied from the original
184 // function. The original function may not be deleted, and dbg metadata need
185 // to be unique, so we need to drop it.
186 F->setSubprogram(nullptr);
187
188 LLVM_DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
189 << "From: " << *F);
190
191 uint64_t LargestVectorWidth = 0;
192 for (auto *I : Params)
193 if (auto *VT = dyn_cast<llvm::VectorType>(I))
194 LargestVectorWidth = std::max(
195 LargestVectorWidth, VT->getPrimitiveSizeInBits().getKnownMinValue());
196
197 // Recompute the parameter attributes list based on the new arguments for
198 // the function.
199 NF->setAttributes(AttributeList::get(F->getContext(), PAL.getFnAttrs(),
200 PAL.getRetAttrs(), ArgAttrVec));
201
202 // Remap argument indices in allocsize attribute.
203 if (auto AllocSize = NF->getAttributes().getFnAttrs().getAllocSizeArgs()) {
204 unsigned Arg1 = NewArgIndices[AllocSize->first];
205 assert(Arg1 != (unsigned)-1 && "allocsize cannot be promoted argument");
206 std::optional<unsigned> Arg2;
207 if (AllocSize->second) {
208 Arg2 = NewArgIndices[*AllocSize->second];
209 assert(Arg2 != (unsigned)-1 && "allocsize cannot be promoted argument");
210 }
211 NF->addFnAttr(Attribute::getWithAllocSizeArgs(F->getContext(), Arg1, Arg2));
212 }
213
214 AttributeFuncs::updateMinLegalVectorWidthAttr(*NF, LargestVectorWidth);
215 ArgAttrVec.clear();
216
217 F->getParent()->getFunctionList().insert(F->getIterator(), NF);
218 NF->takeName(F);
219
220 // Loop over all the callers of the function, transforming the call sites to
221 // pass in the loaded pointers.
223 const DataLayout &DL = F->getDataLayout();
225
226 while (!F->use_empty()) {
227 CallBase &CB = cast<CallBase>(*F->user_back());
228 assert(CB.getCalledFunction() == F);
229 const AttributeList &CallPAL = CB.getAttributes();
230 IRBuilder<NoFolder> IRB(&CB);
231
232 // Loop over the operands, inserting GEP and loads in the caller as
233 // appropriate.
234 auto *AI = CB.arg_begin();
235 ArgNo = 0;
236 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
237 ++I, ++AI, ++ArgNo) {
238 if (!ArgsToPromote.count(&*I)) {
239 Args.push_back(*AI); // Unmodified argument
240 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo));
241 } else if (!I->use_empty()) {
242 Value *V = *AI;
243 const auto &ArgParts = ArgsToPromote.find(&*I)->second;
244 for (const auto &Pair : ArgParts) {
245 LoadInst *LI = IRB.CreateAlignedLoad(
246 Pair.second.Ty,
247 createByteGEP(IRB, DL, V, Pair.second.Ty, Pair.first),
248 Pair.second.Alignment, V->getName() + ".val");
249 if (Pair.second.MustExecInstr) {
250 LI->setAAMetadata(Pair.second.MustExecInstr->getAAMetadata());
251 LI->copyMetadata(*Pair.second.MustExecInstr,
252 {LLVMContext::MD_dereferenceable,
253 LLVMContext::MD_dereferenceable_or_null,
254 LLVMContext::MD_noundef,
255 LLVMContext::MD_nontemporal});
256 // Only transfer poison-generating metadata if we also have
257 // !noundef.
258 // TODO: Without !noundef, we could merge this metadata across
259 // all promoted loads.
260 if (LI->hasMetadata(LLVMContext::MD_noundef))
261 LI->copyMetadata(*Pair.second.MustExecInstr,
262 {LLVMContext::MD_range, LLVMContext::MD_nonnull,
263 LLVMContext::MD_align});
264 }
265 Args.push_back(LI);
266 ArgAttrVec.push_back(AttributeSet());
267 }
268 } else {
269 assert(ArgsToPromote.count(&*I) && I->use_empty());
270 DeadArgs.emplace_back(AI->get());
271 }
272 }
273
274 // Push any varargs arguments on the list.
275 for (; AI != CB.arg_end(); ++AI, ++ArgNo) {
276 Args.push_back(*AI);
277 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo));
278 }
279
281 CB.getOperandBundlesAsDefs(OpBundles);
282
283 CallBase *NewCS = nullptr;
284 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
285 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
286 Args, OpBundles, "", CB.getIterator());
287 } else {
288 auto *NewCall =
289 CallInst::Create(NF, Args, OpBundles, "", CB.getIterator());
290 NewCall->setTailCallKind(cast<CallInst>(&CB)->getTailCallKind());
291 NewCS = NewCall;
292 }
293 NewCS->setCallingConv(CB.getCallingConv());
294 NewCS->setAttributes(AttributeList::get(F->getContext(),
295 CallPAL.getFnAttrs(),
296 CallPAL.getRetAttrs(), ArgAttrVec));
297 NewCS->copyMetadata(CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
298 Args.clear();
299 ArgAttrVec.clear();
300
302 LargestVectorWidth);
303
304 if (!CB.use_empty()) {
305 CB.replaceAllUsesWith(NewCS);
306 NewCS->takeName(&CB);
307 }
308
309 // Finally, remove the old call from the program, reducing the use-count of
310 // F.
311 CB.eraseFromParent();
312 }
313
315
316 // Since we have now created the new function, splice the body of the old
317 // function right into the new function, leaving the old rotting hulk of the
318 // function empty.
319 NF->splice(NF->begin(), F);
320
321 // We will collect all the new created allocas to promote them into registers
322 // after the following loop
324
325 // Loop over the argument list, transferring uses of the old arguments over to
326 // the new arguments, also transferring over the names as well.
328 for (Argument &Arg : F->args()) {
329 if (!ArgsToPromote.count(&Arg)) {
330 // If this is an unmodified argument, move the name and users over to the
331 // new version.
332 Arg.replaceAllUsesWith(&*I2);
333 I2->takeName(&Arg);
334 ++I2;
335 continue;
336 }
337
338 // There potentially are metadata uses for things like llvm.dbg.value.
339 // Replace them with poison, after handling the other regular uses.
340 auto RauwPoisonMetadata = make_scope_exit(
341 [&]() { Arg.replaceAllUsesWith(PoisonValue::get(Arg.getType())); });
342
343 if (Arg.use_empty())
344 continue;
345
346 // Otherwise, if we promoted this argument, we have to create an alloca in
347 // the callee for every promotable part and store each of the new incoming
348 // arguments into the corresponding alloca, what lets the old code (the
349 // store instructions if they are allowed especially) a chance to work as
350 // before.
351 assert(Arg.getType()->isPointerTy() &&
352 "Only arguments with a pointer type are promotable");
353
354 IRBuilder<NoFolder> IRB(&NF->begin()->front());
355
356 // Add only the promoted elements, so parts from ArgsToPromote
358 for (const auto &Pair : ArgsToPromote.find(&Arg)->second) {
359 int64_t Offset = Pair.first;
360 const ArgPart &Part = Pair.second;
361
362 Argument *NewArg = I2++;
363 NewArg->setName(Arg.getName() + "." + Twine(Offset) + ".val");
364
365 AllocaInst *NewAlloca = IRB.CreateAlloca(
366 Part.Ty, nullptr, Arg.getName() + "." + Twine(Offset) + ".allc");
367 NewAlloca->setAlignment(Pair.second.Alignment);
368 IRB.CreateAlignedStore(NewArg, NewAlloca, Pair.second.Alignment);
369
370 // Collect the alloca to retarget the users to
371 OffsetToAlloca.insert({Offset, NewAlloca});
372 }
373
374 auto GetAlloca = [&](Value *Ptr) {
375 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
376 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
377 /* AllowNonInbounds */ true);
378 assert(Ptr == &Arg && "Not constant offset from arg?");
379 return OffsetToAlloca.lookup(Offset.getSExtValue());
380 };
381
382 // Cleanup the code from the dead instructions: GEPs and BitCasts in between
383 // the original argument and its users: loads and stores. Retarget every
384 // user to the new created alloca.
387 append_range(Worklist, Arg.users());
388 while (!Worklist.empty()) {
389 Value *V = Worklist.pop_back_val();
390 if (isa<GetElementPtrInst>(V)) {
391 DeadInsts.push_back(cast<Instruction>(V));
392 append_range(Worklist, V->users());
393 continue;
394 }
395
396 if (auto *LI = dyn_cast<LoadInst>(V)) {
397 Value *Ptr = LI->getPointerOperand();
398 LI->setOperand(LoadInst::getPointerOperandIndex(), GetAlloca(Ptr));
399 continue;
400 }
401
402 if (auto *SI = dyn_cast<StoreInst>(V)) {
403 assert(!SI->isVolatile() && "Volatile operations can't be promoted.");
404 Value *Ptr = SI->getPointerOperand();
405 SI->setOperand(StoreInst::getPointerOperandIndex(), GetAlloca(Ptr));
406 continue;
407 }
408
409 llvm_unreachable("Unexpected user");
410 }
411
412 for (Instruction *I : DeadInsts) {
413 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
414 I->eraseFromParent();
415 }
416
417 // Collect the allocas for promotion
418 for (const auto &Pair : OffsetToAlloca) {
419 assert(isAllocaPromotable(Pair.second) &&
420 "By design, only promotable allocas should be produced.");
421 Allocas.push_back(Pair.second);
422 }
423 }
424
425 LLVM_DEBUG(dbgs() << "ARG PROMOTION: " << Allocas.size()
426 << " alloca(s) are promotable by Mem2Reg\n");
427
428 if (!Allocas.empty()) {
429 // And we are able to call the `promoteMemoryToRegister()` function.
430 // Our earlier checks have ensured that PromoteMemToReg() will
431 // succeed.
432 auto &DT = FAM.getResult<DominatorTreeAnalysis>(*NF);
433 auto &AC = FAM.getResult<AssumptionAnalysis>(*NF);
434 PromoteMemToReg(Allocas, DT, &AC);
435 }
436
437 return NF;
438}
439
440/// Return true if we can prove that all callees pass in a valid pointer for the
441/// specified function argument.
443 Argument *Arg, SmallPtrSetImpl<CallBase *> &RecursiveCalls,
444 Align NeededAlign, uint64_t NeededDerefBytes) {
445 Function *Callee = Arg->getParent();
446 const DataLayout &DL = Callee->getDataLayout();
447 APInt Bytes(64, NeededDerefBytes);
448
449 // Check if the argument itself is marked dereferenceable and aligned.
450 if (isDereferenceableAndAlignedPointer(Arg, NeededAlign, Bytes, DL))
451 return true;
452
453 // Look at all call sites of the function. At this point we know we only have
454 // direct callees.
455 return all_of(Callee->users(), [&](User *U) {
456 CallBase &CB = cast<CallBase>(*U);
457 // In case of functions with recursive calls, this check
458 // (isDereferenceableAndAlignedPointer) will fail when it tries to look at
459 // the first caller of this function. The caller may or may not have a load,
460 // incase it doesn't load the pointer being passed, this check will fail.
461 // So, it's safe to skip the check incase we know that we are dealing with a
462 // recursive call. For example we have a IR given below.
463 //
464 // def fun(ptr %a) {
465 // ...
466 // %loadres = load i32, ptr %a, align 4
467 // %res = call i32 @fun(ptr %a)
468 // ...
469 // }
470 //
471 // def bar(ptr %x) {
472 // ...
473 // %resbar = call i32 @fun(ptr %x)
474 // ...
475 // }
476 //
477 // Since we record processed recursive calls, we check if the current
478 // CallBase has been processed before. If yes it means that it is a
479 // recursive call and we can skip the check just for this call. So, just
480 // return true.
481 if (RecursiveCalls.contains(&CB))
482 return true;
483
484 return isDereferenceableAndAlignedPointer(CB.getArgOperand(Arg->getArgNo()),
485 NeededAlign, Bytes, DL);
486 });
487}
488
489// Try to prove that all Calls to F do not modify the memory pointed to by Arg,
490// using alias analysis local to each caller of F.
493 for (User *U : Arg->getParent()->users()) {
494
495 auto *Call = cast<CallBase>(U);
496
497 MemoryLocation Loc =
498 MemoryLocation::getForArgument(Call, Arg->getArgNo(), nullptr);
499
500 AAResults &AAR = FAM.getResult<AAManager>(*Call->getFunction());
501 // Bail as soon as we find a Call where Arg may be modified.
502 if (isModSet(AAR.getModRefInfo(Call, Loc)))
503 return false;
504 }
505
506 // All Users are Calls which do not modify the Arg.
507 return true;
508}
509
510/// Determine that this argument is safe to promote, and find the argument
511/// parts it can be promoted into.
512static bool findArgParts(Argument *Arg, const DataLayout &DL, AAResults &AAR,
513 unsigned MaxElements, bool IsRecursive,
516 // Quick exit for unused arguments
517 if (Arg->use_empty())
518 return true;
519
520 // We can only promote this argument if all the uses are loads at known
521 // offsets.
522 //
523 // Promoting the argument causes it to be loaded in the caller
524 // unconditionally. This is only safe if we can prove that either the load
525 // would have happened in the callee anyway (ie, there is a load in the entry
526 // block) or the pointer passed in at every call site is guaranteed to be
527 // valid.
528 // In the former case, invalid loads can happen, but would have happened
529 // anyway, in the latter case, invalid loads won't happen. This prevents us
530 // from introducing an invalid load that wouldn't have happened in the
531 // original code.
532
534 Align NeededAlign(1);
535 uint64_t NeededDerefBytes = 0;
536
537 // And if this is a byval argument we also allow to have store instructions.
538 // Only handle in such way arguments with specified alignment;
539 // if it's unspecified, the actual alignment of the argument is
540 // target-specific.
541 bool AreStoresAllowed = Arg->getParamByValType() && Arg->getParamAlign();
542
543 // An end user of a pointer argument is a load or store instruction.
544 // Returns std::nullopt if this load or store is not based on the argument.
545 // Return true if we can promote the instruction, false otherwise.
546 auto HandleEndUser = [&](auto *I, Type *Ty,
547 bool GuaranteedToExecute) -> std::optional<bool> {
548 // Don't promote volatile or atomic instructions.
549 if (!I->isSimple())
550 return false;
551
552 Value *Ptr = I->getPointerOperand();
553 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
554 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
555 /* AllowNonInbounds */ true);
556 if (Ptr != Arg)
557 return std::nullopt;
558
559 if (Offset.getSignificantBits() >= 64)
560 return false;
561
562 TypeSize Size = DL.getTypeStoreSize(Ty);
563 // Don't try to promote scalable types.
564 if (Size.isScalable())
565 return false;
566
567 // If this is a recursive function and one of the types is a pointer,
568 // then promoting it might lead to recursive promotion.
569 if (IsRecursive && Ty->isPointerTy())
570 return false;
571
572 int64_t Off = Offset.getSExtValue();
573 auto Pair = ArgParts.try_emplace(
574 Off, ArgPart{Ty, I->getAlign(), GuaranteedToExecute ? I : nullptr});
575 ArgPart &Part = Pair.first->second;
576 bool OffsetNotSeenBefore = Pair.second;
577
578 // We limit promotion to only promoting up to a fixed number of elements of
579 // the aggregate.
580 if (MaxElements > 0 && ArgParts.size() > MaxElements) {
581 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
582 << "more than " << MaxElements << " parts\n");
583 return false;
584 }
585
586 // For now, we only support loading/storing one specific type at a given
587 // offset.
588 if (Part.Ty != Ty) {
589 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
590 << "accessed as both " << *Part.Ty << " and " << *Ty
591 << " at offset " << Off << "\n");
592 return false;
593 }
594
595 // If this instruction is not guaranteed to execute, and we haven't seen a
596 // load or store at this offset before (or it had lower alignment), then we
597 // need to remember that requirement.
598 // Note that skipping instructions of previously seen offsets is only
599 // correct because we only allow a single type for a given offset, which
600 // also means that the number of accessed bytes will be the same.
601 if (!GuaranteedToExecute &&
602 (OffsetNotSeenBefore || Part.Alignment < I->getAlign())) {
603 // We won't be able to prove dereferenceability for negative offsets.
604 if (Off < 0)
605 return false;
606
607 // If the offset is not aligned, an aligned base pointer won't help.
608 if (!isAligned(I->getAlign(), Off))
609 return false;
610
611 NeededDerefBytes = std::max(NeededDerefBytes, Off + Size.getFixedValue());
612 NeededAlign = std::max(NeededAlign, I->getAlign());
613 }
614
615 Part.Alignment = std::max(Part.Alignment, I->getAlign());
616 return true;
617 };
618
619 // Look for loads and stores that are guaranteed to execute on entry.
620 for (Instruction &I : Arg->getParent()->getEntryBlock()) {
621 std::optional<bool> Res{};
622 if (LoadInst *LI = dyn_cast<LoadInst>(&I))
623 Res = HandleEndUser(LI, LI->getType(), /* GuaranteedToExecute */ true);
624 else if (StoreInst *SI = dyn_cast<StoreInst>(&I))
625 Res = HandleEndUser(SI, SI->getValueOperand()->getType(),
626 /* GuaranteedToExecute */ true);
627 if (Res && !*Res)
628 return false;
629
631 break;
632 }
633
634 // Now look at all loads of the argument. Remember the load instructions
635 // for the aliasing check below.
639 SmallPtrSet<CallBase *, 4> RecursiveCalls;
640 auto AppendUses = [&](const Value *V) {
641 for (const Use &U : V->uses())
642 if (Visited.insert(&U).second)
643 Worklist.push_back(&U);
644 };
645 AppendUses(Arg);
646 while (!Worklist.empty()) {
647 const Use *U = Worklist.pop_back_val();
648 Value *V = U->getUser();
649
650 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
651 if (!GEP->hasAllConstantIndices())
652 return false;
653 AppendUses(V);
654 continue;
655 }
656
657 if (auto *LI = dyn_cast<LoadInst>(V)) {
658 if (!*HandleEndUser(LI, LI->getType(), /* GuaranteedToExecute */ false))
659 return false;
660 Loads.push_back(LI);
661 continue;
662 }
663
664 // Stores are allowed for byval arguments
665 auto *SI = dyn_cast<StoreInst>(V);
666 if (AreStoresAllowed && SI &&
667 U->getOperandNo() == StoreInst::getPointerOperandIndex()) {
668 if (!*HandleEndUser(SI, SI->getValueOperand()->getType(),
669 /* GuaranteedToExecute */ false))
670 return false;
671 continue;
672 // Only stores TO the argument is allowed, all the other stores are
673 // unknown users
674 }
675
676 auto *CB = dyn_cast<CallBase>(V);
677 Value *PtrArg = U->get();
678 if (CB && CB->getCalledFunction() == CB->getFunction()) {
679 if (PtrArg != Arg) {
680 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
681 << "pointer offset is not equal to zero\n");
682 return false;
683 }
684
685 unsigned int ArgNo = Arg->getArgNo();
686 if (U->getOperandNo() != ArgNo) {
687 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
688 << "arg position is different in callee\n");
689 return false;
690 }
691
692 // We limit promotion to only promoting up to a fixed number of elements
693 // of the aggregate.
694 if (MaxElements > 0 && ArgParts.size() > MaxElements) {
695 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
696 << "more than " << MaxElements << " parts\n");
697 return false;
698 }
699
700 RecursiveCalls.insert(CB);
701 continue;
702 }
703 // Unknown user.
704 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
705 << "unknown user " << *V << "\n");
706 return false;
707 }
708
709 if (NeededDerefBytes || NeededAlign > 1) {
710 // Try to prove a required deref / aligned requirement.
711 if (!allCallersPassValidPointerForArgument(Arg, RecursiveCalls, NeededAlign,
712 NeededDerefBytes)) {
713 LLVM_DEBUG(dbgs() << "ArgPromotion of " << *Arg << " failed: "
714 << "not dereferenceable or aligned\n");
715 return false;
716 }
717 }
718
719 if (ArgParts.empty())
720 return true; // No users, this is a dead argument.
721
722 // Sort parts by offset.
723 append_range(ArgPartsVec, ArgParts);
724 sort(ArgPartsVec, llvm::less_first());
725
726 // Make sure the parts are non-overlapping.
727 int64_t Offset = ArgPartsVec[0].first;
728 for (const auto &Pair : ArgPartsVec) {
729 if (Pair.first < Offset)
730 return false; // Overlap with previous part.
731
732 Offset = Pair.first + DL.getTypeStoreSize(Pair.second.Ty);
733 }
734
735 // If store instructions are allowed, the path from the entry of the function
736 // to each load may be not free of instructions that potentially invalidate
737 // the load, and this is an admissible situation.
738 if (AreStoresAllowed)
739 return true;
740
741 // Okay, now we know that the argument is only used by load instructions, and
742 // it is safe to unconditionally perform all of them.
743
744 // If we can determine that no call to the Function modifies the memory region
745 // accessed through Arg, through alias analysis using actual arguments in the
746 // callers, we know that it is guaranteed to be safe to promote the argument.
748 return true;
749
750 // Otherwise, use alias analysis to check if the pointer is guaranteed to not
751 // be modified from entry of the function to each of the load instructions.
752 for (LoadInst *Load : Loads) {
753 // Check to see if the load is invalidated from the start of the block to
754 // the load itself.
755 BasicBlock *BB = Load->getParent();
756
758 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, ModRefInfo::Mod))
759 return false; // Pointer is invalidated!
760
761 // Now check every path from the entry block to the load for transparency.
762 // To do this, we perform a depth first search on the inverse CFG from the
763 // loading block.
764 for (BasicBlock *P : predecessors(BB)) {
765 for (BasicBlock *TranspBB : inverse_depth_first(P))
766 if (AAR.canBasicBlockModify(*TranspBB, Loc))
767 return false;
768 }
769 }
770
771 // If the path from the entry of the function to each load is free of
772 // instructions that potentially invalidate the load, we can make the
773 // transformation!
774 return true;
775}
776
777/// Check if callers and callee agree on how promoted arguments would be
778/// passed.
780 const TargetTransformInfo &TTI) {
781 return all_of(F.uses(), [&](const Use &U) {
782 CallBase *CB = dyn_cast<CallBase>(U.getUser());
783 if (!CB)
784 return false;
785
786 const Function *Caller = CB->getCaller();
787 const Function *Callee = CB->getCalledFunction();
788 return TTI.areTypesABICompatible(Caller, Callee, Types);
789 });
790}
791
792/// PromoteArguments - This method checks the specified function to see if there
793/// are any promotable arguments and if it is safe to promote the function (for
794/// example, all callers are direct). If safe to promote some arguments, it
795/// calls the DoPromotion method.
797 unsigned MaxElements, bool IsRecursive) {
798 // Don't perform argument promotion for naked functions; otherwise we can end
799 // up removing parameters that are seemingly 'not used' as they are referred
800 // to in the assembly.
801 if (F->hasFnAttribute(Attribute::Naked))
802 return nullptr;
803
804 // Make sure that it is local to this module.
805 if (!F->hasLocalLinkage())
806 return nullptr;
807
808 // Don't promote arguments for variadic functions. Adding, removing, or
809 // changing non-pack parameters can change the classification of pack
810 // parameters. Frontends encode that classification at the call site in the
811 // IR, while in the callee the classification is determined dynamically based
812 // on the number of registers consumed so far.
813 if (F->isVarArg())
814 return nullptr;
815
816 // Don't transform functions that receive inallocas, as the transformation may
817 // not be safe depending on calling convention.
818 if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca))
819 return nullptr;
820
821 // First check: see if there are any pointer arguments! If not, quick exit.
822 SmallVector<Argument *, 16> PointerArgs;
823 for (Argument &I : F->args())
824 if (I.getType()->isPointerTy())
825 PointerArgs.push_back(&I);
826 if (PointerArgs.empty())
827 return nullptr;
828
829 // Second check: make sure that all callers are direct callers. We can't
830 // transform functions that have indirect callers. Also see if the function
831 // is self-recursive.
832 for (Use &U : F->uses()) {
833 CallBase *CB = dyn_cast<CallBase>(U.getUser());
834 // Must be a direct call.
835 if (CB == nullptr || !CB->isCallee(&U) ||
836 CB->getFunctionType() != F->getFunctionType())
837 return nullptr;
838
839 // Can't change signature of musttail callee
840 if (CB->isMustTailCall())
841 return nullptr;
842
843 if (CB->getFunction() == F)
844 IsRecursive = true;
845 }
846
847 // Can't change signature of musttail caller
848 // FIXME: Support promoting whole chain of musttail functions
849 for (BasicBlock &BB : *F)
850 if (BB.getTerminatingMustTailCall())
851 return nullptr;
852
853 const DataLayout &DL = F->getDataLayout();
854 auto &AAR = FAM.getResult<AAManager>(*F);
855 const auto &TTI = FAM.getResult<TargetIRAnalysis>(*F);
856
857 // Check to see which arguments are promotable. If an argument is promotable,
858 // add it to ArgsToPromote.
860 unsigned NumArgsAfterPromote = F->getFunctionType()->getNumParams();
861 for (Argument *PtrArg : PointerArgs) {
862 // Replace sret attribute with noalias. This reduces register pressure by
863 // avoiding a register copy.
864 if (PtrArg->hasStructRetAttr()) {
865 unsigned ArgNo = PtrArg->getArgNo();
866 F->removeParamAttr(ArgNo, Attribute::StructRet);
867 F->addParamAttr(ArgNo, Attribute::NoAlias);
868 for (Use &U : F->uses()) {
869 CallBase &CB = cast<CallBase>(*U.getUser());
870 CB.removeParamAttr(ArgNo, Attribute::StructRet);
871 CB.addParamAttr(ArgNo, Attribute::NoAlias);
872 }
873 }
874
875 // If we can promote the pointer to its value.
877
878 if (findArgParts(PtrArg, DL, AAR, MaxElements, IsRecursive, ArgParts,
879 FAM)) {
881 for (const auto &Pair : ArgParts)
882 Types.push_back(Pair.second.Ty);
883
884 if (areTypesABICompatible(Types, *F, TTI)) {
885 NumArgsAfterPromote += ArgParts.size() - 1;
886 ArgsToPromote.insert({PtrArg, std::move(ArgParts)});
887 }
888 }
889 }
890
891 // No promotable pointer arguments.
892 if (ArgsToPromote.empty())
893 return nullptr;
894
895 if (NumArgsAfterPromote > TTI.getMaxNumArgs())
896 return nullptr;
897
898 return doPromotion(F, FAM, ArgsToPromote);
899}
900
903 LazyCallGraph &CG,
904 CGSCCUpdateResult &UR) {
905 bool Changed = false, LocalChange;
906
907 // Iterate until we stop promoting from this SCC.
908 do {
909 LocalChange = false;
910
912 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
913
914 bool IsRecursive = C.size() > 1;
915 for (LazyCallGraph::Node &N : C) {
916 Function &OldF = N.getFunction();
917 Function *NewF = promoteArguments(&OldF, FAM, MaxElements, IsRecursive);
918 if (!NewF)
919 continue;
920 LocalChange = true;
921
922 // Directly substitute the functions in the call graph. Note that this
923 // requires the old function to be completely dead and completely
924 // replaced by the new function. It does no call graph updates, it merely
925 // swaps out the particular function mapped to a particular node in the
926 // graph.
927 C.getOuterRefSCC().replaceNodeFunction(N, *NewF);
928 FAM.clear(OldF, OldF.getName());
929 OldF.eraseFromParent();
930
931 PreservedAnalyses FuncPA;
932 FuncPA.preserveSet<CFGAnalyses>();
933 for (auto *U : NewF->users()) {
934 auto *UserF = cast<CallBase>(U)->getFunction();
935 FAM.invalidate(*UserF, FuncPA);
936 }
937 }
938
939 Changed |= LocalChange;
940 } while (LocalChange);
941
942 if (!Changed)
943 return PreservedAnalyses::all();
944
946 // We've cleared out analyses for deleted functions.
948 // We've manually invalidated analyses for functions we've modified.
950 return PA;
951}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool areTypesABICompatible(ArrayRef< Type * > Types, const Function &F, const TargetTransformInfo &TTI)
Check if callers and callee agree on how promoted arguments would be passed.
static bool findArgParts(Argument *Arg, const DataLayout &DL, AAResults &AAR, unsigned MaxElements, bool IsRecursive, SmallVectorImpl< OffsetAndArgPart > &ArgPartsVec, FunctionAnalysisManager &FAM)
Determine that this argument is safe to promote, and find the argument parts it can be promoted into.
static Function * doPromotion(Function *F, FunctionAnalysisManager &FAM, const DenseMap< Argument *, SmallVector< OffsetAndArgPart, 4 > > &ArgsToPromote)
DoPromotion - This method actually performs the promotion of the specified arguments,...
static Function * promoteArguments(Function *F, FunctionAnalysisManager &FAM, unsigned MaxElements, bool IsRecursive)
PromoteArguments - This method checks the specified function to see if there are any promotable argum...
static Value * createByteGEP(IRBuilderBase &IRB, const DataLayout &DL, Value *Ptr, Type *ResElemTy, int64_t Offset)
static bool isArgUnmodifiedByAllCalls(Argument *Arg, FunctionAnalysisManager &FAM)
static bool allCallersPassValidPointerForArgument(Argument *Arg, SmallPtrSetImpl< CallBase * > &RecursiveCalls, Align NeededAlign, uint64_t NeededDerefBytes)
Return true if we can prove that all callees pass in a valid pointer for the specified function argum...
#define DEBUG_TYPE
This file contains the simple types necessary to represent the attributes associated with functions a...
This is the interface for LLVM's primary stateless and local alias analysis.
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
return RetTy
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
uint64_t Size
Hexagon Common GEP
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.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
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:166
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, const MemoryLocation &Loc, const ModRefInfo Mode)
Check if it is possible for the execution of the specified instructions to mod(according to the mode)...
bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc)
Check if it is possible for execution of the specified basic block to modify the location Loc.
Class for arbitrary precision integers.
Definition: APInt.h:78
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:49
an instruction to allocate memory on the stack
Definition: Instructions.h:63
void setAlignment(Align Align)
Definition: Instructions.h:128
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
void clear(IRUnitT &IR, llvm::StringRef Name)
Clear any cached analysis results for a single unit of IR.
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
const Function * getParent() const
Definition: Argument.h:43
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition: Argument.h:49
Type * getParamByValType() const
If this is a byval argument, return its type.
Definition: Function.cpp:235
MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition: Function.cpp:226
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A function analysis which provides an AssumptionCache.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
std::optional< std::pair< unsigned, std::optional< unsigned > > > getAllocSizeArgs() const
static Attribute getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg, const std::optional< unsigned > &NumElemsArg)
Definition: Attributes.cpp:292
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const Instruction & front() const
Definition: BasicBlock.h:471
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1411
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Removes the attribute from the given argument.
Definition: InstrTypes.h:1549
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1349
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1407
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Definition: InstrTypes.h:1269
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
Definition: InstrTypes.h:1360
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1428
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Definition: InstrTypes.h:1275
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1207
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1425
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1502
Function * getCaller()
Helper to get the caller (the parent function).
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
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:194
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:226
unsigned size() const
Definition: DenseMap.h:99
bool empty() const
Definition: DenseMap.h:98
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
A proxy from a FunctionAnalysisManager to an SCC.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:641
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:173
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition: Function.h:761
const BasicBlock & getEntryBlock() const
Definition: Function.h:809
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:353
iterator begin()
Definition: Function.h:853
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Function.cpp:458
arg_iterator arg_begin()
Definition: Function.h:868
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:356
void setIsNewDbgInfoFormat(bool NewVal)
Definition: Function.cpp:105
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:860
void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1799
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:91
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1796
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1830
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:2002
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1849
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition: IRBuilder.h:499
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1764
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:368
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Invoke instruction.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
A node in the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
An instruction for reading from memory.
Definition: Instructions.h:176
static unsigned getPointerOperandIndex()
Definition: Instructions.h:257
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:363
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:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
static unsigned getPointerOperandIndex()
Definition: Instructions.h:383
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
bool use_empty() const
Definition: Value.h:344
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
self_iterator getIterator()
Definition: ilist_node.h:132
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void updateMinLegalVectorWidthAttr(Function &Fn, uint64_t Width)
Update min-legal-vector-width if it is in Attribute and less than Width.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1739
void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition: Alignment.h:145
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition: Loads.cpp:215
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
iterator_range< idf_iterator< T > > inverse_depth_first(const T &G)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
Definition: Local.cpp:561
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto predecessors(const MachineBasicBlock *BB)
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1467