LLVM 24.0.0git
GlobalOpt.cpp
Go to the documentation of this file.
1//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 transforms simple global variables that never have their address
10// taken. If obviously true, it marks read/write globals as constant, deletes
11// variables only stored to, etc.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/Twine.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalAlias.h"
41#include "llvm/IR/GlobalValue.h"
43#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/Operator.h"
51#include "llvm/IR/Type.h"
52#include "llvm/IR/Use.h"
53#include "llvm/IR/User.h"
54#include "llvm/IR/Value.h"
55#include "llvm/IR/ValueHandle.h"
59#include "llvm/Support/Debug.h"
62#include "llvm/Transforms/IPO.h"
67#include <cassert>
68#include <cstdint>
69#include <optional>
70#include <utility>
71#include <vector>
72
73using namespace llvm;
74
75#define DEBUG_TYPE "globalopt"
76
77STATISTIC(NumMarked , "Number of globals marked constant");
78STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
79STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
80STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
81STATISTIC(NumDeleted , "Number of globals deleted");
82STATISTIC(NumGlobUses , "Number of global uses devirtualized");
83STATISTIC(NumLocalized , "Number of globals localized");
84STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
85STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
86STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
87STATISTIC(NumNestRemoved , "Number of nest attributes removed");
88STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
89STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
90STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
91STATISTIC(NumAtExitRemoved, "Number of atexit handlers removed");
92STATISTIC(NumInternalFunc, "Number of internal functions");
93STATISTIC(NumColdCC, "Number of functions marked coldcc");
94STATISTIC(NumIFuncsResolved, "Number of statically resolved IFuncs");
95STATISTIC(NumIFuncsDeleted, "Number of IFuncs removed");
96
97static cl::opt<bool>
98 OptimizeNonFMVCallers("optimize-non-fmv-callers",
99 cl::desc("Statically resolve calls to versioned "
100 "functions from non-versioned callers."),
101 cl::init(true), cl::Hidden);
102
104 "max-ifunc-versions", cl::Hidden, cl::init(5),
105 cl::desc("Maximum number of caller/callee versions that is allowed for "
106 "using the expensive (cubic) static resolution algorithm."));
107
108static cl::opt<bool>
109 EnableColdCCStressTest("enable-coldcc-stress-test",
110 cl::desc("Enable stress test of coldcc by adding "
111 "calling conv to all internal functions."),
112 cl::init(false), cl::Hidden);
113
115 "coldcc-rel-freq", cl::Hidden, cl::init(2),
116 cl::desc(
117 "Maximum block frequency, expressed as a percentage of caller's "
118 "entry frequency, for a call site to be considered cold for enabling "
119 "coldcc"));
120
121/// Is this global variable possibly used by a leak checker as a root? If so,
122/// we might not really want to eliminate the stores to it.
124 // A global variable is a root if it is a pointer, or could plausibly contain
125 // a pointer. There are two challenges; one is that we could have a struct
126 // the has an inner member which is a pointer. We recurse through the type to
127 // detect these (up to a point). The other is that we may actually be a union
128 // of a pointer and another type, and so our LLVM type is an integer which
129 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
130 // potentially contained here.
131
132 if (GV->hasPrivateLinkage())
133 return false;
134
136 Types.push_back(GV->getValueType());
137
138 unsigned Limit = 20;
139 do {
140 Type *Ty = Types.pop_back_val();
141 switch (Ty->getTypeID()) {
142 default: break;
144 return true;
147 if (cast<VectorType>(Ty)->getElementType()->isPointerTy())
148 return true;
149 break;
150 case Type::ArrayTyID:
151 Types.push_back(cast<ArrayType>(Ty)->getElementType());
152 break;
153 case Type::StructTyID: {
154 StructType *STy = cast<StructType>(Ty);
155 if (STy->isOpaque()) return true;
156 for (Type *InnerTy : STy->elements()) {
157 if (isa<PointerType>(InnerTy)) return true;
158 if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) ||
159 isa<VectorType>(InnerTy))
160 Types.push_back(InnerTy);
161 }
162 break;
163 }
164 }
165 if (--Limit == 0) return true;
166 } while (!Types.empty());
167 return false;
168}
169
170/// Given a value that is stored to a global but never read, determine whether
171/// it's safe to remove the store and the chain of computation that feeds the
172/// store.
174 Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
175 do {
176 if (isa<Constant>(V))
177 return true;
178 if (!V->hasOneUse())
179 return false;
180 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
182 return false;
183 if (isAllocationFn(V, GetTLI))
184 return true;
185
187 if (I->mayHaveSideEffects())
188 return false;
190 if (!GEP->hasAllConstantIndices())
191 return false;
192 } else if (I->getNumOperands() != 1) {
193 return false;
194 }
195
196 V = I->getOperand(0);
197 } while (true);
198}
199
200/// This GV is a pointer root. Loop over all users of the global and clean up
201/// any that obviously don't assign the global a value that isn't dynamically
202/// allocated.
203static bool
206 // A brief explanation of leak checkers. The goal is to find bugs where
207 // pointers are forgotten, causing an accumulating growth in memory
208 // usage over time. The common strategy for leak checkers is to explicitly
209 // allow the memory pointed to by globals at exit. This is popular because it
210 // also solves another problem where the main thread of a C++ program may shut
211 // down before other threads that are still expecting to use those globals. To
212 // handle that case, we expect the program may create a singleton and never
213 // destroy it.
214
215 bool Changed = false;
216
217 // If Dead[n].first is the only use of a malloc result, we can delete its
218 // chain of computation and the store to the global in Dead[n].second.
220
221 SmallVector<User *> Worklist(GV->users());
222 // Constants can't be pointers to dynamically allocated memory.
223 while (!Worklist.empty()) {
224 User *U = Worklist.pop_back_val();
225 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
226 Value *V = SI->getValueOperand();
227 if (isa<Constant>(V)) {
228 Changed = true;
229 SI->eraseFromParent();
230 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
231 if (I->hasOneUse())
232 Dead.push_back(std::make_pair(I, SI));
233 }
234 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
235 if (isa<Constant>(MSI->getValue())) {
236 Changed = true;
237 MSI->eraseFromParent();
238 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
239 if (I->hasOneUse())
240 Dead.push_back(std::make_pair(I, MSI));
241 }
242 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
243 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
244 if (MemSrc && MemSrc->isConstant()) {
245 Changed = true;
246 MTI->eraseFromParent();
247 } else if (Instruction *I = dyn_cast<Instruction>(MTI->getSource())) {
248 if (I->hasOneUse())
249 Dead.push_back(std::make_pair(I, MTI));
250 }
251 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
252 if (isa<GEPOperator>(CE))
253 append_range(Worklist, CE->users());
254 }
255 }
256
257 for (const auto &[Inst, Store] : Dead) {
258 if (IsSafeComputationToRemove(Inst, GetTLI)) {
259 Store->eraseFromParent();
260 Instruction *I = Inst;
261 do {
262 if (isAllocationFn(I, GetTLI))
263 break;
264 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
265 if (!J)
266 break;
267 I->eraseFromParent();
268 I = J;
269 } while (true);
270 I->eraseFromParent();
271 Changed = true;
272 }
273 }
274
276 return Changed;
277}
278
279/// We just marked GV constant. Loop over all users of the global, cleaning up
280/// the obvious ones. This is largely just a quick scan over the use list to
281/// clean up the easy and obvious cruft. This returns true if it made a change.
283 const DataLayout &DL) {
285 SmallVector<User *, 8> WorkList(GV->users());
287 bool Changed = false;
288
289 SmallVector<WeakTrackingVH> MaybeDeadInsts;
290 auto EraseFromParent = [&](Instruction *I) {
291 for (Value *Op : I->operands())
292 if (auto *OpI = dyn_cast<Instruction>(Op))
293 MaybeDeadInsts.push_back(OpI);
294 I->eraseFromParent();
295 Changed = true;
296 };
297 while (!WorkList.empty()) {
298 User *U = WorkList.pop_back_val();
299 if (!Visited.insert(U).second)
300 continue;
301
302 if (auto *BO = dyn_cast<BitCastOperator>(U))
303 append_range(WorkList, BO->users());
304 if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U))
305 append_range(WorkList, ASC->users());
306 else if (auto *GEP = dyn_cast<GEPOperator>(U))
307 append_range(WorkList, GEP->users());
308 else if (auto *LI = dyn_cast<LoadInst>(U)) {
309 // A load from a uniform value is always the same, regardless of any
310 // applied offset.
311 Type *Ty = LI->getType();
313 LI->replaceAllUsesWith(Res);
314 EraseFromParent(LI);
315 continue;
316 }
317
318 Value *PtrOp = LI->getPointerOperand();
319 APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
321 DL, Offset, /* AllowNonInbounds */ true);
323 if (II->getIntrinsicID() == Intrinsic::threadlocal_address)
324 PtrOp = II->getArgOperand(0);
325 }
326 if (PtrOp == GV) {
327 if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) {
328 LI->replaceAllUsesWith(Value);
329 EraseFromParent(LI);
330 }
331 }
332 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
333 // Store must be unreachable or storing Init into the global.
334 EraseFromParent(SI);
335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (getUnderlyingObject(MI->getRawDest()) == GV)
337 EraseFromParent(MI);
338 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
339 if (II->getIntrinsicID() == Intrinsic::threadlocal_address)
340 append_range(WorkList, II->users());
341 }
342 }
343
344 Changed |=
347 return Changed;
348}
349
350/// Part of the global at a specific offset, which is only accessed through
351/// loads and stores with the given type.
355 bool IsLoaded = false;
356 bool IsStored = false;
357};
358
359/// Look at all uses of the global and determine which (offset, type) pairs it
360/// can be split into.
362 GlobalVariable *GV, const DataLayout &DL) {
363 SmallVector<Use *, 16> Worklist;
365 auto AppendUses = [&](Value *V) {
366 for (Use &U : V->uses())
367 if (Visited.insert(&U).second)
368 Worklist.push_back(&U);
369 };
370 AppendUses(GV);
371 while (!Worklist.empty()) {
372 Use *U = Worklist.pop_back_val();
373 User *V = U->getUser();
374
375 auto *GEP = dyn_cast<GEPOperator>(V);
377 (GEP && GEP->hasAllConstantIndices())) {
378 AppendUses(V);
379 continue;
380 }
381
382 if (Value *Ptr = getLoadStorePointerOperand(V)) {
383 // This is storing the global address into somewhere, not storing into
384 // the global.
385 if (isa<StoreInst>(V) && U->getOperandNo() == 0)
386 return false;
387
388 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
389 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
390 /* AllowNonInbounds */ true);
391 if (Ptr != GV || Offset.getActiveBits() >= 64)
392 return false;
393
394 // TODO: We currently require that all accesses at a given offset must
395 // use the same type. This could be relaxed.
396 Type *Ty = getLoadStoreType(V);
397 const auto &[It, Inserted] =
398 Parts.try_emplace(Offset.getZExtValue(), GlobalPart{Ty});
399 if (Ty != It->second.Ty)
400 return false;
401
402 if (Inserted) {
403 It->second.Initializer =
405 if (!It->second.Initializer) {
406 LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of "
407 << *GV << " with type " << *Ty << " at offset "
408 << Offset.getZExtValue());
409 return false;
410 }
411 }
412
413 // Scalable types not currently supported.
414 if (Ty->isScalableTy())
415 return false;
416
417 auto IsStored = [](Value *V, Constant *Initializer) {
418 auto *SI = dyn_cast<StoreInst>(V);
419 if (!SI)
420 return false;
421
422 Constant *StoredConst = dyn_cast<Constant>(SI->getOperand(0));
423 if (!StoredConst)
424 return true;
425
426 // Don't consider stores that only write the initializer value.
427 return Initializer != StoredConst;
428 };
429
430 It->second.IsLoaded |= isa<LoadInst>(V);
431 It->second.IsStored |= IsStored(V, It->second.Initializer);
432 continue;
433 }
434
435 // Ignore dead constant users.
436 if (auto *C = dyn_cast<Constant>(V)) {
438 return false;
439 continue;
440 }
441
442 // Unknown user.
443 return false;
444 }
445
446 return true;
447}
448
449/// Copy over the debug info for a variable to its SRA replacements.
451 uint64_t FragmentOffsetInBits,
452 uint64_t FragmentSizeInBits,
453 uint64_t VarSize) {
455 GV->getDebugInfo(GVs);
456 for (auto *GVE : GVs) {
457 DIVariable *Var = GVE->getVariable();
458 DIExpression *Expr = GVE->getExpression();
459 int64_t CurVarOffsetInBytes = 0;
460 uint64_t CurVarOffsetInBits = 0;
461 uint64_t FragmentEndInBits = FragmentOffsetInBits + FragmentSizeInBits;
462
463 // Calculate the offset (Bytes), Continue if unknown.
464 if (!Expr->extractIfOffset(CurVarOffsetInBytes))
465 continue;
466
467 // Ignore negative offset.
468 if (CurVarOffsetInBytes < 0)
469 continue;
470
471 // Convert offset to bits.
472 CurVarOffsetInBits = CHAR_BIT * (uint64_t)CurVarOffsetInBytes;
473
474 // Current var starts after the fragment, ignore.
475 if (CurVarOffsetInBits >= FragmentEndInBits)
476 continue;
477
478 uint64_t CurVarSize = Var->getType()->getSizeInBits();
479 uint64_t CurVarEndInBits = CurVarOffsetInBits + CurVarSize;
480 // Current variable ends before start of fragment, ignore.
481 if (CurVarSize != 0 && /* CurVarSize is known */
482 CurVarEndInBits <= FragmentOffsetInBits)
483 continue;
484
485 // Current variable fits in (not greater than) the fragment,
486 // does not need fragment expression.
487 if (CurVarSize != 0 && /* CurVarSize is known */
488 CurVarOffsetInBits >= FragmentOffsetInBits &&
489 CurVarEndInBits <= FragmentEndInBits) {
490 uint64_t CurVarOffsetInFragment =
491 (CurVarOffsetInBits - FragmentOffsetInBits) / 8;
492 if (CurVarOffsetInFragment != 0)
493 Expr = DIExpression::get(Expr->getContext(), {dwarf::DW_OP_plus_uconst,
494 CurVarOffsetInFragment});
495 else
496 Expr = DIExpression::get(Expr->getContext(), {});
497 auto *NGVE =
498 DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
499 NGV->addDebugInfo(NGVE);
500 continue;
501 }
502 // Current variable does not fit in single fragment,
503 // emit a fragment expression.
504 if (FragmentSizeInBits < VarSize) {
505 if (CurVarOffsetInBits > FragmentOffsetInBits)
506 continue;
507 uint64_t CurVarFragmentOffsetInBits =
508 FragmentOffsetInBits - CurVarOffsetInBits;
509 uint64_t CurVarFragmentSizeInBits = FragmentSizeInBits;
510 if (CurVarSize != 0 && CurVarEndInBits < FragmentEndInBits)
511 CurVarFragmentSizeInBits -= (FragmentEndInBits - CurVarEndInBits);
512 if (CurVarOffsetInBits)
513 Expr = DIExpression::get(Expr->getContext(), {});
515 Expr, CurVarFragmentOffsetInBits, CurVarFragmentSizeInBits))
516 Expr = *E;
517 else
518 continue;
519 }
520 auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
521 NGV->addDebugInfo(NGVE);
522 }
523}
524
525/// Perform scalar replacement of aggregates on the specified global variable.
526/// This opens the door for other optimizations by exposing the behavior of the
527/// program in a more fine-grained way. We have determined that this
528/// transformation is safe already. We return the first global variable we
529/// insert so that the caller can reprocess it.
531 assert(GV->hasLocalLinkage());
532
533 // Collect types to split into.
535 if (!collectSRATypes(Parts, GV, DL) || Parts.empty())
536 return nullptr;
537
538 // Make sure we don't SRA back to the same type.
539 if (Parts.size() == 1 && Parts.begin()->second.Ty == GV->getValueType())
540 return nullptr;
541
542 // Don't perform SRA if we would have to split into many globals. Ignore
543 // parts that are either only loaded or only stored, because we expect them
544 // to be optimized away.
545 unsigned NumParts = count_if(Parts, [](const auto &Pair) {
546 return Pair.second.IsLoaded && Pair.second.IsStored;
547 });
548 if (NumParts > 16)
549 return nullptr;
550
551 // Sort by offset.
553 for (const auto &Pair : Parts) {
554 TypesVector.push_back(
555 {Pair.first, Pair.second.Ty, Pair.second.Initializer});
556 }
557 sort(TypesVector, llvm::less_first());
558
559 // Check that the types are non-overlapping.
560 uint64_t Offset = 0;
561 for (const auto &[OffsetForTy, Ty, _] : TypesVector) {
562 // Overlaps with previous type.
563 if (OffsetForTy < Offset)
564 return nullptr;
565
566 Offset = OffsetForTy + DL.getTypeAllocSize(Ty);
567 }
568
569 // Some accesses go beyond the end of the global, don't bother.
570 if (Offset > GV->getGlobalSize(DL))
571 return nullptr;
572
573 LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
574
575 // Get the alignment of the global, either explicit or target-specific.
576 Align StartAlignment =
577 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
578 uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType());
579
580 // Create replacement globals.
582 unsigned NameSuffix = 0;
583 for (auto &[OffsetForTy, Ty, Initializer] : TypesVector) {
586 Initializer, GV->getName() + "." + Twine(NameSuffix++), GV,
588 // Start out by copying attributes from the original, including alignment.
589 NGV->copyAttributesFrom(GV);
590 NewGlobals.insert({OffsetForTy, NGV});
591
592 // Calculate the known alignment of the field. If the original aggregate
593 // had 256 byte alignment for example, then the element at a given offset
594 // may also have a known alignment, and something might depend on that:
595 // propagate info to each field.
596 Align NewAlign = commonAlignment(StartAlignment, OffsetForTy);
597 NGV->setAlignment(NewAlign);
598
599 // Copy over the debug info for the variable.
600 transferSRADebugInfo(GV, NGV, OffsetForTy * 8,
601 DL.getTypeAllocSizeInBits(Ty), VarSize);
602 }
603
604 // Replace uses of the original global with uses of the new global.
608 auto AppendUsers = [&](Value *V) {
609 for (User *U : V->users())
610 if (Visited.insert(U).second)
611 Worklist.push_back(U);
612 };
613 AppendUsers(GV);
614 while (!Worklist.empty()) {
615 Value *V = Worklist.pop_back_val();
617 isa<GEPOperator>(V)) {
618 AppendUsers(V);
619 if (isa<Instruction>(V))
620 DeadInsts.push_back(V);
621 continue;
622 }
623
624 if (Value *Ptr = getLoadStorePointerOperand(V)) {
625 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
626 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
627 /* AllowNonInbounds */ true);
628 assert(Ptr == GV && "Load/store must be from/to global");
629 GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()];
630 assert(NGV && "Must have replacement global for this offset");
631
632 // Update the pointer operand and recalculate alignment.
633 Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V));
634 Align NewAlign =
636
637 if (auto *LI = dyn_cast<LoadInst>(V)) {
638 LI->setOperand(0, NGV);
639 LI->setAlignment(NewAlign);
640 } else {
641 auto *SI = cast<StoreInst>(V);
642 SI->setOperand(1, NGV);
643 SI->setAlignment(NewAlign);
644 }
645 continue;
646 }
647
649 "Other users can only be dead constants");
650 }
651
652 // Delete old instructions and global.
655 GV->eraseFromParent();
656 ++NumSRA;
657
658 assert(NewGlobals.size() > 0);
659 return NewGlobals.begin()->second;
660}
661
663 bool Changed = false;
664 SmallVector<User *, 8> Users(V->user_begin(), V->user_end());
665 for (User *U : Users) {
667 // Uses are non-trapping if null pointer is considered valid.
668 // Non address-space 0 globals are already pruned by the caller.
669 if (NullPointerIsDefined(I->getFunction()))
670 return false;
671 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
672 LI->setOperand(0, NewV);
673 Changed = true;
674 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
675 if (SI->getOperand(1) == V) {
676 SI->setOperand(1, NewV);
677 Changed = true;
678 }
679 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
681 if (CB->getCalledOperand() == V) {
682 // Calling through the pointer! Turn into a direct call, but be careful
683 // that the pointer is not also being passed as an argument.
684 CB->setCalledOperand(NewV);
685 Changed = true;
686 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
687 if (CB->getArgOperand(i) == V)
688 CB->setArgOperand(i, NewV);
689 }
692 CI, ConstantExpr::getAddrSpaceCast(NewV, CI->getType()));
693 if (CI->use_empty()) {
694 Changed = true;
695 CI->eraseFromParent();
696 }
697 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
698 // Should handle GEP here.
700 Idxs.reserve(GEPI->getNumOperands()-1);
701 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
702 i != e; ++i)
703 if (Constant *C = dyn_cast<Constant>(*i))
704 Idxs.push_back(C);
705 else
706 break;
707 if (Idxs.size() == GEPI->getNumOperands() - 1) {
709 V->getDataLayout(), GEPI->getSourceElementType(), NewV, Idxs))
711 }
712 if (GEPI->use_empty()) {
713 Changed = true;
714 GEPI->eraseFromParent();
715 }
716 }
717 }
718
719 return Changed;
720}
721
722/// The specified global has only one non-null value stored into it. If there
723/// are uses of the loaded value that would trap if the loaded value is
724/// dynamically null, then we know that they cannot be reachable with a null
725/// optimize away the load.
727 GlobalVariable *GV, Constant *LV, const DataLayout &DL,
729 bool Changed = false;
730
731 // Keep track of whether we are able to remove all the uses of the global
732 // other than the store that defines it.
733 bool AllNonStoreUsesGone = true;
734
735 // Replace all uses of loads with uses of uses of the stored value.
736 for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) {
737 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
739 // If we were able to delete all uses of the loads
740 if (LI->use_empty()) {
741 LI->eraseFromParent();
742 Changed = true;
743 } else {
744 AllNonStoreUsesGone = false;
745 }
746 } else if (isa<StoreInst>(GlobalUser)) {
747 // Ignore the store that stores "LV" to the global.
748 assert(GlobalUser->getOperand(1) == GV &&
749 "Must be storing *to* the global");
750 } else {
751 AllNonStoreUsesGone = false;
752 }
753 }
754
755 if (Changed) {
756 LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
757 << "\n");
758 ++NumGlobUses;
759 }
760
761 // If we nuked all of the loads, then none of the stores are needed either,
762 // nor is the global.
763 if (AllNonStoreUsesGone) {
764 if (isLeakCheckerRoot(GV)) {
765 Changed |= CleanupPointerRootUsers(GV, GetTLI);
766 } else {
767 Changed = true;
769 }
770 if (GV->use_empty()) {
771 LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
772 Changed = true;
773 GV->eraseFromParent();
774 ++NumDeleted;
775 }
776 }
777 return Changed;
778}
779
780// Try to optimize globals based on the knowledge that only one value (besides
781// its initializer) is ever stored to the global.
782static bool
784 const DataLayout &DL,
786 // If we are dealing with a pointer global that is initialized to null and
787 // only has one (non-null) value stored into it, then we can optimize any
788 // users of the loaded value (often calls and loads) that would trap if the
789 // value was null.
790 if (GV->getInitializer()->getType()->isPointerTy() &&
791 GV->getInitializer()->isNullValue() &&
792 StoredOnceVal->getType()->isPointerTy() &&
794 nullptr /* F */,
796 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
797 // Optimize away any trapping uses of the loaded value.
798 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI))
799 return true;
800 }
801 }
802
803 return false;
804}
805
806/// At this point, we have learned that the only two values ever stored into GV
807/// are its initializer and OtherVal. See if we can shrink the global into a
808/// boolean and select between the two values whenever it is used. This exposes
809/// the values to other scalar optimizations.
811 Type *GVElType = GV->getValueType();
812
813 // If GVElType is already i1, it is already shrunk. If the type of the GV is
814 // an FP value, pointer or vector, don't do this optimization because a select
815 // between them is very expensive and unlikely to lead to later
816 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
817 // where v1 and v2 both require constant pool loads, a big loss.
818 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
819 GVElType->isFloatingPointTy() ||
820 GVElType->isPointerTy() || GVElType->isVectorTy())
821 return false;
822
823 // Walk the use list of the global seeing if all the uses are load or store.
824 // If there is anything else, bail out.
825 for (User *U : GV->users()) {
826 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
827 return false;
828 if (getLoadStoreType(U) != GVElType)
829 return false;
830 }
831
832 LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
833
834 // Create the new global, initializing it to false.
836 false,
839 GV->getName()+".b",
840 GV->getThreadLocalMode(),
841 GV->getType()->getAddressSpace());
842 NewGV->copyAttributesFrom(GV);
843 GV->getParent()->insertGlobalVariable(GV->getIterator(), NewGV);
844
845 Constant *InitVal = GV->getInitializer();
846 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
847 "No reason to shrink to bool!");
848
850 GV->getDebugInfo(GVs);
851
852 // If initialized to zero and storing one into the global, we can use a cast
853 // instead of a select to synthesize the desired value.
854 bool IsOneZero = false;
855 bool EmitOneOrZero = true;
856 auto *CI = dyn_cast<ConstantInt>(OtherVal);
857 if (CI && CI->getValue().getActiveBits() <= 64) {
858 IsOneZero = InitVal->isNullValue() && CI->isOne();
859
860 auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer());
861 if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
862 uint64_t ValInit = CIInit->getZExtValue();
863 uint64_t ValOther = CI->getZExtValue();
864 uint64_t ValMinus = ValOther - ValInit;
865
866 for(auto *GVe : GVs){
867 DIGlobalVariable *DGV = GVe->getVariable();
868 DIExpression *E = GVe->getExpression();
869 const DataLayout &DL = GV->getDataLayout();
870 unsigned SizeInOctets = NewGV->getGlobalSize(DL);
871
872 // It is expected that the address of global optimized variable is on
873 // top of the stack. After optimization, value of that variable will
874 // be ether 0 for initial value or 1 for other value. The following
875 // expression should return constant integer value depending on the
876 // value at global object address:
877 // val * (ValOther - ValInit) + ValInit:
878 // DW_OP_deref DW_OP_constu <ValMinus>
879 // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value
881 dwarf::DW_OP_deref_size, SizeInOctets,
882 dwarf::DW_OP_constu, ValMinus,
883 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
884 dwarf::DW_OP_plus};
885 bool WithStackValue = true;
886 E = DIExpression::prependOpcodes(E, Ops, WithStackValue);
889 NewGV->addDebugInfo(DGVE);
890 }
891 EmitOneOrZero = false;
892 }
893 }
894
895 if (EmitOneOrZero) {
896 // FIXME: This will only emit address for debugger on which will
897 // be written only 0 or 1.
898 for(auto *GV : GVs)
899 NewGV->addDebugInfo(GV);
900 }
901
902 while (!GV->use_empty()) {
904 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
905 // Change the store into a boolean store.
906 bool StoringOther = SI->getOperand(0) == OtherVal;
907 // Only do this if we weren't storing a loaded value.
908 Value *StoreVal;
909 if (StoringOther || SI->getOperand(0) == InitVal) {
910 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
911 StoringOther);
912 } else {
913 // Otherwise, we are storing a previously loaded copy. To do this,
914 // change the copy from copying the original value to just copying the
915 // bool.
916 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
917
918 // If we've already replaced the input, StoredVal will be a cast or
919 // select instruction. If not, it will be a load of the original
920 // global.
921 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
922 assert(LI->getOperand(0) == GV && "Not a copy!");
923 // Insert a new load, to preserve the saved value.
924 StoreVal =
925 new LoadInst(NewGV->getValueType(), NewGV, LI->getName() + ".b",
926 false, Align(1), LI->getOrdering(),
927 LI->getSyncScopeID(), LI->getIterator());
928 cast<LoadInst>(StoreVal)->setDebugLoc(LI->getDebugLoc());
929 } else {
930 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
931 "This is not a form that we understand!");
932 StoreVal = StoredVal->getOperand(0);
933 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
934 }
935 }
936 StoreInst *NSI =
937 new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(),
938 SI->getSyncScopeID(), SI->getIterator());
939 NSI->setDebugLoc(SI->getDebugLoc());
940 } else {
941 // Change the load into a load of bool then a select.
942 LoadInst *LI = cast<LoadInst>(UI);
943 LoadInst *NLI = new LoadInst(
944 NewGV->getValueType(), NewGV, LI->getName() + ".b", false, Align(1),
945 LI->getOrdering(), LI->getSyncScopeID(), LI->getIterator());
946 Instruction *NSI;
947 if (IsOneZero)
948 NSI = new ZExtInst(NLI, LI->getType(), "", LI->getIterator());
949 else {
950 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI->getIterator());
952 }
953 NSI->takeName(LI);
954 // Since LI is split into two instructions, NLI and NSI both inherit the
955 // same DebugLoc
956 NLI->setDebugLoc(LI->getDebugLoc());
957 NSI->setDebugLoc(LI->getDebugLoc());
958 LI->replaceAllUsesWith(NSI);
959 }
960 UI->eraseFromParent();
961 }
962
963 // Retain the name of the old global variable. People who are debugging their
964 // programs may expect these variables to be named the same.
965 NewGV->takeName(GV);
966 GV->eraseFromParent();
967 return true;
968}
969
970static bool
972 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
973 function_ref<void(Function &)> DeleteFnCallback = nullptr) {
975
976 if (!GV.isDiscardableIfUnused() && !GV.isDeclaration())
977 return false;
978
979 if (const Comdat *C = GV.getComdat())
980 if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C))
981 return false;
982
983 bool Dead;
984 if (auto *F = dyn_cast<Function>(&GV))
985 Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead();
986 else
987 Dead = GV.use_empty();
988 if (!Dead)
989 return false;
990
991 LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n");
992 if (auto *F = dyn_cast<Function>(&GV)) {
993 if (DeleteFnCallback)
994 DeleteFnCallback(*F);
995 }
997 GV.eraseFromParent();
998 ++NumDeleted;
999 return true;
1000}
1001
1003 const Function *F, GlobalValue *GV,
1004 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1005 // Find all uses of GV. We expect them all to be in F, and if we can't
1006 // identify any of the uses we bail out.
1007 //
1008 // On each of these uses, identify if the memory that GV points to is
1009 // used/required/live at the start of the function. If it is not, for example
1010 // if the first thing the function does is store to the GV, the GV can
1011 // possibly be demoted.
1012 //
1013 // We don't do an exhaustive search for memory operations - simply look
1014 // through bitcasts as they're quite common and benign.
1015 const DataLayout &DL = GV->getDataLayout();
1018 for (auto *U : GV->users()) {
1020 if (!I)
1021 return false;
1022 assert(I->getParent()->getParent() == F);
1023
1024 if (auto *LI = dyn_cast<LoadInst>(I))
1025 Loads.push_back(LI);
1026 else if (auto *SI = dyn_cast<StoreInst>(I))
1027 Stores.push_back(SI);
1028 else
1029 return false;
1030 }
1031
1032 // We have identified all uses of GV into loads and stores. Now check if all
1033 // of them are known not to depend on the value of the global at the function
1034 // entry point. We do this by ensuring that every load is dominated by at
1035 // least one store.
1036 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1037
1038 // The below check is quadratic. Check we're not going to do too many tests.
1039 // FIXME: Even though this will always have worst-case quadratic time, we
1040 // could put effort into minimizing the average time by putting stores that
1041 // have been shown to dominate at least one load at the beginning of the
1042 // Stores array, making subsequent dominance checks more likely to succeed
1043 // early.
1044 //
1045 // The threshold here is fairly large because global->local demotion is a
1046 // very powerful optimization should it fire.
1047 const unsigned Threshold = 100;
1048 if (Loads.size() * Stores.size() > Threshold)
1049 return false;
1050
1051 for (auto *L : Loads) {
1052 auto *LTy = L->getType();
1053 if (none_of(Stores, [&](const StoreInst *S) {
1054 auto *STy = S->getValueOperand()->getType();
1055 // The load is only dominated by the store if DomTree says so
1056 // and the number of bits loaded in L is less than or equal to
1057 // the number of bits stored in S.
1058 return DT.dominates(S, L) &&
1059 DL.getTypeStoreSize(LTy).getFixedValue() <=
1060 DL.getTypeStoreSize(STy).getFixedValue();
1061 }))
1062 return false;
1063 }
1064 // All loads have known dependences inside F, so the global can be localized.
1065 return true;
1066}
1067
1068// For a global variable with one store, if the store dominates any loads,
1069// those loads will always load the stored value (as opposed to the
1070// initializer), even in the presence of recursion.
1072 GlobalVariable *GV, const StoreInst *StoredOnceStore,
1073 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1074 const Value *StoredOnceValue = StoredOnceStore->getValueOperand();
1075 // We can do this optimization for non-constants in nosync + norecurse
1076 // functions, but globals used in exactly one norecurse functions are already
1077 // promoted to an alloca.
1078 if (!isa<Constant>(StoredOnceValue))
1079 return false;
1080 const Function *F = StoredOnceStore->getFunction();
1082 for (User *U : GV->users()) {
1083 if (auto *LI = dyn_cast<LoadInst>(U)) {
1084 if (LI->getFunction() == F &&
1085 LI->getType() == StoredOnceValue->getType() && LI->isSimple())
1086 Loads.push_back(LI);
1087 }
1088 }
1089 // Only compute DT if we have any loads to examine.
1090 bool MadeChange = false;
1091 if (!Loads.empty()) {
1092 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1093 for (auto *LI : Loads) {
1094 if (DT.dominates(StoredOnceStore, LI)) {
1095 LI->replaceAllUsesWith(const_cast<Value *>(StoredOnceValue));
1096 LI->eraseFromParent();
1097 MadeChange = true;
1098 }
1099 }
1100 }
1101 return MadeChange;
1102}
1103
1104/// Analyze the specified global variable and optimize
1105/// it if possible. If we make a change, return true.
1106static bool
1110 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1111 auto &DL = GV->getDataLayout();
1112 // If this is a first class global and has only one accessing function and
1113 // this function is non-recursive, we replace the global with a local alloca
1114 // in this function.
1115 //
1116 // NOTE: It doesn't make sense to promote non-single-value types since we
1117 // are just replacing static memory to stack memory.
1118 //
1119 // If the global is in different address space, don't bring it to stack.
1120 if (!GS.HasMultipleAccessingFunctions &&
1121 GS.AccessingFunction &&
1123 GV->getType()->getAddressSpace() == DL.getAllocaAddrSpace() &&
1124 !GV->isExternallyInitialized() &&
1125 GS.AccessingFunction->doesNotRecurse() &&
1126 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV,
1127 LookupDomTree)) {
1128 const DataLayout &DL = GV->getDataLayout();
1129
1130 LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
1131 BasicBlock::iterator FirstI =
1132 GS.AccessingFunction->getEntryBlock().begin().getNonConst();
1133 Type *ElemTy = GV->getValueType();
1134 // FIXME: Pass Global's alignment when globals have alignment
1135 AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(),
1136 nullptr, GV->getName(), FirstI);
1138 if (!isa<UndefValue>(GV->getInitializer())) {
1139 auto *SI = new StoreInst(GV->getInitializer(), Alloca, FirstI);
1140 // FIXME: We're localizing a global and creating a store instruction for
1141 // the initial value of that global. Could we logically use the global
1142 // variable's (if one exists) line for this?
1143 SI->setDebugLoc(DebugLoc::getCompilerGenerated());
1144 }
1145
1146 GV->replaceAllUsesWith(Alloca);
1147 GV->eraseFromParent();
1148 ++NumLocalized;
1149 return true;
1150 }
1151
1152 bool Changed = false;
1153
1154 // If the global is never loaded (but may be stored to), it is dead.
1155 // Delete it now.
1156 if (!GS.IsLoaded) {
1157 LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
1158
1159 if (isLeakCheckerRoot(GV)) {
1160 // Delete any constant stores to the global.
1161 Changed = CleanupPointerRootUsers(GV, GetTLI);
1162 } else {
1163 // Delete any stores we can find to the global. We may not be able to
1164 // make it completely dead though.
1166 }
1167
1168 // If the global is dead now, delete it.
1169 if (GV->use_empty()) {
1170 GV->eraseFromParent();
1171 ++NumDeleted;
1172 Changed = true;
1173 }
1174 return Changed;
1175
1176 }
1177 if (GS.StoredType <= GlobalStatus::InitializerStored) {
1178 LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
1179
1180 // Don't actually mark a global constant if it's atomic because atomic loads
1181 // are implemented by a trivial cmpxchg in some edge-cases and that usually
1182 // requires write access to the variable even if it's not actually changed.
1183 if (GS.Ordering == AtomicOrdering::NotAtomic) {
1184 assert(!GV->isConstant() && "Expected a non-constant global");
1185 GV->setConstant(true);
1186 Changed = true;
1187 }
1188
1189 // Clean up any obviously simplifiable users now.
1191
1192 // If the global is dead now, just nuke it.
1193 if (GV->use_empty()) {
1194 LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1195 << "all users and delete global!\n");
1196 GV->eraseFromParent();
1197 ++NumDeleted;
1198 return true;
1199 }
1200
1201 // Fall through to the next check; see if we can optimize further.
1202 ++NumMarked;
1203 }
1204 if (!GV->getInitializer()->getType()->isSingleValueType()) {
1205 const DataLayout &DL = GV->getDataLayout();
1206 if (SRAGlobal(GV, DL))
1207 return true;
1208 }
1209 Value *StoredOnceValue = GS.getStoredOnceValue();
1210 if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) {
1211 Function &StoreFn =
1212 const_cast<Function &>(*GS.StoredOnceStore->getFunction());
1213 bool CanHaveNonUndefGlobalInitializer =
1214 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace(
1215 GV->getType()->getAddressSpace());
1216 // If the initial value for the global was an undef value, and if only
1217 // one other value was stored into it, we can just change the
1218 // initializer to be the stored value, then delete all stores to the
1219 // global. This allows us to mark it constant.
1220 // This is restricted to address spaces that allow globals to have
1221 // initializers. NVPTX, for example, does not support initializers for
1222 // shared memory (AS 3).
1223 auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue);
1224 if (SOVConstant && isa<UndefValue>(GV->getInitializer()) &&
1225 DL.getTypeAllocSize(SOVConstant->getType()).getFixedValue() ==
1226 GV->getGlobalSize(DL) &&
1227 CanHaveNonUndefGlobalInitializer) {
1228 if (SOVConstant->getType() == GV->getValueType()) {
1229 // Change the initializer in place.
1230 GV->setInitializer(SOVConstant);
1231 } else {
1232 // Create a new global with adjusted type.
1233 auto *NGV = new GlobalVariable(
1234 *GV->getParent(), SOVConstant->getType(), GV->isConstant(),
1235 GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(),
1236 GV->getAddressSpace());
1237 NGV->takeName(GV);
1238 NGV->copyAttributesFrom(GV);
1239 GV->replaceAllUsesWith(NGV);
1240 GV->eraseFromParent();
1241 GV = NGV;
1242 }
1243
1244 // Clean up any obviously simplifiable users now.
1246
1247 if (GV->use_empty()) {
1248 LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1249 << "simplify all users and delete global!\n");
1250 GV->eraseFromParent();
1251 ++NumDeleted;
1252 }
1253 ++NumSubstitute;
1254 return true;
1255 }
1256
1257 // Try to optimize globals based on the knowledge that only one value
1258 // (besides its initializer) is ever stored to the global.
1259 if (optimizeOnceStoredGlobal(GV, StoredOnceValue, DL, GetTLI))
1260 return true;
1261
1262 // Try to forward the store to any loads. If we have more than one store, we
1263 // may have a store of the initializer between StoredOnceStore and a load.
1264 if (GS.NumStores == 1)
1265 if (forwardStoredOnceStore(GV, GS.StoredOnceStore, LookupDomTree))
1266 return true;
1267
1268 // Otherwise, if the global was not a boolean, we can shrink it to be a
1269 // boolean. Skip this optimization for AS that doesn't allow an initializer.
1270 if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic &&
1272 CanHaveNonUndefGlobalInitializer)) {
1273 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1274 ++NumShrunkToBool;
1275 return true;
1276 }
1277 }
1278 }
1279
1280 return Changed;
1281}
1282
1283/// Analyze the specified global variable and optimize it if possible. If we
1284/// make a change, return true.
1285static bool
1289 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1290 if (GV.getName().starts_with("llvm."))
1291 return false;
1292
1293 // The only transformation performed here on functions is setting
1294 // unnamed_addr. Avoid scanning uses when its value cannot be strengthened.
1295 if (isa<Function>(GV) &&
1296 (GV.hasGlobalUnnamedAddr() ||
1298 return false;
1299
1300 GlobalStatus GS;
1301
1302 if (GlobalStatus::analyzeGlobal(&GV, GS))
1303 return false;
1304
1305 bool Changed = false;
1306 if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) {
1307 auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global
1309 if (NewUnnamedAddr != GV.getUnnamedAddr()) {
1310 GV.setUnnamedAddr(NewUnnamedAddr);
1311 NumUnnamed++;
1312 Changed = true;
1313 }
1314 }
1315
1316 // Do more involved optimizations if the global is internal.
1317 if (!GV.hasLocalLinkage())
1318 return Changed;
1319
1320 auto *GVar = dyn_cast<GlobalVariable>(&GV);
1321 if (!GVar)
1322 return Changed;
1323
1324 if (GVar->isConstant() || !GVar->hasInitializer())
1325 return Changed;
1326
1327 return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) ||
1328 Changed;
1329}
1330
1331/// Walk all of the direct calls of the specified function, changing them to
1332/// FastCC.
1334 for (User *U : F->users())
1335 if (auto *Call = dyn_cast<CallBase>(U))
1336 if (Call->getCalledOperand() == F)
1337 Call->setCallingConv(CallingConv::Fast);
1338}
1339
1342 unsigned AttrIndex;
1343 if (Attrs.hasAttrSomewhere(A, &AttrIndex))
1344 return Attrs.removeAttributeAtIndex(C, AttrIndex, A);
1345 return Attrs;
1346}
1347
1349 F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A));
1350 for (User *U : F->users()) {
1351 CallBase *CB = cast<CallBase>(U);
1352 CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A));
1353 }
1354}
1355
1356/// Return true if this is a calling convention that we'd like to change. The
1357/// idea here is that we don't want to mess with the convention if the user
1358/// explicitly requested something with performance implications like coldcc,
1359/// GHC, or anyregcc.
1361 CallingConv::ID CC = F->getCallingConv();
1362
1363 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1365 return false;
1366
1367 if (!F->canChangeSignature())
1368 return false;
1369
1370 if (F->isVarArg())
1371 return false;
1372
1373 // FIXME: Change CC for the whole chain of musttail calls when possible.
1374 //
1375 // Can't change CC of the function that either has musttail calls, or is a
1376 // musttail callee itself
1377 for (User *U : F->users()) {
1379 if (!CI)
1380 continue;
1381
1382 if (CI->isMustTailCall())
1383 return false;
1384 }
1385
1386 for (BasicBlock &BB : *F)
1387 if (BB.getTerminatingMustTailCall())
1388 return false;
1389
1390 return !F->hasAddressTaken();
1391}
1392
1395 ChangeableCCCacheTy &ChangeableCCCache) {
1396 auto Res = ChangeableCCCache.try_emplace(F, false);
1397 if (Res.second)
1398 Res.first->second = hasChangeableCCImpl(F);
1399 return Res.first->second;
1400}
1401
1402/// Return true if the block containing the call site has a BlockFrequency of
1403/// less than ColdCCRelFreq% of the entry block.
1404static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) {
1405 const BranchProbability ColdProb(ColdCCRelFreq, 100);
1406 auto *CallSiteBB = CB.getParent();
1407 auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB);
1408 auto CallerEntryFreq =
1409 CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock()));
1410 return CallSiteFreq < CallerEntryFreq * ColdProb;
1411}
1412
1413// This function checks if the input function F is cold at all call sites. It
1414// also looks each call site's containing function, returning false if the
1415// caller function contains other non cold calls. HasOnlyColdCalls returns
1416// whether a function only has call sites in cold blocks.
1417static bool
1420 function_ref<bool(Function &)> HasOnlyColdCalls) {
1421
1422 if (F.user_empty())
1423 return false;
1424
1425 for (User *U : F.users()) {
1427 if (!CB || CB->getCalledOperand() != &F)
1428 continue;
1429 Function *CallerFunc = CB->getParent()->getParent();
1430 BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc);
1431 if (!isColdCallSite(*CB, CallerBFI))
1432 return false;
1433 if (!HasOnlyColdCalls(*CallerFunc))
1434 return false;
1435 }
1436 return true;
1437}
1438
1440 for (User *U : F->users())
1441 if (auto *Call = dyn_cast<CallBase>(U))
1442 if (Call->getCalledOperand() == F)
1443 Call->setCallingConv(CallingConv::Cold);
1444}
1445
1446// This function iterates over all the call instructions in the input Function
1447// and checks that all call sites are in cold blocks and are allowed to use the
1448// coldcc calling convention.
1449static bool
1452 ChangeableCCCacheTy &ChangeableCCCache) {
1453 for (BasicBlock &BB : F) {
1454 for (Instruction &I : BB) {
1455 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1456 // Skip over isline asm instructions since they aren't function calls.
1457 if (CI->isInlineAsm())
1458 continue;
1459 Function *CalledFn = CI->getCalledFunction();
1460 if (!CalledFn)
1461 return false;
1462 // Skip over intrinsics since they won't remain as function calls.
1463 // Important to do this check before the linkage check below so we
1464 // won't bail out on debug intrinsics, possibly making the generated
1465 // code dependent on the presence of debug info.
1466 if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic)
1467 continue;
1468 if (!CalledFn->hasLocalLinkage())
1469 return false;
1470 // Check if it's valid to use coldcc calling convention.
1471 if (!hasChangeableCC(CalledFn, ChangeableCCCache))
1472 return false;
1473 BlockFrequencyInfo &CallerBFI = GetBFI(F);
1474 if (!isColdCallSite(*CI, CallerBFI))
1475 return false;
1476 }
1477 }
1478 }
1479 return true;
1480}
1481
1483 for (User *U : F->users()) {
1484 CallBase *CB = cast<CallBase>(U);
1485 if (CB->isMustTailCall())
1486 return true;
1487 }
1488 return false;
1489}
1490
1492 for (User *U : F->users())
1493 if (isa<InvokeInst>(U))
1494 return true;
1495 return false;
1496}
1497
1499 RemoveAttribute(F, Attribute::Preallocated);
1500
1501 auto *M = F->getParent();
1502
1503 IRBuilder<> Builder(*M);
1504
1505 // Cannot modify users() while iterating over it, so make a copy.
1506 SmallVector<User *, 4> PreallocatedCalls(F->users());
1507 for (CallBase *CB : make_isa_range<CallBase>(PreallocatedCalls)) {
1508 assert(
1509 !CB->isMustTailCall() &&
1510 "Shouldn't call RemotePreallocated() on a musttail preallocated call");
1511 // Create copy of call without "preallocated" operand bundle.
1513 CB->getOperandBundlesAsDefs(OpBundles);
1514 CallBase *PreallocatedSetup = nullptr;
1515 for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) {
1516 if (It->getTag() == "preallocated") {
1517 PreallocatedSetup = cast<CallBase>(*It->input_begin());
1518 OpBundles.erase(It);
1519 break;
1520 }
1521 }
1522 assert(PreallocatedSetup && "Did not find preallocated bundle");
1523 uint64_t ArgCount =
1524 cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue();
1525
1526 assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
1527 "Unknown indirect call type");
1528 CallBase *NewCB = CallBase::Create(CB, OpBundles, CB->getIterator());
1529 CB->replaceAllUsesWith(NewCB);
1530 NewCB->takeName(CB);
1531 CB->eraseFromParent();
1532
1533 Builder.SetInsertPoint(PreallocatedSetup);
1534 auto *StackSave = Builder.CreateStackSave();
1535 Builder.SetInsertPoint(NewCB->getNextNode());
1536 Builder.CreateStackRestore(StackSave);
1537
1538 // Replace @llvm.call.preallocated.arg() with alloca.
1539 // Cannot modify users() while iterating over it, so make a copy.
1540 // @llvm.call.preallocated.arg() can be called with the same index multiple
1541 // times. So for each @llvm.call.preallocated.arg(), we see if we have
1542 // already created a Value* for the index, and if not, create an alloca and
1543 // bitcast right after the @llvm.call.preallocated.setup() so that it
1544 // dominates all uses.
1545 SmallVector<Value *, 2> ArgAllocas(ArgCount);
1546 SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users());
1547 for (auto *User : PreallocatedArgs) {
1548 auto *UseCall = cast<CallBase>(User);
1549 assert(UseCall->getCalledFunction()->getIntrinsicID() ==
1550 Intrinsic::call_preallocated_arg &&
1551 "preallocated token use was not a llvm.call.preallocated.arg");
1552 uint64_t AllocArgIndex =
1553 cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue();
1554 Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
1555 if (!AllocaReplacement) {
1556 auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
1557 auto *ArgType =
1558 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType();
1559 auto *InsertBefore = PreallocatedSetup->getNextNode();
1560 Builder.SetInsertPoint(InsertBefore);
1561 auto *Alloca =
1562 Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg");
1563 ArgAllocas[AllocArgIndex] = Alloca;
1564 AllocaReplacement = Alloca;
1565 }
1566
1567 UseCall->replaceAllUsesWith(AllocaReplacement);
1568 UseCall->eraseFromParent();
1569 }
1570 // Remove @llvm.call.preallocated.setup().
1571 cast<Instruction>(PreallocatedSetup)->eraseFromParent();
1572 }
1573}
1574
1575static bool
1580 function_ref<DominatorTree &(Function &)> LookupDomTree,
1581 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
1582 function_ref<void(Function &F)> ChangedCFGCallback,
1583 function_ref<void(Function &F)> DeleteFnCallback) {
1584
1585 bool Changed = false;
1586
1587 ChangeableCCCacheTy ChangeableCCCache;
1588 // Whether each function only has cold calls. This is only needed for
1589 // functions the target wants to use coldcc for, so compute it lazily.
1590 DenseMap<Function *, bool> AllCallsColdCache;
1591 auto HasOnlyColdCalls = [&](Function &Caller) {
1592 auto Res = AllCallsColdCache.try_emplace(&Caller, false);
1593 if (Res.second)
1594 Res.first->second = hasOnlyColdCalls(Caller, GetBFI, ChangeableCCCache);
1595 return Res.first->second;
1596 };
1597
1598 // Optimize functions.
1600 // Don't perform global opt pass on naked functions; we don't want fast
1601 // calling conventions for naked functions.
1602 if (F.hasFnAttribute(Attribute::Naked))
1603 continue;
1604
1605 // Functions without names cannot be referenced outside this module.
1606 if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage())
1607 F.setLinkage(GlobalValue::InternalLinkage);
1608
1609 if (deleteIfDead(F, NotDiscardableComdats, DeleteFnCallback)) {
1610 Changed = true;
1611 continue;
1612 }
1613
1614 // LLVM's definition of dominance allows instructions that are cyclic
1615 // in unreachable blocks, e.g.:
1616 // %pat = select i1 %condition, @global, i16* %pat
1617 // because any instruction dominates an instruction in a block that's
1618 // not reachable from entry.
1619 // So, remove unreachable blocks from the function, because a) there's
1620 // no point in analyzing them and b) GlobalOpt should otherwise grow
1621 // some more complicated logic to break these cycles.
1622 // Notify the analysis manager that we've modified the function's CFG.
1623 if (!F.isDeclaration()) {
1625 Changed = true;
1626 ChangedCFGCallback(F);
1627 }
1628 }
1629
1630 Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree);
1631
1632 if (!F.hasLocalLinkage())
1633 continue;
1634
1635 // Ensure function definition is available for interprocedural analysis.
1636 if (!F.isDefinitionExact())
1637 continue;
1638
1639 // If we have an inalloca parameter that we can safely remove the
1640 // inalloca attribute from, do so. This unlocks optimizations that
1641 // wouldn't be safe in the presence of inalloca.
1642 // FIXME: We should also hoist alloca affected by this to the entry
1643 // block if possible.
1644 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
1645 !F.hasAddressTaken() && !hasMustTailCallers(&F) && !F.isVarArg()) {
1646 RemoveAttribute(&F, Attribute::InAlloca);
1647 Changed = true;
1648 }
1649
1650 // FIXME: handle invokes
1651 // FIXME: handle musttail
1652 if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
1653 if (!F.hasAddressTaken() && !hasMustTailCallers(&F) &&
1654 !hasInvokeCallers(&F)) {
1656 Changed = true;
1657 }
1658 continue;
1659 }
1660
1661 if (hasChangeableCC(&F, ChangeableCCCache)) {
1662 NumInternalFunc++;
1663 TargetTransformInfo &TTI = GetTTI(F);
1664 // Change the calling convention to coldcc if either stress testing is
1665 // enabled or the target would like to use coldcc on functions which are
1666 // cold at all call sites and the callers contain no other non coldcc
1667 // calls.
1669 (TTI.useColdCCForColdCall(F) &&
1670 isValidCandidateForColdCC(F, GetBFI, HasOnlyColdCalls))) {
1671 ChangeableCCCache.erase(&F);
1672 F.setCallingConv(CallingConv::Cold);
1674 Changed = true;
1675 NumColdCC++;
1676 }
1677 }
1678
1679 if (hasChangeableCC(&F, ChangeableCCCache)) {
1680 // If this function has a calling convention worth changing, is not a
1681 // varargs function, is only called directly, and is supported by the
1682 // target, promote it to use the Fast calling convention.
1683 TargetTransformInfo &TTI = GetTTI(F);
1684 if (TTI.useFastCCForInternalCall(F)) {
1685 F.setCallingConv(CallingConv::Fast);
1687 ++NumFastCallFns;
1688 Changed = true;
1689 }
1690 }
1691
1692 if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1693 !F.hasAddressTaken()) {
1694 // The function is not used by a trampoline intrinsic, so it is safe
1695 // to remove the 'nest' attribute.
1696 RemoveAttribute(&F, Attribute::Nest);
1697 ++NumNestRemoved;
1698 Changed = true;
1699 }
1700 }
1701 return Changed;
1702}
1703
1704static bool
1708 function_ref<DominatorTree &(Function &)> LookupDomTree,
1709 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
1710 bool Changed = false;
1711
1712 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
1713 // Global variables without names cannot be referenced outside this module.
1714 if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage())
1716 // Simplify the initializer.
1717 if (GV.hasInitializer()) {
1718 const Constant *C = GV.getInitializer();
1719 auto &DL = M.getDataLayout();
1720 // TLI is not used in the case of a Constant, so use default nullptr
1721 // for that optional parameter, since we don't have a Function to
1722 // provide GetTLI anyway.
1723 Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr);
1724 if (New != C)
1725 GV.setInitializer(New);
1726 }
1727
1728 if (deleteIfDead(GV, NotDiscardableComdats)) {
1729 Changed = true;
1730 continue;
1731 }
1732
1733 Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree);
1734 }
1735 return Changed;
1736}
1737
1738/// Evaluate static constructors in the function, if we can. Return true if we
1739/// can, false otherwise.
1741 TargetLibraryInfo *TLI) {
1742 // Skip external functions.
1743 if (F->isDeclaration())
1744 return false;
1745 // Call the function.
1746 Evaluator Eval(DL, TLI);
1747 Constant *RetValDummy;
1748 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
1750
1751 if (EvalSuccess) {
1752 ++NumCtorsEvaluated;
1753
1754 // We succeeded at evaluation: commit the result.
1755 auto NewInitializers = Eval.getMutatedInitializers();
1756 LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1757 << F->getName() << "' to " << NewInitializers.size()
1758 << " stores.\n");
1759 for (const auto &Pair : NewInitializers)
1760 Pair.first->setInitializer(Pair.second);
1761 for (GlobalVariable *GV : Eval.getInvariants())
1762 GV->setConstant(true);
1763 }
1764
1765 return EvalSuccess;
1766}
1767
1768static int compareNames(Constant *const *A, Constant *const *B) {
1769 Value *AStripped = (*A)->stripPointerCasts();
1770 Value *BStripped = (*B)->stripPointerCasts();
1771 return AStripped->getName().compare(BStripped->getName());
1772}
1773
1776 if (Init.empty()) {
1777 V.eraseFromParent();
1778 return;
1779 }
1780
1781 // Get address space of pointers in the array of pointers.
1782 const Type *UsedArrayType = V.getValueType();
1783 const auto *VAT = cast<ArrayType>(UsedArrayType);
1784 const auto *VEPT = cast<PointerType>(VAT->getArrayElementType());
1785
1786 // Type of pointer to the array of pointers.
1787 PointerType *PtrTy =
1788 PointerType::get(V.getContext(), VEPT->getAddressSpace());
1789
1791 for (GlobalValue *GV : Init) {
1793 UsedArray.push_back(Cast);
1794 }
1795
1796 // Sort to get deterministic order.
1797 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
1798 ArrayType *ATy = ArrayType::get(PtrTy, UsedArray.size());
1799
1800 Module *M = V.getParent();
1801 V.removeFromParent();
1803 *M, ATy, false, GlobalValue::AppendingLinkage,
1804 ConstantArray::get(ATy, UsedArray), "", nullptr,
1805 GlobalVariable::NotThreadLocal, V.getType()->getAddressSpace());
1806 NV->takeName(&V);
1807 NV->setSection("llvm.metadata");
1808 delete &V;
1809}
1810
1811namespace {
1812
1813/// An easy to access representation of llvm.used and llvm.compiler.used.
1814class LLVMUsed {
1815 SmallPtrSet<GlobalValue *, 4> Used;
1816 SmallPtrSet<GlobalValue *, 4> CompilerUsed;
1817 GlobalVariable *UsedV;
1818 GlobalVariable *CompilerUsedV;
1819
1820public:
1821 LLVMUsed(Module &M) {
1823 UsedV = collectUsedGlobalVariables(M, Vec, false);
1824 Used = {llvm::from_range, Vec};
1825 Vec.clear();
1826 CompilerUsedV = collectUsedGlobalVariables(M, Vec, true);
1827 CompilerUsed = {llvm::from_range, Vec};
1828 }
1829
1830 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator;
1831 using used_iterator_range = iterator_range<iterator>;
1832
1833 iterator usedBegin() { return Used.begin(); }
1834 iterator usedEnd() { return Used.end(); }
1835
1836 used_iterator_range used() {
1837 return used_iterator_range(usedBegin(), usedEnd());
1838 }
1839
1840 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
1841 iterator compilerUsedEnd() { return CompilerUsed.end(); }
1842
1843 used_iterator_range compilerUsed() {
1844 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
1845 }
1846
1847 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
1848
1849 bool compilerUsedCount(GlobalValue *GV) const {
1850 return CompilerUsed.count(GV);
1851 }
1852
1853 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
1854 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
1855 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
1856
1857 bool compilerUsedInsert(GlobalValue *GV) {
1858 return CompilerUsed.insert(GV).second;
1859 }
1860
1861 void syncVariablesAndSets() {
1862 if (UsedV)
1863 setUsedInitializer(*UsedV, Used);
1864 if (CompilerUsedV)
1865 setUsedInitializer(*CompilerUsedV, CompilerUsed);
1866 }
1867};
1868
1869} // end anonymous namespace
1870
1871static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
1872 if (GA.use_empty()) // No use at all.
1873 return false;
1874
1875 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
1876 "We should have removed the duplicated "
1877 "element from llvm.compiler.used");
1878 if (!GA.hasOneUse())
1879 // Strictly more than one use. So at least one is not in llvm.used and
1880 // llvm.compiler.used.
1881 return true;
1882
1883 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
1884 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
1885}
1886
1887static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U) {
1888 if (!GV.hasLocalLinkage())
1889 return true;
1890
1891 return U.usedCount(&GV) || U.compilerUsedCount(&GV);
1892}
1893
1894static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
1895 bool &RenameTarget) {
1896 if (GA.isWeakForLinker())
1897 return false;
1898
1899 RenameTarget = false;
1900 bool Ret = false;
1901 if (hasUseOtherThanLLVMUsed(GA, U))
1902 Ret = true;
1903
1904 // If the alias is externally visible, we may still be able to simplify it.
1905 if (!mayHaveOtherReferences(GA, U))
1906 return Ret;
1907
1908 // If the aliasee has internal linkage and no other references (e.g.,
1909 // @llvm.used, @llvm.compiler.used), give it the name and linkage of the
1910 // alias, and delete the alias. This turns:
1911 // define internal ... @f(...)
1912 // @a = alias ... @f
1913 // into:
1914 // define ... @a(...)
1915 Constant *Aliasee = GA.getAliasee();
1918 return Ret;
1919
1920 RenameTarget = true;
1921 return true;
1922}
1923
1924static bool
1926 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
1927 bool Changed = false;
1928 LLVMUsed Used(M);
1929
1930 for (GlobalValue *GV : Used.used())
1931 Used.compilerUsedErase(GV);
1932
1933 // Return whether GV is explicitly or implicitly dso_local and not replaceable
1934 // by another definition in the current linkage unit.
1935 auto IsModuleLocal = [](GlobalValue &GV) {
1937 (GV.isDSOLocal() || GV.isImplicitDSOLocal());
1938 };
1939
1940 for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) {
1941 // Aliases without names cannot be referenced outside this module.
1942 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage())
1943 J.setLinkage(GlobalValue::InternalLinkage);
1944
1945 if (deleteIfDead(J, NotDiscardableComdats)) {
1946 Changed = true;
1947 continue;
1948 }
1949
1950 // If the alias can change at link time, nothing can be done - bail out.
1951 if (!IsModuleLocal(J))
1952 continue;
1953
1954 Constant *Aliasee = J.getAliasee();
1956 // We can't trivially replace the alias with the aliasee if the aliasee is
1957 // non-trivial in some way. We also can't replace the alias with the aliasee
1958 // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible
1959 // alias can be used to access the definition as if preemption did not
1960 // happen.
1961 // TODO: Try to handle non-zero GEPs of local aliasees.
1962 if (!Target || !IsModuleLocal(*Target))
1963 continue;
1964
1965 Target->removeDeadConstantUsers();
1966
1967 // Make all users of the alias use the aliasee instead.
1968 bool RenameTarget;
1969 if (!hasUsesToReplace(J, Used, RenameTarget))
1970 continue;
1971
1972 J.replaceAllUsesWith(Aliasee);
1973 ++NumAliasesResolved;
1974 Changed = true;
1975
1976 if (RenameTarget) {
1977 // Give the aliasee the name, linkage and other attributes of the alias.
1978 Target->takeName(&J);
1979 Target->setLinkage(J.getLinkage());
1980 Target->setDSOLocal(J.isDSOLocal());
1981 Target->setVisibility(J.getVisibility());
1982 Target->setDLLStorageClass(J.getDLLStorageClass());
1983
1984 if (Used.usedErase(&J))
1985 Used.usedInsert(Target);
1986
1987 if (Used.compilerUsedErase(&J))
1988 Used.compilerUsedInsert(Target);
1989 } else if (mayHaveOtherReferences(J, Used))
1990 continue;
1991
1992 // Delete the alias.
1993 M.eraseAlias(&J);
1994 ++NumAliasesRemoved;
1995 Changed = true;
1996 }
1997
1998 Used.syncVariablesAndSets();
1999
2000 return Changed;
2001}
2002
2003static Function *
2006 LibFunc Func) {
2007 // Hack to get a default TLI before we have actual Function.
2008 auto FuncIter = M.begin();
2009 if (FuncIter == M.end())
2010 return nullptr;
2011 auto *TLI = &GetTLI(*FuncIter);
2012
2013 if (!TLI->has(Func))
2014 return nullptr;
2015
2016 Function *Fn = M.getFunction(TLI->getName(Func));
2017 if (!Fn)
2018 return nullptr;
2019
2020 // Now get the actual TLI for Fn.
2021 TLI = &GetTLI(*Fn);
2022
2023 // Make sure that the function has the correct prototype.
2024 if (TLI->getLibFunc(*Fn) != Func)
2025 return nullptr;
2026
2027 return Fn;
2028}
2029
2030/// Returns whether the given function is an empty C++ destructor or atexit
2031/// handler and can therefore be eliminated. Note that we assume that other
2032/// optimization passes have already simplified the code so we simply check for
2033/// 'ret'.
2034static bool IsEmptyAtExitFunction(const Function &Fn) {
2035 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
2036 // nounwind, but that doesn't seem worth doing.
2037 if (Fn.isDeclaration())
2038 return false;
2039
2040 for (const auto &I : Fn.getEntryBlock()) {
2042 continue;
2043 if (isa<ReturnInst>(I))
2044 return true;
2045 break;
2046 }
2047 return false;
2048}
2049
2050static bool OptimizeEmptyGlobalAtExitDtors(Function *CXAAtExitFn, bool isCXX) {
2051 /// Itanium C++ ABI p3.3.5:
2052 ///
2053 /// After constructing a global (or local static) object, that will require
2054 /// destruction on exit, a termination function is registered as follows:
2055 ///
2056 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2057 ///
2058 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2059 /// call f(p) when DSO d is unloaded, before all such termination calls
2060 /// registered before this one. It returns zero if registration is
2061 /// successful, nonzero on failure.
2062
2063 // This pass will look for calls to __cxa_atexit or atexit where the function
2064 // is trivial and remove them.
2065 bool Changed = false;
2066
2067 for (Use &U : llvm::make_early_inc_range(CXAAtExitFn->uses())) {
2068 // We're only interested in calls to the atexit function. Theoretically, we
2069 // could handle invoke instructions as well, but neither llvm-gcc nor clang
2070 // generate invokes to __cxa_atexit.
2071 CallInst *CI = dyn_cast<CallInst>(U.getUser());
2072 if (!CI || !CI->isCallee(&U))
2073 continue;
2074
2075 Function *DtorFn =
2077 if (!DtorFn || !IsEmptyAtExitFunction(*DtorFn))
2078 continue;
2079
2080 // Just remove the call.
2082 CI->eraseFromParent();
2083
2084 if (isCXX)
2085 ++NumCXXDtorsRemoved;
2086 else
2087 ++NumAtExitRemoved;
2088
2089 Changed |= true;
2090 }
2091
2092 return Changed;
2093}
2094
2096 if (IF.isInterposable())
2097 return nullptr;
2098
2100 if (!Resolver)
2101 return nullptr;
2102
2103 if (Resolver->isInterposable())
2104 return nullptr;
2105
2106 // Only handle functions that have been optimized into a single basic block.
2107 auto It = Resolver->begin();
2108 if (++It != Resolver->end())
2109 return nullptr;
2110
2111 BasicBlock &BB = Resolver->getEntryBlock();
2112
2113 if (any_of(BB, [](Instruction &I) { return I.mayHaveSideEffects(); }))
2114 return nullptr;
2115
2116 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
2117 if (!Ret)
2118 return nullptr;
2119
2120 return dyn_cast<Function>(Ret->getReturnValue());
2121}
2122
2123/// Find IFuncs that have resolvers that always point at the same statically
2124/// known callee, and replace their callers with a direct call.
2126 bool Changed = false;
2127 for (GlobalIFunc &IF : M.ifuncs())
2129 if (!IF.use_empty() &&
2130 (!Callee->isDeclaration() ||
2131 none_of(IF.users(), [](User *U) { return isa<GlobalAlias>(U); }))) {
2132 IF.replaceAllUsesWith(Callee);
2133 NumIFuncsResolved++;
2134 Changed = true;
2135 }
2136 return Changed;
2137}
2138
2139static bool
2141 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2142 bool Changed = false;
2143 for (GlobalIFunc &IF : make_early_inc_range(M.ifuncs()))
2144 if (deleteIfDead(IF, NotDiscardableComdats)) {
2145 NumIFuncsDeleted++;
2146 Changed = true;
2147 }
2148 return Changed;
2149}
2150
2151// Follows the use-def chain of \p V backwards until it finds a Function,
2152// in which case it collects in \p Versions. Return true on successful
2153// use-def chain traversal, false otherwise.
2154static bool
2157 if (auto *F = dyn_cast<Function>(V)) {
2158 if (!GetTTI(*F).isMultiversionedFunction(*F))
2159 return false;
2160 Versions.push_back(F);
2161 } else if (auto *Sel = dyn_cast<SelectInst>(V)) {
2162 if (!collectVersions(Sel->getTrueValue(), Versions, GetTTI))
2163 return false;
2164 if (!collectVersions(Sel->getFalseValue(), Versions, GetTTI))
2165 return false;
2166 } else if (auto *Phi = dyn_cast<PHINode>(V)) {
2167 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
2168 if (!collectVersions(Phi->getIncomingValue(I), Versions, GetTTI))
2169 return false;
2170 } else {
2171 // Unknown instruction type. Bail.
2172 return false;
2173 }
2174 return true;
2175}
2176
2177// Try to statically resolve calls to versioned functions when possible. First
2178// we identify the function versions which are associated with an IFUNC symbol.
2179// We do that by examining the resolver function of the IFUNC. Once we have
2180// collected all the function versions, we sort them in decreasing priority
2181// order. This is necessary for determining the most suitable callee version
2182// for each caller version. We then collect all the callsites to versioned
2183// functions. The static resolution is performed by comparing the feature sets
2184// between callers and callees. Specifically:
2185// * Start a walk over caller and callee lists simultaneously in order of
2186// decreasing priority.
2187// * Statically resolve calls from the current caller to the current callee,
2188// iff the caller feature bits are a superset of the callee feature bits.
2189// * For FMV callers, as long as the caller feature bits are a subset of the
2190// callee feature bits, advance to the next callee. This effectively prevents
2191// considering the current callee as a candidate for static resolution by
2192// following callers (explanation: preceding callers would not have been
2193// selected in a hypothetical runtime execution).
2194// * Advance to the next caller.
2195//
2196// Presentation in EuroLLVM2025:
2197// https://www.youtube.com/watch?v=k54MFimPz-A&t=867s
2200 bool Changed = false;
2201
2202 // Map containing the feature bits for a given function.
2203 DenseMap<Function *, APInt> FeatureMask;
2204 // Map containing the priority bits for a given function.
2205 DenseMap<Function *, APInt> PriorityMask;
2206 // Map containing all the function versions corresponding to an IFunc symbol.
2208 // Map containing the IFunc symbol a function is version of.
2210 // List of all the interesting IFuncs found in the module.
2212
2213 for (GlobalIFunc &IF : M.ifuncs()) {
2214 LLVM_DEBUG(dbgs() << "Examining IFUNC " << IF.getName() << "\n");
2215
2216 if (IF.isInterposable())
2217 continue;
2218
2219 Function *Resolver = IF.getResolverFunction();
2220 if (!Resolver)
2221 continue;
2222
2223 if (Resolver->isInterposable())
2224 continue;
2225
2226 SmallVector<Function *> Versions;
2227 // Discover the versioned functions.
2228 if (any_of(*Resolver, [&](BasicBlock &BB) {
2229 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
2230 if (!collectVersions(Ret->getReturnValue(), Versions, GetTTI))
2231 return true;
2232 return false;
2233 }))
2234 continue;
2235
2236 if (Versions.empty())
2237 continue;
2238
2239 for (Function *V : Versions) {
2240 VersionOf.insert({V, &IF});
2241 auto [FeatIt, FeatInserted] = FeatureMask.try_emplace(V);
2242 if (FeatInserted)
2243 FeatIt->second = GetTTI(*V).getFeatureMask(*V);
2244 auto [PriorIt, PriorInserted] = PriorityMask.try_emplace(V);
2245 if (PriorInserted)
2246 PriorIt->second = GetTTI(*V).getPriorityMask(*V);
2247 }
2248
2249 // Sort function versions in decreasing priority order.
2250 sort(Versions, [&](auto *LHS, auto *RHS) {
2251 return PriorityMask[LHS].ugt(PriorityMask[RHS]);
2252 });
2253
2254 IFuncs.push_back(&IF);
2255 VersionedFuncs.try_emplace(&IF, std::move(Versions));
2256 }
2257
2258 for (GlobalIFunc *CalleeIF : IFuncs) {
2259 SmallVector<Function *> NonFMVCallers;
2260 DenseSet<GlobalIFunc *> CallerIFuncs;
2262
2263 // Find the callsites.
2264 for (User *U : CalleeIF->users()) {
2265 if (auto *CB = dyn_cast<CallBase>(U)) {
2266 if (CB->getCalledOperand() == CalleeIF) {
2267 Function *Caller = CB->getFunction();
2268 GlobalIFunc *CallerIF = nullptr;
2269 TargetTransformInfo &TTI = GetTTI(*Caller);
2270 bool CallerIsFMV = TTI.isMultiversionedFunction(*Caller);
2271 // The caller is a version of a known IFunc.
2272 if (auto It = VersionOf.find(Caller); It != VersionOf.end())
2273 CallerIF = It->second;
2274 else if (!CallerIsFMV && OptimizeNonFMVCallers) {
2275 // The caller is non-FMV.
2276 auto [It, Inserted] = FeatureMask.try_emplace(Caller);
2277 if (Inserted)
2278 It->second = TTI.getFeatureMask(*Caller);
2279 } else
2280 // The caller is none of the above, skip.
2281 continue;
2282 auto [It, Inserted] = CallSites.try_emplace(Caller);
2283 if (Inserted) {
2284 if (CallerIsFMV)
2285 CallerIFuncs.insert(CallerIF);
2286 else
2287 NonFMVCallers.push_back(Caller);
2288 }
2289 It->second.push_back(CB);
2290 }
2291 }
2292 }
2293
2294 if (CallSites.empty())
2295 continue;
2296
2297 LLVM_DEBUG(dbgs() << "Statically resolving calls to function "
2298 << CalleeIF->getResolverFunction()->getName() << "\n");
2299
2300 // The complexity of this algorithm is linear: O(NumCallers + NumCallees)
2301 // if NumCallers > MaxIFuncVersions || NumCallees > MaxIFuncVersions,
2302 // otherwise it is cubic: O((NumCallers ^ 2) x NumCallees).
2303 auto staticallyResolveCalls = [&](ArrayRef<Function *> Callers,
2304 ArrayRef<Function *> Callees,
2305 bool CallerIsFMV) {
2306 bool AllowExpensiveChecks = CallerIsFMV &&
2307 Callers.size() <= MaxIFuncVersions &&
2308 Callees.size() <= MaxIFuncVersions;
2309 // Index to the highest callee candidate.
2310 unsigned J = 0;
2311
2312 for (unsigned I = 0, E = Callers.size(); I < E; ++I) {
2313 // There are no callee candidates left.
2314 if (J == Callees.size())
2315 break;
2316
2317 Function *Caller = Callers[I];
2318 APInt CallerBits = FeatureMask[Caller];
2319
2320 // Compare the feature bits of the best callee candidate with all the
2321 // caller versions preceeding the current one. For each prior caller
2322 // discard feature bits that are known to be available in the current
2323 // caller. As long as the known missing feature bits are a subset of the
2324 // callee feature bits, advance to the next callee and start over.
2325 auto eliminateAvailableFeatures = [&](unsigned BestCandidate) {
2326 unsigned K = 0;
2327 while (K < I && BestCandidate < Callees.size()) {
2328 APInt MissingBits = FeatureMask[Callers[K]] & ~CallerBits;
2329 if (MissingBits.isSubsetOf(FeatureMask[Callees[BestCandidate]])) {
2330 ++BestCandidate;
2331 // Start over.
2332 K = 0;
2333 } else
2334 ++K;
2335 }
2336 return BestCandidate;
2337 };
2338
2339 unsigned BestCandidate =
2340 AllowExpensiveChecks ? eliminateAvailableFeatures(J) : J;
2341 // No callee candidate was found for this caller.
2342 if (BestCandidate == Callees.size())
2343 continue;
2344
2345 LLVM_DEBUG(dbgs() << " Examining "
2346 << (CallerIsFMV ? "FMV" : "regular") << " caller "
2347 << Caller->getName() << "\n");
2348
2349 Function *Callee = Callees[BestCandidate];
2350 APInt CalleeBits = FeatureMask[Callee];
2351
2352 // Statically resolve calls from the current caller to the current
2353 // callee, iff the caller feature bits are a superset of the callee
2354 // feature bits.
2355 if (CalleeBits.isSubsetOf(CallerBits)) {
2356 // Not all caller versions are necessarily users of the callee IFUNC.
2357 if (auto It = CallSites.find(Caller); It != CallSites.end()) {
2358 for (CallBase *CS : It->second) {
2359 LLVM_DEBUG(dbgs() << " Redirecting call " << Caller->getName()
2360 << " -> " << Callee->getName() << "\n");
2361 CS->setCalledOperand(Callee);
2362 }
2363 Changed = true;
2364 }
2365 }
2366
2367 // Nothing else to do about non-FMV callers.
2368 if (!CallerIsFMV)
2369 continue;
2370
2371 // For FMV callers, as long as the caller feature bits are a subset of
2372 // the callee feature bits, advance to the next callee. This effectively
2373 // prevents considering the current callee as a candidate for static
2374 // resolution by following callers.
2375 while (CallerBits.isSubsetOf(FeatureMask[Callees[J]]) &&
2376 ++J < Callees.size())
2377 ;
2378 }
2379 };
2380
2381 auto &Callees = VersionedFuncs[CalleeIF];
2382
2383 // Optimize non-FMV calls.
2385 staticallyResolveCalls(NonFMVCallers, Callees, /*CallerIsFMV=*/false);
2386
2387 // Optimize FMV calls.
2388 for (GlobalIFunc *CallerIF : CallerIFuncs) {
2389 auto &Callers = VersionedFuncs[CallerIF];
2390 staticallyResolveCalls(Callers, Callees, /*CallerIsFMV=*/true);
2391 }
2392
2393 if (CalleeIF->use_empty() ||
2394 all_of(CalleeIF->users(), [](User *U) { return isa<GlobalAlias>(U); }))
2395 NumIFuncsResolved++;
2396 }
2397 return Changed;
2398}
2399
2400static bool
2405 function_ref<DominatorTree &(Function &)> LookupDomTree,
2406 function_ref<void(Function &F)> ChangedCFGCallback,
2407 function_ref<void(Function &F)> DeleteFnCallback) {
2408 SmallPtrSet<const Comdat *, 8> NotDiscardableComdats;
2409 bool Changed = false;
2410 bool LocalChange = true;
2411 std::optional<uint32_t> FirstNotFullyEvaluatedPriority;
2412
2413 while (LocalChange) {
2414 LocalChange = false;
2415
2416 NotDiscardableComdats.clear();
2417 for (const GlobalVariable &GV : M.globals())
2418 if (const Comdat *C = GV.getComdat())
2419 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
2420 NotDiscardableComdats.insert(C);
2421 for (Function &F : M)
2422 if (const Comdat *C = F.getComdat())
2423 if (!F.isDefTriviallyDead())
2424 NotDiscardableComdats.insert(C);
2425 for (GlobalAlias &GA : M.aliases())
2426 if (const Comdat *C = GA.getComdat())
2427 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2428 NotDiscardableComdats.insert(C);
2429
2430 // Delete functions that are trivially dead, ccc -> fastcc
2431 LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree,
2432 NotDiscardableComdats, ChangedCFGCallback,
2433 DeleteFnCallback);
2434
2435 // Optimize global_ctors list.
2436 LocalChange |=
2437 optimizeGlobalCtorsList(M, [&](uint32_t Priority, Function *F) {
2438 if (FirstNotFullyEvaluatedPriority &&
2439 *FirstNotFullyEvaluatedPriority != Priority)
2440 return false;
2441 bool Evaluated = EvaluateStaticConstructor(F, DL, &GetTLI(*F));
2442 if (!Evaluated)
2443 FirstNotFullyEvaluatedPriority = Priority;
2444 return Evaluated;
2445 });
2446
2447 // Optimize non-address-taken globals.
2448 LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree,
2449 NotDiscardableComdats);
2450
2451 // Resolve aliases, when possible.
2452 LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats);
2453
2454 // Try to remove trivial global destructors if they are not removed
2455 // already.
2456 if (Function *CXAAtExitFn =
2457 FindAtExitLibFunc(M, GetTLI, LibFunc_cxa_atexit))
2458 LocalChange |= OptimizeEmptyGlobalAtExitDtors(CXAAtExitFn, true);
2459
2460 if (Function *AtExitFn = FindAtExitLibFunc(M, GetTLI, LibFunc_atexit))
2461 LocalChange |= OptimizeEmptyGlobalAtExitDtors(AtExitFn, false);
2462
2463 // Optimize IFuncs whose callee's are statically known.
2464 LocalChange |= OptimizeStaticIFuncs(M);
2465
2466 // Optimize IFuncs based on the target features of the caller.
2467 LocalChange |= OptimizeNonTrivialIFuncs(M, GetTTI);
2468
2469 // Remove any IFuncs that are now dead.
2470 LocalChange |= DeleteDeadIFuncs(M, NotDiscardableComdats);
2471
2472 Changed |= LocalChange;
2473 }
2474
2475 // TODO: Move all global ctors functions to the end of the module for code
2476 // layout.
2477
2478 return Changed;
2479}
2480
2482 auto &DL = M.getDataLayout();
2483 auto &FAM =
2485 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{
2486 return FAM.getResult<DominatorTreeAnalysis>(F);
2487 };
2488 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2489 return FAM.getResult<TargetLibraryAnalysis>(F);
2490 };
2491 auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
2492 return FAM.getResult<TargetIRAnalysis>(F);
2493 };
2494
2495 auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
2496 return FAM.getResult<BlockFrequencyAnalysis>(F);
2497 };
2498 auto ChangedCFGCallback = [&FAM](Function &F) {
2499 FAM.invalidate(F, PreservedAnalyses::none());
2500 };
2501 auto DeleteFnCallback = [&FAM](Function &F) { FAM.clear(F, F.getName()); };
2502
2503 if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree,
2504 ChangedCFGCallback, DeleteFnCallback))
2505 return PreservedAnalyses::all();
2506
2508 // We made sure to clear analyses for deleted functions.
2510 // The only place we modify the CFG is when calling
2511 // removeUnreachableBlocks(), but there we make sure to invalidate analyses
2512 // for modified functions.
2514 return PA;
2515}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
#define DEBUG_TYPE
static bool IsSafeComputationToRemove(Value *V, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Given a value that is stored to a global but never read, determine whether it's safe to remove the st...
static Function * FindAtExitLibFunc(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, LibFunc Func)
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
static Function * hasSideeffectFreeStaticResolution(GlobalIFunc &IF)
static bool OptimizeStaticIFuncs(Module &M)
Find IFuncs that have resolvers that always point at the same statically known callee,...
static bool hasOnlyColdCalls(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, ChangeableCCCacheTy &ChangeableCCCache)
static bool hasChangeableCCImpl(Function *F)
Return true if this is a calling convention that we'd like to change.
static bool collectVersions(Value *V, SmallVectorImpl< Function * > &Versions, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool IsEmptyAtExitFunction(const Function &Fn)
Returns whether the given function is an empty C++ destructor or atexit handler and can therefore be ...
static bool collectSRATypes(DenseMap< uint64_t, GlobalPart > &Parts, GlobalVariable *GV, const DataLayout &DL)
Look at all uses of the global and determine which (offset, type) pairs it can be split into.
static bool OptimizeFunctions(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool DeleteDeadIFuncs(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static void RemoveAttribute(Function *F, Attribute::AttrKind A)
static bool hasChangeableCC(Function *F, ChangeableCCCacheTy &ChangeableCCCache)
static bool deleteIfDead(GlobalValue &GV, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &)> DeleteFnCallback=nullptr)
static void RemovePreallocated(Function *F)
static cl::opt< bool > OptimizeNonFMVCallers("optimize-non-fmv-callers", cl::desc("Statically resolve calls to versioned " "functions from non-versioned callers."), cl::init(true), cl::Hidden)
static bool processGlobal(GlobalValue &GV, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, uint64_t FragmentOffsetInBits, uint64_t FragmentSizeInBits, uint64_t VarSize)
Copy over the debug info for a variable to its SRA replacements.
static cl::opt< bool > EnableColdCCStressTest("enable-coldcc-stress-test", cl::desc("Enable stress test of coldcc by adding " "calling conv to all internal functions."), cl::init(false), cl::Hidden)
static bool OptimizeGlobalAliases(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
At this point, we have learned that the only two values ever stored into GV are its initializer and O...
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
static bool hasMustTailCallers(Function *F)
static bool OptimizeNonTrivialIFuncs(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool OptimizeGlobalVars(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool OptimizeEmptyGlobalAtExitDtors(Function *CXAAtExitFn, bool isCXX)
static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U)
static void changeCallSitesToColdCC(Function *F)
static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, Attribute::AttrKind A)
static bool hasInvokeCallers(Function *F)
static bool OptimizeAwayTrappingUsesOfValue(Instruction *V, Constant *NewV)
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSetImpl< GlobalValue * > &Init)
static cl::opt< unsigned > MaxIFuncVersions("max-ifunc-versions", cl::Hidden, cl::init(5), cl::desc("Maximum number of caller/callee versions that is allowed for " "using the expensive (cubic) static resolution algorithm."))
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
The specified global has only one non-null value stored into it.
static cl::opt< int > ColdCCRelFreq("coldcc-rel-freq", cl::Hidden, cl::init(2), cl::desc("Maximum block frequency, expressed as a percentage of caller's " "entry frequency, for a call site to be considered cold for enabling " "coldcc"))
static bool optimizeGlobalsInModule(Module &M, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, TargetLibraryInfo *TLI)
Evaluate static constructors in the function, if we can.
static bool CleanupConstantGlobalUsers(GlobalVariable *GV, const DataLayout &DL)
We just marked GV constant.
SmallDenseMap< Function *, bool, 8 > ChangeableCCCacheTy
static bool isLeakCheckerRoot(GlobalVariable *GV)
Is this global variable possibly used by a leak checker as a root?
static bool forwardStoredOnceStore(GlobalVariable *GV, const StoreInst *StoredOnceStore, function_ref< DominatorTree &(Function &)> LookupDomTree)
static int compareNames(Constant *const *A, Constant *const *B)
static bool CleanupPointerRootUsers(GlobalVariable *GV, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
This GV is a pointer root.
static bool isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV, function_ref< DominatorTree &(Function &)> LookupDomTree)
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, bool &RenameTarget)
static bool isValidCandidateForColdCC(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< bool(Function &)> HasOnlyColdCalls)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
Perform scalar replacement of aggregates on the specified global variable.
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
RISCVCC::CondCode CC
This file contains some templates that are useful if you are working with the STL at all.
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.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
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...
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.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
void setCalledOperand(Value *V)
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isMustTailCall() const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1477
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
const Constant * stripPointerCasts() const
Definition Constant.h:243
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DWARF expression.
LLVM_ABI bool extractIfOffset(int64_t &Offset) const
If this is a constant offset, extract it.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
A pair of DIGlobalVariable and DIExpression.
uint64_t getSizeInBits() const
Base class for variables.
DIType * getType() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
iterator begin()
Definition DenseMap.h:682
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
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
Definition Evaluator.h:37
DenseMap< GlobalVariable *, Constant * > getMutatedInitializers() const
Definition Evaluator.h:102
LLVM_ABI bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant * > &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it.
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
Definition Evaluator.h:109
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
const Function & getFunction() const
Definition Function.h:167
iterator begin()
Definition Function.h:838
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:759
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:274
ThreadLocalMode getThreadLocalMode() const
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
bool hasAtLeastLocalUnnamedAddr() const
Returns true if this value's address is not significant in this module.
bool hasGlobalUnnamedAddr() const
UnnamedAddr getUnnamedAddr() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
bool isExternallyInitialized() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition Globals.cpp:647
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
LLVMContext & getContext() const
Definition Metadata.h:1245
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void insertGlobalVariable(GlobalVariable *GV)
Insert global variable GV at the end of the global variable list and take ownership.
Definition Module.h:657
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
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
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:340
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2295
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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...
void reserve(size_type N)
iterator erase(const_iterator CI)
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.
Value * getValueOperand()
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
int compare(StringRef RHS) const
Compare two strings; the result is negative, zero, or positive if this string is lexicographically le...
Definition StringRef.h:177
Class to represent struct types.
ArrayRef< Type * > elements() const
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ StructTyID
Structures.
Definition Type.h:75
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ PointerTyID
Pointers.
Definition Type.h:74
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Use * op_iterator
Definition User.h:254
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
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.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
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
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ X86_ThisCall
Similar to X86_StdCall.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
bool used(const UsedT *U, size_t I)
Definition DenseMap.h:117
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 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
@ Dead
Unused definition.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1560
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2911
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
LLVM_ABI bool optimizeGlobalCtorsList(Module &M, function_ref< bool(uint32_t, Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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
TargetTransformInfo TTI
DWARFExpression::Operation Op
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
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:966
Part of the global at a specific offset, which is only accessed through loads and stores with the giv...
Constant * Initializer
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
As we analyze each global or thread-local variable, keep track of some information about it.
@ InitializerStored
This global is stored to, but the only thing stored is the constant it was initialized with.
@ StoredOnce
This global is stored to, but only its initializer and one other value is ever stored to it.
static LLVM_ABI bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455