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