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