76 #define DEBUG_TYPE "globalopt" 78 STATISTIC(NumMarked ,
"Number of globals marked constant");
79 STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
80 STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
81 STATISTIC(NumHeapSRA ,
"Number of heap objects SRA'd");
82 STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
83 STATISTIC(NumDeleted ,
"Number of globals deleted");
84 STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
85 STATISTIC(NumLocalized ,
"Number of globals localized");
86 STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
87 STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
88 STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
89 STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
90 STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
91 STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
92 STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
93 STATISTIC(NumInternalFunc,
"Number of internal functions");
94 STATISTIC(NumColdCC,
"Number of functions marked coldcc");
98 cl::desc(
"Enable stress test of coldcc by adding " 99 "calling conv to all internal functions."),
105 "Maximum block frequency, expressed as a percentage of caller's " 106 "entry frequency, for a call site to be considered cold for enabling" 144 if (isa<PointerType>(InnerTy))
return true;
145 if (isa<CompositeType>(InnerTy))
151 if (--Limit == 0)
return true;
152 }
while (!Types.
empty());
162 if (isa<Constant>(V))
166 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
176 if (!
GEP->hasAllConstantIndices())
201 bool Changed =
false;
212 Value *V =
SI->getValueOperand();
213 if (isa<Constant>(V)) {
215 SI->eraseFromParent();
220 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
221 if (isa<Constant>(MSI->getValue())) {
223 MSI->eraseFromParent();
224 }
else if (
Instruction *
I = dyn_cast<Instruction>(MSI->getValue())) {
232 MTI->eraseFromParent();
233 }
else if (
Instruction *
I = dyn_cast<Instruction>(MemSrc)) {
237 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
238 if (CE->use_empty()) {
239 CE->destroyConstant();
242 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
244 C->destroyConstant();
253 for (
int i = 0,
e = Dead.
size(); i !=
e; ++i) {
255 Dead[i].second->eraseFromParent();
279 bool Changed =
false;
285 while (!WorkList.empty()) {
286 Value *UV = WorkList.pop_back_val();
290 User *U = cast<User>(UV);
292 if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
296 LI->eraseFromParent();
299 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
301 SI->eraseFromParent();
303 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
304 if (CE->getOpcode() == Instruction::GetElementPtr) {
309 }
else if ((CE->getOpcode() == Instruction::BitCast &&
310 CE->getType()->isPointerTy()) ||
311 CE->getOpcode() == Instruction::AddrSpaceCast) {
316 if (CE->use_empty()) {
317 CE->destroyConstant();
325 if (!isa<ConstantExpr>(
GEP->getOperand(0))) {
328 if (Init && CE && CE->
getOpcode() == Instruction::GetElementPtr)
334 if (Init && isa<ConstantAggregateZero>(Init) &&
GEP->isInBounds())
339 if (
GEP->use_empty()) {
340 GEP->eraseFromParent();
344 if (
MI->getRawDest() == V) {
345 MI->eraseFromParent();
349 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
353 C->destroyConstant();
372 !cast<Constant>(U->
getOperand(1))->isNullValue())
383 for (; GEPI !=
E; ++GEPI) {
405 if (!I)
return false;
408 if (isa<LoadInst>(I))
return true;
412 return SI->getOperand(0) != V;
423 if (!isa<GetElementPtrInst>(U) &&
424 (!isa<ConstantExpr>(U) ||
425 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
439 if (isa<StructType>(Init->
getType())) {
452 uint64_t FragmentOffsetInBits,
453 uint64_t FragmentSizeInBits,
454 unsigned NumElements) {
457 for (
auto *GVE : GVs) {
460 if (NumElements > 1) {
462 Expr, FragmentOffsetInBits, FragmentSizeInBits))
484 Type *Ty = Init->getType();
486 std::map<unsigned, GlobalVariable *> NewGlobals;
490 if (StartAlignment == 0)
497 Instruction::GetElementPtr) ||
498 isa<GetElementPtrInst>(
GEP)) &&
499 "NonGEP CE's are not SRAable!");
504 unsigned ElementIdx = cast<ConstantInt>(
GEP->getOperand(2))->getZExtValue();
505 if (NewGlobals.count(ElementIdx) == 1)
507 assert(NewGlobals.count(ElementIdx) == 0);
509 Type *ElTy =
nullptr;
510 if (
StructType *STy = dyn_cast<StructType>(Ty))
511 ElTy = STy->getElementType(ElementIdx);
513 ElTy = STy->getElementType();
516 Constant *
In = Init->getAggregateElement(ElementIdx);
517 assert(In &&
"Couldn't get element of initializer?");
525 NewGlobals.insert(std::make_pair(ElementIdx, NGV));
527 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
543 STy->getNumElements());
552 Align NewAlign(
MinAlign(StartAlignment, EltSize * ElementIdx));
553 if (NewAlign > EltAlign)
556 FragmentSizeInBits, STy->getNumElements());
560 if (NewGlobals.empty())
564 for (
auto NewGlobalVar : NewGlobals)
567 LLVM_DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV <<
"\n");
575 assert(((isa<ConstantExpr>(GEP) &&
576 cast<ConstantExpr>(GEP)->
getOpcode()==Instruction::GetElementPtr)||
577 isa<GetElementPtrInst>(GEP)) &&
"NonGEP CE's are not SRAable!");
582 unsigned ElementIdx = cast<ConstantInt>(GEP->
getOperand(2))->getZExtValue();
583 assert(NewGlobals.count(ElementIdx) == 1);
585 Value *NewPtr = NewGlobals[ElementIdx];
586 Type *NewTy = NewGlobals[ElementIdx]->getValueType();
593 for (
unsigned i = 3,
e = CE->getNumOperands(); i !=
e; ++i)
604 NewTy, NewPtr, Idxs, GEPI->
getName() +
"." +
Twine(ElementIdx),
611 GEPI->eraseFromParent();
613 cast<ConstantExpr>(
GEP)->destroyConstant();
620 assert(NewGlobals.size() > 0);
621 return NewGlobals.begin()->second;
636 if (isa<LoadInst>(U)) {
638 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
639 if (
SI->getOperand(0) == V) {
643 }
else if (
const CallInst *CI = dyn_cast<CallInst>(U)) {
644 if (CI->getCalledValue() != V) {
648 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
649 if (II->getCalledValue() != V) {
653 }
else if (
const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
657 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
662 }
else if (isa<ICmpInst>(U) &&
663 isa<ConstantPointerNull>(U->getOperand(1))) {
678 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
682 }
else if (isa<StoreInst>(U)) {
693 bool Changed =
false;
700 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
701 LI->setOperand(0, NewV);
703 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
704 if (
SI->getOperand(1) == V) {
705 SI->setOperand(1, NewV);
708 }
else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
715 bool PassedAsArg =
false;
716 for (
unsigned i = 0,
e = CS.
arg_size(); i !=
e; ++i)
727 }
else if (
CastInst *CI = dyn_cast<CastInst>(I)) {
731 if (CI->use_empty()) {
733 CI->eraseFromParent();
738 Idxs.
reserve(GEPI->getNumOperands()-1);
741 if (
Constant *
C = dyn_cast<Constant>(*i))
745 if (Idxs.
size() == GEPI->getNumOperands()-1)
749 if (GEPI->use_empty()) {
751 GEPI->eraseFromParent();
766 bool Changed =
false;
770 bool AllNonStoreUsesGone =
true;
774 User *GlobalUser = *GUI++;
775 if (
LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
778 if (LI->use_empty()) {
779 LI->eraseFromParent();
782 AllNonStoreUsesGone =
false;
784 }
else if (isa<StoreInst>(GlobalUser)) {
787 "Must be storing *to* the global");
789 AllNonStoreUsesGone =
false;
793 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
794 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
795 isa<BitCastInst>(GlobalUser) ||
796 isa<GetElementPtrInst>(GlobalUser)) &&
797 "Only expect load and stores!");
802 LLVM_DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
809 if (AllNonStoreUsesGone) {
833 I->replaceAllUsesWith(NewC);
837 while (UI !=
E && *UI ==
I)
840 I->eraseFromParent();
853 LLVM_DEBUG(
errs() <<
"PROMOTING GLOBAL: " << *GV <<
" CALL = " << *CI
858 GlobalType = AllocTy;
876 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
877 if (BCI->getType() == NewGV->getType()) {
879 BCI->eraseFromParent();
881 BCI->setOperand(0, NewGV);
898 GlobalValue::InternalLinkage,
901 bool InitBoolUsed =
false;
908 None,
SI->getOrdering(),
SI->getSyncScopeID(),
SI);
909 SI->eraseFromParent();
956 cast<StoreInst>(InitBool->
user_back())->eraseFromParent();
969 if (RepValue != NewGV)
984 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
988 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
989 if (
SI->getOperand(0) == V &&
SI->getOperand(1) != GV)
995 if (isa<GetElementPtrInst>(Inst) && Inst->
getNumOperands() >= 3) {
1001 if (
const PHINode *PN = dyn_cast<PHINode>(Inst)) {
1004 if (PHIs.
insert(PN).second)
1010 if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1032 if (
SI->getOperand(1) == GV) {
1033 SI->eraseFromParent();
1036 }
else if (
PHINode *PN = dyn_cast<PHINode>(U)) {
1039 InsertPt = PN->getIncomingBlock(*Alloc->
use_begin())->getTerminator();
1040 }
else if (isa<BitCastInst>(U)) {
1048 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1049 if (
StoreInst *
SI = dyn_cast<StoreInst>(GEPI->user_back()))
1050 if (
SI->getOperand(1) == GV) {
1054 GEPI->eraseFromParent();
1078 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
1079 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1087 if (GEPI->getNumOperands() < 3)
1094 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
1095 if (!LoadUsingPHIsPerLoad.
insert(PN).second)
1099 if (!LoadUsingPHIs.
insert(PN).second)
1105 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1125 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1127 LoadUsingPHIsPerLoad))
1129 LoadUsingPHIsPerLoad.
clear();
1137 for (
const PHINode *PN : LoadUsingPHIs) {
1138 for (
unsigned op = 0,
e = PN->getNumIncomingValues();
op !=
e; ++
op) {
1139 Value *InVal = PN->getIncomingValue(
op);
1142 if (InVal == StoredVal)
continue;
1144 if (
const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1146 if (LoadUsingPHIs.count(InPN))
1152 if (
const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1153 if (LI->getOperand(0) == GV)
1167 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1168 std::vector<std::pair<PHINode *, unsigned>> &PHIsToRewrite) {
1169 std::vector<Value *> &FieldVals = InsertedScalarizedValues[V];
1171 if (FieldNo >= FieldVals.size())
1172 FieldVals.resize(FieldNo+1);
1176 if (
Value *FieldVal = FieldVals[FieldNo])
1181 if (
LoadInst *LI = dyn_cast<LoadInst>(V)) {
1185 InsertedScalarizedValues, PHIsToRewrite);
1189 PHINode *PN = cast<PHINode>(V);
1194 StructType *
ST = cast<StructType>(PTy->getElementType());
1196 unsigned AS = PTy->getAddressSpace();
1202 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1205 return FieldVals[FieldNo] = Result;
1211 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1212 std::vector<std::pair<PHINode *, unsigned>> &PHIsToRewrite) {
1214 if (
ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1215 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1219 InsertedScalarizedValues, PHIsToRewrite);
1225 SCI->eraseFromParent();
1231 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1232 &&
"Unexpected GEPI!");
1235 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1237 InsertedScalarizedValues, PHIsToRewrite);
1242 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1247 GEPI->eraseFromParent();
1257 PHINode *PN = cast<PHINode>(LoadUser);
1258 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1259 std::vector<Value *>())).second)
1274 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1275 std::vector<std::pair<PHINode *, unsigned> > &PHIsToRewrite) {
1283 InsertedScalarizedValues.
erase(Load);
1292 LLVM_DEBUG(
dbgs() <<
"SROA HEAP ALLOC: " << *GV <<
" MALLOC = " << *CI
1305 std::vector<Value *> FieldGlobals;
1306 std::vector<Value *> FieldMallocs;
1312 for (
unsigned FieldNo = 0,
e = STy->
getNumElements(); FieldNo !=
e;++FieldNo){
1321 FieldGlobals.push_back(NGV);
1329 NElems, OpBundles,
nullptr,
1331 FieldMallocs.push_back(NMI);
1350 ConstantZero,
"isneg");
1351 for (
unsigned i = 0,
e = FieldMallocs.size(); i !=
e; ++i) {
1355 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond,
"tmp", CI);
1376 for (
unsigned i = 0,
e = FieldGlobals.size(); i !=
e; ++i) {
1378 new LoadInst(cast<GlobalVariable>(FieldGlobals[i])->getValueType(),
1379 FieldGlobals[i],
"tmp", NullPtrBlock);
1395 NullPtrBlock = NextBlock;
1406 InsertedScalarizedValues[GV] = FieldGlobals;
1408 std::vector<std::pair<PHINode *, unsigned>> PHIsToRewrite;
1416 if (
LoadInst *LI = dyn_cast<LoadInst>(User)) {
1424 "Unexpected heap-sra user!");
1427 for (
unsigned i = 0,
e = FieldGlobals.size(); i !=
e; ++i) {
1428 Type *ValTy = cast<GlobalValue>(FieldGlobals[i])->getValueType();
1430 new StoreInst(Null, FieldGlobals[i], SI);
1437 while (!PHIsToRewrite.empty()) {
1438 PHINode *PN = PHIsToRewrite.back().first;
1439 unsigned FieldNo = PHIsToRewrite.back().second;
1440 PHIsToRewrite.pop_back();
1441 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1455 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1457 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1458 PN->dropAllReferences();
1459 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1460 LI->dropAllReferences();
1465 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1467 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1468 PN->eraseFromParent();
1469 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1470 LI->eraseFromParent();
1477 return cast<GlobalVariable>(FieldGlobals[0]);
1518 if (
ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1537 if (
ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1538 AllocTy = AT->getElementType();
1560 OpBundles,
nullptr, CI->
getName());
1564 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1565 CI = cast<CallInst>(BCI->getOperand(0));
1567 CI = cast<CallInst>(Malloc);
1596 if (
Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1604 auto *TLI = &GetTLI(*CI->getFunction());
1635 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1653 "No reason to shrink to bool!");
1660 bool IsOneZero =
false;
1661 bool EmitOneOrZero =
true;
1663 if (CI && CI->getValue().getActiveBits() <= 64) {
1664 IsOneZero = InitVal->
isNullValue() && CI->isOne();
1667 if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
1669 uint64_t ValOther = CI->getZExtValue();
1670 uint64_t ValMinus = ValOther - ValInit;
1672 for(
auto *GVe : GVs){
1676 unsigned SizeInOctets =
1688 dwarf::DW_OP_deref_size, SizeInOctets,
1689 dwarf::DW_OP_constu, ValMinus,
1690 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
1692 bool WithStackValue =
true;
1698 EmitOneOrZero =
false;
1702 if (EmitOneOrZero) {
1713 bool StoringOther =
SI->getOperand(0) == OtherVal;
1716 if (StoringOther ||
SI->getOperand(0) == InitVal) {
1723 Instruction *StoredVal = cast<Instruction>(
SI->getOperand(0));
1728 if (
LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1729 assert(LI->getOperand(0) == GV &&
"Not a copy!");
1733 LI->getOrdering(), LI->getSyncScopeID(), LI);
1735 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1736 "This is not a form that we understand!");
1738 assert(isa<LoadInst>(StoreVal) &&
"Not a load of NewGV!");
1743 SI->getSyncScopeID(),
SI);
1785 if (
auto *
F = dyn_cast<Function>(&GV))
1786 Dead = (
F->isDeclaration() &&
F->use_empty()) ||
F->isDefTriviallyDead();
1814 for (
auto *U : GV->
users()) {
1816 for (
auto *UU : U->users()) {
1817 if (
auto *LI = dyn_cast<LoadInst>(UU))
1819 else if (
auto *
SI = dyn_cast<StoreInst>(UU))
1832 if (
auto *LI = dyn_cast<LoadInst>(I))
1834 else if (
auto *
SI = dyn_cast<StoreInst>(I))
1844 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1859 for (
auto *L : Loads) {
1860 auto *LTy = L->getType();
1866 return DT.dominates(S, L) &&
1884 for (
auto *U : C->
users()) {
1885 if (isa<Instruction>(U))
1887 if (!isa<ConstantExpr>(U))
1890 for (
auto *UU : U->users())
1891 if (!isa<Instruction>(UU))
1905 for (
auto *U : C->
users()) {
1906 if (isa<ConstantExpr>(U))
1912 isa<Instruction>(U) &&
1913 "Can't transform non-constantexpr non-instruction to instruction!");
1917 for (
auto *U : Users) {
1919 for (
auto *UU : U->users())
1921 for (
auto *UU : UUsers) {
1929 U->destroyConstant();
2016 LLVM_DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify " 2017 <<
"all users and delete global!\n");
2045 LLVM_DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to " 2046 <<
"simplify all users and delete global!\n");
2089 bool Changed =
false;
2108 if (GVar->isConstant() || !GVar->hasInitializer())
2118 if (isa<BlockAddress>(U))
2136 if (isa<BlockAddress>(U))
2159 if (isa<BlockAddress>(U))
2170 if (BB.getTerminatingMustTailCall())
2181 auto CallSiteFreq = CallerBFI.
getBlockFreq(CallSiteBB);
2182 auto CallerEntryFreq =
2184 return CallSiteFreq < CallerEntryFreq * ColdProb;
2194 const std::vector<Function *> &AllCallsCold) {
2200 if (isa<BlockAddress>(U))
2208 auto It =
std::find(AllCallsCold.begin(), AllCallsCold.end(), CallerFunc);
2209 if (It == AllCallsCold.end())
2217 if (isa<BlockAddress>(U))
2232 if (
CallInst *CI = dyn_cast<CallInst>(&
I)) {
2233 CallSite CS(cast<Instruction>(CI));
2235 if (CI->isInlineAsm())
2237 Function *CalledFn = CI->getCalledFunction();
2266 bool Changed =
false;
2268 std::vector<Function *> AllCallsCold;
2272 AllCallsCold.push_back(F);
2305 auto &DT = LookupDomTree(*F);
2372 bool Changed =
false;
2388 if (New && New !=
C)
2416 for (
unsigned i = 0,
e = STy->getNumElements(); i !=
e; ++i)
2422 assert(Idx < STy->getNumElements() &&
"Struct index out of range!");
2434 for (uint64_t i = 0,
e = NumElts; i !=
e; ++i)
2450 assert(GV->hasInitializer());
2451 GV->setInitializer(Val);
2507 for (
const auto &
I : Mem) {
2508 if (
auto *GV = dyn_cast<GlobalVariable>(
I.first)) {
2514 ComplexCEs.
push_back(std::make_pair(GEP,
I.second));
2516 SimpleCEs.
push_back(std::make_pair(GEP,
I.second));
2522 for (
auto ComplexCE : ComplexCEs)
2525 for (
auto GVPair : GVs) {
2526 assert(GVPair.first->hasInitializer());
2527 GVPair.first->setInitializer(GVPair.second);
2530 if (SimpleCEs.
empty())
2541 auto commitAndSetupCache = [&](
GlobalVariable *GV,
bool Update) {
2546 assert(CurrentGV &&
"Expected a GV to commit to!");
2549 if (
StructType *STy = dyn_cast<StructType>(CurrentInitTy))
2551 else if (
ArrayType *ArrTy = dyn_cast<ArrayType>(CurrentInitTy))
2556 if (CurrentGV == GV)
2562 if (
auto *STy = dyn_cast<StructType>(Ty))
2563 NumElts = STy->getNumElements();
2565 NumElts = cast<SequentialType>(Ty)->getNumElements();
2566 for (
unsigned i = 0,
e = NumElts; i !=
e; ++i)
2571 for (
auto CEPair : SimpleCEs) {
2576 commitAndSetupCache(GV, GV != CurrentGV);
2582 commitAndSetupCache(CurrentGV,
true);
2596 ++NumCtorsEvaluated;
2604 GV->setConstant(
true);
2630 UsedArray.push_back(Cast);
2664 iterator usedBegin() {
return Used.
begin(); }
2665 iterator usedEnd() {
return Used.
end(); }
2667 used_iterator_range used() {
2668 return used_iterator_range(usedBegin(), usedEnd());
2671 iterator compilerUsedBegin() {
return CompilerUsed.
begin(); }
2672 iterator compilerUsedEnd() {
return CompilerUsed.
end(); }
2674 used_iterator_range compilerUsed() {
2675 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2681 return CompilerUsed.
count(GV);
2689 return CompilerUsed.
insert(GV).second;
2692 void syncVariablesAndSets() {
2706 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2707 "We should have removed the duplicated " 2708 "element from llvm.compiler.used");
2715 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2719 const LLVMUsed &U) {
2721 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2722 "We should have removed the duplicated " 2723 "element from llvm.compiler.used");
2724 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2733 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2737 bool &RenameTarget) {
2738 RenameTarget =
false;
2764 RenameTarget =
true;
2771 bool Changed =
false;
2775 Used.compilerUsedErase(GV);
2809 ++NumAliasesResolved;
2820 if (Used.usedErase(&*J))
2821 Used.usedInsert(Target);
2823 if (Used.compilerUsedErase(&*J))
2824 Used.compilerUsedInsert(Target);
2830 ++NumAliasesRemoved;
2834 Used.syncVariablesAndSets();
2842 auto FuncIter = M.
begin();
2843 if (FuncIter == M.
end())
2845 auto *TLI = &GetTLI(*FuncIter);
2847 LibFunc F = LibFunc_cxa_atexit;
2859 if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit)
2876 if (isa<DbgInfoIntrinsic>(
I))
2878 if (isa<ReturnInst>(
I))
2900 bool Changed =
false;
2920 ++NumCXXDtorsRemoved;
2935 bool Changed =
false;
2936 bool LocalChange =
true;
2937 while (LocalChange) {
2938 LocalChange =
false;
2940 NotDiscardableComdats.
clear();
2944 NotDiscardableComdats.
insert(
C);
2948 NotDiscardableComdats.
insert(
C);
2950 if (
const Comdat *
C = GA.getComdat())
2951 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2952 NotDiscardableComdats.
insert(
C);
2956 NotDiscardableComdats);
2976 Changed |= LocalChange;
3010 struct GlobalOptLegacyPass :
public ModulePass {
3017 bool runOnModule(
Module &M)
override {
3023 return this->getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
3026 return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3029 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3033 return this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
3053 "Global Variable Optimizer",
false,
false)
3062 return new GlobalOptLegacyPass();
void setVisibility(VisibilityTypes V)
bool isBoundedSequential() const
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getAlignment() const
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
ThreadLocalMode getThreadLocalMode() const
void initializeGlobalOptLegacyPassPass(PassRegistry &)
bool IsLoaded
True if the global is ever loaded.
static bool isLeakCheckerRoot(GlobalVariable *GV)
Is this global variable possibly used by a leak checker as a root? If so, we might not really want to...
static IntegerType * getInt1Ty(LLVMContext &C)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * StoredOnceValue
If only one value (besides the initializer constant) is ever stored to this global, keep track of what value it is.
const Function * AccessingFunction
These start out null/false.
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Atomic ordering constants.
bool hasPrivateLinkage() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static bool CanDoGlobalSRA(GlobalVariable *GV)
iterator erase(iterator where)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Type * getElementType(unsigned N) const
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a getelementptr constantexpr, return the constant value being addressed by the constant expression, or null if something is funny and we can't decide.
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
We just marked GV constant.
static Value * GetHeapSROAValue(Value *V, unsigned FieldNo, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned >> &PHIsToRewrite)
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, GlobalVariable *GV)
The Alloc pointer is stored into GV somewhere.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
This class represents zero extension of integer types.
unsigned getNumElements() const
Random access to the elements.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
void push_back(const T &Elt)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
LLVM_NODISCARD int compare(StringRef RHS) const
compare - Compare two strings; the result is -1, 0, or 1 if this string is lexicographically less tha...
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static bool isSafeSROAElementUse(Value *V)
Return true if the specified instruction is a safe user of a derived expression from a global that we...
static bool cxxDtorIsEmpty(const Function &Fn)
Returns whether the given function is an empty C++ destructor and can therefore be eliminated...
static bool deleteIfDead(GlobalValue &GV, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
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.
gep_type_iterator gep_type_end(const User *GEP)
An efficient, type-erasing, non-owning reference to a callable.
static bool hasChangeableCC(Function *F)
Return true if this is a calling convention that we'd like to change.
static Constant * EvaluateStoreInto(Constant *Init, Constant *Val, ConstantExpr *Addr, unsigned OpNo)
Evaluate a piece of a constantexpr store into a global initializer.
Analysis pass providing the TargetTransformInfo.
static bool hasOnlyColdCalls(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
static GlobalVariable * OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy, ConstantInt *NElements, const DataLayout &DL, TargetLibraryInfo *TLI)
This function takes the specified global variable, and transforms the program as if it always contain...
static bool isSafeSROAGEP(User *U)
Return true if the specified GEP is a safe user of a derived expression from a global that we want to...
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
bool HasMultipleAccessingFunctions
LLVMContext & getContext() const
All values hold a context through their type.
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class wraps the llvm.memset intrinsic.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
C - The default llvm calling convention, compatible with C.
STATISTIC(NumFunctions, "Total number of functions")
static cl::opt< bool > EnableColdCCStressTest("enable-coldcc-stress-test", cl::desc("Enable stress test of coldcc by adding " "calling conv to all internal functions."), cl::init(false), cl::Hidden)
Analysis pass which computes a DominatorTree.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
Generate the IR for a call to the builtin free function.
iv Induction Variable Users
static GlobalVariable * PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, Value *NElems, const DataLayout &DL, const TargetLibraryInfo *TLI)
CI is an allocation of an array of structures.
This defines the Use class.
void reserve(size_type N)
bool isMustTailCall() const
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...
static bool processGlobal(GlobalValue &GV, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
LLVMContext & getContext() const
Get the context in which this basic block lives.
static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V, SmallPtrSetImpl< const PHINode *> &LoadUsingPHIs, SmallPtrSetImpl< const PHINode *> &LoadUsingPHIsPerLoad)
Verify that all uses of V (a load, or a phi of a load) are simple enough to perform heap SRA on...
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
This global is stored to, but the only thing stored is the constant it was initialized with...
static int compareNames(Constant *const *A, Constant *const *B)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
Value * getArgOperand(unsigned i) const
unsigned getAllocaAddrSpace() const
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, bool &RenameTarget)
static void makeAllConstantUsesInstructions(Constant *C)
C may have non-instruction users, and allNonInstructionUsersCanBeMadeInstructions has returned true...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static bool isColdCallSite(CallSite CS, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV)
Return true if all uses of any loads from GV will trap if the loaded value is null.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const CallInst * extractMallocCall(const Value *I, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
This is the base class for all instructions that perform data casts.
TypeID getTypeID() const
Return the type id for the type.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
static void changeCallSitesToColdCC(Function *F)
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
uint64_t getElementOffsetInBits(unsigned Idx) const
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
UnnamedAddr getUnnamedAddr() const
static bool CleanupPointerRootUsers(GlobalVariable *GV, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
This GV is a pointer root.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
This file contains the simple types necessary to represent the attributes associated with functions a...
Legacy analysis pass which computes BlockFrequencyInfo.
StoredType
Keep track of what stores to the global look like.
static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U)
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
void setDLLStorageClass(DLLStorageClassTypes C)
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
At this point, we have learned that the only two values ever stored into GV are its initializer and O...
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
AtomicOrdering
Atomic ordering for LLVM's memory model.
INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt", "Global Variable Optimizer", false, false) INITIALIZE_PASS_END(GlobalOptLegacyPass
global_iterator global_begin()
InstrTy * getInstruction() const
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static cl::opt< int > ColdCCRelFreq("coldcc-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::desc("Maximum block frequency, expressed as a percentage of caller's " "entry frequency, for a call site to be considered cold for enabling" "coldcc"))
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
A constant value that is initialized with an expression using other constant values.
void setArgument(unsigned ArgNo, Value *newVal)
Type * getType() const
All values are typed, get the type of this value.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSetImpl< GlobalValue *> &Init)
Class to represent array types.
static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, const GlobalVariable *GV, SmallPtrSetImpl< const PHINode *> &PHIs)
Scan the use-list of V checking to make sure that there are no complex uses of V. ...
This class represents a no-op cast from one type to another.
AttributeList getAttributes() const
Return the attribute list for this Function.
An instruction for storing to memory.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void takeName(Value *V)
Transfer the name from V to this value.
Type::subtype_iterator element_iterator
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)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Class to represent pointers.
This global is stored to, but only its initializer and one other value is ever stored to it...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
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...
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Value * getMallocArraySize(CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
getMallocArraySize - Returns the array size of a malloc call.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
void setCallingConv(CallingConv::ID CC)
initializer< Ty > init(const Ty &Val)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
As we analyze each global, keep track of some information about it.
void setCalledFunction(Value *V)
Set the callee to the specified value.
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
DLLStorageClassTypes getDLLStorageClass() const
VisibilityTypes getVisibility() const
alias_iterator alias_end()
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
AttributeList getAttributes() const
Get the parameter attributes of the call.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void setExternallyInitialized(bool Val)
ValTy * getArgument(unsigned ArgNo) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
element_iterator element_end() const
A pair of DIGlobalVariable and DIExpression.
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
static 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.
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
static Constant * get(StructType *T, ArrayRef< Constant *> V)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Base class for variables.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
ModulePass * createGlobalOptimizerPass()
createGlobalOptimizerPass - This function returns a new pass that optimizes non-address taken interna...
static bool isValidCandidateForColdCC(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, const std::vector< Function *> &AllCallsCold)
static bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
const Function * getFunction() const
Return the function this instruction belongs to.
void setConstant(bool Val)
static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, const LLVMUsed &U)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static void ConstantPropUsersOf(Value *V, const DataLayout &DL, TargetLibraryInfo *TLI)
Walk the use list of V, constant folding all of the instructions that are foldable.
static void RewriteHeapSROALoadUser(Instruction *LoadUser, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned >> &PHIsToRewrite)
Given a load instruction and a value derived from the load, rewrite the derived value to use the Heap...
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, Attribute::AttrKind A)
bool doesNotRecurse() const
Determine if the function is known not to recurse, directly or indirectly.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
global_iterator global_end()
This is the superclass of the array and vector type classes.
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallPtrSetImpl< GlobalValue *> &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Global Variable Optimizer
This is the shared class of boolean and integer constants.
static void CommitValueTo(Constant *Val, Constant *Addr)
We have decided that Addr (which satisfies the predicate isSimpleEnoughPointerToCommit) should get Va...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
16: SIMD 'packed' format, or other vector type
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
unsigned arg_size() const
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
alias_iterator alias_begin()
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
bool hasGlobalUnnamedAddr() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
void setLinkage(LinkageTypes LT)
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, TargetLibraryInfo *TLI)
Evaluate static constructors in the function, if we can.
A range adaptor for a pair of iterators.
This file contains constants used for implementing Dwarf debug support.
const Comdat * getComdat() const
Target - Wrapper for Target specific information.
void push_back(pointer val)
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
iterator_range< user_iterator > users()
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, AtomicOrdering Ordering, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C)
C may have non-instruction users.
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
element_iterator element_begin() const
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=nullptr, Function *MallocF=nullptr, const Twine &Name="")
Generate the IR for a call to malloc:
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
static void BatchCommitValueTo(const DenseMap< Constant *, Constant *> &Mem)
Given a map of address -> value, where addresses are expected to be some form of either a global or a...
const Comdat * getComdat() const
Predicate getPredicate() const
Return the predicate for this instruction.
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, Instruction *StoredVal)
If all users of values loaded from GV are simple enough to perform HeapSRA, return true...
This class wraps the llvm.memcpy/memmove intrinsics.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
static bool GlobalUsersSafeToSRA(GlobalValue *GV)
Look at all uses of the global and decide whether it is safe for us to perform this transformation...
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void setAlignment(MaybeAlign Align)
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)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t getElementOffset(unsigned Idx) const
static IntegerType * getInt32Ty(LLVMContext &C)
bool IsCompared
True if the global's address is used in a comparison.
uint64_t getSequentialNumElements() const
Value * getOperand() const
LLVM_NODISCARD bool empty() const
AtomicOrdering Ordering
Set to the strongest atomic ordering requirement.
unsigned greater or equal
static bool OptimizeGlobalAliases(Module &M, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
StringRef getName() const
Return a constant reference to the value's name.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
const Function * getParent() const
Return the enclosing method, or null if none.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
Perform scalar replacement of aggregates on the specified global variable.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
const DenseMap< Constant *, Constant * > & getMutatedMemory() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Rename collisions when linking (static functions).
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
static bool tryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI, Type *AllocTy, AtomicOrdering Ordering, const DataLayout &DL, TargetLibraryInfo *TLI)
This function is called when we see a pointer global variable with a single value stored it that is a...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Analysis pass providing the TargetLibraryInfo.
static void RemoveAttribute(Function *F, Attribute::AttrKind A)
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, uint64_t FragmentOffsetInBits, uint64_t FragmentSizeInBits, unsigned NumElements)
Copy over the debug info for a variable to its SRA replacements.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV)
bool hasInitializer() const
Definitions have initializers, declarations don't.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Type * getElementType() const
iterator_range< global_iterator > globals()
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
static bool isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV, function_ref< DominatorTree &(Function &)> LookupDomTree)
bool optimizeGlobalCtorsList(Module &M, function_ref< bool(Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
static bool OptimizeGlobalVars(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
We are performing Heap SRoA on a global.
bool isExternallyInitialized() const
void setSection(StringRef S)
Change the section for this global.
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
static Constant * get(ArrayRef< Constant *> V)
static bool AllUsesOfValueWillTrapIfNull(const Value *V, SmallPtrSetImpl< const PHINode *> &PHIs)
Return true if all users of the specified value will trap if the value is dynamically null...
Type * getElementType() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
X86_ThisCall - Similar to X86_StdCall.
bool isArrayTy() const
True if this is an instance of ArrayType.
static 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 Function * FindCXAAtExit(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
gep_type_iterator gep_type_begin(const User *GEP)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
const Constant * getAliasee() const
FunTy * getCaller() const
Return the caller function for this call site.