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