51 #define DEBUG_TYPE "globalopt"
53 STATISTIC(NumMarked ,
"Number of globals marked constant");
54 STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
55 STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
56 STATISTIC(NumHeapSRA ,
"Number of heap objects SRA'd");
57 STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
58 STATISTIC(NumDeleted ,
"Number of globals deleted");
59 STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
60 STATISTIC(NumLocalized ,
"Number of globals localized");
61 STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
62 STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
63 STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
64 STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
65 STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
66 STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
67 STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
104 if (isa<PointerType>(InnerTy))
return true;
105 if (isa<CompositeType>(InnerTy))
111 if (--Limit == 0)
return true;
112 }
while (!Types.
empty());
121 if (isa<Constant>(V))
125 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
135 if (!
GEP->hasAllConstantIndices())
159 bool Changed =
false;
170 Value *V =
SI->getValueOperand();
171 if (isa<Constant>(V)) {
173 SI->eraseFromParent();
178 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
179 if (isa<Constant>(MSI->getValue())) {
181 MSI->eraseFromParent();
182 }
else if (
Instruction *
I = dyn_cast<Instruction>(MSI->getValue())) {
190 MTI->eraseFromParent();
191 }
else if (
Instruction *
I = dyn_cast<Instruction>(MemSrc)) {
195 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
196 if (CE->use_empty()) {
197 CE->destroyConstant();
200 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
202 C->destroyConstant();
211 for (
int i = 0, e = Dead.
size();
i != e; ++
i) {
213 Dead[
i].second->eraseFromParent();
237 bool Changed =
false;
243 while (!WorkList.empty()) {
244 Value *UV = WorkList.pop_back_val();
248 User *U = cast<User>(UV);
250 if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
254 LI->eraseFromParent();
257 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
259 SI->eraseFromParent();
261 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
262 if (CE->getOpcode() == Instruction::GetElementPtr) {
267 }
else if ((CE->getOpcode() == Instruction::BitCast &&
268 CE->getType()->isPointerTy()) ||
269 CE->getOpcode() == Instruction::AddrSpaceCast) {
274 if (CE->use_empty()) {
275 CE->destroyConstant();
283 if (!isa<ConstantExpr>(
GEP->getOperand(0))) {
286 if (Init && CE && CE->
getOpcode() == Instruction::GetElementPtr)
292 if (Init && isa<ConstantAggregateZero>(Init) &&
GEP->isInBounds())
297 if (
GEP->use_empty()) {
298 GEP->eraseFromParent();
302 if (
MI->getRawDest() == V) {
303 MI->eraseFromParent();
307 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
311 C->destroyConstant();
328 if (!I)
return false;
331 if (isa<LoadInst>(I))
return true;
335 return SI->getOperand(0) != V;
339 if (!GEPI)
return false;
342 !cast<Constant>(GEPI->
getOperand(1))->isNullValue())
356 if (!isa<GetElementPtrInst>(U) &&
357 (!isa<ConstantExpr>(U) ||
358 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
366 !cast<Constant>(U->
getOperand(1))->isNullValue() ||
435 Type *Ty = Init->getType();
437 std::vector<GlobalVariable*> NewGlobals;
442 if (StartAlignment == 0)
445 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
446 NewGlobals.reserve(STy->getNumElements());
448 for (
unsigned i = 0, e = STy->getNumElements();
i != e; ++
i) {
450 assert(In &&
"Couldn't get element of initializer?");
459 NewGlobals.push_back(NGV);
470 unsigned NumElements = STy->getNumElements();
473 NewGlobals.reserve(NumElements);
477 for (
unsigned i = 0, e = NumElements;
i != e; ++
i) {
479 assert(In &&
"Couldn't get element of initializer?");
489 NewGlobals.push_back(NGV);
495 if (NewAlign > EltAlign)
500 if (NewGlobals.empty())
503 DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV <<
"\n");
511 assert(((isa<ConstantExpr>(GEP) &&
512 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
513 isa<GetElementPtrInst>(GEP)) &&
"NonGEP CE's are not SRAable!");
518 unsigned Val = cast<ConstantInt>(GEP->
getOperand(2))->getZExtValue();
519 if (Val >= NewGlobals.size()) Val = 0;
521 Value *NewPtr = NewGlobals[Val];
522 Type *NewTy = NewGlobals[Val]->getValueType();
529 for (
unsigned i = 3, e = CE->getNumOperands();
i != e; ++
i)
540 NewTy, NewPtr, Idxs, GEPI->
getName() +
"." +
Twine(Val), GEPI);
546 GEPI->eraseFromParent();
548 cast<ConstantExpr>(
GEP)->destroyConstant();
558 unsigned FirstGlobal = 0;
559 for (
unsigned i = 0, e = NewGlobals.size();
i != e; ++
i)
560 if (NewGlobals[
i]->use_empty()) {
561 Globals.
erase(NewGlobals[
i]);
562 if (FirstGlobal == i) ++FirstGlobal;
565 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] :
nullptr;
574 if (isa<LoadInst>(U)) {
576 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
577 if (
SI->getOperand(0) == V) {
581 }
else if (
const CallInst *CI = dyn_cast<CallInst>(U)) {
582 if (CI->getCalledValue() != V) {
586 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
587 if (II->getCalledValue() != V) {
591 }
else if (
const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
595 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
600 }
else if (isa<ICmpInst>(U) &&
601 isa<ConstantPointerNull>(U->getOperand(1))) {
616 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
620 }
else if (isa<StoreInst>(U)) {
631 bool Changed =
false;
634 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
635 LI->setOperand(0, NewV);
637 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
638 if (
SI->getOperand(1) == V) {
639 SI->setOperand(1, NewV);
642 }
else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
649 bool PassedAsArg =
false;
650 for (
unsigned i = 0, e = CS.
arg_size();
i != e; ++
i)
661 }
else if (
CastInst *CI = dyn_cast<CastInst>(I)) {
665 if (CI->use_empty()) {
667 CI->eraseFromParent();
672 Idxs.
reserve(GEPI->getNumOperands()-1);
679 if (Idxs.
size() == GEPI->getNumOperands()-1)
682 if (GEPI->use_empty()) {
684 GEPI->eraseFromParent();
700 bool Changed =
false;
704 bool AllNonStoreUsesGone =
true;
708 User *GlobalUser = *GUI++;
709 if (
LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
712 if (LI->use_empty()) {
713 LI->eraseFromParent();
716 AllNonStoreUsesGone =
false;
718 }
else if (isa<StoreInst>(GlobalUser)) {
721 "Must be storing *to* the global");
723 AllNonStoreUsesGone =
false;
727 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
728 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
729 isa<BitCastInst>(GlobalUser) ||
730 isa<GetElementPtrInst>(GlobalUser)) &&
731 "Only expect load and stores!");
736 DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV <<
"\n");
742 if (AllNonStoreUsesGone) {
750 DEBUG(
dbgs() <<
" *** GLOBAL NOW DEAD!\n");
766 I->replaceAllUsesWith(NewC);
770 while (UI !=
E && *UI ==
I)
773 I->eraseFromParent();
786 DEBUG(
errs() <<
"PROMOTING GLOBAL: " << *GV <<
" CALL = " << *CI <<
'\n');
790 GlobalType = AllocTy;
808 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
809 if (BCI->getType() == NewGV->getType()) {
811 BCI->eraseFromParent();
813 BCI->setOperand(0, NewGV);
830 GlobalValue::InternalLinkage,
833 bool InitBoolUsed =
false;
840 SI->getOrdering(),
SI->getSynchScope(),
SI);
841 SI->eraseFromParent();
887 cast<StoreInst>(InitBool->
user_back())->eraseFromParent();
900 if (RepValue != NewGV)
915 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
919 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
920 if (
SI->getOperand(0) == V &&
SI->getOperand(1) != GV)
926 if (isa<GetElementPtrInst>(Inst) && Inst->
getNumOperands() >= 3) {
932 if (
const PHINode *PN = dyn_cast<PHINode>(Inst)) {
935 if (PHIs.
insert(PN).second)
941 if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
963 if (
SI->getOperand(1) == GV) {
964 SI->eraseFromParent();
967 }
else if (
PHINode *PN = dyn_cast<PHINode>(U)) {
970 InsertPt = PN->getIncomingBlock(*Alloc->
use_begin())->getTerminator();
971 }
else if (isa<BitCastInst>(U)) {
979 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
980 if (
StoreInst *
SI = dyn_cast<StoreInst>(GEPI->user_back()))
981 if (
SI->getOperand(1) == GV) {
985 GEPI->eraseFromParent();
1008 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
1009 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1017 if (GEPI->getNumOperands() < 3)
1024 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
1025 if (!LoadUsingPHIsPerLoad.
insert(PN).second)
1029 if (!LoadUsingPHIs.
insert(PN).second)
1035 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1056 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1058 LoadUsingPHIsPerLoad))
1060 LoadUsingPHIsPerLoad.
clear();
1068 for (
const PHINode *PN : LoadUsingPHIs) {
1069 for (
unsigned op = 0, e = PN->getNumIncomingValues();
op != e; ++
op) {
1070 Value *InVal = PN->getIncomingValue(
op);
1073 if (InVal == StoredVal)
continue;
1075 if (
const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1077 if (LoadUsingPHIs.count(InPN))
1083 if (
const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1084 if (LI->getOperand(0) == GV)
1098 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1099 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1100 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1102 if (FieldNo >= FieldVals.size())
1103 FieldVals.resize(FieldNo+1);
1107 if (
Value *FieldVal = FieldVals[FieldNo])
1112 if (
LoadInst *LI = dyn_cast<LoadInst>(V)) {
1116 InsertedScalarizedValues,
1120 PHINode *PN = cast<PHINode>(V);
1125 StructType *
ST = cast<StructType>(PTy->getElementType());
1127 unsigned AS = PTy->getAddressSpace();
1133 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1136 return FieldVals[FieldNo] = Result;
1142 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1143 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1145 if (
ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1146 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1150 InsertedScalarizedValues, PHIsToRewrite);
1156 SCI->eraseFromParent();
1162 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1163 &&
"Unexpected GEPI!");
1166 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1168 InsertedScalarizedValues, PHIsToRewrite);
1173 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1178 GEPI->eraseFromParent();
1188 PHINode *PN = cast<PHINode>(LoadUser);
1189 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1190 std::vector<Value*>())).second)
1205 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1206 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1214 InsertedScalarizedValues.
erase(Load);
1223 DEBUG(
dbgs() <<
"SROA HEAP ALLOC: " << *GV <<
" MALLOC = " << *CI <<
'\n');
1235 std::vector<Value*> FieldGlobals;
1236 std::vector<Value*> FieldMallocs;
1242 for (
unsigned FieldNo = 0, e = STy->
getNumElements(); FieldNo != e;++FieldNo){
1251 FieldGlobals.push_back(NGV);
1259 NElems, OpBundles,
nullptr,
1261 FieldMallocs.push_back(NMI);
1280 ConstantZero,
"isneg");
1281 for (
unsigned i = 0, e = FieldMallocs.size();
i != e; ++
i) {
1285 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond,
"tmp", CI);
1306 for (
unsigned i = 0, e = FieldGlobals.size();
i != e; ++
i) {
1307 Value *GVVal =
new LoadInst(FieldGlobals[
i],
"tmp", NullPtrBlock);
1323 NullPtrBlock = NextBlock;
1334 InsertedScalarizedValues[GV] = FieldGlobals;
1336 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1344 if (
LoadInst *LI = dyn_cast<LoadInst>(User)) {
1352 "Unexpected heap-sra user!");
1355 for (
unsigned i = 0, e = FieldGlobals.size();
i != e; ++
i) {
1356 Type *ValTy = cast<GlobalValue>(FieldGlobals[
i])->getValueType();
1365 while (!PHIsToRewrite.empty()) {
1366 PHINode *PN = PHIsToRewrite.back().first;
1367 unsigned FieldNo = PHIsToRewrite.back().second;
1368 PHIsToRewrite.pop_back();
1369 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1383 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1385 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1386 PN->dropAllReferences();
1387 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1388 LI->dropAllReferences();
1393 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1395 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1396 PN->eraseFromParent();
1397 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1398 LI->eraseFromParent();
1405 return cast<GlobalVariable>(FieldGlobals[0]);
1446 if (
ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1465 if (
ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1466 AllocTy = AT->getElementType();
1488 OpBundles,
nullptr, CI->
getName());
1492 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1493 CI = cast<CallInst>(BCI->getOperand(0));
1495 CI = cast<CallInst>(Malloc);
1521 if (
Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1559 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1562 DEBUG(
dbgs() <<
" *** SHRINKING TO BOOL: " << *GV <<
"\n");
1577 "No reason to shrink to bool!");
1581 bool IsOneZero =
false;
1582 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1583 IsOneZero = InitVal->
isNullValue() && CI->isOne();
1589 bool StoringOther =
SI->getOperand(0) == OtherVal;
1592 if (StoringOther ||
SI->getOperand(0) == InitVal) {
1599 Instruction *StoredVal = cast<Instruction>(
SI->getOperand(0));
1604 if (
LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1605 assert(LI->getOperand(0) == GV &&
"Not a copy!");
1608 LI->getOrdering(), LI->getSynchScope(), LI);
1610 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1611 "This is not a form that we understand!");
1613 assert(isa<LoadInst>(StoreVal) &&
"Not a load of NewGV!");
1616 new StoreInst(StoreVal, NewGV,
false, 0,
1617 SI->getOrdering(),
SI->getSynchScope(),
SI);
1653 if (
auto *
F = dyn_cast<Function>(&GV))
1654 Dead = (
F->isDeclaration() &&
F->use_empty()) ||
F->isDefTriviallyDead();
1660 DEBUG(
dbgs() <<
"GLOBAL DEAD: " << GV <<
"\n");
1682 for (
auto *U : GV->
users()) {
1684 for (
auto *UU : U->users()) {
1685 if (
auto *LI = dyn_cast<LoadInst>(UU))
1687 else if (
auto *
SI = dyn_cast<StoreInst>(UU))
1700 if (
auto *LI = dyn_cast<LoadInst>(I))
1702 else if (
auto *
SI = dyn_cast<StoreInst>(I))
1712 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1727 for (
auto *
L : Loads) {
1728 auto *LTy =
L->getType();
1734 return DT.dominates(S,
L) &&
1752 for (
auto *U : C->
users()) {
1753 if (isa<Instruction>(U))
1755 if (!isa<ConstantExpr>(U))
1758 for (
auto *UU : U->users())
1759 if (!isa<Instruction>(UU))
1773 for (
auto *U : C->
users()) {
1774 if (isa<ConstantExpr>(U))
1780 isa<Instruction>(U) &&
1781 "Can't transform non-constantexpr non-instruction to instruction!");
1785 for (
auto *U : Users) {
1787 for (
auto *UU : U->users())
1789 for (
auto *UU : UUsers) {
1795 U->dropAllReferences();
1822 DEBUG(
dbgs() <<
"LOCALIZING GLOBAL: " << *GV <<
"\n");
1843 DEBUG(
dbgs() <<
"GLOBAL NEVER LOADED: " << *GV <<
"\n");
1865 DEBUG(
dbgs() <<
"MARKING CONSTANT: " << *GV <<
"\n");
1873 DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify "
1874 <<
"all users and delete global!\n");
1902 DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to "
1903 <<
"simplify all users and delete global!\n");
1944 bool Changed =
false;
1963 if (GVar->isConstant() || !GVar->hasInitializer())
1973 if (isa<BlockAddress>(U))
1996 if (isa<BlockAddress>(U))
2017 bool Changed =
false;
2061 bool Changed =
false;
2074 if (New && New !=
C)
2102 for (
unsigned i = 0, e = STy->getNumElements();
i != e; ++
i)
2108 assert(Idx < STy->getNumElements() &&
"Struct index out of range!");
2120 for (uint64_t
i = 0, e = NumElts;
i != e; ++
i)
2136 assert(GV->hasInitializer());
2137 GV->setInitializer(Val);
2157 ++NumCtorsEvaluated;
2160 DEBUG(
dbgs() <<
"FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2166 GV->setConstant(
true);
2192 UsedArray.push_back(Cast);
2223 iterator usedBegin() {
return Used.
begin(); }
2224 iterator usedEnd() {
return Used.end(); }
2225 used_iterator_range used() {
2226 return used_iterator_range(usedBegin(), usedEnd());
2228 iterator compilerUsedBegin() {
return CompilerUsed.begin(); }
2229 iterator compilerUsedEnd() {
return CompilerUsed.end(); }
2230 used_iterator_range compilerUsed() {
2231 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2233 bool usedCount(
GlobalValue *GV)
const {
return Used.count(GV); }
2235 return CompilerUsed.count(GV);
2237 bool usedErase(
GlobalValue *GV) {
return Used.erase(GV); }
2238 bool compilerUsedErase(
GlobalValue *GV) {
return CompilerUsed.erase(GV); }
2239 bool usedInsert(
GlobalValue *GV) {
return Used.insert(GV).second; }
2241 return CompilerUsed.insert(GV).second;
2244 void syncVariablesAndSets() {
2257 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2258 "We should have removed the duplicated "
2259 "element from llvm.compiler.used");
2266 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2270 const LLVMUsed &U) {
2272 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2273 "We should have removed the duplicated "
2274 "element from llvm.compiler.used");
2275 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2284 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2288 bool &RenameTarget) {
2289 RenameTarget =
false;
2315 RenameTarget =
true;
2322 bool Changed =
false;
2326 Used.compilerUsedErase(GV);
2360 ++NumAliasesResolved;
2370 if (Used.usedErase(&*J))
2371 Used.usedInsert(Target);
2373 if (Used.compilerUsedErase(&*J))
2374 Used.compilerUsedInsert(Target);
2380 ++NumAliasesRemoved;
2384 Used.syncVariablesAndSets();
2399 if (!TLI->
getLibFunc(*Fn, F) || F != LibFunc::cxa_atexit)
2424 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
2426 if (isa<DbgInfoIntrinsic>(CI))
2429 const Function *CalledFn = CI->getCalledFunction();
2437 if (!NewCalledFunctions.
insert(CalledFn).second)
2442 }
else if (isa<ReturnInst>(*
I))
2444 else if (
I->mayHaveSideEffects())
2466 bool Changed =
false;
2490 ++NumCXXDtorsRemoved;
2502 bool Changed =
false;
2503 bool LocalChange =
true;
2504 while (LocalChange) {
2505 LocalChange =
false;
2507 NotDiscardableComdats.
clear();
2511 NotDiscardableComdats.
insert(
C);
2515 NotDiscardableComdats.
insert(
C);
2517 if (
const Comdat *
C = GA.getComdat())
2518 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2519 NotDiscardableComdats.
insert(
C);
2532 NotDiscardableComdats);
2543 Changed |= LocalChange;
2566 struct GlobalOptLegacyPass :
public ModulePass {
2572 bool runOnModule(
Module &M)
override {
2577 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2579 return this->getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
2593 "Global Variable Optimizer",
false,
false)
2600 return new GlobalOptLegacyPass();
void setVisibility(VisibilityTypes V)
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
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. ...
LinkageTypes getLinkage() const
static ConstantInt * getFalse(LLVMContext &Context)
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, const DataLayout &DL, TargetLibraryInfo *TLI)
We just marked GV constant.
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.
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.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
VisibilityTypes getVisibility() const
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)
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI)
Given a value that is stored to a global but never read, determine whether it's safe to remove the st...
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
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.
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 ...
A Module instance is used to store all the information related to an LLVM module. ...
static bool optimizeGlobalsInModule(Module &M, const DataLayout &DL, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, GlobalVariable *GV)
The Alloc pointer is stored into GV somewhere.
This class represents zero extension of integer types.
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
unsigned getNumOperands() const
UnnamedAddr getUnnamedAddr() const
static bool isSafeSROAElementUse(Value *V)
Return true if the specified instruction is a safe user of a derived expression from a global that we...
Type * getValueType() const
This class represents a function call, abstracting a target machine's calling convention.
void setAttributes(AttributeSet PAL)
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
gep_type_iterator gep_type_end(const User *GEP)
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
An efficient, type-erasing, non-owning reference to a callable.
static Constant * EvaluateStoreInto(Constant *Init, Constant *Val, ConstantExpr *Addr, unsigned OpNo)
Evaluate a piece of a constantexpr store into a global initializer.
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...
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
bool HasMultipleAccessingFunctions
This class wraps the llvm.memset intrinsic.
const Function * getParent() const
Return the enclosing method, or null if none.
Analysis pass which computes a DominatorTree.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
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.
void reserve(size_type N)
bool isSequential() const
void setAlignment(unsigned Align)
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
const Constant * getAliasee() const
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
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...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
This global is stored to, but the only thing stored is the constant it was initialized with...
unsigned arg_size() const
static int compareNames(Constant *const *A, Constant *const *B)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
element_iterator element_end() 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 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...
Type::subtype_iterator element_iterator
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
This is the base class for all instructions that perform data casts.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
bool has(LibFunc::Func F) const
Tests whether a library function is available.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
ValTy * getCalledValue() const
getCalledValue - Return the pointer to function that is being called.
static Constant * get(ArrayRef< Constant * > V)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
StoredType
Keep track of what stores to the global look like.
element_iterator element_begin() const
const DenseMap< Constant *, Constant * > & getMutatedMemory() const
static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U)
void eraseFromParent() override
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
void setDLLStorageClass(DLLStorageClassTypes C)
void setArgument(unsigned ArgNo, Value *newVal)
X86_ThisCall - Similar to X86_StdCall.
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)
bool hasPrivateLinkage() const
SynchronizationScope getSynchScope() const
LLVM_NODISCARD bool empty() const
AtomicOrdering
Atomic ordering for LLVM's memory model.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
global_iterator global_begin()
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
user_iterator_impl< User > user_iterator
A constant value that is initialized with an expression using other constant values.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, AtomicOrdering Ordering, const DataLayout &DL, TargetLibraryInfo *TLI)
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
GraphT::NodeRef Eval(DominatorTreeBaseByGraphTraits< GraphT > &DT, typename GraphT::NodeRef VIn, unsigned LastLinked)
static Function * FindCXAAtExit(Module &M, TargetLibraryInfo *TLI)
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...
unsigned getAlignment() const
Class to represent array types.
This class represents a no-op cast from one type to another.
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.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Type * getElementType() const
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.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
uint64_t getElementOffset(unsigned Idx) const
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)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
MinAlign - A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
bool getLibFunc(StringRef funcName, LibFunc::Func &F) const
Searches for a particular function name.
Value * stripPointerCastsNoFollowAliases()
Strip off pointer casts and all-zero GEPs.
void setCallingConv(CallingConv::ID CC)
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
bool isExternallyInitialized() const
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
As we analyze each global, keep track of some information about it.
A set of analyses that are preserved following a run of a transformation pass.
Constant * stripPointerCasts()
alias_iterator alias_end()
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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.
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
C - The default llvm calling convention, compatible with C.
bool isVectorTy() const
True if this is an instance of VectorType.
Type * getElementType(unsigned N) const
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
const Comdat * getComdat() const
This is an important base class in LLVM.
static Value * GetHeapSROAValue(Value *V, unsigned FieldNo, DenseMap< Value *, std::vector< Value * > > &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setExternallyInitialized(bool Val)
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
static void RemoveNestAttribute(Function *F)
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
void setCallingConv(CallingConv::ID CC)
uint64_t getNumElements() const
User * getUser() const
Returns the User that contains this Use.
bool doesNotRecurse() const
Determine if the function is known not to recurse, directly or indirectly.
static bool cxxDtorIsEmpty(const Function &Fn, SmallPtrSet< const Function *, 8 > &CalledFunctions)
Returns whether the given function is an empty C++ destructor and can therefore be eliminated...
Value * getOperand(unsigned i) const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static bool OptimizeGlobalAliases(Module &M, SmallSet< const Comdat *, 8 > &NotDiscardableComdats)
self_iterator getIterator()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
ModulePass * createGlobalOptimizerPass()
createGlobalOptimizerPass - This function returns a new pass that optimizes non-address taken interna...
Predicate getPredicate() const
Return the predicate for this instruction.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV)
U is a direct user of the specified global value.
void setConstant(bool Val)
static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, const LLVMUsed &U)
LLVM_NODISCARD bool empty() const
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE int compare(StringRef RHS) const
compare - Compare two strings; the result is -1, 0, or 1 if this string is lexicographically less tha...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
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 GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
global_iterator global_end()
AttributeSet getAttributes() const
getAttributes/setAttributes - get or set the parameter attributes of the call.
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...
This is the superclass of the array and vector type classes.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
uint64_t getSequentialNumElements() const
bool hasGlobalUnnamedAddr() const
Global Variable Optimizer
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...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
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...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
16: SIMD 'packed' format, or other vector type
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
ValTy * getArgument(unsigned ArgNo) const
static bool isProfitableToMakeFastCC(Function *F)
Return true if this is a calling convention that we'd like to change.
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.
Type * getType() const
All values are typed, get the type of this value.
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.
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
alias_iterator alias_begin()
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
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 AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs)
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
AtomicOrdering getOrdering() const
Returns the ordering effect of this fence.
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...
const BasicBlock & getEntryBlock() const
static bool deleteIfDead(GlobalValue &GV, SmallSet< const Comdat *, 8 > &NotDiscardableComdats)
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass,"globalopt","Global Variable Optimizer", false, false) INITIALIZE_PASS_END(GlobalOptLegacyPass
static ConstantInt * getTrue(LLVMContext &Context)
void setLinkage(LinkageTypes LT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
bool isBoundedSequential() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
AttributeSet getAttributes() const
Return the attribute list for this Function.
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, TargetLibraryInfo *TLI)
Evaluate static constructors in the function, if we can.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
A range adaptor for a pair of iterators.
Target - Wrapper for Target specific information.
bool hasInitializer() const
Definitions have initializers, declarations don't.
void push_back(pointer val)
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
iterator_range< user_iterator > users()
static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C)
C may have non-instruction users.
static bool OptimizeFunctions(Module &M, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallSet< const Comdat *, 8 > &NotDiscardableComdats)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
AttributeSet removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
void setAttributes(AttributeSet Attrs)
Set the attribute list for this Function.
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:
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
ThreadLocalMode getThreadLocalMode() const
Value * getOperand() const
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, Instruction *StoredVal)
If all users of values loaded from GV are simple enough to perform HeapSRA, return true...
PointerType * getType() const
Global values are always pointers.
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
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)
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
void setUnnamedAddr(UnnamedAddr Val)
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. ...
static bool OptimizeGlobalVars(Module &M, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallSet< const Comdat *, 8 > &NotDiscardableComdats)
StringRef getName(LibFunc::Func F) const
static IntegerType * getInt32Ty(LLVMContext &C)
bool IsCompared
True if the global's address is used in a comparison.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
AtomicOrdering Ordering
Set to the strongest atomic ordering requirement.
unsigned greater or equal
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
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...
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.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
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 hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
bool hasLocalLinkage() const
Analysis pass providing the TargetLibraryInfo.
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL, TargetLibraryInfo *TLI)
The specified global has only one non-null value stored into it.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
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...
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static bool processGlobal(GlobalValue &GV, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
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.
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV)
virtual void eraseFromParent()=0
This method unlinks 'this' from the containing module and deletes it.
DLLStorageClassTypes getDLLStorageClass() const
iterator_range< global_iterator > globals()
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
static bool CleanupPointerRootUsers(GlobalVariable *GV, const TargetLibraryInfo *TLI)
This GV is a pointer root.
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 ret...
unsigned getNumElements() const
Random access to the elements.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSet< GlobalValue *, 8 > &Init)
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
void setSection(StringRef S)
Change the section for this global.
void setCalledFunction(Value *V)
setCalledFunction - Set the callee to the specified value.
const BasicBlock * getParent() const
void removeFromParent() override
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it...
an instruction to allocate memory on the stack
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...